public static final SecurityHandler basicAuth(AuthConfig config) {
    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    securityHandler.setAuthenticator(new BasicAuthenticator());
    securityHandler.setRealmName(config.getRealm());

    ConstraintMapping constraintMapping = new ConstraintMapping();

    Constraint constraint = new Constraint(Constraint.__BASIC_AUTH, USER_ROLE);
    constraint.setAuthenticate(true);

    constraintMapping.setConstraint(constraint);

    constraintMapping.setPathSpec("/*");

    securityHandler.addConstraintMapping(constraintMapping);

    HashLoginService loginService = new HashLoginService();
    loginService.putUser(
        config.getUsername(),
        Credential.getCredential(config.getPassword()),
        new String[] {USER_ROLE});
    loginService.setName(config.getRealm());

    securityHandler.setLoginService(loginService);

    return securityHandler;
  }
  private static void addAuthHandler(
      Server server, String auth, LoginAuthenticator authenticator, Handler handler) {

    server.addBean(LOGIN_SERVICE);

    Constraint constraint = new Constraint();
    constraint.setName(auth);
    constraint.setRoles(new String[] {USER, ADMIN});
    constraint.setAuthenticate(true);

    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setConstraint(constraint);
    mapping.setPathSpec("/*");

    Set<String> knownRoles = new HashSet<>();
    knownRoles.add(USER);
    knownRoles.add(ADMIN);

    List<ConstraintMapping> cm = new ArrayList<>();
    cm.add(mapping);

    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    security.setConstraintMappings(cm, knownRoles);
    security.setAuthenticator(authenticator);
    security.setLoginService(LOGIN_SERVICE);
    security.setHandler(handler);
    server.setHandler(security);
  }
Esempio n. 3
0
  private static SecurityHandler createSecurityHandler(LoginService loginService) {
    Constraint constraint = new Constraint();
    constraint.setAuthenticate(false);

    ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec("/*");

    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    securityHandler.setLoginService(loginService);

    // TODO: support for other auth schemes (digest, etc)
    securityHandler.setAuthenticator(new BasicAuthenticator());
    securityHandler.setConstraintMappings(Arrays.asList(constraintMapping));
    return securityHandler;
  }
  @BeforeClass(alwaysRun = true)
  @Override
  public void setUpGlobal() throws Exception {
    server = new Server();
    Logger root = Logger.getRootLogger();
    root.setLevel(Level.DEBUG);
    root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));

    port1 = 8080;
    Connector listener = new SelectChannelConnector();

    listener.setHost("127.0.0.1");
    listener.setPort(port1);

    server.addConnector(listener);

    LoginService loginService =
        new HashLoginService("MyRealm", "src/test/resources/realm.properties");
    server.addBean(loginService);

    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__BASIC_AUTH);
    constraint.setRoles(new String[] {user, admin});
    constraint.setAuthenticate(true);

    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setConstraint(constraint);
    mapping.setPathSpec("/*");

    Set<String> knownRoles = new HashSet<String>();
    knownRoles.add(user);
    knownRoles.add(admin);

    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    security.setConstraintMappings(new ConstraintMapping[] {mapping}, knownRoles);
    security.setAuthenticator(new BasicAuthenticator());
    security.setLoginService(loginService);
    security.setStrict(false);

    security.setHandler(configureHandler());
    server.setHandler(security);
    server.start();
    log.info("Local HTTP server started successfully");
  }
