This file is indexed.

/usr/bin/snmpsimd is in snmpsim 0.2.4-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
#! /usr/bin/python
#
# SNMP Agent Simulator
#
# Written by Ilya Etingof <ilya@glas.net>, 2010-2013
#
import os
import stat
import sys
import getopt
import traceback
if sys.version_info[0] < 3 and sys.version_info[1] < 5:
    from md5 import md5
else:
    from hashlib import md5
from pyasn1.type import univ
from pyasn1.codec.ber import encoder, decoder
from pyasn1.compat.octets import str2octs
from pyasn1.error import PyAsn1Error
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asynsock.dgram import udp
try:
    from pysnmp.carrier.asynsock.dgram import udp6
except ImportError:
    udp6 = None
try:
    from pysnmp.carrier.asynsock.dgram import unix
except ImportError:
    unix = None
from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher
from pysnmp.smi import exval, indices
from pysnmp.smi.error import MibOperationError
from pysnmp.proto import rfc1902, rfc1905, api
from pysnmp import error
from pysnmp import debug
from snmpsim.error import SnmpsimError, NoDataNotification
from snmpsim import confdir, log, daemon
from snmpsim.record import dump, mvc, sap, walk, snmprec
from snmpsim.record.search.file import searchRecordByOid
from snmpsim.record.search.database import RecordIndex

# Settings
forceIndexBuild = False
validateData = False
transportIdOffset= 0
v2cArch = False
v3Only = False
pidFile = '/var/run/snmpsim/snmpsimd.pid'
foregroundFlag = True
procUser = procGroup = None
variationModulesOptions = {}
variationModules = {}

authProtocols = {
  'MD5': config.usmHMACMD5AuthProtocol,
  'SHA': config.usmHMACSHAAuthProtocol,
  'NONE': config.usmNoAuthProtocol
}

privProtocols = {
  'DES': config.usmDESPrivProtocol,
  '3DES': config.usm3DESEDEPrivProtocol,
  'AES': config.usmAesCfb128Protocol,
  'AES128': config.usmAesCfb128Protocol,
  'AES192': config.usmAesCfb192Protocol,
  'AES256': config.usmAesCfb256Protocol,
  'NONE': config.usmNoPrivProtocol
}

# Transport endpoints collection

class TransportEndpointsBase:
    def __init__(self):
        self.__endpoint = None

    def add(self, addr):
        self.__endpoint = self._addEndpoint(addr)
        return self

    def _addEndpoint(self, addr): raise NotImplementedError()

    def __len__(self): return len(self.__endpoint)
    def __getitem__(self, i): return self.__endpoint[i]

class IPv4TransportEndpoints(TransportEndpointsBase):
    def _addEndpoint(self, addr):
        f = lambda h,p=161: (h, int(p))
        try:
            h, p = f(*addr.split(':'))
        except:
            raise SnmpsimError('improper IPv4/UDP endpoint %s' % addr)
        return udp.UdpTransport().openServerMode((h, p)), addr

class IPv6TransportEndpoints(TransportEndpointsBase):
    def _addEndpoint(self, addr):
        if not udp6:
            raise SnmpsimError('This system does not support UDP/IP6')
        if addr.find(']:') != -1 and addr[0] == '[':
            h, p = addr.split(']:')
            try:
                h, p = h[1:], int(p)
            except:
                raise SnmpsimError('improper IPv6/UDP endpoint %s' % addr)
        elif addr[0] == '[' and addr[-1] == ']':
            h, p = addr[1:-1], 161
        else:
            h, p = addr, 161
        return udp6.Udp6Transport().openServerMode((h, p)), addr
 
class UnixTransportEndpoints(TransportEndpointsBase):
    def _addEndpoint(self, addr):
        if not unix:
            raise SnmpsimError('This system does not support UNIX domain sockets')
        return unix.UnixTransport().openServerMode(addr), addr

# Extended snmprec record handler

class SnmprecRecord(snmprec.SnmprecRecord):
    def evaluateValue(self, oid, tag, value, **context):
        # Variation module reference
        if ':' in tag:
            modName, tag = tag[tag.index(':')+1:], tag[:tag.index(':')]
        else:
            modName = None

        if modName:
            if 'variationModules' in context and \
                   modName in context['variationModules']:
                if 'dataValidation' in context:
                    return oid, tag, univ.Null
                else:
                    if context['setFlag']:
                        hexvalue = self.grammar.hexifyValue(context['origValue'])
                        if hexvalue is not None:
                            context['hexvalue'] = hexvalue
                            context['hextag'] = self.grammar.getTagByType(context['origValue']) + 'x'

                    # prepare agent and record contexts on first reference
                    ( variationModule,
                      agentContexts,
                      recordContexts ) = context['variationModules'][modName]
                    if context['dataFile'] not in agentContexts:
                        agentContexts[context['dataFile']] = {}
                    variationModule['agentContext'] = agentContexts[context['dataFile']]
                    if oid not in recordContexts:
                        recordContexts[oid] = {}
                    variationModule['recordContext'] = recordContexts[oid]

                    # invoke variation module
                    oid, tag, value = variationModule['variate'](oid, tag, value, **context)
            else:
                raise SnmpsimError('Variation module "%s" referenced but not loaded\r\n' % modName)

        if not modName:
            if 'dataValidation' in context:
                snmprec.SnmprecRecord.evaluateValue(
                    self, oid, tag, value, **context
                )

            if not context['nextFlag'] and not context['exactMatch'] or \
                   context['setFlag']:
                return context['origOid'], tag, context['errorStatus']

        if not hasattr(value, 'tagSet'):  # not already a pyasn1 object
            return snmprec.SnmprecRecord.evaluateValue(
                       self, oid, tag, value, **context
                   )

        return oid, tag, value

    def evaluate(self, line, **context):
        oid, tag, value = self.grammar.parse(line)
        oid = self.evaluateOid(oid)
        if context.get('oidOnly'):
            value = None
        else:
            try:
                oid, tag, value = self.evaluateValue(oid, tag, value, **context)
            except NoDataNotification:
                raise
            except MibOperationError:
                raise
            except PyAsn1Error:
                raise SnmpsimError('value evaluation for %s = %r failed: %s\r\n' % (oid, value, sys.exc_info()[1]))
        return oid, value

