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
.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
;
33 import javax
.security
.auth
.login
.Configuration
;
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
;
45 * Implementation of a {@link CmsState}, initialising the required services.
47 public class CmsStateImpl
implements CmsState
{
48 private final static CmsLog log
= CmsLog
.getLog(CmsStateImpl
.class);
51 private Long availableSince
;
54 // private final boolean cleanState;
55 private String hostname
;
57 private UuidFactory uuidFactory
;
59 private final Map
<CmsDeployProperty
, String
> deployPropertyDefaults
;
61 public CmsStateImpl() {
62 this.deployPropertyDefaults
= Collections
.unmodifiableMap(createDeployPropertiesDefaults());
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());
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());
78 Path trustStorePath
= getDataPath(KernelConstants
.DEFAULT_TRUSTSTORE_PATH
);
79 if (trustStorePath
!= null) {
80 deployPropertyDefaults
.put(CmsDeployProperty
.SSL_TRUSTSTORE
, trustStorePath
.toAbsolutePath().toString());
82 deployPropertyDefaults
.put(CmsDeployProperty
.SSL_TRUSTSTORETYPE
, KernelConstants
.PKCS12
);
83 deployPropertyDefaults
.put(CmsDeployProperty
.SSL_TRUSTSTOREPASSWORD
, KernelConstants
.DEFAULT_KEYSTORE_PASSWORD
);
86 Path authorizedKeysPath
= getDataPath(KernelConstants
.NODE_SSHD_AUTHORIZED_KEYS_PATH
);
87 if (authorizedKeysPath
!= null) {
88 deployPropertyDefaults
.put(CmsDeployProperty
.SSHD_AUTHORIZEDKEYS
,
89 authorizedKeysPath
.toAbsolutePath().toString());
91 return deployPropertyDefaults
;
97 Path privateBase
= getDataPath(KernelConstants
.DIR_PRIVATE
);
98 if (privateBase
!= null && !Files
.exists(privateBase
)) {// first init
100 Files
.createDirectories(privateBase
);
104 // initArgeoLogger();
106 if (log
.isTraceEnabled())
107 log
.trace("CMS State started");
109 this.uuid
= uuidFactory
.timeUUID();
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(() -> {
118 String hostname
= InetAddress
.getLocalHost().getHostName();
120 } catch (UnknownHostException e
) {
121 throw new IllegalStateException("Cannot get local hostname", e
);
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
);
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
);
144 boolean isDefault
= deployPropertyDefaults
.containsKey(deployProperty
)
145 && value
.equals(deployPropertyDefaults
.get(deployProperty
));
146 String line
= deployProperty
.getProperty() + (i
== 0 ?
"" : "." + i
) + "=" + value
147 + (isDefault ?
" (default)" : "");
152 log
.debug("## CMS starting... (" + uuid
+ ")\n" + sb
+ "\n");
155 } catch (RuntimeException
| IOException e
) {
156 log
.error("## FATAL: CMS state failed", e
);
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
);
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
);
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
);
186 // explicitly load JAAS configuration
187 Configuration
.getConfiguration();
189 boolean initSsl
= getDeployProperty(CmsDeployProperty
.HTTPS_PORT
) != null;
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();
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
);
221 Path trustStorePath
= Paths
.get(getDeployProperty(CmsDeployProperty
.SSL_TRUSTSTORE
));
222 char[] trustStorePassword
= getDeployProperty(CmsDeployProperty
.SSL_TRUSTSTOREPASSWORD
).toCharArray();
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
);
240 // if (!Files.exists(keyStorePath))
241 // PkiUtils.createSelfSignedKeyStore(keyStorePath, keyStorePassword, PkiUtils.PKCS12);
245 if (log
.isDebugEnabled())
246 log
.debug("CMS stopping... (" + this.uuid
+ ")");
248 long duration
= ((System
.currentTimeMillis() - availableSince
) / 1000) / 60;
249 log
.info("## ARGEO CMS STOPPED after " + (duration
/ 60) + "h " + (duration
% 60) + "min uptime ##");
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
);
261 public String
getDeployProperty(String property
) {
262 CmsDeployProperty deployProperty
= CmsDeployProperty
.find(property
);
263 if (deployProperty
== null) {
265 if (property
.startsWith("argeo.node.")) {
266 return doGetDeployProperty(property
);
268 if (property
.equals("argeo.i18n.locales")) {
269 String value
= doGetDeployProperty(property
);
271 log
.warn("Property " + property
+ " was ignored (value=" + value
+ ")");
276 throw new IllegalArgumentException("Unsupported deploy property " + property
);
278 int index
= CmsDeployProperty
.getPropertyIndex(property
);
279 return getDeployProperty(deployProperty
, index
);
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
);
290 public static List
<String
> getDeployProperties(CmsState cmsState
, CmsDeployProperty deployProperty
) {
291 return ((CmsStateImpl
) cmsState
).getDeployProperties(deployProperty
);
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
);
305 public static String
getDeployProperty(CmsState cmsState
, CmsDeployProperty deployProperty
) {
306 return ((CmsStateImpl
) cmsState
).getDeployProperty(deployProperty
);
309 public String
getDeployProperty(CmsDeployProperty deployProperty
) {
310 String value
= getDeployProperty(deployProperty
, 0);
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) {
319 if (deployPropertyDefaults
.containsKey(deployProperty
)) {
320 value
= deployPropertyDefaults
.get(deployProperty
);
321 if (deployProperty
.isSystemPropertyOnly())
322 System
.setProperty(deployProperty
.getProperty(), value
);
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";
339 if (legacyProperty
!= null) {
340 value
= doGetDeployProperty(legacyProperty
);
342 log
.warn("Retrieved deploy property " + deployProperty
.getProperty()
343 + " through deprecated property " + legacyProperty
);
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
);
355 return value
!= null ? value
.toString() : null;
358 protected String
getLegacyProperty(String legacyProperty
, CmsDeployProperty deployProperty
) {
359 String value
= doGetDeployProperty(legacyProperty
);
361 log
.warn("Retrieved deploy property " + deployProperty
.getProperty() + " through deprecated property "
362 + legacyProperty
+ ".");
367 protected String
doGetDeployProperty(String property
) {
368 return KernelUtils
.getFrameworkProp(property
);
372 public Path
getDataPath(String relativePath
) {
373 return KernelUtils
.getOsgiInstancePath(relativePath
);
377 public Long
getAvailableSince() {
378 return availableSince
;
385 public UUID
getUuid() {
389 public void setUuidFactory(UuidFactory uuidFactory
) {
390 this.uuidFactory
= uuidFactory
;
393 public String
getHostname() {
398 * Called before node initialisation, in order populate OSGi instance are with
399 * some files (typically LDIF, etc).
401 public static void prepareFirstInitInstanceArea(List
<String
> nodeInits
) {
403 for (String nodeInit
: nodeInits
) {
404 if (nodeInit
== null)
407 if (nodeInit
.startsWith("http")) {
409 // registerRemoteInit(nodeInit);
412 // TODO use java.nio.file
414 if (nodeInit
.startsWith("."))
415 initDir
= KernelUtils
.getExecutionDir(nodeInit
);
417 initDir
= Paths
.get(nodeInit
);
418 // TODO also uncompress archives
419 if (Files
.exists(initDir
)) {
420 Path dataPath
= KernelUtils
.getOsgiInstancePath("");
421 FsUtils
.copyDirectory(initDir
, dataPath
);
422 log
.info("CMS initialized from " + initDir
);
431 public static IdentClient
getIdentClient(String remoteAddr
) {
432 if (!IdentClient
.isDefaultAuthdPassphraseFileAvailable())
434 // TODO make passphrase more configurable
435 return new IdentClient(remoteAddr
);