Esempio n. 5
0
  public AuthenticationServer(Integer port) {
    server = new BlockingServer(port);

    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__BASIC_AUTH);
    constraint.setRoles(new String[] {"user", "admin", "moderator"});
    constraint.setAuthenticate(true);

    ConstraintMapping cm = new ConstraintMapping();
    cm.setConstraint(constraint);
    cm.setPathSpec("/*");

    ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
    loginService = new HashLoginService("MyRealm");
    sh.setLoginService(loginService);
    sh.setConstraintMappings(new ConstraintMapping[] {cm});
    sh.setStrict(false);

    accessedUri = new ArrayList<String>();

    Handler handler =
        new AbstractHandler() {
          public void handle(
              String target,
              Request baseRequest,
              HttpServletRequest request,
              HttpServletResponse response)
              throws IOException, ServletException {
            response.setContentType("text/html");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println("<h1>Hello</h1>");
            ((Request) request).setHandled(true);
            accessedUri.add(((Request) request).getUri().toString());
          }
        };

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {handler, new DefaultHandler()});

    sh.setHandler(handlers);
    server.setHandler(sh);
  }
Esempio n. 6
0
  private static final SecurityHandler basicAuth(String realm) {

    OpenfireLoginService l = new OpenfireLoginService();
    l.setName(realm);

    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__BASIC_AUTH);
    constraint.setRoles(new String[] {"jmxweb"});
    constraint.setAuthenticate(true);

    ConstraintMapping cm = new ConstraintMapping();
    cm.setConstraint(constraint);
    cm.setPathSpec("/*");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName(realm);
    csh.addConstraintMapping(cm);
    csh.setLoginService(l);

    return csh;
  }
  private void start(Authenticator authenticator, Handler handler) throws Exception {
    server = new Server();
    File realmFile = MavenTestingUtils.getTestResourceFile("realm.properties");
    LoginService loginService = new HashLoginService(realm, realmFile.getAbsolutePath());
    server.addBean(loginService);

    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();

    Constraint constraint = new Constraint();
    constraint.setAuthenticate(true);
    constraint.setRoles(new String[] {"*"});
    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/secure");
    mapping.setConstraint(constraint);

    securityHandler.addConstraintMapping(mapping);
    securityHandler.setAuthenticator(authenticator);
    securityHandler.setLoginService(loginService);
    securityHandler.setStrict(false);

    securityHandler.setHandler(handler);
    start(securityHandler);
  }
  private SecurityHandler getSecurityHandler() throws IOException {
    Constraint constraint = new Constraint(Constraint.__BASIC_AUTH, "websocket");
    constraint.setAuthenticate(true);

    ConstraintMapping cm = new ConstraintMapping();
    cm.setPathSpec("/openicf/*");
    cm.setConstraint(constraint);

    ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
    sh.setAuthenticator(new BasicAuthenticator());
    sh.setConstraintMappings(Arrays.asList(new ConstraintMapping[] {cm}));

    MappedLoginService loginService =
        new MappedLoginService() {

          @Override
          protected UserIdentity loadUser(String username) {
            return null;
          }

          @Override
          protected void loadUsers() throws IOException {
            Credential credential = Credential.getCredential(DEFAULT_PASSWORD);
            String[] roles = new String[] {"websocket"};
            putUser("plain", credential, roles);
            putUser("secure", credential, roles);
            putUser("proxy", credential, roles);
            putUser("anonymous", credential, roles);
          }
        };
    loginService.setName("OpenICF-Service");
    sh.setLoginService(loginService);
    sh.setConstraintMappings(Arrays.asList(new ConstraintMapping[] {cm}));

    return sh;
  }
