Пример #1
0
  /** Invoked when a message is received. */
  public void messageReceived(IoSession session, Object message) throws Exception {
    log.debug("messageReceived()...");
    // <iq id="567-3" type="result"><test>aaaa</test></iq>
    // <iq id="567-3" type="result"><test>aaaa</test></iq>
    // log.info("RCVD: " + message);

    // Get the stanza handler
    StanzaHandler handler = (StanzaHandler) session.getAttribute(STANZA_HANDLER);

    // Get the XMPP packet parser
    int hashCode = Thread.currentThread().hashCode();
    XMPPPacketReader parser = parsers.get(hashCode);
    if (parser == null) {
      parser = new XMPPPacketReader();
      parser.setXPPFactory(factory);
      parsers.put(hashCode, parser);
    }

    // The stanza handler processes the message
    try {
      handler.process((String) message, parser);
    } catch (Exception e) {
      log.error("Closing connection due to error while processing message: " + message, e);
      Connection connection = (Connection) session.getAttribute(CONNECTION);
      connection.close();
    }
  }
Пример #2
0
  @Override
  public void messageReceived(Object in, IoSession session) throws Exception {
    RTMPConnection conn = (RTMPConnection) session.getAttribute(RTMPConnection.RTMP_CONNECTION_KEY);
    RTMP state = (RTMP) session.getAttribute(ProtocolState.SESSION_KEY);
    IRTMPEvent message = null;
    final Packet packet = (Packet) in;
    message = packet.getMessage();
    final Header header = packet.getHeader();
    final Channel channel = conn.getChannel(header.getChannelId());

    // Increase number of received messages
    conn.messageReceived();

    if (header.getDataType() == TYPE_BYTES_READ) {
      // TODO need to sync the bytes read on edge and origin
      onStreamBytesRead(conn, channel, header, (BytesRead) message);
    }

    if (header.getDataType() == TYPE_INVOKE) {
      final IServiceCall call = ((Invoke) message).getCall();
      final String action = call.getServiceMethodName();
      if (call.getServiceName() == null
          && !conn.isConnected()
          && StreamAction.valueOf(action).equals(StreamAction.CONNECT)) {
        handleConnect(conn, channel, header, (Invoke) message, (RTMP) state);
        return;
      }
    }

    switch (header.getDataType()) {
      case TYPE_CHUNK_SIZE:
      case TYPE_INVOKE:
      case TYPE_FLEX_MESSAGE:
      case TYPE_NOTIFY:
      case TYPE_AUDIO_DATA:
      case TYPE_VIDEO_DATA:
      case TYPE_FLEX_SHARED_OBJECT:
      case TYPE_FLEX_STREAM_SEND:
      case TYPE_SHARED_OBJECT:
      case TYPE_BYTES_READ:
        forwardPacket(conn, packet);
        break;
      case TYPE_PING:
        onPing(conn, channel, header, (Ping) message);
        break;

      default:
        if (log.isDebugEnabled()) {
          log.debug("Unknown type: {}", header.getDataType());
        }
    }
    if (message instanceof Unknown) {
      log.info(message.toString());
    }
    if (message != null) {
      message.release();
    }
  }
 @Override
 public void sessionClosed(IoSession session) throws Exception {
   if (session.getAttribute(OTHER_IO_SESSION) != null) {
     IoSession sess = (IoSession) session.getAttribute(OTHER_IO_SESSION);
     sess.setAttribute(OTHER_IO_SESSION, null);
     sess.close(false);
     session.setAttribute(OTHER_IO_SESSION, null);
   }
 }
  public DigestMD5PrivacyIoFilterCodec(IoSession session) {
    super(session);
    String encoding = (String) session.getAttribute(AuthDigestMD5Command.ENCODING);
    try {
      AuthDigestMD5IoFilter.computePrivacyKeys(session, encoding, false);
    } catch (Exception e) {
      e.printStackTrace();
    }

    encCipher = (Cipher) session.getAttribute(AuthDigestMD5IoFilter.ENCODING_CIPHER);
    decCipher = (Cipher) session.getAttribute(AuthDigestMD5IoFilter.DECODING_CIPHER);
  }
 private static String getSessionInfo(IoSession session) {
   if (session != null) {
     return "["
         + (session.getAttribute("ID") == null
             ? String.valueOf(session.getId())
             : session.getAttribute("ID"))
         + "]"
         + "["
         + session.getId()
         + "] => "
         + session.getRemoteAddress();
   }
   return "[NULL] => NULL";
 }
  @Override
  public boolean send(String data) {
    // Check for and disconnect slow consumers.
    if (maxScheduledWriteRequests > 0
        && ioSession.getScheduledWriteMessages() >= maxScheduledWriteRequests) {
      Session qfjSession = (Session) ioSession.getAttribute(SessionConnector.QF_SESSION);
      try {
        qfjSession.disconnect("Slow consumer", true);
      } catch (IOException e) {
      }
      return false;
    }

    // The data is written asynchronously in a MINA thread
    WriteFuture future = ioSession.write(data);
    if (synchronousWrites) {
      try {
        if (!future.awaitUninterruptibly(synchronousWriteTimeout)) {
          log.error("Synchronous write timed out after " + synchronousWriteTimeout + "ms");
          return false;
        }
      } catch (RuntimeException e) {
        log.error("Synchronous write failed: " + e.getMessage());
        return false;
      }
    }
    return true;
  }
