forked from http4s/http4s
/
BlazeServerBuilder.scala
350 lines (300 loc) · 12.2 KB
/
BlazeServerBuilder.scala
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
package org.http4s
package server
package blaze
import cats._
import cats.data.Kleisli
import cats.implicits._
import cats.effect._
import java.io.FileInputStream
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.security.{KeyStore, Security}
import javax.net.ssl.{KeyManagerFactory, SSLContext, SSLEngine, TrustManagerFactory}
import org.http4s.blaze.{BuildInfo => BlazeBuildInfo}
import org.http4s.blaze.channel.{ChannelOptions, DefaultPoolSize, SocketConnection}
import org.http4s.blaze.channel.nio1.NIO1SocketServerGroup
import org.http4s.blaze.channel.nio2.NIO2SocketServerGroup
import org.http4s.blaze.http.http2.server.ALPNServerSelector
import org.http4s.blaze.pipeline.LeafBuilder
import org.http4s.blaze.pipeline.stages.SSLStage
import org.http4s.blazecore.{BlazeBackendBuilder, tickWheelResource}
import org.http4s.server.SSLKeyStoreSupport.StoreInfo
import org.log4s.getLogger
import scala.collection.immutable
import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration._
/**
* BlazeBuilder is the component for the builder pattern aggregating
* different components to finally serve requests.
*
* Variables:
* @param socketAddress: Socket Address the server will be mounted at
* @param executionContext: Execution Context the underlying blaze futures
* will be executed upon.
* @param responseHeaderTimeout: Time from when the request is made until a
* response line is generated before a 503 response is returned and the
* `HttpApp` is canceled
* @param idleTimeout: Period of Time a connection can remain idle before the
* connection is timed out and disconnected.
* Duration.Inf disables this feature.
* @param isNio2: Whether or not to use NIO2 or NIO1 Socket Server Group
* @param connectorPoolSize: Number of worker threads for the new Socket Server Group
* @param bufferSize: Buffer size to use for IO operations
* @param enableWebsockets: Enables Websocket Support
* @param sslBits: If defined enables secure communication to the server using the
* sslContext
* @param isHttp2Enabled: Whether or not to enable Http2 Server Features
* @param maxRequestLineLength: Maximum request line to parse
* If exceeded returns a 400 Bad Request.
* @param maxHeadersLen: Maximum data that composes the headers.
* If exceeded returns a 400 Bad Request.
* @param serviceMounts: The services that are mounted on this server to serve.
* These services get assembled into a Router with the longer prefix winning.
* @param serviceErrorHandler: The last resort to recover and generate a response
* this is necessary to recover totality from the error condition.
* @param banner: Pretty log to display on server start. An empty sequence
* such as Nil disables this
*/
class BlazeServerBuilder[F[_]](
socketAddress: InetSocketAddress,
executionContext: ExecutionContext,
responseHeaderTimeout: Duration,
idleTimeout: Duration,
isNio2: Boolean,
connectorPoolSize: Int,
bufferSize: Int,
enableWebSockets: Boolean,
sslBits: Option[SSLConfig],
isHttp2Enabled: Boolean,
maxRequestLineLen: Int,
maxHeadersLen: Int,
httpApp: HttpApp[F],
serviceErrorHandler: ServiceErrorHandler[F],
banner: immutable.Seq[String],
val channelOptions: ChannelOptions
)(implicit protected val F: ConcurrentEffect[F], timer: Timer[F])
extends ServerBuilder[F]
with BlazeBackendBuilder[Server[F]] {
type Self = BlazeServerBuilder[F]
private[this] val logger = getLogger
private def copy(
socketAddress: InetSocketAddress = socketAddress,
executionContext: ExecutionContext = executionContext,
idleTimeout: Duration = idleTimeout,
responseHeaderTimeout: Duration = responseHeaderTimeout,
isNio2: Boolean = isNio2,
connectorPoolSize: Int = connectorPoolSize,
bufferSize: Int = bufferSize,
enableWebSockets: Boolean = enableWebSockets,
sslBits: Option[SSLConfig] = sslBits,
http2Support: Boolean = isHttp2Enabled,
maxRequestLineLen: Int = maxRequestLineLen,
maxHeadersLen: Int = maxHeadersLen,
httpApp: HttpApp[F] = httpApp,
serviceErrorHandler: ServiceErrorHandler[F] = serviceErrorHandler,
banner: immutable.Seq[String] = banner,
channelOptions: ChannelOptions = channelOptions
): Self =
new BlazeServerBuilder(
socketAddress,
executionContext,
responseHeaderTimeout,
idleTimeout,
isNio2,
connectorPoolSize,
bufferSize,
enableWebSockets,
sslBits,
http2Support,
maxRequestLineLen,
maxHeadersLen,
httpApp,
serviceErrorHandler,
banner,
channelOptions
)
/** Configure HTTP parser length limits
*
* These are to avoid denial of service attacks due to,
* for example, an infinite request line.
*
* @param maxRequestLineLen maximum request line to parse
* @param maxHeadersLen maximum data that compose headers
*/
def withLengthLimits(
maxRequestLineLen: Int = maxRequestLineLen,
maxHeadersLen: Int = maxHeadersLen): Self =
copy(maxRequestLineLen = maxRequestLineLen, maxHeadersLen = maxHeadersLen)
def withSSL(
keyStore: StoreInfo,
keyManagerPassword: String,
protocol: String = "TLS",
trustStore: Option[StoreInfo] = None,
clientAuth: Boolean = false): Self = {
val bits = KeyStoreBits(keyStore, keyManagerPassword, protocol, trustStore, clientAuth)
copy(sslBits = Some(bits))
}
def withSSLContext(sslContext: SSLContext, clientAuth: Boolean = false): Self =
copy(sslBits = Some(SSLContextBits(sslContext, clientAuth)))
override def bindSocketAddress(socketAddress: InetSocketAddress): Self =
copy(socketAddress = socketAddress)
def withExecutionContext(executionContext: ExecutionContext): BlazeServerBuilder[F] =
copy(executionContext = executionContext)
def withIdleTimeout(idleTimeout: Duration): Self = copy(idleTimeout = idleTimeout)
def withResponseHeaderTimeout(responseHeaderTimeout: Duration): Self =
copy(responseHeaderTimeout = responseHeaderTimeout)
def withConnectorPoolSize(size: Int): Self = copy(connectorPoolSize = size)
def withBufferSize(size: Int): Self = copy(bufferSize = size)
def withNio2(isNio2: Boolean): Self = copy(isNio2 = isNio2)
def withWebSockets(enableWebsockets: Boolean): Self =
copy(enableWebSockets = enableWebsockets)
def enableHttp2(enabled: Boolean): Self = copy(http2Support = enabled)
def withHttpApp(httpApp: HttpApp[F]): Self =
copy(httpApp = httpApp)
def withServiceErrorHandler(serviceErrorHandler: ServiceErrorHandler[F]): Self =
copy(serviceErrorHandler = serviceErrorHandler)
def withBanner(banner: immutable.Seq[String]): Self =
copy(banner = banner)
def withChannelOptions(channelOptions: ChannelOptions): BlazeServerBuilder[F] =
copy(channelOptions = channelOptions)
def resource: Resource[F, Server[F]] = tickWheelResource.flatMap { scheduler =>
Resource(F.delay {
def resolveAddress(address: InetSocketAddress) =
if (address.isUnresolved) new InetSocketAddress(address.getHostName, address.getPort)
else address
val pipelineFactory: SocketConnection => Future[LeafBuilder[ByteBuffer]] = {
conn: SocketConnection =>
def requestAttributes(secure: Boolean) =
(conn.local, conn.remote) match {
case (local: InetSocketAddress, remote: InetSocketAddress) =>
AttributeMap(
AttributeEntry(
Request.Keys.ConnectionInfo,
Request.Connection(
local = local,
remote = remote,
secure = secure
)))
case _ =>
AttributeMap.empty
}
def http1Stage(secure: Boolean) =
Http1ServerStage(
httpApp,
requestAttributes(secure = secure),
executionContext,
enableWebSockets,
maxRequestLineLen,
maxHeadersLen,
serviceErrorHandler,
responseHeaderTimeout,
idleTimeout,
scheduler
)
def http2Stage(engine: SSLEngine): ALPNServerSelector =
ProtocolSelector(
engine,
httpApp,
maxRequestLineLen,
maxHeadersLen,
requestAttributes(secure = true),
executionContext,
serviceErrorHandler,
responseHeaderTimeout,
idleTimeout,
scheduler
)
Future.successful {
getContext() match {
case Some((ctx, clientAuth)) =>
val engine = ctx.createSSLEngine()
engine.setUseClientMode(false)
engine.setNeedClientAuth(clientAuth)
LeafBuilder(
if (isHttp2Enabled) http2Stage(engine)
else http1Stage(secure = true)
).prepend(new SSLStage(engine))
case None =>
if (isHttp2Enabled)
logger.warn("HTTP/2 support requires TLS. Falling back to HTTP/1.")
LeafBuilder(http1Stage(secure = false))
}
}
}
val factory =
if (isNio2)
NIO2SocketServerGroup.fixedGroup(connectorPoolSize, bufferSize, channelOptions)
else
NIO1SocketServerGroup.fixedGroup(connectorPoolSize, bufferSize, channelOptions)
val address = resolveAddress(socketAddress)
// if we have a Failure, it will be caught by the effect
val serverChannel = factory.bind(address, pipelineFactory).get
val server = new Server[F] {
val address: InetSocketAddress =
serverChannel.socketAddress
val isSecure = sslBits.isDefined
override def toString: String =
s"BlazeServer($address)"
}
val shutdown = F.delay {
serverChannel.close()
factory.closeGroup()
}
Option(banner)
.filter(_.nonEmpty)
.map(_.mkString("\n", "\n", ""))
.foreach(logger.info(_))
logger.info(
s"http4s v${BuildInfo.version} on blaze v${BlazeBuildInfo.version} started at ${server.baseUri}")
server -> shutdown
})
}
private def getContext(): Option[(SSLContext, Boolean)] = sslBits.map {
case KeyStoreBits(keyStore, keyManagerPassword, protocol, trustStore, clientAuth) =>
val ksStream = new FileInputStream(keyStore.path)
val ks = KeyStore.getInstance("JKS")
ks.load(ksStream, keyStore.password.toCharArray)
ksStream.close()
val tmf = trustStore.map { auth =>
val ksStream = new FileInputStream(auth.path)
val ks = KeyStore.getInstance("JKS")
ks.load(ksStream, auth.password.toCharArray)
ksStream.close()
val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
tmf.init(ks)
tmf.getTrustManagers
}
val kmf = KeyManagerFactory.getInstance(
Option(Security.getProperty("ssl.KeyManagerFactory.algorithm"))
.getOrElse(KeyManagerFactory.getDefaultAlgorithm))
kmf.init(ks, keyManagerPassword.toCharArray)
val context = SSLContext.getInstance(protocol)
context.init(kmf.getKeyManagers, tmf.orNull, null)
(context, clientAuth)
case SSLContextBits(context, clientAuth) =>
(context, clientAuth)
}
}
object BlazeServerBuilder {
def apply[F[_]](implicit F: ConcurrentEffect[F], timer: Timer[F]): BlazeServerBuilder[F] =
new BlazeServerBuilder(
socketAddress = defaults.SocketAddress,
executionContext = ExecutionContext.global,
responseHeaderTimeout = 1.minute,
idleTimeout = defaults.IdleTimeout,
isNio2 = false,
connectorPoolSize = DefaultPoolSize,
bufferSize = 64 * 1024,
enableWebSockets = true,
sslBits = None,
isHttp2Enabled = false,
maxRequestLineLen = 4 * 1024,
maxHeadersLen = 40 * 1024,
httpApp = defaultApp[F],
serviceErrorHandler = DefaultServiceErrorHandler[F],
banner = defaults.Banner,
channelOptions = ChannelOptions(Vector.empty)
)
private def defaultApp[F[_]: Applicative]: HttpApp[F] =
Kleisli(_ => Response[F](Status.NotFound).pure[F])
}