summaryrefslogtreecommitdiffstats
path: root/net/websockets/websocket_unittest.cc
blob: 8c412d90d0eea5d983beaa52bd2772635f84e828 (plain)
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
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>
#include <vector>

#include "base/callback.h"
#include "net/base/completion_callback.h"
#include "net/base/io_buffer.h"
#include "net/base/mock_host_resolver.h"
#include "net/base/test_completion_callback.h"
#include "net/socket/socket_test_util.h"
#include "net/url_request/url_request_test_util.h"
#include "net/websockets/websocket.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/platform_test.h"

struct WebSocketEvent {
  enum EventType {
    EVENT_OPEN, EVENT_MESSAGE, EVENT_ERROR, EVENT_CLOSE,
  };

  WebSocketEvent(EventType type, net::WebSocket* websocket,
                 const std::string& websocket_msg, bool websocket_flag)
      : event_type(type), socket(websocket), msg(websocket_msg),
        flag(websocket_flag) {}

  EventType event_type;
  net::WebSocket* socket;
  std::string msg;
  bool flag;
};

class WebSocketEventRecorder : public net::WebSocketDelegate {
 public:
  explicit WebSocketEventRecorder(net::CompletionCallback* callback)
      : onopen_(NULL),
        onmessage_(NULL),
        onerror_(NULL),
        onclose_(NULL),
        callback_(callback) {}
  virtual ~WebSocketEventRecorder() {
    delete onopen_;
    delete onmessage_;
    delete onerror_;
    delete onclose_;
  }

  void SetOnOpen(Callback1<WebSocketEvent*>::Type* callback) {
    onopen_ = callback;
  }
  void SetOnMessage(Callback1<WebSocketEvent*>::Type* callback) {
    onmessage_ = callback;
  }
  void SetOnClose(Callback1<WebSocketEvent*>::Type* callback) {
    onclose_ = callback;
  }

  virtual void OnOpen(net::WebSocket* socket) {
    events_.push_back(
        WebSocketEvent(WebSocketEvent::EVENT_OPEN, socket,
                       std::string(), false));
    if (onopen_)
      onopen_->Run(&events_.back());
  }

  virtual void OnMessage(net::WebSocket* socket, const std::string& msg) {
    events_.push_back(
        WebSocketEvent(WebSocketEvent::EVENT_MESSAGE, socket, msg, false));
    if (onmessage_)
      onmessage_->Run(&events_.back());
  }
  virtual void OnError(net::WebSocket* socket) {
    events_.push_back(
        WebSocketEvent(WebSocketEvent::EVENT_ERROR, socket,
                       std::string(), false));
    if (onerror_)
      onerror_->Run(&events_.back());
  }
  virtual void OnClose(net::WebSocket* socket, bool was_clean) {
    events_.push_back(
        WebSocketEvent(WebSocketEvent::EVENT_CLOSE, socket,
                       std::string(), was_clean));
    if (onclose_)
      onclose_->Run(&events_.back());
    if (callback_)
      callback_->Run(net::OK);
  }

  void DoClose(WebSocketEvent* event) {
    event->socket->Close();
  }

  const std::vector<WebSocketEvent>& GetSeenEvents() const {
    return events_;
  }

 private:
  std::vector<WebSocketEvent> events_;
  Callback1<WebSocketEvent*>::Type* onopen_;
  Callback1<WebSocketEvent*>::Type* onmessage_;
  Callback1<WebSocketEvent*>::Type* onerror_;
  Callback1<WebSocketEvent*>::Type* onclose_;
  net::CompletionCallback* callback_;

  DISALLOW_COPY_AND_ASSIGN(WebSocketEventRecorder);
};

namespace net {

class WebSocketTest : public PlatformTest {
 protected:
  void InitReadBuf(WebSocket* websocket) {
    // Set up |current_read_buf_|.
    websocket->current_read_buf_ = new GrowableIOBuffer();
  }
  void SetReadConsumed(WebSocket* websocket, int consumed) {
    websocket->read_consumed_len_ = consumed;
  }
  void AddToReadBuf(WebSocket* websocket, const char* data, int len) {
    websocket->AddToReadBuffer(data, len);
  }

