2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.digitalstrom.internal.lib.serverconnection.impl;
15 import java.io.ByteArrayInputStream;
17 import java.io.FileInputStream;
18 import java.io.FileNotFoundException;
19 import java.io.FileWriter;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.net.HttpURLConnection;
23 import java.net.MalformedURLException;
24 import java.net.SocketTimeoutException;
26 import java.nio.charset.StandardCharsets;
27 import java.security.KeyManagementException;
28 import java.security.NoSuchAlgorithmException;
29 import java.security.SecureRandom;
30 import java.security.Security;
31 import java.security.cert.CertificateEncodingException;
32 import java.security.cert.CertificateException;
33 import java.security.cert.CertificateFactory;
34 import java.security.cert.X509Certificate;
35 import java.util.Base64;
37 import javax.net.ssl.HostnameVerifier;
38 import javax.net.ssl.HttpsURLConnection;
39 import javax.net.ssl.SSLContext;
40 import javax.net.ssl.SSLHandshakeException;
41 import javax.net.ssl.SSLSession;
42 import javax.net.ssl.SSLSocketFactory;
43 import javax.net.ssl.TrustManager;
44 import javax.net.ssl.X509TrustManager;
46 import org.apache.commons.lang3.StringUtils;
47 import org.openhab.binding.digitalstrom.internal.lib.config.Config;
48 import org.openhab.binding.digitalstrom.internal.lib.manager.ConnectionManager;
49 import org.openhab.binding.digitalstrom.internal.lib.serverconnection.HttpTransport;
50 import org.openhab.binding.digitalstrom.internal.lib.serverconnection.simpledsrequestbuilder.constants.ParameterKeys;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
55 * The {@link HttpTransportImpl} executes a request to the digitalSTROM-Server.
57 * If a {@link Config} is given at the constructor. It sets the SSL-Certificate what is set in
58 * {@link Config#getCert()}. If there is no SSL-Certificate, but a path to an external SSL-Certificate file what is set
59 * in {@link Config#getTrustCertPath()} this will be set. If no SSL-Certificate is set in the {@link Config} it will be
60 * red out from the server and set in {@link Config#setCert(String)}.
63 * If no {@link Config} is given the SSL-Certificate will be stored locally.
66 * The method {@link #writePEMCertFile(String)} saves the SSL-Certificate in a file at the given path. If all
67 * SSL-Certificates shout be ignored the flag <i>exeptAllCerts</i> have to be true at the constructor
70 * If a {@link ConnectionManager} is given at the constructor, the session-token is not needed by requests and the
71 * {@link ConnectionListener}, which is registered at the {@link ConnectionManager}, will be automatically informed
73 * connection state changes through the {@link #execute(String, int, int)} method.
76 * @author Michael Ochel - Initial contribution
77 * @author Matthias Siegele - Initial contribution
79 public class HttpTransportImpl implements HttpTransport {
81 private static final String LINE_SEPERATOR = System.getProperty("line.separator");
82 private static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----" + LINE_SEPERATOR;
83 private static final String END_CERT = LINE_SEPERATOR + "-----END CERTIFICATE-----" + LINE_SEPERATOR;
85 private final Logger logger = LoggerFactory.getLogger(HttpTransportImpl.class);
86 private static final short MAY_A_NEW_SESSION_TOKEN_IS_NEEDED = 1;
90 private int connectTimeout;
91 private int readTimeout;
93 private Config config;
95 private ConnectionManager connectionManager;
98 private SSLSocketFactory sslSocketFactory;
99 private final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
102 public boolean verify(String arg0, SSLSession arg1) {
103 return arg0.equals(arg1.getPeerHost()) || arg0.contains("dss.local.");
108 * Creates a new {@link HttpTransportImpl} with registration of the given {@link ConnectionManager} and set ignore
109 * all SSL-Certificates. The {@link Config} will be automatically added from the configurations of the given
110 * {@link ConnectionManager}.
112 * @param connectionManager to check connection, can be null
113 * @param exeptAllCerts (true = all will ignore)
115 public HttpTransportImpl(ConnectionManager connectionManager, boolean exeptAllCerts) {
116 this.connectionManager = connectionManager;
117 this.config = connectionManager.getConfig();
118 init(config.getHost(), config.getConnectionTimeout(), config.getReadTimeout(), exeptAllCerts);
122 * Creates a new {@link HttpTransportImpl} with configurations of the given {@link Config} and set ignore all
125 * @param config to get configurations, must not be null
126 * @param exeptAllCerts (true = all will ignore)
128 public HttpTransportImpl(Config config, boolean exeptAllCerts) {
129 this.config = config;
130 init(config.getHost(), config.getConnectionTimeout(), config.getReadTimeout(), exeptAllCerts);
134 * Creates a new {@link HttpTransportImpl} with configurations of the given {@link Config}.
136 * @param config to get configurations, must not be null
138 public HttpTransportImpl(Config config) {
139 this.config = config;
140 init(config.getHost(), config.getConnectionTimeout(), config.getReadTimeout(), false);
144 * Creates a new {@link HttpTransportImpl}.
146 * @param uri of the server, must not be null
148 public HttpTransportImpl(String uri) {
149 init(uri, Config.DEFAULT_CONNECTION_TIMEOUT, Config.DEFAULT_READ_TIMEOUT, false);
153 * Creates a new {@link HttpTransportImpl} and set ignore all SSL-Certificates.
155 * @param uri of the server, must not be null
156 * @param exeptAllCerts (true = all will ignore)
158 public HttpTransportImpl(String uri, boolean exeptAllCerts) {
159 init(uri, Config.DEFAULT_CONNECTION_TIMEOUT, Config.DEFAULT_READ_TIMEOUT, exeptAllCerts);
163 * Creates a new {@link HttpTransportImpl}.
165 * @param uri of the server, must not be null
166 * @param connectTimeout to set
167 * @param readTimeout to set
169 public HttpTransportImpl(String uri, int connectTimeout, int readTimeout) {
170 init(uri, connectTimeout, readTimeout, false);
174 * Creates a new {@link HttpTransportImpl} and set ignore all SSL-Certificates..
176 * @param uri of the server, must not be null
177 * @param connectTimeout to set
178 * @param readTimeout to set
179 * @param exeptAllCerts (true = all will ignore)
181 public HttpTransportImpl(String uri, int connectTimeout, int readTimeout, boolean exeptAllCerts) {
182 init(uri, connectTimeout, readTimeout, exeptAllCerts);
185 private void init(String uri, int connectTimeout, int readTimeout, boolean exeptAllCerts) {
186 logger.debug("init HttpTransportImpl");
187 this.uri = fixURI(uri);
188 this.connectTimeout = connectTimeout;
189 this.readTimeout = readTimeout;
190 // Check SSL Certificate
192 sslSocketFactory = generateSSLContextWhichAcceptAllSSLCertificats();
194 if (config != null) {
195 cert = config.getCert();
196 logger.debug("generate SSLcontext from config cert");
197 if (cert != null && !cert.isBlank()) {
198 sslSocketFactory = generateSSLContextFromPEMCertString(cert);
200 String trustCertPath = config.getTrustCertPath();
201 if (trustCertPath != null && !trustCertPath.isBlank()) {
202 logger.debug("generate SSLcontext from config cert path");
203 cert = readPEMCertificateStringFromFile(trustCertPath);
204 if (cert != null && !cert.isBlank()) {
205 sslSocketFactory = generateSSLContextFromPEMCertString(cert);
208 logger.debug("generate SSLcontext from server");
209 cert = getPEMCertificateFromServer(this.uri);
210 sslSocketFactory = generateSSLContextFromPEMCertString(cert);
211 if (sslSocketFactory != null) {
212 config.setCert(cert);
217 logger.debug("generate SSLcontext from server");
218 cert = getPEMCertificateFromServer(this.uri);
219 sslSocketFactory = generateSSLContextFromPEMCertString(cert);
224 private String fixURI(String uri) {
225 String fixedURI = uri;
226 if (!fixedURI.startsWith("https://")) {
227 fixedURI = "https://" + fixedURI;
229 if (fixedURI.split(":").length != 3) {
230 fixedURI = fixedURI + ":8080";
235 private String fixRequest(String request) {
236 return request.replace(" ", "");
240 public String execute(String request) {
241 return execute(request, this.connectTimeout, this.readTimeout);
244 private short loginCounter = 0;
247 public String execute(String request, int connectTimeout, int readTimeout) {
248 // NOTE: We will only show exceptions in the debug level, because they will be handled in the checkConnection()
249 // method and this changes the bridge state. If a command was send it fails than and a sensorJob will be
250 // execute the next time, by TimeOutExceptions. By other exceptions the checkConnection() method handles it in
252 String response = null;
253 HttpsURLConnection connection = null;
255 String correctedRequest = checkSessionToken(request);
256 connection = getConnection(correctedRequest, connectTimeout, readTimeout);
257 if (connection != null) {
258 connection.connect();
259 final int responseCode = connection.getResponseCode();
260 if (responseCode != HttpURLConnection.HTTP_FORBIDDEN) {
261 if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
262 response = new String(connection.getErrorStream().readAllBytes(), StandardCharsets.UTF_8);
264 response = new String(connection.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
266 if (response != null) {
267 if (!response.contains("Authentication failed")) {
268 if (loginCounter > 0) {
269 connectionManager.checkConnection(responseCode);
273 connectionManager.checkConnection(ConnectionManager.AUTHENTIFICATION_PROBLEM);
279 connection.disconnect();
280 if (response == null && connectionManager != null
281 && loginCounter <= MAY_A_NEW_SESSION_TOKEN_IS_NEEDED) {
282 if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
283 execute(addSessionToken(correctedRequest, connectionManager.getNewSessionToken()),
284 connectTimeout, readTimeout);
287 connectionManager.checkConnection(responseCode);
294 } catch (SocketTimeoutException e) {
295 informConnectionManager(ConnectionManager.SOCKET_TIMEOUT_EXCEPTION);
296 } catch (java.net.ConnectException e) {
297 informConnectionManager(ConnectionManager.CONNECTION_EXCEPTION);
298 } catch (MalformedURLException e) {
299 informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION);
300 } catch (java.net.UnknownHostException e) {
301 informConnectionManager(ConnectionManager.UNKNOWN_HOST_EXCEPTION);
302 } catch (SSLHandshakeException e) {
303 informConnectionManager(ConnectionManager.SSL_HANDSHAKE_EXCEPTION);
304 } catch (IOException e) {
305 logger.error("An IOException occurred: ", e);
306 informConnectionManager(ConnectionManager.GENERAL_EXCEPTION);
308 if (connection != null) {
309 connection.disconnect();
315 private boolean informConnectionManager(int code) {
316 if (connectionManager != null && loginCounter < MAY_A_NEW_SESSION_TOKEN_IS_NEEDED) {
317 connectionManager.checkConnection(code);
323 private String checkSessionToken(String request) {
324 if (checkNeededSessionToken(request)) {
325 if (connectionManager != null) {
326 String sessionToken = connectionManager.getSessionToken();
327 if (sessionToken == null) {
328 return addSessionToken(request, connectionManager.getNewSessionToken());
330 return addSessionToken(request, sessionToken);
336 private boolean checkNeededSessionToken(String request) {
337 String functionName = StringUtils.substringAfterLast(StringUtils.substringBefore(request, "?"), "/");
338 return !DsAPIImpl.METHODS_MUST_NOT_BE_LOGGED_IN.contains(functionName);
341 private String addSessionToken(String request, String sessionToken) {
342 String correctedRequest = request;
343 if (!correctedRequest.contains(ParameterKeys.TOKEN)) {
344 if (correctedRequest.contains("?")) {
345 correctedRequest = correctedRequest + "&" + ParameterKeys.TOKEN + "=" + sessionToken;
347 correctedRequest = correctedRequest + "?" + ParameterKeys.TOKEN + "=" + sessionToken;
350 correctedRequest = StringUtils.replaceOnce(correctedRequest, StringUtils.substringBefore(
351 StringUtils.substringAfter(correctedRequest, ParameterKeys.TOKEN + "="), "&"), sessionToken);
354 return correctedRequest;
357 private HttpsURLConnection getConnection(String request, int connectTimeout, int readTimeout) throws IOException {
358 String correctedRequest = request;
359 if (correctedRequest != null && !correctedRequest.isBlank()) {
360 correctedRequest = fixRequest(correctedRequest);
361 URL url = new URL(this.uri + correctedRequest);
362 HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
363 if (connection != null) {
364 connection.setConnectTimeout(connectTimeout);
365 connection.setReadTimeout(readTimeout);
366 if (sslSocketFactory != null) {
367 connection.setSSLSocketFactory(sslSocketFactory);
369 if (hostnameVerifier != null) {
370 connection.setHostnameVerifier(hostnameVerifier);
379 public int checkConnection(String testRequest) {
381 HttpsURLConnection connection = getConnection(testRequest, connectTimeout, readTimeout);
382 if (connection != null) {
383 connection.connect();
384 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
385 if (new String(connection.getInputStream().readAllBytes(), StandardCharsets.UTF_8)
386 .contains("Authentication failed")) {
387 return ConnectionManager.AUTHENTIFICATION_PROBLEM;
390 connection.disconnect();
391 return connection.getResponseCode();
393 return ConnectionManager.GENERAL_EXCEPTION;
395 } catch (SocketTimeoutException e) {
396 return ConnectionManager.SOCKET_TIMEOUT_EXCEPTION;
397 } catch (java.net.ConnectException e) {
398 return ConnectionManager.CONNECTION_EXCEPTION;
399 } catch (MalformedURLException e) {
400 return ConnectionManager.MALFORMED_URL_EXCEPTION;
401 } catch (java.net.UnknownHostException e) {
402 return ConnectionManager.UNKNOWN_HOST_EXCEPTION;
403 } catch (IOException e) {
404 return ConnectionManager.GENERAL_EXCEPTION;
409 public int getSensordataConnectionTimeout() {
410 return config != null ? config.getSensordataConnectionTimeout() : Config.DEFAULT_SENSORDATA_CONNECTION_TIMEOUT;
414 public int getSensordataReadTimeout() {
415 return config != null ? config.getSensordataReadTimeout() : Config.DEFAULT_SENSORDATA_READ_TIMEOUT;
418 private String readPEMCertificateStringFromFile(String path) {
419 if (path == null || path.isBlank()) {
420 logger.error("Path is empty.");
422 File dssCert = new File(path);
423 if (dssCert.exists()) {
424 if (path.endsWith(".crt")) {
425 try (InputStream certInputStream = new FileInputStream(dssCert)) {
426 String cert = new String(certInputStream.readAllBytes(), StandardCharsets.UTF_8);
427 if (cert.startsWith(BEGIN_CERT)) {
430 logger.error("File is not a PEM certificate file. PEM-Certificates starts with: {}",
433 } catch (FileNotFoundException e) {
434 logger.error("Can't find a certificate file at the path: {}\nPlease check the path!", path);
435 } catch (IOException e) {
436 logger.error("An IOException occurred: ", e);
439 logger.error("File is not a certificate (.crt) file.");
442 logger.error("File not found");
449 public String writePEMCertFile(String path) {
450 String correctedPath = path == null ? "" : path.trim();
452 if (!correctedPath.isBlank()) {
453 certFilePath = new File(correctedPath);
454 boolean pathExists = certFilePath.exists();
456 pathExists = certFilePath.mkdirs();
458 if (pathExists && !correctedPath.endsWith("/")) {
459 correctedPath = correctedPath + "/";
462 InputStream certInputStream = new ByteArrayInputStream(cert.getBytes(StandardCharsets.UTF_8));
463 X509Certificate trustedCert;
465 trustedCert = (X509Certificate) CertificateFactory.getInstance("X.509")
466 .generateCertificate(certInputStream);
468 certFilePath = new File(
469 correctedPath + trustedCert.getSubjectDN().getName().split(",")[0].substring(2) + ".crt");
470 if (!certFilePath.exists()) {
471 certFilePath.createNewFile();
472 FileWriter writer = new FileWriter(certFilePath, true);
476 return certFilePath.getAbsolutePath();
478 logger.error("File allready exists!");
480 } catch (IOException e) {
481 logger.error("An IOException occurred: ", e);
482 } catch (CertificateException e1) {
483 logger.error("A CertificateException occurred: ", e1);
488 private SSLSocketFactory generateSSLContextFromPEMCertString(String pemCert) {
489 if (pemCert != null && !pemCert.isBlank() && pemCert.startsWith(BEGIN_CERT)) {
491 InputStream certInputStream = new ByteArrayInputStream(pemCert.getBytes(StandardCharsets.UTF_8));
492 final X509Certificate trustedCert = (X509Certificate) CertificateFactory.getInstance("X.509")
493 .generateCertificate(certInputStream);
495 final TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
498 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
503 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
504 throws CertificateException {
505 if (!certs[0].equals(trustedCert)) {
506 throw new CertificateException();
511 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
512 throws CertificateException {
513 if (!certs[0].equals(trustedCert)) {
514 throw new CertificateException();
519 SSLContext sslContext = SSLContext.getInstance("SSL");
520 sslContext.init(null, trustManager, new java.security.SecureRandom());
521 return sslContext.getSocketFactory();
522 } catch (NoSuchAlgorithmException e) {
523 logger.error("A NoSuchAlgorithmException occurred: ", e);
524 } catch (KeyManagementException e) {
525 logger.error("A KeyManagementException occurred: ", e);
526 } catch (CertificateException e) {
527 logger.error("A CertificateException occurred: ", e);
530 logger.error("Cert is empty");
535 private String getPEMCertificateFromServer(String host) {
536 HttpsURLConnection connection = null;
538 URL url = new URL(host);
540 connection = (HttpsURLConnection) url.openConnection();
541 connection.setHostnameVerifier(hostnameVerifier);
542 connection.setSSLSocketFactory(generateSSLContextWhichAcceptAllSSLCertificats());
543 connection.connect();
545 java.security.cert.Certificate[] cert = connection.getServerCertificates();
546 connection.disconnect();
548 byte[] by = ((X509Certificate) cert[0]).getEncoded();
549 if (by.length != 0) {
550 return BEGIN_CERT + Base64.getEncoder().encodeToString(by) + END_CERT;
552 } catch (MalformedURLException e) {
553 if (!informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION)) {
554 logger.error("A MalformedURLException occurred: ", e);
556 } catch (IOException e) {
557 short code = ConnectionManager.GENERAL_EXCEPTION;
558 if (e instanceof java.net.ConnectException) {
559 code = ConnectionManager.CONNECTION_EXCEPTION;
560 } else if (e instanceof java.net.UnknownHostException) {
561 code = ConnectionManager.UNKNOWN_HOST_EXCEPTION;
563 if (!informConnectionManager(code) || code == -1) {
564 logger.error("An IOException occurred: ", e);
566 } catch (CertificateEncodingException e) {
567 logger.error("A CertificateEncodingException occurred: ", e);
569 if (connection != null) {
570 connection.disconnect();
576 private SSLSocketFactory generateSSLContextWhichAcceptAllSSLCertificats() {
577 Security.addProvider(Security.getProvider("SunJCE"));
578 TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
581 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
586 public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
590 public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
595 SSLContext sslContext = SSLContext.getInstance("SSL");
597 sslContext.init(null, trustAllCerts, new SecureRandom());
599 return sslContext.getSocketFactory();
600 } catch (KeyManagementException e) {
601 logger.error("A KeyManagementException occurred", e);
602 } catch (NoSuchAlgorithmException e) {
603 logger.error("A NoSuchAlgorithmException occurred", e);