/**
  * Starts the listener thread that accepts incoming messages. The thread is started in daemon mode
  * and thus it will not block application terminated. Nevertheless, the {@link #close()} method
  * should be called to stop the listen thread gracefully and free associated ressources.
  *
  * @throws IOException
  */
 public synchronized void listen() throws IOException {
   if (listener != null) {
     throw new SocketException("Port already listening");
   }
   ensureSocket();
   listenerThread = new ListenThread();
   listener =
       SNMP4JSettings.getThreadFactory()
           .createWorkerThread("DefaultUDPTransportMapping_" + getAddress(), listenerThread, true);
   listener.run();
 }
 /**
  * Add the default SecurityProtocols.
  *
  * <p>The names of the SecurityProtocols to add are read from a properties file.
  *
  * @throws InternalError if the properties file cannot be opened/read.
  */
 public synchronized void addDefaultProtocols() {
   if (SNMP4JSettings.isExtensibilityEnabled()) {
     String secProtocols =
         System.getProperty(SECURITY_PROTOCOLS_PROPERTIES, SECURITY_PROTOCOLS_PROPERTIES_DEFAULT);
     InputStream is = SecurityProtocols.class.getResourceAsStream(secProtocols);
     if (is == null) {
       throw new InternalError("Could not read '" + secProtocols + "' from classpath!");
     }
     Properties props = new Properties();
     try {
       props.load(is);
       for (Enumeration en = props.propertyNames(); en.hasMoreElements(); ) {
         String className = en.nextElement().toString();
         try {
           Class c = Class.forName(className);
           Object proto = c.newInstance();
           if (proto instanceof AuthenticationProtocol) {
             addAuthenticationProtocol((AuthenticationProtocol) proto);
           } else if (proto instanceof PrivacyProtocol) {
             addPrivacyProtocol((PrivacyProtocol) proto);
           } else {
             logger.error(
                 "Failed to register security protocol because it does "
                     + "not implement required interfaces: "
                     + className);
           }
         } catch (Exception cnfe) {
           logger.error(cnfe);
           throw new InternalError(cnfe.toString());
         }
       }
     } catch (IOException iox) {
       String txt = "Could not read '" + secProtocols + "': " + iox.getMessage();
       logger.error(txt);
       throw new InternalError(txt);
     } finally {
       try {
         is.close();
       } catch (IOException ex) {
         // ignore
         logger.warn(ex);
       }
     }
   } else {
     addAuthenticationProtocol(new AuthMD5());
     addAuthenticationProtocol(new AuthSHA());
     addPrivacyProtocol(new PrivDES());
     addPrivacyProtocol(new PrivAES128());
     addPrivacyProtocol(new PrivAES192());
     addPrivacyProtocol(new PrivAES256());
   }
 }
Beispiel #3
0
  @Before
  public void setUp() throws Exception {
    // Create a global USM that all client calls will use
    SNMP4JSettings.setEnterpriseID(5813);
    m_usm =
        new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
    SecurityModels.getInstance().addSecurityModel(m_usm);

    try {
      m_agent =
          MockSnmpAgent.createAgentAndRun(
              classPathResource("penrose-lldp-mib.properties"),
              str(InetAddress.getLocalHost()) + "/0");
    } catch (Throwable e) {
      m_agent =
          MockSnmpAgent.createAgentAndRun(
              classPathResource("penrose-lldp-mib.properties"),
              str(InetAddressUtils.ONE_TWENTY_SEVEN) + "/0");
    }

    m_requestedVarbinds = new ArrayList<AnticipatedRequest>();
  }
 public void run() {
   DatagramSocket socketCopy = socket;
   if (socketCopy != null) {
     try {
       socketCopy.setSoTimeout(getSocketTimeout());
       if (receiveBufferSize > 0) {
         socketCopy.setReceiveBufferSize(Math.max(receiveBufferSize, maxInboundMessageSize));
       }
       if (logger.isDebugEnabled()) {
         logger.debug(
             "UDP receive buffer size for socket "
                 + getAddress()
                 + " is set to: "
                 + socketCopy.getReceiveBufferSize());
       }
     } catch (SocketException ex) {
       logger.error(ex);
       setSocketTimeout(0);
     }
   }
   while (!stop) {
     DatagramPacket packet =
         new DatagramPacket(buf, buf.length, udpAddress.getInetAddress(), udpAddress.getPort());
     try {
       socketCopy = socket;
       try {
         if (socketCopy == null) {
           stop = true;
           continue;
         }
         socketCopy.receive(packet);
       } catch (InterruptedIOException iiox) {
         if (iiox.bytesTransferred <= 0) {
           continue;
         }
       }
       if (logger.isDebugEnabled()) {
         logger.debug(
             "Received message from "
                 + packet.getAddress()
                 + "/"
                 + packet.getPort()
                 + " with length "
                 + packet.getLength()
                 + ": "
                 + new OctetString(packet.getData(), 0, packet.getLength()).toHexString());
       }
       ByteBuffer bis;
       // If messages are processed asynchronously (i.e. multi-threaded)
       // then we have to copy the buffer's content here!
       if (isAsyncMsgProcessingSupported()) {
         byte[] bytes = new byte[packet.getLength()];
         System.arraycopy(packet.getData(), 0, bytes, 0, bytes.length);
         bis = ByteBuffer.wrap(bytes);
       } else {
         bis = ByteBuffer.wrap(packet.getData());
       }
       TransportStateReference stateReference =
           new TransportStateReference(
               DefaultUdpTransportMapping.this,
               udpAddress,
               null,
               SecurityLevel.undefined,
               SecurityLevel.undefined,
               false,
               socketCopy);
       fireProcessMessage(
           new UdpAddress(packet.getAddress(), packet.getPort()), bis, stateReference);
     } catch (SocketTimeoutException stex) {
       // ignore
     } catch (PortUnreachableException purex) {
       synchronized (DefaultUdpTransportMapping.this) {
         listener = null;
       }
       logger.error(purex);
       if (logger.isDebugEnabled()) {
         purex.printStackTrace();
       }
       if (SNMP4JSettings.isFowardRuntimeExceptions()) {
         throw new RuntimeException(purex);
       }
       break;
     } catch (SocketException soex) {
       if (!stop) {
         logger.error(
             "Socket for transport mapping " + toString() + " error: " + soex.getMessage(),
             soex);
       }
       if (SNMP4JSettings.isFowardRuntimeExceptions()) {
         stop = true;
         throw new RuntimeException(soex);
       }
     } catch (IOException iox) {
       logger.warn(iox);
       if (logger.isDebugEnabled()) {
         iox.printStackTrace();
       }
       if (SNMP4JSettings.isFowardRuntimeExceptions()) {
         throw new RuntimeException(iox);
       }
     }
   }
   synchronized (DefaultUdpTransportMapping.this) {
     listener = null;
     stop = true;
     DatagramSocket closingSocket = socket;
     if ((closingSocket != null) && (!closingSocket.isClosed())) {
       closingSocket.close();
     }
   }
   if (logger.isDebugEnabled()) {
     logger.debug("Worker task stopped:" + getClass().getName());
   }
 }