List of usage examples for io.netty.buffer ByteBuf resetReaderIndex
public abstract ByteBuf resetReaderIndex();
From source file:org.lanternpowered.server.network.pipeline.LegacyProtocolHandler.java
License:MIT License
@Override public void channelRead(ChannelHandlerContext ctx, Object object) throws Exception { final LanternServer server = this.session.getServer(); ByteBuf buf = (ByteBuf) object; buf.markReaderIndex();/*from w w w . j a v a 2 s . c om*/ // Whether it was a valid legacy message boolean legacy = false; try { final int messageId = buf.readUnsignedByte(); // Old client's are not so smart, make sure that // they don't attempt to login if (messageId == 0x02) { int protocol = buf.readByte(); // Protocol version int value = buf.readShort(); // Check the length if (value < 0 || value > 16) { return; } buf.readBytes(value << 1); // Username value = buf.readShort(); // Check the length if (value < 0 || value > 255) { return; } buf.readBytes(value << 1); // Host address buf.readInt(); // Port if (buf.readableBytes() > 0) { return; } legacy = true; sendDisconnectMessage(ctx, LanternTexts.toPlain(t("multiplayer.disconnect.outdated_client", Lantern.getGame().getPlatform().getMinecraftVersion().getName()))); final MinecraftVersion clientVersion = Lantern.getGame().getMinecraftVersionCache() .getVersionOrUnknown(protocol, true); if (clientVersion == LanternMinecraftVersion.UNKNOWN_LEGACY) { Lantern.getLogger().debug( "Client with unknown legacy protocol version {} attempted to join the server.", protocol); } else { Lantern.getLogger().debug( "Client with legacy protocol version {} (mc-version {}) attempted to join the server.", protocol, clientVersion.getName()); } return; } // Check for the ping message id. if (messageId != 0xfe) { return; } int readable = buf.readableBytes(); boolean full = false; // The version used to ping the server int protocol = V1_3_2_PROTOCOL; // Versions 1.4 - 1.5.x + 1.6 - Can request full data. if (readable > 0) { // Is always 1 if (buf.readUnsignedByte() != 1) { return; } full = true; protocol = V1_5_2_PROTOCOL; } // The virtual address that was used to join the server InetSocketAddress virtualAddress = null; // Version 1.6 - Used extra data. if (readable > 1) { if (buf.readUnsignedByte() != 0xfa) { return; } byte[] bytes = new byte[buf.readShort() << 1]; buf.readBytes(bytes); if (!new String(bytes, StandardCharsets.UTF_16BE).equals("MC|PingHost")) { return; } // Not used buf.readShort(); // The protocol version is present protocol = buf.readUnsignedByte(); // There is extra host and port data if (protocol >= 73) { bytes = new byte[buf.readShort() << 1]; buf.readBytes(bytes); final String host = new String(bytes, StandardCharsets.UTF_16BE); final int port = buf.readInt(); virtualAddress = InetSocketAddress.createUnresolved(host, port); } readable = buf.readableBytes(); if (readable > 0) { Lantern.getLogger().warn("Trailing bytes on a legacy ping message: {}b", readable); } } final MinecraftVersion clientVersion = Lantern.getGame().getMinecraftVersionCache() .getVersionOrUnknown(protocol, true); if (clientVersion == LanternMinecraftVersion.UNKNOWN) { Lantern.getLogger().debug("Client with unknown legacy protocol version {} pinged the server.", protocol); } // The message was successfully decoded as a legacy one legacy = true; final MinecraftVersion serverVersion = Lantern.getGame().getPlatform().getMinecraftVersion(); Text description = server.getMotd(); final InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress(); final LanternStatusClient client = new LanternStatusClient(address, clientVersion, virtualAddress); final ClientPingServerEvent.Response.Players players = LanternStatusHelper.createPlayers(server); final LanternStatusResponse response = new LanternStatusResponse(serverVersion, server.getFavicon(), description, players); final ClientPingServerEvent event = SpongeEventFactory .createClientPingServerEvent(Cause.source(client).build(), client, response); Sponge.getEventManager().post(event); // Cancelled, we are done here if (event.isCancelled()) { ctx.channel().close(); return; } description = response.getDescription(); int online = players.getOnline(); final int max = players.getMax(); // The players should be hidden, this will replace the player count // with ??? if (!response.getPlayers().isPresent()) { online = -1; } final String data; if (full) { final String description0 = getFirstLine( TextSerializers.LEGACY_FORMATTING_CODE.serialize(description)); // 1. This value is always 1. // 2. The protocol version, just use a value out of range // of the available ones. // 3. The version/name string of the server. // 4. The motd of the server. In legacy format. // 5. The online players // 6. The maximum amount of players data = String.format("\u00A7%s\u0000%s\u0000%s\u0000%s\u0000%s\u0000%s", 1, 127, response.getVersion().getName(), description0, online, max); } else { final String description0 = getFirstLine(TextSerializers.PLAIN.serialize(description)); // 1. The motd of the server. In legacy format. // 2. The online players // 3. The maximum amount of players data = String.format("%s\u00A7%s\u00A7%s", description0, online, max); } sendDisconnectMessage(ctx, data); } catch (Exception ignore) { } finally { if (legacy) { buf.release(); } else { buf.resetReaderIndex(); ctx.channel().pipeline().remove(this); ctx.fireChannelRead(buf); } } }
From source file:org.lanternpowered.server.network.rcon.RconFramingHandler.java
License:MIT License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 4) { return;/*from w w w. j a v a 2s . co m*/ } in.markReaderIndex(); int length = in.readIntLE(); if (in.readableBytes() < length) { in.resetReaderIndex(); return; } final ByteBuf buf = ctx.alloc().buffer(length); in.readBytes(buf, length); out.add(buf); }
From source file:org.lightmare.remote.rcp.decoders.RcpDecoder.java
License:Open Source License
/** * Decodes if data is enough in buffer/*from www . j a v a 2s . com*/ * * @param buffer * @param out * @throws IOException */ private void decode(ByteBuf buffer, List<Object> out) throws IOException { boolean valid = buffer.readByte() > CollectionUtils.EMPTY_ARRAY_LENGTH; int dataSize = buffer.readInt(); if (buffer.readableBytes() < dataSize) { buffer.resetReaderIndex(); } else { byte[] data = new byte[dataSize]; Object value = NativeSerializer.deserialize(data); RcpWrapper rcp = new RcpWrapper(); rcp.setValid(valid); rcp.setValue(value); out.add(rcp); } }
From source file:org.lightmare.remote.rcp.decoders.RcpDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> out) throws IOException { int validSize = RpcUtils.INT_SIZE + RpcUtils.BYTE_SIZE; if (buffer.readableBytes() < validSize) { buffer.resetReaderIndex(); } else {/*from w w w . j av a2 s . c om*/ decode(buffer, out); } }
From source file:org.lightmare.remote.rpc.decoders.RpcDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> out) throws IOException { if (buffer.readableBytes() < RpcUtils.PROTOCOL_SIZE) { buffer.resetReaderIndex(); return;/*w w w . j a va 2 s . c o m*/ } int beanNameSize = buffer.readInt(); int methodSize = buffer.readInt(); int paramTypesSize = buffer.readInt(); int classSize = buffer.readInt(); int paramArraySize = buffer.readInt(); int paramsSize = beanNameSize + methodSize + classSize + paramArraySize; if (buffer.readableBytes() < paramsSize) { buffer.resetReaderIndex(); return; } byte[] beanNameBt = new byte[beanNameSize]; buffer.readBytes(beanNameBt); byte[] methodBt = new byte[methodSize]; buffer.readBytes(methodBt); byte[] paramTypesBt = new byte[paramTypesSize]; buffer.readBytes(paramTypesBt); byte[] classBt = new byte[classSize]; buffer.readBytes(classBt); byte[] paramBt = new byte[paramArraySize]; buffer.readBytes(paramBt); RpcWrapper wrapper = new RpcWrapper(); String beanName = new String(beanNameBt); String methodName = (String) NativeSerializer.deserialize(methodBt); Class<?>[] paramTypes = (Class<?>[]) NativeSerializer.deserialize(paramTypesBt); Class<?> interfaceClass = (Class<?>) NativeSerializer.deserialize(classBt); Object[] params = (Object[]) NativeSerializer.deserialize(paramBt); wrapper.setBeanName(beanName); wrapper.setMethodName(methodName); wrapper.setParamTypes(paramTypes); wrapper.setInterfaceClass(interfaceClass); wrapper.setParams(params); out.add(wrapper); }
From source file:org.mobicents.protocols.ss7.m3ua.impl.message.MessageFactoryImpl.java
License:Open Source License
public M3UAMessageImpl createMessage(ByteBuf message) { int dataLen;//w ww .j a v a 2 s . c om if (message.readableBytes() < 8) { return null; } // obtain message class and type from header message.markReaderIndex(); message.skipBytes(2); int messageClass = message.readUnsignedByte(); int messageType = message.readUnsignedByte(); // obtain remaining length of the message and prepare buffer dataLen = message.readInt() - 8; if (message.readableBytes() < dataLen) { message.resetReaderIndex(); return null; } // construct new message instance M3UAMessageImpl messageTemp = this.createMessage(messageClass, messageType); // parsing params of this message message.markWriterIndex(); message.writerIndex(message.readerIndex() + dataLen); messageTemp.decode(message); message.resetWriterIndex(); return messageTemp; }
From source file:org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerWriter.java
License:Open Source License
private void writeWithPendingDetection(final ChannelHandlerContext ctx, final ChannelPromise promise, final ByteBuf byteBufMsg, boolean wasPending) { try {/*w ww .j av a 2 s . c om*/ if (LOG.isTraceEnabled()) { LOG.trace("Writing request on channel: {}, message: {}", ctx.channel(), byteBufToString(byteBufMsg)); } asyncIn.write(toBuffer(byteBufMsg)).addListener(new SshFutureListener<IoWriteFuture>() { @Override public void operationComplete(final IoWriteFuture future) { if (LOG.isTraceEnabled()) { LOG.trace( "Ssh write request finished on channel: {} with result: {}: and ex:{}, message: {}", ctx.channel(), future.isWritten(), future.getException(), byteBufToString(byteBufMsg)); } // Notify success or failure if (future.isWritten()) { promise.setSuccess(); } else { LOG.warn("Ssh write request failed on channel: {} for message: {}", ctx.channel(), byteBufToString(byteBufMsg), future.getException()); promise.setFailure(future.getException()); } // Not needed anymore, release byteBufMsg.release(); // Check pending queue and schedule next // At this time we are guaranteed that we are not in pending state anymore so the next request should succeed writePendingIfAny(); } }); //rescheduling message from queue after successfully sent if (wasPending) { byteBufMsg.resetReaderIndex(); pending.remove(); } } catch (final WritePendingException e) { if (wasPending == false) { queueRequest(ctx, byteBufMsg, promise); } } }
From source file:org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerWriter.java
License:Open Source License
public static String byteBufToString(final ByteBuf msg) { final String s = msg.toString(Charsets.UTF_8); msg.resetReaderIndex(); return s;//from w ww. j ava 2 s . c o m }
From source file:org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerWriter.java
License:Open Source License
private Buffer toBuffer(final ByteBuf msg) { // TODO Buffer vs ByteBuf translate, Can we handle that better ? msg.resetReaderIndex(); final byte[] temp = new byte[msg.readableBytes()]; msg.readBytes(temp, 0, msg.readableBytes()); return new Buffer(temp); }
From source file:org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerWriter.java
License:Open Source License
private void writeWithPendingDetection(final ChannelHandlerContext ctx, final ChannelPromise promise, final ByteBuf byteBufMsg, final boolean wasPending) { try {//from w ww.j a v a 2 s. c o m if (LOG.isTraceEnabled()) { LOG.trace("Writing request on channel: {}, message: {}", ctx.channel(), byteBufToString(byteBufMsg)); } asyncIn.write(toBuffer(byteBufMsg)).addListener(new SshFutureListener<IoWriteFuture>() { @Override public void operationComplete(final IoWriteFuture future) { // synchronized block due to deadlock that happens on ssh window resize // writes and pending writes would lock the underlyinch channel session // window resize write would try to write the message on an already locked channelSession, // while the pending write was in progress from the write callback synchronized (asyncIn) { if (LOG.isTraceEnabled()) { LOG.trace( "Ssh write request finished on channel: {} with result: {}: and ex:{}, message: {}", ctx.channel(), future.isWritten(), future.getException(), byteBufToString(byteBufMsg)); } // Notify success or failure if (future.isWritten()) { promise.setSuccess(); } else { LOG.warn("Ssh write request failed on channel: {} for message: {}", ctx.channel(), byteBufToString(byteBufMsg), future.getException()); promise.setFailure(future.getException()); } // Not needed anymore, release byteBufMsg.release(); //rescheduling message from queue after successfully sent if (wasPending) { byteBufMsg.resetReaderIndex(); pending.remove(); } } // Check pending queue and schedule next // At this time we are guaranteed that we are not in pending state anymore so the next request should succeed writePendingIfAny(); } }); } catch (final WritePendingException e) { if (wasPending == false) { queueRequest(ctx, byteBufMsg, promise); } } }