List of usage examples for io.netty.buffer ByteBuf readerIndex
public abstract int readerIndex();
From source file:io.vertx.core.buffer.BufferTest.java
License:Open Source License
@Test public void testAppendDoesNotModifyByteBufIndex() throws Exception { ByteBuf buf = Unpooled.copiedBuffer("foobar".getBytes()); assertEquals(0, buf.readerIndex()); assertEquals(6, buf.writerIndex());//from ww w . j a v a2s. c o m Buffer buffer = Buffer.buffer(buf); Buffer other = Buffer.buffer("prefix"); other.appendBuffer(buffer); assertEquals(0, buf.readerIndex()); assertEquals(6, buf.writerIndex()); assertEquals(other.toString(), "prefixfoobar"); }
From source file:io.vertx.core.dns.impl.decoder.RecordDecoder.java
License:Open Source License
static Function<DnsRecord, String> address(int octets) { return record -> { ByteBuf data = ((DnsRawRecord) record).content(); int size = data.writerIndex() - data.readerIndex(); if (size != octets) { throw new DecoderException("Invalid content length, or reader index when decoding address [index: " + data.readerIndex() + ", expected length: " + octets + ", actual: " + size + "]."); }/*from ww w .j a v a 2 s. c o m*/ byte[] address = new byte[octets]; data.getBytes(data.readerIndex(), address); try { return InetAddress.getByAddress(address).getHostAddress(); } catch (UnknownHostException e) { throw new DecoderException("Could not convert address " + data.toString(data.readerIndex(), size, CharsetUtil.UTF_8) + " to InetAddress."); } }; }
From source file:io.vertx.core.dns.impl.decoder.RecordDecoder.java
License:Open Source License
/** * Retrieves a domain name given a buffer containing a DNS packet. If the * name contains a pointer, the position of the buffer will be set to * directly after the pointer's index after the name has been read. * * @param buf the byte buffer containing the DNS packet * @return the domain name for an entry//from w w w . ja va 2s .c o m */ static String readName(ByteBuf buf) { int position = -1; StringBuilder name = new StringBuilder(); for (int len = buf.readUnsignedByte(); buf.isReadable() && len != 0; len = buf.readUnsignedByte()) { boolean pointer = (len & 0xc0) == 0xc0; if (pointer) { if (position == -1) { position = buf.readerIndex() + 1; } buf.readerIndex((len & 0x3f) << 8 | buf.readUnsignedByte()); } else { name.append(buf.toString(buf.readerIndex(), len, CharsetUtil.UTF_8)).append("."); buf.skipBytes(len); } } if (position != -1) { buf.readerIndex(position); } if (name.length() == 0) { return null; } return name.substring(0, name.length() - 1); }
From source file:io.vertx.core.dns.impl.fix.DnsNameResolverContext.java
License:Apache License
private void onResponseAorAAAA(DnsRecordType qType, DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> envelope) { // We often get a bunch of CNAMES as well when we asked for A/AAAA. final DnsResponse response = envelope.content(); final Map<String, String> cnames = buildAliasMap(response); final int answerCount = response.count(DnsSection.ANSWER); boolean found = false; for (int i = 0; i < answerCount; i++) { final DnsRecord r = response.recordAt(DnsSection.ANSWER, i); final DnsRecordType type = r.type(); if (type != DnsRecordType.A && type != DnsRecordType.AAAA) { continue; }/*from w w w. j a v a2s .co m*/ final String qName = question.name().toLowerCase(Locale.US); final String rName = r.name().toLowerCase(Locale.US); // Make sure the record is for the questioned domain. if (!rName.equals(qName)) { // Even if the record's name is not exactly same, it might be an alias defined in the CNAME records. String resolved = qName; do { resolved = cnames.get(resolved); if (rName.equals(resolved)) { break; } } while (resolved != null); if (resolved == null) { continue; } } if (!(r instanceof DnsRawRecord)) { continue; } final ByteBuf content = ((ByteBufHolder) r).content(); final int contentLen = content.readableBytes(); if (contentLen != INADDRSZ4 && contentLen != INADDRSZ6) { continue; } final byte[] addrBytes = new byte[contentLen]; content.getBytes(content.readerIndex(), addrBytes); final InetAddress resolved; try { resolved = InetAddress.getByAddress(hostname, addrBytes); } catch (UnknownHostException e) { // Should never reach here. throw new Error(e); } if (resolvedEntries == null) { resolvedEntries = new ArrayList<DnsCacheEntry>(8); } final DnsCacheEntry e = new DnsCacheEntry(hostname, resolved); resolveCache.cache(hostname, resolved, r.timeToLive(), parent.ch.eventLoop()); resolvedEntries.add(e); found = true; // Note that we do not break from the loop here, so we decode/cache all A/AAAA records. } if (found) { return; } if (traceEnabled) { addTrace(envelope.sender(), "no matching " + qType + " record found"); } // We aked for A/AAAA but we got only CNAME. if (!cnames.isEmpty()) { onResponseCNAME(question, envelope, cnames, false); } }
From source file:io.vertx.core.dns.impl.fix.DnsNameResolverContext.java
License:Apache License
/** * Retrieves a domain name given a buffer containing a DNS packet. If the * name contains a pointer, the position of the buffer will be set to * directly after the pointer's index after the name has been read. * * @param in the byte buffer containing the DNS packet * @return the domain name for an entry/* w w w . j a va 2 s. c o m*/ */ public static String decodeName(ByteBuf in) { int position = -1; int checked = 0; final int end = in.writerIndex(); final int readable = in.readableBytes(); // Looking at the spec we should always have at least enough readable bytes to read a byte here but it seems // some servers do not respect this for empty names. So just workaround this and return an empty name in this // case. // // See: // - https://github.com/netty/netty/issues/5014 // - https://www.ietf.org/rfc/rfc1035.txt , Section 3.1 if (readable == 0) { return "."; } final StringBuilder name = new StringBuilder(readable << 1); while (in.isReadable()) { final int len = in.readUnsignedByte(); final boolean pointer = (len & 0xc0) == 0xc0; if (pointer) { if (position == -1) { position = in.readerIndex() + 1; } if (!in.isReadable()) { throw new CorruptedFrameException("truncated pointer in a name"); } final int next = (len & 0x3f) << 8 | in.readUnsignedByte(); if (next >= end) { throw new CorruptedFrameException("name has an out-of-range pointer"); } in.readerIndex(next); // check for loops checked += 2; if (checked >= end) { throw new CorruptedFrameException("name contains a loop."); } } else if (len != 0) { if (!in.isReadable(len)) { throw new CorruptedFrameException("truncated label in a name"); } name.append(in.toString(in.readerIndex(), len, CharsetUtil.UTF_8)).append('.'); in.skipBytes(len); } else { // len == 0 break; } } if (position != -1) { in.readerIndex(position); } if (name.length() == 0) { return "."; } if (name.charAt(name.length() - 1) != '.') { name.append('.'); } return name.toString(); }
From source file:io.vertx.core.http.impl.Http1xOrH2CHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; int len = Math.min(buf.readableBytes(), HTTP_2_PREFACE_ARRAY.length - current); int i = 0;/*w ww . ja v a2 s . c o m*/ while (i < len) { if (buf.getByte(buf.readerIndex() + i) != HTTP_2_PREFACE_ARRAY[current + i]) { end(ctx, buf, false); return; } i++; } if (current + i == HTTP_2_PREFACE_ARRAY.length) { end(ctx, buf, true); } else { current += len; buf.release(); } }
From source file:io.viewserver.network.netty.IncomingMessageHandler.java
License:Apache License
@Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> objects) throws Exception { final byte[] array; final int offset; final int length = byteBuf.readableBytes(); // try { if (byteBuf.hasArray()) { array = byteBuf.array();/*ww w .ja v a2s. co m*/ offset = byteBuf.arrayOffset() + byteBuf.readerIndex(); networkMessageWheel.pushToWheel(new NettyChannel(channelHandlerContext.channel()), array, offset, length); } else { // array = new byte[length]; // byteBuf.getBytes(byteBuf.readerIndex(), array, 0, length); // offset = 0; networkMessageWheel.pushToWheel(new NettyChannel(channelHandlerContext.channel()), new ByteBufInputStream(byteBuf)); } // } finally { // byteBuf.release(); // } }
From source file:jazmin.server.msg.codec.json.JSONDecoder.java
License:Open Source License
/** * Create a frame out of the {@link ByteBuf} and return it. * * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to * @param buffer the {@link ByteBuf} from which to read data * @return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could * be created.//from w w w . ja v a2 s . c o m */ protected ByteBuf decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { final int eol = findEndOfLine(buffer); if (!discarding) { if (eol >= 0) { final ByteBuf frame; final int length = eol - buffer.readerIndex(); final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1; if (length > maxLength) { buffer.readerIndex(eol + delimLength); fail(ctx, length); return null; } if (stripDelimiter) { frame = buffer.readBytes(length); buffer.skipBytes(delimLength); } else { frame = buffer.readBytes(length + delimLength); } return frame; } else { final int length = buffer.readableBytes(); if (length > maxLength) { discardedBytes = length; buffer.readerIndex(buffer.writerIndex()); discarding = true; if (failFast) { fail(ctx, "over " + discardedBytes); } } return null; } } else { if (eol >= 0) { final int length = discardedBytes + eol - buffer.readerIndex(); final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1; buffer.readerIndex(eol + delimLength); discardedBytes = 0; discarding = false; if (!failFast) { fail(ctx, length); } } else { discardedBytes = buffer.readableBytes(); buffer.readerIndex(buffer.writerIndex()); } return null; } }
From source file:jazmin.server.msg.codec.json.JSONDecoder.java
License:Open Source License
/** * Returns the index in the buffer of the end of line found. * Returns -1 if no end of line was found in the buffer. *///from w ww. j av a 2 s.co m private static int findEndOfLine(final ByteBuf buffer) { final int n = buffer.writerIndex(); for (int i = buffer.readerIndex(); i < n; i++) { final byte b = buffer.getByte(i); if (b == '\n') { return i; } else if (b == '\r' && i < n - 1 && buffer.getByte(i + 1) == '\n') { return i; // \r\n } } return -1; // Not found. }
From source file:jss.proto.ResultsetPacketTest.java
/** * ??/*from www . j a va 2 s. c o m*/ */ @Test @Ignore public void testResultset() { ByteBuf buf = fromDumpBytes(BASIC_DUMP); System.out.println(); int flags = CapabilityFlags.CLIENT_BASIC_FLAGS; PacketData data = new PacketData(); readPacket(buf, data, flags); ByteBuf payload = data.payload; Dumper.hexDumpOut(payload); long fieldCount = int_lenenc(payload); readPacket(buf, data, flags); payload = data.payload; Dumper.hexDumpOut(payload); List<ColumnDefinition41> columns = Lists.newArrayList(); for (long i = 0; i < fieldCount; i++) { ColumnDefinition41 packet = readPacket(payload, new ColumnDefinition41(), 0); System.out.println(packet); // System.out.println("\n" + Dumper.hexDumpReadable(payload)); // System.out.println("\n" + Dumper.hexDumpReadable(buf)); readPacket(buf, data, 0); payload = data.payload; columns.add(packet); } readPacket(buf, data, flags); payload = data.payload; System.out.println(readPacket(payload, new EOF_Packet(), flags)); readPacket(buf, data, flags); payload = data.payload; // System.out.println("\n" + Dumper.hexDumpReadable(buf)); while (true) { readPacket(buf, data, flags); payload = data.payload; if (payload.getUnsignedByte(payload.readerIndex()) == 0xfe) { break; } System.out.printf("| "); for (long i = 0; i < fieldCount; i++) { System.out.printf(string_lenenc(payload).toString(UTF_8) + " | "); } System.out.println(); } System.out.println(readPacket(payload, new EOF_Packet(), flags)); System.out.println("\n" + Dumper.hexDumpReadable(buf)); }