Пример #7
0
 public Certificate[] getLocalCertificates() {
   SSLSession sslSession = (SSLSession) ioSession.getAttribute(SslFilter.SSL_SESSION);
   if (sslSession != null) {
     return sslSession.getLocalCertificates();
   }
   return new Certificate[0];
 }
Пример #8
0
  @Override
  public void messageReceived(IoSession session, Object message) {
    // client only sends AddMessage. otherwise, we will have to identify
    // its type using instanceof operator.
    AddMessage am = (AddMessage) message;

    // add the value to the current sum.
    int sum = ((Integer) session.getAttribute(SUM_KEY)).intValue();
    int value = am.getValue();
    long expectedSum = (long) sum + value;
    if (expectedSum > Integer.MAX_VALUE || expectedSum < Integer.MIN_VALUE) {
      // if the sum overflows or underflows, return error message
      ResultMessage rm = new ResultMessage();
      rm.setSequence(am.getSequence()); // copy sequence
      rm.setOk(false);
      session.write(rm);
    } else {
      // sum up
      sum = (int) expectedSum;
      session.setAttribute(SUM_KEY, new Integer(sum));

      // return the result message
      ResultMessage rm = new ResultMessage();
      rm.setSequence(am.getSequence()); // copy sequence
      rm.setOk(true);
      rm.setValue(sum);
      session.write(rm);
    }
  }
 /** {@inheritDoc} */
 @Override
 public void sessionClosed(IoSession session) throws Exception {
   String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
   log.debug("Session closed: {} id: {}", session.getId(), sessionId);
   if (log.isTraceEnabled()) {
     log.trace("Session attributes: {}", session.getAttributeKeys());
   }
   if (sessionId != null) {
     RTMPMinaConnection conn =
         (RTMPMinaConnection) RTMPConnManager.getInstance().getConnectionBySessionId(sessionId);
     if (conn != null) {
       // fire-off closed event
       handler.connectionClosed(conn);
       // clear any session attributes we may have previously set
       // TODO: verify this cleanup code is necessary. The session is over and will be garbage
       // collected surely?
       if (session.containsAttribute(RTMPConnection.RTMP_HANDSHAKE)) {
         session.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
       }
       if (session.containsAttribute(RTMPConnection.RTMPE_CIPHER_IN)) {
         session.removeAttribute(RTMPConnection.RTMPE_CIPHER_IN);
         session.removeAttribute(RTMPConnection.RTMPE_CIPHER_OUT);
       }
     } else {
       log.warn("Connection was not found for {}", sessionId);
     }
     cleanSession(session, false);
   } else {
     log.debug("Connections session id was null in session, may already be closed");
   }
 }
Пример #10
0
 public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
   System.out.println(cause.getMessage());
   CmdListener cmdListener = (CmdListener) session.getAttribute("CmdListener");
   cmdListener.setClose();
   session.close(true);
   cmdListener.onException(cause);
 }
