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