/** * Create a new instance from the given {@link ServerSocket} * * @param socket the {@link ServerSocket} which is used by this instance */ public OioServerSocketChannel(ServerSocket socket) { super(null); if (socket == null) { throw new NullPointerException("socket"); } boolean success = false; try { socket.setSoTimeout(SO_TIMEOUT); success = true; } catch (IOException e) { throw new ChannelException("Failed to set the server socket timeout.", e); } finally { if (!success) { try { socket.close(); } catch (IOException e) { if (logger.isWarnEnabled()) { logger.warn("Failed to close a partially initialized socket.", e); } } } } this.socket = socket; config = new DefaultOioServerSocketChannelConfig(this, socket); }
static { boolean disabled; if (SystemPropertyUtil.get("io.netty.noResourceLeakDetection") != null) { boolean disabled = SystemPropertyUtil.getBoolean("io.netty.noResourceLeakDetection", false); logger.debug("-Dio.netty.noResourceLeakDetection: {}", Boolean.valueOf(disabled)); logger.warn( "-Dio.netty.noResourceLeakDetection is deprecated. Use '-D{}={}' instead.", "io.netty.leakDetectionLevel", DEFAULT_LEVEL.name().toLowerCase()); } else { disabled = false; } Level defaultLevel = disabled ? Level.DISABLED : DEFAULT_LEVEL; String levelStr = SystemPropertyUtil.get("io.netty.leakDetectionLevel", defaultLevel.name()) .trim() .toUpperCase(); Level level = DEFAULT_LEVEL; for (Level l : EnumSet.allOf(Level.class)) { if ((levelStr.equals(l.name())) || (levelStr.equals(String.valueOf(l.ordinal())))) { level = l; } } level = level; if (logger.isDebugEnabled()) { logger.debug("-D{}: {}", "io.netty.leakDetectionLevel", level.name().toLowerCase()); } }
private static void processGoAwayWriteResult( final ChannelHandlerContext ctx, final int lastStreamId, final long errorCode, final ByteBuf debugData, ChannelFuture future) { try { if (future.isSuccess()) { if (errorCode != NO_ERROR.code()) { if (logger.isDebugEnabled()) { logger.debug( format( "Sent GOAWAY: lastStreamId '%d', errorCode '%d', " + "debugData '%s'. Forcing shutdown of the connection.", lastStreamId, errorCode, debugData.toString(UTF_8)), future.cause()); } ctx.close(); } } else { if (logger.isErrorEnabled()) { logger.error( format( "Sending GOAWAY failed: lastStreamId '%d', errorCode '%d', " + "debugData '%s'. Forcing shutdown of the connection.", lastStreamId, errorCode, debugData.toString(UTF_8)), future.cause()); } ctx.close(); } } finally { // We're done with the debug data now. debugData.release(); } }
@Override protected int doReadMessages(MessageList<Object> buf) throws Exception { if (socket.isClosed()) { return -1; } try { Socket s = socket.accept(); try { if (s != null) { buf.add(new OioSocketChannel(this, s)); return 1; } } catch (Throwable t) { logger.warn("Failed to create a new channel from an accepted socket.", t); if (s != null) { try { s.close(); } catch (Throwable t2) { logger.warn("Failed to close a socket.", t2); } } } } catch (SocketTimeoutException e) { // Expected } return 0; }
static { DEFAULT_EVENT_LOOP_THREADS = Math.max( 1, SystemPropertyUtil.getInt( "io.netty.eventLoopThreads", Runtime.getRuntime().availableProcessors() * 2)); if (logger.isDebugEnabled()) { logger.debug("-Dio.netty.eventLoopThreads: {}", DEFAULT_EVENT_LOOP_THREADS); } }
private void reportLeak(Level level) { if (!logger.isErrorEnabled()) { for (; ; ) { ResourceLeakDetector<T>.DefaultResourceLeak ref = (DefaultResourceLeak) this.refQueue.poll(); if (ref == null) { break; } ref.close(); } return; } int samplingInterval = level == Level.PARANOID ? 1 : this.samplingInterval; if ((this.active * samplingInterval > this.maxActive) && (this.loggedTooManyActive.compareAndSet(false, true))) { logger.error( "LEAK: You are creating too many " + this.resourceType + " instances. " + this.resourceType + " is a shared resource that must be reused across the JVM," + "so that only a few instances are created."); } for (; ; ) { ResourceLeakDetector<T>.DefaultResourceLeak ref = (DefaultResourceLeak) this.refQueue.poll(); if (ref == null) { break; } ref.clear(); if (ref.close()) { String records = ref.toString(); if (this.reportedLeaks.putIfAbsent(records, Boolean.TRUE) == null) { if (records.isEmpty()) { logger.error( "LEAK: {}.release() was not called before it's garbage-collected. Enable advanced leak reporting to find out where the leak occurred. To enable advanced leak reporting, specify the JVM option '-D{}={}' or call {}.setLevel()", new Object[] { this.resourceType, "io.netty.leakDetectionLevel", Level.ADVANCED.name().toLowerCase(), StringUtil.simpleClassName(this) }); } else { logger.error( "LEAK: {}.release() was not called before it's garbage-collected.{}", this.resourceType, records); } } } } }
/** Notify all the handshake futures about the failure during the handshake. */ private void setHandshakeFailure(Throwable cause) { // Release all resources such as internal buffers that SSLEngine // is managing. engine.closeOutbound(); try { engine.closeInbound(); } catch (SSLException e) { // only log in debug mode as it most likely harmless and latest chrome still trigger // this all the time. // // See https://github.com/netty/netty/issues/1340 String msg = e.getMessage(); if (msg == null || !msg.contains("possible truncation attack")) { logger.debug("SSLEngine.closeInbound() raised an exception.", e); } } notifyHandshakeFailure(cause); for (; ; ) { PendingWrite write = pendingUnencryptedWrites.poll(); if (write == null) { break; } write.failAndRecycle(cause); } }
@Parameters(name = "{index}: serverEngine = {0}, clientEngine = {1}") public static Collection<Object[]> data() throws Exception { List<SslContext> serverContexts = new ArrayList<SslContext>(); List<SslContext> clientContexts = new ArrayList<SslContext>(); clientContexts.add(new JdkSslClientContext(CERT_FILE)); boolean hasOpenSsl = OpenSsl.isAvailable(); if (hasOpenSsl) { OpenSslServerContext context = new OpenSslServerContext(CERT_FILE, KEY_FILE); context.setRejectRemoteInitiatedRenegotiation(true); serverContexts.add(context); } else { logger.warn( "OpenSSL is unavailable and thus will not be tested.", OpenSsl.unavailabilityCause()); } List<Object[]> params = new ArrayList<Object[]>(); for (SslContext sc : serverContexts) { for (SslContext cc : clientContexts) { for (int i = 0; i < 32; i++) { params.add(new Object[] {sc, cc}); } } } return params; }
@Override protected void encode(ChannelHandlerContext ctx, SingleResponse response, List<Object> out) throws WeixinException { String content = response.toContent(); ctx.writeAndFlush(HttpUtil.createHttpResponse(content, ServerToolkits.CONTENTTYPE$TEXT_PLAIN)); logger.debug("encode single response:{}", content); }
private static void safeClose(OutputStream out) { try { out.close(); } catch (IOException e) { logger.warn("Failed to close a stream.", e); } }
private static void safeClose(InputStream in) { try { in.close(); } catch (IOException e) { logger.warn("Failed to close a stream.", e); } }
private void register( AfterBeanDiscovery afterBeanDiscovery, Set<Annotation> qualifiers, Bean<?> bean) { LOGGER.info( String.format( "Registering bean '%s' with qualifiers %s.", bean.getBeanClass().getName(), qualifiers)); afterBeanDiscovery.addBean(bean); }
/** * Create a new instance * * @param parent the {@link Channel} which is the parent of this {@link NioSctpChannel} or {@code * null}. * @param sctpChannel the underlying {@link SctpChannel} */ public NioSctpChannel(Channel parent, SctpChannel sctpChannel) { super(parent, sctpChannel, SelectionKey.OP_READ); try { sctpChannel.configureBlocking(false); config = new NioSctpChannelConfig(this, sctpChannel); notificationHandler = new SctpNotificationHandler(this); } catch (IOException e) { try { sctpChannel.close(); } catch (IOException e2) { if (logger.isWarnEnabled()) { logger.warn("Failed to close a partially initialized sctp channel.", e2); } } throw new ChannelException("Failed to enter non-blocking mode.", e); } }
/** Notify all the handshake futures about the successfully handshake */ private void setHandshakeSuccess() { // Work around the JVM crash which occurs when a cipher suite with GCM enabled. final String cipherSuite = String.valueOf(engine.getSession().getCipherSuite()); if (!wantsDirectBuffer && (cipherSuite.contains("_GCM_") || cipherSuite.contains("-GCM-"))) { wantsInboundHeapBuffer = true; } handshakePromise.trySuccess(ctx.channel()); if (logger.isDebugEnabled()) { logger.debug("{} HANDSHAKEN: {}", ctx.channel(), engine.getSession().getCipherSuite()); } ctx.fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS); if (readDuringHandshake && !ctx.channel().config().isAutoRead()) { readDuringHandshake = false; ctx.read(); } }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (ignoreException(cause)) { // It is safe to ignore the 'connection reset by peer' or // 'broken pipe' error after sending close_notify. if (logger.isDebugEnabled()) { logger.debug( "Swallowing a harmless 'connection reset by peer / broken pipe' error that occurred " + "while writing close_notify in response to the peer's close_notify", cause); } // Close the connection explicitly just in case the transport // did not close the connection automatically. if (ctx.channel().isActive()) { ctx.close(); } } else { ctx.fireExceptionCaught(cause); } }
public void send(ByteBuf msg) throws Exception { byte[] arr = msg.array(); byte[] buf = new byte[arr.length + id.length]; System.arraycopy(id, 0, buf, 0, id.length); System.arraycopy(arr, 0, buf, id.length, arr.length); ByteBuf bbuf = Unpooled.wrappedBuffer(buf); if (debug && logger != null) logger.info("discovery send " + new String(bbuf.array())); datagramChannel.writeAndFlush(new DatagramPacket(bbuf, multicastAddress)).sync(); // datagramChannel.writeAndFlush(buf, multicastAddress); }
/** * Implementation of a an observer which checks for RedisURI beans and stores them in {@link * #redisUris} for later association with corresponding repository beans. * * @param <T> The type. * @param processBean The annotated type as defined by CDI. */ @SuppressWarnings("unchecked") <T> void processBean(@Observes ProcessBean<T> processBean) { Bean<T> bean = processBean.getBean(); for (Type type : bean.getTypes()) { // Check if the bean is an RedisURI. if (type instanceof Class<?> && RedisURI.class.isAssignableFrom((Class<?>) type)) { Set<Annotation> qualifiers = new HashSet<Annotation>(bean.getQualifiers()); if (bean.isAlternative() || !redisUris.containsKey(qualifiers)) { LOGGER.debug( String.format( "Discovered '%s' with qualifiers %s.", RedisURI.class.getName(), qualifiers)); redisUris.put(qualifiers, (Bean<RedisURI>) bean); } } } }
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvt = (SslHandshakeCompletionEvent) evt; if (handshakeCounter == 0) { handshakeCounter++; if (handshakeEvt.cause() != null) { logger.warn("Handshake failed:", handshakeEvt.cause()); } assertSame(SslHandshakeCompletionEvent.SUCCESS, evt); } else { if (ctx.channel().parent() == null) { assertTrue(handshakeEvt.cause() instanceof ClosedChannelException); } } } }
private synchronized void registerActorClasses() { if (actorClasses.isEmpty()) { try { final ClassLoader classLoader = userClassLoader != null ? userClassLoader : this.getClass().getClassLoader(); ClassLoaderUtil.accept( (URLClassLoader) classLoader, new ClassLoaderUtil.Visitor() { @Override public final void visit(String resource, URL url, ClassLoader cl) { if (packagePrefixes != null) { boolean found = false; for (final String packagePrefix : packagePrefixes) { if (packagePrefix != null && resource.startsWith(packagePrefix.replace('.', '/'))) { found = true; break; } } if (!found) return; } if (!ClassLoaderUtil.isClassFile(resource)) return; final String className = ClassLoaderUtil.resourceToClass(resource); try (final InputStream is = cl.getResourceAsStream(resource)) { if (AnnotationUtil.hasClassAnnotation(WebActor.class, is)) registerWebActor(cl.loadClass(className)); } catch (final IOException | ClassNotFoundException e) { log.error( "Exception while scanning class " + className + " for WebActor annotation", e); throw new RuntimeException(e); } } private void registerWebActor(Class<?> c) { actorClasses.add(c); } }); } catch (final IOException e) { log.error("IOException while scanning classes for WebActor annotation", e); } } }
/** Notify all the handshake futures about the failure during the handshake. */ private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause) { // Release all resources such as internal buffers that SSLEngine // is managing. engine.closeOutbound(); try { engine.closeInbound(); } catch (SSLException e) { // only log in debug mode as it most likely harmless and latest chrome still trigger // this all the time. // // See https://github.com/netty/netty/issues/1340 String msg = e.getMessage(); if (msg == null || !msg.contains("possible truncation attack")) { logger.debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e); } } notifyHandshakeFailure(cause); pendingUnencryptedWrites.removeAndFailAll(cause); }
@Override protected void encode(ChannelHandlerContext ctx, WeixinResponse response, List<Object> out) throws WeixinException { WeixinMessageTransfer messageTransfer = ctx.channel().attr(ServerToolkits.MESSAGE_TRANSFER_KEY).get(); EncryptType encryptType = messageTransfer.getEncryptType(); StringBuilder content = new StringBuilder(); content.append("<xml>"); content.append( String.format( "<ToUserName><![CDATA[%s]]></ToUserName>", messageTransfer.getFromUserName())); content.append( String.format( "<FromUserName><![CDATA[%s]]></FromUserName>", messageTransfer.getToUserName())); content.append( String.format( "<CreateTime><![CDATA[%d]]></CreateTime>", System.currentTimeMillis() / 1000l)); content.append(String.format("<MsgType><![CDATA[%s]]></MsgType>", response.getMsgType())); content.append(response.toContent()); content.append("</xml>"); if (encryptType == EncryptType.AES) { AesToken aesToken = messageTransfer.getAesToken(); String nonce = ServerToolkits.generateRandomString(32); String timestamp = Long.toString(System.currentTimeMillis() / 1000l); String encrtypt = MessageUtil.aesEncrypt(aesToken.getWeixinId(), aesToken.getAesKey(), content.toString()); String msgSignature = MessageUtil.signature(aesToken.getToken(), nonce, timestamp, encrtypt); content.delete(0, content.length()); content.append("<xml>"); content.append(String.format("<Nonce><![CDATA[%s]]></Nonce>", nonce)); content.append(String.format("<TimeStamp><![CDATA[%s]]></TimeStamp>", timestamp)); content.append(String.format("<MsgSignature><![CDATA[%s]]></MsgSignature>", msgSignature)); content.append(String.format("<Encrypt><![CDATA[%s]]></Encrypt>", encrtypt)); content.append("</xml>"); } ctx.writeAndFlush( HttpUtil.createHttpResponse( content.toString(), OK, ServerToolkits.CONTENTTYPE$APPLICATION_XML)); logger.info("{} encode weixin response:{}", encryptType, content); }
public Message proc(Message msg, ChannelHandlerContext ctx) { String clientId = MemPool.getClientId(ctx.channel()); if (clientId == null) { return DISCONNECT; } PublishMessage pm = (PublishMessage) msg; Set<ChannelEntity> channelEntitys = MemPool.getChannelByTopics(pm.getTopic()); if (channelEntitys == null) { return null; } for (ChannelEntity channelEntity : channelEntitys) { logger.debug( "PUBLISH to ChannelEntity topic = " + pm.getTopic() + " payload = " + pm.getDataAsString()); channelEntity.write(pm); } return null; }
/** * Create a new instance from the given {@link Socket} * * @param parent the parent {@link Channel} which was used to create this instance. This can be * null if the {@link} has no parent as it was created by your self. * @param socket the {@link Socket} which is used by this instance */ public OioSocketChannel(Channel parent, EventLoop eventLoop, Socket socket) { super(parent, eventLoop); this.socket = socket; config = new DefaultOioSocketChannelConfig(this, socket); boolean success = false; try { if (socket.isConnected()) { activate(socket.getInputStream(), socket.getOutputStream()); } socket.setSoTimeout(SO_TIMEOUT); success = true; } catch (Exception e) { throw new ChannelException("failed to initialize a socket", e); } finally { if (!success) { try { socket.close(); } catch (IOException e) { logger.warn("Failed to close a socket.", e); } } } }
@Override public final void close(Throwable t) { log.error("Exception while closing HTTP adapter", t); if (actor != null) actor.die(t); }
public LettuceCdiExtension() { LOGGER.info("Activating CDI extension for lettuce."); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { ctx.close(); logger.error("catch the exception:", cause); }
static { InternalLogger logger = InternalLoggerFactory.getInstance(SocketConnectionAttemptTest.class); logger.debug("-Dio.netty.testsuite.badHost: {}", BAD_HOST); logger.debug("-Dio.netty.testsuite.badPort: {}", BAD_PORT); }
@Test public void testSpdyServerSessionHandlerGoAway() { logger.info("Running: testSpdyServerSessionHandlerGoAway v3.1"); testSpdySessionHandlerGoAway(SpdyVersion.SPDY_3_1, true); }
@Test public void testSpdyClientSessionHandlerGoAway() { logger.info("Running: testSpdyClientSessionHandlerGoAway v3.1"); testSpdySessionHandlerGoAway(SpdyVersion.SPDY_3_1, false); }
public boolean isWarnEnabled() { return _log.isWarnEnabled(); }