-
Notifications
You must be signed in to change notification settings - Fork 974
/
WebSocketUtils.java
441 lines (412 loc) · 18.7 KB
/
WebSocketUtils.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
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.websockets.core;
import io.undertow.UndertowLogger;
import org.xnio.Buffers;
import org.xnio.ChannelExceptionHandler;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.IoUtils;
import io.undertow.connector.ByteBufferPool;
import io.undertow.connector.PooledByteBuffer;
import org.xnio.channels.StreamSinkChannel;
import org.xnio.channels.StreamSourceChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
/**
* Utility class which holds general useful utility methods which
* can be used within WebSocket implementations.
*
* @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a>
*/
public final class WebSocketUtils {
private static final String EMPTY = "";
/**
* Create a {@link ByteBuffer} which holds the UTF8 encoded bytes for the
* given {@link String}.
*
* @param utfString The {@link String} to convert
* @return buffer The {@link ByteBuffer} which was created
*/
public static ByteBuffer fromUtf8String(CharSequence utfString) {
if (utfString == null || utfString.length() == 0) {
return Buffers.EMPTY_BYTE_BUFFER;
} else {
return ByteBuffer.wrap(utfString.toString().getBytes(StandardCharsets.UTF_8));
}
}
public static String toUtf8String(ByteBuffer buffer) {
if (!buffer.hasRemaining()) {
return EMPTY;
}
if (buffer.hasArray()) {
return new String(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining(), StandardCharsets.UTF_8);
} else {
byte[] content = new byte[buffer.remaining()];
buffer.get(content);
return new String(content, StandardCharsets.UTF_8);
}
}
public static String toUtf8String(ByteBuffer... buffers) {
int size = 0;
for (ByteBuffer buf: buffers) {
size += buf.remaining();
}
if (size == 0) {
return EMPTY;
}
int index = 0;
byte[] bytes = new byte[size];
for (ByteBuffer buf: buffers) {
if (buf.hasArray()) {
int len = buf.remaining();
System.arraycopy(buf.array(), buf.arrayOffset() + buf.position(), bytes, index, len);
index += len;
} else {
int len = buf.remaining();
buf.get(bytes, index, len);
index += len;
}
}
return new String(bytes, StandardCharsets.UTF_8);
}
/**
* Transfer the data from the source to the sink using the given through buffer to pass data through.
*/
public static long transfer(final ReadableByteChannel source, final long count, final ByteBuffer throughBuffer, final WritableByteChannel sink) throws IOException {
long total = 0L;
while (total < count) {
throughBuffer.clear();
if (count - total < throughBuffer.remaining()) {
throughBuffer.limit((int) (count - total));
}
try {
long res = source.read(throughBuffer);
if (res <= 0) {
return total == 0L ? res : total;
}
} finally {
throughBuffer.flip();
}
while (throughBuffer.hasRemaining()) {
long res = sink.write(throughBuffer);
if (res <= 0) {
return total;
}
total += res;
}
}
return total;
}
/**
* Echo back the frame to the sender
*/
public static void echoFrame(final WebSocketChannel channel, final StreamSourceFrameChannel ws) throws IOException {
final WebSocketFrameType type;
switch (ws.getType()) {
case PONG:
// pong frames must be discarded
ws.close();
return;
case PING:
// if a ping is send the autobahn testsuite expects a PONG when echo back
type = WebSocketFrameType.PONG;
break;
default:
type = ws.getType();
break;
}
final StreamSinkFrameChannel sink = channel.send(type);
sink.setRsv(ws.getRsv());
initiateTransfer(ws, sink, new ChannelListener<StreamSourceFrameChannel>() {
@Override
public void handleEvent(StreamSourceFrameChannel streamSourceFrameChannel) {
IoUtils.safeClose(streamSourceFrameChannel);
}
}, new ChannelListener<StreamSinkFrameChannel>() {
@Override
public void handleEvent(StreamSinkFrameChannel streamSinkFrameChannel) {
try {
streamSinkFrameChannel.shutdownWrites();
} catch (IOException e) {
UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
IoUtils.safeClose(streamSinkFrameChannel, channel);
return;
}
try {
if (!streamSinkFrameChannel.flush()) {
streamSinkFrameChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener(
new ChannelListener<StreamSinkFrameChannel>() {
@Override
public void handleEvent(StreamSinkFrameChannel streamSinkFrameChannel) {
streamSinkFrameChannel.getWriteSetter().set(null);
IoUtils.safeClose(streamSinkFrameChannel);
if (type == WebSocketFrameType.CLOSE) {
IoUtils.safeClose(channel);
}
}
}, new ChannelExceptionHandler<StreamSinkFrameChannel>() {
@Override
public void handleException(StreamSinkFrameChannel streamSinkFrameChannel, IOException e) {
UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
IoUtils.safeClose(streamSinkFrameChannel, channel);
}
}
));
streamSinkFrameChannel.resumeWrites();
} else {
if (type == WebSocketFrameType.CLOSE) {
IoUtils.safeClose(channel);
}
streamSinkFrameChannel.getWriteSetter().set(null);
IoUtils.safeClose(streamSinkFrameChannel);
}
} catch (IOException e) {
UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
IoUtils.safeClose(streamSinkFrameChannel, channel);
}
}
}, new ChannelExceptionHandler<StreamSourceFrameChannel>() {
@Override
public void handleException(StreamSourceFrameChannel streamSourceFrameChannel, IOException e) {
UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
IoUtils.safeClose(streamSourceFrameChannel, channel);
}
}, new ChannelExceptionHandler<StreamSinkFrameChannel>() {
@Override
public void handleException(StreamSinkFrameChannel streamSinkFrameChannel, IOException e) {
UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
IoUtils.safeClose(streamSinkFrameChannel, channel);
}
}, channel.getBufferPool()
);
}
/**
* Initiate a low-copy transfer between two stream channels. The pool should be a direct buffer pool for best
* performance.
*
* @param source the source channel
* @param sink the target channel
* @param sourceListener the source listener to set and call when the transfer is complete, or {@code null} to clear the listener at that time
* @param sinkListener the target listener to set and call when the transfer is complete, or {@code null} to clear the listener at that time
* @param readExceptionHandler the read exception handler to call if an error occurs during a read operation
* @param writeExceptionHandler the write exception handler to call if an error occurs during a write operation
* @param pool the pool from which the transfer buffer should be allocated
*/
public static <I extends StreamSourceChannel, O extends StreamSinkChannel> void initiateTransfer(final I source, final O sink, final ChannelListener<? super I> sourceListener, final ChannelListener<? super O> sinkListener, final ChannelExceptionHandler<? super I> readExceptionHandler, final ChannelExceptionHandler<? super O> writeExceptionHandler, ByteBufferPool pool) {
if (pool == null) {
throw new IllegalArgumentException("pool is null");
}
final PooledByteBuffer allocated = pool.allocate();
boolean free = true;
try {
final ByteBuffer buffer = allocated.getBuffer();
buffer.clear();
long transferred;
do {
try {
transferred = source.transferTo(Long.MAX_VALUE, buffer, sink);
} catch (IOException e) {
ChannelListeners.invokeChannelExceptionHandler(source, readExceptionHandler, e);
return;
}
if (transferred == -1) {
source.suspendReads();
sink.suspendWrites();
ChannelListeners.invokeChannelListener(source, sourceListener);
ChannelListeners.invokeChannelListener(sink, sinkListener);
return;
}
while (buffer.hasRemaining()) {
final int res;
try {
res = sink.write(buffer);
} catch (IOException e) {
ChannelListeners.invokeChannelExceptionHandler(sink, writeExceptionHandler, e);
return;
}
if (res == 0) {
// write first listener
final TransferListener<I, O> listener = new TransferListener<>(allocated, source, sink, sourceListener, sinkListener, writeExceptionHandler, readExceptionHandler, 1);
source.suspendReads();
source.getReadSetter().set(listener);
sink.getWriteSetter().set(listener);
sink.resumeWrites();
free = false;
return;
} else if (res == -1) {
source.suspendReads();
sink.suspendWrites();
ChannelListeners.invokeChannelListener(source, sourceListener);
ChannelListeners.invokeChannelListener(sink, sinkListener);
return;
}
}
} while (transferred > 0L);
final TransferListener<I, O> listener = new TransferListener<>(allocated, source, sink, sourceListener, sinkListener, writeExceptionHandler, readExceptionHandler, 0);
sink.suspendWrites();
sink.getWriteSetter().set(listener);
source.getReadSetter().set(listener);
// read first listener
sink.suspendWrites();
source.resumeReads();
free = false;
} finally {
if (free) {
allocated.close();
}
}
}
static final class TransferListener<I extends StreamSourceChannel, O extends StreamSinkChannel> implements ChannelListener<Channel> {
private final PooledByteBuffer pooledBuffer;
private final I source;
private final O sink;
private final ChannelListener<? super I> sourceListener;
private final ChannelListener<? super O> sinkListener;
private final ChannelExceptionHandler<? super O> writeExceptionHandler;
private final ChannelExceptionHandler<? super I> readExceptionHandler;
private volatile int state;
TransferListener(final PooledByteBuffer pooledBuffer, final I source, final O sink, final ChannelListener<? super I> sourceListener, final ChannelListener<? super O> sinkListener, final ChannelExceptionHandler<? super O> writeExceptionHandler, final ChannelExceptionHandler<? super I> readExceptionHandler, final int state) {
this.pooledBuffer = pooledBuffer;
this.source = source;
this.sink = sink;
this.sourceListener = sourceListener;
this.sinkListener = sinkListener;
this.writeExceptionHandler = writeExceptionHandler;
this.readExceptionHandler = readExceptionHandler;
this.state = state;
}
@Override
public void handleEvent(final Channel channel) {
final ByteBuffer buffer = pooledBuffer.getBuffer();
int state = this.state;
long lres;
int ires;
switch (state) {
case 0: {
// read listener
for (; ; ) {
try {
lres = source.transferTo(Long.MAX_VALUE, buffer, sink);
} catch (IOException e) {
readFailed(e);
return;
}
if (lres == 0 && !buffer.hasRemaining()) {
return;
}
if (lres == -1) {
// possibly unexpected EOF
// it's OK; just be done
done();
return;
}
while (buffer.hasRemaining()) {
try {
ires = sink.write(buffer);
} catch (IOException e) {
writeFailed(e);
return;
}
if (ires == 0) {
this.state = 1;
source.suspendReads();
sink.resumeWrites();
return;
}
}
}
}
case 1: {
// write listener
for (; ; ) {
while (buffer.hasRemaining()) {
try {
ires = sink.write(buffer);
} catch (IOException e) {
writeFailed(e);
return;
}
if (ires == 0) {
return;
}
}
try {
lres = source.transferTo(Long.MAX_VALUE, buffer, sink);
} catch (IOException e) {
readFailed(e);
return;
}
if (lres == 0 && !buffer.hasRemaining()) {
this.state = 0;
sink.suspendWrites();
source.resumeReads();
return;
}
if (lres == -1) {
done();
return;
}
}
}
}
}
private void writeFailed(final IOException e) {
try {
source.suspendReads();
sink.suspendWrites();
ChannelListeners.invokeChannelExceptionHandler(sink, writeExceptionHandler, e);
} finally {
pooledBuffer.close();
}
}
private void readFailed(final IOException e) {
try {
source.suspendReads();
sink.suspendWrites();
ChannelListeners.invokeChannelExceptionHandler(source, readExceptionHandler, e);
} finally {
pooledBuffer.close();
}
}
private void done() {
try {
final ChannelListener<? super I> sourceListener = this.sourceListener;
final ChannelListener<? super O> sinkListener = this.sinkListener;
final I source = this.source;
final O sink = this.sink;
source.suspendReads();
sink.suspendWrites();
ChannelListeners.invokeChannelListener(source, sourceListener);
ChannelListeners.invokeChannelListener(sink, sinkListener);
} finally {
pooledBuffer.close();
}
}
public String toString() {
return "Transfer channel listener (" + source + " to " + sink + ") -> (" + sourceListener + " and " + sinkListener + ')';
}
}
private WebSocketUtils() {
// utility class
}
}