Java Code Examples for org.jboss.netty.handler.ssl.SslHandler

The following examples show how to use org.jboss.netty.handler.ssl.SslHandler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: hadoop   Source File: ShuffleHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
  ChannelPipeline pipeline = Channels.pipeline();
  if (sslFactory != null) {
    pipeline.addLast("ssl", new SslHandler(sslFactory.createSSLEngine()));
  }
  pipeline.addLast("decoder", new HttpRequestDecoder());
  pipeline.addLast("aggregator", new HttpChunkAggregator(1 << 16));
  pipeline.addLast("encoder", new HttpResponseEncoder());
  pipeline.addLast("chunking", new ChunkedWriteHandler());
  pipeline.addLast("shuffle", SHUFFLE);
  return pipeline;
  // TODO factor security manager into pipeline
  // TODO factor out encode/decode to permit binary shuffle
  // TODO factor out decode of index to permit alt. models
}
 
Example 2
Source Project: big-c   Source File: ShuffleHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
  ChannelPipeline pipeline = Channels.pipeline();
  if (sslFactory != null) {
    pipeline.addLast("ssl", new SslHandler(sslFactory.createSSLEngine()));
  }
  pipeline.addLast("decoder", new HttpRequestDecoder());
  pipeline.addLast("aggregator", new HttpChunkAggregator(1 << 16));
  pipeline.addLast("encoder", new HttpResponseEncoder());
  pipeline.addLast("chunking", new ChunkedWriteHandler());
  pipeline.addLast("shuffle", SHUFFLE);
  return pipeline;
  // TODO factor security manager into pipeline
  // TODO factor out encode/decode to permit binary shuffle
  // TODO factor out decode of index to permit alt. models
}
 
Example 3
@Override
public ChannelPipeline getPipeline() throws Exception {
    ChannelPipeline pipeline =  super.getPipeline();

    if (isSSLSocket()) {
        // We need to set clientMode to false.
        // See https://issues.apache.org/jira/browse/JAMES-1025
        SSLEngine engine = getSSLContext().createSSLEngine();
        engine.setUseClientMode(false);
        if (enabledCipherSuites != null && enabledCipherSuites.length > 0) {
            engine.setEnabledCipherSuites(enabledCipherSuites);
        }
        pipeline.addFirst(HandlerConstants.SSL_HANDLER, new SslHandler(engine));
    }
    return pipeline;
}
 
Example 4
Source Project: james-project   Source File: NettyImapSession.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean startTLS() {
    if (!supportStartTLS()) {
        return false;
    }
    channel.setReadable(false);

    SslHandler filter = new SslHandler(sslContext.createSSLEngine(), false);
    filter.getEngine().setUseClientMode(false);
    if (enabledCipherSuites != null && enabledCipherSuites.length > 0) {
        filter.getEngine().setEnabledCipherSuites(enabledCipherSuites);
    }
    channel.getPipeline().addFirst(SSL_HANDLER, filter);

    channel.setReadable(true);

    return true;
}
 
Example 5
Source Project: james-project   Source File: ChannelImapResponseWriter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void write(Literal literal) throws IOException {
    if (channel.isConnected()) {
        InputStream in = literal.getInputStream();
        if (in instanceof FileInputStream && channel.getFactory() instanceof NioServerSocketChannelFactory) {
            FileChannel fc = ((FileInputStream) in).getChannel();
            // Zero-copy is only possible if no SSL/TLS  and no COMPRESS is in place
            //
            // See JAMES-1305 and JAMES-1306
            ChannelPipeline cp = channel.getPipeline();
            if (zeroCopy && cp.get(SslHandler.class) == null && cp.get(ZlibEncoder.class) == null) {
                channel.write(new DefaultFileRegion(fc, fc.position(), literal.size()));
            } else {
                channel.write(new ChunkedNioFile(fc, 8192));
            }
        } else {
            channel.write(new ChunkedStream(literal.getInputStream()));
        }
    }
}
 