Esempio n. 9
0
  public void start(String args[]) {
    Logger.getRootLogger().setLevel(Level.ERROR);

    PropertiesManager pm = new PropertiesManager();
    File propFile = new File(propFileName);
    if (propFile.isFile()) pm.join(propFile);
    pm.importSystemProps();
    try {
      pm.update();
    } catch (IllegalArgumentException e) {
      System.err.println("invalid configuration, can't start: " + e.getMessage());
      System.exit(1);
    }

    if (pm.withjmx) {
      doJmx(pm);
    }

    System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.Slf4jLog");
    System.setProperty("org.eclipse.jetty.LEVEL", "DEBUG");

    final Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    if (host != null) {
      connector.setHost(host);
    }
    connector.setPort(port);

    // Let's try to start the connector before the application
    try {
      connector.open();
    } catch (IOException e) {
      connector.close();
      throw new RuntimeException("Jetty server failed to start", e);
    }
    server.setConnectors(new Connector[] {connector});

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setResourceBase(webRoot);
    webapp.setClassLoader(getClass().getClassLoader());
    webapp.setInitParameter("propertiesFile", propFileName);

    ResourceHandler staticFiles = new ResourceHandler();
    staticFiles.setWelcomeFiles(new String[] {"index.html"});
    staticFiles.setResourceBase(webRoot);

    if (pm.security) {
      LoginService loginService = new HashLoginService("jrds", pm.userfile);
      server.addBean(loginService);

      Authenticator auth = new BasicAuthenticator();
      Constraint constraint = new Constraint();
      constraint.setName("jrds");
      constraint.setRoles(new String[] {Constraint.ANY_ROLE});
      constraint.setAuthenticate(true);
      constraint.setDataConstraint(Constraint.DC_NONE);

      ConstraintMapping cm = new ConstraintMapping();
      cm.setConstraint(constraint);
      cm.setPathSpec("/*");

      ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
      sh.setConstraintMappings(Collections.singletonList(cm));
      sh.setAuthenticator(auth);
      webapp.setSecurityHandler(sh);
    }

    HandlerCollection handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {staticFiles, webapp});
    server.setHandler(handlers);

    if (pm.withjmx || MBeanServerFactory.findMBeanServer(null).size() > 0) {
      MBeanServer mbs = java.lang.management.ManagementFactory.getPlatformMBeanServer();
      server.addBean(new MBeanContainer(mbs));
      handlers.addHandler(new StatisticsHandler());
    }

    // Properties are not needed any more
    pm = null;

    Thread finish =
        new Thread() {
          public void run() {
            try {
              server.stop();
            } catch (Exception e) {
              throw new RuntimeException("Jetty server failed to stop", e);
            }
          }
        };
    Runtime.getRuntime().addShutdownHook(finish);

    try {
      server.start();
      server.join();
    } catch (Exception e) {
      throw new RuntimeException("Jetty server failed to start", e);
    }
  }
Esempio n. 10
0
  public Server getJettyServer(int port, int sslPort, int maxThreads) throws IOException {

    Server server = new Server();
    HandlerCollection handlers = new HandlerCollection();
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setThreadPool(new QueuedThreadPool(maxThreads));

    SslSocketConnector sslSocketConnector = null;
    if (sslPort > 0) {
      System.out.println("SSL is Starting on port " + sslPort + "...");
      sslSocketConnector = new SslSocketConnector();
      sslSocketConnector.setPort(getContainerConfig().getSSLPort());
      sslSocketConnector.setKeystore("conf/servertestkeystore");
      sslSocketConnector.setPassword(getContainerConfig().getSSLKeyPassword());
      sslSocketConnector.setKeyPassword(getContainerConfig().getSSLKeyStorePassword());
      sslSocketConnector.setTruststore("conf/servertestkeystore");
      sslSocketConnector.setTrustPassword(getContainerConfig().getSSLKeyStorePassword());
    } else if (getContainerConfig().isAcEnabled())
      logger.error("SSL MUST be configured in the gsn.xml file when Access Control is enabled !");

    AbstractConnector connector =
        new SelectChannelConnector(); // before was connector//new SocketConnector ();//using basic
                                      // connector for windows bug; Fast
                                      // option=>SelectChannelConnector
    connector.setPort(port);
    connector.setMaxIdleTime(30000);
    connector.setAcceptors(2);
    connector.setConfidentialPort(sslPort);

    if (sslSocketConnector == null) server.setConnectors(new Connector[] {connector});
    else server.setConnectors(new Connector[] {connector, sslSocketConnector});

    WebAppContext webAppContext = new WebAppContext(contexts, DEFAULT_WEB_APP_PATH, "/");

    handlers.setHandlers(new Handler[] {contexts, new DefaultHandler()});
    server.setHandler(handlers);

    Properties usernames = new Properties();
    usernames.load(new FileReader("conf/realm.properties"));
    if (!usernames.isEmpty()) {
      HashLoginService loginService = new HashLoginService();
      loginService.setName("GSNRealm");
      loginService.setConfig("conf/realm.properties");
      loginService.setRefreshInterval(10000); // re-reads the file every 10 seconds.

      Constraint constraint = new Constraint();
      constraint.setName("GSN User");
      constraint.setRoles(new String[] {"gsnuser"});
      constraint.setAuthenticate(true);

      ConstraintMapping cm = new ConstraintMapping();
      cm.setConstraint(constraint);
      cm.setPathSpec("/*");
      cm.setMethod("GET");

      ConstraintMapping cm2 = new ConstraintMapping();
      cm2.setConstraint(constraint);
      cm2.setPathSpec("/*");
      cm2.setMethod("POST");

      ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
      securityHandler.setLoginService(loginService);
      securityHandler.setConstraintMappings(new ConstraintMapping[] {cm, cm2});
      securityHandler.setAuthenticator(new BasicAuthenticator());
      webAppContext.setSecurityHandler(securityHandler);
    }

    server.setSendServerVersion(true);
    server.setStopAtShutdown(true);
    server.setSendServerVersion(false);
    server.setSessionIdManager(new HashSessionIdManager(new Random()));

    return server;
  }
