use of org.eclipse.jetty.server.HttpConnectionFactory in project rest.li by linkedin.
the class H2cJettyServer method getConnectors.
@Override
protected Connector[] getConnectors(Server server) {
HttpConfiguration configuration = new HttpConfiguration();
ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(configuration, HttpCompliance.RFC2616), new HTTP2CServerConnectionFactory(configuration));
connector.setPort(_port);
return new Connector[] { connector };
}
use of org.eclipse.jetty.server.HttpConnectionFactory in project gitblit by gitblit.
the class GitBlitServer method start.
/**
* Start Gitblit GO.
*/
protected final void start(Params params) {
final File baseFolder = getBaseFolder(params);
FileSettings settings = params.FILESETTINGS;
if (!StringUtils.isEmpty(params.settingsfile)) {
if (new File(params.settingsfile).exists()) {
settings = new FileSettings(params.settingsfile);
}
}
if (params.dailyLogFile) {
// Configure log4j for daily log file generation
InputStream is = null;
try {
is = getClass().getResourceAsStream("/log4j.properties");
Properties loggingProperties = new Properties();
loggingProperties.load(is);
loggingProperties.put("log4j.appender.R.File", new File(baseFolder, "logs/gitblit.log").getAbsolutePath());
loggingProperties.put("log4j.rootCategory", "INFO, R");
if (settings.getBoolean(Keys.web.debugMode, false)) {
loggingProperties.put("log4j.logger.com.gitblit", "DEBUG");
}
PropertyConfigurator.configure(loggingProperties);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
logger = LoggerFactory.getLogger(GitBlitServer.class);
logger.info("\n" + Constants.getASCIIArt());
System.setProperty("java.awt.headless", "true");
String osname = System.getProperty("os.name");
String osversion = System.getProperty("os.version");
logger.info("Running on " + osname + " (" + osversion + ")");
QueuedThreadPool threadPool = new QueuedThreadPool();
int maxThreads = settings.getInteger(Keys.server.threadPoolSize, 50);
if (maxThreads > 0) {
threadPool.setMaxThreads(maxThreads);
}
Server server = new Server(threadPool);
server.setStopAtShutdown(true);
// conditionally configure the https connector
if (params.securePort > 0) {
File certificatesConf = new File(baseFolder, X509Utils.CA_CONFIG);
File serverKeyStore = new File(baseFolder, X509Utils.SERVER_KEY_STORE);
File serverTrustStore = new File(baseFolder, X509Utils.SERVER_TRUST_STORE);
File caRevocationList = new File(baseFolder, X509Utils.CA_REVOCATION_LIST);
// generate CA & web certificates, create certificate stores
X509Metadata metadata = new X509Metadata("localhost", params.storePassword);
// set default certificate values from config file
if (certificatesConf.exists()) {
FileBasedConfig config = new FileBasedConfig(certificatesConf, FS.detect());
try {
config.load();
} catch (Exception e) {
logger.error("Error parsing " + certificatesConf, e);
}
NewCertificateConfig certificateConfig = NewCertificateConfig.KEY.parse(config);
certificateConfig.update(metadata);
}
metadata.notAfter = new Date(System.currentTimeMillis() + 10 * TimeUtils.ONEYEAR);
X509Utils.prepareX509Infrastructure(metadata, baseFolder, new X509Log() {
@Override
public void log(String message) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(new File(baseFolder, X509Utils.CERTS + File.separator + "log.txt"), true));
writer.write(MessageFormat.format("{0,date,yyyy-MM-dd HH:mm}: {1}", new Date(), message));
writer.newLine();
writer.flush();
} catch (Exception e) {
LoggerFactory.getLogger(GitblitAuthority.class).error("Failed to append log entry!", e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
}
});
if (serverKeyStore.exists()) {
/*
* HTTPS
*/
logger.info("Setting up HTTPS transport on port " + params.securePort);
GitblitSslContextFactory factory = new GitblitSslContextFactory(params.alias, serverKeyStore, serverTrustStore, params.storePassword, caRevocationList);
if (params.requireClientCertificates) {
factory.setNeedClientAuth(true);
} else {
factory.setWantClientAuth(true);
}
ServerConnector connector = new ServerConnector(server, factory);
connector.setSoLingerTime(-1);
connector.setIdleTimeout(30000);
connector.setPort(params.securePort);
String bindInterface = settings.getString(Keys.server.httpsBindInterface, null);
if (!StringUtils.isEmpty(bindInterface)) {
logger.warn(MessageFormat.format("Binding HTTPS transport on port {0,number,0} to {1}", params.securePort, bindInterface));
connector.setHost(bindInterface);
}
if (params.securePort < 1024 && !isWindows()) {
logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
}
server.addConnector(connector);
} else {
logger.warn("Failed to find or load Keystore?");
logger.warn("HTTPS transport DISABLED.");
}
}
// conditionally configure the http transport
if (params.port > 0) {
/*
* HTTP
*/
logger.info("Setting up HTTP transport on port " + params.port);
HttpConfiguration httpConfig = new HttpConfiguration();
if (params.port > 0 && params.securePort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true)) {
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(params.securePort);
}
httpConfig.setSendServerVersion(false);
httpConfig.setSendDateHeader(false);
ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
connector.setSoLingerTime(-1);
connector.setIdleTimeout(30000);
connector.setPort(params.port);
String bindInterface = settings.getString(Keys.server.httpBindInterface, null);
if (!StringUtils.isEmpty(bindInterface)) {
logger.warn(MessageFormat.format("Binding HTTP transport on port {0,number,0} to {1}", params.port, bindInterface));
connector.setHost(bindInterface);
}
if (params.port < 1024 && !isWindows()) {
logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
}
server.addConnector(connector);
}
// tempDir is where the embedded Gitblit web application is expanded and
// where Jetty creates any necessary temporary files
File tempDir = com.gitblit.utils.FileUtils.resolveParameter(Constants.baseFolder$, baseFolder, params.temp);
if (tempDir.exists()) {
try {
FileUtils.delete(tempDir, FileUtils.RECURSIVE | FileUtils.RETRY);
} catch (IOException x) {
logger.warn("Failed to delete temp dir " + tempDir.getAbsolutePath(), x);
}
}
if (!tempDir.mkdirs()) {
logger.warn("Failed to create temp dir " + tempDir.getAbsolutePath());
}
// Get the execution path of this class
// We use this to set the WAR path.
ProtectionDomain protectionDomain = GitBlitServer.class.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();
// Root WebApp Context
WebAppContext rootContext = new WebAppContext();
rootContext.setContextPath(settings.getString(Keys.server.contextPath, "/"));
rootContext.setServer(server);
rootContext.setWar(location.toExternalForm());
rootContext.setTempDirectory(tempDir);
// Set cookies HttpOnly so they are not accessible to JavaScript engines
HashSessionManager sessionManager = new HashSessionManager();
sessionManager.setHttpOnly(true);
// Use secure cookies if only serving https
sessionManager.setSecureRequestOnly((params.port <= 0 && params.securePort > 0) || (params.port > 0 && params.securePort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true)));
rootContext.getSessionHandler().setSessionManager(sessionManager);
// Ensure there is a defined User Service
String realmUsers = params.userService;
if (StringUtils.isEmpty(realmUsers)) {
logger.error(MessageFormat.format("PLEASE SPECIFY {0}!!", Keys.realm.userService));
return;
}
// Override settings from the command-line
settings.overrideSetting(Keys.realm.userService, params.userService);
settings.overrideSetting(Keys.git.repositoriesFolder, params.repositoriesFolder);
settings.overrideSetting(Keys.git.daemonPort, params.gitPort);
settings.overrideSetting(Keys.git.sshPort, params.sshPort);
// Start up an in-memory LDAP server, if configured
try {
if (!StringUtils.isEmpty(params.ldapLdifFile)) {
File ldifFile = new File(params.ldapLdifFile);
if (ldifFile != null && ldifFile.exists()) {
URI ldapUrl = new URI(settings.getRequiredString(Keys.realm.ldap.server));
String firstLine = new Scanner(ldifFile).nextLine();
String rootDN = firstLine.substring(4);
String bindUserName = settings.getString(Keys.realm.ldap.username, "");
String bindPassword = settings.getString(Keys.realm.ldap.password, "");
// Get the port
int port = ldapUrl.getPort();
if (port == -1)
port = 389;
InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(rootDN);
config.addAdditionalBindCredentials(bindUserName, bindPassword);
config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", port));
config.setSchema(null);
InMemoryDirectoryServer ds = new InMemoryDirectoryServer(config);
ds.importFromLDIF(true, new LDIFReader(ldifFile));
ds.startListening();
logger.info("LDAP Server started at ldap://localhost:" + port);
}
}
} catch (Exception e) {
// Completely optional, just show a warning
logger.warn("Unable to start LDAP server", e);
}
// Set the server's contexts
server.setHandler(rootContext);
// redirect HTTP requests to HTTPS
if (params.port > 0 && params.securePort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true)) {
logger.info(String.format("Configuring automatic http(%1$s) -> https(%2$s) redirects", params.port, params.securePort));
// Create the internal mechanisms to handle secure connections and redirects
Constraint constraint = new Constraint();
constraint.setDataConstraint(Constraint.DC_CONFIDENTIAL);
ConstraintMapping cm = new ConstraintMapping();
cm.setConstraint(constraint);
cm.setPathSpec("/*");
ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
sh.setConstraintMappings(new ConstraintMapping[] { cm });
// Configure this context to use the Security Handler defined before
rootContext.setHandler(sh);
}
// Setup the Gitblit context
GitblitContext gitblit = newGitblit(settings, baseFolder);
rootContext.addEventListener(gitblit);
try {
// start the shutdown monitor
if (params.shutdownPort > 0) {
Thread shutdownMonitor = new ShutdownMonitorThread(server, params);
shutdownMonitor.start();
}
// start Jetty
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
}
use of org.eclipse.jetty.server.HttpConnectionFactory in project opennms by OpenNMS.
the class JUnitServer method initializeServerWithConfig.
protected void initializeServerWithConfig(final JUnitHttpServer config) {
Server server = null;
if (config.https()) {
server = new Server();
// SSL context configuration
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(config.keystore());
sslContextFactory.setKeyStorePassword(config.keystorePassword());
sslContextFactory.setKeyManagerPassword(config.keyPassword());
sslContextFactory.setTrustStorePath(config.keystore());
sslContextFactory.setTrustStorePassword(config.keystorePassword());
// HTTP Configuration
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(config.port());
http_config.setOutputBufferSize(32768);
http_config.setRequestHeaderSize(8192);
http_config.setResponseHeaderSize(8192);
http_config.setSendServerVersion(true);
http_config.setSendDateHeader(false);
// SSL HTTP Configuration
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https_config));
sslConnector.setPort(config.port());
server.addConnector(sslConnector);
} 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.setHotReload(true);
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.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);
}
use of org.eclipse.jetty.server.HttpConnectionFactory in project chassis by Kixeye.
the class JettyConnectorRegistry method registerHttpsConnector.
/**
* Register to listen to HTTPS.
*
* @param server
* @param address
* @throws Exception
*/
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned, boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword, String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword, String[] excludedCipherSuites) throws Exception {
// SSL Context Factory
SslContextFactory sslContextFactory = new SslContextFactory();
if (selfSigned) {
char[] passwordChars = UUID.randomUUID().toString().toCharArray();
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, passwordChars);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
v3CertGen.setPublicKey(keyPair.getPublic());
v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());
keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars, new java.security.cert.Certificate[] { privateKeyCertificate });
ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
keyStore.store(keyStoreBaos, passwordChars);
keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
keyStorePassword = new String(passwordChars);
keyManagerPassword = keyStorePassword;
sslContextFactory.setTrustAll(true);
}
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
if (StringUtils.isNotBlank(keyStoreData)) {
keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
} else if (StringUtils.isNotBlank(keyStorePath)) {
try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
keyStore.load(inputStream, keyStorePassword.toCharArray());
}
}
sslContextFactory.setKeyStore(keyStore);
sslContextFactory.setKeyStorePassword(keyStorePassword);
if (StringUtils.isBlank(keyManagerPassword)) {
keyManagerPassword = keyStorePassword;
}
sslContextFactory.setKeyManagerPassword(keyManagerPassword);
KeyStore trustStore = null;
if (StringUtils.isNotBlank(trustStoreData)) {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
} else if (StringUtils.isNotBlank(trustStorePath)) {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath).getInputStream()) {
trustStore.load(inputStream, trustStorePassword.toCharArray());
}
}
if (trustStore != null) {
sslContextFactory.setTrustStore(trustStore);
sslContextFactory.setTrustStorePassword(trustStorePassword);
}
sslContextFactory.setNeedClientAuth(mutualSsl);
sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);
// SSL Connector
ServerConnector connector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()), new HttpConnectionFactory());
connector.setHost(address.getHostName());
connector.setPort(address.getPort());
server.addConnector(connector);
}
use of org.eclipse.jetty.server.HttpConnectionFactory in project jena by apache.
the class JettyFuseki method defaultServerConfig.
private void defaultServerConfig(int port, boolean loopback) {
server = new Server();
HttpConnectionFactory f1 = new HttpConnectionFactory();
// Some people do try very large operations ... really, should use POST.
f1.getHttpConfiguration().setRequestHeaderSize(512 * 1024);
f1.getHttpConfiguration().setOutputBufferSize(5 * 1024 * 1024);
// Do not add "Server: Jetty(....) when not a development system.
if (!Fuseki.outputJettyServerHeader)
f1.getHttpConfiguration().setSendServerVersion(false);
// https is better done with a Jetty configuration file
// because there are several things to configure.
// See "examples/fuseki-jetty-https.xml"
ServerConnector connector = new ServerConnector(server, f1);
connector.setPort(port);
server.addConnector(connector);
if (loopback)
connector.setHost("localhost");
serverConnector = connector;
}
Aggregations