File: SNMPv1AgentInterface.java

package info (click to toggle)
java-snmp 1.4.2-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 592 kB
  • ctags: 612
  • sloc: java: 5,380; xml: 49; makefile: 38
file content (493 lines) | stat: -rw-r--r-- 19,632 bytes parent folder | download | duplicates (2)
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
/*
 * SNMP Package
 *
 * Copyright (C) 2004, Jonathan Sevy <jsevy@mcs.drexel.edu>
 *
 * This is free software. Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that the following conditions
 * are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice, this
 *     list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation 
 *     and/or other materials provided with the distribution.
 *  3. The name of the author may not be used to endorse or promote products 
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 
 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */


package snmp;

import java.io.*;
import java.net.*;
import java.util.*;


/**
*    The class SNMPv1AgentInterface implements an interface for responding to requests sent from a remote SNMP 
*   manager. The agent simply listens for requests for information, and passes requested OIDs on to concrete 
*   subclasses of SNMPRequestListener. These are expected to retrieve requested information from the system,
*   and return this to the agent interface for inclusion in a response to the manager. 
*   The approach is that from version 1 of SNMP, using no encryption of data. The agent listens on UDP port 161,
*   the standard SNMP port, unless an alternate (non-standard) port is supplied in the conbstructor.
*/