Esempio n. 11
0
  protected void initializeServerWithConfig(final JUnitHttpServer config) {
    Server server = null;
    if (config.https()) {
      server = new Server();
      final SslContextFactory factory = new SslContextFactory(config.keystore());
      factory.setKeyStorePath(config.keystore());
      factory.setKeyStorePassword(config.keystorePassword());
      factory.setKeyManagerPassword(config.keyPassword());
      factory.setTrustStore(config.keystore());
      factory.setTrustStorePassword(config.keystorePassword());

      final SslSocketConnector connector = new SslSocketConnector(factory);
      connector.setPort(config.port());
      server.setConnectors(new Connector[] {connector});
    } else {
      server = new Server(config.port());
    }
    m_server = server;
    final ContextHandler context1 = new ContextHandler();
    context1.setContextPath("/");
    context1.setWelcomeFiles(new String[] {"index.html"});
    context1.setResourceBase(config.resource());
    context1.setClassLoader(Thread.currentThread().getContextClassLoader());
    context1.setVirtualHosts(config.vhosts());

    final ContextHandler context = context1;

    Handler topLevelHandler = null;
    final HandlerList handlers = new HandlerList();

    if (config.basicAuth()) {
      // check for basic auth if we're configured to do so
      LOG.debug("configuring basic auth");

      final HashLoginService loginService = new HashLoginService("MyRealm", config.basicAuthFile());
      loginService.setRefreshInterval(300000);
      m_server.addBean(loginService);

      final ConstraintSecurityHandler security = new ConstraintSecurityHandler();

      final Set<String> knownRoles = new HashSet<String>();
      knownRoles.add("user");
      knownRoles.add("admin");
      knownRoles.add("moderator");

      final Constraint constraint = new Constraint();
      constraint.setName("auth");
      constraint.setAuthenticate(true);
      constraint.setRoles(knownRoles.toArray(new String[0]));

      final ConstraintMapping mapping = new ConstraintMapping();
      mapping.setPathSpec("/*");
      mapping.setConstraint(constraint);

      security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
      security.setAuthenticator(new BasicAuthenticator());
      security.setLoginService(loginService);
      security.setStrict(false);
      security.setRealmName("MyRealm");

      security.setHandler(context);
      topLevelHandler = security;
    } else {
      topLevelHandler = context;
    }

    final Webapp[] webapps = config.webapps();
    if (webapps != null) {
      for (final Webapp webapp : webapps) {
        final WebAppContext wac = new WebAppContext();
        String path = null;
        if (!"".equals(webapp.pathSystemProperty())
            && System.getProperty(webapp.pathSystemProperty()) != null) {
          path = System.getProperty(webapp.pathSystemProperty());
        } else {
          path = webapp.path();
        }
        if (path == null || "".equals(path)) {
          throw new IllegalArgumentException(
              "path or pathSystemProperty of @Webapp points to a null or blank value");
        }
        wac.setWar(path);
        wac.setContextPath(webapp.context());
        handlers.addHandler(wac);
      }
    }

    final ResourceHandler rh = new ResourceHandler();
    rh.setWelcomeFiles(new String[] {"index.html"});
    rh.setResourceBase(config.resource());
    handlers.addHandler(rh);

    // fall through to default
    handlers.addHandler(new DefaultHandler());

    context.setHandler(handlers);
    m_server.setHandler(topLevelHandler);
  }