Example 6
Source Project: tajo   Source File: TajoPullServerService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
  ChannelPipeline pipeline = Channels.pipeline();
  if (sslFactory != null) {
    pipeline.addLast("ssl", new SslHandler(sslFactory.createSSLEngine()));
  }
  int maxChunkSize = getConfig().getInt(ConfVars.SHUFFLE_FETCHER_CHUNK_MAX_SIZE.varname,
      ConfVars.SHUFFLE_FETCHER_CHUNK_MAX_SIZE.defaultIntVal);
  pipeline.addLast("codec", new HttpServerCodec(maxUrlLength, 8192, maxChunkSize));
  pipeline.addLast("aggregator", new HttpChunkAggregator(1 << 16));
  pipeline.addLast("chunking", new ChunkedWriteHandler());
  pipeline.addLast("shuffle", PullServer);
  return pipeline;
  // TODO factor security manager into pipeline
  // TODO factor out encode/decode to permit binary shuffle
  // TODO factor out decode of index to permit alt. models
}
 
Example 7
Source Project: incubator-tajo   Source File: HttpDataServerHandler.java    License: Apache License 2.0 6 votes vote down vote up
private ChannelFuture sendFile(ChannelHandlerContext ctx, Channel ch, FileChunk file) throws IOException {
  RandomAccessFile raf;
  try {
    raf = new RandomAccessFile(file.getFile(), "r");
  } catch (FileNotFoundException fnfe) {
    return null;
  }

  ChannelFuture writeFuture;
  if (ch.getPipeline().get(SslHandler.class) != null) {
    // Cannot use zero-copy with HTTPS.
    writeFuture = ch.write(new ChunkedFile(raf, file.startOffset(), file.length(), 8192));
  } else {
    // No encryption - use zero-copy.
    final FileRegion region = new DefaultFileRegion(raf.getChannel(), file.startOffset(), file.length());
    writeFuture = ch.write(region);
    writeFuture.addListener(new ChannelFutureListener() {
      public void operationComplete(ChannelFuture future) {
        region.releaseExternalResources();
      }
    });
  }

  return writeFuture;
}
 
Example 8
Source Project: incubator-tajo   Source File: TajoPullServerService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
  ChannelPipeline pipeline = Channels.pipeline();
  if (sslFactory != null) {
    pipeline.addLast("ssl", new SslHandler(sslFactory.createSSLEngine()));
  }
  pipeline.addLast("decoder", new HttpRequestDecoder());
  pipeline.addLast("aggregator", new HttpChunkAggregator(1 << 16));
  pipeline.addLast("encoder", new HttpResponseEncoder());
  pipeline.addLast("chunking", new ChunkedWriteHandler());
  pipeline.addLast("shuffle", PullServer);
  return pipeline;
  // TODO factor security manager into pipeline
  // TODO factor out encode/decode to permit binary shuffle
  // TODO factor out decode of index to permit alt. models
}
 
Example 9
Source Project: incubator-tajo   Source File: PullServerAuxService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
  ChannelPipeline pipeline = Channels.pipeline();
  if (sslFactory != null) {
    pipeline.addLast("ssl", new SslHandler(sslFactory.createSSLEngine()));
  }
  pipeline.addLast("decoder", new HttpRequestDecoder());
  pipeline.addLast("aggregator", new HttpChunkAggregator(1 << 16));
  pipeline.addLast("encoder", new HttpResponseEncoder());
  pipeline.addLast("chunking", new ChunkedWriteHandler());
  pipeline.addLast("shuffle", PullServer);
  return pipeline;
  // TODO factor security manager into pipeline
  // TODO factor out encode/decode to permit binary shuffle
  // TODO factor out decode of index to permit alt. models
}
 
Example 10
Source Project: mt-flume   Source File: AvroSource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
  ChannelPipeline pipeline = Channels.pipeline();
  if (enableCompression) {
    ZlibEncoder encoder = new ZlibEncoder(6);
    pipeline.addFirst("deflater", encoder);
    pipeline.addFirst("inflater", new ZlibDecoder());
  }
  if (enableSsl) {
    SSLEngine sslEngine = createServerSSLContext().createSSLEngine();
    sslEngine.setUseClientMode(false);
    // addFirst() will make SSL handling the first stage of decoding
    // and the last stage of encoding this must be added after
    // adding compression handling above
    pipeline.addFirst("ssl", new SslHandler(sslEngine));
  }
  return pipeline;
}
 
