]> git.basschouten.com Git - openhab-addons.git/blob
d53ea05943af0465ffa6b848be1a8419602b007f
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.DataOutputStream;
16 import java.io.IOException;
17 import java.net.ConnectException;
18 import java.net.UnknownHostException;
19 import java.security.KeyManagementException;
20 import java.security.NoSuchAlgorithmException;
21 import java.security.cert.CertificateException;
22 import java.security.cert.X509Certificate;
23
24 import javax.net.ssl.SSLContext;
25 import javax.net.ssl.SSLSocket;
26 import javax.net.ssl.TrustManager;
27 import javax.net.ssl.X509TrustManager;
28
29 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.openhab.binding.velux.internal.VeluxBindingConstants;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 /**
36  * Transport layer supported by the Velux bridge.
37  * <P>
38  * SLIP-based 2nd Level I/O interface towards the <B>Velux</B> bridge.
39  * <P>
40  * It provides methods for pre- and post-communication
41  * as well as a common method for the real communication.
42  * <UL>
43  * <LI>{@link SSLconnection#SSLconnection} for establishing the connection,</LI>
44  * <LI>{@link SSLconnection#send} for sending a message to the bridge,</LI>
45  * <LI>{@link SSLconnection#available} for observation whether there are bytes available,</LI>
46  * <LI>{@link SSLconnection#receive} for receiving a message from the bridge,</LI>
47  * <LI>{@link SSLconnection#close} for tearing down the connection.</LI>
48  * <LI>{@link SSLconnection#setTimeout} for adapting communication parameters.</LI>
49  * </UL>
50  *
51  * @author Guenther Schreiner - Initial contribution.
52  */
53 @NonNullByDefault
54 class SSLconnection {
55     private final Logger logger = LoggerFactory.getLogger(SSLconnection.class);
56
57     // Public definition
58     public static final SSLconnection UNKNOWN = new SSLconnection();
59
60     /*
61      * ***************************
62      * ***** Private Objects *****
63      */
64
65     private static final int CONNECTION_BUFFER_SIZE = 4096;
66
67     private boolean ready = false;
68     private @Nullable SSLSocket socket;
69     private @Nullable DataOutputStream dOut;
70     private @Nullable DataInputStreamWithTimeout dIn;
71     private int ioTimeoutMSecs = 60000;
72
73     /**
74      * Fake trust manager to suppress any certificate errors,
75      * used within {@link #SSLconnection} for seamless operation
76      * even on self-signed certificates like provided by <B>Velux</B>.
77      */
78     private final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
79         @Override
80         public X509Certificate @Nullable [] getAcceptedIssuers() {
81             return null;
82         }
83
84         @Override
85         public void checkClientTrusted(X509Certificate @Nullable [] arg0, @Nullable String arg1)
86                 throws CertificateException {
87         }
88
89         @Override
90         public void checkServerTrusted(X509Certificate @Nullable [] arg0, @Nullable String arg1)
91                 throws CertificateException {
92         }
93     } };
94
95     /*
96      * ************************
97      * ***** Constructors *****
98      */
99
100     /**
101      * Constructor for initialization of an unfinished connectivity.
102      */
103     SSLconnection() {
104         logger.debug("SSLconnection() called.");
105         ready = false;
106         logger.trace("SSLconnection() finished.");
107     }
108
109     /**
110      * Constructor to setup and establish a connection.
111      *
112      * @param host as String describing the Service Access Point location i.e. hostname.
113      * @param port as String describing the Service Access Point location i.e. TCP port.
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(String host, int port) throws ConnectException, IOException, UnknownHostException {
119         logger.debug("SSLconnection({},{}) called.", host, port);
120         logger.info("Starting {} bridge connection.", VeluxBindingConstants.BINDING_ID);
121         SSLContext ctx = null;
122         try {
123             ctx = SSLContext.getInstance("SSL");
124             ctx.init(null, trustAllCerts, null);
125         } catch (NoSuchAlgorithmException | KeyManagementException e) {
126             throw new IOException(String.format("create of an empty trust store failed: %s.", e.getMessage()));
127         }
128         logger.trace("SSLconnection(): creating socket...");
129         // Just for avoidance of Potential null pointer access
130         SSLSocket socketX = (SSLSocket) ctx.getSocketFactory().createSocket(host, port);
131         logger.trace("SSLconnection(): starting SSL handshake...");
132         if (socketX != null) {
133             socketX.startHandshake();
134             dOut = new DataOutputStream(socketX.getOutputStream());
135             dIn = new DataInputStreamWithTimeout(socketX.getInputStream());
136             ready = true;
137             socket = socketX;
138         }
139         logger.trace("SSLconnection() finished.");
140     }
141
142     /*
143      * **************************
144      * ***** Public Methods *****
145      */
146
147     /**
148      * Method to query the readiness of the connection.
149      *
150      * @return <b>ready</b> as boolean for an established connection.
151      */
152     synchronized boolean isReady() {
153         return ready;
154     }
155
156     /**
157      * Method to pass a message towards the bridge.
158      *
159      * @param packet as Array of bytes to be transmitted towards the bridge via the established connection.
160      * @throws java.io.IOException in case of a communication I/O failure.
161      */
162     @SuppressWarnings("null")
163     synchronized void send(byte[] packet) throws IOException {
164         logger.trace("send() called, writing {} bytes.", packet.length);
165         if (!ready || (dOut == null)) {
166             throw new IOException();
167         }
168         dOut.write(packet, 0, packet.length);
169         if (logger.isTraceEnabled()) {
170             StringBuilder sb = new StringBuilder();
171             for (byte b : packet) {
172                 sb.append(String.format("%02X ", b));
173             }
174             logger.trace("send() finished after having send {} bytes: {}", packet.length, sb.toString());
175         }
176     }
177
178     /**
179      * Method to verify that there is message from the bridge.
180      *
181      * @return <b>true</b> if there are any bytes ready to be queried using {@link SSLconnection#receive}.
182      * @throws java.io.IOException in case of a communication I/O failure.
183      */
184     synchronized boolean available() throws IOException {
185         logger.trace("available() called.");
186         if (!ready || (dIn == null)) {
187             throw new IOException();
188         }
189         @SuppressWarnings("null")
190         int availableBytes = dIn.available();
191         logger.trace("available(): found {} bytes ready to be read (> 0 means true).", availableBytes);
192         return availableBytes > 0;
193     }
194
195     /**
196      * Method to get a message from the bridge.
197      *
198      * @return <b>packet</b> as Array of bytes as received from the bridge via the established connection.
199      * @throws java.io.IOException in case of a communication I/O failure.
200      */
201     synchronized byte[] receive() throws IOException {
202         logger.trace("receive() called.");
203         if (!ready || (dIn == null)) {
204             throw new IOException();
205         }
206         byte[] message = new byte[CONNECTION_BUFFER_SIZE];
207         @SuppressWarnings("null")
208         int messageLength = dIn.read(message, 0, message.length, ioTimeoutMSecs);
209         byte[] packet = new byte[messageLength];
210         System.arraycopy(message, 0, packet, 0, messageLength);
211         if (logger.isTraceEnabled()) {
212             StringBuilder sb = new StringBuilder();
213             for (byte b : packet) {
214                 sb.append(String.format("%02X ", b));
215             }
216             logger.trace("receive() finished after having read {} bytes: {}", messageLength, sb.toString());
217         }
218         return packet;
219     }
220
221     /**
222      * Destructor to tear down a connection.
223      *
224      * @throws java.io.IOException in case of a communication I/O failure.
225      */
226     synchronized void close() throws IOException {
227         logger.debug("close() called.");
228         ready = false;
229         logger.info("Shutting down Velux bridge connection.");
230         // Just for avoidance of Potential null pointer access
231         DataInputStreamWithTimeout dInX = dIn;
232         if (dInX != null) {
233             dInX.close();
234         }
235         // Just for avoidance of Potential null pointer access
236         DataOutputStream dOutX = dOut;
237         if (dOutX != null) {
238             dOutX.close();
239         }
240         // Just for avoidance of Potential null pointer access
241         SSLSocket socketX = socket;
242         if (socketX != null) {
243             socketX.close();
244         }
245         logger.trace("close() finished.");
246     }
247
248     /**
249      * Parameter modification.
250      *
251      * @param timeoutMSecs the maximum duration in milliseconds for read operations.
252      */
253     void setTimeout(int timeoutMSecs) {
254         logger.debug("setTimeout() set timeout to {} milliseconds.", timeoutMSecs);
255         ioTimeoutMSecs = timeoutMSecs;
256     }
257 }