Beispiel #1
0
  // =========================================================================================================
  // HTTPS handling
  private HttpServer createHttpsServer(
      InetSocketAddress pSocketAddress, JolokiaServerConfig pConfig) {
    // initialise the HTTPS server
    try {
      HttpsServer server = HttpsServer.create(pSocketAddress, pConfig.getBacklog());
      SSLContext sslContext = SSLContext.getInstance(pConfig.getSecureSocketProtocol());

      // initialise the keystore
      KeyStore ks = getKeyStore(pConfig);

      // setup the key manager factory
      KeyManagerFactory kmf = getKeyManagerFactory(pConfig);
      kmf.init(ks, pConfig.getKeystorePassword());

      // setup the trust manager factory
      TrustManagerFactory tmf = getTrustManagerFactory(pConfig);
      tmf.init(ks);

      // setup the HTTPS context and parameters
      sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

      // Update the config to filter out bad protocols or ciphers
      pConfig.updateHTTPSSettingsFromContext(sslContext);

      server.setHttpsConfigurator(new JolokiaHttpsConfigurator(sslContext, pConfig));
      return server;
    } catch (GeneralSecurityException e) {
      throw new IllegalStateException("Cannot use keystore for https communication: " + e, e);
    } catch (IOException e) {
      throw new IllegalStateException("Cannot open keystore for https communication: " + e, e);
    }
  }
  private HttpServer httpsServer(InetSocketAddress address)
      throws IOException, GeneralSecurityException {
    // Initialize the keystore
    char[] password = "******".toCharArray();
    ks = KeyStore.getInstance("JKS");
    try (FileInputStream fis = new FileInputStream("UMS.jks")) {
      ks.load(fis, password);
    }

    // Setup the key manager factory
    kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, password);

    // Setup the trust manager factory
    tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    HttpsServer server = HttpsServer.create(address, 0);
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    server.setHttpsConfigurator(
        new HttpsConfigurator(sslContext) {
          @Override
          public void configure(HttpsParameters params) {
            try {
              // initialise the SSL context
              SSLContext c = SSLContext.getDefault();
              SSLEngine engine = c.createSSLEngine();
              params.setNeedClientAuth(true);
              params.setCipherSuites(engine.getEnabledCipherSuites());
              params.setProtocols(engine.getEnabledProtocols());

              // get the default parameters
              SSLParameters defaultSSLParameters = c.getDefaultSSLParameters();
              params.setSSLParameters(defaultSSLParameters);
            } catch (Exception e) {
              LOGGER.debug("https configure error  " + e);
            }
          }
        });
    return server;
  }
Beispiel #3
0
  static HttpServer createDashboardHttpServer(Config config) throws IOException {
    boolean secure = config.isServerSecure();
    HttpServer server;
    if (!secure) {
      server = HttpServer.create();
    } else {
      server = HttpsServer.create();
      SSLContext defaultSslContext;
      try {
        defaultSslContext = SSLContext.getDefault();
      } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
      }
      HttpsConfigurator httpsConf = new HttpsConfigurator(defaultSslContext);
      ((HttpsServer) server).setHttpsConfigurator(httpsConf);
    }
    // The Dashboard is on a separate port to prevent malicious HTML documents
    // in the user's repository from performing admin actions with
    // XMLHttpRequest or the like, as the HTML page will then be blocked by
    // same-origin policies.
    try {
      server.bind(new InetSocketAddress(config.getServerDashboardPort()), 0);
    } catch (BindException ex) {
      log.log(
          Level.WARNING,
          "Server dashboard port {0,number,#} is in use.",
          config.getServerDashboardPort());
      throw ex;
    }

    // Use separate Executor for Dashboard to allow the administrator to
    // investigate why things are going wrong without waiting on the normal work
    // queue.
    int maxThreads = 4;
    Executor executor =
        new ThreadPoolExecutor(
            maxThreads, maxThreads, 10, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>());
    server.setExecutor(executor);

    log.info("dashboard is listening on port #" + server.getAddress().getPort());

    return server;
  }
