Search in sources :

Example 56 with Server

use of org.eclipse.jetty.server.Server in project jetty.project by eclipse.

the class SslConnectionFactoryTest method before.

@Before
public void before() throws Exception {
    String keystorePath = "src/test/resources/keystore";
    File keystoreFile = new File(keystorePath);
    if (!keystoreFile.exists())
        throw new FileNotFoundException(keystoreFile.getAbsolutePath());
    _server = new Server();
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    http_config.setSecurePort(8443);
    http_config.setOutputBufferSize(32768);
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
    sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
    ServerConnector https = _connector = new ServerConnector(_server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https_config));
    https.setPort(0);
    https.setIdleTimeout(30000);
    _server.addConnector(https);
    _server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            response.setStatus(200);
            response.getWriter().write("url=" + request.getRequestURI() + "\nhost=" + request.getServerName());
            response.flushBuffer();
        }
    });
    _server.start();
    _port = https.getLocalPort();
}
Also used : SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) FileNotFoundException(java.io.FileNotFoundException) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) IOException(java.io.IOException) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) File(java.io.File) Before(org.junit.Before)

Example 57 with Server

use of org.eclipse.jetty.server.Server in project jetty.project by eclipse.

the class SslContextFactoryReloadTest method testReloadWhileServing.

@Test
public void testReloadWhileServing() throws Exception {
    start(new EchoHandler());
    Scheduler scheduler = new ScheduledExecutorScheduler();
    scheduler.start();
    try {
        SSLContext ctx = SSLContext.getInstance("TLSv1.2");
        ctx.init(null, SslContextFactory.TRUST_ALL_CERTS, null);
        SSLSocketFactory socketFactory = ctx.getSocketFactory();
        // Perform 4 reloads while connections are being served.
        AtomicInteger reloads = new AtomicInteger(4);
        long reloadPeriod = 500;
        AtomicBoolean running = new AtomicBoolean(true);
        scheduler.schedule(new Runnable() {

            @Override
            public void run() {
                if (reloads.decrementAndGet() == 0) {
                    running.set(false);
                } else {
                    try {
                        sslContextFactory.reload(sslContextFactory -> {
                            if (sslContextFactory.getKeyStorePath().endsWith(KEYSTORE_1))
                                sslContextFactory.setKeyStorePath(KEYSTORE_2);
                            else
                                sslContextFactory.setKeyStorePath(KEYSTORE_1);
                        });
                        scheduler.schedule(this, reloadPeriod, TimeUnit.MILLISECONDS);
                    } catch (Exception x) {
                        running.set(false);
                        reloads.set(-1);
                    }
                }
            }
        }, reloadPeriod, TimeUnit.MILLISECONDS);
        byte[] content = new byte[16 * 1024];
        while (running.get()) {
            try (SSLSocket client = (SSLSocket) socketFactory.createSocket("localhost", connector.getLocalPort())) {
                // We need to invalidate the session every time we open a new SSLSocket.
                // This is because when the client uses session resumption, it caches
                // the server certificates and then checks that it is the same during
                // a new TLS handshake. If the SslContextFactory is reloaded during the
                // TLS handshake, the client will see the new certificate and blow up.
                // Note that browsers can handle this case better: they will just not
                // use session resumption and fallback to the normal TLS handshake.
                client.getSession().invalidate();
                String request1 = "" + "POST / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Content-Length: " + content.length + "\r\n" + "\r\n";
                OutputStream outputStream = client.getOutputStream();
                outputStream.write(request1.getBytes(StandardCharsets.UTF_8));
                outputStream.write(content);
                outputStream.flush();
                InputStream inputStream = client.getInputStream();
                HttpTester.Response response1 = HttpTester.parseResponse(HttpTester.from(inputStream));
                Assert.assertNotNull(response1);
                Assert.assertThat(response1.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
                String request2 = "" + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n";
                outputStream.write(request2.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
                HttpTester.Response response2 = HttpTester.parseResponse(HttpTester.from(inputStream));
                Assert.assertNotNull(response2);
                Assert.assertThat(response2.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
            }
        }
        Assert.assertEquals(0, reloads.get());
    } finally {
        scheduler.stop();
    }
}
Also used : Request(org.eclipse.jetty.server.Request) HttpTester(org.eclipse.jetty.http.HttpTester) Handler(org.eclipse.jetty.server.Handler) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) SSLContext(javax.net.ssl.SSLContext) ServletException(javax.servlet.ServletException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HttpVersion(org.eclipse.jetty.http.HttpVersion) Scheduler(org.eclipse.jetty.util.thread.Scheduler) SSLSocket(javax.net.ssl.SSLSocket) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) HttpStatus(org.eclipse.jetty.http.HttpStatus) Server(org.eclipse.jetty.server.Server) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) ScheduledExecutorScheduler(org.eclipse.jetty.util.thread.ScheduledExecutorScheduler) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Test(org.junit.Test) IO(org.eclipse.jetty.util.IO) StandardCharsets(java.nio.charset.StandardCharsets) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) TimeUnit(java.util.concurrent.TimeUnit) HttpMethod(org.eclipse.jetty.http.HttpMethod) ServerConnector(org.eclipse.jetty.server.ServerConnector) Assert(org.junit.Assert) InputStream(java.io.InputStream) Scheduler(org.eclipse.jetty.util.thread.Scheduler) ScheduledExecutorScheduler(org.eclipse.jetty.util.thread.ScheduledExecutorScheduler) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) OutputStream(java.io.OutputStream) ScheduledExecutorScheduler(org.eclipse.jetty.util.thread.ScheduledExecutorScheduler) SSLContext(javax.net.ssl.SSLContext) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) HttpTester(org.eclipse.jetty.http.HttpTester) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Test(org.junit.Test)