Пример #11
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.apache.mina.core.service.IoHandlerAdapter#sessionClosed(org.apache
  * .mina.core.session.IoSession)
  */
 public void sessionClosed(IoSession session) throws Exception {
   log.debug("closed stub: " + session.getRemoteAddress());
   TConn d = (TConn) session.getAttribute("conn");
   if (d != null) {
     d.close();
   }
 }
Пример #12
0
  @Override
  public void filterClose(final NextFilter nextFilter, final IoSession session)
      throws SSLException {
    SslHandler handler = (SslHandler) session.getAttribute(SSL_HANDLER);
    if (handler == null) {
      // The connection might already have closed, or
      // SSL might have not started yet.
      nextFilter.filterClose(session);
      return;
    }

    WriteFuture future = null;
    try {
      synchronized (handler) {
        if (isSslStarted(session)) {
          future = initiateClosure(nextFilter, session);
          future.addListener(
              new IoFutureListener<IoFuture>() {
                public void operationComplete(IoFuture future) {
                  nextFilter.filterClose(session);
                }
              });
        }
      }

      handler.flushScheduledEvents();
    } finally {
      if (future == null) {
        nextFilter.filterClose(session);
      }
    }
  }
Пример #13
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.apache.mina.core.service.IoHandlerAdapter#exceptionCaught(org.apache
  * .mina.core.session.IoSession, java.lang.Throwable)
  */
 @Override
 public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
   TConn d = (TConn) session.getAttribute("conn");
   if (d != null && d.valid()) {
     App.bye(d);
   }
 }
Пример #14
0
 /** {@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);
   }
 }
 /**
  * 登录/登出是否成功
  *
  * @return boolean
  */
 public boolean isLockOk() {
   if (session != null) {
     LockExpress lock = (LockExpress) session.getAttribute(ExpressConstant.SESSION_LOCK);
     return lock.isOk();
   }
   return false;
 }
Пример #16
0
  @Override
  public void encode(IoSession session, Object o, ProtocolEncoderOutput out) throws Exception {
    PacketBuilder message = (PacketBuilder) o;

    // Allocate a buffer of the exact size for the packet
    IoBuffer buffer = IoBuffer.allocate(Packet.HEADER_SIZE + message.size(), false);

    // Write the packet header
    int ordinal = message.getType().ordinal();

    // If encryption is enabled, encrypt the packet type
    if (session.containsAttribute("encrypter")) {
      ISAACAlgorithm encrypter = (ISAACAlgorithm) session.getAttribute("encrypter");
      ordinal += encrypter.nextInt();
    }

    // Write the packet headers
    buffer.putInt(ordinal);
    buffer.putInt(message.size());

    // Write the packet payload
    buffer.put(message.getPayload());

    // Flip then output
    out.write(buffer.flip());
  }
 protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
     throws Exception {
   DecoderState decoderState = (DecoderState) session.getAttribute(DECODER_STATE_KEY);
   if (decoderState == null) {
     decoderState = new DecoderState();
     session.setAttribute(DECODER_STATE_KEY, decoderState);
   }
   if (decoderState.image1 == null) {
     // try to read first image
     if (in.prefixedDataAvailable(4, MAX_IMAGE_SIZE)) {
       decoderState.image1 = readImage(in);
     } else {
       // not enough data available to read first image
       return false;
     }
   }
   if (decoderState.image1 != null) {
     // try to read second image
     if (in.prefixedDataAvailable(4, MAX_IMAGE_SIZE)) {
       BufferedImage image2 = readImage(in);
       ImageResponse imageResponse = new ImageResponse(decoderState.image1, image2);
       out.write(imageResponse);
       decoderState.image1 = null;
       return true;
     } else {
       // not enough data available to read second image
       return false;
     }
   }
   return false;
 }
 /**
  * Handles a packet.
  *
  * @param session The session.
  * @param packet The packet.
  */
 public void handle(IoSession session, Packet packet) {
   try {
     packetHandlers[packet.getOpcode()].handle((Player) session.getAttribute("player"), packet);
   } catch (final Exception ex) {
     logger.log(Level.SEVERE, "Exception handling packet.", ex);
     session.close(false);
   }
 }