Example 11
Source Project: mt-flume   Source File: TestAvroSource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SocketChannel newChannel(ChannelPipeline pipeline) {
  try {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[]{new PermissiveTrustManager()},
                    null);
    SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(true);
    // addFirst() will make SSL handling the first stage of decoding
    // and the last stage of encoding
    pipeline.addFirst("ssl", new SslHandler(sslEngine));
    return super.newChannel(pipeline);
  } catch (Exception ex) {
    throw new RuntimeException("Cannot create SSL channel", ex);
  }
}
 
Example 12
Source Project: usergrid   Source File: WebSocketServerPipelineFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
    // Create a default pipeline implementation.
    ChannelPipeline pipeline = pipeline();
    if ( ssl ) {
        SSLEngine sslEngine = WebSocketSslContextFactory.getServerContext().createSSLEngine();
        sslEngine.setUseClientMode( false );
        pipeline.addLast( "ssl", new SslHandler( sslEngine ) );
    }
    pipeline.addLast( "decoder", new HttpRequestDecoder() );
    pipeline.addLast( "aggregator", new HttpChunkAggregator( 65536 ) );
    pipeline.addLast( "encoder", new HttpResponseEncoder() );
    pipeline.addLast( "execution", executionHandler );
    pipeline.addLast( "handler", new WebSocketChannelHandler( emf, smf, management, securityManager, ssl ) );
    return pipeline;
}
 
Example 13
Source Project: tez   Source File: ShuffleHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
  ChannelPipeline pipeline = Channels.pipeline();
  if (sslFactory != null) {
    pipeline.addLast("ssl", new SslHandler(sslFactory.createSSLEngine()));
  }
  pipeline.addLast("decoder", new HttpRequestDecoder());
  pipeline.addLast("aggregator", new HttpChunkAggregator(1 << 16));
  pipeline.addLast("encoder", new HttpResponseEncoder());
  pipeline.addLast("chunking", new ChunkedWriteHandler());
  pipeline.addLast("shuffle", SHUFFLE);
  pipeline.addLast("idle", idleStateHandler);
  pipeline.addLast(TIMEOUT_HANDLER, new TimeoutHandler());
  return pipeline;
  // TODO factor security manager into pipeline
  // TODO factor out encode/decode to permit binary shuffle
  // TODO factor out decode of index to permit alt. models
}
 
Example 14
Source Project: ck   Source File: NettyAsyncHttpProvider.java    License: Apache License 2.0 5 votes vote down vote up
void configure(final boolean useSSL, final ConnectListener<?> cl){

		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

			/* @Override */
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline = pipeline();

				if (useSSL){
					try{
						SSLEngine sslEngine = config.getSSLEngine();
						if (sslEngine == null){
							sslEngine = SslUtils.getSSLEngine();
						}
						pipeline.addLast("ssl", new SslHandler(sslEngine));
					} catch (Throwable ex){
						cl.future().abort(ex);
					}
				}

				pipeline.addLast("codec", new HttpClientCodec());

				if (config.isCompressionEnabled()) {
					pipeline.addLast("inflater", new HttpContentDecompressor());
				}
				pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
				return pipeline;
			}
		});
	}
 
Example 15
private void turnSSLon(Channel channel) {
    if (sslContext != null) {
        channel.setReadable(false);
        SslHandler filter = new SslHandler(sslContext.createSSLEngine(), false);
        filter.getEngine().setUseClientMode(false);
        if (enabledCipherSuites != null && enabledCipherSuites.length > 0) {
            filter.getEngine().setEnabledCipherSuites(enabledCipherSuites);
        }
        channel.getPipeline().addFirst(SSL_HANDLER, filter);
        channel.setReadable(true);
    }
}
 