recordSet = {
    dump.DumpRecord.ext: dump.DumpRecord(),
    mvc.MvcRecord.ext: mvc.MvcRecord(),
    sap.SapRecord.ext: sap.SapRecord(),
    walk.WalkRecord.ext: walk.WalkRecord(),
    SnmprecRecord.ext: SnmprecRecord()
}

class AbstractLayout:
    layout = '?'

# Data text file and OID index

class DataFile(AbstractLayout):
    layout = 'text'
    openedQueue = []
    maxQueueEntries = 31  # max number of open text and index files
    def __init__(self, textFile, textParser):
        self.__recordIndex = RecordIndex(textFile, textParser)
        self.__textParser = textParser
        self.__textFile = textFile
        
    def indexText(self, forceIndexBuild=False):
        self.__recordIndex.create(forceIndexBuild, validateData)
        return self

    def close(self):
        self.__recordIndex.close()
    
    def getHandles(self):
        if not self.__recordIndex.isOpen():
            if len(DataFile.openedQueue) > self.maxQueueEntries:
                log.msg('Closing %s' % self)
                DataFile.openedQueue[0].close()
                del DataFile.openedQueue[0]

            DataFile.openedQueue.append(self)

            log.msg('Opening %s' % self)

        return self.__recordIndex.getHandles()

    def processVarBinds(self, varBinds, **context):
        rspVarBinds = []

        if context.get('nextFlag'):
            errorStatus = exval.endOfMib
        else:
            errorStatus = exval.noSuchInstance

        try:
            text, db = self.getHandles()
        except SnmpsimError:
            log.msg('Problem with data file or its index: %s' % sys.exc_info()[1])
            return [ (vb[0],errorStatus) for vb in varBinds ]
       
        varsRemaining = varsTotal = len(varBinds)
        
        log.msg('Request var-binds: %s, flags: %s, %s' % (', '.join(['%s=<%s>' % (vb[0], vb[1].prettyPrint()) for vb in varBinds]), context.get('nextFlag') and 'NEXT' or 'EXACT', context.get('setFlag') and 'SET' or 'GET'))

        for oid, val in varBinds:
            textOid = str(
                univ.OctetString('.'.join([ '%s' % x for x in oid ]))
            )

            try:
                line = self.__recordIndex.lookup(
                    str(univ.OctetString('.'.join([ '%s' % x for x in oid ])))
                )
            except KeyError:
                offset = searchRecordByOid(oid, text, self.__textParser)
                subtreeFlag = exactMatch = False
            else:
                offset, subtreeFlag, prevOffset = line.split(str2octs(','))
                subtreeFlag, exactMatch = int(subtreeFlag), True

            offset = int(offset)

            text.seek(offset)

            varsRemaining -= 1

            line = text.readline()  # matched line
 
            while True:
                if exactMatch:
                    if context.get('nextFlag') and not subtreeFlag:
                        _nextLine = text.readline() # next line
                        if _nextLine:
                            _nextOid, _ = self.__textParser.evaluate(_nextLine, oidOnly=True)
                            try:
                                _, subtreeFlag, _ = self.__recordIndex.lookup(str(_nextOid)).split(str2octs(','))
                            except KeyError:
                                log.msg('data error for %s at %s, index broken?' % (self, _nextOid))
                                line = ''  # fatal error
                            else:
                                subtreeFlag = int(subtreeFlag)
                                line = _nextLine
                        else:
                            line = _nextLine
                else: # search function above always rounds up to the next OID
                    if line:
                        _oid, _  = self.__textParser.evaluate(
                            line, oidOnly=True
                        )
                    else:  # eom
                        _oid = 'last'

                    try:
                        _, _, _prevOffset = self.__recordIndex.lookup(str(_oid)).split(str2octs(','))
                    except KeyError:
                        log.msg('data error for %s at %s, index broken?' % (self, _oid))
                        line = ''  # fatal error
                    else:
                        _prevOffset = int(_prevOffset)

                        # previous line serves a subtree?
                        if _prevOffset >= 0:
                            text.seek(_prevOffset)
                            _prevLine = text.readline()
                            _prevOid, _ = self.__textParser.evaluate(
                                _prevLine, oidOnly=True
                            )
                            if _prevOid.isPrefixOf(oid):
                                # use previous line to the matched one
                                line = _prevLine
                                subtreeFlag = True

                if not line:
                    _oid = oid
                    _val = errorStatus
                    break

                callContext = context.copy()
                callContext.update((),
                    origOid=oid, 
                    origValue=val,
                    dataFile=self.__textFile,
                    subtreeFlag=subtreeFlag,
                    exactMatch=exactMatch,
                    errorStatus=errorStatus,
                    varsTotal=varsTotal,
                    varsRemaining=varsRemaining,
                    variationModules=variationModules
                )
 
                try:
                    _oid, _val = self.__textParser.evaluate(line, **callContext)
                    if _val is exval.endOfMib:
                        exactMatch = True
                        subtreeFlag = False
                        continue
                except NoDataNotification:
                    raise
                except MibOperationError:
                    raise
                except Exception:
                    _oid = oid
                    _val = errorStatus
                    log.msg('data error at %s for %s: %s' % (self, textOid, sys.exc_info()[1]))

                break

            rspVarBinds.append((_oid, _val))

        log.msg('Response var-binds: %s' % (', '.join(['%s=<%s>' % (vb[0], vb[1].prettyPrint()) for vb in rspVarBinds])))

        return rspVarBinds
 
    def __str__(self): return '%s controller' % self.__textFile

# Collect data files

def getDataFiles(tgtDir, topLen=None):
    if topLen is None:
        topLen = len(tgtDir.split(os.path.sep))
    dirContent = []
    for dFile in os.listdir(tgtDir):
        fullPath = tgtDir + os.path.sep + dFile
        inode = os.lstat(fullPath)
        if stat.S_ISLNK(inode.st_mode):
            relPath = fullPath.split(os.path.sep)[topLen:]
            fullPath = os.readlink(fullPath)
            if not os.path.isabs(fullPath):
                fullPath = tgtDir + os.path.sep + fullPath
            inode = os.stat(fullPath)
        else:
            relPath = fullPath.split(os.path.sep)[topLen:]
        if stat.S_ISDIR(inode.st_mode):
            dirContent = dirContent + getDataFiles(fullPath, topLen)
            continue            
        if not stat.S_ISREG(inode.st_mode):
            continue
        dExt = os.path.splitext(dFile)[1][1:]
        if dExt not in recordSet:
            continue
        dirContent.append(
            (fullPath,
             recordSet[dExt],
             os.path.splitext(os.path.join(*relPath))[0].replace(os.path.sep, '/'))
        )
    return dirContent

