1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.http.websocketx;
17
18 import io.netty.handler.codec.http.DefaultFullHttpResponse;
19 import io.netty.handler.codec.http.FullHttpRequest;
20 import io.netty.handler.codec.http.FullHttpResponse;
21 import io.netty.handler.codec.http.HttpHeaders;
22 import io.netty.handler.codec.http.HttpHeaders.Names;
23 import io.netty.handler.codec.http.HttpResponseStatus;
24 import io.netty.util.CharsetUtil;
25
26 import static io.netty.handler.codec.http.HttpHeaders.Values.*;
27 import static io.netty.handler.codec.http.HttpVersion.*;
28
29
30
31
32
33
34
35 public class WebSocketServerHandshaker13 extends WebSocketServerHandshaker {
36
37 public static final String WEBSOCKET_13_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
38
39 private final boolean allowExtensions;
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55 public WebSocketServerHandshaker13(
56 String webSocketURL, String subprotocols, boolean allowExtensions, int maxFramePayloadLength) {
57 super(WebSocketVersion.V13, webSocketURL, subprotocols, maxFramePayloadLength);
58 this.allowExtensions = allowExtensions;
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 @Override
96 protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
97 FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);
98 if (headers != null) {
99 res.headers().add(headers);
100 }
101
102 String key = req.headers().get(Names.SEC_WEBSOCKET_KEY);
103 if (key == null) {
104 throw new WebSocketHandshakeException("not a WebSocket request: missing key");
105 }
106 String acceptSeed = key + WEBSOCKET_13_ACCEPT_GUID;
107 byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
108 String accept = WebSocketUtil.base64(sha1);
109
110 if (logger.isDebugEnabled()) {
111 logger.debug("WebSocket version 13 server handshake key: {}, response: {}", key, accept);
112 }
113
114 res.headers().add(Names.UPGRADE, WEBSOCKET.toLowerCase());
115 res.headers().add(Names.CONNECTION, Names.UPGRADE);
116 res.headers().add(Names.SEC_WEBSOCKET_ACCEPT, accept);
117 String subprotocols = req.headers().get(Names.SEC_WEBSOCKET_PROTOCOL);
118 if (subprotocols != null) {
119 String selectedSubprotocol = selectSubprotocol(subprotocols);
120 if (selectedSubprotocol == null) {
121 if (logger.isDebugEnabled()) {
122 logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
123 }
124 } else {
125 res.headers().add(Names.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
126 }
127 }
128 return res;
129 }
130
131 @Override
132 protected WebSocketFrameDecoder newWebsocketDecoder() {
133 return new WebSocket13FrameDecoder(true, allowExtensions, maxFramePayloadLength());
134 }
135
136 @Override
137 protected WebSocketFrameEncoder newWebSocketEncoder() {
138 return new WebSocket13FrameEncoder(false);
139 }
140 }