View Javadoc
1   package org.argeo.cms.internal.kernel;
2   
3   import static org.argeo.cms.internal.kernel.KernelUtils.getFrameworkProp;
4   
5   import java.io.File;
6   import java.io.FileFilter;
7   import java.io.IOException;
8   import java.net.InetAddress;
9   import java.net.URI;
10  import java.nio.file.Files;
11  import java.nio.file.Path;
12  import java.security.KeyStore;
13  import java.util.ArrayList;
14  import java.util.Arrays;
15  import java.util.Dictionary;
16  import java.util.Hashtable;
17  import java.util.List;
18  
19  import javax.security.auth.x500.X500Principal;
20  
21  import org.apache.commons.io.FileUtils;
22  import org.apache.commons.logging.Log;
23  import org.apache.commons.logging.LogFactory;
24  import org.argeo.api.NodeConstants;
25  import org.argeo.cms.CmsException;
26  import org.argeo.cms.internal.http.InternalHttpConstants;
27  import org.argeo.cms.internal.jcr.RepoConf;
28  import org.argeo.osgi.useradmin.UserAdminConf;
29  
30  /**
31   * Interprets framework properties in order to generate the initial deploy
32   * configuration.
33   */
34  class InitUtils {
35  	private final static Log log = LogFactory.getLog(InitUtils.class);
36  
37  	/** Override the provided config with the framework properties */
38  	static Dictionary<String, Object> getNodeRepositoryConfig(Dictionary<String, Object> provided) {
39  		Dictionary<String, Object> props = provided != null ? provided : new Hashtable<String, Object>();
40  		for (RepoConf repoConf : RepoConf.values()) {
41  			Object value = getFrameworkProp(NodeConstants.NODE_REPO_PROP_PREFIX + repoConf.name());
42  			if (value != null) {
43  				props.put(repoConf.name(), value);
44  				if (log.isDebugEnabled())
45  					log.debug("Set node repo configuration " + repoConf.name() + " to " + value);
46  			}
47  		}
48  		props.put(NodeConstants.CN, NodeConstants.NODE_REPOSITORY);
49  		return props;
50  	}
51  
52  	static Dictionary<String, Object> getRepositoryConfig(String dataModelName, Dictionary<String, Object> provided) {
53  		if (dataModelName.equals(NodeConstants.NODE_REPOSITORY) || dataModelName.equals(NodeConstants.EGO_REPOSITORY))
54  			throw new IllegalArgumentException("Data model '" + dataModelName + "' is reserved.");
55  		Dictionary<String, Object> props = provided != null ? provided : new Hashtable<String, Object>();
56  		for (RepoConf repoConf : RepoConf.values()) {
57  			Object value = getFrameworkProp(
58  					NodeConstants.NODE_REPOS_PROP_PREFIX + dataModelName + '.' + repoConf.name());
59  			if (value != null) {
60  				props.put(repoConf.name(), value);
61  				if (log.isDebugEnabled())
62  					log.debug("Set " + dataModelName + " repo configuration " + repoConf.name() + " to " + value);
63  			}
64  		}
65  		if (props.size() != 0)
66  			props.put(NodeConstants.CN, dataModelName);
67  		return props;
68  	}
69  
70  	/** Override the provided config with the framework properties */
71  	static Dictionary<String, Object> getHttpServerConfig(Dictionary<String, Object> provided) {
72  		String httpPort = getFrameworkProp("org.osgi.service.http.port");
73  		String httpsPort = getFrameworkProp("org.osgi.service.http.port.secure");
74  		/// TODO make it more generic
75  		String httpHost = getFrameworkProp(
76  				InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.HTTP_HOST);
77  		String httpsHost = getFrameworkProp(
78  				InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.HTTPS_HOST);
79  		String webSocketEnabled = getFrameworkProp(
80  				InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.WEBSOCKET_ENABLED);
81  
82  		final Hashtable<String, Object> props = new Hashtable<String, Object>();
83  		// try {
84  		if (httpPort != null || httpsPort != null) {
85  			boolean httpEnabled = httpPort != null;
86  			props.put(InternalHttpConstants.HTTP_ENABLED, httpEnabled);
87  			boolean httpsEnabled = httpsPort != null;
88  			props.put(InternalHttpConstants.HTTPS_ENABLED, httpsEnabled);
89  
90  			if (httpEnabled) {
91  				props.put(InternalHttpConstants.HTTP_PORT, httpPort);
92  				if (httpHost != null)
93  					props.put(InternalHttpConstants.HTTP_HOST, httpHost);
94  			}
95  
96  			if (httpsEnabled) {
97  				props.put(InternalHttpConstants.HTTPS_PORT, httpsPort);
98  				if (httpsHost != null)
99  					props.put(InternalHttpConstants.HTTPS_HOST, httpsHost);
100 
101 				// server certificate
102 				Path keyStorePath = KernelUtils.getOsgiInstancePath(KernelConstants.DEFAULT_KEYSTORE_PATH);
103 				String keyStorePassword = getFrameworkProp(
104 						InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.SSL_PASSWORD);
105 				if (keyStorePassword == null)
106 					keyStorePassword = "changeit";
107 				if (!Files.exists(keyStorePath))
108 					createSelfSignedKeyStore(keyStorePath, keyStorePassword, PkiUtils.PKCS12);
109 				props.put(InternalHttpConstants.SSL_KEYSTORETYPE, PkiUtils.PKCS12);
110 				props.put(InternalHttpConstants.SSL_KEYSTORE, keyStorePath.toString());
111 				props.put(InternalHttpConstants.SSL_PASSWORD, keyStorePassword);
112 
113 				// client certificate authentication
114 				String wantClientAuth = getFrameworkProp(
115 						InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.SSL_WANTCLIENTAUTH);
116 				if (wantClientAuth != null)
117 					props.put(InternalHttpConstants.SSL_WANTCLIENTAUTH, Boolean.parseBoolean(wantClientAuth));
118 				String needClientAuth = getFrameworkProp(
119 						InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.SSL_NEEDCLIENTAUTH);
120 				if (needClientAuth != null)
121 					props.put(InternalHttpConstants.SSL_NEEDCLIENTAUTH, Boolean.parseBoolean(needClientAuth));
122 			}
123 
124 			// web socket
125 			if (webSocketEnabled != null && webSocketEnabled.equals("true"))
126 				props.put(InternalHttpConstants.WEBSOCKET_ENABLED, true);
127 
128 			props.put(NodeConstants.CN, NodeConstants.DEFAULT);
129 		}
130 		return props;
131 	}
132 
133 	static List<Dictionary<String, Object>> getUserDirectoryConfigs() {
134 		List<Dictionary<String, Object>> res = new ArrayList<>();
135 		File nodeBaseDir = KernelUtils.getOsgiInstancePath(KernelConstants.DIR_NODE).toFile();
136 		List<String> uris = new ArrayList<>();
137 
138 		// node roles
139 		String nodeRolesUri = getFrameworkProp(NodeConstants.ROLES_URI);
140 		String baseNodeRoleDn = NodeConstants.ROLES_BASEDN;
141 		if (nodeRolesUri == null) {
142 			nodeRolesUri = baseNodeRoleDn + ".ldif";
143 			File nodeRolesFile = new File(nodeBaseDir, nodeRolesUri);
144 			if (!nodeRolesFile.exists())
145 				try {
146 					FileUtils.copyInputStreamToFile(InitUtils.class.getResourceAsStream(baseNodeRoleDn + ".ldif"),
147 							nodeRolesFile);
148 				} catch (IOException e) {
149 					throw new CmsException("Cannot copy demo resource", e);
150 				}
151 			// nodeRolesUri = nodeRolesFile.toURI().toString();
152 		}
153 		uris.add(nodeRolesUri);
154 
155 		// node tokens
156 		String nodeTokensUri = getFrameworkProp(NodeConstants.TOKENS_URI);
157 		String baseNodeTokensDn = NodeConstants.TOKENS_BASEDN;
158 		if (nodeTokensUri == null) {
159 			nodeTokensUri = baseNodeTokensDn + ".ldif";
160 			File nodeRolesFile = new File(nodeBaseDir, nodeRolesUri);
161 			if (!nodeRolesFile.exists())
162 				try {
163 					FileUtils.copyInputStreamToFile(InitUtils.class.getResourceAsStream(baseNodeTokensDn + ".ldif"),
164 							nodeRolesFile);
165 				} catch (IOException e) {
166 					throw new CmsException("Cannot copy demo resource", e);
167 				}
168 			// nodeRolesUri = nodeRolesFile.toURI().toString();
169 		}
170 		uris.add(nodeTokensUri);
171 
172 		// Business roles
173 		String userAdminUris = getFrameworkProp(NodeConstants.USERADMIN_URIS);
174 		if (userAdminUris == null) {
175 			String demoBaseDn = "dc=example,dc=com";
176 			userAdminUris = demoBaseDn + ".ldif";
177 			File businessRolesFile = new File(nodeBaseDir, userAdminUris);
178 			File systemRolesFile = new File(nodeBaseDir, "ou=roles,ou=node.ldif");
179 			if (!businessRolesFile.exists())
180 				try {
181 					FileUtils.copyInputStreamToFile(InitUtils.class.getResourceAsStream(demoBaseDn + ".ldif"),
182 							businessRolesFile);
183 					if (!systemRolesFile.exists())
184 						FileUtils.copyInputStreamToFile(
185 								InitUtils.class.getResourceAsStream("example-ou=roles,ou=node.ldif"), systemRolesFile);
186 				} catch (IOException e) {
187 					throw new CmsException("Cannot copy demo resources", e);
188 				}
189 			// userAdminUris = businessRolesFile.toURI().toString();
190 			log.warn("## DEV Using dummy base DN " + demoBaseDn);
191 			// TODO downgrade security level
192 		}
193 		for (String userAdminUri : userAdminUris.split(" "))
194 			uris.add(userAdminUri);
195 
196 		// Interprets URIs
197 		for (String uri : uris) {
198 			URI u;
199 			try {
200 				u = new URI(uri);
201 				if (u.getPath() == null)
202 					throw new CmsException("URI " + uri + " must have a path in order to determine base DN");
203 				if (u.getScheme() == null) {
204 					if (uri.startsWith("/") || uri.startsWith("./") || uri.startsWith("../"))
205 						u = new File(uri).getCanonicalFile().toURI();
206 					else if (!uri.contains("/")) {
207 						// u = KernelUtils.getOsgiInstanceUri(KernelConstants.DIR_NODE + '/' + uri);
208 						u = new URI(uri);
209 					} else
210 						throw new CmsException("Cannot interpret " + uri + " as an uri");
211 				} else if (u.getScheme().equals(UserAdminConf.SCHEME_FILE)) {
212 					u = new File(u).getCanonicalFile().toURI();
213 				}
214 			} catch (Exception e) {
215 				throw new CmsException("Cannot interpret " + uri + " as an uri", e);
216 			}
217 			Dictionary<String, Object> properties = UserAdminConf.uriAsProperties(u.toString());
218 			res.add(properties);
219 		}
220 
221 		return res;
222 	}
223 
224 	/**
225 	 * Called before node initialisation, in order populate OSGi instance are with
226 	 * some files (typically LDIF, etc).
227 	 */
228 	static void prepareFirstInitInstanceArea() {
229 		String nodeInit = getFrameworkProp(NodeConstants.NODE_INIT);
230 		if (nodeInit == null)
231 			nodeInit = "../../init";
232 		if (nodeInit.startsWith("http")) {
233 			// remoteFirstInit(nodeInit);
234 			return;
235 		}
236 
237 		// TODO use java.nio.file
238 		File initDir;
239 		if (nodeInit.startsWith("."))
240 			initDir = KernelUtils.getExecutionDir(nodeInit);
241 		else
242 			initDir = new File(nodeInit);
243 		// TODO also uncompress archives
244 		if (initDir.exists())
245 			try {
246 				FileUtils.copyDirectory(initDir, KernelUtils.getOsgiInstanceDir(), new FileFilter() {
247 
248 					@Override
249 					public boolean accept(File pathname) {
250 						if (pathname.getName().equals(".svn") || pathname.getName().equals(".git"))
251 							return false;
252 						return true;
253 					}
254 				});
255 				log.info("CMS initialized from " + initDir.getCanonicalPath());
256 			} catch (IOException e) {
257 				throw new CmsException("Cannot initialize from " + initDir, e);
258 			}
259 	}
260 
261 	private static void createSelfSignedKeyStore(Path keyStorePath, String keyStorePassword, String keyStoreType) {
262 		// for (Provider provider : Security.getProviders())
263 		// System.out.println(provider.getName());
264 		File keyStoreFile = keyStorePath.toFile();
265 		char[] ksPwd = keyStorePassword.toCharArray();
266 		char[] keyPwd = Arrays.copyOf(ksPwd, ksPwd.length);
267 		if (!keyStoreFile.exists()) {
268 			try {
269 				keyStoreFile.getParentFile().mkdirs();
270 				KeyStore keyStore = PkiUtils.getKeyStore(keyStoreFile, ksPwd, keyStoreType);
271 				PkiUtils.generateSelfSignedCertificate(keyStore,
272 						new X500Principal("CN=" + InetAddress.getLocalHost().getHostName() + ",OU=UNSECURE,O=UNSECURE"),
273 						1024, keyPwd);
274 				PkiUtils.saveKeyStore(keyStoreFile, ksPwd, keyStore);
275 				if (log.isDebugEnabled())
276 					log.debug("Created self-signed unsecure keystore " + keyStoreFile);
277 			} catch (Exception e) {
278 				if (keyStoreFile.length() == 0)
279 					keyStoreFile.delete();
280 				log.error("Cannot create keystore " + keyStoreFile, e);
281 			}
282 		} else {
283 			throw new CmsException("Keystore " + keyStorePath + " already exists");
284 		}
285 	}
286 
287 }