예제 #1
0
 @Override
 public void sessionCreated(IoSession session) throws Exception {
   MRTMPEdgeConnection conn = new MRTMPEdgeConnection();
   conn.setIoSession(session);
   mrtmpManager.registerConnection(conn);
   session.setAttribute(MRTMPEdgeConnection.EDGE_CONNECTION_KEY, conn);
   session.getFilterChain().addFirst("protocolFilter", new ProtocolCodecFilter(this.codecFactory));
   if (log.isDebugEnabled()) {
     session.getFilterChain().addLast("logger", new LoggingFilter());
   }
   log.debug("Created MRTMP Edge Connection {}", conn);
 }
  private IoSession newSessionWithoutLock(SocketAddress remoteAddress, SocketAddress localAddress)
      throws Exception {
    DatagramChannel handle = boundHandles.get(localAddress);

    if (handle == null) {
      throw new IllegalArgumentException("Unknown local address: " + localAddress);
    }

    IoSession session;

    synchronized (sessionRecycler) {
      session = sessionRecycler.recycle(remoteAddress);

      if (session != null) {
        return session;
      }

      // If a new session needs to be created.
      NioSession newSession = newSession(this, handle, remoteAddress);
      getSessionRecycler().put(newSession);
      session = newSession;
    }

    initSession(session, null, null);

    try {
      this.getFilterChainBuilder().buildFilterChain(session.getFilterChain());
      getListeners().fireSessionCreated(session);
    } catch (Exception e) {
      ExceptionMonitor.getInstance().exceptionCaught(e);
    }

    return session;
  }
  /** Calls {@link IoServiceListener#sessionDestroyed(IoSession)} for all registered listeners. */
  public void fireSessionDestroyed(IoSession session) {
    // Try to remove the remaining empty session set after removal.
    if (managedSessions.remove(Long.valueOf(session.getId())) == null) {
      return;
    }

    // Fire session events.
    session.getFilterChain().fireSessionClosed();

    // Fire listener events.
    try {
      for (IoServiceListener l : listeners) {
        try {
          l.sessionDestroyed(session);
        } catch (Throwable e) {
          ExceptionMonitor.getInstance().exceptionCaught(e);
        }
      }
    } finally {
      // Fire a virtual service deactivation event for the last session of the connector.
      if (session.getService() instanceof IoConnector) {
        boolean lastSession = false;
        synchronized (managedSessions) {
          lastSession = managedSessions.isEmpty();
        }
        if (lastSession) {
          fireServiceDeactivated();
        }
      }
    }
  }
 /** {@inheritDoc} */
 @Override
 public void messageReceived(IoSession session, Object message) throws Exception {
   if (log.isTraceEnabled()) {
     log.trace("messageReceived session: {} message: {}", session, message);
     log.trace("Filter chain: {}", session.getFilterChain());
   }
   String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
   if (log.isTraceEnabled()) {
     log.trace("Message received on session: {} id: {}", session.getId(), sessionId);
   }
   RTMPMinaConnection conn =
       (RTMPMinaConnection) RTMPConnManager.getInstance().getConnectionBySessionId(sessionId);
   if (conn != null) {
     if (message != null) {
       if (message instanceof Packet) {
         byte state = conn.getStateCode();
         // checking the state before allowing a task to be created will hopefully prevent rejected
         // task exceptions
         if (state != RTMP.STATE_DISCONNECTING && state != RTMP.STATE_DISCONNECTED) {
           conn.handleMessageReceived((Packet) message);
         } else {
           log.info(
               "Ignoring received message on {} due to state: {}", sessionId, RTMP.states[state]);
         }
       }
     }
   } else {
     log.warn("Connection was not found for {}, force closing", sessionId);
     forceClose(session);
   }
 }
예제 #5
0
 public void addCompression() {
   IoFilterChain chain = ioSession.getFilterChain();
   String baseFilter = EXECUTOR_FILTER_NAME;
   if (chain.contains(TLS_FILTER_NAME)) {
     baseFilter = TLS_FILTER_NAME;
   }
   chain.addAfter(
       baseFilter,
       COMPRESSION_FILTER_NAME,
       new CompressionFilter(true, false, CompressionFilter.COMPRESSION_MAX));
 }
