-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
HTTP2ServerConnection.java
381 lines (346 loc) · 13.1 KB
/
HTTP2ServerConnection.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
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// 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 Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.http2.server;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.Executor;
import org.eclipse.jetty.http.BadMessageException;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.MetaData;
import org.eclipse.jetty.http.MetaData.Request;
import org.eclipse.jetty.http2.ErrorCode;
import org.eclipse.jetty.http2.HTTP2Channel;
import org.eclipse.jetty.http2.HTTP2Connection;
import org.eclipse.jetty.http2.ISession;
import org.eclipse.jetty.http2.IStream;
import org.eclipse.jetty.http2.api.server.ServerSessionListener;
import org.eclipse.jetty.http2.frames.DataFrame;
import org.eclipse.jetty.http2.frames.Frame;
import org.eclipse.jetty.http2.frames.HeadersFrame;
import org.eclipse.jetty.http2.frames.PrefaceFrame;
import org.eclipse.jetty.http2.frames.ResetFrame;
import org.eclipse.jetty.http2.frames.SettingsFrame;
import org.eclipse.jetty.http2.parser.ServerParser;
import org.eclipse.jetty.http2.parser.SettingsBodyParser;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.RetainableByteBufferPool;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.thread.AutoLock;
public class HTTP2ServerConnection extends HTTP2Connection
{
/**
* @param protocol An HTTP2 protocol variant
* @return True if the protocol version is supported
*/
public static boolean isSupportedProtocol(String protocol)
{
switch (protocol)
{
case "h2":
case "h2-17":
case "h2-16":
case "h2-15":
case "h2-14":
case "h2c":
case "h2c-17":
case "h2c-16":
case "h2c-15":
case "h2c-14":
return true;
default:
return false;
}
}
private final AutoLock lock = new AutoLock();
private final Queue<HttpChannelOverHTTP2> channels = new ArrayDeque<>();
private final List<Frame> upgradeFrames = new ArrayList<>();
private final ServerSessionListener listener;
private final HttpConfiguration httpConfig;
private boolean recycleHttpChannels = true;
public HTTP2ServerConnection(RetainableByteBufferPool retainableByteBufferPool, Executor executor, EndPoint endPoint, HttpConfiguration httpConfig, ServerParser parser, ISession session, int inputBufferSize, ServerSessionListener listener)
{
super(retainableByteBufferPool, executor, endPoint, parser, session, inputBufferSize);
this.listener = listener;
this.httpConfig = httpConfig;
}
@Override
protected ServerParser getParser()
{
return (ServerParser)super.getParser();
}
public boolean isRecycleHttpChannels()
{
return recycleHttpChannels;
}
public void setRecycleHttpChannels(boolean recycleHttpChannels)
{
this.recycleHttpChannels = recycleHttpChannels;
}
@Override
public void onOpen()
{
ISession session = getSession();
notifyAccept(session);
for (Frame frame : upgradeFrames)
{
session.onFrame(frame);
}
super.onOpen();
produce();
}
private void notifyAccept(ISession session)
{
try
{
listener.onAccept(session);
}
catch (Throwable x)
{
LOG.info("Failure while notifying listener {}", listener, x);
}
}
public void onNewStream(Connector connector, IStream stream, HeadersFrame frame)
{
if (LOG.isDebugEnabled())
LOG.debug("Processing {} on {}", frame, stream);
HttpChannelOverHTTP2 channel = provideHttpChannel(connector, stream);
Runnable task = channel.onRequest(frame);
if (task != null)
offerTask(task, false);
}
public void onData(IStream stream, DataFrame frame, Callback callback)
{
if (LOG.isDebugEnabled())
LOG.debug("Processing {} on {}", frame, stream);
HTTP2Channel.Server channel = (HTTP2Channel.Server)stream.getAttachment();
if (channel != null)
{
Runnable task = channel.onData(frame, callback);
if (task != null)
offerTask(task, false);
}
else
{
callback.failed(new IOException("channel_not_found"));
}
}
public void onTrailers(IStream stream, HeadersFrame frame)
{
if (LOG.isDebugEnabled())
LOG.debug("Processing trailers {} on {}", frame, stream);
HTTP2Channel.Server channel = (HTTP2Channel.Server)stream.getAttachment();
if (channel != null)
{
Runnable task = channel.onTrailer(frame);
if (task != null)
offerTask(task, false);
}
}
public boolean onStreamTimeout(IStream stream, Throwable failure)
{
HTTP2Channel.Server channel = (HTTP2Channel.Server)stream.getAttachment();
boolean result = channel != null && channel.onTimeout(failure, task -> offerTask(task, true));
if (LOG.isDebugEnabled())
LOG.debug("{} idle timeout on {}: {}", result ? "Processed" : "Ignored", stream, failure);
return result;
}
public void onStreamFailure(IStream stream, Throwable failure, Callback callback)
{
if (LOG.isDebugEnabled())
LOG.debug("Processing stream failure on {}", stream, failure);
HTTP2Channel.Server channel = (HTTP2Channel.Server)stream.getAttachment();
if (channel != null)
{
Runnable task = channel.onFailure(failure, callback);
if (task != null)
{
// We must dispatch to another thread because the task
// may call application code that performs blocking I/O.
offerTask(task, true);
}
}
else
{
callback.succeeded();
}
}
public boolean onSessionTimeout(Throwable failure)
{
ISession session = getSession();
// Compute whether all requests are idle.
boolean result = session.getStreams().stream()
.map(stream -> (IStream)stream)
.map(stream -> (HTTP2Channel.Server)stream.getAttachment())
.filter(Objects::nonNull)
.map(HTTP2Channel.Server::isIdle)
.reduce(true, Boolean::logicalAnd);
if (LOG.isDebugEnabled())
LOG.debug("{} idle timeout on {}: {}", result ? "Processed" : "Ignored", session, failure);
return result;
}
public void onSessionFailure(Throwable failure, Callback callback)
{
if (LOG.isDebugEnabled())
LOG.debug("Processing session failure on {}", getSession(), failure);
// All the streams have already been failed, just succeed the callback.
callback.succeeded();
}
public void push(Connector connector, IStream stream, MetaData.Request request)
{
if (LOG.isDebugEnabled())
LOG.debug("Processing push {} on {}", request, stream);
HttpChannelOverHTTP2 channel = provideHttpChannel(connector, stream);
Runnable task = channel.onPushRequest(request);
if (task != null)
offerTask(task, true);
}
private HttpChannelOverHTTP2 provideHttpChannel(Connector connector, IStream stream)
{
HttpChannelOverHTTP2 channel = pollHttpChannel();
if (channel != null)
{
channel.getHttpTransport().setStream(stream);
if (LOG.isDebugEnabled())
LOG.debug("Recycling channel {} for {}", channel, this);
}
else
{
HttpTransportOverHTTP2 transport = new HttpTransportOverHTTP2(connector, this);
transport.setStream(stream);
channel = newServerHttpChannelOverHTTP2(connector, httpConfig, transport);
channel.setUseOutputDirectByteBuffers(isUseOutputDirectByteBuffers());
if (LOG.isDebugEnabled())
LOG.debug("Creating channel {} for {}", channel, this);
}
stream.setAttachment(channel);
return channel;
}
protected ServerHttpChannelOverHTTP2 newServerHttpChannelOverHTTP2(Connector connector, HttpConfiguration httpConfig, HttpTransportOverHTTP2 transport)
{
return new ServerHttpChannelOverHTTP2(connector, httpConfig, getEndPoint(), transport);
}
private void offerHttpChannel(HttpChannelOverHTTP2 channel)
{
if (isRecycleHttpChannels())
{
try (AutoLock l = lock.lock())
{
channels.offer(channel);
}
}
}
private HttpChannelOverHTTP2 pollHttpChannel()
{
if (isRecycleHttpChannels())
{
try (AutoLock l = lock.lock())
{
return channels.poll();
}
}
else
{
return null;
}
}
public boolean upgrade(Request request, HttpFields.Mutable responseFields)
{
if (HttpMethod.PRI.is(request.getMethod()))
{
getParser().directUpgrade();
}
else
{
HttpField settingsField = request.getFields().getField(HttpHeader.HTTP2_SETTINGS);
if (settingsField == null)
throw new BadMessageException("Missing " + HttpHeader.HTTP2_SETTINGS + " header");
String value = settingsField.getValue();
final byte[] settings = Base64.getUrlDecoder().decode(value == null ? "" : value);
if (LOG.isDebugEnabled())
LOG.debug("{} {}: {}", this, HttpHeader.HTTP2_SETTINGS, TypeUtil.toHexString(settings));
SettingsFrame settingsFrame = SettingsBodyParser.parseBody(BufferUtil.toBuffer(settings));
if (settingsFrame == null)
{
LOG.warn("Invalid {} header value: {}", HttpHeader.HTTP2_SETTINGS, value);
throw new BadMessageException();
}
responseFields.put(HttpHeader.UPGRADE, "h2c");
responseFields.put(HttpHeader.CONNECTION, "Upgrade");
getParser().standardUpgrade();
// We fake that we received a client preface, so that we can send the
// server preface as the first HTTP/2 frame as required by the spec.
// When the client sends the real preface, the parser won't notify it.
upgradeFrames.add(new PrefaceFrame());
// This is the settings from the HTTP2-Settings header.
upgradeFrames.add(settingsFrame);
// Remember the request to send a response.
upgradeFrames.add(new HeadersFrame(1, request, null, true));
}
return true;
}
protected class ServerHttpChannelOverHTTP2 extends HttpChannelOverHTTP2 implements Closeable
{
public ServerHttpChannelOverHTTP2(Connector connector, HttpConfiguration configuration, EndPoint endPoint, HttpTransportOverHTTP2 transport)
{
super(connector, configuration, endPoint, transport);
}
@Override
protected boolean checkAndPrepareUpgrade()
{
return isTunnel() && getHttpTransport().prepareUpgrade();
}
@Override
public void onCompleted()
{
super.onCompleted();
if (!getStream().isReset() && !isTunnel())
recycle();
}
private boolean isTunnel()
{
return HttpMethod.CONNECT.is(getRequest().getMethod()) && getResponse().getStatus() == HttpStatus.OK_200;
}
@Override
public void recycle()
{
getStream().setAttachment(null);
super.recycle();
offerHttpChannel(this);
}
@Override
public void close()
{
IStream stream = getStream();
if (LOG.isDebugEnabled())
LOG.debug("HTTP2 Request #{}/{} rejected", stream.getId(), Integer.toHexString(stream.getSession().hashCode()));
stream.reset(new ResetFrame(stream.getId(), ErrorCode.ENHANCE_YOUR_CALM_ERROR.code), Callback.NOOP);
// Consume the existing queued data frames to
// avoid stalling the session flow control.
consumeInput();
}
}
}