]> git.basschouten.com Git - openhab-addons.git/blob
6625f91894d324efdef51e8d9f661fdc059a520b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.velux.internal.bridge.slip.io;
14
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;
25
26 import javax.net.ssl.SSLContext;
27 import javax.net.ssl.SSLSocket;
28 import javax.net.ssl.TrustManager;
29 import javax.net.ssl.X509TrustManager;
30
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;
38
39 /**
40  * Transport layer supported by the Velux bridge.
41  * <P>
42  * SLIP-based 2nd Level I/O interface towards the <B>Velux</B> bridge.
43  * <P>
44  * It provides methods for pre- and post-communication
45  * as well as a common method for the real communication.
46  * <UL>
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>
53  * </UL>
54  *
55  * @author Guenther Schreiner - Initial contribution.
56  */
57 @NonNullByDefault
58 class SSLconnection implements Closeable {
59     private final Logger logger = LoggerFactory.getLogger(SSLconnection.class);
60
61     // Public definition
62     public static final SSLconnection UNKNOWN = new SSLconnection();
63
64     /*
65      * ***************************
66      * ***** Private Objects *****
67      */
68
69     private @Nullable SSLSocket socket;
70     private @Nullable DataOutputStream dOut;
71     private @Nullable DataInputStreamWithTimeout dIn;
72
73     private int readTimeoutMSecs = 2000;
74     private int connTimeoutMSecs = 6000;
75
76     /**
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>.
80      */
81     private final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
82         @Override
83         public X509Certificate @Nullable [] getAcceptedIssuers() {
84             return null;
85         }
86
87         @Override
88         public void checkClientTrusted(X509Certificate @Nullable [] arg0, @Nullable String arg1)
89                 throws CertificateException {
90         }
91
92         @Override
93         public void checkServerTrusted(X509Certificate @Nullable [] arg0, @Nullable String arg1)
94                 throws CertificateException {
95         }
96     } };
97
98     /*
99      * ************************
100      * ***** Constructors *****
101      */
102
103     /**
104      * Constructor for initialization of an unfinished connectivity.
105      */
106     SSLconnection() {
107         logger.debug("SSLconnection() called.");
108     }
109
110     /**
111      * Constructor to setup and establish a connection.
112      *
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.
117      */
118     SSLconnection(VeluxBridgeHandler bridgeInstance) throws ConnectException, IOException, UnknownHostException {
119         logger.debug("Starting {} bridge connection.", VeluxBindingConstants.BINDING_ID);
120         SSLContext ctx = null;
121         try {
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()));
126         }
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()) {
144                 logger.trace(
145                         "SSLconnection(): connected... (ip={}, port={}, sslTimeout={}, soTimeout={}, soKeepAlive={})",
146                         cfg.ipAddress, cfg.tcpPort, connTimeoutMSecs, socket.getSoTimeout(),
147                         socket.getKeepAlive() ? "true" : "false");
148             }
149         }
150         logger.trace("SSLconnection() finished.");
151     }
152
153     /*
154      * **************************
155      * ***** Public Methods *****
156      */
157
158     /**
159      * Method to query the readiness of the connection.
160      *
161      * @return <b>ready</b> as boolean for an established connection.
162      */
163     synchronized boolean isReady() {
164         return socket != null && dIn != null && dOut != null;
165     }
166
167     /**
168      * Method to pass a message towards the bridge. This method gets called when we are initiating a new SLIP
169      * transaction.
170      *
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
173      */
174     synchronized void send(byte[] packet) throws IOException {
175         logger.trace("send() called, writing {} bytes.", packet.length);
176         DataOutputStream dOutX = dOut;
177         if (dOutX == null) {
178             throw new IOException("DataOutputStream not initialised");
179         }
180         try {
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
184             dOutX.flush();
185             if (logger.isTraceEnabled()) {
186                 StringBuilder sb = new StringBuilder();
187                 for (byte b : packet) {
188                     sb.append(String.format("%02X ", b));
189                 }
190                 logger.trace("send() finished after having send {} bytes: {}", packet.length, sb.toString());
191             }
192         } catch (IOException e) {
193             close();
194             throw e;
195         }
196     }
197
198     /**
199      * Method to verify that there is message from the bridge.
200      *
201      * @return <b>true</b> if there are any messages ready to be queried using {@link SSLconnection#receive}.
202      */
203     synchronized boolean available() {
204         logger.trace("available() called.");
205         DataInputStreamWithTimeout dInX = dIn;
206         if (dInX != null) {
207             int availableMessages = dInX.available();
208             logger.trace("available(): found {} messages ready to be read (> 0 means true).", availableMessages);
209             return availableMessages > 0;
210         }
211         return false;
212     }
213
214     /**
215      * Method to get a message from the bridge.
216      *
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.
219      */
220     synchronized byte[] receive() throws IOException {
221         logger.trace("receive() called.");
222         DataInputStreamWithTimeout dInX = dIn;
223         if (dInX == null) {
224             throw new IOException("DataInputStreamWithTimeout not initialised");
225         }
226         try {
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));
232                 }
233                 logger.trace("receive() finished after having read {} bytes: {}", packet.length, sb.toString());
234             }
235             return packet;
236         } catch (IOException e) {
237             close();
238             throw e;
239         }
240     }
241
242     /**
243      * Destructor to tear down a connection.
244      *
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
247      */
248     @Override
249     public synchronized void close() throws IOException {
250         logger.debug("close() called.");
251         DataInputStreamWithTimeout dInX = dIn;
252         if (dInX != null) {
253             try {
254                 dInX.close();
255             } catch (IOException e) {
256                 // eat the exception so the following will always be executed
257             }
258         }
259         DataOutputStream dOutX = dOut;
260         if (dOutX != null) {
261             try {
262                 dOutX.close();
263             } catch (IOException e) {
264                 // eat the exception so the following will always be executed
265             }
266         }
267         SSLSocket socketX = socket;
268         if (socketX != null) {
269             logger.debug("Shutting down Velux bridge connection.");
270             try {
271                 socketX.close();
272             } catch (IOException e) {
273                 // eat the exception so the following will always be executed
274             }
275         }
276         dIn = null;
277         dOut = null;
278         socket = null;
279         logger.trace("close() finished.");
280     }
281 }