Example 16
Source Project: incubator-tajo   Source File: HttpDataServerHandler.java    License: Apache License 2.0 5 votes vote down vote up
private ChannelFuture sendFile(ChannelHandlerContext ctx,
                               Channel ch,
                               FileChunk file) throws IOException {
  RandomAccessFile raf;
  try {
    raf = new RandomAccessFile(file.getFile(), "r");
  } catch (FileNotFoundException fnfe) {
    return null;
  }

  ChannelFuture writeFuture;
  if (ch.getPipeline().get(SslHandler.class) != null) {
    // Cannot use zero-copy with HTTPS.
    writeFuture = ch.write(new ChunkedFile(raf, file.startOffset(),
        file.length(), 8192));
  } else {
    // No encryption - use zero-copy.
    final FileRegion region = new DefaultFileRegion(raf.getChannel(),
        file.startOffset(), file.length());
    writeFuture = ch.write(region);
    writeFuture.addListener(new ChannelFutureListener() {
      public void operationComplete(ChannelFuture future) {
        region.releaseExternalResources();
      }
    });
  }

  return writeFuture;
}
 
Example 17
Source Project: restcommander   Source File: SslPlayHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    ctx.setAttachment(e.getValue());
    // Get the SslHandler in the current pipeline.
    final SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class);
    sslHandler.setEnableRenegotiation(false);
    // Get notified when SSL handshake is done.
    ChannelFuture handshakeFuture = sslHandler.handshake();
    handshakeFuture.addListener(new SslListener());
}
 
Example 18
public ChannelPipeline getPipeline() throws Exception {

        Integer max = Integer.valueOf(Play.configuration.getProperty("play.netty.maxContentLength", "-1"));
        String mode = Play.configuration.getProperty("play.netty.clientAuth", "none");

        ChannelPipeline pipeline = pipeline();

        // Add SSL handler first to encrypt and decrypt everything.
        SSLEngine engine = SslHttpServerContextFactory.getServerContext().createSSLEngine();
        engine.setUseClientMode(false);
        
        if ("want".equalsIgnoreCase(mode)) {
            engine.setWantClientAuth(true);
        } else if ("need".equalsIgnoreCase(mode)) {
            engine.setNeedClientAuth(true);
        }
        
        engine.setEnableSessionCreation(true);

        pipeline.addLast("flashPolicy", new FlashPolicyHandler());
        pipeline.addLast("ssl", new SslHandler(engine));
        pipeline.addLast("decoder", new HttpRequestDecoder());
        pipeline.addLast("aggregator", new StreamChunkAggregator(max));
        pipeline.addLast("encoder", new HttpResponseEncoder());
        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

        pipeline.addLast("handler", new SslPlayHandler());

        return pipeline;
    }
 
Example 19
Source Project: mt-flume   Source File: TestAvroSink.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
  ChannelPipeline pipeline = Channels.pipeline();
  SSLEngine sslEngine = createServerSSLContext().createSSLEngine();
  sslEngine.setUseClientMode(false);
  pipeline.addLast("ssl", new SslHandler(sslEngine));
  return pipeline;
}
 
Example 20
Source Project: hadoop   Source File: ShuffleHandler.java    License: Apache License 2.0 4 votes vote down vote up
protected ChannelFuture sendMapOutput(ChannelHandlerContext ctx, Channel ch,
    String user, String mapId, int reduce, MapOutputInfo mapOutputInfo)
    throws IOException {
  final IndexRecord info = mapOutputInfo.indexRecord;
  final ShuffleHeader header =
    new ShuffleHeader(mapId, info.partLength, info.rawLength, reduce);
  final DataOutputBuffer dob = new DataOutputBuffer();
  header.write(dob);
  ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
  final File spillfile =
      new File(mapOutputInfo.mapOutputFileName.toString());
  RandomAccessFile spill;
  try {
    spill = SecureIOUtils.openForRandomRead(spillfile, "r", user, null);
  } catch (FileNotFoundException e) {
    LOG.info(spillfile + " not found");
    return null;
  }
  ChannelFuture writeFuture;
  if (ch.getPipeline().get(SslHandler.class) == null) {
    final FadvisedFileRegion partition = new FadvisedFileRegion(spill,
        info.startOffset, info.partLength, manageOsCache, readaheadLength,
        readaheadPool, spillfile.getAbsolutePath(), 
        shuffleBufferSize, shuffleTransferToAllowed);
    writeFuture = ch.write(partition);
    writeFuture.addListener(new ChannelFutureListener() {
        // TODO error handling; distinguish IO/connection failures,
        //      attribute to appropriate spill output
      @Override
      public void operationComplete(ChannelFuture future) {
        if (future.isSuccess()) {
          partition.transferSuccessful();
        }
        partition.releaseExternalResources();
      }
    });
  } else {
    // HTTPS cannot be done with zero copy.
    final FadvisedChunkedFile chunk = new FadvisedChunkedFile(spill,
        info.startOffset, info.partLength, sslFileBufferSize,
        manageOsCache, readaheadLength, readaheadPool,
        spillfile.getAbsolutePath());
    writeFuture = ch.write(chunk);
  }
  metrics.shuffleConnections.incr();
  metrics.shuffleOutputBytes.incr(info.partLength); // optimistic
  return writeFuture;
}
 
