List of usage examples for io.netty.buffer ByteBuf release
boolean release();
From source file:divconq.net.ssl.PemReader.java
License:Apache License
static ByteBuf readPrivateKey(File file) throws KeyException { String content;/*from www.j a v a2s . c o m*/ try { content = readContent(file); } catch (IOException e) { throw new KeyException("failed to read a file: " + file, e); } Matcher m = KEY_PATTERN.matcher(content); if (!m.find()) { throw new KeyException("found no private key: " + file); } ByteBuf base64 = Unpooled.copiedBuffer(m.group(1), CharsetUtil.US_ASCII); ByteBuf der = Base64.decode(base64); base64.release(); return der; }
From source file:divconq.net.ssl.SslHandler.java
License:Apache License
private void finishWrap(ChannelHandlerContext ctx, ByteBuf out, ChannelPromise promise, boolean inUnwrap) { if (out == null) { out = Unpooled.EMPTY_BUFFER;//from w w w . j a va 2 s. co m } else if (!out.isReadable()) { out.release(); out = Unpooled.EMPTY_BUFFER; } if (promise != null) { ctx.write(out, promise); } else { ctx.write(out); } if (inUnwrap) { needsFlush = true; } }
From source file:divconq.net.ssl.SslHandler.java
License:Apache License
private void wrapNonAppData(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException { ByteBuf out = null; try {// w w w. j a v a2 s .co m for (;;) { if (out == null) { out = allocateOutNetBuf(ctx, 0); } SSLEngineResult result = wrap(engine, Unpooled.EMPTY_BUFFER, out); if (result.bytesProduced() > 0) { ctx.write(out); if (inUnwrap) { needsFlush = true; } out = null; } switch (result.getHandshakeStatus()) { case FINISHED: setHandshakeSuccess(); break; case NEED_TASK: runDelegatedTasks(); break; case NEED_UNWRAP: if (!inUnwrap) { unwrapNonAppData(ctx); } break; case NEED_WRAP: break; case NOT_HANDSHAKING: setHandshakeSuccessIfStillHandshaking(); // Workaround for TLS False Start problem reported at: // https://github.com/netty/netty/issues/1108#issuecomment-14266970 if (!inUnwrap) { unwrapNonAppData(ctx); } break; default: throw new IllegalStateException("Unknown handshake status: " + result.getHandshakeStatus()); } if (result.bytesProduced() == 0) { break; } } } catch (SSLException e) { setHandshakeFailure(e); throw e; } finally { if (out != null) { out.release(); } } }
From source file:divconq.net.ssl.SslHandler.java
License:Apache License
private void unwrap(ChannelHandlerContext ctx, ByteBuffer packet, int initialOutAppBufCapacity) throws SSLException { // If SSLEngine expects a heap buffer for unwrapping, do the conversion. final ByteBuffer oldPacket; final ByteBuf newPacket; final int oldPos = packet.position(); if (wantsInboundHeapBuffer && packet.isDirect()) { newPacket = ctx.alloc().heapBuffer(packet.limit() - oldPos); newPacket.writeBytes(packet);/*from ww w .j a v a 2 s. c o m*/ oldPacket = packet; packet = newPacket.nioBuffer(); } else { oldPacket = null; newPacket = null; } boolean wrapLater = false; ByteBuf decodeOut = allocate(ctx, initialOutAppBufCapacity); try { for (;;) { final SSLEngineResult result = unwrap(engine, packet, decodeOut); final Status status = result.getStatus(); final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); final int produced = result.bytesProduced(); final int consumed = result.bytesConsumed(); if (status == Status.CLOSED) { // notify about the CLOSED state of the SSLEngine. See #137 sslCloseFuture.trySuccess(ctx.channel()); break; } switch (handshakeStatus) { case NEED_UNWRAP: break; case NEED_WRAP: wrapNonAppData(ctx, true); break; case NEED_TASK: runDelegatedTasks(); break; case FINISHED: setHandshakeSuccess(); wrapLater = true; continue; case NOT_HANDSHAKING: if (setHandshakeSuccessIfStillHandshaking()) { wrapLater = true; continue; } if (flushedBeforeHandshakeDone) { // We need to call wrap(...) in case there was a flush done before the handshake completed. // // See https://github.com/netty/netty/pull/2437 flushedBeforeHandshakeDone = false; wrapLater = true; } break; default: throw new IllegalStateException("Unknown handshake status: " + handshakeStatus); } if (status == Status.BUFFER_UNDERFLOW || consumed == 0 && produced == 0) { break; } } if (wrapLater) { wrap(ctx, true); } } catch (SSLException e) { setHandshakeFailure(e); throw e; } finally { // If we converted packet into a heap buffer at the beginning of this method, // we should synchronize the position of the original buffer. if (newPacket != null) { oldPacket.position(oldPos + packet.position()); newPacket.release(); } if (decodeOut.isReadable()) { ctx.fireChannelRead(decodeOut); } else { decodeOut.release(); } } }
From source file:divconq.pgp.EncryptedFileStream.java
License:Open Source License
public void writeData(byte[] bytes, int offset, int len) { // the first time this is called we need to write headers - those headers // call into this method so clear flag immediately if (!this.writeFirst) { this.writeFirst = true; this.writeFirstLiteral(len); }/*from www. java 2 s. c o m*/ int remaining = len; int avail = this.packetsize - this.packetpos; // packetbuf may have data that has not yet been processed, so if we are doing any writes // we need to write the packet buffer first ByteBuf pbb = this.packetbuf; if (pbb != null) { int bbremaining = pbb.readableBytes(); // only write if there is space available in current packet or if we have a total // amount of data larger than max packet size while ((bbremaining > 0) && ((avail > 0) || (bbremaining + remaining) >= MAX_PACKET_SIZE)) { // out of current packet space? create more packets if (avail == 0) { this.packetsize = MAX_PACKET_SIZE; this.packetpos = 0; this.writeDataInternal((byte) MAX_PARTIAL_LEN); // partial packet length avail = this.packetsize; } // figure out how much we can write to the current packet, write it, update indexes int alen = Math.min(avail, bbremaining); this.writeDataInternal(pbb.array(), pbb.arrayOffset() + pbb.readerIndex(), alen); pbb.skipBytes(alen); bbremaining = pbb.readableBytes(); this.packetpos += alen; avail = this.packetsize - this.packetpos; // our formula always assumes that packetbuf starts at zero offset, anytime // we write out part of the packetbuf we either need to write it all and clear it // or we need to start with a new buffer with data starting at offset 0 if (bbremaining == 0) { pbb.clear(); } else { ByteBuf npb = Hub.instance.getBufferAllocator().heapBuffer(MAX_PACKET_SIZE); npb.writeBytes(pbb, bbremaining); this.packetbuf = npb; pbb.release(); pbb = npb; } } } // only write if there is space available in current packet or if we have a total // amount of data larger than max packet size while ((remaining > 0) && ((avail > 0) || (remaining >= MAX_PACKET_SIZE))) { // out of current packet space? create more packets if (avail == 0) { this.packetsize = MAX_PACKET_SIZE; this.packetpos = 0; this.writeDataInternal((byte) MAX_PARTIAL_LEN); // partial packet length avail = this.packetsize; } // figure out how much we can write to the current packet, write it, update indexes int alen = Math.min(avail, remaining); this.writeDataInternal(bytes, offset, alen); remaining -= alen; offset += alen; this.packetpos += alen; avail = this.packetsize - this.packetpos; } // buffer remaining to build larger packet later if (remaining > 0) { if (this.packetbuf == null) this.packetbuf = Hub.instance.getBufferAllocator().heapBuffer(MAX_PACKET_SIZE); // add to new buffer or add to existing buffer, either way it should be less than max here this.packetbuf.writeBytes(bytes, offset, remaining); } }
From source file:divconq.pgp.PGPUtil.java
License:Open Source License
static public void encryptFile(String outputFileName, String inputFileName, String encKeyFileName) throws IOException, NoSuchProviderException, PGPException { Path fileIn = Paths.get(inputFileName); Path fileOut = Paths.get(outputFileName); Path fileKey = Paths.get(encKeyFileName); OutputStream out = new BufferedOutputStream(new FileOutputStream(fileOut.toFile())); try {//from w ww .j a va2 s.c o m EncryptedFileStream pw = new EncryptedFileStream(); //pw.setAlgorithm(SymmetricKeyAlgorithmTags.NULL); pw.setFileName(fileIn.getFileName().toString()); pw.loadPublicKey(fileKey); pw.init(); FileInputStream in = new FileInputStream(fileIn.toFile()); byte[] ibuf = new byte[31 * 1024]; int len; while ((len = in.read(ibuf)) > 0) { pw.writeData(ibuf, 0, len); ByteBuf buf = pw.nextReadyBuffer(); while (buf != null) { out.write(buf.array(), buf.arrayOffset(), buf.readableBytes()); buf.release(); buf = pw.nextReadyBuffer(); } } in.close(); pw.close(); ByteBuf buf = pw.nextReadyBuffer(); while (buf != null) { out.write(buf.array(), buf.arrayOffset(), buf.readableBytes()); buf.release(); buf = pw.nextReadyBuffer(); } out.close(); } catch (Exception e) { System.err.println(e); e.printStackTrace(); } }
From source file:divconq.struct.CompositeStruct.java
License:Open Source License
public void toSerialMemory(Memory res) throws BuilderStateException { ByteBuf buf = Hub.instance.getBufferAllocator().heapBuffer(16 * 1024, 16 * 1024 * 1024); CompositeToBufferBuilder rb = new CompositeToBufferBuilder(buf); this.toBuilder(rb); rb.write(Special.End);// w w w . ja v a 2s . c o m res.write(buf.array(), buf.arrayOffset(), buf.readableBytes()); buf.release(); }
From source file:divconq.struct.CompositeStruct.java
License:Open Source License
public Memory toSerialMemory() throws BuilderStateException { ByteBuf buf = Hub.instance.getBufferAllocator().heapBuffer(16 * 1024, 16 * 1024 * 1024); CompositeToBufferBuilder rb = new CompositeToBufferBuilder(buf); this.toBuilder(rb); rb.write(Special.End);/*from w ww . j a va 2 s.c om*/ Memory res = new Memory(buf.readableBytes()); res.write(buf.array(), buf.arrayOffset(), buf.readableBytes()); buf.release(); return res; }
From source file:dorkbox.network.pipeline.discovery.BroadcastServer.java
License:Apache License
/** * @return true if the broadcast was responded to, false if it was not a broadcast (and there was no response) *//* w w w.j a v a 2s . c o m*/ public boolean isDiscoveryRequest(final Channel channel, ByteBuf byteBuf, final InetSocketAddress localAddress, InetSocketAddress remoteAddress) { if (byteBuf.readableBytes() == 1) { // this is a BROADCAST discovery event. Don't read the byte unless it is... if (byteBuf.getByte(0) == MagicBytes.broadcastID) { byteBuf.readByte(); // read the byte to consume it (now that we verified it is a broadcast byte) // absolutely MUST send packet > 0 across, otherwise netty will think it failed to write to the socket, and keep trying. // (this bug was fixed by netty, however we are keeping this code) ByteBuf directBuffer = channel.alloc().ioBuffer(bufferSize); directBuffer.writeByte(MagicBytes.broadcastResponseID); // now output the port information for TCP/UDP so the broadcast client knows which port to connect to // either it will be TCP or UDP, or BOTH int enabledFlag = 0; if (tcpPort > 0) { enabledFlag |= MagicBytes.HAS_TCP; } if (udpPort > 0) { enabledFlag |= MagicBytes.HAS_UDP; } directBuffer.writeByte(enabledFlag); // TCP is always first if (tcpPort > 0) { directBuffer.writeShort(tcpPort); } if (udpPort > 0) { directBuffer.writeShort(udpPort); } channel.writeAndFlush(new DatagramPacket(directBuffer, remoteAddress, localAddress)); logger.info("Responded to host discovery from [{}]", EndPoint.getHostDetails(remoteAddress)); byteBuf.release(); return true; } } return false; }
From source file:dorkbox.network.pipeline.discovery.BroadcastServer.java
License:Apache License
/** * @return true if this is a broadcast response, false if it was not a broadcast response *//*from w w w . j av a 2s . c om*/ public static boolean isDiscoveryResponse(ByteBuf byteBuf, final InetAddress remoteAddress, final Channel channel) { if (byteBuf.readableBytes() <= MagicBytes.maxPacketSize) { // this is a BROADCAST discovery RESPONSE event. Don't read the byte unless it is... if (byteBuf.getByte(0) == MagicBytes.broadcastResponseID) { byteBuf.readByte(); // read the byte to consume it (now that we verified it is a broadcast byte) // either it will be TCP or UDP, or BOTH int typeID = byteBuf.readByte(); int tcpPort = 0; int udpPort = 0; // TCP is always first if ((typeID & MagicBytes.HAS_TCP) == MagicBytes.HAS_TCP) { tcpPort = byteBuf.readUnsignedShort(); } if ((typeID & MagicBytes.HAS_UDP) == MagicBytes.HAS_UDP) { udpPort = byteBuf.readUnsignedShort(); } channel.attr(ClientDiscoverHostHandler.STATE) .set(new BroadcastResponse(remoteAddress, tcpPort, udpPort)); byteBuf.release(); return true; } } return false; }