Example 58 with Server

use of org.eclipse.jetty.server.Server in project jetty.project by eclipse.

the class StatisticsServlet method init.

public void init() throws ServletException {
    ServletContext context = getServletContext();
    ContextHandler.Context scontext = (ContextHandler.Context) context;
    Server _server = scontext.getContextHandler().getServer();
    Handler handler = _server.getChildHandlerByClass(StatisticsHandler.class);
    if (handler != null) {
        _statsHandler = (StatisticsHandler) handler;
    } else {
        LOG.warn("Statistics Handler not installed!");
        return;
    }
    _memoryBean = ManagementFactory.getMemoryMXBean();
    _connectors = _server.getConnectors();
    if (getInitParameter("restrictToLocalhost") != null) {
        _restrictToLocalhost = "true".equals(getInitParameter("restrictToLocalhost"));
    }
}
Also used : ServletContext(javax.servlet.ServletContext) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) Server(org.eclipse.jetty.server.Server) ServletContext(javax.servlet.ServletContext) Handler(org.eclipse.jetty.server.Handler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler)

Example 59 with Server

use of org.eclipse.jetty.server.Server in project jetty.project by eclipse.

the class SessionCookieTest method testSecureSessionCookie.

@Test
public void testSecureSessionCookie() throws Exception {
    Server server = new Server();
    MockSessionIdManager idMgr = new MockSessionIdManager(server);
    idMgr.setWorkerName("node1");
    SessionHandler mgr = new SessionHandler();
    MockSessionStore store = new MockSessionStore(mgr);
    store.setSessionDataStore(new NullSessionDataStore());
    mgr.setSessionCache(store);
    mgr.setSessionIdManager(idMgr);
    long now = System.currentTimeMillis();
    Session session = new Session(null, new SessionData("123", "_foo", "0.0.0.0", now, now, now, 30));
    SessionCookieConfig sessionCookieConfig = mgr.getSessionCookieConfig();
    sessionCookieConfig.setSecure(true);
    //sessionCookieConfig.secure == true, always mark cookie as secure, irrespective of if requestIsSecure
    HttpCookie cookie = mgr.getSessionCookie(session, "/foo", true);
    assertTrue(cookie.isSecure());
    //sessionCookieConfig.secure == true, always mark cookie as secure, irrespective of if requestIsSecure
    cookie = mgr.getSessionCookie(session, "/foo", false);
    assertTrue(cookie.isSecure());
    //sessionCookieConfig.secure==false, setSecureRequestOnly==true, requestIsSecure==true
    //cookie should be secure: see SessionCookieConfig.setSecure() javadoc
    sessionCookieConfig.setSecure(false);
    cookie = mgr.getSessionCookie(session, "/foo", true);
    assertTrue(cookie.isSecure());
    //sessionCookieConfig.secure=false, setSecureRequestOnly==true, requestIsSecure==false
    //cookie is not secure: see SessionCookieConfig.setSecure() javadoc
    cookie = mgr.getSessionCookie(session, "/foo", false);
    assertFalse(cookie.isSecure());
    //sessionCookieConfig.secure=false, setSecureRequestOnly==false, requestIsSecure==false
    //cookie is not secure: not a secure request
    mgr.setSecureRequestOnly(false);
    cookie = mgr.getSessionCookie(session, "/foo", false);
    assertFalse(cookie.isSecure());
    //sessionCookieConfig.secure=false, setSecureRequestOnly==false, requestIsSecure==true
    //cookie is not secure: not on secured requests and request is secure
    cookie = mgr.getSessionCookie(session, "/foo", true);
    assertFalse(cookie.isSecure());
}
Also used : Server(org.eclipse.jetty.server.Server) SessionCookieConfig(javax.servlet.SessionCookieConfig) HttpCookie(org.eclipse.jetty.http.HttpCookie) Test(org.junit.Test)

