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