use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.
the class SendMessageThread method generateTargets.
private void generateTargets(ConfigManager cfgMgr) throws ProvisioningException {
if (cfgMgr.getCfg().getProvisioning() == null) {
return;
}
this.targetIDs = new HashMap<String, Targets>();
Iterator<TargetType> it = cfgMgr.getCfg().getProvisioning().getTargets().getTarget().iterator();
while (it.hasNext()) {
TargetType targetCfg = it.next();
addTarget(cfgMgr, targetCfg);
}
if (cfgMgr.getCfg().getProvisioning().getTargets().getDynamicTargets() != null && cfgMgr.getCfg().getProvisioning().getTargets().getDynamicTargets().isEnabled()) {
DynamicPortalUrlsType dynamicTargets = cfgMgr.getCfg().getProvisioning().getTargets().getDynamicTargets();
String className = dynamicTargets.getClassName();
HashMap<String, Attribute> cfgAttrs = new HashMap<String, Attribute>();
for (ParamType pt : dynamicTargets.getParams()) {
Attribute attr = cfgAttrs.get(pt.getName());
if (attr == null) {
attr = new Attribute(pt.getName());
cfgAttrs.put(pt.getName(), attr);
}
attr.getValues().add(pt.getValue());
}
try {
DynamicTargets dynTargets = (DynamicTargets) Class.forName(className).newInstance();
dynTargets.loadDynamicTargets(cfgMgr, this, cfgAttrs);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new ProvisioningException("Could not initialize dynamic targets", e);
}
}
}
use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.
the class UnisonConfigManagerImpl method loadAuthMechs.
/* (non-Javadoc)
* @see com.tremolosecurity.config.util.ConfigManager#loadAuthMechs()
*/
/* (non-Javadoc)
* @see com.tremolosecurity.config.util.UnisonConfigManager#loadAuthMechs()
*/
@Override
public void loadAuthMechs() throws ServletException {
try {
this.mechs = new HashMap<String, AuthMechanism>();
// UnisonConfigManagerImpl tremoloCfg = (UnisonConfigManagerImpl) ctx.getAttribute(ConfigFilter.TREMOLO_CONFIG);
if (getCfg().getAuthMechs() != null) {
Iterator<MechanismType> mechs = getCfg().getAuthMechs().getMechanism().iterator();
while (mechs.hasNext()) {
MechanismType mt = mechs.next();
initializeAuthenticationMechanism(mt);
}
}
} catch (Exception e) {
throw new ServletException("Could not initialize Auth Mechanism Filter", e);
}
for (String key : this.authChains.keySet()) {
AuthChainType act = this.authChains.get(key);
if (act.getLevel() == 0) {
this.anonAct = act;
String mechName = act.getAuthMech().get(0).getName();
this.anonAuthMech = (AnonAuth) this.getAuthMech(this.authMechs.get(mechName).getUri());
}
}
if (this.anonAuthMech == null) {
this.anonAct = new AuthChainType();
this.anonAct.setFinishOnRequiredSucess(true);
this.anonAct.setLevel(0);
this.anonAct.setName("anon");
this.anonAuthMech = new AnonAuth();
}
if (this.alwaysFailAuth == null) {
this.alwaysFailAuth = new AlwaysFail();
String failAuthUri = this.ctxPath + "/fail";
this.mechs.put(failAuthUri, alwaysFailAuth);
MechanismType fmt = new MechanismType();
fmt.setClassName("com.tremolosecurity.proxy.auth.AlwaysFail");
fmt.setInit(new ConfigType());
fmt.setParams(new ParamListType());
fmt.setName("fail");
fmt.setUri(failAuthUri);
if (this.cfg.getAuthMechs() == null) {
this.cfg.setAuthMechs(new AuthMechTypes());
}
this.cfg.getAuthMechs().getMechanism().add(fmt);
this.alwaysFailAuthMech = fmt;
}
for (String key : this.authChains.keySet()) {
AuthChainType act = this.authChains.get(key);
for (AuthMechType amt : act.getAuthMech()) {
if (amt.getName().equals(this.alwaysFailAuthMech.getName())) {
this.authFailChain = act;
break;
}
}
}
if (this.authFailChain == null) {
this.authFailChain = new AuthChainType();
this.authFailChain.setLevel(0);
this.authFailChain.setName("alwaysfail");
AuthMechType amt = new AuthMechType();
amt.setName(this.alwaysFailAuthMech.getName());
amt.setRequired("required");
amt.setParams(new AuthMechParamType());
this.authFailChain.getAuthMech().add(amt);
}
try {
if (this.getCfg().getAuthMechs() != null && this.getCfg().getAuthMechs().getDynamicAuthMechs() != null && this.getCfg().getAuthMechs().getDynamicAuthMechs().isEnabled()) {
DynamicPortalUrlsType dynamicAuthMechs = this.getCfg().getAuthMechs().getDynamicAuthMechs();
String className = dynamicAuthMechs.getClassName();
HashMap<String, Attribute> cfgAttrs = new HashMap<String, Attribute>();
for (ParamType pt : dynamicAuthMechs.getParams()) {
Attribute attr = cfgAttrs.get(pt.getName());
if (attr == null) {
attr = new Attribute(pt.getName());
cfgAttrs.put(pt.getName(), attr);
}
attr.getValues().add(pt.getValue());
}
DynamicAuthMechs dynCustomAuMechs = (DynamicAuthMechs) Class.forName(className).newInstance();
dynCustomAuMechs.loadDynamicAuthMechs(this, this.getProvisioningEngine(), cfgAttrs);
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | ProvisioningException e) {
throw new ServletException("Could not initialize authentication mechanisms", e);
}
}
use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.
the class PreAuthFilter method initFilter.
@Override
public void initFilter(HttpFilterConfig config) throws Exception {
this.postSAML = config.getAttribute("postSAML") != null && config.getAttribute("postSAML").getValues().get(0).equalsIgnoreCase("true");
if (postSAML) {
String idpName = config.getAttribute("idpName").getValues().get(0);
ApplicationType app = config.getConfigManager().getApp(idpName);
IdpType idp = app.getUrls().getUrl().get(0).getIdp();
for (ParamType pt : idp.getParams()) {
if (pt.getName().equalsIgnoreCase("sigKey")) {
this.keyAlias = pt.getValue();
}
}
TrustType tt = idp.getTrusts().getTrust().get(0);
for (ParamType pt : tt.getParam()) {
if (pt.getName().equalsIgnoreCase("signResponse")) {
this.signResponse = pt.getValue().equalsIgnoreCase("true");
} else if (pt.getName().equalsIgnoreCase("signAssertion")) {
this.signAssertion = pt.getValue().equalsIgnoreCase("true");
} else if (pt.getName().equalsIgnoreCase("httpPostRespURL")) {
this.assertionConsumerURL = pt.getValue();
} else if (pt.getName().equalsIgnoreCase("defaultNameId")) {
this.nameIDType = pt.getValue();
} else if (pt.getName().equalsIgnoreCase("nameIdMap")) {
this.nameIDAttribute = pt.getValue().substring(pt.getValue().indexOf('=') + 1);
} else if (pt.getName().equalsIgnoreCase("defaultAuthCtx")) {
this.authnCtxClassRef = pt.getValue();
}
}
String issuerHost = config.getAttribute("issuerHost").getValues().get(0);
String issuerPort = config.getAttribute("issuerPort").getValues().get(0);
boolean issuerSSL = config.getAttribute("issuerSSL").getValues().get(0).equalsIgnoreCase("true");
StringBuffer b = new StringBuffer();
if (issuerSSL) {
b.append("https://");
} else {
b.append("http://");
}
b.append(issuerHost);
if (!issuerPort.isEmpty()) {
b.append(':').append(issuerPort);
}
b.append("/auth/idp/").append(idpName);
this.issuer = b.toString();
// this.issuer = config.getAttribute("issuer").getValues().get(0);
this.audience = tt.getName();
this.relayState = config.getAttribute("relayState").getValues().get(0);
InitializationService.initialize();
this.url = this.assertionConsumerURL;
} else {
this.url = config.getAttribute("url").getValues().get(0);
}
URL nurl = new URL(this.url);
this.uri = nurl.getPath();
UrlType urlCfg = config.getConfigManager().findURL(this.url).getUrl();
for (FilterConfigType filterCfg : urlCfg.getFilterChain().getFilter()) {
if (filterCfg.getClazz().equalsIgnoreCase("com.tremolosecurity.proxy.filters.LastMile")) {
for (ParamWithValueType pt : filterCfg.getParam()) {
if (pt.getName().equalsIgnoreCase("encKeyAlias")) {
this.lastMileKeyAlias = pt.getValue();
} else if (pt.getName().equalsIgnoreCase("headerName")) {
this.headerName = pt.getValue();
} else if (pt.getName().equalsIgnoreCase("userAttribute")) {
this.loginAttribute = pt.getValue();
}
}
for (ParamWithValueType pt : filterCfg.getParam()) {
if (pt.getName().equalsIgnoreCase("attribs")) {
String param = pt.getValue();
String fromUser = param.substring(0, param.indexOf('='));
String toApp = param.substring(param.indexOf('=') + 1);
if (fromUser.equalsIgnoreCase(this.headerName)) {
this.headerName = toApp;
}
}
}
}
}
logger.info("URL : '" + this.url + "'");
logger.info("Key Alias : '" + this.lastMileKeyAlias + "'");
logger.info("Login ID Attribute : '" + this.loginAttribute + "'");
logger.info("Header Attribute : '" + this.headerName + "'");
if (this.postSAML) {
logger.info("Saml : true");
logger.info("Issuer : " + this.issuer);
}
}
use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.
the class ScaleMain method loadWorkflows.
private void loadWorkflows(HttpFilterRequest request, HttpFilterResponse response, Gson gson) throws Exception {
String orgid = request.getRequestURI().substring(request.getRequestURI().lastIndexOf('/') + 1);
ConfigManager cfgMgr = GlobalEntries.getGlobalEntries().getConfigManager();
HashSet<String> allowedOrgs = new HashSet<String>();
AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
OrgType ot = GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getProvisioning().getOrg();
AzSys az = new AzSys();
this.checkOrg(allowedOrgs, ot, az, userData, request.getSession());
if (!allowedOrgs.contains(orgid)) {
response.setStatus(401);
response.setContentType("application/json");
ScaleError error = new ScaleError();
error.getErrors().add("Unauthorized");
ScaleJSUtils.addCacheHeaders(response);
response.getWriter().print(gson.toJson(error).trim());
response.getWriter().flush();
} else {
List<WorkflowType> wfs = GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getProvisioning().getWorkflows().getWorkflow();
ArrayList<WFDescription> workflows = new ArrayList<WFDescription>();
for (WorkflowType wf : wfs) {
if (wf.isInList() != null && wf.isInList().booleanValue()) {
if (wf.getOrgid() == null || wf.getOrgid().equalsIgnoreCase(orgid)) {
if (wf.getDynamicConfiguration() != null && wf.getDynamicConfiguration().isDynamic()) {
HashMap<String, Attribute> params = new HashMap<String, Attribute>();
if (wf.getDynamicConfiguration().getParam() != null) {
for (ParamType p : wf.getDynamicConfiguration().getParam()) {
Attribute attr = params.get(p.getName());
if (attr == null) {
attr = new Attribute(p.getName());
params.put(p.getName(), attr);
}
attr.getValues().add(p.getValue());
}
}
DynamicWorkflow dwf = (DynamicWorkflow) Class.forName(wf.getDynamicConfiguration().getClassName()).newInstance();
List<Map<String, String>> wfParams = dwf.generateWorkflows(wf, cfgMgr, params, userData);
StringBuffer b = new StringBuffer();
b.append('/').append(URLEncoder.encode(wf.getName(), "UTF-8"));
String uri = b.toString();
for (Map<String, String> wfParamSet : wfParams) {
DateTime now = new DateTime();
DateTime expires = now.plusHours(1);
LastMile lm = new LastMile(uri, now, expires, 0, "");
for (String key : wfParamSet.keySet()) {
String val = wfParamSet.get(key);
Attribute attr = new Attribute(key, val);
lm.getAttributes().add(attr);
}
WFDescription desc = new WFDescription();
desc.setUuid(UUID.randomUUID().toString());
desc.setName(wf.getName());
ST st = new ST(wf.getLabel(), '$', '$');
for (String key : wfParamSet.keySet()) {
st.add(key.replaceAll("[.]", "_"), wfParamSet.get(key));
}
desc.setLabel(st.render());
st = new ST(wf.getDescription(), '$', '$');
for (String key : wfParamSet.keySet()) {
st.add(key.replaceAll("[.]", "_"), wfParamSet.get(key));
}
desc.setDescription(st.render());
desc.setEncryptedParams(lm.generateLastMileToken(cfgMgr.getSecretKey(cfgMgr.getCfg().getProvisioning().getApprovalDB().getEncryptionKey())));
workflows.add(desc);
}
} else {
WFDescription desc = new WFDescription();
desc.setUuid(UUID.randomUUID().toString());
desc.setName(wf.getName());
desc.setLabel(wf.getLabel());
desc.setDescription(wf.getDescription());
workflows.add(desc);
}
}
}
}
ScaleJSUtils.addCacheHeaders(response);
response.setContentType("application/json");
response.getWriter().println(gson.toJson(workflows).trim());
response.getWriter().flush();
}
}
use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.
the class OpenUnisonOnUndertow method main.
public static void main(String[] args) throws Exception {
OpenUnisonConfig config = null;
logger.info("Starting OpenUnison on Undertow " + OpenUnisonServletFilter.version);
if (args.length == 0) {
logger.error("One argument required, path to yaml or json config");
System.exit(1);
} else if (args[0].endsWith(".yaml")) {
logger.info("Parsing YAML : '" + args[0] + "'");
Yaml yaml = new Yaml();
Map<String, Object> map = (Map<String, Object>) yaml.load(new FileInputStream(args[0]));
JSONObject jsonObject = new JSONObject(map);
String json = jsonObject.toJSONString();
config = gson.fromJson(json, OpenUnisonConfig.class);
} else {
logger.info("Parsing JSON : '" + args[0] + "'");
config = gson.fromJson(new InputStreamReader(new FileInputStream(args[0])), OpenUnisonConfig.class);
}
final OpenUnisonConfig fconfig = config;
if (config.getContextRoot() == null) {
config.setContextRoot("/");
}
logger.info("Config Open Port : '" + config.getOpenPort() + "'");
logger.info("Disable HTTP2 : '" + config.isDisableHttp2() + "'");
logger.info("Allow unescaped characters : '" + config.isAllowUnEscapedChars() + "'");
logger.info("Config Open External Port : '" + config.getOpenExternalPort() + "'");
logger.info("Config Secure Port : '" + config.getSecurePort() + "'");
logger.info("Config Secure External Port : '" + config.getSecureExternalPort() + "'");
logger.info("Config Context Root : '" + config.getContextRoot() + "'");
logger.info("Force to Secure : '" + config.isForceToSecure() + "'");
logger.info("ActiveMQ Directory : '" + config.getActivemqDir() + "'");
logger.info("Quartz Directory : '" + config.getQuartzDir() + "'");
logger.info("Config TLS Client Auth Mode : '" + config.getClientAuth() + "'");
logger.info("Config TLS Allowed Client Subjects : '" + config.getAllowedClientNames() + "'");
logger.info("Config TLS Protocols : '" + config.getAllowedTlsProtocols() + "'");
logger.info("Config TLS Ciphers : '" + config.getCiphers() + "'");
logger.info("Config Path to Deployment : '" + config.getPathToDeployment() + "'");
logger.info("Config Path to Environment File : '" + config.getPathToEnvFile() + "'");
logger.info("Redirect to contex root : '" + config.isRedirectToContextRoot() + "'");
logger.info("Support socket shutdown : " + config.isSocketShutdownListener());
if (config.isSocketShutdownListener()) {
logger.info("Socket shutdown host : '" + config.getSocketShutdownHost() + "'");
logger.info("Socket shutdown port : '" + config.getSocketShutdownPort() + "'");
logger.info("Socket shutdown command : '" + config.getSocketShutdownCommand() + "'");
}
logger.info("Override Queue Configuration : '" + config.getQueueConfiguration() != null + "'");
logger.info("Creating unisonServiceProps");
File f = File.createTempFile("unisonService", "props");
logger.info("Temporary unisonServiceProps : '" + f.getAbsolutePath() + "'");
Properties unisonServiceProps = new Properties();
unisonServiceProps.put("com.tremolosecurity.openunison.forceToSSL", Boolean.toString(config.isForceToSecure()));
unisonServiceProps.put("com.tremolosecurity.openunison.openPort", Integer.toString(config.getOpenPort()));
unisonServiceProps.put("com.tremolosecurity.openunison.securePort", Integer.toString(config.getSecurePort()));
unisonServiceProps.put("com.tremolosecurity.openunison.externalOpenPort", Integer.toString(config.getOpenExternalPort()));
unisonServiceProps.put("com.tremolosecurity.openunison.externalSecurePort", Integer.toString(config.getSecureExternalPort()));
if (config.getActivemqDir() != null) {
unisonServiceProps.put("com.tremolosecurity.openunison.activemqdir", config.getActivemqDir());
}
if (config.getQuartzDir() != null) {
unisonServiceProps.put("com.tremolosecurity.openunison.quartzdir", config.getQuartzDir());
}
unisonServiceProps.store(new FileOutputStream(f), "OpenUnison Configuration");
System.getProperties().put("com.tremolosecurity.unison.unisonServicePropsPath", f.getAbsolutePath());
System.getProperties().put("com.tremolosecurity.unison.unisonXML", config.getPathToDeployment() + "/webapp/WEB-INF/unison.xml");
logger.info("Loading environment file : '" + config.getPathToEnvFile() + "'");
Properties env = new Properties();
env.load(new FileInputStream(config.getPathToEnvFile()));
for (Object name : env.keySet()) {
logger.info("Adding property : '" + name + "'");
System.setProperty((String) name, env.getProperty((String) name));
}
if (config.getQueueConfiguration() != null) {
QueueConfigType qc = new QueueConfigType();
qc.setConnectionFactory(config.getQueueConfiguration().getConnectionFactory());
qc.setEncryptionKeyName(config.getQueueConfiguration().getEncryptionKeyName());
qc.setIsUseInternalQueue(config.getQueueConfiguration().isUseInternalQueue());
qc.setKeepAliveMillis(config.getQueueConfiguration().getKeepAliveMillis());
qc.setMaxConsumers(((Long) config.getQueueConfiguration().getMaxConsumers()).intValue());
qc.setMaxProducers(((Long) config.getQueueConfiguration().getMaxProducers()).intValue());
qc.setMaxSessionsPerConnection(((Long) config.getQueueConfiguration().getMaxSessionsPerConnection()).intValue());
qc.setMultiTaskQueues(config.getQueueConfiguration().isMultiTaskQueues());
qc.setNumQueues(((Long) config.getQueueConfiguration().getNumQueues()).intValue());
qc.setSmtpQueueName(config.getQueueConfiguration().getSmtpQueueName());
qc.setTaskQueueName(config.getQueueConfiguration().getTaskQueueName());
for (QueueConfigParam param : config.getQueueConfiguration().getParams()) {
ParamType pt = new ParamType();
pt.setName(param.getName());
if (param.getSourceType().equalsIgnoreCase("static")) {
pt.setValue(param.getValue());
} else {
pt.setValue(System.getProperty(param.getValue()));
}
qc.getParam().add(pt);
}
GlobalEntries.getGlobalEntries().set("openunison.queueconfig", qc);
}
logger.info("Loading keystore for Undertow");
String unisonXML = config.getPathToDeployment() + "/webapp/WEB-INF/unison.xml";
logger.info("OpenUnison XML File : '" + unisonXML + "'");
String unisonXMLContent = OpenUnisonConfigLoader.generateOpenUnisonConfig(unisonXML);
JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.config.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
Object obj = unmarshaller.unmarshal(new ByteArrayInputStream(unisonXMLContent.getBytes("UTF-8")));
JAXBElement<TremoloType> cfg = (JAXBElement<TremoloType>) obj;
TremoloType unisonConfiguration = cfg.getValue();
logger.info("Loading keystore : '" + unisonConfiguration.getKeyStorePath() + "'");
logger.info("Building Undertow");
Builder buildUndertow = Undertow.builder();
buildUndertow.setServerOption(UndertowOptions.NO_REQUEST_TIMEOUT, 60000);
logger.info("Check if enabling HTTP2 - " + config.isDisableHttp2());
if (!config.isDisableHttp2()) {
logger.info("Enabling HTTP2");
buildUndertow.setServerOption(UndertowOptions.ENABLE_HTTP2, true);
}
if (config.getOpenPort() > 0) {
buildUndertow.addHttpListener(config.getOpenPort(), "0.0.0.0");
logger.info("Adding open port : '" + config.getOpenPort() + "'");
}
if (config.getSecurePort() > 0) {
setupTlsListener(config, unisonConfiguration, buildUndertow);
}
File pathToWebApp = new File(config.getPathToDeployment() + "/webapp");
logger.info("Path to webapp : '" + pathToWebApp.getAbsolutePath() + "'");
logger.info("Path directory? : '" + pathToWebApp.isDirectory() + "'");
logger.info("Path exists : '" + pathToWebApp.exists() + "'");
DeploymentInfo servletBuilder = Servlets.deployment().setClassLoader(OpenUnisonOnUndertow.class.getClassLoader()).setEagerFilterInit(true).setContextPath(config.getContextRoot()).setDeploymentName("openunison").addFilter(Servlets.filter("openunison", com.tremolosecurity.openunison.OpenUnisonServletFilter.class).addInitParam("mode", "appliance")).addFilterUrlMapping("openunison", "/*", DispatcherType.REQUEST).setResourceManager(new FileResourceManager(pathToWebApp, 1024, true, true)).addServlet(JspServletBuilder.createServlet("Default Jsp Servlet", "*.jsp")).addServlet(Servlets.servlet("identityProvider", com.tremolosecurity.idp.server.IDP.class).addMapping("/auth/idp/*"));
if (config.getWelcomePages() != null) {
servletBuilder.addWelcomePages(config.getWelcomePages());
}
if (config.getErrorPages() != null) {
logger.info("Adding error pages");
ArrayList<ErrorPage> errorPages = new ArrayList<ErrorPage>();
for (ErrorPageConfig ep : config.getErrorPages()) {
if (ep.getCode() == 0) {
logger.info("Adding default page: " + ep.getLocation());
errorPages.add(new ErrorPage(ep.getLocation()));
} else {
logger.info("Adding page for " + ep.getCode() + " : " + ep.getLocation());
errorPages.add(new ErrorPage(ep.getLocation(), ep.getCode()));
}
}
servletBuilder.addErrorPages(errorPages);
}
JspServletBuilder.setupDeployment(servletBuilder, new HashMap<String, JspPropertyGroup>(), new HashMap<String, TagLibraryInfo>(), new HackInstanceManager());
DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
manager.deploy();
PathHandler path = Handlers.path(Handlers.redirect(config.getContextRoot())).addPrefixPath(config.getContextRoot(), manager.start());
if (config.isForceToLowerCase()) {
buildUndertow.setHandler(new OpenUnisonPathHandler(path));
} else {
buildUndertow.setHandler(path);
}
if (!config.getContextRoot().equals("/")) {
if (!config.isRedirectToContextRoot()) {
logger.info("Not redirecting to context");
servletBuilder = Servlets.deployment().setClassLoader(OpenUnisonOnUndertow.class.getClassLoader()).setEagerFilterInit(true).setContextPath("/").setDeploymentName("root");
manager = Servlets.defaultContainer().addDeployment(servletBuilder);
manager.deploy();
path.addPrefixPath("/", manager.start());
} else {
logger.info("Redirecting to context");
path.addPrefixPath("/", new RedirectHandler(config.getContextRoot()));
}
}
if (config.isAllowUnEscapedChars()) {
buildUndertow.setServerOption(UndertowOptions.ALLOW_UNESCAPED_CHARACTERS_IN_URL, true);
}
undertow = buildUndertow.build();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
logger.info("Shutting down");
undertow.stop();
GlobalEntries.getGlobalEntries().getConfigManager().clearThreads();
if (myvd != null) {
try {
myvd.shutdown();
} catch (Exception e) {
logger.warn("Did not gracefullt stop directory service", e);
}
}
}
});
if (config.isSocketShutdownListener()) {
new Thread() {
public void run() {
logger.info("Starting shutdown socket listener");
try {
ServerSocket socket = new ServerSocket(fconfig.getSocketShutdownPort(), 0, InetAddress.getByName(fconfig.getSocketShutdownHost()));
while (true) {
logger.info("shutdown waiting for input");
Socket clientSocket = null;
try {
clientSocket = socket.accept();
} catch (Throwable t) {
logger.warn("Could not accept connection", t);
continue;
}
logger.info("request received");
// PrintWriter out =
// new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
logger.info("reading data");
String command = in.readLine();
logger.info("'" + command + "'");
if (command != null) {
command.trim();
}
logger.info("'" + command + "'");
if (fconfig.getSocketShutdownCommand().equalsIgnoreCase(command)) {
logger.info("Stopping threads");
GlobalEntries.getGlobalEntries().getConfigManager().clearThreads();
logger.info("Shutting down undertow");
undertow.stop();
if (myvd != null) {
try {
myvd.shutdown();
} catch (Exception e) {
logger.warn("Did not gracefullt stop directory service", e);
}
}
logger.info("Closing input stream");
try {
in.close();
} catch (Throwable t) {
}
/*try {
out.close();
} catch (Throwable t) {}*/
logger.info("Closing client socket");
try {
clientSocket.close();
} catch (Throwable t) {
}
logger.info("Closing server socket");
try {
socket.close();
} catch (Throwable t) {
}
logger.info("Sleeping for 10 seconds");
try {
Thread.sleep(10000);
logger.info("Exiting");
System.exit(0);
return;
} catch (Exception e) {
}
} else {
command = null;
logger.info("invalid command");
try {
in.close();
} catch (Throwable t) {
}
/*try {
out.close();
} catch (Throwable t) {}
*/
try {
clientSocket.close();
} catch (Throwable t) {
}
}
}
} catch (IOException e) {
logger.error("Could not start shutdown listener", e);
}
}
}.start();
}
undertow.start();
if (config.getLdapPort() != 0 || config.getLdapsPort() != 0) {
myvd = (MyVDWrapper) Class.forName("com.tremolosecurity.openunison.myvd.MyVDOnUndertow").newInstance();
myvd.startMyVD(config, unisonConfiguration);
}
}
Aggregations