mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Christophe Sovant
17.05.2008 2f2b85856e60cc6706b066a426148b58f378ce95
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
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2008 Sun Microsystems, Inc.
 */
 
// OpenDS imports
import org.opends.server.snmp.DIRECTORY_SERVER_MIBOidTable;
 
// OpenDMK imports
//
import com.sun.management.snmp.SnmpDefinitions;
import com.sun.management.snmp.SnmpVarBindList;
import com.sun.management.snmp.SnmpEngine;
import com.sun.management.snmp.SnmpEngineParameters;
import com.sun.management.snmp.SnmpOid;
import com.sun.management.snmp.SnmpOidTableSupport;
import com.sun.management.snmp.SnmpStatusException;
import com.sun.management.snmp.SnmpString;
import com.sun.management.snmp.SnmpVarBind;
import com.sun.management.snmp.manager.SnmpRequest;
import com.sun.management.snmp.manager.SnmpSession;
import com.sun.management.snmp.manager.SnmpPeer;
import com.sun.management.snmp.manager.SnmpParameters;
import com.sun.management.snmp.manager.usm.SnmpUsmPeer;
import com.sun.management.snmp.manager.usm.SnmpUsmParameters;
 
/**
 * This class perform a SNMP set operation.
 */
public class SNMPSet {
 
  /**
   * Gets the calling arguments.
   *
   * @param args SNMP agent version + SNMP agent host + SNMP agent port
   * @return 0 if the init succeeded or 1 if the init failed
   */
  public int init(String[] args) {
    int rc = 0;
 
    System.out.println("\n");
 
    if (args.length < 5) {
      // Missing arguments
      System.out.println(
              "usage: " +
              " -v <SNMP version>" +
              " -h <remoteHost>" +
              " -p <port>" +
              " -o <oids>" +
              " -c <community>" +
              " -u <user>" +
              " -l <securityLevel>" +
              " -f <securityFile>" +
              " -s <connectionStatus>" +
              " -n <checkOIDs>");
      rc = 1;
    } else {
      for (int i = 0; i < args.length; i++) {
        String opt = args[i];
        String val = args[i + 1];
 
        switch (opt.charAt(1)) {
          case 'v':
            version = new Integer(val).intValue();
            break;
          case 'h':
            remoteHost = val;
            break;
          case 'p':
            port = new Integer(val).intValue();
            break;
          case 'o':
            oids = val;
            break;
          case 'c':
            community = val;
            break;
          case 'u':
            user = val;
            break;
          case 'l':
            if (val.compareTo("noauthnopriv") == 0) {
              securityLevel = SnmpDefinitions.noAuthNoPriv;
            } else if (val.compareTo("authnopriv") == 0) {
              securityLevel = SnmpDefinitions.authNoPriv;
            } else if (val.compareTo("authpriv") == 0) {
              securityLevel = SnmpDefinitions.authPriv;
            } else {
              System.out.println(
                      "Unknown security level " + opt.charAt(1) + ".");
              rc = 1;
            }
            break;
          case 'f':
            securityFile = val;
            break;
          case 's':
            connectStatus = val;
            break;
          case 'n':
            validOIDs = new Boolean(val).booleanValue();
            break;
          default:
            System.out.println("Unknown option -" + opt.charAt(1) + ".");
            rc = 1;
        }
 
        if (rc == 1) {
          break;
        }
 
        i = i + 1;
      }
    }
 
    if (rc == 0) {
      System.out.println("init() of SNMPSet succeeded");
    } else {
      System.out.println("init() of SNMPSet failed");
    }
 
    return rc;
  }
 