Пример #19
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.apache.mina.core.service.IoHandlerAdapter#sessionIdle(org.apache.
  * mina.core.session.IoSession, org.apache.mina.core.session.IdleStatus)
  */
 public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
   if (IdleStatus.BOTH_IDLE.equals(status)) {
     Long l = (Long) session.getAttribute("last");
     if (l != null && System.currentTimeMillis() - l > 60 * 1000) {
       session.close(true);
     }
   }
 }
 /////////////////////////////////////
 // 结合CumulativeProtocolDecoder/////////////////////////////////////////////////
 // 获取session的context
 public Context getContext(IoSession session) {
   Context ctx = (Context) session.getAttribute(CONTEXT);
   if (ctx == null) {
     ctx = new Context();
     session.setAttribute(CONTEXT, ctx);
   }
   return ctx;
 }
Пример #21
0
 @Override
 public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
   Object userSid = session.getAttribute(BaseHandler.ATTR_USER_SID);
   if (userSid != null) {
     logger.debug("===> sessionIdle:" + userSid.toString());
   }
   session.closeOnFlush();
 }
Пример #22
0
 /** Invoked with the related IdleStatus when a connection becomes idle. */
 public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
   log.debug("sessionIdle()...");
   Connection connection = (Connection) session.getAttribute(CONNECTION);
   if (log.isDebugEnabled()) {
     log.debug("Closing connection that has been idle: " + connection);
   }
   connection.close();
 }
Пример #23
0
 @Override
 public void sessionClosed(IoSession session) throws Exception {
   MRTMPEdgeConnection conn =
       (MRTMPEdgeConnection) session.getAttribute(MRTMPEdgeConnection.EDGE_CONNECTION_KEY);
   mrtmpManager.unregisterConnection(conn);
   conn.close();
   log.debug("Closed MRTMP Edge Connection " + conn);
 }
 /**
  * 锁定登录/登出当前线程
  *
  * @throws InterruptedException
  */
 public void doLock() throws InterruptedException {
   if (session != null) {
     LockExpress lock = (LockExpress) session.getAttribute(ExpressConstant.SESSION_LOCK);
     synchronized (lock) {
       lock.setOk(false);
       lock.wait(ExpressConstant.CONNECT_TIMEOUT * 1000L);
     }
   }
 }
 private void closeSession(IoSession session) {
   String room = (String) session.getAttribute(ROOM, null);
   if (room != null) {
     log.info("Closing session [" + room + "]. ");
   } else {
     log.info("Cannot determine session to close.");
   }
   CloseFuture future = session.close(true);
 }
  @Override
  public void messageReceived(NextFilter nextFilter, final IoSession session, Object message)
      throws Exception {

    int maxReadThroughput = this.maxReadThroughput;
    // process the request if our max is greater than zero
    if (maxReadThroughput > 0) {
      final State state = (State) session.getAttribute(STATE);
      long currentTime = System.currentTimeMillis();

      long suspendTime = 0;
      boolean firstRead = false;
      synchronized (state) {
        state.readBytes += messageSizeEstimator.estimateSize(message);

        if (!state.suspendedRead) {
          if (state.readStartTime == 0) {
            firstRead = true;
            state.readStartTime = currentTime - 1000;
          }

          long throughput = (state.readBytes * 1000 / (currentTime - state.readStartTime));
          if (throughput >= maxReadThroughput) {
            suspendTime =
                Math.max(
                    0,
                    state.readBytes * 1000 / maxReadThroughput
                        - (firstRead ? 0 : currentTime - state.readStartTime));

            state.readBytes = 0;
            state.readStartTime = 0;
            state.suspendedRead = suspendTime != 0;

            adjustReadBufferSize(session);
          }
        }
      }

      if (suspendTime != 0) {
        session.suspendRead();
        scheduledExecutor.schedule(
            new Runnable() {
              public void run() {
                synchronized (state) {
                  state.suspendedRead = false;
                }
                session.resumeRead();
              }
            },
            suspendTime,
            TimeUnit.MILLISECONDS);
      }
    }

    nextFilter.messageReceived(session, message);
  }
Пример #27
0
 private CharsetDecoder charsetDecoder(IoSession session) {
   synchronized (session) {
     CharsetDecoder decoder = (CharsetDecoder) session.getAttribute(CHARSET_DECODER);
     if (decoder == null) {
       decoder = config.getCharset().newDecoder();
       session.setAttribute(CHARSET_DECODER, decoder);
     }
     return decoder;
   }
 }
