-
Notifications
You must be signed in to change notification settings - Fork 215
/
AbstractHiveMqttClientFactory.java
181 lines (157 loc) · 8.4 KB
/
AbstractHiveMqttClientFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/*
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.connectivity.service.messaging.mqtt.hivemq;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import javax.net.ssl.KeyManagerFactory;
import org.eclipse.ditto.connectivity.model.Connection;
import org.eclipse.ditto.connectivity.service.messaging.internal.ssl.DittoTrustManagerFactory;
import org.eclipse.ditto.connectivity.service.messaging.internal.ssl.KeyManagerFactoryFactory;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.logs.ConnectionLogger;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.MqttSpecificConfig;
import org.eclipse.ditto.connectivity.service.messaging.tunnel.SshTunnelState;
import com.hivemq.client.mqtt.MqttClientBuilderBase;
import com.hivemq.client.mqtt.MqttClientSslConfig;
import com.hivemq.client.mqtt.MqttClientSslConfigBuilder;
import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.lifecycle.MqttClientConnectedListener;
import com.hivemq.client.mqtt.lifecycle.MqttClientDisconnectedListener;
import com.hivemq.client.mqtt.mqtt3.Mqtt3ClientBuilder;
import com.hivemq.client.mqtt.mqtt3.message.auth.Mqtt3SimpleAuthBuilder;
import com.hivemq.client.mqtt.mqtt3.message.publish.Mqtt3WillPublishBuilder;
import com.hivemq.client.mqtt.mqtt5.Mqtt5ClientBuilder;
import com.hivemq.client.mqtt.mqtt5.message.auth.Mqtt5SimpleAuthBuilder;
import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5WillPublishBuilder;
/**
* Common code between MQTT3 and MQTT5 client factories.
*/
abstract class AbstractHiveMqttClientFactory {
private static final List<String> MQTT_SECURE_SCHEMES = Arrays.asList("ssl", "wss");
private final Supplier<SshTunnelState> tunnelStateSupplier;
protected AbstractHiveMqttClientFactory(final Supplier<SshTunnelState> tunnelStateSupplier) {
this.tunnelStateSupplier = tunnelStateSupplier;
}
// duplicate code unavoidable because there is no common interface
// between Mqtt3SimpleAuthBuilder.Nested and Mqtt5SimpleAuthBuilder.Nested
@SuppressWarnings("Duplicates")
void configureSimpleAuth(final Mqtt3SimpleAuthBuilder.Nested<?> simpleAuth, final Connection connection, final boolean doubleDecodingEnabled) {
final Optional<String> username =
connection.getUsername().map(u -> doubleDecodingEnabled ? tryDecodeUriComponent(u) : u);
final Optional<String> password =
connection.getPassword().map(p -> doubleDecodingEnabled ? tryDecodeUriComponent(p) : p);
if (username.isPresent() && password.isPresent()) {
simpleAuth.username(username.get())
.password(password.get().getBytes(StandardCharsets.UTF_8))
.applySimpleAuth();
}
}
private static String tryDecodeUriComponent(final String string) {
try {
final String withoutPlus = string.replace("+", "%2B");
return URLDecoder.decode(withoutPlus, StandardCharsets.UTF_8);
} catch (final IllegalArgumentException e) {
return string;
}
}
// duplicate code unavoidable because there is no common interface
// between Mqtt3SimpleAuthBuilder.Nested and Mqtt5SimpleAuthBuilder.Nested
@SuppressWarnings("Duplicates")
void configureSimpleAuth(final Mqtt5SimpleAuthBuilder.Nested<?> simpleAuth, final Connection connection, final boolean doubleDecodingEnabled) {
final Optional<String> username =
connection.getUsername().map(u -> doubleDecodingEnabled ? tryDecodeUriComponent(u) : u);
final Optional<String> password =
connection.getPassword().map(p -> doubleDecodingEnabled ? tryDecodeUriComponent(p) : p);
if (username.isPresent() && password.isPresent()) {
simpleAuth.username(username.get())
.password(password.get().getBytes(StandardCharsets.UTF_8))
.applySimpleAuth();
}
}
@SuppressWarnings("Duplicates")
void configureWillPublish(final Mqtt3ClientBuilder clientBuilder, final MqttSpecificConfig mqttSpecificConfig) {
// since topic is required, the other last will parameters will only be applied if the topic is set
mqttSpecificConfig.getMqttWillTopic()
.map(topic -> clientBuilder.willPublish().topic(topic))
.map(step -> step.retain(mqttSpecificConfig.getMqttWillRetain()))
.map(step -> Optional.ofNullable(MqttQos.fromCode(mqttSpecificConfig.getMqttWillQos()))
.map(step::qos)
.orElse(step))
.map(step -> mqttSpecificConfig.getMqttWillMessage()
.map(msg -> step.payload(msg.getBytes(StandardCharsets.UTF_8)))
.orElse(step))
.ifPresent(Mqtt3WillPublishBuilder.Nested.Complete::applyWillPublish);
}
@SuppressWarnings("Duplicates")
void configureWillPublish(final Mqtt5ClientBuilder clientBuilder, final MqttSpecificConfig mqttSpecificConfig) {
// since topic is required, the other last will parameters will only be applied if the topic is set
mqttSpecificConfig.getMqttWillTopic()
.map(topic -> clientBuilder.willPublish().topic(topic))
.map(step -> step.retain(mqttSpecificConfig.getMqttWillRetain()))
.map(step -> Optional.ofNullable(MqttQos.fromCode(mqttSpecificConfig.getMqttWillQos()))
.map(step::qos)
.orElse(step))
.map(step -> mqttSpecificConfig.getMqttWillMessage()
.map(msg -> step.payload(msg.getBytes(StandardCharsets.UTF_8)))
.orElse(step))
.ifPresent(Mqtt5WillPublishBuilder.Nested.Complete::applyWillPublish);
}
<T extends MqttClientBuilderBase<T>> T configureClientBuilder(
final T newBuilder,
final Connection connection,
final String identifier,
@Nullable final MqttClientConnectedListener connectedListener,
@Nullable final MqttClientDisconnectedListener disconnectedListener,
final ConnectionLogger connectionLogger,
final int eventLoopThreads) {
final var uri = tunnelStateSupplier.get().getURI(connection);
T builder = newBuilder;
if (eventLoopThreads > 0) {
builder = builder.executorConfig()
.nettyThreads(eventLoopThreads)
.applyExecutorConfig();
}
builder = builder
.transportConfig()
.applyTransportConfig()
.serverHost(uri.getHost())
.serverPort(uri.getPort());
if (isSecuredConnection(connection.getProtocol())) {
// create DittoTrustManagerFactory to apply hostname verification
// or to disable certificate check when the connection requires it
MqttClientSslConfigBuilder sslConfigBuilder = MqttClientSslConfig.builder()
.trustManagerFactory(DittoTrustManagerFactory.from(connection, connectionLogger));
final Optional<KeyManagerFactory> keyManagerFactory = connection.getCredentials()
.map(credentials -> credentials.accept(KeyManagerFactoryFactory.getInstance()));
if (keyManagerFactory.isPresent()) {
sslConfigBuilder = sslConfigBuilder.keyManagerFactory(keyManagerFactory.get());
}
builder = builder.sslConfig(sslConfigBuilder.build());
}
if (null != connectedListener) {
builder = builder.addConnectedListener(connectedListener);
}
if (null != disconnectedListener) {
builder = builder.addDisconnectedListener(disconnectedListener);
}
builder = builder.identifier(identifier);
return builder;
}
private static boolean isSecuredConnection(final String protocol) {
return MQTT_SECURE_SCHEMES.contains(protocol.toLowerCase());
}
}