# Lightweignt MIB instrumentation (API-compatible with pysnmp's)

class MibInstrumController:
    def __init__(self, dataFile):
        self.__dataFile = dataFile

    def __str__(self): return str(self.__dataFile)

    def __getCallContext(self, acInfo, nextFlag=False, setFlag=False):
        if acInfo is None:
            return { 'nextFlag': nextFlag,
                     'setFlag': setFlag }

        acFun, acCtx = acInfo
        ( snmpEngine, 
          securityModel,
          securityName,
          securityLevel,
          contextName, 
          pduType ) = acCtx  # this is not [yet] documented

        log.msg('SNMP EngineID %s, securityModel %s, securityName %s, securityLevel %s' % (hasattr(snmpEngine, 'snmpEngineID') and snmpEngine.snmpEngineID.prettyPrint() or '<unknown>', securityModel, securityName, securityLevel))

        return { 'snmpEngine': snmpEngine,
                 'securityModel': securityModel,
                 'securityName': securityName,
                 'securityLevel': securityLevel,
                 'contextName': contextName,
                 'nextFlag': nextFlag,
                 'setFlag': setFlag }

    def readVars(self, varBinds, acInfo=None):
        return self.__dataFile.processVarBinds(
                varBinds, **self.__getCallContext(acInfo, False)
        )

    def readNextVars(self, varBinds, acInfo=None):
        return self.__dataFile.processVarBinds(
                varBinds, **self.__getCallContext(acInfo, True)
        )

    def writeVars(self, varBinds, acInfo=None):
        return self.__dataFile.processVarBinds(
                varBinds, **self.__getCallContext(acInfo, False, True)
        )

# Data files index as a MIB instrumentaion at a dedicated SNMP context

class DataIndexInstrumController:
    indexSubOid = (1,)
    def __init__(self, baseOid=(1, 3, 6, 1, 4, 1, 20408, 999)):
        self.__db = indices.OidOrderedDict()
        self.__indexOid = baseOid + self.indexSubOid
        self.__idx = 1

    def __str__(self): return '<index> controller'

    def readVars(self, varBinds, acInfo=None):
        return [ (vb[0], self.__db.get(vb[0], exval.noSuchInstance)) for vb in varBinds ]

    def __getNextVal(self, key, default):
        try:
            key = self.__db.nextKey(key)
        except KeyError:
            return key, default
        else:
            return key, self.__db[key]
                                                            
    def readNextVars(self, varBinds, acInfo=None):
        return [ self.__getNextVal(vb[0], exval.endOfMib) for vb in varBinds ]        

    def writeVars(self, varBinds, acInfo=None):
        return [ (vb[0], exval.noSuchInstance) for vb in varBinds ]        
    
    def addDataFile(self, *args):
        for idx in range(len(args)):
            self.__db[
                self.__indexOid + (idx+1, self.__idx)
                ] = rfc1902.OctetString(args[idx])
        self.__idx = self.__idx + 1

mibInstrumControllerSet = {
    DataFile.layout: MibInstrumController
}

# Suggest variations of context name based on request data
def probeContext(transportDomain, transportAddress, contextName):
    candidate = [
        contextName, '.'.join([ str(x) for x in transportDomain ])
    ]
    if transportDomain[:len(udp.domainName)] == udp.domainName:
        candidate.append(transportAddress[0])
    elif udp6 and transportDomain[:len(udp6.domainName)] == udp6.domainName:
        candidate.append(
            str(transportAddress[0]).replace(':', '_')
        )
    elif unix and transportDomain[:len(unix.domainName)] == unix.domainName:
        candidate.append(transportAddress)

    candidate = [ str(x) for x in candidate if x ]

    while candidate:
        yield rfc1902.OctetString(os.path.normpath(os.path.sep.join(candidate)).replace(os.path.sep, '/')).asOctets()
        del candidate[-1]
 
# main script body starts here

helpMessage = """\
Usage: %s [--help]
    [--version ]
    [--debug=<%s>]
    [--daemonize]
    [--process-user=<uname>] [--process-group=<gname>]
    [--pid-file=<file>]
    [--logging-method=<stdout|stderr|syslog|file>[:args>]]
    [--cache-dir=<dir>]
    [--variation-modules-dir=<dir>]
    [--variation-module-options=<module[=alias][:args]>] 
    [--force-index-rebuild]
    [--validate-data]
    [--v2c-arch]
    [--v3-only]
    [--transport-id-offset=<number>]
    [--args-from-file=<file>]
    [--v3-engine-id=<hexvalue>]
    [--data-dir=<dir>]
    [--agent-udpv4-endpoint=<X.X.X.X:NNNNN>]
    [--agent-udpv6-endpoint=<[X:X:..X]:NNNNN>]
    [--agent-unix-endpoint=</path/to/named/pipe>]
    [--v3-user=<username>]
    [--v3-auth-key=<key>]
    [--v3-auth-proto=<%s>]
    [--v3-priv-key=<key>]
    [--v3-priv-proto=<%s>]""" % (
        sys.argv[0],
        '|'.join([ x for x in debug.flagMap.keys() if x != 'mibview' ]),
        '|'.join(authProtocols),
        '|'.join(privProtocols)
    )

try:
    opts, params = getopt.getopt(sys.argv[1:], 'hv', [
        'help', 'version', 'debug=', 'daemonize', 'process-user=',
        'process-group=', 'pid-file=', 'logging-method=', 'device-dir=',
        'cache-dir=', 'variation-modules-dir=', 
        'force-index-rebuild', 'validate-device-data', 'validate-data',
        'v2c-arch', 'v3-only', 'transport-id-offset=', 
        'variation-module-options=',
        'args-from-file=',
        # this option starts new SNMPv3 engine configuration
        'data-dir=',
        'v3-engine-id=',
        'agent-udpv4-endpoint=','agent-udpv6-endpoint=','agent-unix-endpoint=',
        'v3-user=',
        'v3-auth-key=', 'v3-auth-proto=', 
        'v3-priv-key=', 'v3-priv-proto='
    ])
