Home | History | Annotate | Download | only in websockets
      1 // Copyright (c) 2012 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 
      9 #include "base/basictypes.h"
     10 #include "base/logging.h"
     11 #include "base/rand_util.h"
     12 #include "net/base/big_endian.h"
     13 #include "net/base/io_buffer.h"
     14 #include "net/base/net_errors.h"
     15 
     16 namespace {
     17 
     18 const uint8 kFinalBit = 0x80;
     19 const uint8 kReserved1Bit = 0x40;
     20 const uint8 kReserved2Bit = 0x20;
     21 const uint8 kReserved3Bit = 0x10;
     22 const uint8 kOpCodeMask = 0xF;
     23 const uint8 kMaskBit = 0x80;
     24 const uint64 kMaxPayloadLengthWithoutExtendedLengthField = 125;
     25 const uint64 kPayloadLengthWithTwoByteExtendedLengthField = 126;
     26 const uint64 kPayloadLengthWithEightByteExtendedLengthField = 127;
     27 
     28 inline void MaskWebSocketFramePayloadByBytes(
     29     const net::WebSocketMaskingKey& masking_key,
     30     size_t masking_key_offset,
     31     char* const begin,
     32     char* const end) {
     33   for (char* masked = begin; masked != end; ++masked) {
     34     *masked ^= masking_key.key[masking_key_offset++];
     35     if (masking_key_offset == net::WebSocketFrameHeader::kMaskingKeyLength)
     36       masking_key_offset = 0;
     37   }
     38 }
     39 
     40 }  // Unnamed namespace.
     41 
     42 namespace net {
     43 
     44 scoped_ptr<WebSocketFrameHeader> WebSocketFrameHeader::Clone() {
     45   scoped_ptr<WebSocketFrameHeader> ret(new WebSocketFrameHeader(opcode));
     46   ret->final = final;
     47   ret->reserved1 = reserved1;
     48   ret->reserved2 = reserved2;
     49   ret->reserved3 = reserved3;
     50   ret->opcode = opcode;
     51   ret->masked = masked;
     52   ret->payload_length = payload_length;
     53   return ret.Pass();
     54 }
     55 
     56 WebSocketFrameChunk::WebSocketFrameChunk() : final_chunk(false) {}
     57 
     58 WebSocketFrameChunk::~WebSocketFrameChunk() {}
     59 
     60 int GetWebSocketFrameHeaderSize(const WebSocketFrameHeader& header) {
     61   int extended_length_size = 0;
     62   if (header.payload_length > kMaxPayloadLengthWithoutExtendedLengthField &&
     63       header.payload_length <= kuint16max) {
     64     extended_length_size = 2;
     65   } else if (header.payload_length > kuint16max) {
     66     extended_length_size = 8;
     67   }
     68 
     69   return (WebSocketFrameHeader::kBaseHeaderSize + extended_length_size +
     70           (header.masked ? WebSocketFrameHeader::kMaskingKeyLength : 0));
     71 }
     72 
     73 int WriteWebSocketFrameHeader(const WebSocketFrameHeader& header,
     74                               const WebSocketMaskingKey* masking_key,
     75                               char* buffer,
     76                               int buffer_size) {
     77   DCHECK((header.opcode & kOpCodeMask) == header.opcode)
     78       << "header.opcode must fit to kOpCodeMask.";
     79   DCHECK(header.payload_length <= static_cast<uint64>(kint64max))
     80       << "WebSocket specification doesn't allow a frame longer than "
     81       << "kint64max (0x7FFFFFFFFFFFFFFF) bytes.";
     82   DCHECK_GE(buffer_size, 0);
     83 
     84   // WebSocket frame format is as follows:
     85   // - Common header (2 bytes)
     86   // - Optional extended payload length
     87   //   (2 or 8 bytes, present if actual payload length is more than 125 bytes)
     88   // - Optional masking key (4 bytes, present if MASK bit is on)
     89   // - Actual payload (XOR masked with masking key if MASK bit is on)
     90   //
     91   // This function constructs frame header (the first three in the list
     92   // above).
     93 
     94   int header_size = GetWebSocketFrameHeaderSize(header);
     95   if (header_size > buffer_size)
     96     return ERR_INVALID_ARGUMENT;
     97 
     98   int buffer_index = 0;
     99 
    100   uint8 first_byte = 0u;
    101   first_byte |= header.final ? kFinalBit : 0u;
    102   first_byte |= header.reserved1 ? kReserved1Bit : 0u;
    103   first_byte |= header.reserved2 ? kReserved2Bit : 0u;
    104   first_byte |= header.reserved3 ? kReserved3Bit : 0u;
    105   first_byte |= header.opcode & kOpCodeMask;
    106   buffer[buffer_index++] = first_byte;
    107 
    108   int extended_length_size = 0;
    109   uint8 second_byte = 0u;
    110   second_byte |= header.masked ? kMaskBit : 0u;
    111   if (header.payload_length <= kMaxPayloadLengthWithoutExtendedLengthField) {
    112     second_byte |= header.payload_length;
    113   } else if (header.payload_length <= kuint16max) {
    114     second_byte |= kPayloadLengthWithTwoByteExtendedLengthField;
    115     extended_length_size = 2;
    116   } else {
    117     second_byte |= kPayloadLengthWithEightByteExtendedLengthField;
    118     extended_length_size = 8;
    119   }
    120   buffer[buffer_index++] = second_byte;
    121 
    122   // Writes "extended payload length" field.
    123   if (extended_length_size == 2) {
    124     uint16 payload_length_16 = static_cast<uint16>(header.payload_length);
    125     WriteBigEndian(buffer + buffer_index, payload_length_16);
    126     buffer_index += sizeof(payload_length_16);
    127   } else if (extended_length_size == 8) {
    128     WriteBigEndian(buffer + buffer_index, header.payload_length);
    129     buffer_index += sizeof(header.payload_length);
    130   }
    131 
    132   // Writes "masking key" field, if needed.
    133   if (header.masked) {
    134     DCHECK(masking_key);
    135     std::copy(masking_key->key,
    136               masking_key->key + WebSocketFrameHeader::kMaskingKeyLength,
    137               buffer + buffer_index);
    138     buffer_index += WebSocketFrameHeader::kMaskingKeyLength;
    139   } else {
    140     DCHECK(!masking_key);
    141   }
    142 
    143   DCHECK_EQ(header_size, buffer_index);
    144   return header_size;
    145 }
    146 
    147 WebSocketMaskingKey GenerateWebSocketMaskingKey() {
    148   // Masking keys should be generated from a cryptographically secure random
    149   // number generator, which means web application authors should not be able
    150   // to guess the next value of masking key.
    151   WebSocketMaskingKey masking_key;
    152   base::RandBytes(masking_key.key, WebSocketFrameHeader::kMaskingKeyLength);
    153   return masking_key;
    154 }
    155 
    156 void MaskWebSocketFramePayload(const WebSocketMaskingKey& masking_key,
    157                                uint64 frame_offset,
    158                                char* const data,
    159                                int data_size) {
    160   static const size_t kMaskingKeyLength =
    161       WebSocketFrameHeader::kMaskingKeyLength;
    162 
    163   DCHECK_GE(data_size, 0);
    164 
    165   // Most of the masking is done one word at a time, except for the beginning
    166   // and the end of the buffer which may be unaligned. We use size_t to get the
    167   // word size for this architecture. We require it be a multiple of
    168   // kMaskingKeyLength in size.
    169   typedef size_t PackedMaskType;
    170   PackedMaskType packed_mask_key = 0;
    171   static const size_t kPackedMaskKeySize = sizeof(packed_mask_key);
    172   COMPILE_ASSERT((kPackedMaskKeySize >= kMaskingKeyLength &&
    173                   kPackedMaskKeySize % kMaskingKeyLength == 0),
    174                  word_size_is_not_multiple_of_mask_length);
    175   char* const end = data + data_size;
    176   // If the buffer is too small for the vectorised version to be useful, revert
    177   // to the byte-at-a-time implementation early.
    178   if (data_size <= static_cast<int>(kPackedMaskKeySize * 2)) {
    179     MaskWebSocketFramePayloadByBytes(
    180         masking_key, frame_offset % kMaskingKeyLength, data, end);
    181     return;
    182   }
    183   const size_t data_modulus =
    184       reinterpret_cast<size_t>(data) % kPackedMaskKeySize;
    185   char* const aligned_begin =
    186       data_modulus == 0 ? data : (data + kPackedMaskKeySize - data_modulus);
    187   // Guaranteed by the above check for small data_size.
    188   DCHECK(aligned_begin < end);
    189   MaskWebSocketFramePayloadByBytes(
    190       masking_key, frame_offset % kMaskingKeyLength, data, aligned_begin);
    191   const size_t end_modulus = reinterpret_cast<size_t>(end) % kPackedMaskKeySize;
    192   char* const aligned_end = end - end_modulus;
    193   // Guaranteed by the above check for small data_size.
    194   DCHECK(aligned_end > aligned_begin);
    195   // Create a version of the mask which is rotated by the appropriate offset
    196   // for our alignment. The "trick" here is that 0 XORed with the mask will
    197   // give the value of the mask for the appropriate byte.
    198   char realigned_mask[kMaskingKeyLength] = { 0 };
    199   MaskWebSocketFramePayloadByBytes(
    200       masking_key,
    201       (frame_offset + aligned_begin - data) % kMaskingKeyLength,
    202       realigned_mask,
    203       realigned_mask + kMaskingKeyLength);
    204 
    205   for (size_t i = 0; i < kPackedMaskKeySize; i += kMaskingKeyLength) {
    206     // memcpy() is allegedly blessed by the C++ standard for type-punning.
    207     memcpy(reinterpret_cast<char*>(&packed_mask_key) + i,
    208            realigned_mask,
    209            kMaskingKeyLength);
    210   }
    211 
    212   // The main loop.
    213   for (char* merged = aligned_begin; merged != aligned_end;
    214        merged += kPackedMaskKeySize) {
    215     // This is not quite standard-compliant C++. However, the standard-compliant
    216     // equivalent (using memcpy()) compiles to slower code using g++. In
    217     // practice, this will work for the compilers and architectures currently
    218     // supported by Chromium, and the tests are extremely unlikely to pass if a
    219     // future compiler/architecture breaks it.
    220     *reinterpret_cast<PackedMaskType*>(merged) ^= packed_mask_key;
    221   }
    222 
    223   MaskWebSocketFramePayloadByBytes(
    224       masking_key,
    225       (frame_offset + (aligned_end - data)) % kMaskingKeyLength,
    226       aligned_end,
    227       end);
    228 }
    229 
    230 }  // namespace net
    231