예제 #6
0
  public void startTLS(boolean clientMode, String remoteServer, ClientAuth authentication)
      throws Exception {
    boolean c2s = (remoteServer == null);
    KeyStore ksKeys = SSLConfig.getKeyStore();
    String keypass = SSLConfig.getKeyPassword();

    KeyStore ksTrust = (c2s ? SSLConfig.getc2sTrustStore() : SSLConfig.gets2sTrustStore());
    String trustpass = (c2s ? SSLConfig.getc2sTrustPassword() : SSLConfig.gets2sTrustPassword());
    if (c2s) Log.debug("NIOConnection: startTLS: using c2s");
    else Log.debug("NIOConnection: startTLS: using s2s");
    // KeyManager's decide which key material to use.
    KeyManager[] km = SSLJiveKeyManagerFactory.getKeyManagers(ksKeys, keypass);

    // TrustManager's decide whether to allow connections.
    TrustManager[] tm = SSLJiveTrustManagerFactory.getTrustManagers(ksTrust, trustpass);

    if (clientMode || authentication == ClientAuth.needed || authentication == ClientAuth.wanted) {
      // We might need to verify a certificate from our peer, so get different TrustManager[]'s
      if (c2s) {
        // Check if we can trust certificates presented by the client
        tm = new TrustManager[] {new ClientTrustManager(ksTrust)};
      } else {
        // Check if we can trust certificates presented by the server
        tm = new TrustManager[] {new ServerTrustManager(remoteServer, ksTrust, this)};
      }
    }

    String algorithm = JiveGlobals.getProperty(ConnectionSettings.Client.TLS_ALGORITHM, "TLS");
    SSLContext tlsContext = SSLContext.getInstance(algorithm);

    tlsContext.init(km, tm, null);

    SslFilter filter = new SslFilter(tlsContext);
    filter.setUseClientMode(clientMode);
    // Disable SSLv3 due to POODLE vulnerability.
    filter.setEnabledProtocols(new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"});
    if (authentication == ClientAuth.needed) {
      filter.setNeedClientAuth(true);
    } else if (authentication == ClientAuth.wanted) {
      // Just indicate that we would like to authenticate the client but if client
      // certificates are self-signed or have no certificate chain then we are still
      // good
      filter.setWantClientAuth(true);
    }
    ioSession.getFilterChain().addAfter(EXECUTOR_FILTER_NAME, TLS_FILTER_NAME, filter);
    ioSession.setAttribute(SslFilter.DISABLE_ENCRYPTION_ONCE, Boolean.TRUE);

    if (!clientMode) {
      // Indicate the client that the server is ready to negotiate TLS
      deliverRawText("<proceed xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>");
    }
  }
  private void readHandle(DatagramChannel handle) throws Exception {
    IoBuffer readBuf = IoBuffer.allocate(getSessionConfig().getReadBufferSize());

    SocketAddress remoteAddress = receive(handle, readBuf);

    if (remoteAddress != null) {
      IoSession session = newSessionWithoutLock(remoteAddress, localAddress(handle));

      readBuf.flip();

      session.getFilterChain().fireMessageReceived(readBuf);
    }
  }
 /** {@inheritDoc} */
 @Override
 public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
   log.debug("Filter chain: {}", session.getFilterChain());
   String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
   if (log.isDebugEnabled()) {
     log.warn("Exception caught on session: {} id: {}", session.getId(), sessionId, cause);
   }
   if (cause instanceof IOException) {
     // Mina states that the connection will be automatically closed when an IOException is caught
     log.debug("IOException caught on {}", sessionId);
   } else {
     log.debug("Non-IOException caught on {}", sessionId);
     forceClose(session);
   }
 }
 /** {@inheritDoc} */
 @Override
 public void sessionCreated(IoSession session) throws Exception {
   log.debug("Session created RTMP");
   // add rtmpe filter, rtmp protocol filter is added upon successful handshake
   session.getFilterChain().addFirst("rtmpeFilter", new RTMPEIoFilter());
   // create a connection
   RTMPMinaConnection conn = createRTMPMinaConnection();
   // add session to the connection
   conn.setIoSession(session);
   // add the handler
   conn.setHandler(handler);
   // add the connections session id for look up using the connection manager
   session.setAttribute(RTMPConnection.RTMP_SESSION_ID, conn.getSessionId());
   // create an inbound handshake
   InboundHandshake handshake = new InboundHandshake();
   // set whether or not unverified will be allowed
   handshake.setUnvalidatedConnectionAllowed(
       ((RTMPHandler) handler).isUnvalidatedConnectionAllowed());
   // add the in-bound handshake, defaults to non-encrypted mode
   session.setAttribute(RTMPConnection.RTMP_HANDSHAKE, handshake);
 }
  /** Calls {@link IoServiceListener#sessionCreated(IoSession)} for all registered listeners. */
  public void fireSessionCreated(IoSession session) {
    boolean firstSession = false;
    if (session.getService() instanceof IoConnector) {
      synchronized (managedSessions) {
        firstSession = managedSessions.isEmpty();
      }
    }

    // If already registered, ignore.
    if (managedSessions.putIfAbsent(Long.valueOf(session.getId()), session) != null) {
      return;
    }

    // If the first connector session, fire a virtual service activation event.
    if (firstSession) {
      fireServiceActivated();
    }

    // Fire session events.
    session.getFilterChain().fireSessionCreated();
    session.getFilterChain().fireSessionOpened();

    int managedSessionCount = managedSessions.size();
    if (managedSessionCount > largestManagedSessionCount) {
      largestManagedSessionCount = managedSessionCount;
    }
    cumulativeManagedSessionCount++;

    // Fire listener events.
    for (IoServiceListener l : listeners) {
      try {
        l.sessionCreated(session);
      } catch (Throwable e) {
        ExceptionMonitor.getInstance().exceptionCaught(e);
      }
    }
  }