  /**
   * Open SNMP connection with SNMP agent.
   *
   * @return 0 if the connect succeeded or 1 if the connect failed
   */
  public int connect() {
    int rc = 0;
 
    try {
      // The OidTable generated by mibgen when compiling DIRECTORY_SERVER_MIB
      //
      final SnmpOidTableSupport oidTable = new DIRECTORY_SERVER_MIBOidTable();
 
      // Specify the OidTable containing all the DIRECTORY_SERVER_MIB knowledge
      //
      SnmpOid.setSnmpOidTable(oidTable);
 
      switch (version) {
        case 1:
        case 2:
          // Create the session
          //
          session = new SnmpSession("Set V" + version + " session");
 
          // Create an SnmpPeer object for representing the entity
          // to communicate with.
          //
          final SnmpPeer agent = new SnmpPeer(remoteHost, port);
 
          // Specify the read and write community to be used
          //
          final SnmpParameters params = new SnmpParameters(
                  community,
                  community);
 
          // Specify the protocol version
          //
          switch (version) {
            case 1:
              params.setProtocolVersion(SnmpDefinitions.snmpVersionOne);
              break;
            case 2:
              params.setProtocolVersion(SnmpDefinitions.snmpVersionTwo);
              break;
            default:
              break;
          }
 
          // Associate the parameters with the agent
          //
          agent.setTimeout(timeOut);
          agent.setMaxTries(maxRetries);
          agent.setParams(params);
 
          // Set the default peer (agent) to a SnmpSession
          //
          session.setDefaultPeer(agent);
          break;
        case 3:
          // Custom engine parameters
          final SnmpEngineParameters engineParameters =
                  new SnmpEngineParameters();
          
          // Activate encryption
          engineParameters.activateEncryption();
          
          // Set the security file
          engineParameters.setSecurityFile(securityFile);
 
          // Create the session
          //
          session = new SnmpSession(
                  engineParameters,
                  null,
                  "Set V3 session",
                  null);
 
          // SNMP V3 introduces the notion of SnmpEngine. An engine is
          // associated to the session. Other objects  might need
          // the engine. You can access it using getEngine method.
          //
          final SnmpEngine engine = session.getEngine();
 
          // Create an SnmpUsmPeer object for representing the entity
          // to communicate with
          //
          final SnmpUsmPeer agentV3 = new SnmpUsmPeer(engine, remoteHost, port);
 
          // Create USM parameters for the principal defaultuser (user used when
          // requests are sent: the defaultuser is a template and for this
          // reason we cannot find it under the user mib (not created as a user)
          //
          final SnmpUsmParameters paramsV3 = new SnmpUsmParameters(
                  engine,
                  user);
 
          // Set the security level authentication but without privacy
          //
          paramsV3.setSecurityLevel(securityLevel);
 
          // Set the context name
          //
          if (community.compareTo("null") != 0) {
            paramsV3.setContextName(community.getBytes());
          }
 
          // Set the contextEngineId discovered by the peer upon
          // its creation
          //
          paramsV3.setContextEngineId(agentV3.getEngineId().getBytes());
 
          // Associate the parameters with the agent
          //
          agentV3.setTimeout(timeOut);
          agentV3.setMaxTries(maxRetries);
          agentV3.setParams(paramsV3);
 
          // Discover timeliness of creation and boot
          //
         try {
            agentV3.processUsmTimelinessDiscovery();
         } catch (SnmpStatusException e) {
           if (connectStatus.compareTo("SnmpStatusException") == 0) {
             System.out.println(
                     "connect() of SNMPSet catched as expected a " +
                     "SNMP status exception: " + e.getMessage() + "\"");
           } else {
             System.out.println(
                     "connect() of SNMPSet should not catch a " +
                     "SNMP status exception: " + e.getMessage() + "\"");
 
             rc = 1;
           }
          } catch (Exception e) {
            System.out.println(
                    "connect() of SNMPSet catched an unexpected exception: " +
                    e.getMessage() + "\"");
 
            rc = 1;
          }
 
          if (rc == 0) {
            // Set the default peer (agent) to a SnmpSession
            //
            session.setDefaultPeer(agentV3);
          }
          break;
        default:
          System.out.println(
                  "connect() of SNMPSet: Unknown SNMP version: "
                  + version + " .");
 
          rc = 1;
      }
    } catch (Exception e) {
      System.out.println(
              "connect() of SNMPSet catched an unexpected exception: " +
              e.getMessage() + "\"");
 
      rc = 1;
    }
 
    if (rc == 0) {
      System.out.println("connect() of SNMPSet succeeded");
    } else {
      System.out.println("connect() of SNMPSet succeeded");
    }
 
    return rc;
  }
 
