1 package org
.argeo
.cms
.internal
.runtime
;
3 import java
.io
.BufferedInputStream
;
4 import java
.io
.IOException
;
6 import java
.net
.InetAddress
;
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
;
23 import java
.util
.Objects
;
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
;
34 import javax
.security
.auth
.login
.Configuration
;
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
;
46 * Implementation of a {@link CmsState}, initialising the required services.
48 public class CmsStateImpl
implements CmsState
{
49 private final static CmsLog log
= CmsLog
.getLog(CmsStateImpl
.class);
52 private Long availableSince
;
55 // private final boolean cleanState;
56 private String hostname
;
58 private UuidFactory uuidFactory
;
60 private final Map
<CmsDeployProperty
, String
> deployPropertyDefaults
;
62 public CmsStateImpl() {
63 this.deployPropertyDefaults
= Collections
.unmodifiableMap(createDeployPropertiesDefaults());
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());
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());
79 Path trustStorePath
= getDataPath(KernelConstants
.DEFAULT_TRUSTSTORE_PATH
);
80 if (trustStorePath
!= null) {
81 deployPropertyDefaults
.put(CmsDeployProperty
.SSL_TRUSTSTORE
, trustStorePath
.toAbsolutePath().toString());
83 deployPropertyDefaults
.put(CmsDeployProperty
.SSL_TRUSTSTORETYPE
, KernelConstants
.PKCS12
);
84 deployPropertyDefaults
.put(CmsDeployProperty
.SSL_TRUSTSTOREPASSWORD
, KernelConstants
.DEFAULT_KEYSTORE_PASSWORD
);
87 Path authorizedKeysPath
= getDataPath(KernelConstants
.NODE_SSHD_AUTHORIZED_KEYS_PATH
);
88 if (authorizedKeysPath
!= null) {
89 deployPropertyDefaults
.put(CmsDeployProperty
.SSHD_AUTHORIZEDKEYS
,
90 authorizedKeysPath
.toAbsolutePath().toString());
92 return deployPropertyDefaults
;
98 Path privateBase
= getDataPath(KernelConstants
.DIR_PRIVATE
);
99 if (privateBase
!= null && !Files
.exists(privateBase
)) {// first init
101 Files
.createDirectories(privateBase
);
105 // initArgeoLogger();
107 if (log
.isTraceEnabled())
108 log
.trace("CMS State started");
110 this.uuid
= uuidFactory
.timeUUID();
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(() -> {
119 String hostname
= InetAddress
.getLocalHost().getHostName();
121 } catch (UnknownHostException e
) {
122 throw new IllegalStateException("Cannot get local hostname", e
);
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
);
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
);
145 boolean isDefault
= deployPropertyDefaults
.containsKey(deployProperty
)
146 && value
.equals(deployPropertyDefaults
.get(deployProperty
));
147 String line
= deployProperty
.getProperty() + (i
== 0 ?
"" : "." + i
) + "=" + value
148 + (isDefault ?
" (default)" : "");
153 log
.debug("## CMS starting... (" + uuid
+ ")\n" + sb
+ "\n");
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()));
162 log
.trace("System properties:\n" + sb
+ "\n");
166 } catch (RuntimeException
| IOException e
) {
167 log
.error("## FATAL: CMS state failed", e
);
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
);
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
);
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
);
197 // explicitly load JAAS configuration
198 Configuration
.getConfiguration();
200 boolean initCertificates
= (getDeployProperty(CmsDeployProperty
.HTTPS_PORT
) != null)
201 || (getDeployProperty(CmsDeployProperty
.SSHD_PORT
) != null);
202 if (initCertificates
) {
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();
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
);
233 Path trustStorePath
= Paths
.get(getDeployProperty(CmsDeployProperty
.SSL_TRUSTSTORE
));
234 char[] trustStorePassword
= getDeployProperty(CmsDeployProperty
.SSL_TRUSTSTOREPASSWORD
).toCharArray();
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
);
254 if (log
.isDebugEnabled())
255 log
.debug("CMS stopping... (" + this.uuid
+ ")");
257 long duration
= ((System
.currentTimeMillis() - availableSince
) / 1000) / 60;
258 log
.info("## ARGEO CMS STOPPED after " + (duration
/ 60) + "h " + (duration
% 60) + "min uptime ##");
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
);
270 public String
getDeployProperty(String property
) {
271 CmsDeployProperty deployProperty
= CmsDeployProperty
.find(property
);
272 if (deployProperty
== null) {
274 if (property
.startsWith("argeo.node.")) {
275 return doGetDeployProperty(property
);
277 if (property
.equals("argeo.i18n.locales")) {
278 String value
= doGetDeployProperty(property
);
280 log
.warn("Property " + property
+ " was ignored (value=" + value
+ ")");
285 throw new IllegalArgumentException("Unsupported deploy property " + property
);
287 int index
= CmsDeployProperty
.getPropertyIndex(property
);
288 return getDeployProperty(deployProperty
, index
);
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
);
299 public static List
<String
> getDeployProperties(CmsState cmsState
, CmsDeployProperty deployProperty
) {
300 return ((CmsStateImpl
) cmsState
).getDeployProperties(deployProperty
);
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
);
314 public static String
getDeployProperty(CmsState cmsState
, CmsDeployProperty deployProperty
) {
315 return ((CmsStateImpl
) cmsState
).getDeployProperty(deployProperty
);
318 public String
getDeployProperty(CmsDeployProperty deployProperty
) {
319 String value
= getDeployProperty(deployProperty
, 0);
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) {
328 if (deployPropertyDefaults
.containsKey(deployProperty
)) {
329 value
= deployPropertyDefaults
.get(deployProperty
);
330 if (deployProperty
.isSystemPropertyOnly())
331 System
.setProperty(deployProperty
.getProperty(), value
);
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";
348 if (legacyProperty
!= null) {
349 value
= doGetDeployProperty(legacyProperty
);
351 log
.warn("Retrieved deploy property " + deployProperty
.getProperty()
352 + " through deprecated property " + legacyProperty
);
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
);
364 return value
!= null ? value
.toString() : null;
367 protected String
getLegacyProperty(String legacyProperty
, CmsDeployProperty deployProperty
) {
368 String value
= doGetDeployProperty(legacyProperty
);
370 log
.warn("Retrieved deploy property " + deployProperty
.getProperty() + " through deprecated property "
371 + legacyProperty
+ ".");
376 protected String
doGetDeployProperty(String property
) {
377 return KernelUtils
.getFrameworkProp(property
);
381 public Path
getDataPath(String relativePath
) {
382 return KernelUtils
.getOsgiInstancePath(relativePath
);
386 public Path
getStatePath(String relativePath
) {
387 return KernelUtils
.getOsgiConfigurationPath(relativePath
);
391 public Long
getAvailableSince() {
392 return availableSince
;
399 public UUID
getUuid() {
403 public void setUuidFactory(UuidFactory uuidFactory
) {
404 this.uuidFactory
= uuidFactory
;
407 public String
getHostname() {
412 * Called before node initialisation, in order populate OSGi instance are with
413 * some files (typically LDIF, etc).
415 public static void prepareFirstInitInstanceArea(List
<String
> nodeInits
) {
417 for (String nodeInit
: nodeInits
) {
418 if (nodeInit
== null)
421 if (nodeInit
.startsWith("http")) {
423 // registerRemoteInit(nodeInit);
426 // TODO use java.nio.file
428 if (nodeInit
.startsWith("."))
429 initDir
= KernelUtils
.getExecutionDir(nodeInit
);
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
);
445 public static IdentClient
getIdentClient(String remoteAddr
) {
446 if (!IdentClient
.isDefaultAuthdPassphraseFileAvailable())
448 // TODO make passphrase more configurable
449 return new IdentClient(remoteAddr
);