-
Notifications
You must be signed in to change notification settings - Fork 364
/
HttpService.java
832 lines (778 loc) · 25.4 KB
/
HttpService.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
/********************************************************************************
* Copyright (c) 2024 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 v. 2.0 which is available at
* https://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
********************************************************************************/
package org.eclipse.californium.cloud.http;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.eclipse.californium.cloud.resources.Devices;
import org.eclipse.californium.cloud.util.CredentialsStore;
import org.eclipse.californium.cloud.util.CredentialsStore.Observer;
import org.eclipse.californium.core.WebLink;
import org.eclipse.californium.core.coap.CoAP.ResponseCode;
import org.eclipse.californium.core.coap.CoAP.Type;
import org.eclipse.californium.core.coap.LinkFormat;
import org.eclipse.californium.core.coap.MediaTypeRegistry;
import org.eclipse.californium.core.coap.OptionSet;
import org.eclipse.californium.core.coap.Request;
import org.eclipse.californium.core.coap.Response;
import org.eclipse.californium.core.network.Exchange;
import org.eclipse.californium.core.network.Exchange.Origin;
import org.eclipse.californium.core.server.MessageDeliverer;
import org.eclipse.californium.elements.util.Bytes;
import org.eclipse.californium.elements.util.SslContextUtil;
import org.eclipse.californium.elements.util.SslContextUtil.Credentials;
import org.eclipse.californium.elements.util.StandardCharsets;
import org.eclipse.californium.elements.util.StringUtil;
import org.eclipse.californium.elements.util.SystemResourceMonitors.SystemResourceMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsParameters;
import com.sun.net.httpserver.HttpsServer;
/**
* Https service.
*
* Provides either forwarding to external site, a single page application in
* javascript, or a simple http access to data sent via coap.
*
* The simple http access is implemented with a simplified http2coap proxy. It
* supports only very limited conversion from http to coap. Allows only GET
* access to resource "diagnose" and "devices" with sub-resources.
*
* For forwarding and data access no authentication is supported!
*
* @since 3.12
*/
@SuppressWarnings("restriction")
public class HttpService {
/**
* Logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(HttpService.class);
/**
* Logger for fail2ban support.
*/
private final static Logger LOGGER_BAN = LoggerFactory.getLogger("org.eclipse.californium.ban");
/**
* TLS any protocol version.
*/
private static final String TLS = "TLS";
/**
* TLS 1.2 protocol version.
*/
private static final String TLS_1_2 = "TLSv1.2";
/**
* TLS 1.3 protocol version.
*/
private static final String TLS_1_3 = "TLSv1.3";
private static final String[] TLS_PROTOCOLS = { TLS_1_3, TLS_1_2 };
private static final String[] TLS_PROTOCOLS_1_2_ONLY = { TLS_1_2 };
/**
* Name of private key file.
*/
private static final String HTTPS_PRIVATE_KEY = "privkey.pem";
/**
* Name of full chain file.
*/
private static final String HTTPS_FULL_CHAIN = "fullchain.pem";
/**
* Service instance.
*/
private static volatile HttpService httpService;
/**
* Local secure address.
*/
private final InetSocketAddress localSecureAddress;
/**
* Supported TLS protocols.
*/
private final String[] protocols;
/**
* Algorithm for SSLContext.
*/
private final String sslContextAlgorithm;
/**
* Ssl credentials for https.
*/
private final CredentialsStore credentialsStore;
/**
* SSL context for https.
*/
private SSLContext context;
/**
* Current node certificate.
*/
private X509Certificate node;
/**
* Executor for http server.
*/
private volatile ExecutorService executor;
/**
* Https server.
*/
private HttpsServer secureServer;
private volatile boolean started;
/**
* Handler map.
*/
private final Map<String, HttpHandler> handlers = new ConcurrentHashMap<>();
/**
* Create service.
*
* @param localSecureAddress local address for secure endpoint (https).
* @param credentialsStore credentials
* @param sslContextAlgorithm algorithm for SSL context.
* @param protocols list of TLS protocols
*/
public HttpService(InetSocketAddress localSecureAddress, CredentialsStore credentialsStore,
String sslContextAlgorithm, String[] protocols) {
this.localSecureAddress = localSecureAddress;
this.sslContextAlgorithm = sslContextAlgorithm;
this.protocols = protocols == null ? null : protocols.clone();
this.credentialsStore = credentialsStore;
applyCredentials(credentialsStore.getCredentials());
this.credentialsStore.setObserver(new Observer() {
@Override
public void update(Credentials newCredentials) {
if (newCredentials != null) {
applyCredentials(newCredentials);
}
}
});
}
public Executor getExecutor() {
return new Executor() {
@Override
public void execute(Runnable command) {
Executor serverExecutor = HttpService.this.executor;
if (serverExecutor == null) {
throw new RejectedExecutionException("Target executor missing!");
}
serverExecutor.execute(command);
}
};
}
/**
* Set HTTPS configuration from {@link SSLContext}.
*
* @param sslContext context for HTTPS configuration
*/
public void setHttpsConfigurator(SSLContext sslContext) {
if (secureServer != null && sslContext != null) {
secureServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
@Override
public void configure(HttpsParameters parameters) {
parameters.setWantClientAuth(false);
if (protocols != null) {
try {
boolean useTlsProtocols = false;
String[] clientProtocols = parameters.getProtocols();
if (clientProtocols == null || clientProtocols.length == 0) {
LOGGER.trace("TLS: protocol info not available!");
useTlsProtocols = true;
} else {
for (String protocol : clientProtocols) {
LOGGER.trace("TLS: {}", protocol);
if (protocol.equals(TLS_1_2)) {
useTlsProtocols = true;
}
}
}
if (useTlsProtocols) {
parameters.setProtocols(protocols);
for (String protocol : protocols) {
LOGGER.trace("TLS: set {}", protocol);
}
}
} catch (Throwable t) {
LOGGER.error("TLS:", t);
}
}
}
});
} else {
if (secureServer == null) {
LOGGER.warn("missing https server!");
}
if (sslContext == null) {
LOGGER.warn("missing TLS context!");
}
}
}
public void createContext(String name, HttpHandler handler) {
String url = name;
if (!url.startsWith("/")) {
url = "/" + url;
}
handlers.put(url, handler);
if (secureServer != null) {
secureServer.createContext(url, handler);
}
}
public void createFileHandler(String resource, String contentType, boolean reload) {
if (!resource.startsWith("http")) {
// download resource from local server
createContext(resource, new FileHandler(resource, contentType, reload));
}
}
/**
* Start https service.
*/
public void start() {
executor = Executors.newCachedThreadPool();
if (localSecureAddress != null && context != null) {
try {
secureServer = HttpsServer.create(localSecureAddress, 10);
setHttpsConfigurator(context);
secureServer.createContext("/favicon.ico", new FileHandler(null, "image/x-icon", false));
for (Map.Entry<String, HttpHandler> context : handlers.entrySet()) {
secureServer.createContext(context.getKey(), context.getValue());
}
// Thread control is given to executor service.
secureServer.setExecutor(executor);
secureServer.start();
started = true;
LOGGER.info("starting {} succeeded!", localSecureAddress);
} catch (IOException ex) {
LOGGER.warn("starting {} failed!", localSecureAddress, ex);
}
} else {
if (localSecureAddress == null) {
LOGGER.warn("missing local address!");
}
if (context == null) {
LOGGER.warn("missing TLS context!");
}
}
}
/**
* Stop https service.
*/
public void stop() {
started = false;
if (secureServer != null) {
// stop with 2s delay
secureServer.stop(2);
secureServer = null;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
if (executor != null) {
executor.shutdown();
executor = null;
}
}
private void applyCredentials(Credentials newCredentials) {
X509Certificate[] certificateChain = newCredentials.getCertificateChain();
if (certificateChain != null && certificateChain.length > 0) {
if (node == null || !node.equals(certificateChain[0])) {
PrivateKey privateKey = newCredentials.getPrivateKey();
if (privateKey != null) {
try {
KeyManager[] keyManager = SslContextUtil.createKeyManager("server", privateKey,
certificateChain);
TrustManager[] trustManager = SslContextUtil.createTrustAllManager();
SSLContext sslContext = SSLContext.getInstance(sslContextAlgorithm);
sslContext.init(keyManager, trustManager, null);
context = sslContext;
node = certificateChain[0];
if (started) {
LOGGER.info("restart - certificates reloaded.");
stop();
start();
}
} catch (GeneralSecurityException ex) {
LOGGER.warn("creating SSLcontext failed", ex);
}
} else {
LOGGER.debug("private key missing.");
}
} else {
LOGGER.debug("certificates not changed.");
}
} else {
LOGGER.warn("missing certificates.");
}
}
/**
* Create resource monitor for automatic credentials reloading.
*
* @return created resource monitor
*/
public SystemResourceMonitor getFileMonitor() {
return credentialsStore.getMonitor();
}
public static void logHeaders(String title, Headers headers) {
for (String key : headers.keySet()) {
LOGGER.debug("{}: {} {}", title, key, headers.getFirst(key));
}
}
/**
* Respond http-request.
*
* @param httpExchange http-exchange with request
* @param httpCode http-response code
* @param contentType response content type. May be {@code null}.
* @param payload response payload. May be {@code null}.
* @throws IOException if an i/o-error occurred
*/
public static void respond(HttpExchange httpExchange, int httpCode, String contentType, byte[] payload)
throws IOException {
try {
long length = payload != null && payload.length > 0 ? payload.length : -1;
if (contentType != null) {
httpExchange.getResponseHeaders().set("Content-Type", contentType);
}
if (httpExchange.getRequestMethod().equals("HEAD")) {
httpExchange.getResponseHeaders().set("content-length", Long.toString(length));
httpExchange.getResponseHeaders().set("connection", "close");
length = -1;
}
httpExchange.sendResponseHeaders(httpCode, length);
logHeaders("response", httpExchange.getResponseHeaders());
if (length > 0) {
try (OutputStream out = httpExchange.getResponseBody()) {
out.write(payload);
}
LOGGER.info("respond {} {} {} bytes", httpExchange.getRequestMethod(), httpCode, length);
} else {
LOGGER.info("respond {} {}", httpExchange.getRequestMethod(), httpCode);
}
} catch (IOException e) {
LOGGER.warn("writing response to {} failed!", httpExchange.getRemoteAddress(), e);
} catch (Throwable e) {
LOGGER.warn("respond to {} failed!", httpExchange.getRemoteAddress(), e);
}
}
public static void ban(HttpExchange httpExchange, String topic) {
if (LOGGER_BAN.isInfoEnabled()) {
String address = httpExchange.getRemoteAddress().getAddress().getHostAddress();
String protocol = httpExchange.getProtocol();
String method = httpExchange.getRequestMethod();
String uri = httpExchange.getRequestURI().toString();
LOGGER_BAN.info("https: {} {} {} {} Ban: {}", method, uri, protocol, topic, address);
}
}
/**
* HTTP handler to forward request.
*/
public static class ForwardHandler implements HttpHandler {
/**
* External meta-element, intended for automatic forwarding.
*/
private final String forwardLink;
/**
* External section, intended for manual forwarding.
*/
private final String forwardTitle;
public ForwardHandler(String link, String title) {
this.forwardLink = link;
this.forwardTitle = title;
}
public void handle(final HttpExchange httpExchange) throws IOException {
final URI uri = httpExchange.getRequestURI();
LOGGER.info("/request: {} {}", httpExchange.getRequestMethod(), uri);
String method = httpExchange.getRequestMethod();
String contentType = "text/html; charset=utf-8";
byte[] payload = null;
int httpCode = 405;
if (method.equals("GET")) {
String page = HtmlGenerator.createForwardPage(forwardLink, forwardTitle);
httpCode = 200;
payload = page.toString().getBytes(StandardCharsets.UTF_8);
} else if (method.equals("HEAD")) {
} else {
payload = "<h1>405 - Method not allowed!</h1>".getBytes(StandardCharsets.UTF_8);
}
respond(httpExchange, httpCode, contentType, payload);
}
}
/**
* HTTP handler for files, e.g. favicon.ico or java-script.
*/
public static class FileHandler implements HttpHandler {
private final String file;
private final String path;
private final String contentType;
private final boolean classpath;
private final boolean reload;
private byte[] data;
public FileHandler(String file, String contentType, boolean reload) {
this.contentType = contentType;
String path = null;
boolean classpath = false;
if (file != null) {
classpath = file.startsWith(SslContextUtil.CLASSPATH_SCHEME);
if (classpath) {
file = file.substring(SslContextUtil.CLASSPATH_SCHEME.length());
} else {
path = "src/main/resources/";
File f = new File(path + file);
if (!f.isFile() || !f.canRead()) {
path = "";
f = new File(file);
if (!f.isFile() || !f.canRead()) {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
if (in != null) {
classpath = true;
try {
in.close();
} catch (IOException e) {
}
}
}
}
}
}
this.classpath = classpath;
this.file = file;
this.path = path;
if (this.classpath) {
this.reload = false;
} else {
this.reload = reload;
}
load();
}
public void load() {
byte[] data = Bytes.EMPTY;
if (file != null && !file.isEmpty()) {
InputStream inStream;
try {
if (classpath) {
inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
} else {
inStream = new FileInputStream(path + file);
}
if (inStream != null) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream(8192);
byte[] temp = new byte[4096];
int length;
while ((length = inStream.read(temp)) > 0) {
out.write(temp, 0, length);
}
data = out.toByteArray();
} catch (IOException ex) {
LOGGER.info("Failure loading file {}", file, ex);
} finally {
try {
inStream.close();
} catch (IOException e) {
}
}
}
} catch (FileNotFoundException e1) {
LOGGER.info("Failure loading file {}", file, e1);
}
}
this.data = data;
LOGGER.info("{} file {} bytes", contentType, data.length);
}
public void handle(final HttpExchange httpExchange) throws IOException {
final URI uri = httpExchange.getRequestURI();
LOGGER.info("file-request: {} {}", httpExchange.getRequestMethod(), uri);
String method = httpExchange.getRequestMethod();
String contentType = "text/html; charset=utf-8";
byte[] payload = null;
int httpCode = 405;
if (method.equals("GET")) {
if (reload) {
load();
}
httpCode = 200;
payload = data;
contentType = this.contentType;
if (reload) {
httpExchange.getResponseHeaders().add("Cache-Control", "no-cache");
}
} else if (method.equals("HEAD")) {
} else {
payload = "<h1>405 - Method not allowed!</h1>".getBytes(StandardCharsets.UTF_8);
}
respond(httpExchange, httpCode, contentType, payload);
}
}
/**
* HTTP handler for coap-resource.
*/
public static class CoapProxyHandler implements HttpHandler {
private final MessageDeliverer messageDeliverer;
private final Executor executor;
private final String[] prefix;
public CoapProxyHandler(MessageDeliverer messageDeliverer, Executor executor, String... prefix) {
this.messageDeliverer = messageDeliverer;
this.executor = executor;
this.prefix = prefix;
}
public void fillUri(OptionSet options, String uri) {
String[] prefix = this.prefix;
String[] path = uri.split("/");
int index = 0;
for (index = 0; index < path.length - 1; ++index) {
String element = path[index + 1];
if (prefix != null && index < prefix.length) {
String pre = prefix[index];
if (pre.equals(element)) {
continue;
}
prefix = null;
}
options.addUriPath(element);
}
}
public boolean checkResourcePath(String path) {
return true;
}
/**
* Simply transformation of http-get-request into coap-get-request.
*/
@Override
public void handle(final HttpExchange httpExchange) throws IOException {
final URI uri = httpExchange.getRequestURI();
final String method = httpExchange.getRequestMethod();
final Headers headers = httpExchange.getRequestHeaders();
Request request = null;
LOGGER.info("http-request: {} {}", method, uri);
logHeaders("request", headers);
if (method.equals("GET") || method.equals("HEAD")) {
request = Request.newGet();
} else {
// use ping to fail ...
request = Request.newPing();
}
fillUri(request.getOptions(), uri.getPath());
String coapPath = "/" + request.getOptions().getUriPathString();
if (checkResourcePath(coapPath)) {
Exchange coapExchange = new Exchange(request, httpExchange.getRemoteAddress(), Origin.REMOTE,
executor) {
@Override
public void sendAccept() {
// has no meaning for HTTP: do nothing
}
@Override
public void sendReject() {
Response response = Response.createResponse(getRequest(), ResponseCode.INTERNAL_SERVER_ERROR);
sendResponse(response);
}
@Override
public void sendResponse(Response response) {
Request request = getRequest();
if (response.getType() == null) {
Type reqType = request.getType();
if (request.acknowledge()) {
response.setType(Type.ACK);
} else {
response.setType(reqType);
}
}
request.setResponse(response);
respond(httpExchange, response);
}
};
messageDeliverer.deliverRequest(coapExchange);
} else {
int httpCode = 404;
String contentType = "text/html; charset=utf-8";
byte[] payload = "<h1>404 - Not found!</h1>".getBytes(StandardCharsets.UTF_8);
respond(httpExchange, httpCode, contentType, payload);
updateBan(httpExchange);
}
}
public boolean respond(HttpExchange httpExchange, Response response) {
LOGGER.info("CoAP response: {}", response);
final URI uri = httpExchange.getRequestURI();
String contentType = "text/html; charset=utf-8";
byte[] payload = response.getPayload();
int httpCode = 200;
if (response.isSuccess()) {
if (response.getOptions().getContentFormat() == MediaTypeRegistry.APPLICATION_LINK_FORMAT) {
Set<WebLink> links = LinkFormat.parse(response.getPayloadString());
String path = uri.getPath();
String title = path;
int index = path.lastIndexOf('/');
if (index >= 0) {
title = path.substring(index + 1);
path = path.substring(0, index + 1);
}
String page = HtmlGenerator.createListPage(path, "", title, links, null, Devices.ATTRIBUTE_TIME);
payload = page.getBytes(StandardCharsets.UTF_8);
} else {
contentType = "text/plain; charset=utf-8";
}
List<byte[]> tags = response.getOptions().getETags();
if (!tags.isEmpty()) {
byte[] etag = tags.get(0);
httpExchange.getResponseHeaders().set("ETag", StringUtil.byteArray2Hex(etag));
}
} else {
switch (response.getCode()) {
case NOT_FOUND:
httpCode = 404;
payload = "<h1>404 - Not found!</h1>".getBytes(StandardCharsets.UTF_8);
break;
case METHOD_NOT_ALLOWED:
httpCode = 405;
payload = "<h1>405 - Method not allowed!</h1>".getBytes(StandardCharsets.UTF_8);
break;
default:
httpCode = 500;
payload = "<h1>500 - Internal server error!</h1>".getBytes(StandardCharsets.UTF_8);
break;
}
}
try {
respond(httpExchange, httpCode, contentType, payload);
LOGGER.info("HTTP returned {}", response);
} catch (IOException e) {
LOGGER.warn("write response to {} failed!", httpExchange.getRemoteAddress(), e);
}
updateBan(httpExchange);
return true;
}
public void respond(HttpExchange httpExchange, int httpCode, String contentType, byte[] payload)
throws IOException {
HttpService.respond(httpExchange, httpCode, contentType, payload);
}
public boolean updateBan(final HttpExchange httpExchange) {
return true;
}
}
/**
* Create {@link CredentialsStore} from "lets encrypt path".
*
* Appends {@link #HTTPS_PRIVATE_KEY} and {@link #HTTPS_FULL_CHAIN} to the
* provided path to load credentials.
*
* @param credentialsPath path to lets encrypt credentials
* @param password64 base64 encoded password of credentials. May be
* {@code null}, if credentials are not encrypted.
* @return created credentials store
* @throws IOException if an i/o error occurs
* @throws GeneralSecurityException if an encryption error occurs.
*/
public static CredentialsStore loadCredentials(String credentialsPath, String password64)
throws IOException, GeneralSecurityException {
if (credentialsPath.endsWith("/")) {
credentialsPath = credentialsPath.substring(0, credentialsPath.length() - 1);
}
String privateKey = credentialsPath + "/" + HTTPS_PRIVATE_KEY;
String fullChain = credentialsPath + "/" + HTTPS_FULL_CHAIN;
File directory = new File(credentialsPath);
if (!directory.exists()) {
LOGGER.error("Missing directory {} for https credentials!", credentialsPath);
} else {
File file = new File(fullChain);
if (!file.exists()) {
LOGGER.error("Missing https full-chain {}!", fullChain);
} else if (!file.canRead()) {
LOGGER.error("Missing read permission for https full-chain {}!", fullChain);
}
file = new File(privateKey);
if (!file.exists()) {
LOGGER.error("Missing https private-key {}!", privateKey);
} else if (!file.canRead()) {
LOGGER.error("Missing read permission for https private-key {}!", privateKey);
}
}
CredentialsStore credentialsStore = new CredentialsStore() {
/**
* {@inheritDoc}
*
* Add check for certificate chain.
*/
@Override
protected boolean complete(Credentials newCredentials) {
return super.complete(newCredentials) && newCredentials.getCertificateChain() != null;
}
};
credentialsStore.setTag("https ");
credentialsStore.loadAndCreateMonitor(fullChain, privateKey, password64, true);
return credentialsStore;
}
public static HttpService getHttpService() {
return httpService;
}
/**
* Create http service.
*
* @param httpsPort server poet
* @param credentialsPath server credentials
* @param password64 base64 encoded password of credentials. May be
* {@code null}, if credentials are not encrypted.
* @param tls12Only use TLS 1.2 only
* @return {@code true} on success, {@code false} otherwise.
*/
public static boolean createHttpService(int httpsPort, String credentialsPath, String password64,
boolean tls12Only) {
try {
CredentialsStore credentials = loadCredentials(credentialsPath, password64);
HttpService service = new HttpService(new InetSocketAddress(httpsPort), credentials,
tls12Only ? TLS_1_2 : TLS, tls12Only ? TLS_PROTOCOLS_1_2_ONLY : TLS_PROTOCOLS);
httpService = service;
return true;
} catch (IOException e) {
LOGGER.error("I/O error", e);
} catch (GeneralSecurityException e) {
LOGGER.error("Crypto error", e);
}
return false;
}
public static boolean startHttpService() {
HttpService service = httpService;
if (service != null) {
service.start();
return true;
} else {
LOGGER.error("HTTP service missing!");
return false;
}
}
public static boolean stopHttpService() {
HttpService service = httpService;
if (service != null) {
service.stop();
return true;
} else {
LOGGER.error("HTTP service missing!");
return false;
}
}
}