private Request byOrderedParam(int protocol, String message) throws ProtocolDecoderException { String argLength = message.substring(0, 2); message = message.substring(2); String[] msgs = message.split(Protocols.LINE_SPLIT, -1); if (msgs.length < 2) { throw new ProtocolDecoderException("error ordered param req"); } Request req = GsonUtil.fromJson(msgs[0], Request.class); int len = Integer.parseInt(argLength); if (len > 0) { String[] params = new String[len]; for (int i = 0; i < len; i++) { params[i] = msgs[i + 1]; } req.setParamArray(params); } req.protocol = protocol; return req; }
protected Object decodeBody(IoSession session, IoBuffer in) throws Exception { // 跳过消息头 int nLen = in.getShort();// 包长(包括消息头) int cmdId = in.getShort(); // 跳过 版本 预留3个字节 in.skip(3); int bodyLen = nLen - MessageCodec.HEAD_LENGTH; byte[] bodys = new byte[bodyLen]; in.get(bodys); Packet packet = Packet.parseFrom(bodys); if (cmdId != packet.getCmdId()) { log.warn("head CMDid {} != body CMDid {}", cmdId, packet.getCmdId()); throw new ProtocolDecoderException("head CMDid " + cmdId + " != body CMDid " + packet.getCmdId()); } return packet; }
/** * 异常处理 */ public void exceptionCaught(IoSession ioSession, Throwable cause) throws Exception { if (cause instanceof IOException) { log.info("IOException异常 session= " + ioSession, cause); } else if (cause instanceof ProtocolDecoderException) { log.error("关闭session由于协议解码异常:" + ioSession, cause); ioSession.close(true); } else { log.error("未知异常session= " + ioSession, cause); } UserSession session = (UserSession) ioSession.getAttribute("session"); if (null != session) { StringBuffer logBuf = new StringBuffer(256); logBuf.append( "由于异常 session 关闭! userId=" + session.getUserId() + " ioSession=" + ioSession.getRemoteAddress()); boolean bIsClose = ioSession.isClosing(); boolean bIsConnect = ioSession.isConnected(); session.close(); logBuf.append(" isClosing:(" + bIsClose + "," + ioSession.isClosing() + ") isConnect:(" + bIsConnect + "," + ioSession.isConnected() + ")\n"); log.info(logBuf.toString()); } }
@Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { if (cause instanceof IOException) { // TODO Verify if there were packets pending to be sent and decide what to do with them Log.info("ConnectionHandler reports IOException for session: " + session, cause); } else if (cause instanceof ProtocolDecoderException) { Log.warn("Closing session due to exception: " + session, cause); // PIO-524: Determine stream:error message. final StreamError error; if (cause.getCause() != null && cause.getCause() instanceof XMLNotWellFormedException) { error = new StreamError(StreamError.Condition.xml_not_well_formed); } else { error = new StreamError(StreamError.Condition.internal_server_error); } final Connection connection = (Connection) session.getAttribute(CONNECTION); connection.deliverRawText(error.toXML()); session.close(); } else { Log.error("ConnectionHandler reports unexpected exception for session: " + session, cause); } }
public void exceptionCaught(final FtpIoSession session, final Throwable cause) throws Exception { if(cause instanceof ProtocolDecoderException && cause.getCause() instanceof MalformedInputException) { // client probably sent something which is not UTF-8 and we failed to // decode it LOG.warn( "Client sent command that could not be decoded: {}", ((ProtocolDecoderException)cause).getHexdump()); session.write(new DefaultFtpReply(FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS, "Invalid character in command")); } else if (cause instanceof WriteToClosedSessionException) { WriteToClosedSessionException writeToClosedSessionException = (WriteToClosedSessionException) cause; LOG.warn( "Client closed connection before all replies could be sent, last reply was {}", writeToClosedSessionException.getRequest()); session.close(false).awaitUninterruptibly(10000); } else { LOG.error("Exception caught, closing session", cause); session.close(false).awaitUninterruptibly(10000); } }
/** * {@inheritDoc} */ public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception { if (buffer == null) { buffer = IoBuffer.allocate(256).setAutoExpand(true); } if (buffer.position() + in.remaining() > maxLength) { throw new ProtocolDecoderException("Received data exceeds " + maxLength + " byte(s)."); } buffer.put(in); return this; }
/** * {@inheritDoc} */ public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception { boolean found = false; boolean finished = false; while (in.hasRemaining()) { byte b = in.get(); if (!hasCR) { if (b == CR) { hasCR = true; } else { if (b == LF) { found = true; } else { in.position(in.position() - 1); found = false; } finished = true; break; } } else { if (b == LF) { found = true; finished = true; break; } throw new ProtocolDecoderException("Expected LF after CR but was: " + (b & 0xff)); } } if (finished) { hasCR = false; return finishDecode(found, out); } return this; }
private Request byJsonParam(int protocol, String message) throws ProtocolDecoderException { String[] msgs = message.split(Protocols.LINE_SPLIT, -1); if (msgs.length < 2) { throw new ProtocolDecoderException("error jsoned param req"); } Request req = GsonUtil.fromJson(msgs[0], Request.class); req.setJsonedParam(msgs[1]); req.protocol = protocol; return req; }
public Object deserialize(int protocol, String message) throws ProtocolDecoderException { if (Protocols.hasFeature(protocol, Protocols.REQ_PARAM_JSON)) { return this.byJsonParam(protocol, message); } if (Protocols.hasFeature(protocol, Protocols.REQ_PARAM_ORDER)) { return this.byOrderedParam(protocol, message); } if (Protocols.hasFeature(protocol, Protocols.RESPONSE_JSON)) { return this.parseResponse(protocol, message); } throw new ProtocolDecoderException("error req protocol:" + Integer.toHexString(protocol)); }
protected boolean doDecodeString(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws CharacterCodingException, ProtocolDecoderException { int pos = in.position(); int protocol = in.getInt(); int prefixLength = 0, maxDataLength = 0; if ((protocol & Protocols.ONE) != 0) { prefixLength = 1; maxDataLength = 0xFF; } else if ((protocol & Protocols.TWO) != 0) { prefixLength = 2; maxDataLength = 0xFFFF; } else if ((protocol & Protocols.FOUR) != 0) { prefixLength = 4; maxDataLength = Protocols.MAX_LENGTH; } else { throw new ProtocolDecoderException("error transport protocol," + Integer.toHexString(protocol)); } if (in.prefixedDataAvailable(prefixLength, maxDataLength)) { String msg = in.getPrefixedString(prefixLength, charset.newDecoder()); if (msg == null || msg.isEmpty()) { return true; } out.write(msgDeserializer.deserialize(protocol, msg)); return true; } in.position(pos); return false; }
@Override public void exceptionCaught(IoSession session, Throwable throwable) throws Exception { if(throwable instanceof ProtocolDecoderException) { Throwable cause = ((ProtocolDecoderException) throwable).getCause(); if(cause instanceof HttpException && ((HttpException) cause).getStatusCode() == HttpStatus.CLIENT_ERROR_LENGTH_REQUIRED.code()) { //Ignore - Icecast 2.4 sometimes doesn't send any headers with their HTTP responses. Mina expects a //content-length for HTTP responses. } else { mLog.error("HTTP protocol decoder error", throwable); setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR); disconnect(); } } else { mLog.error("Broadcast error", throwable); setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR); disconnect(); } mConnecting.set(false); }
public void exceptionCaught(IoSession ioSession, Throwable cause) throws Exception { boolean disconnectNeeded = false; Session quickFixSession = findQFSession(ioSession); Throwable realCause = cause; if (cause instanceof ProtocolDecoderException && cause.getCause() != null) { realCause = cause.getCause(); } String reason; if (realCause instanceof IOException) { if (quickFixSession != null && quickFixSession.isEnabled()) { reason = "Socket exception (" + ioSession.getRemoteAddress() + "): " + cause; } else { reason = "Socket (" + ioSession.getRemoteAddress() + "): " + cause; } disconnectNeeded = true; } else if (realCause instanceof CriticalProtocolCodecException) { reason = "Critical protocol codec error: " + cause; disconnectNeeded = true; } else if (realCause instanceof ProtocolCodecException) { reason = "Protocol handler exception: " + cause; } else { reason = cause.toString(); } if (disconnectNeeded) { if (quickFixSession != null) { quickFixSession.disconnect(reason, true); } else { log.error(reason, cause); ioSession.close(); } } else { log.error(reason, cause); } }
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { if (in == null) { throw new ProtocolDecoderException("IoBuffer is null"); } // byte[] buff = new byte[in.limit()]; in.get(buff); out.write(buff); }
@Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { if (cause instanceof IOException) { // TODO Verify if there were packets pending to be sent and decide what to do with them Log.debug("ConnectionHandler: ",cause); } else if (cause instanceof ProtocolDecoderException) { Log.warn("Closing session due to exception: " + session, cause); session.close(); } else { Log.error(cause.getMessage(), cause); } }
/** * {@inheritDoc} * * @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 { super.exceptionCaught(session, cause); if (cause instanceof ProtocolDecoderException) { session.close(true); } }
@Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { if (cause instanceof ProtocolDecoderException) { log.warn("Malformed RTSP message."); Exceptions.logStackTrace(cause); session.write(RtspResponse.errorResponse(RtspCode.BadRequest)); return; } // close all: same as sessionClosed() log.info("Exception: " + cause); Exceptions.logStackTrace(cause); sessionClosed(session); }
/** * Decode a line using the default delimiter on the current system */ private void decodeAuto(Context ctx, IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws CharacterCodingException, ProtocolDecoderException { int matchCount = ctx.getMatchCount(); // Try to find a match int oldPos = in.position(); int oldLimit = in.limit(); while (in.hasRemaining()) { byte b = in.get(); boolean matched = false; switch (b) { case '\r': // Might be Mac, but we don't auto-detect Mac EOL // to avoid confusion. matchCount++; break; case '\n': // UNIX matchCount++; matched = true; break; default: matchCount = 0; } if (matched) { // Found a match. int pos = in.position(); in.limit(pos); in.position(oldPos); ctx.append(in); in.limit(oldLimit); in.position(pos); if (ctx.getOverflowPosition() == 0) { IoBuffer buf = ctx.getBuffer(); buf.flip(); buf.limit(buf.limit() - matchCount); try { byte[] data = new byte[buf.limit()]; buf.get(data); CharsetDecoder decoder = ctx.getDecoder(); CharBuffer buffer = decoder.decode(ByteBuffer.wrap(data)); String str = new String(buffer.array()); writeText(session, str, out); } finally { buf.clear(); } } else { int overflowPosition = ctx.getOverflowPosition(); ctx.reset(); throw new RecoverableProtocolDecoderException("Line is too long: " + overflowPosition); } oldPos = pos; matchCount = 0; } } // Put remainder to buf. in.position(oldPos); ctx.append(in); ctx.setMatchCount(matchCount); }
/** * Decode a line using the delimiter defined by the caller */ private void decodeNormal(Context ctx, IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws CharacterCodingException, ProtocolDecoderException { int matchCount = ctx.getMatchCount(); // Try to find a match int oldPos = in.position(); int oldLimit = in.limit(); while (in.hasRemaining()) { byte b = in.get(); if (delimBuf.get(matchCount) == b) { matchCount++; if (matchCount == delimBuf.limit()) { // Found a match. int pos = in.position(); in.limit(pos); in.position(oldPos); ctx.append(in); in.limit(oldLimit); in.position(pos); if (ctx.getOverflowPosition() == 0) { IoBuffer buf = ctx.getBuffer(); buf.flip(); buf.limit(buf.limit() - matchCount); try { writeText(session, buf.getString(ctx.getDecoder()), out); } finally { buf.clear(); } } else { int overflowPosition = ctx.getOverflowPosition(); ctx.reset(); throw new RecoverableProtocolDecoderException("Line is too long: " + overflowPosition); } oldPos = pos; matchCount = 0; } } else { // fix for DIRMINA-506 & DIRMINA-536 in.position(Math.max(0, in.position() - matchCount)); matchCount = 0; } } // Put remainder to buf. in.position(oldPos); ctx.append(in); ctx.setMatchCount(matchCount); }
/** * {@inheritDoc} */ public DecodingState finishDecode(ProtocolDecoderOutput out) throws Exception { throw new ProtocolDecoderException("Unexpected end of session while waiting for an integer."); }
/** * {@inheritDoc} */ public DecodingState finishDecode(ProtocolDecoderOutput out) throws Exception { throw new ProtocolDecoderException("Unexpected end of session while waiting for a single byte."); }
/** * {@inheritDoc} */ public DecodingState finishDecode(ProtocolDecoderOutput out) throws Exception { throw new ProtocolDecoderException("Unexpected end of session while waiting for a short integer."); }
@Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { if (cause instanceof ProtocolDecoderException) { session.close(true); } }
/** * Decode a line using the default delimiter on the current system */ private void decodeAuto(Context ctx, IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws CharacterCodingException, ProtocolDecoderException { int matchCount = ctx.getMatchCount(); // Try to find a match int oldPos = in.position(); int oldLimit = in.limit(); while (in.hasRemaining()) { byte b = in.get(); boolean matched = false; switch (b) { case '\r': // Might be Mac, but we don't auto-detect Mac EOL // to avoid confusion. matchCount++; break; case '\n': // UNIX matchCount++; matched = true; break; default: matchCount = 0; } if (matched) { // Found a match. int pos = in.position(); in.limit(pos); in.position(oldPos); ctx.append(in); in.limit(oldLimit); in.position(pos); if (ctx.getOverflowPosition() == 0) { IoBuffer buf = ctx.getBuffer(); buf.flip(); buf.limit(buf.limit() - matchCount); try { writeText(session, buf.getString(ctx.getDecoder()), out); } finally { buf.clear(); } } else { int overflowPosition = ctx.getOverflowPosition(); ctx.reset(); throw new RecoverableProtocolDecoderException("Line is too long: " + overflowPosition); } oldPos = pos; matchCount = 0; } } // Put remainder to buf. in.position(oldPos); ctx.append(in); ctx.setMatchCount(matchCount); }