Esempio n. 12
0
  public static void main(String[] args) throws Exception {
    ReplayProps.Init();

    ReplayDB.init();

    ReplayLogger.log(Level.INFO, "Log opened...");

    org.eclipse.jetty.util.log.Log.setLog(ReplayLogger.replayLogger);

    final int quickTaskFrequencyInSeconds = ReplayProps.getInt("quickTaskFrequencyInSeconds", "10");
    final int longTaskFrequencyInHours = ReplayProps.getInt("longTaskFrequencyInHours", "1");

    timer = new Timer();

    if (quickTaskFrequencyInSeconds != 0) {
      timer.schedule(
          new CleanupTask.QuickTask(),
          quickTaskFrequencyInSeconds * 1000,
          quickTaskFrequencyInSeconds * 1000);
    }

    if (quickTaskFrequencyInSeconds != 0) {
      timer.schedule(
          new CleanupTask.LongTask(),
          60 * 60 * 1000 * longTaskFrequencyInHours,
          60 * 60 * 1000 * longTaskFrequencyInHours);
    }

    final int httpPort = ReplayProps.getInt("httpPort", "80");

    final Server server = new Server(httpPort);

    ServletContextHandler context =
        new ServletContextHandler(ServletContextHandler.SESSIONS | ServletContextHandler.SECURITY);
    context.setContextPath("/");
    server.setHandler(context);

    // Change default timeout to 45 seconds (from 30)
    /*
    ServerConnector http = new ServerConnector( server );
    //http.setHost( "localhost" );
    http.setPort( httpPort );
    http.setIdleTimeout( 45000 );

    server.addConnector( http );
    */

    final boolean bTestAuthorize = false;

    if (bTestAuthorize) {
      context.addServlet(
          new ServletHolder(
              new HttpServlet() {
                private static final long serialVersionUID = 1L;

                @Override
                protected void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
                  final ServletInputStream inputStream = request.getInputStream();

                  FileUtils.ReplayOutputStream outputStream =
                      FileUtils.getReplayOutputStream("authorize.txt", false);

                  byte[] buffer = new byte[1024];

                  int readBytes = 0;

                  while ((readBytes = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, readBytes);
                  }

                  inputStream.close();
                  outputStream.close();

                  response.setContentType("text/html");
                  response
                      .getWriter()
                      .println("<p>Worked: " + request.getContentType() + " </p><br>");
                }
              }),
          "/j_security_check");
    }

    context.addServlet(new ServletHolder(new Download()), "/download/*");
    context.addServlet(new ServletHolder(new DownloadEvent()), "/downloadevent/*");
    context.addServlet(new ServletHolder(new Upload()), "/upload/*");
    context.addServlet(new ServletHolder(new UploadEvent()), "/uploadevent/*");
    context.addServlet(new ServletHolder(new StartUploading()), "/startuploading/*");
    context.addServlet(new ServletHolder(new StopUploading()), "/stopuploading/*");
    context.addServlet(new ServletHolder(new StartDownloading()), "/startdownloading/*");
    context.addServlet(new ServletHolder(new DeleteSession()), "/deletesession/*");
    context.addServlet(new ServletHolder(new EnumerateSessions()), "/enumsessions/*");
    context.addServlet(new ServletHolder(new EnumEvents()), "/enumevents/*");
    context.addServlet(new ServletHolder(new RefreshViewer()), "/refreshviewer/*");
    context.addServlet(new ServletHolder(new ViewFile()), "/viewfile/*");

    if (ReplayProps.getInt("enableBuiltInWebServer", "1") == 1) {
      context.addServlet(new ServletHolder(new Index()), "/*");
    }

    // Password protect the delete session page
    context.addServlet(
        new ServletHolder(
            new HttpServlet() {
              private static final long serialVersionUID = 1L;

              @Override
              protected void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
                response.setContentType("text/html");
                response
                    .getWriter()
                    .append(
                        "<form method='POST' action='/j_security_check'>"
                            + "<input type='text' name='j_username'/>"
                            + "<input type='password' name='j_password'/>"
                            + "<input type='submit' value='Login'/></form>");
              }
            }),
        "/login");

    final Constraint constraint = new Constraint();
    constraint.setName(Constraint.__FORM_AUTH);
    constraint.setRoles(new String[] {"user", "admin", "moderator"});
    constraint.setAuthenticate(true);

    final ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec("/deletesession/*");

    final ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    securityHandler.addConstraintMapping(constraintMapping);
    HashLoginService loginService = new HashLoginService();
    loginService.putUser("usern", new Password("pass"), new String[] {"user"});
    loginService.putUser("admin", new Password("pass"), new String[] {"admin"});
    securityHandler.setLoginService(loginService);

    final FormAuthenticator authenticator = new FormAuthenticator("/login", "/login", false);
    securityHandler.setAuthenticator(authenticator);

    if (!bTestAuthorize) {
      context.setSecurityHandler(securityHandler);
    }

    server.start();
    server.join();

    ReplayDB.shutdown();
  }