예제 #11
0
 @Override
 public void sessionOpened(IoSession session) throws Exception {
   session.setAttribute("remote", session.getRemoteAddress());
   session.getFilterChain().addFirst("protocol", new ProtocolCodecFilter(RS2CodecFactory.LOGIN));
   engine.pushTask(new SessionOpenedTask(session));
 }
예제 #12
0
 public boolean isCompressed() {
   return ioSession.getFilterChain().contains(COMPRESSION_FILTER_NAME);
 }
예제 #13
0
 public void startCompression() {
   CompressionFilter ioFilter =
       (CompressionFilter) ioSession.getFilterChain().get(COMPRESSION_FILTER_NAME);
   ioFilter.setCompressOutbound(true);
 }
예제 #14
0
 public boolean isSecure() {
   return ioSession.getFilterChain().contains(TLS_FILTER_NAME);
 }
 @Override
 public void sessionCreated(IoSession session) throws Exception {
   super.sessionCreated(session);
   session.getFilterChain().addLast("codec", streamWriteFilter);
 }
예제 #16
0
  /** {@inheritDoc} */
  @SuppressWarnings("resource")
  @Override
  public void sessionCreated(IoSession session) throws Exception {

    boolean isClient = session.getRemoteAddress().equals(forward);

    if (log.isDebugEnabled()) {
      log.debug("Is downstream: " + isClient);
      session.getFilterChain().addFirst("protocol", new ProtocolCodecFilter(codecFactory));
    }

    session.getFilterChain().addFirst("proxy", new ProxyFilter(isClient ? "client" : "server"));

    if (true) {

      String fileName =
          System.currentTimeMillis()
              + '_'
              + forward.getHostName()
              + '_'
              + forward.getPort()
              + '_'
              + (isClient ? "DOWNSTREAM" : "UPSTREAM");

      File headersFile = loader.getResource(dumpTo + fileName + ".cap").getFile();
      headersFile.createNewFile();

      File rawFile = loader.getResource(dumpTo + fileName + ".raw").getFile();
      rawFile.createNewFile();

      FileOutputStream headersFos = new FileOutputStream(headersFile);
      WritableByteChannel headers = headersFos.getChannel();

      FileOutputStream rawFos = new FileOutputStream(rawFile);
      WritableByteChannel raw = rawFos.getChannel();

      IoBuffer header = IoBuffer.allocate(1);
      header.put((byte) (isClient ? 0x00 : 0x01));
      header.flip();
      headers.write(header.buf());

      session.getFilterChain().addFirst("dump", new NetworkDumpFilter(headers, raw));
    }

    // session.getFilterChain().addLast("logger", new LoggingFilter() );

    if (!isClient) {
      log.debug("Connecting..");
      IoConnector connector = new NioSocketConnector();
      connector.setHandler(this);
      ConnectFuture future = connector.connect(forward);
      future.awaitUninterruptibly(); // wait for connect, or timeout
      if (future.isConnected()) {
        if (log.isDebugEnabled()) {
          log.debug("Connected: {}", forward);
        }
        IoSession client = future.getSession();
        client.setAttribute(ProxyFilter.FORWARD_KEY, session);
        session.setAttribute(ProxyFilter.FORWARD_KEY, client);
      }
    }
    super.sessionCreated(session);
  }