List of usage examples for io.netty.buffer ByteBuf readerIndex
public abstract int readerIndex();
From source file:com.talent.mysql.packet.response.HandshakePacket.java
License:Open Source License
@Override public HandshakePacket decodeBody(ByteBuf byteBuf, MysqlHeader mysqlHeader) throws DecodeException { this.setMysqlHeader(mysqlHeader); int _index = byteBuf.readerIndex(); int index = _index; protocolVersion = byteBuf.getByte(index++); int len = 0;//from w w w. java 2 s . co m while (byteBuf.getByte(index + len) != 0) { len++; } versionInfo = new byte[len]; byteBuf.getBytes(index, versionInfo, 0, len); index += len; index++; threadId = byteBuf.getInt(index); index += 4; encrypt1 = new byte[8]; byteBuf.getBytes(index, encrypt1, 0, 8); index += 8; fix1 = byteBuf.getByte(index++); serverProp1 = new byte[2]; byteBuf.getBytes(index, serverProp1, 0, 2); index += 2; charset = byteBuf.getByte(index++); serverStatus = new byte[2]; byteBuf.getBytes(index, serverStatus, 0, 2); index += 2; serverProp2 = new byte[2]; byteBuf.getBytes(index, serverProp2, 0, 2); index += 2; fix2 = byteBuf.getByte(index++); // byte10 = new byte[10]; // byteBuf.getBytes(index, byte10, 0, 10); index += 10; len = 0; while (byteBuf.getByte(index + len) != 0) { len++; } encrypt2 = new byte[len]; byteBuf.getBytes(index, encrypt2, 0, len); index += len; index++; len = 0; while (byteBuf.getByte(index + len) != 0) { len++; } authPluginName = new byte[len]; byteBuf.getBytes(index, authPluginName, 0, len); index += len; index++; byteBuf.readerIndex(index); return this; }
From source file:com.tesora.dve.db.mysql.common.MysqlAPIUtils.java
License:Open Source License
static boolean isLengthCodedLongNull(ByteBuf cb) { boolean isNull = (cb.getUnsignedByte(cb.readerIndex()) == LEN_CODED_NULL); if (isNull)/*from w ww. jav a 2 s .c o m*/ cb.readUnsignedByte(); return isNull; }
From source file:com.tesora.dve.db.mysql.common.MysqlAPIUtils.java
License:Open Source License
public static ArrayList<Integer> locateLengthCodedStrings(ByteBuf cb, int skipAmount) { ArrayList<Integer> offsets = new ArrayList<>(); ByteBuf slice = cb.slice().order(ByteOrder.LITTLE_ENDIAN); slice.skipBytes(skipAmount);/*from w w w .j a v a2 s.c o m*/ while (slice.isReadable()) { offsets.add(slice.readerIndex()); skipLengthCodedString(slice); } return offsets; }
From source file:com.tesora.dve.db.mysql.libmy.MyBinaryResultRow.java
License:Open Source License
@Override public void unmarshallMessage(ByteBuf cb) throws PEException { int expectedFieldCount = fieldConverters.size(); int expectedBitmapLength = MyNullBitmap.computeSize(expectedFieldCount, MyNullBitmap.BitmapType.RESULT_ROW); cb = cb.order(ByteOrder.LITTLE_ENDIAN); cb.skipBytes(1);//skip the bin row marker. byte[] nullBitmap = new byte[expectedBitmapLength]; cb.readBytes(nullBitmap);//from w w w. ja va2 s. c om MyNullBitmap resultBitmap = new MyNullBitmap(nullBitmap, expectedFieldCount, MyNullBitmap.BitmapType.RESULT_ROW); ByteBuf values = cb; for (int i = 0; i < expectedFieldCount; i++) { ByteBuf existing = fieldSlices.get(i); ByteBuf nextSlice = null; int startIndex = values.readerIndex(); if (!resultBitmap.getBit(i + 1)) { fieldConverters.get(i).readObject(values);//TODO: we throw out the unmarshalled value, we could cache it. int endingOffset = values.readerIndex(); nextSlice = values.slice(startIndex, endingOffset - startIndex); } if (existing != null) existing.release(); fieldSlices.set(i, nextSlice); } if (cb.readableBytes() > 0) { log.warn("Decoded binary row had {} leftover bytes, re-encoding may fail.", cb.readableBytes()); cb.skipBytes(cb.readableBytes());//consume rest of buffer. } }
From source file:com.tesora.dve.db.mysql.libmy.MyLoginRequest.java
License:Open Source License
@Override public void unmarshallMessage(ByteBuf cb) { clientCapabilities = cb.readUnsignedInt(); boolean hasConnectDatabase = ((clientCapabilities & ClientCapabilities.CLIENT_CONNECT_WITH_DB) == ClientCapabilities.CLIENT_CONNECT_WITH_DB); maxPacketSize = cb.readInt();// ww w.ja v a2s. co m clientCharset = cb.readByte(); cb.skipBytes(23); // login request has a 23 byte filler username = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8); cb.skipBytes(1); // skip the NULL terminator byte passwordLength = cb.readByte(); byte[] passwordBytes = new byte[passwordLength]; cb.getBytes(cb.readerIndex(), passwordBytes, 0, passwordLength); password = new String(passwordBytes, CharsetUtil.ISO_8859_1); cb.skipBytes(passwordLength); // if the clientCapabilities flag has the CLIENT_CONNECT_WITH_DB bit set, // then this message contains an initial database to connect to if (hasConnectDatabase) { database = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8); if (database.length() < 1) { database = null; } } }
From source file:com.tesora.dve.db.mysql.portal.protocol.MSPComStmtExecuteRequestMessage.java
License:Open Source License
@Override protected ParsedData unmarshall(ByteBuf source) { ParsedData parseValues = new ParsedData(); source.skipBytes(1);//skip the type identifier. parseValues.statementID = source.readUnsignedInt(); parseValues.flags = source.readByte(); parseValues.iterationCount = source.readUnsignedInt(); parseValues.metadataOffset = source.readerIndex(); //we don't actually unmarshall the metadata and values here, since we don't know how many parameters there are. parseValues.metadata = null;//from ww w . j ava2s.c o m parseValues.values = null; return parseValues; }
From source file:com.tesora.dve.db.mysql.portal.protocol.MysqlClientAuthenticationHandler.java
License:Open Source License
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out, boolean isLastBytes) throws Exception { ByteBuf leBuf = in.order(ByteOrder.LITTLE_ENDIAN); leBuf.markReaderIndex();/* w ww . java 2 s . c o m*/ boolean messageProcessed = false; try { if (leBuf.readableBytes() > MESSAGE_HEADER_LEN) { int payloadLen = leBuf.readMedium(); leBuf.readByte(); // seq if (leBuf.readableBytes() >= payloadLen) { ByteBuf payload = leBuf.slice(leBuf.readerIndex(), payloadLen).order(ByteOrder.LITTLE_ENDIAN); Byte protocolVersion = leBuf.readByte(); leBuf.skipBytes(payloadLen - 1); messageProcessed = true; if (state == AuthenticationState.AWAIT_GREETING) processGreeting(ctx, payload, protocolVersion); else processAcknowlegement(ctx, payload); } } } catch (Throwable t) { enterState(AuthenticationState.FAILURE); log.warn("Unexpected problem on outbound mysql connection.", t); throw t; } finally { if (!messageProcessed) leBuf.resetReaderIndex(); if (isLastBytes && (state == AuthenticationState.AWAIT_ACKNOWLEGEMENT || state == AuthenticationState.AWAIT_GREETING)) { //we are waiting for handshake packets from mysql, but no more packets will ever arrive. release blocked callers. Channel channel = ctx.channel(); SocketAddress addr = (channel == null ? null : channel.remoteAddress()); log.warn("Socket closed in middle of authentication handshake on socket " + addr); enterState(AuthenticationState.FAILURE); } } }
From source file:com.tesora.dve.db.mysql.portal.protocol.MysqlClientAuthenticationHandler.java
License:Open Source License
private void processAcknowlegement(ChannelHandlerContext ctx, ByteBuf payload) throws Exception { byte fieldCount = payload.getByte(payload.readerIndex()); if (fieldCount == MyErrorResponse.ERRORPKT_FIELD_COUNT) { processErrorPacket(ctx, payload); } else {/*from w w w.j a v a2 s . com*/ ctx.pipeline().remove(this); enterState(AuthenticationState.AUTHENTICATED); } }
From source file:com.twitter.http2.HttpFrameDecoder.java
License:Apache License
/** * Decode the byte buffer.//from ww w.ja v a 2s . co m */ public void decode(ByteBuf buffer) { boolean endStream; boolean endSegment; int minLength; int dependency; int weight; boolean exclusive; int errorCode; while (true) { switch (state) { case READ_CONNECTION_HEADER: while (buffer.isReadable()) { byte b = buffer.readByte(); if (b != CLIENT_CONNECTION_PREFACE[length++]) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid Connection Header"); return; } if (length == CLIENT_CONNECTION_PREFACE.length) { state = State.READ_FRAME_HEADER; break; } } if (buffer.isReadable()) { break; } else { return; } case READ_FRAME_HEADER: // Wait until entire header is readable if (buffer.readableBytes() < HTTP_FRAME_HEADER_SIZE) { return; } // Read frame header fields readFrameHeader(buffer); // TODO(jpinner) Sec 4.2 FRAME_SIZE_ERROR if (!isValidFrameHeader(length, type, flags, streamId)) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid Frame Header"); } else if (frameHasPadding(type, flags)) { state = State.READ_PADDING_LENGTH; } else { paddingLength = 0; state = getNextState(length, type); } break; case READ_PADDING_LENGTH: if (buffer.readableBytes() < 1) { return; } paddingLength = buffer.readUnsignedByte(); --length; if (!isValidPaddingLength(length, type, flags, paddingLength)) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid Frame Padding Length"); } else { state = getNextState(length, type); } break; case READ_DATA_FRAME: endStream = hasFlag(flags, HTTP_FLAG_END_STREAM); state = State.READ_DATA; if (hasFlag(flags, HTTP_FLAG_PADDED)) { delegate.readDataFramePadding(streamId, endStream, paddingLength + 1); } break; case READ_DATA: // Generate data frames that do not exceed maxChunkSize // maxChunkSize must be > 0 so we cannot infinitely loop int dataLength = Math.min(maxChunkSize, length - paddingLength); // Wait until entire frame is readable if (buffer.readableBytes() < dataLength) { return; } ByteBuf data = buffer.readBytes(dataLength); length -= dataLength; if (length == paddingLength) { if (paddingLength == 0) { state = State.READ_FRAME_HEADER; } else { state = State.SKIP_FRAME_PADDING; } } endStream = length == paddingLength && hasFlag(flags, HTTP_FLAG_END_STREAM); endSegment = length == paddingLength && hasFlag(flags, HTTP_FLAG_END_SEGMENT); delegate.readDataFrame(streamId, endStream, endSegment, data); break; case READ_HEADERS_FRAME: minLength = 0; if (hasFlag(flags, HTTP_FLAG_PRIORITY)) { minLength = 5; } if (buffer.readableBytes() < minLength) { return; } endStream = hasFlag(flags, HTTP_FLAG_END_STREAM); endSegment = hasFlag(flags, HTTP_FLAG_END_SEGMENT); exclusive = false; dependency = 0; weight = 16; if (hasFlag(flags, HTTP_FLAG_PRIORITY)) { dependency = getSignedInt(buffer, buffer.readerIndex()); buffer.skipBytes(4); weight = buffer.readUnsignedByte() + 1; if (dependency < 0) { dependency = dependency & 0x7FFFFFFF; exclusive = true; } length -= 5; } state = State.READ_HEADER_BLOCK; delegate.readHeadersFrame(streamId, endStream, endSegment, exclusive, dependency, weight); break; case READ_PRIORITY_FRAME: if (buffer.readableBytes() < length) { return; } exclusive = false; dependency = getSignedInt(buffer, buffer.readerIndex()); buffer.skipBytes(4); weight = buffer.readUnsignedByte() + 1; if (dependency < 0) { dependency = dependency & 0x7FFFFFFF; exclusive = true; } state = State.READ_FRAME_HEADER; delegate.readPriorityFrame(streamId, exclusive, dependency, weight); break; case READ_RST_STREAM_FRAME: if (buffer.readableBytes() < length) { return; } errorCode = getSignedInt(buffer, buffer.readerIndex()); buffer.skipBytes(length); state = State.READ_FRAME_HEADER; delegate.readRstStreamFrame(streamId, errorCode); break; case READ_SETTINGS_FRAME: boolean ack = hasFlag(flags, HTTP_FLAG_ACK); state = State.READ_SETTING; delegate.readSettingsFrame(ack); break; case READ_SETTING: if (length == 0) { state = State.READ_FRAME_HEADER; delegate.readSettingsEnd(); break; } if (buffer.readableBytes() < 6) { return; } int id = getUnsignedShort(buffer, buffer.readerIndex()); int value = getSignedInt(buffer, buffer.readerIndex() + 2); buffer.skipBytes(6); length -= 6; delegate.readSetting(id, value); break; case READ_PUSH_PROMISE_FRAME: if (buffer.readableBytes() < 4) { return; } int promisedStreamId = getUnsignedInt(buffer, buffer.readerIndex()); buffer.skipBytes(4); length -= 4; if (promisedStreamId == 0) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid Promised-Stream-ID"); } else { state = State.READ_HEADER_BLOCK; delegate.readPushPromiseFrame(streamId, promisedStreamId); } break; case READ_PING_FRAME: if (buffer.readableBytes() < length) { return; } long ping = getSignedLong(buffer, buffer.readerIndex()); buffer.skipBytes(length); boolean pong = hasFlag(flags, HTTP_FLAG_ACK); state = State.READ_FRAME_HEADER; delegate.readPingFrame(ping, pong); break; case READ_GOAWAY_FRAME: if (buffer.readableBytes() < 8) { return; } int lastStreamId = getUnsignedInt(buffer, buffer.readerIndex()); errorCode = getSignedInt(buffer, buffer.readerIndex() + 4); buffer.skipBytes(8); length -= 8; if (length == 0) { state = State.READ_FRAME_HEADER; } else { paddingLength = length; state = State.SKIP_FRAME_PADDING; } delegate.readGoAwayFrame(lastStreamId, errorCode); break; case READ_WINDOW_UPDATE_FRAME: // Wait until entire frame is readable if (buffer.readableBytes() < length) { return; } int windowSizeIncrement = getUnsignedInt(buffer, buffer.readerIndex()); buffer.skipBytes(length); if (windowSizeIncrement == 0) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid Window Size Increment"); } else { state = State.READ_FRAME_HEADER; delegate.readWindowUpdateFrame(streamId, windowSizeIncrement); } break; case READ_CONTINUATION_FRAME_HEADER: // Wait until entire frame header is readable if (buffer.readableBytes() < HTTP_FRAME_HEADER_SIZE) { return; } // Read and validate continuation frame header fields int prevStreamId = streamId; readFrameHeader(buffer); // TODO(jpinner) Sec 4.2 FRAME_SIZE_ERROR // TODO(jpinner) invalid flags if (type != HTTP_CONTINUATION_FRAME || streamId != prevStreamId) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid Continuation Frame"); } else { paddingLength = 0; state = State.READ_HEADER_BLOCK; } break; case READ_HEADER_BLOCK: if (length == paddingLength) { boolean endHeaders = hasFlag(flags, HTTP_FLAG_END_HEADERS); if (endHeaders) { state = State.SKIP_FRAME_PADDING; delegate.readHeaderBlockEnd(); } else { state = State.SKIP_FRAME_PADDING_CONTINUATION; } break; } if (!buffer.isReadable()) { return; } int readableBytes = Math.min(buffer.readableBytes(), length - paddingLength); ByteBuf headerBlockFragment = buffer.readBytes(readableBytes); length -= readableBytes; delegate.readHeaderBlock(headerBlockFragment); break; case SKIP_FRAME_PADDING: int numBytes = Math.min(buffer.readableBytes(), length); buffer.skipBytes(numBytes); length -= numBytes; if (length == 0) { state = State.READ_FRAME_HEADER; break; } return; case SKIP_FRAME_PADDING_CONTINUATION: int numPaddingBytes = Math.min(buffer.readableBytes(), length); buffer.skipBytes(numPaddingBytes); length -= numPaddingBytes; if (length == 0) { state = State.READ_CONTINUATION_FRAME_HEADER; break; } return; case FRAME_ERROR: buffer.skipBytes(buffer.readableBytes()); return; default: throw new Error("Shouldn't reach here."); } } }
From source file:com.twitter.http2.HttpFrameDecoder.java
License:Apache License
/** * Reads the HTTP/2 Frame Header and sets the length, type, flags, and streamId member variables. * * @param buffer input buffer containing the entire 9-octet header */// w ww. j av a 2 s. c o m private void readFrameHeader(ByteBuf buffer) { int frameOffset = buffer.readerIndex(); length = getUnsignedMedium(buffer, frameOffset); type = buffer.getUnsignedByte(frameOffset + 3); flags = buffer.getByte(frameOffset + 4); streamId = getUnsignedInt(buffer, frameOffset + 5); buffer.skipBytes(HTTP_FRAME_HEADER_SIZE); }