]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/internal/runtime/CmsStateImpl.java
47a4b1ff6c3c61301fdf7839d8072eb780dcf5f6
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / runtime / CmsStateImpl.java
1 package org.argeo.cms.internal.runtime;
2
3 import java.io.File;
4 import java.io.FileFilter;
5 import java.io.IOException;
6 import java.io.Reader;
7 import java.net.InetAddress;
8 import java.net.URL;
9 import java.net.UnknownHostException;
10 import java.nio.charset.StandardCharsets;
11 import java.nio.file.Files;
12 import java.nio.file.Path;
13 import java.nio.file.Paths;
14 import java.security.KeyStore;
15 import java.util.ArrayList;
16 import java.util.Arrays;
17 import java.util.Collections;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Locale;
21 import java.util.Map;
22 import java.util.Objects;
23 import java.util.StringJoiner;
24 import java.util.UUID;
25
26 import javax.security.auth.login.Configuration;
27
28 import org.apache.commons.io.FileUtils;
29 import org.argeo.api.cms.CmsConstants;
30 import org.argeo.api.cms.CmsLog;
31 import org.argeo.api.cms.CmsState;
32 import org.argeo.api.uuid.UuidFactory;
33 import org.argeo.cms.CmsDeployProperty;
34 import org.argeo.cms.auth.ident.IdentClient;
35
36 /**
37 * Implementation of a {@link CmsState}, initialising the required services.
38 */
39 public class CmsStateImpl implements CmsState {
40 private final static CmsLog log = CmsLog.getLog(CmsStateImpl.class);
41
42 // REFERENCES
43 private Long availableSince;
44
45 private UUID uuid;
46 // private final boolean cleanState;
47 private String hostname;
48
49 private UuidFactory uuidFactory;
50
51 private final Map<CmsDeployProperty, String> deployPropertyDefaults;
52
53 public CmsStateImpl() {
54 Map<CmsDeployProperty, String> deployPropertyDefaults = new HashMap<>();
55 deployPropertyDefaults.put(CmsDeployProperty.NODE_INIT, "../../init");
56 deployPropertyDefaults.put(CmsDeployProperty.LOCALE, Locale.getDefault().toString());
57
58 // certificates
59 deployPropertyDefaults.put(CmsDeployProperty.SSL_KEYSTORETYPE, PkiUtils.PKCS12);
60 deployPropertyDefaults.put(CmsDeployProperty.SSL_PASSWORD, PkiUtils.DEFAULT_KEYSTORE_PASSWORD);
61 Path keyStorePath = getDataPath(PkiUtils.DEFAULT_KEYSTORE_PATH);
62 deployPropertyDefaults.put(CmsDeployProperty.SSL_KEYSTORE, keyStorePath.toAbsolutePath().toString());
63
64 Path trustStorePath = getDataPath(PkiUtils.DEFAULT_TRUSTSTORE_PATH);
65 deployPropertyDefaults.put(CmsDeployProperty.SSL_TRUSTSTORETYPE, PkiUtils.PKCS12);
66 deployPropertyDefaults.put(CmsDeployProperty.SSL_TRUSTSTOREPASSWORD, PkiUtils.DEFAULT_KEYSTORE_PASSWORD);
67 deployPropertyDefaults.put(CmsDeployProperty.SSL_TRUSTSTORE, trustStorePath.toAbsolutePath().toString());
68
69 this.deployPropertyDefaults = Collections.unmodifiableMap(deployPropertyDefaults);
70 }
71
72 public void start() {
73 // Runtime.getRuntime().addShutdownHook(new CmsShutdown());
74
75 try {
76 initSecurity();
77 // initArgeoLogger();
78
79 if (log.isTraceEnabled())
80 log.trace("CMS State started");
81
82 // String stateUuidStr = KernelUtils.getFrameworkProp(Constants.FRAMEWORK_UUID);
83 // this.uuid = UUID.fromString(stateUuidStr);
84 this.uuid = uuidFactory.timeUUID();
85 // this.cleanState = stateUuid.equals(frameworkUuid);
86 try {
87 this.hostname = InetAddress.getLocalHost().getHostName();
88 } catch (UnknownHostException e) {
89 log.error("Cannot set hostname: " + e);
90 }
91
92 availableSince = System.currentTimeMillis();
93 if (log.isDebugEnabled()) {
94 // log.debug("## CMS starting... stateUuid=" + this.stateUuid + (cleanState ? "
95 // (clean state) " : " "));
96 StringJoiner sb = new StringJoiner("\n");
97 CmsDeployProperty[] deployProperties = CmsDeployProperty.values();
98 Arrays.sort(deployProperties, (o1, o2) -> o1.name().compareTo(o2.name()));
99 for (CmsDeployProperty deployProperty : deployProperties) {
100 List<String> values = getDeployProperties(deployProperty);
101 for (int i = 0; i < values.size(); i++) {
102 String value = values.get(i);
103 if (value != null) {
104 boolean isDefault = deployPropertyDefaults.containsKey(deployProperty)
105 && value.equals(deployPropertyDefaults.get(deployProperty));
106 String line = deployProperty.getProperty() + (i == 0 ? "" : "." + i) + "=" + value
107 + (isDefault ? " (default)" : "");
108 sb.add(line);
109 }
110 }
111 }
112 log.debug("## CMS starting... (" + uuid + ")\n" + sb + "\n");
113 }
114
115 // initI18n();
116 // initServices();
117 if (!Files.exists(getDataPath(CmsConstants.NODE))) {// first init
118 firstInit();
119 }
120
121 } catch (RuntimeException | IOException e) {
122 log.error("## FATAL: CMS activator failed", e);
123 }
124 }
125
126 private void initSecurity() {
127 if (getDeployProperty(CmsDeployProperty.JAVA_LOGIN_CONFIG) == null) {
128 String jaasConfig = KernelConstants.JAAS_CONFIG;
129 URL url = getClass().getResource(jaasConfig);
130 // System.setProperty(KernelConstants.JAAS_CONFIG_PROP,
131 // url.toExternalForm());
132 KernelUtils.setJaasConfiguration(url);
133 }
134 // explicitly load JAAS configuration
135 Configuration.getConfiguration();
136
137 boolean initSsl = getDeployProperty(CmsDeployProperty.HTTPS_PORT) != null;
138 if (initSsl) {
139 initCertificates();
140 }
141 }
142
143 private void initCertificates() {
144 // server certificate
145 Path keyStorePath = Paths.get(getDeployProperty(CmsDeployProperty.SSL_KEYSTORE));
146 Path pemKeyPath = getDataPath(PkiUtils.DEFAULT_PEM_KEY_PATH);
147 Path pemCertPath = getDataPath(PkiUtils.DEFAULT_PEM_CERT_PATH);
148 char[] keyStorePassword = getDeployProperty(CmsDeployProperty.SSL_PASSWORD).toCharArray();
149
150 // Keystore
151 // if PEM files both exists, update the PKCS12 file
152 if (Files.exists(pemCertPath) && Files.exists(pemKeyPath)) {
153 // TODO check certificate update time? monitor changes?
154 KeyStore keyStore = PkiUtils.getKeyStore(keyStorePath, keyStorePassword,
155 getDeployProperty(CmsDeployProperty.SSL_KEYSTORETYPE));
156 try (Reader key = Files.newBufferedReader(pemKeyPath, StandardCharsets.US_ASCII);
157 Reader cert = Files.newBufferedReader(pemCertPath, StandardCharsets.US_ASCII);) {
158 PkiUtils.loadPem(keyStore, key, keyStorePassword, cert);
159 PkiUtils.saveKeyStore(keyStorePath, keyStorePassword, keyStore);
160 if (log.isDebugEnabled())
161 log.debug("PEM certificate stored in " + keyStorePath);
162 } catch (IOException e) {
163 log.error("Cannot read PEM files " + pemKeyPath + " and " + pemCertPath, e);
164 }
165 }
166
167 // Truststore
168 Path trustStorePath = Paths.get(getDeployProperty(CmsDeployProperty.SSL_TRUSTSTORE));
169 char[] trustStorePassword = getDeployProperty(CmsDeployProperty.SSL_TRUSTSTOREPASSWORD).toCharArray();
170
171 // IPA CA
172 Path ipaCaCertPath = Paths.get(PkiUtils.IPA_PEM_CA_CERT_PATH);
173 if (Files.exists(ipaCaCertPath)) {
174 KeyStore trustStore = PkiUtils.getKeyStore(trustStorePath, trustStorePassword,
175 getDeployProperty(CmsDeployProperty.SSL_TRUSTSTORETYPE));
176 try (Reader cert = Files.newBufferedReader(ipaCaCertPath, StandardCharsets.US_ASCII);) {
177 PkiUtils.loadPem(trustStore, null, trustStorePassword, cert);
178 PkiUtils.saveKeyStore(trustStorePath, trustStorePassword, trustStore);
179 if (log.isDebugEnabled())
180 log.debug("IPA CA certificate stored in " + trustStorePath);
181 } catch (IOException e) {
182 log.error("Cannot trust CA certificate", e);
183 }
184 }
185
186 if (!Files.exists(keyStorePath))
187 PkiUtils.createSelfSignedKeyStore(keyStorePath, keyStorePassword, PkiUtils.PKCS12);
188 // props.put(JettyHttpConstants.SSL_KEYSTORETYPE, PkiUtils.PKCS12);
189 // props.put(JettyHttpConstants.SSL_KEYSTORE, keyStorePath.toString());
190 // props.put(JettyHttpConstants.SSL_PASSWORD, new String(keyStorePassword));
191
192 // props.put(InternalHttpConstants.SSL_KEYSTORETYPE, "PKCS11");
193 // props.put(InternalHttpConstants.SSL_KEYSTORE, "../../nssdb");
194 // props.put(InternalHttpConstants.SSL_PASSWORD, keyStorePassword);
195
196 }
197
198 public void stop() {
199 if (log.isDebugEnabled())
200 log.debug("CMS stopping... (" + this.uuid + ")");
201
202 long duration = ((System.currentTimeMillis() - availableSince) / 1000) / 60;
203 log.info("## ARGEO CMS STOPPED after " + (duration / 60) + "h " + (duration % 60) + "min uptime ##");
204 }
205
206 private void firstInit() throws IOException {
207 log.info("## FIRST INIT ##");
208 List<String> nodeInits = getDeployProperties(CmsDeployProperty.NODE_INIT);
209 // if (nodeInits == null)
210 // nodeInits = "../../init";
211 CmsStateImpl.prepareFirstInitInstanceArea(nodeInits);
212 }
213
214 @Override
215 public String getDeployProperty(String property) {
216 CmsDeployProperty deployProperty = CmsDeployProperty.find(property);
217 if (deployProperty == null) {
218 // legacy
219 if (property.startsWith("argeo.node.")) {
220 return doGetDeployProperty(property);
221 }
222 if (property.equals("argeo.i18n.locales")) {
223 String value = doGetDeployProperty(property);
224 if (value != null) {
225 log.warn("Property " + property + " was ignored (value=" + value + ")");
226
227 }
228 return null;
229 }
230 throw new IllegalArgumentException("Unsupported deploy property " + property);
231 }
232 int index = CmsDeployProperty.getPropertyIndex(property);
233 return getDeployProperty(deployProperty, index);
234 }
235
236 @Override
237 public List<String> getDeployProperties(String property) {
238 CmsDeployProperty deployProperty = CmsDeployProperty.find(property);
239 if (deployProperty == null)
240 return new ArrayList<>();
241 return getDeployProperties(deployProperty);
242 }
243
244 public static List<String> getDeployProperties(CmsState cmsState, CmsDeployProperty deployProperty) {
245 return ((CmsStateImpl) cmsState).getDeployProperties(deployProperty);
246 }
247
248 public List<String> getDeployProperties(CmsDeployProperty deployProperty) {
249 List<String> res = new ArrayList<>(deployProperty.getMaxCount());
250 for (int i = 0; i < deployProperty.getMaxCount(); i++) {
251 // String propertyName = i == 0 ? deployProperty.getProperty() :
252 // deployProperty.getProperty() + "." + i;
253 String value = getDeployProperty(deployProperty, i);
254 res.add(i, value);
255 }
256 return res;
257 }
258
259 public static String getDeployProperty(CmsState cmsState, CmsDeployProperty deployProperty) {
260 return ((CmsStateImpl) cmsState).getDeployProperty(deployProperty);
261 }
262
263 public String getDeployProperty(CmsDeployProperty deployProperty) {
264 String value = getDeployProperty(deployProperty, 0);
265 return value;
266 }
267
268 public String getDeployProperty(CmsDeployProperty deployProperty, int index) {
269 String propertyName = deployProperty.getProperty() + (index == 0 ? "" : "." + index);
270 String value = doGetDeployProperty(propertyName);
271 if (value == null && index == 0) {
272 // try defaults
273 if (deployPropertyDefaults.containsKey(deployProperty)) {
274 value = deployPropertyDefaults.get(deployProperty);
275 if (deployProperty.isSystemPropertyOnly())
276 System.setProperty(deployProperty.getProperty(), value);
277 }
278
279 if (value == null) {
280 // try legacy properties
281 String legacyProperty = switch (deployProperty) {
282 case DIRECTORY -> "argeo.node.useradmin.uris";
283 case DB_URL -> "argeo.node.dburl";
284 case DB_USER -> "argeo.node.dbuser";
285 case DB_PASSWORD -> "argeo.node.dbpassword";
286 case HTTP_PORT -> "org.osgi.service.http.port";
287 case HTTPS_PORT -> "org.osgi.service.http.port.secure";
288 case HOST -> "org.eclipse.equinox.http.jetty.http.host";
289 case LOCALE -> "argeo.i18n.defaultLocale";
290
291 default -> null;
292 };
293 if (legacyProperty != null) {
294 value = doGetDeployProperty(legacyProperty);
295 if (value != null) {
296 log.warn("Retrieved deploy property " + deployProperty.getProperty()
297 + " through deprecated property " + legacyProperty);
298 }
299 }
300 }
301 }
302 if (index == 0 && deployProperty.isSystemPropertyOnly()) {
303 String systemPropertyValue = System.getProperty(deployProperty.getProperty());
304 if (!Objects.equals(value, systemPropertyValue))
305 throw new IllegalStateException(
306 "Property " + deployProperty + " must be a ssystem property, but its value is " + value
307 + ", while the system property value is " + systemPropertyValue);
308 }
309 return value != null ? value.toString() : null;
310 }
311
312 protected String getLegacyProperty(String legacyProperty, CmsDeployProperty deployProperty) {
313 String value = doGetDeployProperty(legacyProperty);
314 if (value != null) {
315 log.warn("Retrieved deploy property " + deployProperty.getProperty() + " through deprecated property "
316 + legacyProperty + ".");
317 }
318 return value;
319 }
320
321 protected String doGetDeployProperty(String property) {
322 return KernelUtils.getFrameworkProp(property);
323 }
324
325 @Override
326 public Path getDataPath(String relativePath) {
327 return KernelUtils.getOsgiInstancePath(relativePath);
328 }
329
330 @Override
331 public Long getAvailableSince() {
332 return availableSince;
333 }
334
335 /*
336 * ACCESSORS
337 */
338 public String getHostname() {
339 return hostname;
340 }
341
342 @Override
343 public UUID getUuid() {
344 return uuid;
345 }
346
347 public void setUuidFactory(UuidFactory uuidFactory) {
348 this.uuidFactory = uuidFactory;
349 }
350
351 /**
352 * Called before node initialisation, in order populate OSGi instance are with
353 * some files (typically LDIF, etc).
354 */
355 public static void prepareFirstInitInstanceArea(List<String> nodeInits) {
356
357 for (String nodeInit : nodeInits) {
358 if(nodeInit==null)
359 continue;
360
361 if (nodeInit.startsWith("http")) {
362 // TODO reconnect it
363 // registerRemoteInit(nodeInit);
364 } else {
365
366 // TODO use java.nio.file
367 File initDir;
368 if (nodeInit.startsWith("."))
369 initDir = KernelUtils.getExecutionDir(nodeInit);
370 else
371 initDir = new File(nodeInit);
372 // TODO also uncompress archives
373 if (initDir.exists())
374 try {
375 // TODO use NIO utilities
376 FileUtils.copyDirectory(initDir, KernelUtils.getOsgiInstancePath("").toFile(),
377 new FileFilter() {
378
379 @Override
380 public boolean accept(File pathname) {
381 if (pathname.getName().equals(".svn") || pathname.getName().equals(".git"))
382 return false;
383 return true;
384 }
385 });
386 log.info("CMS initialized from " + initDir.getCanonicalPath());
387 } catch (IOException e) {
388 throw new RuntimeException("Cannot initialize from " + initDir, e);
389 }
390 }
391 }
392 }
393
394 /*
395 * STATIC
396 */
397 public static IdentClient getIdentClient(String remoteAddr) {
398 if (!IdentClient.isDefaultAuthdPassphraseFileAvailable())
399 return null;
400 // TODO make passphrase more configurable
401 return new IdentClient(remoteAddr);
402 }
403 }