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