Esempio n. 13
0
  /**
   * Configure a jetty instance and deploy the webapps presented as args
   *
   * @param args the command line arguments
   * @throws Exception if unable to configure
   */
  public void configure(String[] args) throws Exception {
    // handle classpath bits first so we can initialize the log mechanism.
    for (int i = 0; i < args.length; i++) {
      if ("--lib".equals(args[i])) {
        try (Resource lib = Resource.newResource(args[++i])) {
          if (!lib.exists() || !lib.isDirectory()) usage("No such lib directory " + lib);
          _classpath.addJars(lib);
        }
      } else if ("--jar".equals(args[i])) {
        try (Resource jar = Resource.newResource(args[++i])) {
          if (!jar.exists() || jar.isDirectory()) usage("No such jar " + jar);
          _classpath.addPath(jar);
        }
      } else if ("--classes".equals(args[i])) {
        try (Resource classes = Resource.newResource(args[++i])) {
          if (!classes.exists() || !classes.isDirectory())
            usage("No such classes directory " + classes);
          _classpath.addPath(classes);
        }
      } else if (args[i].startsWith("--")) i++;
    }

    initClassLoader();

    LOG.info("Runner");
    LOG.debug("Runner classpath {}", _classpath);

    String contextPath = __defaultContextPath;
    boolean contextPathSet = false;
    int port = __defaultPort;
    String host = null;
    int stopPort = 0;
    String stopKey = null;

    boolean runnerServerInitialized = false;

    for (int i = 0; i < args.length; i++) {
      switch (args[i]) {
        case "--port":
          port = Integer.parseInt(args[++i]);
          break;
        case "--host":
          host = args[++i];
          break;
        case "--stop-port":
          stopPort = Integer.parseInt(args[++i]);
          break;
        case "--stop-key":
          stopKey = args[++i];
          break;
        case "--log":
          _logFile = args[++i];
          break;
        case "--out":
          String outFile = args[++i];
          PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1));
          LOG.info("Redirecting stderr/stdout to " + outFile);
          System.setErr(out);
          System.setOut(out);
          break;
        case "--path":
          contextPath = args[++i];
          contextPathSet = true;
          break;
        case "--config":
          if (_configFiles == null) _configFiles = new ArrayList<>();
          _configFiles.add(args[++i]);
          break;
        case "--lib":
          ++i; // skip

          break;
        case "--jar":
          ++i; // skip

          break;
        case "--classes":
          ++i; // skip

          break;
        case "--stats":
          _enableStats = true;
          _statsPropFile = args[++i];
          _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile);
          break;
        default:
          // process contexts

          if (!runnerServerInitialized) // log handlers not registered, server maybe not created,
                                        // etc
          {
            if (_server == null) // server not initialized yet
            {
              // build the server
              _server = new Server();
            }

            // apply jetty config files if there are any
            if (_configFiles != null) {
              for (String cfg : _configFiles) {
                try (Resource resource = Resource.newResource(cfg)) {
                  XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL());
                  xmlConfiguration.configure(_server);
                }
              }
            }

            // check that everything got configured, and if not, make the handlers
            HandlerCollection handlers =
                (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class);
            if (handlers == null) {
              handlers = new HandlerCollection();
              _server.setHandler(handlers);
            }

            // check if contexts already configured
            _contexts =
                (ContextHandlerCollection)
                    handlers.getChildHandlerByClass(ContextHandlerCollection.class);
            if (_contexts == null) {
              _contexts = new ContextHandlerCollection();
              prependHandler(_contexts, handlers);
            }

            if (_enableStats) {
              // if no stats handler already configured
              if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) {
                StatisticsHandler statsHandler = new StatisticsHandler();

                Handler oldHandler = _server.getHandler();
                statsHandler.setHandler(oldHandler);
                _server.setHandler(statsHandler);

                ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats");
                statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/");
                statsContext.setSessionHandler(new SessionHandler());
                if (_statsPropFile != null) {
                  HashLoginService loginService =
                      new HashLoginService("StatsRealm", _statsPropFile);
                  Constraint constraint = new Constraint();
                  constraint.setName("Admin Only");
                  constraint.setRoles(new String[] {"admin"});
                  constraint.setAuthenticate(true);

                  ConstraintMapping cm = new ConstraintMapping();
                  cm.setConstraint(constraint);
                  cm.setPathSpec("/*");

                  ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
                  securityHandler.setLoginService(loginService);
                  securityHandler.setConstraintMappings(Collections.singletonList(cm));
                  securityHandler.setAuthenticator(new BasicAuthenticator());
                  statsContext.setSecurityHandler(securityHandler);
                }
              }
            }

            // ensure a DefaultHandler is present
            if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) {
              handlers.addHandler(new DefaultHandler());
            }

            // ensure a log handler is present
            _logHandler =
                (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class);
            if (_logHandler == null) {
              _logHandler = new RequestLogHandler();
              handlers.addHandler(_logHandler);
            }

            // check a connector is configured to listen on
            Connector[] connectors = _server.getConnectors();
            if (connectors == null || connectors.length == 0) {
              ServerConnector connector = new ServerConnector(_server);
              connector.setPort(port);
              if (host != null) connector.setHost(host);
              _server.addConnector(connector);
              if (_enableStats) connector.addBean(new ConnectorStatistics());
            } else {
              if (_enableStats) {
                for (Connector connector : connectors) {
                  ((AbstractConnector) connector).addBean(new ConnectorStatistics());
                }
              }
            }

            runnerServerInitialized = true;
          }

          // Create a context
          try (Resource ctx = Resource.newResource(args[i])) {
            if (!ctx.exists()) usage("Context '" + ctx + "' does not exist");

            if (contextPathSet && !(contextPath.startsWith("/"))) contextPath = "/" + contextPath;

            // Configure the context
            if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml")) {
              // It is a context config file
              XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL());
              xmlConfiguration.getIdMap().put("Server", _server);
              ContextHandler handler = (ContextHandler) xmlConfiguration.configure();
              if (contextPathSet) handler.setContextPath(contextPath);
              _contexts.addHandler(handler);
              handler.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            } else {
              // assume it is a WAR file
              WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath);
              webapp.setConfigurationClasses(__plusConfigurationClasses);
              webapp.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            }
          }
          // reset
          contextPathSet = false;
          contextPath = __defaultContextPath;
          break;
      }
    }

    if (_server == null) usage("No Contexts defined");
    _server.setStopAtShutdown(true);

    switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) {
      case 1:
        usage("Must specify --stop-key when --stop-port is specified");
        break;

      case 2:
        usage("Must specify --stop-port when --stop-key is specified");
        break;

      case 3:
        ShutdownMonitor monitor = ShutdownMonitor.getInstance();
        monitor.setPort(stopPort);
        monitor.setKey(stopKey);
        monitor.setExitVm(true);
        break;
    }

    if (_logFile != null) {
      NCSARequestLog requestLog = new NCSARequestLog(_logFile);
      requestLog.setExtended(false);
      _logHandler.setRequestLog(requestLog);
    }
  }
