/
AbstractWebSocketConnection.java
694 lines (610 loc) · 19.7 KB
/
AbstractWebSocketConnection.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
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.websocket.common.io;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import org.eclipse.jetty.io.AbstractConnection;
import org.eclipse.jetty.io.AbstractEndPoint;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.Scheduler;
import org.eclipse.jetty.websocket.api.BatchMode;
import org.eclipse.jetty.websocket.api.CloseException;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.api.SuspendToken;
import org.eclipse.jetty.websocket.api.WebSocketException;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
import org.eclipse.jetty.websocket.api.WriteCallback;
import org.eclipse.jetty.websocket.api.extensions.ExtensionConfig;
import org.eclipse.jetty.websocket.api.extensions.Frame;
import org.eclipse.jetty.websocket.api.extensions.IncomingFrames;
import org.eclipse.jetty.websocket.common.CloseInfo;
import org.eclipse.jetty.websocket.common.Generator;
import org.eclipse.jetty.websocket.common.LogicalConnection;
import org.eclipse.jetty.websocket.common.Parser;
import org.eclipse.jetty.websocket.common.WebSocketSession;
import org.eclipse.jetty.websocket.common.frames.CloseFrame;
import static org.eclipse.jetty.websocket.api.WebSocketBehavior.SERVER;
/**
* Provides the implementation of {@link LogicalConnection} within the framework of the new {@link org.eclipse.jetty.io.Connection} framework of {@code jetty-io}.
*/
public abstract class AbstractWebSocketConnection extends AbstractConnection implements LogicalConnection, Connection.UpgradeTo, Dumpable
{
private static class CallbackBridge implements WriteCallback
{
private final Callback callback;
public CallbackBridge(Callback callback)
{
this.callback = callback != null ? callback : Callback.NOOP;
}
@Override
public void writeFailed(Throwable x)
{
callback.failed(x);
}
@Override
public void writeSuccess()
{
callback.succeeded();
}
}
private class Flusher extends FrameFlusher
{
private Flusher(ByteBufferPool bufferPool, Generator generator, EndPoint endpoint)
{
super(bufferPool, generator, endpoint, getPolicy().getMaxBinaryMessageBufferSize(), 8);
}
@Override
public void onCompleteFailure(Throwable failure)
{
AbstractWebSocketConnection.this.close(failure);
super.onCompleteFailure(failure);
}
}
@Deprecated
public static class Stats
{
private AtomicLong countFillInterestedEvents = new AtomicLong(0);
private AtomicLong countOnFillableEvents = new AtomicLong(0);
private AtomicLong countFillableErrors = new AtomicLong(0);
public long getFillableErrorCount()
{
return countFillableErrors.get();
}
public long getFillInterestedCount()
{
return countFillInterestedEvents.get();
}
public long getOnFillableCount()
{
return countOnFillableEvents.get();
}
}
private static final Logger LOG = Log.getLogger(AbstractWebSocketConnection.class);
private static final AtomicLong ID_GEN = new AtomicLong(0);
/**
* Minimum size of a buffer is the determined to be what would be the maximum framing header size (not including payload)
*/
private static final int MIN_BUFFER_SIZE = Generator.MAX_HEADER_LENGTH;
private final ByteBufferPool bufferPool;
private final Scheduler scheduler;
private final Generator generator;
private final Parser parser;
private final WebSocketPolicy policy;
private final ReadState readState = new ReadState();
private final ConnectionState connectionState = new ConnectionState();
private final FrameFlusher flusher;
private final String id;
private final LongAdder bytesIn = new LongAdder();
private WebSocketSession session;
private List<ExtensionConfig> extensions = new ArrayList<>();
private ByteBuffer initialBuffer;
private Stats stats = new Stats();
private CloseInfo fatalCloseInfo;
public AbstractWebSocketConnection(EndPoint endp, Executor executor, Scheduler scheduler, WebSocketPolicy policy, ByteBufferPool bufferPool)
{
super(endp, executor);
this.id = Long.toString(ID_GEN.incrementAndGet());
this.policy = policy;
this.bufferPool = bufferPool;
this.generator = new Generator(policy, bufferPool);
this.parser = new Parser(policy, bufferPool);
this.scheduler = scheduler;
this.flusher = new Flusher(bufferPool, generator, endp);
this.setInputBufferSize(policy.getInputBufferSize());
this.setMaxIdleTimeout(policy.getIdleTimeout());
}
@Override
public Executor getExecutor()
{
return super.getExecutor();
}
public void close(CloseInfo close, final Callback callback)
{
if (connectionState.closing())
{
boolean transmit = close.getStatusCode() == StatusCode.NO_CODE || StatusCode.isTransmittable(close.getStatusCode());
if (transmit)
{
CloseFrame frame = close.asFrame();
outgoingFrame(frame, new CallbackBridge(callback), BatchMode.OFF);
if (StatusCode.isFatal(close.getStatusCode()))
{
fatalCloseInfo = close;
}
}
else
{
disconnect();
}
}
else
{
if (callback != null)
{
callback.failed(new IllegalStateException("Local Close already called"));
}
}
}
/**
* Close the connection based on the throwable
*
* @param cause the cause
*/
public void close(Throwable cause)
{
session.callApplicationOnError(cause);
int statusCode = policy.getBehavior() == SERVER ? StatusCode.SERVER_ERROR : StatusCode.ABNORMAL;
if (cause instanceof CloseException)
{
statusCode = ((CloseException)cause).getStatusCode();
}
String reason = cause.getMessage();
if (StringUtil.isBlank(reason))
{
// an exception without a message.
reason = cause.getClass().getSimpleName();
}
CloseInfo closeInfo = new CloseInfo(statusCode, reason);
session.callApplicationOnClose(closeInfo);
close(closeInfo, new DisconnectCallback(this));
}
@Override
public boolean canWriteWebSocketFrames()
{
return connectionState.canWriteWebSocketFrames();
}
@Override
public boolean canReadWebSocketFrames()
{
return connectionState.canReadWebSocketFrames();
}
@Override
public String toStateString()
{
return connectionState.toString();
}
@Override
public boolean opening()
{
return connectionState.opening();
}
@Override
public boolean opened()
{
if (connectionState.opened())
{
if (BufferUtil.hasContent(initialBuffer))
{
if (LOG.isDebugEnabled())
LOG.debug("Parsing upgrade initial buffer ({} remaining)", initialBuffer.remaining());
parser.parse(initialBuffer);
initialBuffer = null;
}
fillInterested();
return true;
}
return false;
}
@Override
public void remoteClose(CloseInfo close)
{
session.callApplicationOnClose(close);
close(close, new DisconnectCallback(this));
}
@Override
public void setSession(WebSocketSession session)
{
this.session = session;
}
@Override
public boolean onIdleExpired()
{
// TODO: handle closing handshake (see HTTP2Connection).
return super.onIdleExpired();
}
/**
* Jetty Connection Close
*/
@Override
public void close()
{
close(new CloseInfo(), Callback.NOOP);
}
@Override
public void disconnect()
{
if (connectionState.disconnected())
{
if (connectionState.wasOpened())
{
/* Use prior Fatal Close Info if present, otherwise
* because if could be from a failed close handshake where
* the local initiated, but the remote never responded.
*/
CloseInfo closeInfo = fatalCloseInfo;
if (closeInfo == null)
{
closeInfo = new CloseInfo(StatusCode.ABNORMAL, "Disconnected");
}
session.callApplicationOnClose(closeInfo);
}
else
{
session.callApplicationOnError(new WebSocketException("Shutdown"));
}
if (LOG.isDebugEnabled())
{
LOG.debug("{} disconnect()", policy.getBehavior());
}
flusher.terminate(new EOFException("Disconnected"));
EndPoint endPoint = getEndPoint();
// We need to gently close first, to allow
// SSL close alerts to be sent by Jetty
endPoint.shutdownOutput();
endPoint.close();
}
}
@Override
public void fillInterested()
{
stats.countFillInterestedEvents.incrementAndGet();
super.fillInterested();
}
@Override
public ByteBufferPool getBufferPool()
{
return bufferPool;
}
/**
* Get the list of extensions in use.
* <p>
* This list is negotiated during the WebSocket Upgrade Request/Response handshake.
*
* @return the list of negotiated extensions in use.
*/
public List<ExtensionConfig> getExtensions()
{
return extensions;
}
public Generator getGenerator()
{
return generator;
}
@Override
public String getId()
{
return id;
}
@Override
public long getIdleTimeout()
{
return getEndPoint().getIdleTimeout();
}
@Override
public long getMaxIdleTimeout()
{
return getEndPoint().getIdleTimeout();
}
public Parser getParser()
{
return parser;
}
@Override
public WebSocketPolicy getPolicy()
{
return this.policy;
}
@Override
public InetSocketAddress getLocalAddress()
{
return getEndPoint().getLocalAddress();
}
@Override
public InetSocketAddress getRemoteAddress()
{
return getEndPoint().getRemoteAddress();
}
public Scheduler getScheduler()
{
return scheduler;
}
@Deprecated()
public Stats getStats()
{
return stats;
}
@Override
public boolean isOpen()
{
return getEndPoint().isOpen();
}
@Override
public boolean isReading()
{
return readState.isReading();
}
@Override
public void onFillable()
{
if (LOG.isDebugEnabled())
LOG.debug("{} onFillable()", policy.getBehavior());
stats.countOnFillableEvents.incrementAndGet();
if (readState.getBuffer() != null)
throw new IllegalStateException();
ByteBuffer buffer = bufferPool.acquire(getInputBufferSize(), true);
onFillable(buffer);
}
private void onFillable(ByteBuffer buffer)
{
if (LOG.isDebugEnabled())
LOG.debug("{} onFillable(ByteBuffer): {}", policy.getBehavior(), buffer);
while (true)
{
ReadState.Action action = readState.getAction(buffer);
if (LOG.isDebugEnabled())
LOG.debug("ReadState Action: {}", action);
switch (action)
{
case PARSE:
try
{
parser.parseSingleFrame(buffer);
}
catch (Throwable t)
{
close(t);
readState.discard();
}
break;
case FILL:
try
{
int filled = getEndPoint().fill(buffer);
if (filled < 0)
{
readState.eof();
break;
}
if (filled == 0)
{
// Done reading, wait for next onFillable
bufferPool.release(buffer);
fillInterested();
return;
}
bytesIn.add(filled);
if (LOG.isDebugEnabled())
LOG.debug("Filled {} bytes - {}", filled, BufferUtil.toDetailString(buffer));
}
catch (IOException e)
{
close(e);
readState.eof();
}
break;
case DISCARD:
if (LOG.isDebugEnabled())
LOG.debug("Discarded buffer - {}", BufferUtil.toDetailString(buffer));
BufferUtil.clear(buffer);
break;
case SUSPEND:
return;
case EOF:
bufferPool.release(buffer);
// Handle case where the remote connection was abruptly terminated without a close frame
CloseInfo close = new CloseInfo(StatusCode.SHUTDOWN);
close(close, new DisconnectCallback(this));
return;
default:
throw new IllegalStateException(action.name());
}
}
}
@Override
public void resume()
{
ByteBuffer resume = readState.resume();
if (resume != null)
getExecutor().execute(() -> onFillable(resume));
}
@Override
public SuspendToken suspend()
{
readState.suspending();
return this;
}
@Override
protected void onFillInterestedFailed(Throwable cause)
{
LOG.ignore(cause);
stats.countFillInterestedEvents.incrementAndGet();
super.onFillInterestedFailed(cause);
}
/**
* Extra bytes from the initial HTTP upgrade that need to
* be processed by the websocket parser before starting
* to read bytes from the connection
*
* @param initialBuffer the bytes of unconsumed content encountered during upgrade
*/
protected void setInitialBuffer(ByteBuffer initialBuffer)
{
if (LOG.isDebugEnabled())
LOG.debug("Set initial buffer - {}", BufferUtil.toDetailString(initialBuffer));
this.initialBuffer = initialBuffer;
}
/**
* Event for no activity on connection (read or write)
*
* @return true to signal that the endpoint must be closed, false to keep the endpoint open
*/
@Override
protected boolean onReadTimeout(Throwable timeout)
{
close(new CloseException(StatusCode.SHUTDOWN, timeout));
return false; // let websocket perform close handshake
}
/**
* Frame from API, User, or Internal implementation destined for network.
*/
@Override
public void outgoingFrame(Frame frame, WriteCallback callback, BatchMode batchMode)
{
if (LOG.isDebugEnabled())
{
LOG.debug("outgoingFrame({}, {})", frame, callback);
}
if (flusher.enqueue(frame, callback, batchMode))
{
flusher.iterate();
}
}
/**
* Get the list of extensions in use.
* <p>
* This list is negotiated during the WebSocket Upgrade Request/Response handshake.
*
* @param extensions the list of negotiated extensions in use.
*/
public void setExtensions(List<ExtensionConfig> extensions)
{
this.extensions = extensions;
}
@Override
public void setInputBufferSize(int inputBufferSize)
{
if (inputBufferSize < MIN_BUFFER_SIZE)
{
throw new IllegalArgumentException("Cannot have buffer size less than " + MIN_BUFFER_SIZE);
}
super.setInputBufferSize(inputBufferSize);
}
@Override
public void setMaxIdleTimeout(long ms)
{
getEndPoint().setIdleTimeout(ms);
}
@Override
public String dumpSelf()
{
return String.format("%s@%x", this.getClass().getSimpleName(), hashCode());
}
public void dump(Appendable out, String indent) throws IOException
{
EndPoint endp = getEndPoint();
Object endpRef = endp.toString();
if (endp instanceof AbstractEndPoint)
{
endpRef = ((AbstractEndPoint)endp).toEndPointString();
}
Dumpable.dumpObjects(out, indent, this, endpRef, flusher, generator, parser);
}
@Override
public String toConnectionString()
{
return String.format("%s@%x[s=%s,f=%s,g=%s,p=%s]",
getClass().getSimpleName(),
hashCode(),
connectionState,
flusher, generator, parser);
}
/**
* Extra bytes from the initial HTTP upgrade that need to
* be processed by the websocket parser before starting
* to read bytes from the connection
*/
@Override
public void onUpgradeTo(ByteBuffer buffer)
{
if (LOG.isDebugEnabled())
LOG.debug("onUpgradeTo({})", BufferUtil.toDetailString(buffer));
setInitialBuffer(buffer);
}
@Override
public void setNextIncomingFrames(IncomingFrames incoming)
{
getParser().setIncomingFramesHandler(incoming);
}
/**
* @return the number of WebSocket frames received over this connection
*/
@Override
public long getMessagesIn()
{
return parser.getMessagesIn();
}
/**
* @return the number of WebSocket frames sent over this connection
*/
@Override
public long getMessagesOut()
{
return flusher.getMessagesOut();
}
/**
* @return the number of bytes received over this connection
*/
@Override
public long getBytesIn()
{
return bytesIn.longValue();
}
/**
* @return the number of bytes frames sent over this connection
*/
@Override
public long getBytesOut()
{
return flusher.getBytesOut();
}
}