Beispiel #4
0
  static HttpServer createHttpServer(Config config) throws IOException {
    HttpServer server;
    if (!config.isServerSecure()) {
      server = HttpServer.create();
    } else {
      server = HttpsServer.create();
      try {
        HttpsConfigurator httpsConf =
            new HttpsConfigurator(SSLContext.getDefault()) {
              public void configure(HttpsParameters params) {
                SSLParameters sslParams = getSSLContext().getDefaultSSLParameters();
                // Allow verifying the GSA and other trusted computers.
                sslParams.setWantClientAuth(true);
                params.setSSLParameters(sslParams);
              }
            };
        ((HttpsServer) server).setHttpsConfigurator(httpsConf);
      } catch (java.security.NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
      }
    }

    int maxThreads = config.getServerMaxWorkerThreads();
    int queueCapacity = config.getServerQueueCapacity();
    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(queueCapacity);
    // The Executor can't reject jobs directly, because HttpServer does not
    // appear to handle that case.
    RejectedExecutionHandler policy = new SuggestHandlerAbortPolicy(HttpExchanges.abortImmediately);
    Executor executor =
        new ThreadPoolExecutor(maxThreads, maxThreads, 1, TimeUnit.MINUTES, blockingQueue, policy);
    server.setExecutor(executor);

    try {
      server.bind(new InetSocketAddress(config.getServerPort()), 0);
    } catch (BindException ex) {
      log.log(Level.WARNING, "Server port {0,number,#} is in use.", config.getServerPort());
      throw ex;
    }
    log.info("GSA host name: " + config.getGsaHostname());
    log.info("server is listening on port #" + server.getAddress().getPort());
    return server;
  }
  private static HttpsServer createHttps(final Configuration config)
      throws KeyStoreException, NoSuchAlgorithmException, IOException, CertificateException,
          FileNotFoundException, UnrecoverableKeyException, KeyManagementException {
    HttpsServer https;
    final String ksFilename = config.KS_FILENAME;

    final char[] ksPassword = config.KS_PASSWORD;
    final char[] certPassword = config.CERT_PASSWORD;

    final KeyStore ks = KeyStore.getInstance("JKS");
    final SSLContext context = SSLContext.getInstance("TLS");
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

    try (FileInputStream ksis = new FileInputStream(ksFilename); ) {
      ks.load(ksis, ksPassword);
    }

    kmf.init(ks, certPassword);
    context.init(kmf.getKeyManagers(), null, null);

    https = HttpsServer.create(config.HOST_HTTPS, config.BACKLOG);
    https.setHttpsConfigurator(new HttpsConfigurator(context));
    return https;
  }
Beispiel #6
0
  public static void main(String[] args) throws Exception {
    HttpServer s1 = null;
    HttpsServer s2 = null;
    ExecutorService executor = null;
    try {
      String root = System.getProperty("test.src") + "/docs";
      System.out.print("Test12: ");
      InetSocketAddress addr = new InetSocketAddress(0);
      s1 = HttpServer.create(addr, 0);
      s2 = HttpsServer.create(addr, 0);
      HttpHandler h = new FileServerHandler(root);
      HttpContext c1 = s1.createContext("/test1", h);
      HttpContext c2 = s2.createContext("/test1", h);
      executor = Executors.newCachedThreadPool();
      s1.setExecutor(executor);
      s2.setExecutor(executor);
      ctx = new SimpleSSLContext(System.getProperty("test.src")).get();
      s2.setHttpsConfigurator(new HttpsConfigurator(ctx));
      s1.start();
      s2.start();

      int port = s1.getAddress().getPort();
      int httpsport = s2.getAddress().getPort();
      Runner r[] = new Runner[8];
      r[0] = new Runner(true, "http", root + "/test1", port, "smallfile.txt", 23);
      r[1] = new Runner(true, "http", root + "/test1", port, "largefile.txt", 2730088);
      r[2] = new Runner(true, "https", root + "/test1", httpsport, "smallfile.txt", 23);
      r[3] = new Runner(true, "https", root + "/test1", httpsport, "largefile.txt", 2730088);
      r[4] = new Runner(false, "http", root + "/test1", port, "smallfile.txt", 23);
      r[5] = new Runner(false, "http", root + "/test1", port, "largefile.txt", 2730088);
      r[6] = new Runner(false, "https", root + "/test1", httpsport, "smallfile.txt", 23);
      r[7] = new Runner(false, "https", root + "/test1", httpsport, "largefile.txt", 2730088);
      start(r);
      join(r);
      System.out.println("OK");
    } finally {
      delay();
      if (s1 != null) s1.stop(2);
      if (s2 != null) s2.stop(2);
      if (executor != null) executor.shutdown();
    }
  }
