-
-
Notifications
You must be signed in to change notification settings - Fork 15.8k
/
WebSocketHandshakeHandOverTest.java
326 lines (292 loc) · 13.9 KB
/
WebSocketHandshakeHandOverTest.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
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you 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.netty.handler.codec.http.websocketx;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler.ClientHandshakeStateEvent;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.ServerHandshakeStateEvent;
import org.junit.Before;
import org.junit.Test;
import java.net.URI;
import java.util.List;
import static org.junit.Assert.*;
public class WebSocketHandshakeHandOverTest {
private boolean serverReceivedHandshake;
private WebSocketServerProtocolHandler.HandshakeComplete serverHandshakeComplete;
private boolean clientReceivedHandshake;
private boolean clientReceivedMessage;
private boolean serverReceivedCloseHandshake;
private boolean clientForceClosed;
private boolean clientHandshakeTimeout;
private final class CloseNoOpServerProtocolHandler extends WebSocketServerProtocolHandler {
CloseNoOpServerProtocolHandler(String websocketPath) {
super(WebSocketServerProtocolConfig.newBuilder()
.websocketPath(websocketPath)
.allowExtensions(false)
.sendCloseFrame(null)
.build());
}
@Override
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
if (frame instanceof CloseWebSocketFrame) {
serverReceivedCloseHandshake = true;
return;
}
super.decode(ctx, frame, out);
}
}
@Before
public void setUp() {
serverReceivedHandshake = false;
serverHandshakeComplete = null;
clientReceivedHandshake = false;
clientReceivedMessage = false;
serverReceivedCloseHandshake = false;
clientForceClosed = false;
clientHandshakeTimeout = false;
}
@Test
public void testHandover() throws Exception {
EmbeddedChannel serverChannel = createServerChannel(new SimpleChannelInboundHandler<Object>() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt == ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
serverReceivedHandshake = true;
// immediately send a message to the client on connect
ctx.writeAndFlush(new TextWebSocketFrame("abc"));
} else if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
serverHandshakeComplete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
}
});
EmbeddedChannel clientChannel = createClientChannel(new SimpleChannelInboundHandler<Object>() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt == ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) {
clientReceivedHandshake = true;
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof TextWebSocketFrame) {
clientReceivedMessage = true;
}
}
});
// Transfer the handshake from the client to the server
transferAllDataWithMerge(clientChannel, serverChannel);
assertTrue(serverReceivedHandshake);
assertNotNull(serverHandshakeComplete);
assertEquals("/test", serverHandshakeComplete.requestUri());
assertEquals(7, serverHandshakeComplete.requestHeaders().size());
assertEquals("test-proto-2", serverHandshakeComplete.selectedSubprotocol());
// Transfer the handshake response and the websocket message to the client
transferAllDataWithMerge(serverChannel, clientChannel);
assertTrue(clientReceivedHandshake);
assertTrue(clientReceivedMessage);
}
@Test(expected = WebSocketHandshakeException.class)
public void testClientHandshakeTimeout() throws Exception {
EmbeddedChannel serverChannel = createServerChannel(new SimpleChannelInboundHandler<Object>() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt == ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
serverReceivedHandshake = true;
// immediately send a message to the client on connect
ctx.writeAndFlush(new TextWebSocketFrame("abc"));
} else if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
serverHandshakeComplete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
}
});
EmbeddedChannel clientChannel = createClientChannel(new SimpleChannelInboundHandler<Object>() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt == ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) {
clientReceivedHandshake = true;
} else if (evt == ClientHandshakeStateEvent.HANDSHAKE_TIMEOUT) {
clientHandshakeTimeout = true;
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof TextWebSocketFrame) {
clientReceivedMessage = true;
}
}
}, 100);
// Client send the handshake request to server
transferAllDataWithMerge(clientChannel, serverChannel);
// Server do not send the response back
// transferAllDataWithMerge(serverChannel, clientChannel);
WebSocketClientProtocolHandshakeHandler handshakeHandler =
(WebSocketClientProtocolHandshakeHandler) clientChannel
.pipeline().get(WebSocketClientProtocolHandshakeHandler.class.getName());
while (!handshakeHandler.getHandshakeFuture().isDone()) {
Thread.sleep(10);
// We need to run all pending tasks as the handshake timeout is scheduled on the EventLoop.
clientChannel.runScheduledPendingTasks();
}
assertTrue(clientHandshakeTimeout);
assertFalse(clientReceivedHandshake);
assertFalse(clientReceivedMessage);
// Should throw WebSocketHandshakeException
try {
handshakeHandler.getHandshakeFuture().syncUninterruptibly();
} finally {
serverChannel.finishAndReleaseAll();
}
}
@Test(timeout = 10000)
public void testClientHandshakerForceClose() throws Exception {
final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(
new URI("ws://localhost:1234/test"), WebSocketVersion.V13, null, true,
EmptyHttpHeaders.INSTANCE, Integer.MAX_VALUE, true, false, 20);
EmbeddedChannel serverChannel = createServerChannel(
new CloseNoOpServerProtocolHandler("/test"),
new SimpleChannelInboundHandler<Object>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
}
});
EmbeddedChannel clientChannel = createClientChannel(handshaker, new SimpleChannelInboundHandler<Object>() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt == ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) {
ctx.channel().closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
clientForceClosed = true;
}
});
handshaker.close(ctx.channel(), new CloseWebSocketFrame());
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
}
});
// Transfer the handshake from the client to the server
transferAllDataWithMerge(clientChannel, serverChannel);
// Transfer the handshake from the server to client
transferAllDataWithMerge(serverChannel, clientChannel);
// Transfer closing handshake
transferAllDataWithMerge(clientChannel, serverChannel);
assertTrue(serverReceivedCloseHandshake);
// Should not be closed yet as we disabled closing the connection on the server
assertFalse(clientForceClosed);
while (!clientForceClosed) {
Thread.sleep(10);
// We need to run all pending tasks as the force close timeout is scheduled on the EventLoop.
clientChannel.runPendingTasks();
}
// clientForceClosed would be set to TRUE after any close,
// so check here that force close timeout was actually fired
assertTrue(handshaker.isForceCloseComplete());
// Both should be empty
assertFalse(serverChannel.finishAndReleaseAll());
assertFalse(clientChannel.finishAndReleaseAll());
}
/**
* Transfers all pending data from the source channel into the destination channel.<br>
* Merges all data into a single buffer before transmission into the destination.
* @param srcChannel The source channel
* @param dstChannel The destination channel
*/
private static void transferAllDataWithMerge(EmbeddedChannel srcChannel, EmbeddedChannel dstChannel) {
ByteBuf mergedBuffer = null;
for (;;) {
Object srcData = srcChannel.readOutbound();
if (srcData != null) {
assertTrue(srcData instanceof ByteBuf);
ByteBuf srcBuf = (ByteBuf) srcData;
try {
if (mergedBuffer == null) {
mergedBuffer = Unpooled.buffer();
}
mergedBuffer.writeBytes(srcBuf);
} finally {
srcBuf.release();
}
} else {
break;
}
}
if (mergedBuffer != null) {
dstChannel.writeInbound(mergedBuffer);
}
}
private static EmbeddedChannel createClientChannel(ChannelHandler handler) throws Exception {
return createClientChannel(handler, WebSocketClientProtocolConfig.newBuilder()
.webSocketUri("ws://localhost:1234/test")
.subprotocol("test-proto-2")
.build());
}
private static EmbeddedChannel createClientChannel(ChannelHandler handler, long timeoutMillis) throws Exception {
return createClientChannel(handler, WebSocketClientProtocolConfig.newBuilder()
.webSocketUri("ws://localhost:1234/test")
.subprotocol("test-proto-2")
.handshakeTimeoutMillis(timeoutMillis)
.build());
}
private static EmbeddedChannel createClientChannel(ChannelHandler handler, WebSocketClientProtocolConfig config) {
return new EmbeddedChannel(
new HttpClientCodec(),
new HttpObjectAggregator(8192),
new WebSocketClientProtocolHandler(config),
handler);
}
private static EmbeddedChannel createClientChannel(WebSocketClientHandshaker handshaker,
ChannelHandler handler) throws Exception {
return new EmbeddedChannel(
new HttpClientCodec(),
new HttpObjectAggregator(8192),
// Note that we're switching off close frames handling on purpose to test forced close on timeout.
new WebSocketClientProtocolHandler(handshaker, false, false),
handler);
}
private static EmbeddedChannel createServerChannel(ChannelHandler handler) {
return new EmbeddedChannel(
new HttpServerCodec(),
new HttpObjectAggregator(8192),
new WebSocketServerProtocolHandler("/test", "test-proto-1, test-proto-2", false),
handler);
}
private static EmbeddedChannel createServerChannel(WebSocketServerProtocolHandler webSocketHandler,
ChannelHandler handler) {
return new EmbeddedChannel(
new HttpServerCodec(),
new HttpObjectAggregator(8192),
webSocketHandler,
handler);
}
}