@Override protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { log.debug("Sending message"); if (!(msg instanceof List)) { log.debug("Invalid msg."); return msg; } @SuppressWarnings("unchecked") List<PcepMessage> msglist = (List<PcepMessage>) msg; ChannelBuffer buf = ChannelBuffers.dynamicBuffer(); for (PcepMessage pm : msglist) { pm.writeTo(buf); } HexDump.pcepHexDump(buf); return buf; }
@Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent evt) { log.debug("OspfChannelHandler::channelDisconnected...!!!"); for (Integer interfaceIndex : ospfInterfaceMap.keySet()) { OspfInterface anInterface = ospfInterfaceMap.get(interfaceIndex); if (anInterface != null) { anInterface.interfaceDown(); anInterface.stopDelayedAckTimer(); } } if (controller != null) { controller.connectPeer(); } }
@Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (LOG.isTraceEnabled()) { LOG.trace("Channel connected " + e); } NettyServerCnxn cnxn = new NettyServerCnxn(ctx.getChannel(), zkServer, NettyServerCnxnFactory.this); ctx.setAttachment(cnxn); if (secure) { SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class); ChannelFuture handshakeFuture = sslHandler.handshake(); handshakeFuture.addListener(new CertificateVerifier(sslHandler, cnxn)); } else { allChannels.add(ctx.getChannel()); addCnxn(cnxn); } }
@Override protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { if (msg instanceof Command) { Command command = (Command) msg; Object encodedCommand = encodeCommand(command); // Log command StringBuilder s = new StringBuilder(); s.append(String.format("[%08X] ", channel.getId())); s.append("id: ").append(getUniqueId(command.getDeviceId())).append(", "); s.append("command type: ").append(command.getType()).append(" "); if (encodedCommand != null) { s.append("sent"); } else { s.append("not sent"); } Log.info(s.toString()); return encodedCommand; } return msg; }
@Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { ChannelBuffer result = (ChannelBuffer) super.decode(ctx, channel, buf); if (result != null) { int index = result.indexOf(result.readerIndex(), result.writerIndex(), (byte) '$'); if (index == -1) { return result; } else { result.skipBytes(index); return result.readBytes(result.readableBytes()); } } return null; }
@Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { if (buf.readableBytes() < 80) { return null; } int spaceIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ' '); if (spaceIndex == -1) { return null; } int endIndex = buf.indexOf(spaceIndex, buf.writerIndex(), (byte) ','); if (endIndex == -1) { return null; } return buf.readBytes(endIndex + 1); }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (e.getMessage() instanceof ChannelBuffer) { ChannelBuffer buffer = (ChannelBuffer) e.getMessage(); int bytesToRead = Math.min(currentChunkSize - bytesRead, buffer.readableBytes()); buffer.readBytes(getMailEnvelope().getMessageOutputStream(), bytesToRead); bytesRead += bytesToRead; if (bytesRead == currentChunkSize) { stopCapturingData(); } return; } super.messageReceived(ctx, e); }
@Override protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { log.debug("BGPMessageEncoder::encode"); if (!(msg instanceof List)) { log.debug("Invalid msg."); return msg; } @SuppressWarnings("unchecked") List<BgpMessage> msglist = (List<BgpMessage>) msg; ChannelBuffer buf = ChannelBuffers.dynamicBuffer(); log.debug("SENDING MESSAGE"); for (BgpMessage pm : msglist) { pm.writeTo(buf); } HexDump.dump(buf); return buf; }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object message = e.getMessage(); if (message instanceof SyncMessage) { handleSyncMessage((SyncMessage)message, ctx.getChannel()); } else if (message instanceof List) { for (Object i : (List<?>)message) { if (i instanceof SyncMessage) { try { handleSyncMessage((SyncMessage)i, ctx.getChannel()); } catch (Exception ex) { Channels.fireExceptionCaught(ctx, ex); } } } } else { handleUnknownMessage(ctx, message); } }
@Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { if (buf.readableBytes() < BINARY_HEADER) { return null; } if (buf.getUnsignedByte(buf.readerIndex()) == 0xbf) { buf.skipBytes(BINARY_HEADER); } int index = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '\r'); if (index != -1 && index + 1 < buf.writerIndex()) { ChannelBuffer result = buf.readBytes(index - buf.readerIndex()); buf.skipBytes(2); return result; } return null; }
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { // Check minimum length if (buf.readableBytes() < MESSAGE_MINIMUM_LENGTH) { return null; } // Check for sync packet if (buf.getUnsignedShort(buf.readerIndex()) == 0xFAF8) { ChannelBuffer syncMessage = buf.readBytes(8); if (channel != null) { channel.write(syncMessage); } } return super.decode(ctx, channel, buf); }
@Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { if (buf.readableBytes() >= MESSAGE_HEADER) { int length = Integer.parseInt(buf.toString(2, 2, StandardCharsets.US_ASCII)) + 5; if (buf.readableBytes() >= length) { ChannelBuffer frame = buf.readBytes(length); while (buf.readable() && buf.getUnsignedByte(buf.readerIndex()) != '$') { buf.readByte(); } return frame; } } return null; }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (e.getMessage() instanceof List) { @SuppressWarnings("unchecked") List<OFMessage> msglist = (List<OFMessage>) e.getMessage(); for (OFMessage ofm : msglist) { // Do the actual packet processing state.processOFMessage(this, ofm); } } else { state.processOFMessage(this, (OFMessage) e.getMessage()); } }
/** * Parses BGP UPDATE Attribute Type ATOMIC_AGGREGATE. * * @param bgpSession the BGP Session to use * @param ctx the Channel Handler Context * @param attrTypeCode the attribute type code * @param attrLen the attribute length (in octets) * @param attrFlags the attribute flags * @param message the message to parse * @throws BgpMessage.BgpParseException */ private static void parseAttributeTypeAtomicAggregate( BgpSession bgpSession, ChannelHandlerContext ctx, int attrTypeCode, int attrLen, int attrFlags, ChannelBuffer message) throws BgpMessage.BgpParseException { // Check the Attribute Length if (attrLen != BgpConstants.Update.AtomicAggregate.LENGTH) { // ERROR: Attribute Length Error actionsBgpUpdateAttributeLengthError( bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message); String errorMsg = "Attribute Length Error"; throw new BgpMessage.BgpParseException(errorMsg); } // Nothing to do: this attribute is primarily informational }
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { if (!channel.isConnected()) { // In testing, I see decode being called AFTER decode last. // This check avoids that from reading corrupted frames return null; } List<OFMessage> messageList = new ArrayList<OFMessage>(); for (;;) { OFMessage message = reader.readFrom(buffer); if (message == null) break; messageList.add(message); } return messageList.isEmpty() ? null : messageList; }
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { if (buf.readableBytes() < MESSAGE_MINIMUM_LENGTH) { return null; } if (buf.getUnsignedShort(buf.readerIndex()) == 0xFAF8) { ChannelBuffer heartbeat = buf.readBytes(12); if (channel != null) { channel.write(heartbeat); } } return super.decode(ctx, channel, buf); }
@Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { if (buf.readableBytes() < 20) { return null; } // Swap byte order for legacy protocol if (buf.getUnsignedByte(buf.readerIndex()) == 0x80) { int length = buf.readableBytes(); byte[] bytes = new byte[length]; buf.getBytes(buf.readerIndex(), bytes); ChannelBuffer result = (ChannelBuffer) super.decode( ctx, channel, ChannelBuffers.wrappedBuffer(ByteOrder.LITTLE_ENDIAN, bytes)); if (result != null) { buf.skipBytes(result.readableBytes()); } return result; } return super.decode(ctx, channel, buf); }
@Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { // Check minimum length if (buf.readableBytes() < MESSAGE_MINIMUM_LENGTH) { return null; } // Read packet int length = buf.getUnsignedShort(buf.readerIndex() + 1) & 0x7fff; if (buf.readableBytes() >= (length + MESSAGE_MINIMUM_LENGTH)) { return buf.readBytes(length + MESSAGE_MINIMUM_LENGTH); } return null; }
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { List<SyncMessage> ms = null; ChannelBuffer frame = null; while (null != (frame = (ChannelBuffer) super.decode(ctx, channel, buffer))) { if (ms == null) ms = new ArrayList<SyncMessage>(); ChannelBufferInputStream is = new ChannelBufferInputStream(frame); TCompactProtocol thriftProtocol = new TCompactProtocol(new TIOStreamTransport(is)); SyncMessage bsm = new SyncMessage(); bsm.read(thriftProtocol); ms.add(bsm); } return ms; }
@Override public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception { if (!isHandshakeComplete()) { return; } if (e.getState() == IdleState.READER_IDLE) { // When no message is received on channel for read timeout, then close // the channel log.info("Disconnecting client {} due to read timeout", getClientInfoString()); ctx.getChannel().close(); } else if (e.getState() == IdleState.WRITER_IDLE) { // Send keep alive message log.debug("Sending keep alive message due to IdleState timeout " + pc.toString()); pc.sendMessage(Collections.singletonList(pc.factory().buildKeepaliveMsg().build())); } }
@Override public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { RpcResponse response = (RpcResponse) e.getMessage(); ByteArrayOutputStream baos = new ByteArrayOutputStream(16384); //先写入标示的魔数 baos.write(Constants.MAGIC_BYTES); MySerializerFactory.getInstance(Constants.DEFAULT_RPC_CODE_MODE).encodeResponse(baos, response); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(baos.toByteArray()); Channels.write(ctx, e.getFuture(), buffer); }
/** * Tests channelConnected() method. */ @Test(expected = Exception.class) public void testChannelConnected() throws Exception { channelHandlerContext = EasyMock.createMock(ChannelHandlerContext.class); channelStateEvent = EasyMock.createMock(ChannelStateEvent.class); ospfInterfaceChannelHandler.channelConnected(channelHandlerContext, channelStateEvent); }
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { if (buffer.readableBytes() < 2) { return null; } byte byte1 = buffer.readByte(); byte byte2 = buffer.readByte(); if (byte1!=Constants.MAGIC_HIGH || byte2!=Constants.MAGIC_LOW) { throw new RuntimeException("magic number not right"); } ChannelBufferInputStream in = new ChannelBufferInputStream(buffer); RpcRequest request = MySerializerFactory.getInstance(Constants.DEFAULT_RPC_CODE_MODE).decodeRequest(in); return request; }
@Override public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e) throws Exception { if (LOG.isTraceEnabled()) { LOG.trace("write complete " + e); } }
@Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { if (channel != null) { channels.put(NetUtils.toAddressString((InetSocketAddress) ctx.getChannel().getRemoteAddress()), channel); } handler.connected(channel); } finally { NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { handler.received(channel, e.getMessage()); } finally { NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } }
@Override public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { super.writeRequested(ctx, e); NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { handler.sent(channel, e.getMessage()); } finally { NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } }
@Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { handler.caught(channel, e.getCause()); } finally { NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } }
@Override protected Object encode(ChannelHandlerContext ctx, Channel ch, Object msg) throws Exception { com.alibaba.dubbo.remoting.buffer.ChannelBuffer buffer = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(1024); NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler); try { codec.encode(channel, buffer, msg); } finally { NettyChannel.removeChannelIfDisconnected(ch); } return ChannelBuffers.wrappedBuffer(buffer.toByteBuffer()); }
@Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (LOG.isTraceEnabled()) { LOG.trace("Channel closed " + e); } allChannels.remove(ctx.getChannel()); }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { ChannelBuffer buf = (ChannelBuffer) e.getMessage(); // Read reply if (!validMessageLength(buf.readableBytes())) { e.getChannel().close(); return; } // handling fragment header for TCP, 4 bytes. byte[] fragmentHeader = Arrays.copyOfRange(buf.array(), 0, 4); int fragmentSize = XDR.fragmentSize(fragmentHeader); boolean isLast = XDR.isLastFragment(fragmentHeader); assert (fragmentSize == 28 && isLast == true); XDR xdr = new XDR(); xdr.writeFixedOpaque(Arrays.copyOfRange(buf.array(), 4, buf.readableBytes())); RpcReply reply = RpcReply.read(xdr); if (reply.getState() == RpcReply.ReplyState.MSG_ACCEPTED) { RpcAcceptedReply acceptedReply = (RpcAcceptedReply) reply; handle(acceptedReply, xdr); } else { RpcDeniedReply deniedReply = (RpcDeniedReply) reply; handle(deniedReply); } e.getChannel().close(); // shutdown now that request is complete }
/** * Processes BGP NOTIFICATION message. * * @param bgpSession the BGP Session to use * @param ctx the Channel Handler Context * @param message the message to process */ static void processBgpNotification(BgpSession bgpSession, ChannelHandlerContext ctx, ChannelBuffer message) { int minLength = BgpConstants.BGP_NOTIFICATION_MIN_LENGTH - BgpConstants.BGP_HEADER_LENGTH; if (message.readableBytes() < minLength) { log.debug("BGP RX NOTIFICATION Error from {}: " + "Message length {} too short. Must be at least {}", bgpSession.remoteInfo().address(), message.readableBytes(), minLength); // // ERROR: Bad Message Length // // NOTE: We do NOT send NOTIFICATION in response to a notification return; } // // Parse the NOTIFICATION message // int errorCode = message.readUnsignedByte(); int errorSubcode = message.readUnsignedByte(); int dataLength = message.readableBytes(); log.debug("BGP RX NOTIFICATION message from {}: Error Code {} " + "Error Subcode {} Data Length {}", bgpSession.remoteInfo().address(), errorCode, errorSubcode, dataLength); // // NOTE: If the peer sent a NOTIFICATION, we leave it to the peer to // close the connection. // // Start the Session Timeout timer bgpSession.restartSessionTimeoutTimer(ctx); }
/** * Process the ls acknowledge message. * * @param ospfMessage OSPF message instance. * @param ctx channel handler context instance. * @throws Exception might throws exception */ void processLsAckMessage(OspfMessage ospfMessage, ChannelHandlerContext ctx) throws Exception { log.debug("OspfChannelHandler::processLsAckMessage"); LsAcknowledge lsAckPacket = (LsAcknowledge) ospfMessage; //check it is present in listOfNeighbors OspfNbrImpl nbr = (OspfNbrImpl) neighbouringRouter(lsAckPacket.routerId().toString()); if (nbr != null) { if (nbr.getState().getValue() < OspfNeighborState.EXCHANGE.getValue()) { // discard the packet. return; } else { // process ls acknowledgements Iterator itr = lsAckPacket.getLinkStateHeaders().iterator(); while (itr.hasNext()) { LsaHeader lsRequest = (LsaHeader) itr.next(); OspfLsa ospfLsa = (OspfLsa) nbr.getPendingReTxList().get(((OspfAreaImpl) ospfArea).getLsaKey(lsRequest)); if (lsRequest != null && ospfLsa != null) { String isSame = ((OspfLsdbImpl) ospfArea.database()).isNewerOrSameLsa( lsRequest, (LsaHeader) ospfLsa); if (isSame.equals("same")) { nbr.getPendingReTxList().remove(((OspfAreaImpl) ospfArea).getLsaKey(lsRequest)); } } } } } }
@Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { channels.remove(NetUtils.toAddressString((InetSocketAddress) ctx.getChannel().getRemoteAddress())); handler.disconnected(channel); } finally { NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } }
/** * Processes BGP notification message. * * @param ctx Channel handler context * @param message notification message */ private void processBgpNotification(ChannelHandlerContext ctx, ChannelBuffer message) { byte[] data; message.readByte(); //read error code message.readByte(); // read error sub code if (message.readableBytes() > 0) { data = new byte[message.readableBytes()]; message.readBytes(data, 0, message.readableBytes()); } // Notification message received receivedNotificationMessageLatch.countDown(); }
@Override public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { /* Create a newly ChannelBuffer */ ChannelBuffer frmBuf = ChannelBuffers.dynamicBuffer(); /* Get a IMessage Object */ IMessage sMsg = (IMessage) e.getMessage(); /* Transfer the object to a byte array */ byte[] frameContent = null; if((sMsg instanceof CPhotoUpdateMsg)) { frmBuf.writeInt(1); frmBuf.writeInt(((CPhotoUpdateMsg)sMsg).getPhoto().length); frmBuf.writeInt(((CPhotoUpdateMsg)sMsg).getUserId()); frmBuf.writeBytes(((CPhotoUpdateMsg)sMsg).getPhoto(), 0, ((CPhotoUpdateMsg)sMsg).getPhoto().length); } else { frameContent = sMsg.toString().getBytes(Config.PACKAGE_ENCODE); frmBuf.writeInt(0); /* Write the content length to the buffer */ frmBuf.writeInt(frameContent.length); /* Write the content to the buffer */ frmBuf.writeBytes(frameContent, 0, frameContent.length); } Channels.write(ctx, e.getFuture(), frmBuf); }