/
CaliforniumClientEndpointsProvider.java
390 lines (334 loc) · 16.1 KB
/
CaliforniumClientEndpointsProvider.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/*******************************************************************************
* Copyright (c) 2022 Sierra Wireless and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors:
* Sierra Wireless - initial API and implementation
*******************************************************************************/
package org.eclipse.leshan.client.californium.endpoint;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.eclipse.californium.core.CoapServer;
import org.eclipse.californium.core.network.CoapEndpoint;
import org.eclipse.californium.core.network.Endpoint;
import org.eclipse.californium.core.network.Exchange;
import org.eclipse.californium.core.server.resources.Resource;
import org.eclipse.californium.elements.config.Configuration;
import org.eclipse.californium.elements.config.Configuration.ModuleDefinitionsProvider;
import org.eclipse.leshan.client.californium.endpoint.coap.CoapClientProtocolProvider;
import org.eclipse.leshan.client.endpoint.ClientEndpointToolbox;
import org.eclipse.leshan.client.endpoint.LwM2mClientEndpoint;
import org.eclipse.leshan.client.endpoint.LwM2mClientEndpointsProvider;
import org.eclipse.leshan.client.request.DownlinkRequestReceiver;
import org.eclipse.leshan.client.resource.LwM2mObjectTree;
import org.eclipse.leshan.client.servers.LwM2mServer;
import org.eclipse.leshan.client.servers.ServerInfo;
import org.eclipse.leshan.core.SecurityMode;
import org.eclipse.leshan.core.californium.identity.IdentityHandler;
import org.eclipse.leshan.core.californium.identity.IdentityHandlerProvider;
import org.eclipse.leshan.core.endpoint.Protocol;
import org.eclipse.leshan.core.peer.IpPeer;
import org.eclipse.leshan.core.peer.OscoreIdentity;
import org.eclipse.leshan.core.peer.PskIdentity;
import org.eclipse.leshan.core.peer.RpkIdentity;
import org.eclipse.leshan.core.peer.X509Identity;
import org.eclipse.leshan.core.util.NamedThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CaliforniumClientEndpointsProvider implements LwM2mClientEndpointsProvider {
// TODO TL : provide a COAP/Californium API ? like previous LeshanClient.coapAPI()
private final Logger LOG = LoggerFactory.getLogger(CaliforniumClientEndpointsProvider.class);
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1,
new NamedThreadFactory("Leshan Async Request timeout"));
protected boolean started = false;
private final Configuration serverConfig;
private final List<CaliforniumClientEndpointFactory> endpointsFactory;
private final ClientCoapMessageTranslator messagetranslator = new ClientCoapMessageTranslator();
private final ServerIdentityExtractor identityExtrator;
private final IdentityHandlerProvider identityHandlerProvider;
private LwM2mObjectTree objectTree;
private final InetAddress clientAddress;
// we support only 1 endpoint at a time by
private LwM2mServer currentServer;
private CaliforniumClientEndpoint endpoint;
private CoapServer coapServer;
public CaliforniumClientEndpointsProvider() {
this(new Builder().generateDefaultValue());
}
protected CaliforniumClientEndpointsProvider(Builder builder) {
this.serverConfig = builder.configuration;
this.endpointsFactory = builder.endpointsFactory;
this.clientAddress = builder.clientAddress;
// create identity handler provider
identityHandlerProvider = new IdentityHandlerProvider();
// create identity extractor
identityExtrator = new ServerIdentityExtractor() {
@Override
public LwM2mServer extractIdentity(Exchange exchange, IpPeer foreignPeer) {
// TODO support multi server
Endpoint currentCoapEndpoint = endpoint.getCoapEndpoint();
// get coap endpoint used for this exchanged :
Endpoint coapEndpoint = exchange.getEndpoint();
// knowing used CoAP endpoint we should be able to know the server identity because :
// - we create 1 CoAP endpoint by server.
// - the lower layer should ensure that only 1 server with expected credential is able to talk.
// (see https://github.com/eclipse/leshan/issues/992 for more details)
if (coapEndpoint != null && coapEndpoint.equals(currentCoapEndpoint)
&& currentCoapEndpoint.isStarted()) {
// For UDP (not secure) endpoint we also check socket address as anybody send data to this kind of
// endpoint.
if (endpoint.getProtocol().equals(Protocol.COAP)) {
if (currentServer.getTransportData() instanceof IpPeer) {
IpPeer currentIpServer = (IpPeer) currentServer.getTransportData();
if (!(currentIpServer.getSocketAddress().equals(foreignPeer.getSocketAddress()))) {
return null;
}
} else {
throw new IllegalStateException(
String.format("%s is not a LwM2mPeer supported by this class",
currentServer.getTransportData().getClass().getSimpleName()));
}
}
// For OSCORE, be sure OSCORE is used.
if (currentServer.getTransportData().getIdentity() instanceof OscoreIdentity) {
if (!(foreignPeer.getIdentity() instanceof OscoreIdentity) //
// we also check OscoreIdentity but this is probably not useful
// because we are using static OSCOREstore which holds only 1 OscoreParameter,
// so if the request was successfully decrypted and OSCORE is used, this MUST be the
// right
// server.
|| !foreignPeer.getIdentity().equals(currentServer.getTransportData().getIdentity())) {
return null;
}
}
return currentServer;
}
return null;
}
};
}
@Override
public void init(LwM2mObjectTree objectTree, DownlinkRequestReceiver requestReceiver,
ClientEndpointToolbox toolbox) {
this.objectTree = objectTree;
// create coap server
coapServer = new CoapServer(serverConfig) {
@Override
protected Resource createRoot() {
return messagetranslator.createRootResource(coapServer, identityHandlerProvider, identityExtrator,
requestReceiver, toolbox, objectTree);
}
};
// create resources
List<Resource> resources = messagetranslator.createResources(coapServer, identityHandlerProvider,
identityExtrator, requestReceiver, toolbox, objectTree);
coapServer.add(resources.toArray(new Resource[resources.size()]));
}
@Override
public LwM2mServer createEndpoint(ServerInfo serverInfo, boolean clientInitiatedOnly, List<Certificate> trustStore,
ClientEndpointToolbox toolbox) {
// create endpoints
for (CaliforniumClientEndpointFactory endpointFactory : endpointsFactory) {
if (endpointFactory.getProtocol().getUriScheme().equals(serverInfo.getFullUri().getScheme())) {
// create Californium endpoint
CoapEndpoint coapEndpoint = endpointFactory.createCoapEndpoint(clientAddress, serverConfig, serverInfo,
clientInitiatedOnly, trustStore, toolbox);
if (coapEndpoint != null) {
// create identity handler and add it to provider
final IdentityHandler identityHandler = endpointFactory.createIdentityHandler();
identityHandlerProvider.addIdentityHandler(coapEndpoint, identityHandler);
// create LWM2M endpoint
endpoint = new CaliforniumClientEndpoint(endpointFactory.getProtocol(),
endpointFactory.getEndpointDescription(), coapEndpoint, messagetranslator, toolbox,
identityHandler, endpointFactory.createConnectionController(), objectTree.getModel(),
endpointFactory.createExceptionTranslator(), executor);
// add Californium endpoint to coap server
coapServer.addEndpoint(coapEndpoint);
currentServer = extractIdentity(serverInfo);
if (started) {
coapServer.start();
try {
coapEndpoint.start();
} catch (IOException e) {
throw new RuntimeException("Unable to start endpoint", e);
}
}
return currentServer;
}
}
}
return null;
}
private LwM2mServer extractIdentity(ServerInfo serverInfo) {
IpPeer transportData;
if (serverInfo.isSecure()) {
// Support PSK
if (serverInfo.secureMode == SecurityMode.PSK) {
transportData = new IpPeer(serverInfo.getAddress(), new PskIdentity(serverInfo.pskId));
} else if (serverInfo.secureMode == SecurityMode.RPK) {
transportData = new IpPeer(serverInfo.getAddress(), new RpkIdentity(serverInfo.serverPublicKey));
} else if (serverInfo.secureMode == SecurityMode.X509) {
// TODO We set CN with '*' as we are not able to know the CN for some certificate usage and so this is
// not used anymore to identify a server with x509.
// See : https://github.com/eclipse/leshan/issues/992
transportData = new IpPeer(serverInfo.getAddress(), new X509Identity("*"));
} else {
throw new RuntimeException("Unable to create connector : unsupported security mode");
}
} else if (serverInfo.useOscore) {
// Build server identity for OSCORE
transportData = new IpPeer(serverInfo.getAddress(),
new OscoreIdentity(serverInfo.oscoreSetting.getRecipientId()));
} else {
transportData = new IpPeer((serverInfo.getAddress()));
}
if (serverInfo.bootstrap) {
return new LwM2mServer(transportData, serverInfo.serverUri);
} else {
return new LwM2mServer(transportData, serverInfo.serverId, serverInfo.serverUri);
}
}
@Override
public Collection<LwM2mServer> createEndpoints(Collection<? extends ServerInfo> serverInfo,
boolean clientInitiatedOnly, List<Certificate> trustStore, ClientEndpointToolbox toolbox) {
// TODO TL : need to be implemented or removed ?
return null;
}
@Override
public void destroyEndpoints() {
identityHandlerProvider.clear();
for (Endpoint endpoint : coapServer.getEndpoints()) {
coapServer.getEndpoints().remove(endpoint);
endpoint.destroy();
}
}
public CoapServer getCoapServer() {
return coapServer;
}
@Override
public LwM2mClientEndpoint getEndpoint(LwM2mServer server) {
if (currentServer != null && currentServer.equals(server)) {
return endpoint;
}
return null;
}
@Override
public List<LwM2mClientEndpoint> getEndpoints() {
return Arrays.asList(endpoint);
}
@Override
public synchronized void start() {
if (started)
return;
started = true;
// we don't have any endpoint so nothing to start
if (coapServer.getEndpoints().isEmpty())
return;
coapServer.start();
}
@Override
public synchronized void stop() {
if (!started)
return;
started = false;
// If we have no endpoint this means that we never start coap server
if (coapServer.getEndpoints().isEmpty())
return;
coapServer.stop();
}
@Override
public synchronized void destroy() {
if (started)
started = false;
executor.shutdownNow();
try {
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOG.warn("Destroying RequestSender was interrupted.", e);
}
coapServer.destroy();
}
public static class Builder {
private final List<ClientProtocolProvider> protocolProviders;
private Configuration configuration;
private final List<CaliforniumClientEndpointFactory> endpointsFactory;
private InetAddress clientAddress;
public Builder(ClientProtocolProvider... protocolProviders) {
// TODO TL : handle duplicate ?
this.protocolProviders = new ArrayList<ClientProtocolProvider>();
if (protocolProviders.length == 0) {
this.protocolProviders.add(new CoapClientProtocolProvider());
} else {
this.protocolProviders.addAll(Arrays.asList(protocolProviders));
}
this.endpointsFactory = new ArrayList<>();
}
/**
* create Default CoAP Server Configuration.
*/
public Configuration createDefaultConfiguration() {
// Get all Californium modules
Set<ModuleDefinitionsProvider> moduleProviders = new HashSet<>();
for (ClientProtocolProvider protocolProvider : protocolProviders) {
moduleProviders.addAll(protocolProvider.getModuleDefinitionsProviders());
}
// create Californium Configuration
Configuration configuration = new Configuration(
moduleProviders.toArray(new ModuleDefinitionsProvider[moduleProviders.size()]));
// apply default value
for (ClientProtocolProvider protocolProvider : protocolProviders) {
protocolProvider.applyDefaultValue(configuration);
}
return configuration;
}
/**
* @param configuration the @{link Configuration} used by the {@link CoapServer}.
*/
public Builder setConfiguration(Configuration configuration) {
this.configuration = configuration;
return this;
}
public Builder setClientAddress(InetAddress addr) {
clientAddress = addr;
return this;
}
protected Builder generateDefaultValue() {
if (configuration == null) {
configuration = createDefaultConfiguration();
}
if (clientAddress == null) {
clientAddress = new InetSocketAddress(0).getAddress();
}
if (endpointsFactory.isEmpty()) {
for (ClientProtocolProvider protocolProvider : protocolProviders) {
// TODO TL : handle duplicates
endpointsFactory.add(protocolProvider.createDefaultEndpointFactory());
}
}
return this;
}
public CaliforniumClientEndpointsProvider build() {
generateDefaultValue();
return new CaliforniumClientEndpointsProvider(this);
}
}
}