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