Example 60 with Server

use of org.eclipse.jetty.server.Server in project jetty.project by eclipse.

the class SSLCloseTest method testClose.

@Test
public void testClose() throws Exception {
    File keystore = MavenTestingUtils.getTestResourceFile("keystore");
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStoreResource(Resource.newResource(keystore));
    sslContextFactory.setKeyStorePassword("storepwd");
    sslContextFactory.setKeyManagerPassword("keypwd");
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server, sslContextFactory);
    connector.setPort(0);
    server.addConnector(connector);
    server.setHandler(new WriteHandler());
    server.start();
    SSLContext ctx = SSLContext.getInstance("TLSv1.2");
    ctx.init(null, SslContextFactory.TRUST_ALL_CERTS, new java.security.SecureRandom());
    int port = connector.getLocalPort();
    Socket socket = ctx.getSocketFactory().createSocket("localhost", port);
    OutputStream os = socket.getOutputStream();
    os.write(("GET /test HTTP/1.1\r\n" + "Host:test\r\n" + "Connection:close\r\n\r\n").getBytes());
    os.flush();
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
        if (line.trim().length() == 0)
            break;
    }
    Thread.sleep(2000);
    while (in.readLine() != null) Thread.yield();
}
Also used : Server(org.eclipse.jetty.server.Server) InputStreamReader(java.io.InputStreamReader) OutputStream(java.io.OutputStream) SSLContext(javax.net.ssl.SSLContext) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) BufferedReader(java.io.BufferedReader) File(java.io.File) Socket(java.net.Socket) Test(org.junit.Test)

Aggregations

Server (org.eclipse.jetty.server.Server)577 ServerConnector (org.eclipse.jetty.server.ServerConnector)217 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)143 Test (org.junit.Test)119 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)113 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)75 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)73 IOException (java.io.IOException)71 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)67 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)67 File (java.io.File)65 URI (java.net.URI)56 Before (org.junit.Before)50 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)49 BeforeClass (org.junit.BeforeClass)48 ServletException (javax.servlet.ServletException)45 Connector (org.eclipse.jetty.server.Connector)42 LocalConnector (org.eclipse.jetty.server.LocalConnector)42 URL (java.net.URL)39 HttpServletRequest (javax.servlet.http.HttpServletRequest)39