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