public class SNMPv1AgentInterface
                    implements Runnable
{
    public static final int SNMP_PORT = 161;
    
    // largest size for datagram packet payload; based on
    // RFC 1157, need to handle messages of at least 484 bytes
    public int receiveBufferSize = 512;
    
    int version = 0;
    
    private DatagramSocket dSocket;
    private Thread receiveThread;
    private Vector listenerVector;
    
    private PrintWriter errorLog;
    
    
    
    
    /**
    *   Construct a new agent object to listen for requests from remote SNMP managers. The agent listens
    *   on the standard SNMP UDP port 161.
    */
    
    public SNMPv1AgentInterface(int version)
        throws SocketException
    {
        this(version, SNMP_PORT, new PrintWriter(System.out));
    }
    

    
    /**
    *   Construct a new agent object to listen for requests from remote SNMP managers. The agent listens
    *   on the supplied local port.
    */
    
    public SNMPv1AgentInterface(int version, int localPort)
        throws SocketException
    {
        this(version, localPort, new PrintWriter(System.out));
    }
    
    
    
    /**
    *   Construct a new agent object to listen for requests from remote SNMP managers. The agent listens
    *   on the supplied port, and sends error messages to the specified PrintWriter.
    */
    
    public SNMPv1AgentInterface(int version, PrintWriter errorReceiver)
        throws SocketException
    {
        this(version, SNMP_PORT, errorReceiver);
    }
    
    
    
    /**
    *   Construct a new agent object to listen for requests from remote SNMP managers. The agent listens
    *   on the supplied port, and sends error messages to the specified PrintWriter.
    */
    
    public SNMPv1AgentInterface(int version, int localPort, PrintWriter errorReceiver)
        throws SocketException
    {
        
        this.version = version;
        
        dSocket = new DatagramSocket(localPort);
        
        listenerVector = new Vector();
            
        receiveThread = new Thread(this);
        
        errorLog = errorReceiver;
        
    }
    
    
    
    /**
    *    Set the specified PrintWriter to receive error messages.
    */
    
    public void setErrorReceiver(PrintWriter errorReceiver)
    {
        errorLog = errorReceiver;
    }
    
    
    
    public void addRequestListener(SNMPRequestListener listener)
    {
        // see if listener already added; if so, ignore
        for (int i = 0; i < listenerVector.size(); i++)
        {
            if (listener == listenerVector.elementAt(i))
            {
                return;
            }
        }
        
        // if got here, it's not in the list; add it
        listenerVector.add(listener);
    }
    
    
    
    public void removeRequestListener(SNMPRequestListener listener)
    {
        // see if listener in list; if so, remove, if not, ignore
        for (int i = 0; i < listenerVector.size(); i++)
        {
            if (listener == listenerVector.elementAt(i))
            {
                listenerVector.removeElementAt(i);
                break;
            }
        }
        
    }

    
    
    /**
    *    Start listening for requests from remote managers.
    */
    
    public void startReceiving()
    {
        // if receiveThread not already running, start it
        if (!receiveThread.isAlive())
        {
            receiveThread = new Thread(this);
            receiveThread.start();
        }
    }
    

    
    
    /**
    *    Stop listening for requests from remote managers.
    */
    
    public void stopReceiving()
        throws SocketException
    {
        // interrupt receive thread so it will die a natural death
        receiveThread.interrupt();
    }

    
    
    
    
    /**
    *    The run() method for the agent interface's listener. Just waits for SNMP request messages to
    *    come in on port 161 (or the port supplied in the constructor), then dispatches the retrieved 
    *   SNMPPDU and community name to each of the registered SNMPRequestListeners by calling their 
    *   processRequest() methods.
    */
    
    public void run()
    {
        
        
        while (!receiveThread.isInterrupted())
        {
                
            try
            {
            
                DatagramPacket inPacket = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize);
        
                dSocket.receive(inPacket);
                
                InetAddress requesterAddress = inPacket.getAddress();
                int requesterPort = inPacket.getPort();
                
                byte[] encodedMessage = inPacket.getData();
                
                /*
                System.out.println("Message bytes length (in): " + inPacket.getLength());
                
                System.out.println("Message bytes (in):");
                for (int i = 0; i < encodedMessage.length; ++i)
                {
                    System.out.print(hexByte(encodedMessage[i]) + " ");
                }
                System.out.println("\n");
                */
                
                SNMPMessage receivedMessage = new SNMPMessage(SNMPBERCodec.extractNextTLV(encodedMessage,0).value);
                
                String communityName = receivedMessage.getCommunityName();
                SNMPPDU receivedPDU = receivedMessage.getPDU();
                byte requestPDUType = receivedPDU.getPDUType();
                
                //System.out.println("Received message; community = " + communityName + ", pdu type = " + Byte.toString(requestPDUType));
                //System.out.println("  read community = " + readCommunityName + ", write community = " + writeCommunityName);
                
                SNMPSequence requestedVarList = receivedPDU.getVarBindList();
                
                Hashtable variablePairHashtable = new Hashtable();
                SNMPSequence responseVarList = new SNMPSequence();
                int errorIndex = 0;
                int errorStatus = SNMPRequestException.NO_ERROR;
                int requestID = receivedPDU.getRequestID();
                
                try
                {
                
                    // pass the received PDU and community name to the processRequest method of any listeners;
                    // handle differently depending on whether the request is a get-next, or a get or set
                
                    if ((requestPDUType == SNMPBERCodec.SNMPGETREQUEST) || (requestPDUType == SNMPBERCodec.SNMPSETREQUEST))
                    {
                
                        // pass the received PDU and community name to any registered listeners
                        for (int i = 0; i < listenerVector.size(); i++)
                        {
                            SNMPRequestListener listener = (SNMPRequestListener)listenerVector.elementAt(i);
                            
                            // return value is sequence of variable pairs for those OIDs handled by the listener
                            SNMPSequence handledVarList = listener.processRequest(receivedPDU, communityName);
                               
                            // add to Hashtable of handled OIDs, if not already there
                            for (int j = 0; j < handledVarList.size(); j++)
                            {

                                SNMPSequence handledPair = (SNMPSequence)handledVarList.getSNMPObjectAt(j);
                                SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)handledPair.getSNMPObjectAt(0);
                                SNMPObject snmpObject = (SNMPObject)handledPair.getSNMPObjectAt(1);

                                if (!variablePairHashtable.containsKey(snmpOID))
                                {
                                    variablePairHashtable.put(snmpOID, snmpObject);
                                }

                            }
                            
                        }
                        
                        
                        
                        // construct response containing the handled OIDs; if any OID not handled, throw exception
                        for (int j = 0; j < requestedVarList.size(); j++)
                        {
                            SNMPSequence requestPair = (SNMPSequence)requestedVarList.getSNMPObjectAt(j);
                            SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)requestPair.getSNMPObjectAt(0);

                            // find corresponding SNMP object in hashtable
                            if (!variablePairHashtable.containsKey(snmpOID))
                            {
                                errorIndex = j + 1;
                                errorStatus = SNMPRequestException.VALUE_NOT_AVAILABLE;
                                
                                if (requestPDUType == SNMPBERCodec.SNMPGETREQUEST)
                                    throw new SNMPGetException("OID " + snmpOID + " not handled", errorIndex, errorStatus);
                                else
                                    throw new SNMPSetException("OID " + snmpOID + " not handled", errorIndex, errorStatus);
                            }

                            SNMPObject snmpObject = (SNMPObject)variablePairHashtable.get(snmpOID);
                            SNMPVariablePair responsePair = new SNMPVariablePair(snmpOID, snmpObject);

                            responseVarList.addSNMPObject(responsePair);
                            
                        }
                    
                    }
                    else if (requestPDUType == SNMPBERCodec.SNMPGETNEXTREQUEST)
                    {
                        // pass the received PDU and community name to any registered listeners
                        for (int i = 0; i < listenerVector.size(); i++)
                        {
                            SNMPRequestListener listener = (SNMPRequestListener)listenerVector.elementAt(i);
                            
                            // return value is sequence of nested variable pairs for those OIDs handled by the listener:
                            // consists of (supplied OID, (following OID, value)) nested variable pairs
                            SNMPSequence handledVarList = listener.processGetNextRequest(receivedPDU, communityName);
                               
                            // add variable pair to Hashtable of handled OIDs, if not already there
                            for (int j = 0; j < handledVarList.size(); j++)
                            {
                                
                                SNMPSequence handledPair = (SNMPSequence)handledVarList.getSNMPObjectAt(j);
                                SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)handledPair.getSNMPObjectAt(0);
                                SNMPObject snmpObject = (SNMPObject)handledPair.getSNMPObjectAt(1);
                                
                                if (!variablePairHashtable.containsKey(snmpOID))
                                {
                                    variablePairHashtable.put(snmpOID, snmpObject);
                                }
                                
                            }
                            
                        }
                        
                        
                        
                        // construct response containing the handled OIDs; if any OID not handled, throw exception
                        for (int j = 0; j < requestedVarList.size(); j++)
                        {
                            SNMPSequence requestPair = (SNMPSequence)requestedVarList.getSNMPObjectAt(j);
                            SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)requestPair.getSNMPObjectAt(0);

                            // find corresponding SNMP object in hashtable
                            if (!variablePairHashtable.containsKey(snmpOID))
                            {
                               errorIndex = j + 1;
                               errorStatus = SNMPRequestException.VALUE_NOT_AVAILABLE;
                               
                               throw new SNMPGetException("OID " + snmpOID + " not handled", errorIndex, errorStatus);
                            }

                            // value in hashtable is complete variable pair
                            SNMPVariablePair responsePair = (SNMPVariablePair)variablePairHashtable.get(snmpOID);

                            responseVarList.addSNMPObject(responsePair);
                            
                        }
                        
                    }
                    else
                    {
                        // some other PDU type; silently ignore
                        continue;
                    }
                    
                    
                }
                catch (SNMPRequestException e)
                {
                    // exception should contain the index and cause of error; return this in message
                    errorIndex = e.errorIndex;
                    errorStatus = e.errorStatus;
                    
                    // just return request variable list as response variable list
                    responseVarList = requestedVarList;
                }
                catch (Exception e)
                {
                    // don't have a specific index and cause of error; return message as general error, index 0
                    errorIndex = 0;
                    errorStatus = SNMPRequestException.FAILED;
                    
                    // just return request variable list as response variable list
                    responseVarList = requestedVarList;
                    
                    // also report the exception locally
                    errorLog.println("Exception while processing request: " + e.toString());
                    errorLog.flush();
                }
                
                
                SNMPPDU pdu = new SNMPPDU(SNMPBERCodec.SNMPGETRESPONSE, requestID, errorStatus, errorIndex, responseVarList);
                SNMPMessage message = new SNMPMessage(version, communityName, pdu);
                byte[] messageEncoding = message.getBEREncoding();
                DatagramPacket outPacket = new DatagramPacket(messageEncoding, messageEncoding.length, requesterAddress, requesterPort);
        
        
                dSocket.send(outPacket);
                
                
        
            }
            catch (IOException e)
            {
                // just report the problem
                errorLog.println("IOException during request processing: " + e.getMessage());
                errorLog.flush();
            }
            catch (SNMPBadValueException e)
            {
                // just report the problem
                errorLog.println("SNMPBadValueException during request processing: " + e.getMessage());
                errorLog.flush();
            }
            catch (Exception e)
            {
                // just report the problem
                errorLog.println("Exception during request processing: " + e.toString());
                errorLog.flush();
            }
        
        }
                
    }
    
    
    
    
    private String hexByte(byte b)
    {
        int pos = b;
        if (pos < 0)
            pos += 256;
        String returnString = new String();
        returnString += Integer.toHexString(pos/16);
        returnString += Integer.toHexString(pos%16);
        return returnString;
    }
    
    
    
    /**
    *   Set the size of the buffer used to receive response packets. RFC 1157 stipulates that an SNMP
    *   implementation must be able to receive packets of at least 484 bytes, so if you try to set the
    *   size to a value less than this, the receive buffer size will be set to 484 bytes. In addition,
    *   the maximum size of a UDP packet payload is 65535 bytes, so setting the buffer to a larger size
    *   will just waste memory. The default value is 512 bytes. The value may need to be increased if
    *   get-requests are issued for multiple OIDs.
    */
    
    public void setReceiveBufferSize(int receiveBufferSize)
    {
        if (receiveBufferSize >= 484)
        {
            this.receiveBufferSize = receiveBufferSize;
        }
        else
        {
            this.receiveBufferSize = 484;
        }
    }
    
    
    
    /**
    *   Returns the current size of the buffer used to receive response packets. 
    */
    
    public int getReceiveBufferSize()
    {
        return this.receiveBufferSize;
    }
    
    
    
}