  void TestProcessFrameData(WebSocket* websocket,
                            const char* expected_remaining_data,
                            int expected_remaining_len) {
    websocket->ProcessFrameData();

    const char* actual_remaining_data =
        websocket->current_read_buf_->StartOfBuffer()
        + websocket->read_consumed_len_;
    int actual_remaining_len =
        websocket->current_read_buf_->offset() - websocket->read_consumed_len_;

    EXPECT_EQ(expected_remaining_len, actual_remaining_len);
    EXPECT_TRUE(!memcmp(expected_remaining_data, actual_remaining_data,
                        expected_remaining_len));
  }
};

TEST_F(WebSocketTest, Connect) {
  MockClientSocketFactory mock_socket_factory;
  MockRead data_reads[] = {
    MockRead("HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
             "Upgrade: WebSocket\r\n"
             "Connection: Upgrade\r\n"
             "WebSocket-Origin: http://example.com\r\n"
             "WebSocket-Location: ws://example.com/demo\r\n"
             "WebSocket-Protocol: sample\r\n"
             "\r\n"),
    // Server doesn't close the connection after handshake.
    MockRead(true, ERR_IO_PENDING),
  };
  MockWrite data_writes[] = {
    MockWrite("GET /demo HTTP/1.1\r\n"
              "Upgrade: WebSocket\r\n"
              "Connection: Upgrade\r\n"
              "Host: example.com\r\n"
              "Origin: http://example.com\r\n"
              "WebSocket-Protocol: sample\r\n"
              "\r\n"),
  };
  StaticSocketDataProvider data(data_reads, arraysize(data_reads),
                                data_writes, arraysize(data_writes));
  mock_socket_factory.AddSocketDataProvider(&data);
  MockHostResolver host_resolver;

  WebSocket::Request* request(
      new WebSocket::Request(GURL("ws://example.com/demo"),
                             "sample",
                             "http://example.com",
                             "ws://example.com/demo",
                             WebSocket::DRAFT75,
                             new TestURLRequestContext()));
  request->SetHostResolver(&host_resolver);
  request->SetClientSocketFactory(&mock_socket_factory);

  TestCompletionCallback callback;

  scoped_ptr<WebSocketEventRecorder> delegate(
      new WebSocketEventRecorder(&callback));
  delegate->SetOnOpen(NewCallback(delegate.get(),
                                  &WebSocketEventRecorder::DoClose));

  scoped_refptr<WebSocket> websocket(
      new WebSocket(request, delegate.get()));

  EXPECT_EQ(WebSocket::INITIALIZED, websocket->ready_state());
  websocket->Connect();

  callback.WaitForResult();

  const std::vector<WebSocketEvent>& events = delegate->GetSeenEvents();
  EXPECT_EQ(2U, events.size());

  EXPECT_EQ(WebSocketEvent::EVENT_OPEN, events[0].event_type);
  EXPECT_EQ(WebSocketEvent::EVENT_CLOSE, events[1].event_type);
}

TEST_F(WebSocketTest, ServerSentData) {
  MockClientSocketFactory mock_socket_factory;
  static const char kMessage[] = "Hello";
  static const char kFrame[] = "\x00Hello\xff";
  static const int kFrameLen = sizeof(kFrame) - 1;
  MockRead data_reads[] = {
    MockRead("HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
             "Upgrade: WebSocket\r\n"
             "Connection: Upgrade\r\n"
             "WebSocket-Origin: http://example.com\r\n"
             "WebSocket-Location: ws://example.com/demo\r\n"
             "WebSocket-Protocol: sample\r\n"
             "\r\n"),
    MockRead(true, kFrame, kFrameLen),
    // Server doesn't close the connection after handshake.
    MockRead(true, ERR_IO_PENDING),
  };
  MockWrite data_writes[] = {
    MockWrite("GET /demo HTTP/1.1\r\n"
              "Upgrade: WebSocket\r\n"
              "Connection: Upgrade\r\n"
              "Host: example.com\r\n"
              "Origin: http://example.com\r\n"
              "WebSocket-Protocol: sample\r\n"
              "\r\n"),
  };
  StaticSocketDataProvider data(data_reads, arraysize(data_reads),
                                data_writes, arraysize(data_writes));
  mock_socket_factory.AddSocketDataProvider(&data);
  MockHostResolver host_resolver;

  WebSocket::Request* request(
      new WebSocket::Request(GURL("ws://example.com/demo"),
                             "sample",
                             "http://example.com",
                             "ws://example.com/demo",
                             WebSocket::DRAFT75,
                             new TestURLRequestContext()));
  request->SetHostResolver(&host_resolver);
  request->SetClientSocketFactory(&mock_socket_factory);

  TestCompletionCallback callback;

  scoped_ptr<WebSocketEventRecorder> delegate(
      new WebSocketEventRecorder(&callback));
  delegate->SetOnMessage(NewCallback(delegate.get(),
                                     &WebSocketEventRecorder::DoClose));

  scoped_refptr<WebSocket> websocket(
      new WebSocket(request, delegate.get()));

  EXPECT_EQ(WebSocket::INITIALIZED, websocket->ready_state());
  websocket->Connect();

  callback.WaitForResult();

  const std::vector<WebSocketEvent>& events = delegate->GetSeenEvents();
  EXPECT_EQ(3U, events.size());

  EXPECT_EQ(WebSocketEvent::EVENT_OPEN, events[0].event_type);
  EXPECT_EQ(WebSocketEvent::EVENT_MESSAGE, events[1].event_type);
  EXPECT_EQ(kMessage, events[1].msg);
  EXPECT_EQ(WebSocketEvent::EVENT_CLOSE, events[2].event_type);
}

TEST_F(WebSocketTest, ProcessFrameDataForLengthCalculation) {
  WebSocket::Request* request(
      new WebSocket::Request(GURL("ws://example.com/demo"),
                             "sample",
                             "http://example.com",
                             "ws://example.com/demo",
                             WebSocket::DRAFT75,
                             new TestURLRequestContext()));
  TestCompletionCallback callback;
  scoped_ptr<WebSocketEventRecorder> delegate(
      new WebSocketEventRecorder(&callback));

  scoped_refptr<WebSocket> websocket(
      new WebSocket(request, delegate.get()));

  // Frame data: skip length 1 ('x'), and try to skip length 129
  // (1 * 128 + 1) bytes after \x81\x01, but buffer is too short to skip.
  static const char kTestLengthFrame[] =
      "\x80\x01x\x80\x81\x01\x01\x00unexpected data\xFF";
  const int kTestLengthFrameLength = sizeof(kTestLengthFrame) - 1;
  InitReadBuf(websocket.get());
  AddToReadBuf(websocket.get(), kTestLengthFrame, kTestLengthFrameLength);
  SetReadConsumed(websocket.get(), 0);

  static const char kExpectedRemainingFrame[] =
      "\x80\x81\x01\x01\x00unexpected data\xFF";
  const int kExpectedRemainingLength = sizeof(kExpectedRemainingFrame) - 1;
  TestProcessFrameData(websocket.get(),
                       kExpectedRemainingFrame, kExpectedRemainingLength);
  // No onmessage event expected.
  const std::vector<WebSocketEvent>& events = delegate->GetSeenEvents();
  EXPECT_EQ(1U, events.size());

  EXPECT_EQ(WebSocketEvent::EVENT_ERROR, events[0].event_type);

  websocket->DetachDelegate();
}

TEST_F(WebSocketTest, ProcessFrameDataForUnterminatedString) {
  WebSocket::Request* request(
      new WebSocket::Request(GURL("ws://example.com/demo"),
                             "sample",
                             "http://example.com",
                             "ws://example.com/demo",
                             WebSocket::DRAFT75,
                             new TestURLRequestContext()));
  TestCompletionCallback callback;
  scoped_ptr<WebSocketEventRecorder> delegate(
      new WebSocketEventRecorder(&callback));

  scoped_refptr<WebSocket> websocket(
      new WebSocket(request, delegate.get()));

  static const char kTestUnterminatedFrame[] =
      "\x00unterminated frame";
  const int kTestUnterminatedFrameLength = sizeof(kTestUnterminatedFrame) - 1;
  InitReadBuf(websocket.get());
  AddToReadBuf(websocket.get(), kTestUnterminatedFrame,
               kTestUnterminatedFrameLength);
  SetReadConsumed(websocket.get(), 0);
  TestProcessFrameData(websocket.get(),
                       kTestUnterminatedFrame, kTestUnterminatedFrameLength);
  {
    // No onmessage event expected.
    const std::vector<WebSocketEvent>& events = delegate->GetSeenEvents();
    EXPECT_EQ(0U, events.size());
  }

  static const char kTestTerminateFrame[] = " is terminated in next read\xff";
  const int kTestTerminateFrameLength = sizeof(kTestTerminateFrame) - 1;
  AddToReadBuf(websocket.get(), kTestTerminateFrame,
               kTestTerminateFrameLength);
  TestProcessFrameData(websocket.get(), "", 0);

  static const char kExpectedMsg[] =
      "unterminated frame is terminated in next read";
  {
    const std::vector<WebSocketEvent>& events = delegate->GetSeenEvents();
    EXPECT_EQ(1U, events.size());

    EXPECT_EQ(WebSocketEvent::EVENT_MESSAGE, events[0].event_type);
    EXPECT_EQ(kExpectedMsg, events[0].msg);
  }

  websocket->DetachDelegate();
}

}  // namespace net