-
-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathServerOptions.java
More file actions
660 lines (583 loc) · 18.9 KB
/
ServerOptions.java
File metadata and controls
660 lines (583 loc) · 18.9 KB
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
/*
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import static java.util.Spliterators.spliteratorUnknownSize;
import static java.util.stream.StreamSupport.stream;
import java.security.Security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.Spliterator;
import java.util.stream.Stream;
import javax.net.ssl.SSLContext;
import org.jspecify.annotations.Nullable;
import com.typesafe.config.Config;
import io.jooby.internal.SslContextProvider;
import io.jooby.output.OutputOptions;
/**
* Available server options. To load server options from configuration files, just do:
*
* <pre>{@code
* Optional<ServerOptions> serverOptions = ServerOptions.from(getEnvironment().getConfig());
*
* }</pre>
*
* @author edgar
* @since 2.0.0
*/
public class ServerOptions {
static {
// Initialize server defaults by loading server first.
ServiceLoader.load(Server.class).findFirst();
}
/**
* Default application port <code>8080</code> or the value of system property <code>server.port
* </code>.
*/
public static final int SERVER_PORT = Integer.parseInt(System.getProperty("server.port", "8080"));
/**
* Default application secures port <code>8443</code> or the value of system property <code>
* server.securePort</code>.
*/
public static final int SERVER_SECURE_PORT =
Integer.parseInt(System.getProperty("server.securePort", "8443"));
/** Default compression level for gzip. */
public static final int DEFAULT_COMPRESSION_LEVEL = 6;
/** 4kb constant in bytes. */
public static final int _4KB = 4096;
/** 8kb constant in bytes. */
public static final int _8KB = 8192;
/** 16kb constant in bytes. */
public static final int _16KB = 16384;
/** 10mb constant in bytes. */
public static final int _10MB = 10485760;
private static final String LOCAL_HOST = "0.0.0.0";
/** Number of available io threads. Default is number of available processors */
public static final int IO_THREADS =
Integer.parseInt(
System.getProperty(
"__server_.ioThreads", Integer.toString(Runtime.getRuntime().availableProcessors())));
private static final String SERVER_NAME = System.getProperty("__server_.name");
/**
* Number of worker (a.k.a application) threads. It is the number of ioThreads multiply by <code>
* 8</code>.
*/
public static final int WORKER_THREADS =
Integer.parseInt(
System.getProperty("__server_.workerThreads", Integer.toString(IO_THREADS * 8)));
/** HTTP port. Default is <code>8080</code> or <code>0</code> for random port. */
private int port = SERVER_PORT;
/** Number of IO threads used by the server. Used by Netty and Undertow. */
private int ioThreads = IO_THREADS;
/** Number of worker threads (a.k.a application) to use. */
private int workerThreads = WORKER_THREADS;
/**
* Configure server to default headers: <code>Date</code>, <code>Content-Type</code> and <code>
* Server</code> header.
*/
private boolean defaultHeaders = true;
/** Name of server: Jetty, Netty or Undertow. */
private String server = SERVER_NAME;
private OutputOptions output = OutputOptions.defaults();
/**
* Maximum request size in bytes. Request exceeding this value results in {@link
* io.jooby.StatusCode#REQUEST_ENTITY_TOO_LARGE} response. Default is <code>10mb</code>.
*/
private int maxRequestSize = _10MB;
/** Max number of form fields. Default: <code>1000</code>. */
private int maxFormFields = 1000;
/** The maximum size in bytes of a http request header. Default is <code>8kb</code> */
private int maxHeaderSize = _8KB;
private String host = LOCAL_HOST;
private SslOptions ssl;
private Integer securePort;
/** Bind only https port. Default is false. */
private boolean httpsOnly;
private Integer compressionLevel;
private Boolean http2;
private Boolean expectContinue;
/** Internal usage only. */
/*package*/ boolean defaults;
/*package*/ ServerOptions(boolean defaults) {
this.defaults = defaults;
}
/** Default constructor. */
public ServerOptions() {
this(false);
}
/**
* Creates server options from config object. The configuration options must provided entries
* like: <code>server.port</code>, <code>server.ioThreads</code>, etc...
*
* @param conf Configuration object.
* @return Server options.
*/
public static Optional<ServerOptions> from(Config conf) {
if (conf.hasPath("server")) {
var options = new ServerOptions();
if (conf.hasPath("server.port")) {
options.setPort(conf.getInt("server.port"));
}
if (conf.hasPath("server.securePort")) {
options.setSecurePort(conf.getInt("server.securePort"));
}
if (conf.hasPath("server.ioThreads")) {
options.setIoThreads(conf.getInt("server.ioThreads"));
}
if (conf.hasPath("server.name")) {
options.setServer(conf.getString("server.name"));
}
if (conf.hasPath("server.output.size")) {
options.output.setSize(conf.getInt("server.output.size"));
}
if (conf.hasPath("server.output.useDirectBuffers")) {
options.output.setDirectBuffers(conf.getBoolean("server.output.useDirectBuffers"));
}
if (conf.hasPath("server.defaultHeaders")) {
options.setDefaultHeaders(conf.getBoolean("server.defaultHeaders"));
}
if (conf.hasPath("server.gzip")) {
throw new UnsupportedOperationException(
"server.gzip was removed, use server.compressionLevel instead.");
}
if (conf.hasPath("server.compressionLevel")) {
options.setCompressionLevel(conf.getInt("server.compressionLevel"));
}
if (conf.hasPath("server.maxRequestSize")) {
options.setMaxRequestSize((int) conf.getMemorySize("server.maxRequestSize").toBytes());
}
if (conf.hasPath("server.maxFormFields")) {
options.setMaxFormFields(conf.getInt("server.maxFormFields"));
}
if (conf.hasPath("server.workerThreads")) {
options.setWorkerThreads(conf.getInt("server.workerThreads"));
}
if (conf.hasPath("server.host")) {
options.setHost(conf.getString("server.host"));
}
if (conf.hasPath("server.expectContinue")) {
options.setExpectContinue(conf.getBoolean("server.expectContinue"));
}
// ssl
SslOptions.from(conf, "server.ssl").ifPresent(options::setSsl);
if (conf.hasPath("server.httpsOnly")) {
options.httpsOnly = conf.getBoolean("server.httpsOnly");
}
if (conf.hasPath("server.http2")) {
options.setHttp2(conf.getBoolean("server.http2"));
}
return Optional.of(options);
}
return Optional.empty();
}
@Override
public String toString() {
StringBuilder buff = new StringBuilder();
buff.append(Optional.ofNullable(server).orElse("server")).append(" {");
buff.append("port: ").append(port);
buff.append(", ioThreads: ").append(getIoThreads());
buff.append(", workerThreads: ").append(getWorkerThreads());
buff.append(", output: ").append(getOutput());
buff.append(", maxRequestSize: ").append(maxRequestSize);
buff.append(", httpsOnly: ").append(httpsOnly);
if (compressionLevel != null) {
buff.append(", gzip");
}
buff.append("}");
return buff.toString();
}
/**
* Set server name.
*
* @param server Name of the underlying server.
* @return This options.
*/
public ServerOptions setServer(String server) {
this.server = server;
return this;
}
/**
* Server name.
*
* @return Server name.
*/
public String getServer() {
return server;
}
/**
* Server HTTP port.
*
* @return Server HTTP port.
*/
public int getPort() {
return port;
}
/**
* Set the server port (default is 8080). For random port use: <code>0</code>.
*
* @param port Server port or <code>0</code> to pick a random port.
* @return This options.
*/
public ServerOptions setPort(int port) {
this.port = Math.max(0, port);
return this;
}
/**
* HTTPs port or <code>null</code>.
*
* @return HTTPs port or <code>null</code>.
*/
public @Nullable Integer getSecurePort() {
return securePort;
}
/**
* True when SSL is enabled. Either bc the secure port, httpsOnly or SSL options are set.
*
* @return True when SSL is enabled. Either bc the secure port, httpsOnly or SSL options are set.
*/
public boolean isSSLEnabled() {
return securePort != null || ssl != null || http2 == Boolean.TRUE || httpsOnly;
}
/**
* Set HTTPs port.
*
* @param securePort Port number or <code>0</code> for random number.
* @return This options.
*/
public ServerOptions setSecurePort(@Nullable Integer securePort) {
if (securePort == null) {
this.securePort = null;
} else {
this.securePort = Math.max(0, securePort);
}
return this;
}
/**
* Bind only https port. Default is false.
*
* @return True when only https is required.
*/
public boolean isHttpsOnly() {
return httpsOnly;
}
/**
* Bind only https port. Default is false.
*
* @param httpsOnly True to bind only HTTPS.
* @return This options.
*/
public ServerOptions setHttpsOnly(boolean httpsOnly) {
this.httpsOnly = httpsOnly;
return this;
}
/**
* Number of IO threads used by the server. Required by Netty and Undertow.
*
* @return Number of IO threads used by the server. Required by Netty and Undertow.
*/
public int getIoThreads() {
return ioThreads;
}
/**
* Set number of IO threads to use. Supported by Netty and Undertow.
*
* @param ioThreads Number of threads. Must be greater than <code>0</code>.
* @return This options.
*/
public ServerOptions setIoThreads(int ioThreads) {
this.ioThreads = ioThreads;
return this;
}
/**
* Number of worker threads (a.k.a application) to use. These are the threads which are allowed to
* block.
*
* @return Number of worker threads (a.k.a application) to use. These are the threads which are
* allowed to block.
*/
public int getWorkerThreads() {
return workerThreads;
}
/**
* Set number of worker threads (a.k.a application) to use. These are the threads which are
* allowed to block.
*
* @param workerThreads Number of worker threads to use.
* @return This options.
*/
public ServerOptions setWorkerThreads(int workerThreads) {
this.workerThreads = workerThreads;
return this;
}
/**
* Indicates compression level to use while producing gzip responses.
*
* @return Compression level value between <code>0...9</code> or <code>null</code> when off.
*/
public @Nullable Integer getCompressionLevel() {
return compressionLevel;
}
/**
* Set compression level to use while producing gzip responses.
*
* <p>Gzip is off by default (compression level is null).
*
* @param compressionLevel Value between <code>0..9</code> or <code>null</code>.
* @return This options.
*/
public ServerOptions setCompressionLevel(@Nullable Integer compressionLevel) {
this.compressionLevel = compressionLevel;
return this;
}
/**
* True if default headers: <code>Date</code>, <code>Content-Type</code> and <code>Server</code>
* are enabled.
*
* @return True if default headers: <code>Date</code>, <code>Content-Type</code> and <code>Server
* </code> are enabled.
*/
public boolean getDefaultHeaders() {
return defaultHeaders;
}
/**
* Enabled/disabled default server headers: <code>Date</code>, <code>Content-Type</code> and
* <code>Server</code>. Enabled by default.
*
* @param defaultHeaders True for enabled.
* @return This options.
*/
public ServerOptions setDefaultHeaders(boolean defaultHeaders) {
this.defaultHeaders = defaultHeaders;
return this;
}
/**
* Output options. Control what type of buffer is used and default size.
*
* @return Output options. Control what type of buffer is used and default size.
*/
public OutputOptions getOutput() {
return output;
}
/**
* Set output options.
*
* @param output Options.
* @return This instance.
*/
public ServerOptions setOutput(OutputOptions output) {
this.output = output;
return this;
}
/**
* Maximum request size in bytes. Request exceeding this value results in {@link
* io.jooby.StatusCode#REQUEST_ENTITY_TOO_LARGE} response. Default is <code>10mb</code>.
*
* @return Maximum request size in bytes.
*/
public int getMaxRequestSize() {
return maxRequestSize;
}
/**
* Set max request size in bytes.
*
* @param maxRequestSize Max request size in bytes.
* @return This options.
*/
public ServerOptions setMaxRequestSize(int maxRequestSize) {
this.maxRequestSize = maxRequestSize;
return this;
}
/**
* Max number of form fields. Default: <code>1000</code>.
*
* @return Max number of form fields. Default: <code>1000</code>.
*/
public int getMaxFormFields() {
return maxFormFields;
}
/**
* Set max number of form fields. Default: <code>1000</code>.
*
* @param maxFormFields Max number of form fields.
* @return Max number of form fields. Default: <code>1000</code>.
*/
public ServerOptions setMaxFormFields(int maxFormFields) {
this.maxFormFields = maxFormFields;
return this;
}
/**
* The maximum size in bytes of an http request header. Exceeding the size generates a different
* response across server implementations.
*
* <ul>
* <li>Jetty: generates a 431 error message
* <li>Netty: the header is dropped/ignored, but don't fail
* <li>Undertow: generates an empty 400 response, and the connection is closed.
* </ul>
*
* @return The maximum size in bytes of an http request header.
*/
public int getMaxHeaderSize() {
return maxHeaderSize;
}
/**
* Set the maximum size in bytes of an http request header.
*
* @param maxHeaderSize The maximum size in bytes of an http request header. Default is <code>8kb
* </code>.
* @return The maximum size in bytes of an http request header. Default is <code>8kb</code>.
*/
public ServerOptions setMaxHeaderSize(int maxHeaderSize) {
this.maxHeaderSize = maxHeaderSize;
return this;
}
/**
* Server host, defaults is <code>0.0.0.0</code>.
*
* @return Server host, defaults is <code>0.0.0.0</code>.
*/
public String getHost() {
return host;
}
/**
* Set the server host, defaults to <code>0.0.0.0</code>.
*
* @param host Server host. Localhost, null or empty values fallback to <code>0.0.0.0</code>.
* @return This options.
*/
public ServerOptions setHost(String host) {
if (host == null || host.trim().length() == 0 || "localhost".equalsIgnoreCase(host.trim())) {
this.host = LOCAL_HOST;
} else {
this.host = host;
}
return this;
}
/**
* SSL options.
*
* @return SSL options.
*/
public @Nullable SslOptions getSsl() {
return ssl;
}
/**
* Set SSL options.
*
* @param ssl SSL options.
* @return Server options.
*/
public ServerOptions setSsl(@Nullable SslOptions ssl) {
this.ssl = ssl;
return this;
}
/**
* Specify when HTTP/2 is enabled or not. This value is set to <code>null</code>, which allows
* Jooby to enabled by default when dependency is added it.
*
* <p>To turn off set to false.
*
* @return Whenever HTTP/2 is enabled.
*/
public @Nullable Boolean isHttp2() {
return http2;
}
/**
* Turn on/off HTTP/2 support.
*
* @param http2 True to enabled.
* @return This options.
*/
public ServerOptions setHttp2(@Nullable Boolean http2) {
this.http2 = http2;
return this;
}
/**
* Whenever 100-Expect and continue requests are handled by the server. This is off by default,
* except for Jetty which is always ON.
*
* @return True when enabled.
*/
public @Nullable Boolean isExpectContinue() {
return expectContinue;
}
/**
* Set 100-Expect and continue requests are handled by the server. This is off by default, except
* for Jetty which is always ON.
*
* @param expectContinue True or false.
* @return This options.
*/
public ServerOptions setExpectContinue(@Nullable Boolean expectContinue) {
this.expectContinue = expectContinue;
return this;
}
/**
* Creates SSL context using the given resource loader. This method attempts to create a
* SSLContext when one of the following is true:
*
* <ul>
* <li>{@link #getSecurePort()} has been set
* <li>{@link #getSsl()} has been set.
* </ul>
*
* <p>If secure port is set and there is no SSL options, this method configure a SSL context using
* the a self-signed certificate for <code>localhost</code>.
*
* <p>If {@link SslOptions#getSslContext()} is set, it is returned without modification.
*
* @param loader Resource loader.
* @return SSLContext or <code>null</code> when SSL is disabled.
*/
public @Nullable SSLContext getSSLContext(ClassLoader loader) {
if (isSSLEnabled()) {
setSecurePort(Optional.ofNullable(securePort).orElse(SERVER_SECURE_PORT));
SslOptions options = Optional.ofNullable(ssl).orElseGet(SslOptions::selfSigned);
setSsl(options);
SSLContext sslContext;
if (options.getSslContext() == null) {
SslContextProvider sslContextProvider =
Stream.of(SslContextProvider.providers())
.filter(it -> it.supports(options.getType()))
.findFirst()
.orElseThrow(
() -> new UnsupportedOperationException("SSL Type: " + options.getType()));
String providerName =
stream(
spliteratorUnknownSize(
ServiceLoader.load(SslProvider.class).iterator(), Spliterator.ORDERED),
false)
.findFirst()
.map(
provider -> {
String name = provider.getName();
if (Security.getProvider(name) == null) {
Security.addProvider(provider.create());
}
return name;
})
.orElse(null);
sslContext = sslContextProvider.create(loader, providerName, options);
} else {
sslContext = options.getSslContext();
}
// validate TLS protocol, at least one protocol must be supported
Set<String> supportedProtocols =
new LinkedHashSet<>(Arrays.asList(sslContext.getDefaultSSLParameters().getProtocols()));
Set<String> protocols = new LinkedHashSet<>(options.getProtocol());
protocols.retainAll(supportedProtocols);
if (protocols.isEmpty()) {
throw new IllegalArgumentException("Unsupported protocol: " + options.getProtocol());
}
ssl.setProtocol(new ArrayList<>(protocols));
return sslContext;
}
return null;
}
}