Example 21
Source Project: big-c   Source File: ShuffleHandler.java    License: Apache License 2.0 4 votes vote down vote up
protected ChannelFuture sendMapOutput(ChannelHandlerContext ctx, Channel ch,
    String user, String mapId, int reduce, MapOutputInfo mapOutputInfo)
    throws IOException {
  final IndexRecord info = mapOutputInfo.indexRecord;
  final ShuffleHeader header =
    new ShuffleHeader(mapId, info.partLength, info.rawLength, reduce);
  final DataOutputBuffer dob = new DataOutputBuffer();
  header.write(dob);
  ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
  final File spillfile =
      new File(mapOutputInfo.mapOutputFileName.toString());
  RandomAccessFile spill;
  try {
    spill = SecureIOUtils.openForRandomRead(spillfile, "r", user, null);
  } catch (FileNotFoundException e) {
    LOG.info(spillfile + " not found");
    return null;
  }
  ChannelFuture writeFuture;
  if (ch.getPipeline().get(SslHandler.class) == null) {
    final FadvisedFileRegion partition = new FadvisedFileRegion(spill,
        info.startOffset, info.partLength, manageOsCache, readaheadLength,
        readaheadPool, spillfile.getAbsolutePath(), 
        shuffleBufferSize, shuffleTransferToAllowed);
    writeFuture = ch.write(partition);
    writeFuture.addListener(new ChannelFutureListener() {
        // TODO error handling; distinguish IO/connection failures,
        //      attribute to appropriate spill output
      @Override
      public void operationComplete(ChannelFuture future) {
        if (future.isSuccess()) {
          partition.transferSuccessful();
        }
        partition.releaseExternalResources();
      }
    });
  } else {
    // HTTPS cannot be done with zero copy.
    final FadvisedChunkedFile chunk = new FadvisedChunkedFile(spill,
        info.startOffset, info.partLength, sslFileBufferSize,
        manageOsCache, readaheadLength, readaheadPool,
        spillfile.getAbsolutePath());
    writeFuture = ch.write(chunk);
  }
  metrics.shuffleConnections.incr();
  metrics.shuffleOutputBytes.incr(info.partLength); // optimistic
  return writeFuture;
}
 
Example 22
Source Project: james-project   Source File: NettyProtocolTransport.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean isTLSStarted() {
    return channel.getPipeline().get(SslHandler.class) != null;
}
 
Example 23
Source Project: james-project   Source File: NettyProtocolTransport.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Add the {@link SslHandler} to the pipeline and start encrypting after the next written message
 */
private void prepareStartTLS() {
    SslHandler filter = new SslHandler(engine, true);
    filter.getEngine().setUseClientMode(false);
    channel.getPipeline().addFirst(HandlerConstants.SSL_HANDLER, filter);
}
 
