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