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