Пример #28
0
 private DecoderState decoderState(IoSession session) {
   synchronized (session) {
     DecoderState decoderState = (DecoderState) session.getAttribute(DECODER_STATE);
     if (decoderState == null) {
       decoderState = new DecoderState();
       session.setAttribute(DECODER_STATE, decoderState);
     }
     return decoderState;
   }
 }
  @Override
  public void messageSent(NextFilter nextFilter, final IoSession session, WriteRequest writeRequest)
      throws Exception {

    int maxWriteThroughput = this.maxWriteThroughput;
    // process the request if our max is greater than zero
    if (maxWriteThroughput > 0) {
      final State state = (State) session.getAttribute(STATE);
      long currentTime = System.currentTimeMillis();

      long suspendTime = 0;
      boolean firstWrite = false;
      synchronized (state) {
        state.writtenBytes += messageSizeEstimator.estimateSize(writeRequest.getMessage());
        if (!state.suspendedWrite) {
          if (state.writeStartTime == 0) {
            firstWrite = true;
            state.writeStartTime = currentTime - 1000;
          }

          long throughput = (state.writtenBytes * 1000 / (currentTime - state.writeStartTime));
          if (throughput >= maxWriteThroughput) {
            suspendTime =
                Math.max(
                    0,
                    state.writtenBytes * 1000 / maxWriteThroughput
                        - (firstWrite ? 0 : currentTime - state.writeStartTime));

            state.writtenBytes = 0;
            state.writeStartTime = 0;
            state.suspendedWrite = suspendTime != 0;
          }
        }
      }

      if (suspendTime != 0) {
        log.trace("Suspending write");
        session.suspendWrite();
        scheduledExecutor.schedule(
            new Runnable() {
              public void run() {
                synchronized (state) {
                  state.suspendedWrite = false;
                }
                session.resumeWrite();
                log.trace("Resuming write");
              }
            },
            suspendTime,
            TimeUnit.MILLISECONDS);
      }
    }

    nextFilter.messageSent(session, writeRequest);
  }
Пример #30
0
 @Override
 public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
   LOG.info("decode invoked with buffer {}", in);
   in.reset();
   int startPos = in.markValue();
   // Common decoding part
   PublishMessage message = new PublishMessage();
   if (!decodeCommonHeader(message, in)) {
     LOG.info("decode ask for more data after {}", in);
     in.reset();
     return;
   }
   if (((int) session.getAttribute(MQTTDecoder.PROTOCOL_VERSION)) == MQTTProtocol.VERSION_3_1_1) {
     if (message.getQos() == AbstractMessage.QOSType.MOST_ONE && message.isDupFlag()) {
       // bad protocol, if QoS=0 => DUP = 0
       throw new CorruptedFrameException(
           "Received a PUBLISH with QoS=0 & DUP = 1, MQTT 3.1.1 violation");
     }
     if (message.getQos() == AbstractMessage.QOSType.RESERVED) {
       throw new CorruptedFrameException(
           "Received a PUBLISH with QoS flags setted 10 b11, MQTT 3.1.1 violation");
     }
   }
   int remainingLength = message.getRemainingLength();
   // Topic name
   String topic = MQTTProtocol.decodeString(in);
   if (topic == null) {
     in.reset();
     return;
   }
   if (topic.contains("+") || topic.contains("#")) {
     throw new CorruptedFrameException(
         "Received a PUBLISH with topic containting wild card chars, topic: " + topic);
   }
   message.setTopicName(topic);
   if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE
       || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) {
     message.setMessageID(in.getUnsignedShort());
   }
   int stopPos = in.position();
   // read the payload
   int payloadSize =
       remainingLength
           - (stopPos - startPos - 2)
           + (MQTTProtocol.numBytesToEncode(remainingLength) - 1);
   LOG.info("payload size: {}", payloadSize);
   if (in.remaining() < payloadSize) {
     in.reset();
     return;
   }
   byte[] payload = new byte[payloadSize];
   in.get(payload);
   message.setPayload(payload);
   out.write(message);
 }