  /**
   * Perform an SNMP set request on SNMP agent.
   *
   * @return 0 if the setRequest succeeded or 1 if the setRequest failed
   */
  public int setRequest() {
    int rc = 0;
 
    try {
      // Build the list of variables you want to query
      //
      final SnmpVarBindList list = new SnmpVarBindList("Get varbind list");
 
      // Write one specific OID
      //
      SnmpVarBind oid = new SnmpVarBind(oids);
      oid.setSnmpValue(new SnmpString("myValue"));
      list.addVarBind(oid);
 
      // Make the SNMP set request
      //
      System.out.println(
              "setRequest() of SNMPSet: Start SNMP V" + version +
              " GET request for SNMP agent on \"" + remoteHost +
              "\" at port \"" + port + "\".");
 
      // Set request
      //
      SnmpRequest request = session.snmpSetRequest(null, list);
 
      // Check for a timeout of the request
      //
      boolean completed = request.waitForCompletion((maxRetries + 1) * timeOut);
      if (completed == false) {
        System.out.println(
                "setRequest() of SNMPSet: Request timed out, " +
                "check reachability of agent.");
 
        // Print request
        //
        System.out.println(
                "setRequest() of SNMPSet: Request= " +
                request.toString() + ".");
 
        rc = 1;
      }
 
      if (rc == 0) {
        System.out.println(
                "getRequest() of SNMPGet: Finish SNMP V" +
                version + " GET request.");
 
        // Now we have a response. Check if the response contains an error
        //
        String errorStatus = SnmpRequest.snmpErrorToString(
                request.getErrorStatus());
        if (errorStatus.compareTo("noError") != 0) {
          System.out.println(
                  "getRequest() of SNMPGet: Error status= " +
                  errorStatus + ".");
 
          System.out.println(
                  "getRequest() of SNMPGet: Error index= " +
                  request.getErrorIndex() + ".");
 
          if (errorStatus.compareTo(connectStatus) == 0) {
            System.out.println(
                    "getRequest() of SNMPGet: Get request failed as " +
                    "expected with " + connectStatus + " status.");
          } else {
            System.out.println(
                    "getRequest() of SNMPGet: Get request should " +
                    "fail with " + connectStatus + " status.");
 
            rc = 1;
          }
        } else {
          // Now we shall display the content of the result
          //
          SnmpVarBindList resp = request.getResponseVarBindList();
 
          System.out.println("getRequest() of SNMPGet: Result=");
 
          for (int i = 0; i < resp.getVarBindCount(); i++) {
            System.out.println(resp.getVarBindAt(i));
          }
 
          if (connectStatus.compareTo("noError") != 0) {
            // Request should failed
            //
            System.out.println(
                    "getRequest() of SNMPGet: Get request should " +
                    "fail with " + connectStatus + " status.");
 
            rc = 1;
          } else {
            if (validOIDs) {
              // Check that we obtain correct values for the OIDs
              //
              if (resp.checkForValidValues()) {
                System.out.println(
                        "getRequest() of SNMPGet: Returned values for" +
                        " OIDs are correct.");
              } else {
                System.out.println(
                        "getRequest() of SNMPGet: Returned values for" +
                        " OIDs are not correct.");
 
                rc = 1;
              }
            } else {
              // Check that we obtain incorrect values for the OIDs
              //
              if (resp.checkForValidValues()) {
                System.out.println(
                        "getRequest() of SNMPGet: Returned values for" +
                        " OIDs should not be correct.");
 
                rc = 1;
              } else {
                System.out.println(
                        "getRequest() of SNMPGet: Returned values for" +
                        " OIDs are not correct as expected.");
              }
            }
          }
        }
      }
    } catch (Exception e) {
      System.out.println(
              "setRequest() of SNMPSet catched an unexpected exception: " +
              e.getMessage() + "\"");
 
      rc = 1;
    }
 
    if (rc == 0) {
      System.out.println("setRequest() of SNMPSet succeeded");
    } else {
      System.out.println("setRequest() of SNMPSet failed");
    }
 
    return rc;
  }
 
  /**
   * Close SNMP connection with SNMP agent.
   */
  public void disconnect() {
 
    // Stop and destroy the SnmpSession if still there
    try {
      session.destroySession();
      session = null;
    } catch (Exception e) {
    // possible session already ended
    }
 
    System.out.println("disconnect() of SNMPSet succeeded");
  }
 
  /**
   * Main.
   *
   * @param args arguments
   */
  public static void main(String[] args) {
 
    SNMPSet client = new SNMPSet();
 
    int rc = 0;
 
    // Retrieve parameters
    rc = client.init(args);
 
    // If init() succeeded then open connection
    if (rc == 0) {
      rc = client.connect();
    }
 
    // If connect() succeeded then perform set request
    if (rc == 0 && connectStatus.compareTo("SnmpStatusException") != 0) {
      rc = client.setRequest();
    }
 
    // Close connection
    client.disconnect();
 
    System.exit(rc);
  }
 
  // Arguments
  int version = 0;
  String remoteHost = null;
  int port = 0;
  String oids = null;
  String community = null;
  String user = null;
  int securityLevel = SnmpDefinitions.authNoPriv;
  String securityFile = null;
  static String connectStatus = null;
  boolean validOIDs = true;
 
  // SnmpSession
  SnmpSession session = null;
 
  int timeOut = 30000;  // default value
  int maxRetries = 1;
}