1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/websockets/websocket_frame.h"
6
7#include <algorithm>
8#include <vector>
9
10#include "base/basictypes.h"
11#include "base/memory/aligned_memory.h"
12#include "net/base/net_errors.h"
13#include "testing/gtest/include/gtest/gtest.h"
14
15namespace net {
16
17namespace {
18
19TEST(WebSocketFrameHeaderTest, FrameLengths) {
20  struct TestCase {
21    const char* frame_header;
22    size_t frame_header_length;
23    uint64 frame_length;
24  };
25  static const TestCase kTests[] = {
26    { "\x81\x00", 2, GG_UINT64_C(0) },
27    { "\x81\x7D", 2, GG_UINT64_C(125) },
28    { "\x81\x7E\x00\x7E", 4, GG_UINT64_C(126) },
29    { "\x81\x7E\xFF\xFF", 4, GG_UINT64_C(0xFFFF) },
30    { "\x81\x7F\x00\x00\x00\x00\x00\x01\x00\x00", 10, GG_UINT64_C(0x10000) },
31    { "\x81\x7F\x7F\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 10,
32      GG_UINT64_C(0x7FFFFFFFFFFFFFFF) }
33  };
34  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
35
36  for (int i = 0; i < kNumTests; ++i) {
37    WebSocketFrameHeader header(WebSocketFrameHeader::kOpCodeText);
38    header.final = true;
39    header.payload_length = kTests[i].frame_length;
40
41    std::vector<char> expected_output(
42        kTests[i].frame_header,
43        kTests[i].frame_header + kTests[i].frame_header_length);
44    std::vector<char> output(expected_output.size());
45    EXPECT_EQ(static_cast<int>(expected_output.size()),
46              WriteWebSocketFrameHeader(
47                  header, NULL, &output.front(), output.size()));
48    EXPECT_EQ(expected_output, output);
49  }
50}
51
52TEST(WebSocketFrameHeaderTest, FrameLengthsWithMasking) {
53  static const char kMaskingKey[] = "\xDE\xAD\xBE\xEF";
54  COMPILE_ASSERT(ARRAYSIZE_UNSAFE(kMaskingKey) - 1 ==
55                     WebSocketFrameHeader::kMaskingKeyLength,
56                 incorrect_masking_key_size);
57
58  struct TestCase {
59    const char* frame_header;
60    size_t frame_header_length;
61    uint64 frame_length;
62  };
63  static const TestCase kTests[] = {
64    { "\x81\x80\xDE\xAD\xBE\xEF", 6, GG_UINT64_C(0) },
65    { "\x81\xFD\xDE\xAD\xBE\xEF", 6, GG_UINT64_C(125) },
66    { "\x81\xFE\x00\x7E\xDE\xAD\xBE\xEF", 8, GG_UINT64_C(126) },
67    { "\x81\xFE\xFF\xFF\xDE\xAD\xBE\xEF", 8, GG_UINT64_C(0xFFFF) },
68    { "\x81\xFF\x00\x00\x00\x00\x00\x01\x00\x00\xDE\xAD\xBE\xEF", 14,
69      GG_UINT64_C(0x10000) },
70    { "\x81\xFF\x7F\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xDE\xAD\xBE\xEF", 14,
71      GG_UINT64_C(0x7FFFFFFFFFFFFFFF) }
72  };
73  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
74
75  WebSocketMaskingKey masking_key;
76  std::copy(kMaskingKey,
77            kMaskingKey + WebSocketFrameHeader::kMaskingKeyLength,
78            masking_key.key);
79
80  for (int i = 0; i < kNumTests; ++i) {
81    WebSocketFrameHeader header(WebSocketFrameHeader::kOpCodeText);
82    header.final = true;
83    header.masked = true;
84    header.payload_length = kTests[i].frame_length;
85
86    std::vector<char> expected_output(
87        kTests[i].frame_header,
88        kTests[i].frame_header + kTests[i].frame_header_length);
89    std::vector<char> output(expected_output.size());
90    EXPECT_EQ(static_cast<int>(expected_output.size()),
91              WriteWebSocketFrameHeader(
92                  header, &masking_key, &output.front(), output.size()));
93    EXPECT_EQ(expected_output, output);
94  }
95}
96
97TEST(WebSocketFrameHeaderTest, FrameOpCodes) {
98  struct TestCase {
99    const char* frame_header;
100    size_t frame_header_length;
101    WebSocketFrameHeader::OpCode opcode;
102  };
103  static const TestCase kTests[] = {
104    { "\x80\x00", 2, WebSocketFrameHeader::kOpCodeContinuation },
105    { "\x81\x00", 2, WebSocketFrameHeader::kOpCodeText },
106    { "\x82\x00", 2, WebSocketFrameHeader::kOpCodeBinary },
107    { "\x88\x00", 2, WebSocketFrameHeader::kOpCodeClose },
108    { "\x89\x00", 2, WebSocketFrameHeader::kOpCodePing },
109    { "\x8A\x00", 2, WebSocketFrameHeader::kOpCodePong },
110    // These are undefined opcodes, but the builder should accept them anyway.
111    { "\x83\x00", 2, 0x3 },
112    { "\x84\x00", 2, 0x4 },
113    { "\x85\x00", 2, 0x5 },
114    { "\x86\x00", 2, 0x6 },
115    { "\x87\x00", 2, 0x7 },
116    { "\x8B\x00", 2, 0xB },
117    { "\x8C\x00", 2, 0xC },
118    { "\x8D\x00", 2, 0xD },
119    { "\x8E\x00", 2, 0xE },
120    { "\x8F\x00", 2, 0xF }
121  };
122  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
123
124  for (int i = 0; i < kNumTests; ++i) {
125    WebSocketFrameHeader header(kTests[i].opcode);
126    header.final = true;
127    header.payload_length = 0;
128
129    std::vector<char> expected_output(
130        kTests[i].frame_header,
131        kTests[i].frame_header + kTests[i].frame_header_length);
132    std::vector<char> output(expected_output.size());
133    EXPECT_EQ(static_cast<int>(expected_output.size()),
134              WriteWebSocketFrameHeader(
135                  header, NULL, &output.front(), output.size()));
136    EXPECT_EQ(expected_output, output);
137  }
138}
139
140TEST(WebSocketFrameHeaderTest, FinalBitAndReservedBits) {
141  struct TestCase {
142    const char* frame_header;
143    size_t frame_header_length;
144    bool final;
145    bool reserved1;
146    bool reserved2;
147    bool reserved3;
148  };
149  static const TestCase kTests[] = {
150    { "\x81\x00", 2, true, false, false, false },
151    { "\x01\x00", 2, false, false, false, false },
152    { "\xC1\x00", 2, true, true, false, false },
153    { "\xA1\x00", 2, true, false, true, false },
154    { "\x91\x00", 2, true, false, false, true },
155    { "\x71\x00", 2, false, true, true, true },
156    { "\xF1\x00", 2, true, true, true, true }
157  };
158  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
159
160  for (int i = 0; i < kNumTests; ++i) {
161    WebSocketFrameHeader header(WebSocketFrameHeader::kOpCodeText);
162    header.final = kTests[i].final;
163    header.reserved1 = kTests[i].reserved1;
164    header.reserved2 = kTests[i].reserved2;
165    header.reserved3 = kTests[i].reserved3;
166    header.payload_length = 0;
167
168    std::vector<char> expected_output(
169        kTests[i].frame_header,
170        kTests[i].frame_header + kTests[i].frame_header_length);
171    std::vector<char> output(expected_output.size());
172    EXPECT_EQ(static_cast<int>(expected_output.size()),
173              WriteWebSocketFrameHeader(
174                  header, NULL, &output.front(), output.size()));
175    EXPECT_EQ(expected_output, output);
176  }
177}
178
179TEST(WebSocketFrameHeaderTest, InsufficientBufferSize) {
180  struct TestCase {
181    uint64 payload_length;
182    bool masked;
183    size_t expected_header_size;
184  };
185  static const TestCase kTests[] = {
186    { GG_UINT64_C(0), false, 2u },
187    { GG_UINT64_C(125), false, 2u },
188    { GG_UINT64_C(126), false, 4u },
189    { GG_UINT64_C(0xFFFF), false, 4u },
190    { GG_UINT64_C(0x10000), false, 10u },
191    { GG_UINT64_C(0x7FFFFFFFFFFFFFFF), false, 10u },
192    { GG_UINT64_C(0), true, 6u },
193    { GG_UINT64_C(125), true, 6u },
194    { GG_UINT64_C(126), true, 8u },
195    { GG_UINT64_C(0xFFFF), true, 8u },
196    { GG_UINT64_C(0x10000), true, 14u },
197    { GG_UINT64_C(0x7FFFFFFFFFFFFFFF), true, 14u }
198  };
199  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
200
201  for (int i = 0; i < kNumTests; ++i) {
202    WebSocketFrameHeader header(WebSocketFrameHeader::kOpCodeText);
203    header.final = true;
204    header.opcode = WebSocketFrameHeader::kOpCodeText;
205    header.masked = kTests[i].masked;
206    header.payload_length = kTests[i].payload_length;
207
208    char dummy_buffer[14];
209    // Set an insufficient size to |buffer_size|.
210    EXPECT_EQ(
211        ERR_INVALID_ARGUMENT,
212        WriteWebSocketFrameHeader(
213            header, NULL, dummy_buffer, kTests[i].expected_header_size - 1));
214  }
215}
216
217TEST(WebSocketFrameTest, MaskPayload) {
218  struct TestCase {
219    const char* masking_key;
220    uint64 frame_offset;
221    const char* input;
222    const char* output;
223    size_t data_length;
224  };
225  static const TestCase kTests[] = {
226    { "\xDE\xAD\xBE\xEF", 0, "FooBar", "\x98\xC2\xD1\xAD\xBF\xDF", 6 },
227    { "\xDE\xAD\xBE\xEF", 1, "FooBar", "\xEB\xD1\x80\x9C\xCC\xCC", 6 },
228    { "\xDE\xAD\xBE\xEF", 2, "FooBar", "\xF8\x80\xB1\xEF\xDF\x9D", 6 },
229    { "\xDE\xAD\xBE\xEF", 3, "FooBar", "\xA9\xB1\xC2\xFC\x8E\xAC", 6 },
230    { "\xDE\xAD\xBE\xEF", 4, "FooBar", "\x98\xC2\xD1\xAD\xBF\xDF", 6 },
231    { "\xDE\xAD\xBE\xEF", 42, "FooBar", "\xF8\x80\xB1\xEF\xDF\x9D", 6 },
232    { "\xDE\xAD\xBE\xEF", 0, "", "", 0 },
233    { "\xDE\xAD\xBE\xEF", 0, "\xDE\xAD\xBE\xEF", "\x00\x00\x00\x00", 4 },
234    { "\xDE\xAD\xBE\xEF", 0, "\x00\x00\x00\x00", "\xDE\xAD\xBE\xEF", 4 },
235    { "\x00\x00\x00\x00", 0, "FooBar", "FooBar", 6 },
236    { "\xFF\xFF\xFF\xFF", 0, "FooBar", "\xB9\x90\x90\xBD\x9E\x8D", 6 },
237  };
238  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
239
240  for (int i = 0; i < kNumTests; ++i) {
241    WebSocketMaskingKey masking_key;
242    std::copy(kTests[i].masking_key,
243              kTests[i].masking_key + WebSocketFrameHeader::kMaskingKeyLength,
244              masking_key.key);
245    std::vector<char> frame_data(kTests[i].input,
246                                 kTests[i].input + kTests[i].data_length);
247    std::vector<char> expected_output(kTests[i].output,
248                                      kTests[i].output + kTests[i].data_length);
249    MaskWebSocketFramePayload(masking_key,
250                              kTests[i].frame_offset,
251                              frame_data.empty() ? NULL : &frame_data.front(),
252                              frame_data.size());
253    EXPECT_EQ(expected_output, frame_data);
254  }
255}
256
257// Check that all combinations of alignment, frame offset and chunk size work
258// correctly for MaskWebSocketFramePayload(). This is mainly used to ensure that
259// vectorisation optimisations don't break anything. We could take a "white box"
260// approach and only test the edge cases, but since the exhaustive "black box"
261// approach runs in acceptable time, we don't have to take the risk of being
262// clever.
263//
264// This brute-force approach runs in O(N^3) time where N is the size of the
265// maximum vector size we want to test again. This might need reconsidering if
266// MaskWebSocketFramePayload() is ever optimised for a dedicated vector
267// architecture.
268TEST(WebSocketFrameTest, MaskPayloadAlignment) {
269  // This reflects what might be implemented in the future, rather than
270  // the current implementation. FMA3 and FMA4 support 256-bit vector ops.
271  static const size_t kMaxVectorSizeInBits = 256;
272  static const size_t kMaxVectorSize = kMaxVectorSizeInBits / 8;
273  static const size_t kMaxVectorAlignment = kMaxVectorSize;
274  static const size_t kMaskingKeyLength =
275      WebSocketFrameHeader::kMaskingKeyLength;
276  static const size_t kScratchBufferSize =
277      kMaxVectorAlignment + kMaxVectorSize * 2;
278  static const char kTestMask[] = "\xd2\xba\x5a\xbe";
279  // We use 786 bits of random input to reduce the risk of correlated errors.
280  static const char kTestInput[] = {
281    "\x3d\x77\x1d\x1b\x19\x8c\x48\xa3\x19\x6d\xf7\xcc\x39\xe7\x57\x0b"
282    "\x69\x8c\xda\x4b\xfc\xac\x2c\xd3\x49\x96\x6e\x8a\x7b\x5a\x32\x76"
283    "\xd0\x11\x43\xa0\x89\xfc\x76\x2b\x10\x2f\x4c\x7b\x4f\xa6\xdd\xe4"
284    "\xfc\x8e\xd8\x72\xcf\x7e\x37\xcd\x31\xcd\xc1\xc0\x89\x0c\xa7\x4c"
285    "\xda\xa8\x4b\x75\xa1\xcb\xa9\x77\x19\x4d\x6e\xdf\xc8\x08\x1c\xb6"
286    "\x6d\xfb\x38\x04\x44\xd5\xba\x57\x9f\x76\xb0\x2e\x07\x91\xe6\xa8"
287  };
288  static const size_t kTestInputSize = arraysize(kTestInput) - 1;
289  static const char kTestOutput[] = {
290    "\xef\xcd\x47\xa5\xcb\x36\x12\x1d\xcb\xd7\xad\x72\xeb\x5d\x0d\xb5"
291    "\xbb\x36\x80\xf5\x2e\x16\x76\x6d\x9b\x2c\x34\x34\xa9\xe0\x68\xc8"
292    "\x02\xab\x19\x1e\x5b\x46\x2c\x95\xc2\x95\x16\xc5\x9d\x1c\x87\x5a"
293    "\x2e\x34\x82\xcc\x1d\xc4\x6d\x73\xe3\x77\x9b\x7e\x5b\xb6\xfd\xf2"
294    "\x08\x12\x11\xcb\x73\x71\xf3\xc9\xcb\xf7\x34\x61\x1a\xb2\x46\x08"
295    "\xbf\x41\x62\xba\x96\x6f\xe0\xe9\x4d\xcc\xea\x90\xd5\x2b\xbc\x16"
296  };
297  COMPILE_ASSERT(arraysize(kTestInput) == arraysize(kTestOutput),
298                 output_and_input_arrays_have_the_same_length);
299  scoped_ptr<char, base::AlignedFreeDeleter> scratch(
300      static_cast<char*>(
301          base::AlignedAlloc(kScratchBufferSize, kMaxVectorAlignment)));
302  WebSocketMaskingKey masking_key;
303  std::copy(kTestMask, kTestMask + kMaskingKeyLength, masking_key.key);
304  for (size_t frame_offset = 0; frame_offset < kMaskingKeyLength;
305       ++frame_offset) {
306    for (size_t alignment = 0; alignment < kMaxVectorAlignment; ++alignment) {
307      char* const aligned_scratch = scratch.get() + alignment;
308      const size_t aligned_len = std::min(kScratchBufferSize - alignment,
309                                          kTestInputSize - frame_offset);
310      for (size_t chunk_size = 1; chunk_size < kMaxVectorSize; ++chunk_size) {
311        memcpy(aligned_scratch, kTestInput + frame_offset, aligned_len);
312        for (size_t chunk_start = 0; chunk_start < aligned_len;
313             chunk_start += chunk_size) {
314          const size_t this_chunk_size =
315              std::min(chunk_size, aligned_len - chunk_start);
316          MaskWebSocketFramePayload(masking_key,
317                                    frame_offset + chunk_start,
318                                    aligned_scratch + chunk_start,
319                                    this_chunk_size);
320        }
321        // Stop the test if it fails, since we don't want to spew thousands of
322        // failures.
323        ASSERT_TRUE(std::equal(aligned_scratch,
324                               aligned_scratch + aligned_len,
325                               kTestOutput + frame_offset))
326            << "Output failed to match for frame_offset=" << frame_offset
327            << ", alignment=" << alignment << ", chunk_size=" << chunk_size;
328      }
329    }
330  }
331}
332
333// "IsKnownDataOpCode" is currently implemented in an "obviously correct"
334// manner, but we test is anyway in case it changes to a more complex
335// implementation in future.
336TEST(WebSocketFrameHeaderTest, IsKnownDataOpCode) {
337  // Make the test less verbose.
338  typedef WebSocketFrameHeader Frame;
339
340  // Known opcode, is used for data frames
341  EXPECT_TRUE(Frame::IsKnownDataOpCode(Frame::kOpCodeContinuation));
342  EXPECT_TRUE(Frame::IsKnownDataOpCode(Frame::kOpCodeText));
343  EXPECT_TRUE(Frame::IsKnownDataOpCode(Frame::kOpCodeBinary));
344
345  // Known opcode, is used for control frames
346  EXPECT_FALSE(Frame::IsKnownDataOpCode(Frame::kOpCodeClose));
347  EXPECT_FALSE(Frame::IsKnownDataOpCode(Frame::kOpCodePing));
348  EXPECT_FALSE(Frame::IsKnownDataOpCode(Frame::kOpCodePong));
349
350  // Check that unused opcodes return false
351  EXPECT_FALSE(Frame::IsKnownDataOpCode(Frame::kOpCodeDataUnused));
352  EXPECT_FALSE(Frame::IsKnownDataOpCode(Frame::kOpCodeControlUnused));
353
354  // Check that opcodes with the 4 bit set return false
355  EXPECT_FALSE(Frame::IsKnownDataOpCode(0x6));
356  EXPECT_FALSE(Frame::IsKnownDataOpCode(0xF));
357
358  // Check that out-of-range opcodes return false
359  EXPECT_FALSE(Frame::IsKnownDataOpCode(-1));
360  EXPECT_FALSE(Frame::IsKnownDataOpCode(0xFF));
361}
362
363// "IsKnownControlOpCode" is implemented in an "obviously correct" manner but
364// might be optimised in future.
365TEST(WebSocketFrameHeaderTest, IsKnownControlOpCode) {
366  // Make the test less verbose.
367  typedef WebSocketFrameHeader Frame;
368
369  // Known opcode, is used for data frames
370  EXPECT_FALSE(Frame::IsKnownControlOpCode(Frame::kOpCodeContinuation));
371  EXPECT_FALSE(Frame::IsKnownControlOpCode(Frame::kOpCodeText));
372  EXPECT_FALSE(Frame::IsKnownControlOpCode(Frame::kOpCodeBinary));
373
374  // Known opcode, is used for control frames
375  EXPECT_TRUE(Frame::IsKnownControlOpCode(Frame::kOpCodeClose));
376  EXPECT_TRUE(Frame::IsKnownControlOpCode(Frame::kOpCodePing));
377  EXPECT_TRUE(Frame::IsKnownControlOpCode(Frame::kOpCodePong));
378
379  // Check that unused opcodes return false
380  EXPECT_FALSE(Frame::IsKnownControlOpCode(Frame::kOpCodeDataUnused));
381  EXPECT_FALSE(Frame::IsKnownControlOpCode(Frame::kOpCodeControlUnused));
382
383  // Check that opcodes with the 4 bit set return false
384  EXPECT_FALSE(Frame::IsKnownControlOpCode(0x6));
385  EXPECT_FALSE(Frame::IsKnownControlOpCode(0xF));
386
387  // Check that out-of-range opcodes return false
388  EXPECT_FALSE(Frame::IsKnownControlOpCode(-1));
389  EXPECT_FALSE(Frame::IsKnownControlOpCode(0xFF));
390}
391
392}  // namespace
393
394}  // namespace net
395