List of usage examples for io.netty.buffer ByteBuf getByte
public abstract byte getByte(int index);
From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java
License:Apache License
private Packet decode(ClientHead head, ByteBuf frame) throws IOException { if ((frame.getByte(0) == 'b' && frame.getByte(1) == '4') || frame.getByte(0) == 4 || frame.getByte(0) == 1) {/* w w w.java2 s . c o m*/ return parseBinary(head, frame); } PacketType type = readType(frame); Packet packet = new Packet(type); if (type == PacketType.PING) { packet.setData(readString(frame)); return packet; } if (!frame.isReadable()) { return packet; } PacketType innerType = readInnerType(frame); packet.setSubType(innerType); parseHeader(frame, packet, innerType); parseBody(head, frame, packet); return packet; }
From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java
License:Apache License
private Packet parseBinary(ClientHead head, ByteBuf frame) throws IOException { if (frame.getByte(0) == 1) { frame.readByte();// w ww .ja v a2 s .c om int headEndIndex = frame.bytesBefore((byte) -1); int len = (int) readLong(frame, headEndIndex); ByteBuf oldFrame = frame; frame = frame.slice(oldFrame.readerIndex() + 1, len); oldFrame.readerIndex(oldFrame.readerIndex() + 1 + len); } if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') { frame.readShort(); } else if (frame.getByte(0) == 4) { frame.readByte(); } Packet binaryPacket = head.getLastBinaryPacket(); if (binaryPacket != null) { ByteBuf attachBuf; if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') { attachBuf = frame; } else { attachBuf = Base64.encode(frame); } binaryPacket.addAttachment(Unpooled.copiedBuffer(attachBuf)); frame.readerIndex(frame.readerIndex() + frame.readableBytes()); if (binaryPacket.isAttachmentsLoaded()) { LinkedList<ByteBuf> slices = new LinkedList<ByteBuf>(); ByteBuf source = binaryPacket.getDataSource(); for (int i = 0; i < binaryPacket.getAttachments().size(); i++) { ByteBuf attachment = binaryPacket.getAttachments().get(i); ByteBuf scanValue = Unpooled.copiedBuffer("{\"_placeholder\":true,\"num\":" + i + "}", CharsetUtil.UTF_8); int pos = PacketEncoder.find(source, scanValue); if (pos == -1) { throw new IllegalStateException( "Can't find attachment by index: " + i + " in packet source"); } ByteBuf prefixBuf = source.slice(source.readerIndex(), pos - source.readerIndex()); slices.add(prefixBuf); slices.add(QUOTES); slices.add(attachment); slices.add(QUOTES); source.readerIndex(pos + scanValue.readableBytes()); } slices.add(source.slice()); ByteBuf compositeBuf = Unpooled.wrappedBuffer(slices.toArray(new ByteBuf[slices.size()])); parseBody(head, compositeBuf, binaryPacket); head.setLastBinaryPacket(null); return binaryPacket; } } return new Packet(PacketType.MESSAGE); }
From source file:com.corundumstudio.socketio.protocol.PacketEncoder.java
License:Apache License
private static boolean isValueFound(ByteBuf buffer, int index, ByteBuf search) { for (int i = 0; i < search.readableBytes(); i++) { if (buffer.getByte(index + i) != search.getByte(i)) { return false; }//from ww w . j a va 2 s. com } return true; }
From source file:com.couchbase.client.core.endpoint.binary.BinaryHandler.java
License:Open Source License
@Override protected CouchbaseResponse decodeResponse(final ChannelHandlerContext ctx, final FullBinaryMemcacheResponse msg) throws Exception { BinaryRequest request = currentRequest(); ResponseStatus status = convertStatus(msg.getStatus()); CouchbaseResponse response;/* w ww .j a va 2s . c om*/ ByteBuf content = msg.content().copy(); long cas = msg.getCAS(); String bucket = request.bucket(); if (request instanceof GetRequest || request instanceof ReplicaGetRequest) { int flags = 0; if (msg.getExtrasLength() > 0) { final ByteBuf extrasReleased = msg.getExtras(); final ByteBuf extras = ctx.alloc().buffer(msg.getExtrasLength()); extras.writeBytes(extrasReleased, extrasReleased.readerIndex(), extrasReleased.readableBytes()); flags = extras.getInt(0); extras.release(); } response = new GetResponse(status, cas, flags, bucket, content, request); } else if (request instanceof GetBucketConfigRequest) { response = new GetBucketConfigResponse(status, bucket, content, ((GetBucketConfigRequest) request).hostname()); } else if (request instanceof InsertRequest) { response = new InsertResponse(status, cas, bucket, content, request); } else if (request instanceof UpsertRequest) { response = new UpsertResponse(status, cas, bucket, content, request); } else if (request instanceof ReplaceRequest) { response = new ReplaceResponse(status, cas, bucket, content, request); } else if (request instanceof RemoveRequest) { response = new RemoveResponse(status, bucket, content, request); } else if (request instanceof CounterRequest) { response = new CounterResponse(status, bucket, msg.content().readLong(), cas, request); } else if (request instanceof UnlockRequest) { response = new UnlockResponse(status, bucket, content, request); } else if (request instanceof TouchRequest) { response = new TouchResponse(status, bucket, content, request); } else if (request instanceof ObserveRequest) { byte observed = content.getByte(content.getShort(2) + 4); response = new ObserveResponse(status, observed, ((ObserveRequest) request).master(), bucket, content, request); } else if (request instanceof AppendRequest) { response = new AppendResponse(status, cas, bucket, content, request); } else if (request instanceof PrependRequest) { response = new PrependResponse(status, cas, bucket, content, request); } else { throw new IllegalStateException( "Unhandled request/response pair: " + request.getClass() + "/" + msg.getClass()); } return response; }
From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandler.java
License:Apache License
/** * Helper method to decode all other response messages. * * @param request the current request.// w w w . j a v a 2 s .c om * @param msg the current response message. * @param status the response status code. * @return the decoded response or null if none did match. */ private static CouchbaseResponse handleOtherResponseMessages(BinaryRequest request, FullBinaryMemcacheResponse msg, ResponseStatus status, boolean seqOnMutation, String remoteHostname) { CouchbaseResponse response = null; ByteBuf content = msg.content(); long cas = msg.getCAS(); short statusCode = msg.getStatus(); String bucket = request.bucket(); if (request instanceof UnlockRequest) { response = new UnlockResponse(status, statusCode, bucket, content, request); } else if (request instanceof TouchRequest) { response = new TouchResponse(status, statusCode, bucket, content, request); } else if (request instanceof AppendRequest) { MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); response = new AppendResponse(status, statusCode, cas, bucket, content, descr, request); } else if (request instanceof PrependRequest) { MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); response = new PrependResponse(status, statusCode, cas, bucket, content, descr, request); } else if (request instanceof KeepAliveRequest) { releaseContent(content); response = new KeepAliveResponse(status, statusCode, request); } else if (request instanceof CounterRequest) { long value = status.isSuccess() ? content.readLong() : 0; releaseContent(content); MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); response = new CounterResponse(status, statusCode, bucket, value, cas, descr, request); } else if (request instanceof StatRequest) { String key = new String(msg.getKey(), CHARSET); String value = content.toString(CHARSET); releaseContent(content); response = new StatResponse(status, statusCode, remoteHostname, key, value, bucket, request); } else if (request instanceof GetAllMutationTokensRequest) { // 2 bytes for partition ID, and 8 bytes for sequence number MutationToken[] mutationTokens = new MutationToken[content.readableBytes() / 10]; for (int i = 0; i < mutationTokens.length; i++) { mutationTokens[i] = new MutationToken((long) content.readShort(), 0, content.readLong(), request.bucket()); } releaseContent(content); response = new GetAllMutationTokensResponse(mutationTokens, status, statusCode, bucket, request); } else if (request instanceof ObserveRequest) { byte observed = ObserveResponse.ObserveStatus.UNKNOWN.value(); long observedCas = 0; if (status.isSuccess()) { short keyLength = content.getShort(2); observed = content.getByte(keyLength + 4); observedCas = content.getLong(keyLength + 5); } releaseContent(content); response = new ObserveResponse(status, statusCode, observed, ((ObserveRequest) request).master(), observedCas, bucket, request); } else if (request instanceof ObserveSeqnoRequest) { if (status.isSuccess()) { byte format = content.readByte(); switch (format) { case 0: response = new NoFailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), content.readShort(), content.readLong(), content.readLong(), content.readLong(), status, statusCode, bucket, request); break; case 1: response = new FailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), content.readShort(), content.readLong(), content.readLong(), content.readLong(), content.readLong(), content.readLong(), status, statusCode, bucket, request); break; default: throw new IllegalStateException("Unknown format for observe-seq: " + format); } } else { response = new NoFailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), (short) 0, 0, 0, 0, status, statusCode, bucket, request); } releaseContent(content); } return response; }
From source file:com.couchbase.client.core.endpoint.util.ByteBufJsonHelper.java
License:Apache License
/** * Find the number of bytes until next occurrence of the character c * from the current {@link ByteBuf#readerIndex() readerIndex} in buf, * with the twist that if this occurrence is prefixed by the prefix * character, we try to find another occurrence. * * @param buf the {@link ByteBuf buffer} to look into. * @param c the character to search for. * @param prefix the character to trigger a retry. * @return the position of the first occurrence of c that is not prefixed by prefix * or -1 if none found./*from w w w .j a v a 2 s. com*/ */ public static final int findNextCharNotPrefixedBy(ByteBuf buf, char c, char prefix) { int found = buf.bytesBefore((byte) c); if (found < 1) { return found; } else { int from; while (found > -1 && (char) buf.getByte(buf.readerIndex() + found - 1) == prefix) { //advance from from = buf.readerIndex() + found + 1; //search again int next = buf.bytesBefore(from, buf.readableBytes() - from + buf.readerIndex(), (byte) c); if (next == -1) { return -1; } else { found += next + 1; } } return found; } }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAsymmetricHandler.java
License:Apache License
private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException { buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize long secureChannelId = buffer.readUnsignedInt(); secureChannel.setChannelId(secureChannelId); AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer); if (!headerRef.compareAndSet(null, securityHeader)) { if (!securityHeader.equals(headerRef.get())) { throw new UaRuntimeException(StatusCodes.Bad_SecurityChecksFailed, "subsequent AsymmetricSecurityHeader did not match"); }//ww w .j a v a2 s.c o m } int chunkSize = buffer.readerIndex(0).readableBytes(); if (chunkSize > maxChunkSize) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk size exceeded (%s)", maxChunkSize)); } chunkBuffers.add(buffer.retain()); if (chunkBuffers.size() > maxChunkCount) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk count exceeded (%s)", maxChunkCount)); } char chunkType = (char) buffer.getByte(3); if (chunkType == 'A' || chunkType == 'F') { final List<ByteBuf> buffersToDecode = chunkBuffers; chunkBuffers = new ArrayList<>(maxChunkCount); serializationQueue.decode((binaryDecoder, chunkDecoder) -> { ByteBuf decodedBuffer = null; try { decodedBuffer = chunkDecoder.decodeAsymmetric(secureChannel, buffersToDecode); UaResponseMessage responseMessage = binaryDecoder.setBuffer(decodedBuffer).decodeMessage(null); StatusCode serviceResult = responseMessage.getResponseHeader().getServiceResult(); if (serviceResult.isGood()) { OpenSecureChannelResponse response = (OpenSecureChannelResponse) responseMessage; secureChannel.setChannelId(response.getSecurityToken().getChannelId().longValue()); logger.debug("Received OpenSecureChannelResponse."); installSecurityToken(ctx, response); } else { ServiceFault serviceFault = (responseMessage instanceof ServiceFault) ? (ServiceFault) responseMessage : new ServiceFault(responseMessage.getResponseHeader()); throw new UaServiceFaultException(serviceFault); } } catch (MessageAbortedException e) { logger.error("Received message abort chunk; error={}, reason={}", e.getStatusCode(), e.getMessage()); ctx.close(); } catch (Throwable t) { logger.error("Error decoding OpenSecureChannelResponse: {}", t.getMessage(), t); ctx.close(); } finally { if (decodedBuffer != null) { decodedBuffer.release(); } buffersToDecode.clear(); } }); } }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientMessageHandler.java
License:Apache License
private boolean accumulateChunk(ByteBuf buffer) throws UaException { int maxChunkCount = serializationQueue.getParameters().getLocalMaxChunkCount(); int maxChunkSize = serializationQueue.getParameters().getLocalReceiveBufferSize(); int chunkSize = buffer.readerIndex(0).readableBytes(); if (chunkSize > maxChunkSize) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk size exceeded (%s)", maxChunkSize)); }// ww w . ja va2 s . c om chunkBuffers.add(buffer.retain()); if (chunkBuffers.size() > maxChunkCount) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk count exceeded (%s)", maxChunkCount)); } char chunkType = (char) buffer.getByte(3); return (chunkType == 'A' || chunkType == 'F'); }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientSymmetricHandler.java
License:Apache License
private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException { buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize long secureChannelId = buffer.readUnsignedInt(); if (secureChannelId != secureChannel.getChannelId()) { throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid, "invalid secure channel id: " + secureChannelId); }// w ww. j a v a 2s. co m int chunkSize = buffer.readerIndex(0).readableBytes(); if (chunkSize > maxChunkSize) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk size exceeded (%s)", maxChunkSize)); } chunkBuffers.add(buffer.retain()); if (chunkBuffers.size() > maxChunkCount) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk count exceeded (%s)", maxChunkCount)); } char chunkType = (char) buffer.getByte(3); if (chunkType == 'A' || chunkType == 'F') { final List<ByteBuf> buffersToDecode = chunkBuffers; chunkBuffers = new ArrayList<>(maxChunkCount); serializationQueue.decode((binaryDecoder, chunkDecoder) -> { ByteBuf decodedBuffer = null; try { validateChunkHeaders(buffersToDecode); decodedBuffer = chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode); binaryDecoder.setBuffer(decodedBuffer); UaResponseMessage response = binaryDecoder.decodeMessage(null); UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId()); if (request != null) { client.getExecutorService().execute(() -> request.getFuture().complete(response)); } else { logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId()); } } catch (MessageAbortedException e) { logger.debug("Received message abort chunk; error={}, reason={}", e.getStatusCode(), e.getMessage()); UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId()); if (request != null) { client.getExecutorService().execute(() -> request.getFuture().completeExceptionally(e)); } else { logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId()); } } catch (Throwable t) { logger.error("Error decoding symmetric message: {}", t.getMessage(), t); ctx.close(); serializationQueue.pause(); } finally { if (decodedBuffer != null) { decodedBuffer.release(); } buffersToDecode.clear(); } }); } }
From source file:com.digitalpetri.opcua.stack.core.channel.ChunkDecoder.java
License:Apache License
private ByteBuf decode(Delegate delegate, SecureChannel channel, List<ByteBuf> chunkBuffers) throws UaException { CompositeByteBuf composite = BufferUtil.compositeBuffer(); int signatureSize = delegate.getSignatureSize(channel); int cipherTextBlockSize = delegate.getCipherTextBlockSize(channel); boolean encrypted = delegate.isEncryptionEnabled(channel); boolean signed = delegate.isSigningEnabled(channel); for (ByteBuf chunkBuffer : chunkBuffers) { char chunkType = (char) chunkBuffer.getByte(3); chunkBuffer.skipBytes(SecureMessageHeader.SECURE_MESSAGE_HEADER_SIZE); delegate.readSecurityHeader(channel, chunkBuffer); if (encrypted) { decryptChunk(delegate, channel, chunkBuffer); }/*w ww.j a v a 2 s . c om*/ int encryptedStart = chunkBuffer.readerIndex(); chunkBuffer.readerIndex(0); if (signed) { delegate.verifyChunk(channel, chunkBuffer); } int paddingSize = encrypted ? getPaddingSize(cipherTextBlockSize, signatureSize, chunkBuffer) : 0; int bodyEnd = chunkBuffer.readableBytes() - signatureSize - paddingSize; chunkBuffer.readerIndex(encryptedStart); SequenceHeader sequenceHeader = SequenceHeader.decode(chunkBuffer); long sequenceNumber = sequenceHeader.getSequenceNumber(); lastRequestId = sequenceHeader.getRequestId(); if (lastSequenceNumber == -1) { lastSequenceNumber = sequenceNumber; } else { if (lastSequenceNumber + 1 != sequenceNumber) { String message = String.format("expected sequence number %s but received %s", lastSequenceNumber + 1, sequenceNumber); logger.error(message); logger.error(ByteBufUtil.hexDump(chunkBuffer, 0, chunkBuffer.writerIndex())); throw new UaException(StatusCodes.Bad_SecurityChecksFailed, message); } lastSequenceNumber = sequenceNumber; } ByteBuf bodyBuffer = chunkBuffer.readSlice(bodyEnd - chunkBuffer.readerIndex()); if (chunkType == 'A') { ErrorMessage errorMessage = ErrorMessage.decode(bodyBuffer); throw new MessageAbortedException(errorMessage.getError(), errorMessage.getReason()); } composite.addComponent(bodyBuffer); composite.writerIndex(composite.writerIndex() + bodyBuffer.readableBytes()); } return composite.order(ByteOrder.LITTLE_ENDIAN); }