Beispiel #7
0
  public static void main(String[] args) throws Exception {
    HttpServer s1 = null;
    HttpsServer s2 = null;
    ExecutorService executor = null;
    try {
      String root = System.getProperty("test.src") + "/docs";
      System.out.print("Test1: ");
      InetSocketAddress addr = new InetSocketAddress(0);
      s1 = HttpServer.create(addr, 0);
      if (s1 instanceof HttpsServer) {
        throw new RuntimeException("should not be httpsserver");
      }
      s2 = HttpsServer.create(addr, 0);
      HttpHandler h = new FileServerHandler(root);
      HttpContext c1 = s1.createContext("/test1", h);
      HttpContext c2 = s2.createContext("/test1", h);
      executor = Executors.newCachedThreadPool();
      s1.setExecutor(executor);
      s2.setExecutor(executor);
      ctx = new SimpleSSLContext(System.getProperty("test.src")).get();
      s2.setHttpsConfigurator(new HttpsConfigurator(ctx));
      s1.start();
      s2.start();

      int port = s1.getAddress().getPort();
      int httpsport = s2.getAddress().getPort();
      test(true, "http", root + "/test1", port, "smallfile.txt", 23);
      test(true, "http", root + "/test1", port, "largefile.txt", 2730088);
      test(true, "https", root + "/test1", httpsport, "smallfile.txt", 23);
      test(true, "https", root + "/test1", httpsport, "largefile.txt", 2730088);
      test(false, "http", root + "/test1", port, "smallfile.txt", 23);
      test(false, "http", root + "/test1", port, "largefile.txt", 2730088);
      test(false, "https", root + "/test1", httpsport, "smallfile.txt", 23);
      test(false, "https", root + "/test1", httpsport, "largefile.txt", 2730088);
      System.out.println("OK");
    } finally {
      delay();
      s1.stop(2);
      s2.stop(2);
      executor.shutdown();
    }
  }
  /** Process initial method */
  public static void main(final String[] args) {

    final Configuration config = new Configuration();

    LOG.trace("Starting server...");

    // log server version

    LOG.trace("Preparing to run " + config.VERSION + ".");

    LOG.trace("Resuming DB from folder: " + config.DATABASE_FOLDER);

    // create listener

    LOG.trace("Creating listener.");

    final HttpServer http;
    try {

      http = HttpServer.create(config.HOST, config.BACKLOG);
    } catch (IOException e) {
      LOG.fatal("Could not create listener.");
      return;
    }

    // Process continues even if Https Listener failed to initialize

    HttpsServer https = null;
    if (config.HOST_HTTPS != null) {
      try {

        https = createHttps(config);

      } catch (IOException
          | KeyStoreException
          | NoSuchAlgorithmException
          | CertificateException
          | UnrecoverableKeyException
          | KeyManagementException e) {
        LOG.error("Could not create HTTPS listener.", e);
      }
    }

    // Single Threaded Executor

    final Executor exec =
        new Executor() {
          @Override
          public void execute(Runnable task) {
            task.run();
          }
        };

    http.setExecutor(exec);

    if (https != null) {
      https.setExecutor(exec);
    }

    LOG.trace("Starting virtual file system.");

    BufferedWriter accessLog = null;

    try {
      // start access log

      try {

        final FileWriter file = new FileWriter(config.ACCESS_LOG, true);
        accessLog = new BufferedWriter(file);
      } catch (IOException e) {
        System.out.println("Access log redirected to console.");
      }

      LOG.trace("Appending to access log.");

      // RequestHandler
      /*
       * final BasicAuthenticator ba = new
       * BasicAuthenticator("Statistics") {
       *
       * @Override public boolean checkCredentials(final String user,
       * final String pass) {
       *
       * LOG.info("login: [" + user + "] | [" + pass + "]");
       *
       * LOG.info("required: [" + config.STATISTICS_USERNAME + "] | [" +
       * config.STATISTICS_PASSWORD + "]");
       *
       * return user.equals(config.STATISTICS_USERNAME) &&
       * pass.equals(config.STATISTICS_PASSWORD.trim()); } };
       */
      final List<Class<?>> pages = new ArrayList<>();

      // scan packages

      PageClassLoader.load(config.PAGES_PACKAGES, pages);

      final List<Object> pageObjs = new ArrayList<>();

      // instantiate objects and inject dependencies

      PageClassLoader.injectDependencies(pages, pageObjs);

      // create contexts

      final HttpHandler enforcer = new HttpsEnforcer(config);

      final boolean usingHttps = https != null && !"no".equals(config.HTTPS_ENABLED);

      for (Class<?> pageClass : pages) {

        LOG.info("Creating context for: " + pageClass.getName());

        final Page page = pageClass.getAnnotation(Page.class);
        if (page == null) {
          LOG.info("Missing required Annotations. Skipping");
          continue;
        }

        final HttpHandler handler;
        try {
          handler = (HttpHandler) pageClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          LOG.info("Class is not a handler.");
          continue;
        }

        if (usingHttps) {
          https.createContext(page.path(), handler);
          http.createContext(page.path(), page.requireLogin() ? enforcer : handler);
        } else {
          https.createContext(page.path(), handler);
        }
      }

      // start server

      http.start();
      if (https != null) {
        http.start();
      }

      LOG.trace("Listener is Started.");

      System.out.println("Server Running. Press [k] to kill listener.");
      boolean running = true;
      do {

        try {
          running = System.in.read() == 'k';
        } catch (IOException e) {
        }

      } while (running);

      LOG.trace("Server stopping.");

      http.stop(1);
      if (https != null) {
        http.stop(1);
      }

    } finally {
      try {
        if (accessLog != null) {
          accessLog.close();
        }
      } catch (IOException e) {
      }
      LOG.trace("Server stopped.");
    }
  }