Example 24
Source Project: james-project   Source File: ManageSieveServer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected ChannelPipelineFactory createPipelineFactory(final ChannelGroup group) {

    return new ChannelPipelineFactory() {

        private final ChannelGroupHandler groupHandler = new ChannelGroupHandler(group);

        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = pipeline();
            Encryption secure = getEncryption();
            if (secure != null && !secure.isStartTLS()) {
                // We need to set clientMode to false.
                // See https://issues.apache.org/jira/browse/JAMES-1025
                SSLEngine engine = secure.getContext().createSSLEngine();
                engine.setUseClientMode(false);
                pipeline.addFirst(SSL_HANDLER, new SslHandler(engine));

            }
            pipeline.addLast(GROUP_HANDLER, groupHandler);
            pipeline.addLast(CONNECTION_LIMIT_HANDLER, new ConnectionLimitUpstreamHandler(ManageSieveServer.this.connectionLimit));
            pipeline.addLast(CONNECTION_LIMIT_PER_IP_HANDLER, new ConnectionPerIpLimitUpstreamHandler(ManageSieveServer.this.connPerIP));
            // Add the text line decoder which limit the max line length,
            // don't strip the delimiter and use CRLF as delimiter
            // Use a SwitchableDelimiterBasedFrameDecoder, see JAMES-1436
            pipeline.addLast(FRAMER, getFrameHandlerFactory().create(pipeline));
            pipeline.addLast(CONNECTION_COUNT_HANDLER, getConnectionCountHandler());
            pipeline.addLast(CHUNK_WRITE_HANDLER, new ChunkedWriteHandler());

            ExecutionHandler ehandler = getExecutionHandler();
            if (ehandler  != null) {
                pipeline.addLast(EXECUTION_HANDLER, ehandler);

            }
            pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
            pipeline.addLast(CORE_HANDLER, createCoreHandler());
            pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
            return pipeline;
        }

    };
}
 
Example 25
Source Project: james-project   Source File: IMAPServer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected ChannelPipelineFactory createPipelineFactory(final ChannelGroup group) {
    
    return new ChannelPipelineFactory() {
        
        private final ChannelGroupHandler groupHandler = new ChannelGroupHandler(group);
        private final HashedWheelTimer timer = new HashedWheelTimer();
        
        private final TimeUnit timeoutUnit = TimeUnit.SECONDS;

        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = pipeline();
            pipeline.addLast(GROUP_HANDLER, groupHandler);
            pipeline.addLast("idleHandler", new IdleStateHandler(timer, 0, 0, timeout, timeoutUnit));
            pipeline.addLast(TIMEOUT_HANDLER, new ImapIdleStateHandler());
            pipeline.addLast(CONNECTION_LIMIT_HANDLER, new ConnectionLimitUpstreamHandler(IMAPServer.this.connectionLimit));

            pipeline.addLast(CONNECTION_LIMIT_PER_IP_HANDLER, new ConnectionPerIpLimitUpstreamHandler(IMAPServer.this.connPerIP));

            // Add the text line decoder which limit the max line length,
            // don't strip the delimiter and use CRLF as delimiter
            // Use a SwitchableDelimiterBasedFrameDecoder, see JAMES-1436
            pipeline.addLast(FRAMER, getFrameHandlerFactory().create(pipeline));
           
            Encryption secure = getEncryption();
            if (secure != null && !secure.isStartTLS()) {
                // We need to set clientMode to false.
                // See https://issues.apache.org/jira/browse/JAMES-1025
                SSLEngine engine = secure.getContext().createSSLEngine();
                engine.setUseClientMode(false);
                pipeline.addFirst(SSL_HANDLER, new SslHandler(engine));

            }
            pipeline.addLast(CONNECTION_COUNT_HANDLER, getConnectionCountHandler());

            pipeline.addLast(CHUNK_WRITE_HANDLER, new ChunkedWriteHandler());

            ExecutionHandler ehandler = getExecutionHandler();
            if (ehandler  != null) {
                pipeline.addLast(EXECUTION_HANDLER, ehandler);

            }
            pipeline.addLast(REQUEST_DECODER, new ImapRequestFrameDecoder(decoder, inMemorySizeLimit, literalSizeLimit));

            pipeline.addLast(CORE_HANDLER, createCoreHandler());
            return pipeline;
        }

    };
}
 
