2 * Copyright (c) 2010-2023 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.velux.internal.bridge.slip.io;
15 import java.io.Closeable;
16 import java.io.DataOutputStream;
17 import java.io.IOException;
18 import java.net.ConnectException;
19 import java.net.InetSocketAddress;
20 import java.net.UnknownHostException;
21 import java.security.KeyManagementException;
22 import java.security.NoSuchAlgorithmException;
23 import java.security.cert.CertificateException;
24 import java.security.cert.X509Certificate;
26 import javax.net.ssl.SSLContext;
27 import javax.net.ssl.SSLSocket;
28 import javax.net.ssl.TrustManager;
29 import javax.net.ssl.X509TrustManager;
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.openhab.binding.velux.internal.VeluxBindingConstants;
34 import org.openhab.binding.velux.internal.config.VeluxBridgeConfiguration;
35 import org.openhab.binding.velux.internal.handler.VeluxBridgeHandler;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
40 * Transport layer supported by the Velux bridge.
42 * SLIP-based 2nd Level I/O interface towards the <B>Velux</B> bridge.
44 * It provides methods for pre- and post-communication
45 * as well as a common method for the real communication.
47 * <LI>{@link SSLconnection#SSLconnection} for establishing the connection,</LI>
48 * <LI>{@link SSLconnection#send} for sending a message to the bridge,</LI>
49 * <LI>{@link SSLconnection#available} for observation whether there are bytes available,</LI>
50 * <LI>{@link SSLconnection#receive} for receiving a message from the bridge,</LI>
51 * <LI>{@link SSLconnection#close} for tearing down the connection.</LI>
52 * <LI>{@link SSLconnection#setTimeout} for adapting communication parameters.</LI>
55 * @author Guenther Schreiner - Initial contribution.
58 class SSLconnection implements Closeable {
59 private final Logger logger = LoggerFactory.getLogger(SSLconnection.class);
62 public static final SSLconnection UNKNOWN = new SSLconnection();
65 * ***************************
66 * ***** Private Objects *****
69 private @Nullable SSLSocket socket;
70 private @Nullable DataOutputStream dOut;
71 private @Nullable DataInputStreamWithTimeout dIn;
73 private int readTimeoutMSecs = 2000;
74 private int connTimeoutMSecs = 6000;
77 * Fake trust manager to suppress any certificate errors,
78 * used within {@link #SSLconnection} for seamless operation
79 * even on self-signed certificates like provided by <B>Velux</B>.
81 private final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
83 public X509Certificate @Nullable [] getAcceptedIssuers() {
88 public void checkClientTrusted(X509Certificate @Nullable [] arg0, @Nullable String arg1)
89 throws CertificateException {
93 public void checkServerTrusted(X509Certificate @Nullable [] arg0, @Nullable String arg1)
94 throws CertificateException {
99 * ************************
100 * ***** Constructors *****
104 * Constructor for initialization of an unfinished connectivity.
107 logger.debug("SSLconnection() called.");
111 * Constructor to setup and establish a connection.
113 * @param bridgeInstance the actual Bridge Thing instance
114 * @throws java.net.ConnectException in case of unrecoverable communication failures.
115 * @throws java.io.IOException in case of continuous communication I/O failures.
116 * @throws java.net.UnknownHostException in case of continuous communication I/O failures.
118 SSLconnection(VeluxBridgeHandler bridgeInstance) throws ConnectException, IOException, UnknownHostException {
119 logger.debug("Starting {} bridge connection.", VeluxBindingConstants.BINDING_ID);
120 SSLContext ctx = null;
122 ctx = SSLContext.getInstance("SSL");
123 ctx.init(null, trustAllCerts, null);
124 } catch (NoSuchAlgorithmException | KeyManagementException e) {
125 throw new IOException(String.format("create of an empty trust store failed: %s.", e.getMessage()));
127 logger.trace("SSLconnection(): creating socket...");
128 SSLSocket socket = this.socket = (SSLSocket) ctx.getSocketFactory().createSocket();
129 if (socket != null) {
130 VeluxBridgeConfiguration cfg = bridgeInstance.veluxBridgeConfiguration();
131 readTimeoutMSecs = cfg.timeoutMsecs;
132 connTimeoutMSecs = Math.max(connTimeoutMSecs, readTimeoutMSecs);
133 // use longer timeout when establishing the connection
134 socket.setSoTimeout(connTimeoutMSecs);
135 socket.setKeepAlive(true);
136 socket.connect(new InetSocketAddress(cfg.ipAddress, cfg.tcpPort), connTimeoutMSecs);
137 logger.trace("SSLconnection(): starting SSL handshake...");
138 socket.startHandshake();
139 // use shorter timeout for normal communications
140 socket.setSoTimeout(readTimeoutMSecs);
141 dOut = new DataOutputStream(socket.getOutputStream());
142 dIn = new DataInputStreamWithTimeout(socket.getInputStream(), bridgeInstance);
143 if (logger.isTraceEnabled()) {
145 "SSLconnection(): connected... (ip={}, port={}, sslTimeout={}, soTimeout={}, soKeepAlive={})",
146 cfg.ipAddress, cfg.tcpPort, connTimeoutMSecs, socket.getSoTimeout(),
147 socket.getKeepAlive() ? "true" : "false");
150 logger.trace("SSLconnection() finished.");
154 * **************************
155 * ***** Public Methods *****
159 * Method to query the readiness of the connection.
161 * @return <b>ready</b> as boolean for an established connection.
163 synchronized boolean isReady() {
164 return socket != null && dIn != null && dOut != null;
168 * Method to pass a message towards the bridge. This method gets called when we are initiating a new SLIP
171 * @param <b>packet</b> as Array of bytes to be transmitted towards the bridge via the established connection.
172 * @throws java.io.IOException in case of a communication I/O failure
174 synchronized void send(byte[] packet) throws IOException {
175 logger.trace("send() called, writing {} bytes.", packet.length);
176 DataOutputStream dOutX = dOut;
178 throw new IOException("DataOutputStream not initialised");
181 // copy packet data to the write buffer
182 dOutX.write(packet, 0, packet.length);
183 // force the write buffer data to be written to the socket
185 if (logger.isTraceEnabled()) {
186 StringBuilder sb = new StringBuilder();
187 for (byte b : packet) {
188 sb.append(String.format("%02X ", b));
190 logger.trace("send() finished after having send {} bytes: {}", packet.length, sb.toString());
192 } catch (IOException e) {
199 * Method to verify that there is message from the bridge.
201 * @return <b>true</b> if there are any messages ready to be queried using {@link SSLconnection#receive}.
203 synchronized boolean available() {
204 logger.trace("available() called.");
205 DataInputStreamWithTimeout dInX = dIn;
207 int availableMessages = dInX.available();
208 logger.trace("available(): found {} messages ready to be read (> 0 means true).", availableMessages);
209 return availableMessages > 0;
215 * Method to get a message from the bridge.
217 * @return <b>packet</b> as Array of bytes as received from the bridge via the established connection.
218 * @throws java.io.IOException in case of a communication I/O failure.
220 synchronized byte[] receive() throws IOException {
221 logger.trace("receive() called.");
222 DataInputStreamWithTimeout dInX = dIn;
224 throw new IOException("DataInputStreamWithTimeout not initialised");
227 byte[] packet = dInX.readSlipMessage(readTimeoutMSecs);
228 if (logger.isTraceEnabled()) {
229 StringBuilder sb = new StringBuilder();
230 for (byte b : packet) {
231 sb.append(String.format("%02X ", b));
233 logger.trace("receive() finished after having read {} bytes: {}", packet.length, sb.toString());
236 } catch (IOException e) {
243 * Destructor to tear down a connection.
245 * @throws java.io.IOException in case of a communication I/O failure.
246 * But actually eats all exceptions to ensure sure that all shutdown code is executed
249 public synchronized void close() throws IOException {
250 logger.debug("close() called.");
251 DataInputStreamWithTimeout dInX = dIn;
255 } catch (IOException e) {
256 // eat the exception so the following will always be executed
259 DataOutputStream dOutX = dOut;
263 } catch (IOException e) {
264 // eat the exception so the following will always be executed
267 SSLSocket socketX = socket;
268 if (socketX != null) {
269 logger.debug("Shutting down Velux bridge connection.");
272 } catch (IOException e) {
273 // eat the exception so the following will always be executed
279 logger.trace("close() finished.");