except Exception:
    sys.stderr.write('ERROR: %s\r\n%s\r\n' % (sys.exc_info()[1], helpMessage))
    sys.exit(-1)

if params:
    sys.stderr.write('ERROR: extra arguments supplied %s\r\n%s\r\n' % (params, helpMessage))
    sys.exit(-1)

log.setLogger('snmpsimd', 'stderr')

v3Args = []

for opt in opts:
    if opt[0] == '-h' or opt[0] == '--help':
        sys.stderr.write("""\
Synopsis:
  SNMP Agents Simulation tool. Responds to SNMP requests, variate responses
  based on transport addresses, SNMP community name or SNMPv3 context name.
  Can implement highly complex behavior through variation modules.
Documentation:
  http://snmpsim.sourceforge.net/simulating-agents.html
%s
""" % helpMessage)
        sys.exit(-1)
    if opt[0] == '-v' or opt[0] == '--version':
        import snmpsim, pysnmp, pyasn1
        sys.stderr.write("""\
SNMP Simulator version %s, written by Ilya Etingof <ilya@glas.net>
Using foundation libraries: pysnmp %s, pyasn1 %s.
Python interpreter: %s
Software documentation and support at http://snmpsim.sf.net
%s
""" % (snmpsim.__version__, hasattr(pysnmp, '__version__') and pysnmp.__version__ or 'unknown', hasattr(pyasn1, '__version__') and pyasn1.__version__ or 'unknown', sys.version, helpMessage))
        sys.exit(-1)
    elif opt[0] == '--debug':
        debug.setLogger(debug.Debug(opt[1]))
    elif opt[0] == '--daemonize':
        foregroundFlag = False
    elif opt[0] == '--process-user':
        procUser = opt[1]
    elif opt[0] == '--process-group':
        procGroup = opt[1]
    elif opt[0] == '--pid-file':
        pidFile = opt[1]
    elif opt[0] == '--logging-method':
        try:
            log.setLogger('snmpsimd', *opt[1].split(':'))
        except SnmpsimError:
            sys.stderr.write('%s\r\n%s\r\n' % (sys.exc_info()[1], helpMessage))
            sys.exit(-1)
    elif opt[0] in ('--device-dir', '--data-dir'):
        if '--v3-engine-id' in [ x[0] for x in v3Args ]:
            v3Args.append(opt)
        else:
            confdir.data.insert(0, opt[1])
    elif opt[0] == '--cache-dir':
        confdir.cache = opt[1]
    elif opt[0] == '--variation-modules-dir':
        confdir.variation.insert(0, opt[1])
    elif opt[0] == '--variation-module-options':
        args = opt[1].split(':', 1)
        try:
            modName, args = args[0], args[1]
        except:
            sys.stderr.write('ERROR: improper variation module options: %s\r\n%s\r\n' % (opt[1], helpMessage))
            sys.exit(-1)
        if '=' in modName:
            modName, alias = modName.split('=', 1)
        else:
            alias = os.path.splitext(os.path.basename(modName))[0]
        if modName not in variationModulesOptions:
            variationModulesOptions[modName] = []
        variationModulesOptions[modName].append((alias, args))
    elif opt[0] == '--force-index-rebuild':
        forceIndexBuild = True
    elif opt[0] in ('--validate-device-data', '--validate-data'):
        validateData = True
    elif opt[0] == '--v2c-arch':
        v2cArch = True
    elif opt[0] == '--v3-only':
        v3Only = True
    elif opt[0] == '--transport-id-offset':
        try:
            transportIdOffset = max(0, int(opt[1]))
        except:
            sys.stderr.write('ERROR: %s\r\n%s\r\n' % (sys.exc_info()[1], helpMessage))
            sys.exit(-1)
    # processing of the following args is postponed till SNMP engine startup
    elif opt[0] in ('--agent-udpv4-endpoint',
                    '--agent-udpv6-endpoint',
                    '--agent-unix-endpoint') :
        v3Args.append(opt)
    elif opt[0] in ('--agent-udpv4-endpoints-list',
                    '--agent-udpv6-endpoints-list',
                    '--agent-unix-endpoints-list'):
        sys.stderr.write('ERROR: use --args-from-file=<file> option to list many endpoints\r\n%s\r\n' % helpMessage)
        sys.exit(-1)
    elif opt[0] in ('--v3-engine-id', '--v3-user', '--v3-auth-key', 
                    '--v3-auth-proto', '--v3-priv-key', '--v3-priv-proto'):
        v3Args.append(opt)
    elif opt[0] == '--args-from-file':
        try:
            v3Args.extend(
                [x.split('=', 1) for x in open(opt[1]).read().split()]
            )
        except:
            sys.stderr.write('ERROR: file %s opening failure: %s\r\n%s\r\n' % (opt[1], sys.exc_info()[1], helpMessage))
            sys.exit(-1)

if v2cArch and (v3Only or [ x for x in v3Args if x[0][:4] == '--v3' ]):
    sys.stderr.write('ERROR: either of --v2c-arch or --v3-* options should be used\r\n%s\r\n' % helpMessage)
    sys.exit(-1)

for opt in tuple(v3Args):
    if opt[0] == '--agent-udpv4-endpoint':
        try:
            v3Args.append((opt[0], IPv4TransportEndpoints().add(opt[1])))
        except:
            sys.stderr.write('ERROR: %s\r\n%s\r\n' % (sys.exc_info()[1], helpMessage))
            sys.exit(-1)
    elif opt[0] == '--agent-udpv6-endpoint':
        try:
            v3Args.append((opt[0], IPv6TransportEndpoints().add(opt[1])))
        except:
            sys.stderr.write('ERROR: %s\r\n%s\r\n' % (sys.exc_info()[1], helpMessage))
            sys.exit(-1)
    elif opt[0] == '--agent-unix-endpoint':
        try:
            v3Args.append((opt[0], UnixTransportEndpoints().add(opt[1])))
        except:
            sys.stderr.write('ERROR: %s\r\n%s\r\n' % (sys.exc_info()[1], helpMessage))
            sys.exit(-1)
    else:
        v3Args.append(opt) 