Example 26
Source Project: mt-flume   Source File: NettyAvroRpcClient.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public SocketChannel newChannel(ChannelPipeline pipeline) {
  TrustManager[] managers;
  try {
    if (enableCompression) {
      ZlibEncoder encoder = new ZlibEncoder(compressionLevel);
      pipeline.addFirst("deflater", encoder);
      pipeline.addFirst("inflater", new ZlibDecoder());
    }
    if (enableSsl) {
      if (trustAllCerts) {
        logger.warn("No truststore configured, setting TrustManager to accept"
            + " all server certificates");
        managers = new TrustManager[] { new PermissiveTrustManager() };
      } else {
        KeyStore keystore = null;

        if (truststore != null) {
          if (truststorePassword == null) {
            throw new NullPointerException("truststore password is null");
          }
          InputStream truststoreStream = new FileInputStream(truststore);
          keystore = KeyStore.getInstance(truststoreType);
          keystore.load(truststoreStream, truststorePassword.toCharArray());
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        // null keystore is OK, with SunX509 it defaults to system CA Certs
        // see http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#X509TrustManager
        tmf.init(keystore);
        managers = tmf.getTrustManagers();
      }

      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, managers, null);
      SSLEngine sslEngine = sslContext.createSSLEngine();
      sslEngine.setUseClientMode(true);
      // addFirst() will make SSL handling the first stage of decoding
      // and the last stage of encoding this must be added after
      // adding compression handling above
      pipeline.addFirst("ssl", new SslHandler(sslEngine));
    }

    return super.newChannel(pipeline);
  } catch (Exception ex) {
    logger.error("Cannot create SSL channel", ex);
    throw new RuntimeException("Cannot create SSL channel", ex);
  }
}
 
Example 27
Source Project: tez   Source File: ShuffleHandler.java    License: Apache License 2.0 4 votes vote down vote up
protected ChannelFuture sendMapOutput(ChannelHandlerContext ctx, Channel ch,
                                      String user, String mapId, Range reduceRange, MapOutputInfo outputInfo)
    throws IOException {
  TezIndexRecord firstIndex = null;
  TezIndexRecord lastIndex = null;

  DataOutputBuffer dobRange = new DataOutputBuffer();
  // Indicate how many record to be written
  WritableUtils.writeVInt(dobRange, reduceRange.getLast() - reduceRange.getFirst() + 1);
  ch.write(wrappedBuffer(dobRange.getData(), 0, dobRange.getLength()));
  for (int reduce = reduceRange.getFirst(); reduce <= reduceRange.getLast(); reduce++) {
    TezIndexRecord index = outputInfo.getIndex(reduce);
    // Records are only valid if they have a non-zero part length
    if (index.getPartLength() != 0) {
      if (firstIndex == null) {
        firstIndex = index;
      }
      lastIndex = index;
    }

    ShuffleHeader header = new ShuffleHeader(mapId, index.getPartLength(), index.getRawLength(), reduce);
    DataOutputBuffer dob = new DataOutputBuffer();
    header.write(dob);
    // Free the memory needed to store the spill and index records
    ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
  }
  outputInfo.finish();

  final long rangeOffset = firstIndex.getStartOffset();
  final long rangePartLength = lastIndex.getStartOffset() + lastIndex.getPartLength() - firstIndex.getStartOffset();
  final File spillFile = new File(outputInfo.mapOutputFileName.toString());
  RandomAccessFile spill;
  try {
    spill = SecureIOUtils.openForRandomRead(spillFile, "r", user, null);
  } catch (FileNotFoundException e) {
    LOG.info(spillFile + " not found");
    return null;
  }
  ChannelFuture writeFuture;
  if (ch.getPipeline().get(SslHandler.class) == null) {
    final FadvisedFileRegion partition = new FadvisedFileRegion(spill,
        rangeOffset, rangePartLength, manageOsCache, readaheadLength,
        readaheadPool, spillFile.getAbsolutePath(),
        shuffleBufferSize, shuffleTransferToAllowed);
    writeFuture = ch.write(partition);
    writeFuture.addListener(new ChannelFutureListener() {
        // TODO error handling; distinguish IO/connection failures,
        //      attribute to appropriate spill output
      @Override
      public void operationComplete(ChannelFuture future) {
        if (future.isSuccess()) {
          partition.transferSuccessful();
        }
        partition.releaseExternalResources();
      }
    });
  } else {
    // HTTPS cannot be done with zero copy.
    final FadvisedChunkedFile chunk = new FadvisedChunkedFile(spill,
        rangeOffset, rangePartLength, sslFileBufferSize,
        manageOsCache, readaheadLength, readaheadPool,
        spillFile.getAbsolutePath());
    writeFuture = ch.write(chunk);
  }
  metrics.shuffleConnections.incr();
  metrics.shuffleOutputBytes.incr(rangePartLength); // optimistic
  return writeFuture;
}