Esempio n. 14
0
  protected void createServer(Connector connector) throws Exception {
    _server.setConnectors(new Connector[] {connector});

    if (H2O.ARGS.hash_login || H2O.ARGS.ldap_login) {
      // REFER TO
      // http://www.eclipse.org/jetty/documentation/9.1.4.v20140401/embedded-examples.html#embedded-secured-hello-handler
      if (H2O.ARGS.login_conf == null) {
        Log.err("Must specify -login_conf argument");
        H2O.exit(1);
      }

      LoginService loginService;
      if (H2O.ARGS.hash_login) {
        Log.info("Configuring HashLoginService");
        loginService = new HashLoginService("H2O", H2O.ARGS.login_conf);
      } else if (H2O.ARGS.ldap_login) {
        Log.info("Configuring JAASLoginService (with LDAP)");
        System.setProperty("java.security.auth.login.config", H2O.ARGS.login_conf);
        loginService = new JAASLoginService("ldaploginmodule");
      } else {
        throw H2O.fail();
      }
      IdentityService identityService = new DefaultIdentityService();
      loginService.setIdentityService(identityService);
      _server.addBean(loginService);

      // Set a security handler as the first handler in the chain.
      ConstraintSecurityHandler security = new ConstraintSecurityHandler();

      // Set up a constraint to authenticate all calls, and allow certain roles in.
      Constraint constraint = new Constraint();
      constraint.setName("auth");
      constraint.setAuthenticate(true);

      // Configure role stuff (to be disregarded).  We are ignoring roles, and only going off the
      // user name.
      //
      //   Jetty 8 and prior.
      //
      //     Jetty 8 requires the security.setStrict(false) and ANY_ROLE.
      security.setStrict(false);
      constraint.setRoles(new String[] {Constraint.ANY_ROLE});

      //   Jetty 9 and later.
      //
      //     Jetty 9 and later uses a different servlet spec, and ANY_AUTH gives the same behavior
      //     for that API version as ANY_ROLE did previously.  This required some low-level
      // debugging
      //     to figure out, so I'm documenting it here.
      //     Jetty 9 did not require security.setStrict(false).
      //
      // constraint.setRoles(new String[]{Constraint.ANY_AUTH});

      ConstraintMapping mapping = new ConstraintMapping();
      mapping.setPathSpec("/*"); // Lock down all API calls
      mapping.setConstraint(constraint);
      security.setConstraintMappings(Collections.singletonList(mapping));

      // Authentication / Authorization
      security.setAuthenticator(new BasicAuthenticator());
      security.setLoginService(loginService);

      // Pass-through to H2O if authenticated.
      registerHandlers(security);
      _server.setHandler(security);
    } else {
      registerHandlers(_server);
    }

    _server.start();
  }