if v3Args[:len(v3Args)//2] == v3Args[len(v3Args)//2:]:
    sys.stderr.write('ERROR: agent endpoint address(es) not specified\r\n%s\r\n' % helpMessage)
    sys.exit(-1)
else:
    v3Args = v3Args[len(v3Args)//2:]

try:
    daemon.dropPrivileges(procUser, procGroup)
except:
    sys.stderr.write('ERROR: cant drop priveleges: %s\r\n%s\r\n' % (sys.exc_info()[1], helpMessage))
    sys.exit(-1)

if not foregroundFlag:
    try:
        daemon.daemonize(pidFile)
    except:
        sys.stderr.write('ERROR: cant daemonize process: %s\r\n%s\r\n' % (sys.exc_info()[1], helpMessage))
        sys.exit(-1)

# hook up variation modules

for variationModulesDir in confdir.variation:
    log.msg('Scanning "%s" directory for variation modules...' % variationModulesDir)
    if not os.path.exists(variationModulesDir):
        log.msg('Directory "%s" does not exist' % variationModulesDir)
        continue
    for dFile in os.listdir(variationModulesDir):
        if dFile[-3:] != '.py':
            continue
        _toLoad = []
        modName = os.path.splitext(os.path.basename(dFile))[0]
        if modName in variationModulesOptions:
            while variationModulesOptions[modName]:
                alias, args = variationModulesOptions[modName].pop()
                _toLoad.append((alias, args))
            del variationModulesOptions[modName]
        else:
            _toLoad.append((modName, ''))

        mod = variationModulesDir + os.path.sep + dFile

        for alias, args in _toLoad:
            if alias in variationModules:
                log.msg('WARNING: ignoring duplicate variation module "%s" at "%s"' %  (alias, mod))
                continue

            ctx = { 'path': mod,
                    'alias': alias,
                    'args': args,
                    'moduleContext': {} }

            try:
                if sys.version_info[0] > 2:
                    exec(compile(open(mod).read(), mod, 'exec'), ctx)
                else:
                    execfile(mod, ctx)
            except Exception:
                log.msg('Variation module "%s" execution failure: %s' %  (mod, sys.exc_info()[1]))
                sys.exit(-1)
            else:
                # moduleContext, agentContext, recordContext
                variationModules[alias] = ctx, {}, {}

    log.msg('A total of %s modules found in %s' % (len(variationModules), variationModulesDir))

if variationModulesOptions:
    log.msg('WARNING: unused options for variation modules: %s' %  ', '.join(variationModulesOptions.keys()))

if not os.path.exists(confdir.cache):
    try:
        os.makedirs(confdir.cache)
    except OSError:
        log.msg('ERROR: failed to create cache directory "%s": %s' % (confdir.cache, sys.exc_info()[1]))
        sys.exit(-1)
    else:
        log.msg('Cache directory "%s" created' % confdir.cache)

if variationModules:
    log.msg('Initializing variation modules...')
    for name, modulesContexts in variationModules.items():
        body = modulesContexts[0]
        for x in ('init', 'variate', 'shutdown'):
            if x not in body:
                log.msg('ERROR: missing "%s" handler at variation module "%s"' % (x, name))
                sys.exit(-1)
        try:
            body['init'](options=body['args'], mode='variating')
        except Exception:
            log.msg('Variation module "%s" load FAILED: %s' % (name,sys.exc_info()[1]))
        else:
            log.msg('Variation module "%s" loaded OK' % name)

# Build pysnmp Managed Objects base from data files information

def configureManagedObjects(dataDirs, dataIndexInstrumController,
                            snmpEngine=None, snmpContext=None):
    _mibInstrums = {}
    _dataFiles = {}

    for dataDir in dataDirs:
        log.msg('Scanning "%s" directory for %s data files...' % (dataDir, ','.join([' *%s%s' % (os.path.extsep, x.ext) for x in recordSet.values()]))
        )
        if not os.path.exists(dataDir):
            log.msg('Directory "%s" does not exist' % dataDir)
            continue
        log.msg('%s' % ('='*66,))
        for fullPath, textParser, communityName in getDataFiles(dataDir):
            if communityName in _dataFiles:
                log.msg('WARNING: ignoring duplicate Community/ContextName "%s" for data file %s (%s already loaded)' % (communityName, fullPath, _dataFiles[communityName]))
                continue
            elif fullPath in _mibInstrums:
                mibInstrum = _mibInstrums[fullPath]
                log.msg('Configuring *shared* %s' % (mibInstrum,))
            else:
                dataFile = DataFile(fullPath, textParser).indexText(forceIndexBuild)
                mibInstrum = mibInstrumControllerSet[dataFile.layout](dataFile)

                _mibInstrums[fullPath] = mibInstrum
                _dataFiles[communityName] = fullPath

                log.msg('Configuring %s' % (mibInstrum,))

            log.msg('SNMPv1/2c community name: %s' % (communityName,))

            if v2cArch:
                contexts[univ.OctetString(communityName)] = mibInstrum
            
                dataIndexInstrumController.addDataFile(
                    fullPath, communityName
                )
            else:
                agentName = contextName = md5(univ.OctetString(communityName).asOctets()).hexdigest()

                if not v3Only:
                    config.addV1System(
                        snmpEngine, agentName, communityName, contextName=contextName
                    )

                snmpContext.registerContextName(contextName, mibInstrum)
                         
                dataIndexInstrumController.addDataFile(
                    fullPath, communityName, contextName
                )
                         
                log.msg('SNMPv3 context name: %s' % (contextName,))
                
            log.msg('%s' % ('-+' * 33,))
                
    del _mibInstrums
    del _dataFiles

if v2cArch:
    def getBulkHandler(reqVarBinds, nonRepeaters, maxRepetitions, readNextVars):
        N = min(int(nonRepeaters), len(reqVarBinds))
        M = int(maxRepetitions)
        R = max(len(reqVarBinds)-N, 0)
        if R: M = min(M, 100/R)  # maxVarBinds

        if N:
            rspVarBinds = readNextVars(reqVarBinds[:N])
        else:
            rspVarBinds = []

        varBinds = reqVarBinds[-R:]
        while M and R:
            rspVarBinds.extend(
                readNextVars(varBinds)
            )
            varBinds = rspVarBinds[-R:]
            M = M - 1

        return rspVarBinds

    def commandResponderCbFun(transportDispatcher, transportDomain,
                              transportAddress, wholeMsg):
        while wholeMsg:
            msgVer = api.decodeMessageVersion(wholeMsg)
            if msgVer in api.protoModules:
                pMod = api.protoModules[msgVer]
            else:
                log.msg('Unsupported SNMP version %s' % (msgVer,))
                return
            reqMsg, wholeMsg = decoder.decode(
                wholeMsg, asn1Spec=pMod.Message(),
                )

            communityName = reqMsg.getComponentByPosition(1)
            for candidate in probeContext(transportDomain, transportAddress, communityName):
                if candidate in contexts:
                    log.msg('Using %s selected by candidate %s; transport ID %s, source address %s, community name "%s"' % (contexts[candidate], candidate, univ.ObjectIdentifier(transportDomain), transportAddress[0], communityName))
                    communityName = candidate
                    break
            else:
                log.msg('No data file selected for transport ID %s, source address %s, community name "%s"' % (univ.ObjectIdentifier(transportDomain), transportAddress[0], communityName))
                return wholeMsg
            
            rspMsg = pMod.apiMessage.getResponse(reqMsg)
            rspPDU = pMod.apiMessage.getPDU(rspMsg)        
            reqPDU = pMod.apiMessage.getPDU(reqMsg)
    
            if reqPDU.isSameTypeWith(pMod.GetRequestPDU()):
                backendFun = contexts[communityName].readVars
            elif reqPDU.isSameTypeWith(pMod.SetRequestPDU()):
                backendFun = contexts[communityName].writeVars
            elif reqPDU.isSameTypeWith(pMod.GetNextRequestPDU()):
                backendFun = contexts[communityName].readNextVars
            elif hasattr(pMod, 'GetBulkRequestPDU') and \
                     reqPDU.isSameTypeWith(pMod.GetBulkRequestPDU()):
                if not msgVer:
                    log.msg('GETBULK over SNMPv1 from %s:%s' % (
                        transportDomain, transportAddress
                        ))
                    return wholeMsg
                backendFun = lambda varBinds: getBulkHandler(varBinds,
                    pMod.apiBulkPDU.getNonRepeaters(reqPDU),
                    pMod.apiBulkPDU.getMaxRepetitions(reqPDU),
                    contexts[communityName].readNextVars)
            else:
                log.msg('Unsuppored PDU type %s from %s:%s' % (
                    reqPDU.__class__.__name__, transportDomain,
                    transportAddress
                    ))
                return wholeMsg
   
            try: 
                varBinds = backendFun(
                    pMod.apiPDU.getVarBinds(reqPDU)
                )
            except NoDataNotification:
                return wholeMsg
            except:
                log.msg('Ignoring SNMP engine failure: %s' % sys.exc_info()[1])

            # Poor man's v2c->v1 translation
            errorMap = {  rfc1902.Counter64.tagSet: 5,
                          rfc1905.NoSuchObject.tagSet: 2,
                          rfc1905.NoSuchInstance.tagSet: 2,
                          rfc1905.EndOfMibView.tagSet: 2  }
 
            if not msgVer:
                for idx in range(len(varBinds)):
                    oid, val = varBinds[idx]
                    if val.tagSet in errorMap:
                        varBinds = pMod.apiPDU.getVarBinds(reqPDU)
                        pMod.apiPDU.setErrorStatus(rspPDU, errorMap[val.tagSet])
                        pMod.apiPDU.setErrorIndex(rspPDU, idx+1)
                        break

            pMod.apiPDU.setVarBinds(rspPDU, varBinds)
            
            transportDispatcher.sendMessage(
                encoder.encode(rspMsg), transportDomain, transportAddress
                )
            
        return wholeMsg

else: # v3arch
    def probeHashContext(self, snmpEngine, stateReference, contextName):
        transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference)

        for candidate in probeContext(transportDomain, transportAddress, contextName):
            probedContextName = md5(candidate).hexdigest()
            try:
                mibInstrum = self.snmpContext.getMibInstrum(probedContextName)
            except error.PySnmpError:
                pass
            else:
                log.msg('Using %s selected by candidate %s; transport ID %s, source address %s, context name "%s"' % (mibInstrum, candidate, univ.ObjectIdentifier(transportDomain), transportAddress[0], probedContextName))
                return probedContextName

        log.msg('Using %s selected by contextName "%s", transport ID %s, source address %s' % (self.snmpContext.getMibInstrum(contextName), contextName, univ.ObjectIdentifier(transportDomain), transportAddress[0]))

        return contextName

    class GetCommandResponder(cmdrsp.GetCommandResponder):
        def handleMgmtOperation(
                self, snmpEngine, stateReference, contextName, PDU, acInfo
            ):
            try:
                cmdrsp.GetCommandResponder.handleMgmtOperation(
                    self, snmpEngine, stateReference, 
                    probeHashContext(self, snmpEngine, stateReference, contextName),
                    PDU, acInfo
                )
            except NoDataNotification:
                self.releaseStateInformation(stateReference)

    class SetCommandResponder(cmdrsp.SetCommandResponder):
        def handleMgmtOperation(
                self, snmpEngine, stateReference, contextName, PDU, acInfo
            ):
            try:
                cmdrsp.SetCommandResponder.handleMgmtOperation(
                    self, snmpEngine, stateReference, 
                    probeHashContext(self, snmpEngine, stateReference, contextName),
                    PDU, acInfo
                )
            except NoDataNotification:
                self.releaseStateInformation(stateReference)

    class NextCommandResponder(cmdrsp.NextCommandResponder):
        def handleMgmtOperation(
                self, snmpEngine, stateReference, contextName, PDU, acInfo
            ):
            try:
                cmdrsp.NextCommandResponder.handleMgmtOperation(
                    self, snmpEngine, stateReference, 
                    probeHashContext(self, snmpEngine, stateReference, contextName),
                    PDU, acInfo
                )
            except NoDataNotification:
                self.releaseStateInformation(stateReference)

    class BulkCommandResponder(cmdrsp.BulkCommandResponder):
        def handleMgmtOperation(
                self, snmpEngine, stateReference, contextName, PDU, acInfo
            ):
            try:
                cmdrsp.BulkCommandResponder.handleMgmtOperation(
                    self, snmpEngine, stateReference, 
                    probeHashContext(self, snmpEngine, stateReference, contextName),
                    PDU, acInfo
                )
            except NoDataNotification:
                self.releaseStateInformation(stateReference)

# Start configuring SNMP engine(s)

transportDispatcher = AsynsockDispatcher()

if v2cArch:
    # Configure access to data index
   
    dataIndexInstrumController = DataIndexInstrumController()
 
    contexts = { univ.OctetString('index'): dataIndexInstrumController }

    configureManagedObjects(confdir.data, dataIndexInstrumController)

    contexts['index'] = dataIndexInstrumController
    
    agentUDPv4Endpoints = []
    agentUDPv6Endpoints = []
    agentUnixEndpoints = []

    for opt in v3Args:
        if opt[0] == '--agent-udpv4-endpoint':
            agentUDPv4Endpoints.append(opt[1])
        elif opt[0] == '--agent-udpv6-endpoint':
            agentUDPv6Endpoints.append(opt[1])
        elif opt[0] == '--agent-unix-endpoint':
            agentUnixEndpoints.append(opt[1])

    if not agentUDPv4Endpoints and \
            not agentUDPv6Endpoints and \
            not agentUnixEndpoints:
        log.msg('ERROR: agent endpoint address(es) not specified for SNMP engine ID %s' % v3EngineId)
        sys.exit(-1)

    # Configure socket server
   
    transportIndex = transportIdOffset
    for agentUDPv4Endpoint in agentUDPv4Endpoints:
        transportDomain = udp.domainName + (transportIndex,)
        transportIndex += 1
        transportDispatcher.registerTransport(
                transportDomain, agentUDPv4Endpoint[0]
        )
        log.msg('Listening at UDP/IPv4 endpoint %s, transport ID %s' % (agentUDPv4Endpoint[1], '.'.join([str(x) for x in transportDomain])))

    transportIndex = transportIdOffset
    for agentUDPv6Endpoint in agentUDPv6Endpoints:
        transportDomain = udp6.domainName + (transportIndex,)
        transportIndex += 1
        transportDispatcher.registerTransport(
                transportDomain, agentUDPv4Endpoint[0]
        )
        log.msg('Listening at UDP/IPv6 endpoint %s, transport ID %s' % (agentUDPv4Endpoint[1], '.'.join([str(x) for x in transportDomain])))

    transportIndex = transportIdOffset
    for agentUnixEndpoint in agentUnixEndpoints:
        transportDomain = unix.domainName + (transportIndex,)
        transportIndex += 1
        transportDispatcher.registerTransport(
                transportDomain, agentUnixEndpoint[0]
        )
        log.msg('Listening at UNIX domain socket endpoint %s, transport ID %s' % (agentUnixEndpoint[1], '.'.join([str(x) for x in transportDomain])))

    transportDispatcher.registerRecvCbFun(commandResponderCbFun)
 
else:  # v3 mode
    if hasattr(transportDispatcher, 'registerRoutingCbFun'):
        transportDispatcher.registerRoutingCbFun(lambda td,t,d: td)
    else:
        log.msg('WARNING: upgrade pysnmp to 4.2.5 or later get multi-engine ID feature working!')

    if v3Args and v3Args[0][0] != '--v3-engine-id':
        v3Args.insert(0, ('--v3-engine-id', 'auto'))
    v3Args.append(('end-of-options', ''))

    snmpEngine = None
    transportIndex = { 'udpv4': transportIdOffset,
                       'udpv6': transportIdOffset,
                       'unix': transportIdOffset }

    for opt in v3Args:
        if opt[0] in ('--v3-engine-id', 'end-of-options'):
            if snmpEngine:
                log.msg('%s' % ('*'*66,))

                dataIndexInstrumController = DataIndexInstrumController()

                configureManagedObjects(dataDirs and dataDirs or confdir.data, 
                                        dataIndexInstrumController,
                                        snmpEngine,
                                        snmpContext)

                # Configure access to data index

                config.addV1System(snmpEngine, 'index',
                                   'index', contextName='index')

                log.msg('SNMPv3 EngineID: %s' % (hasattr(snmpEngine, 'snmpEngineID') and snmpEngine.snmpEngineID.prettyPrint() or '<unknown>',))

                if not v3Users:
                    v3Users = [ 'simulator' ]
                    v3AuthKeys[v3Users[0]] = None not in v3AuthKeys and \
                                             'auctoritas' or v3AuthKeys[None]
                    v3AuthProtos[v3Users[0]] = None not in v3AuthProtos and \
                                             'MD5' or v3AuthProtos[None]
                    v3PrivKeys[v3Users[0]] = None not in v3PrivKeys and \
                                             'privatus' or v3PrivKeys[None]
                    v3PrivProtos[v3Users[0]] = None not in v3PrivProtos and \
                                               'DES' or v3PrivProtos[None]

                for v3User in v3Users:
                    if v3User in v3AuthKeys:
                        if v3User not in v3AuthProtos:
                            v3AuthProtos[v3User] = 'MD5'
                    else:
                        v3AuthKeys[v3User] = None
                        v3AuthProtos[v3User] = 'NONE'
                    if v3User in v3PrivKeys:
                        if v3User not in v3PrivProtos:
                            v3PrivProtos[v3User] = 'DES'
                    else:
                        v3PrivKeys[v3User] = None
                        v3PrivProtos[v3User] = 'NONE'
                    if authProtocols[v3AuthProtos[v3User]] == config.usmNoAuthProtocol and privProtocols[v3PrivProtos[v3User]] != config.usmNoPrivProtocol:
                        log.msg('ERROR: privacy impossible without authentication for USM user %s' % v3User)
                        sys.exit(-1)

                    try:
                        config.addV3User(
                            snmpEngine,
                            v3User,
                            authProtocols[v3AuthProtos[v3User]],
                            v3AuthKeys[v3User],
                            privProtocols[v3PrivProtos[v3User]], 
                            v3PrivKeys[v3User]
                        )
                    except error.PySnmpError:
                        log.msg('ERROR: bad USM values for user %s: %s' % (v3User, sys.exc_info()[1]))
                        sys.exit(-1)

                    log.msg('SNMPv3 USM SecurityName: %s' % v3User)

                    if authProtocols[v3AuthProtos[v3User]] != config.usmNoAuthProtocol:
                        log.msg('SNMPv3 USM authentication key: %s, authentication protocol: %s' % (v3AuthKeys[v3User], v3AuthProtos[v3User]))
                    if privProtocols[v3PrivProtos[v3User]] != config.usmNoPrivProtocol:
                        log.msg('SNMPv3 USM encryption (privacy) key: %s, encryption protocol: %s' % (v3PrivKeys[v3User], v3PrivProtos[v3User]))


                snmpContext.registerContextName(
                    'index', dataIndexInstrumController
                )

                # Configure socket server

                if not agentUDPv4Endpoints and \
                        not agentUDPv6Endpoints and \
                        not agentUnixEndpoints:
                    log.msg('ERROR: agent endpoint address(es) not specified for SNMP engine ID %s' % v3EngineId)
                    sys.exit(-1)

                for agentUDPv4Endpoint in agentUDPv4Endpoints:
                    transportDomain = udp.domainName + \
                            (transportIndex['udpv4'],)
                    transportIndex['udpv4'] += 1
                    snmpEngine.registerTransportDispatcher(
                        transportDispatcher, transportDomain
                    )
                    config.addSocketTransport(
                        snmpEngine,
                        transportDomain, agentUDPv4Endpoint[0]
                    )
                    log.msg('Listening at UDP/IPv4 endpoint %s, transport ID %s' % (agentUDPv4Endpoint[1], '.'.join([str(x) for x in transportDomain])))

                for agentUDPv6Endpoint in agentUDPv6Endpoints:
                    transportDomain = udp6.domainName + \
                            (transportIndex['udpv6'],)
                    transportIndex['udpv6'] += 1
                    snmpEngine.registerTransportDispatcher(
                        transportDispatcher, transportDomain
                    )
                    config.addSocketTransport(
                        snmpEngine,
                        transportDomain, agentUDPv6Endpoint[0]
                    )
                    log.msg('Listening at UDP/IPv6 endpoint %s, transport ID %s' % (agentUDPv6Endpoint[1], '.'.join([str(x) for x in transportDomain])))

                for agentUnixEndpoint in agentUnixEndpoints:
                    transportDomain = unix.domainName + \
                            (transportIndex['unix'],)
                    transportIndex['unix'] += 1
                    snmpEngine.registerTransportDispatcher(
                        transportDispatcher, transportDomain
                    )
                    config.addSocketTransport(
                        snmpEngine,
                        transportDomain, agentUnixEndpoint[0]
                    )
                    log.msg('Listening at UNIX domain socket endpoint %s, transport ID %s' % (agentUnixEndpoint[1], '.'.join([str(x) for x in transportDomain])))

                # SNMP applications
                GetCommandResponder(snmpEngine, snmpContext)
                SetCommandResponder(snmpEngine, snmpContext)
                NextCommandResponder(snmpEngine, snmpContext)
                BulkCommandResponder(snmpEngine, snmpContext)

            if opt[0] == 'end-of-options':
                break

            # Prepare for next engine ID configuration

            dataDirs = []
            v3Users = []
            v3AuthKeys = {}; v3AuthProtos = {}
            v3PrivKeys = {}; v3PrivProtos = {}
            agentUDPv4Endpoints = []
            agentUDPv6Endpoints = []
            agentUnixEndpoints = []

            try:
                v3EngineId = opt[1]
                if v3EngineId.lower() == 'auto':
                    snmpEngine = engine.SnmpEngine()
                else:
                    snmpEngine = engine.SnmpEngine(
                        snmpEngineID=univ.OctetString(hexValue=v3EngineId)
                    )
            except:
                log.msg('ERROR: SNMPv3 Engine initialization failed, EngineID "%s": %s' % (v3EngineId, sys.exc_info()[1]))
                sys.exit(-1)

            
            config.addContext(snmpEngine, '')

            snmpContext = context.SnmpContext(snmpEngine)

        elif opt[0] == '--data-dir':
            dataDirs.append(opt[1])
        elif opt[0] == '--v3-user':
            v3Users.append(opt[1])
            if None in v3AuthKeys:
                v3AuthKeys[None] = v3Users[-1]
        elif opt[0] == '--v3-auth-key':
            v3AuthKeys[v3Users and v3Users[-1] or None] = opt[1]
        elif opt[0] == '--v3-auth-proto':
            if opt[1].upper() not in authProtocols:
                log.msg('ERROR: bad v3 auth protocol %s' % opt[1])
                sys.exit(-1)
            else:
                v3AuthProtos[v3Users and v3Users[-1] or None] = opt[1].upper()
        elif opt[0] == '--v3-priv-key':
            v3PrivKeys[v3Users and v3Users[-1] or None] = opt[1]
        elif opt[0] == '--v3-priv-proto':
            if opt[1].upper() not in privProtocols:
                log.msg('ERROR: bad v3 privacy protocol %s' % opt[1])
                sys.exit(-1)
            else:
                v3PrivProtos[v3Users and v3Users[-1] or None] = opt[1].upper()
        elif opt[0] == '--agent-udpv4-endpoint':
            agentUDPv4Endpoints.append(opt[1])
        elif opt[0] == '--agent-udpv6-endpoint':
            agentUDPv6Endpoints.append(opt[1])
        elif opt[0] == '--agent-unix-endpoint':
            agentUnixEndpoints.append(opt[1])

# Run mainloop

transportDispatcher.jobStarted(1) # server job would never finish

# Python 2.4 does not support the "finally" clause

exc_info = None

try:
    transportDispatcher.runDispatcher()
except KeyboardInterrupt:
    log.msg('Shutting down process...')
except Exception:
    exc_info = sys.exc_info()

if variationModules:
    log.msg('Shutting down variation modules:')
    for name, contexts in variationModules.items():
        body = contexts[0]
        try:
            body['shutdown'](options=body['args'], mode='variation')
        except Exception:
            log.msg('Variation module "%s" shutdown FAILED: %s' % (name, sys.exc_info()[1]))
        else:
            log.msg('Variation module "%s" shutdown OK' % name)

transportDispatcher.closeDispatcher()

log.msg('Process terminated')

if exc_info:
    for line in traceback.format_exception(*exc_info):
        log.msg(line.replace('\n', ';'))