FreeRDP
Loading...
Searching...
No Matches
websocket.c
1
19
20#include "websocket.h"
21#include <freerdp/log.h>
22#include "../tcp.h"
23
24#define TAG FREERDP_TAG("core.gateway.websocket")
25
26#define RESPONSE_SIZE_LIMIT (64ULL * 1024ULL * 1024ULL)
27
28struct s_websocket_context
29{
30 size_t payloadLength;
31 uint32_t maskingKey;
32 BOOL masking;
33 BOOL closeSent;
34 BYTE opcode;
35 BYTE fragmentOriginalOpcode;
36 BYTE lengthAndMaskPosition;
37 WEBSOCKET_STATE state;
38 wStream* responseStreamBuffer;
39};
40
41WINPR_ATTR_NODISCARD
42static BOOL Stream_Reset(wStream* s)
43{
44 Stream_ResetPosition(s);
45 return Stream_SetLength(s, Stream_Capacity(s));
46}
47
48WINPR_ATTR_NODISCARD
49static int websocket_write_all(BIO* bio, const BYTE* data, size_t length);
50
51BOOL websocket_context_mask_and_send(BIO* bio, wStream* sPacket, wStream* sDataPacket,
52 UINT32 maskingKey)
53{
54 const size_t len = Stream_Length(sDataPacket);
55 Stream_ResetPosition(sDataPacket);
56
57 if (!Stream_EnsureRemainingCapacity(sPacket, len))
58 return FALSE;
59
60 /* mask as much as possible with 32bit access */
61 size_t streamPos = 0;
62 for (; streamPos + 4 <= len; streamPos += 4)
63 {
64 const uint32_t data = Stream_Get_UINT32(sDataPacket);
65 Stream_Write_UINT32(sPacket, data ^ maskingKey);
66 }
67
68 /* mask the rest byte by byte */
69 for (; streamPos < len; streamPos++)
70 {
71 BYTE data = 0;
72 BYTE* partialMask = ((BYTE*)&maskingKey) + (streamPos % 4);
73 Stream_Read_UINT8(sDataPacket, data);
74 Stream_Write_UINT8(sPacket, data ^ *partialMask);
75 }
76
77 Stream_SealLength(sPacket);
78
79 ERR_clear_error();
80 const size_t size = Stream_Length(sPacket);
81 const int status = websocket_write_all(bio, Stream_Buffer(sPacket), size);
82 Stream_Free(sPacket, TRUE);
83
84 return !((status < 0) || ((size_t)status != size));
85}
86
87wStream* websocket_context_packet_new(size_t len, WEBSOCKET_OPCODE opcode, UINT32* pMaskingKey)
88{
89 WINPR_ASSERT(pMaskingKey);
90 if (len > INT_MAX)
91 return nullptr;
92
93 size_t fullLen = 0;
94 if (len < 126)
95 fullLen = len + 6; /* 2 byte "mini header" + 4 byte masking key */
96 else if (len < 0x10000)
97 fullLen = len + 8; /* 2 byte "mini header" + 2 byte length + 4 byte masking key */
98 else
99 fullLen = len + 14; /* 2 byte "mini header" + 8 byte length + 4 byte masking key */
100
101 UINT32 maskingKey = 0;
102 if (winpr_RAND(&maskingKey, sizeof(maskingKey)) < 0)
103 return nullptr;
104
105 wStream* sWS = Stream_New(nullptr, fullLen);
106 if (!sWS)
107 return nullptr;
108
109 Stream_Write_UINT8(sWS, (UINT8)(WEBSOCKET_FIN_BIT | opcode));
110 if (len < 126)
111 Stream_Write_UINT8(sWS, (UINT8)len | WEBSOCKET_MASK_BIT);
112 else if (len < 0x10000)
113 {
114 Stream_Write_UINT8(sWS, 126 | WEBSOCKET_MASK_BIT);
115 Stream_Write_UINT16_BE(sWS, (UINT16)len);
116 }
117 else
118 {
119 Stream_Write_UINT8(sWS, 127 | WEBSOCKET_MASK_BIT);
120 Stream_Write_UINT32_BE(sWS, 0); /* payload is limited to INT_MAX */
121 Stream_Write_UINT32_BE(sWS, (UINT32)len);
122 }
123 Stream_Write_UINT32(sWS, maskingKey);
124 *pMaskingKey = maskingKey;
125 return sWS;
126}
127
128BOOL websocket_context_write_wstream(websocket_context* context, BIO* bio, wStream* sPacket,
129 WEBSOCKET_OPCODE opcode)
130{
131 WINPR_ASSERT(context);
132
133 if (context->closeSent)
134 return FALSE;
135
136 if (opcode == WebsocketCloseOpcode)
137 context->closeSent = TRUE;
138
139 WINPR_ASSERT(bio);
140 WINPR_ASSERT(sPacket);
141
142 const size_t len = Stream_Length(sPacket);
143 uint32_t maskingKey = 0;
144 wStream* sWS = websocket_context_packet_new(len, opcode, &maskingKey);
145 if (!sWS)
146 return FALSE;
147
148 return websocket_context_mask_and_send(bio, sWS, sPacket, maskingKey);
149}
150
151int websocket_write_all(BIO* bio, const BYTE* data, size_t length)
152{
153 WINPR_ASSERT(bio);
154 WINPR_ASSERT(data);
155 size_t offset = 0;
156
157 if (length > INT32_MAX)
158 return -1;
159
160 while (offset < length)
161 {
162 ERR_clear_error();
163 const size_t diff = length - offset;
164 int status = BIO_write(bio, &data[offset], (int)diff);
165
166 if (status > 0)
167 offset += (size_t)status;
168 else
169 {
170 if (!BIO_should_retry(bio))
171 return -1;
172
173 if (BIO_write_blocked(bio))
174 {
175 const long rstatus = BIO_wait_write(bio, 100);
176 if (rstatus < 0)
177 return -1;
178 }
179 else if (BIO_read_blocked(bio))
180 return -2; /* Abort write, there is data that must be read */
181 else
182 USleep(100);
183 }
184 }
185
186 return (int)length;
187}
188
189int websocket_context_write(websocket_context* context, BIO* bio, const BYTE* buf, int isize,
190 WEBSOCKET_OPCODE opcode)
191{
192 WINPR_ASSERT(bio);
193 WINPR_ASSERT(buf);
194
195 if (isize < 0)
196 return -1;
197
198 wStream sbuffer = WINPR_C_ARRAY_INIT;
199 wStream* s = Stream_StaticConstInit(&sbuffer, buf, (size_t)isize);
200 if (!Stream_SetLength(s, Stream_Capacity(s)))
201 return -3;
202 if (!websocket_context_write_wstream(context, bio, s, opcode))
203 return -2;
204 return isize;
205}
206
207WINPR_ATTR_NODISCARD
208static int websocket_read_data(BIO* bio, BYTE* pBuffer, size_t size,
209 websocket_context* encodingContext)
210{
211 int status = 0;
212
213 WINPR_ASSERT(bio);
214 WINPR_ASSERT(pBuffer);
215 WINPR_ASSERT(encodingContext);
216
217 if (encodingContext->payloadLength == 0)
218 {
219 encodingContext->state = WebsocketStateOpcodeAndFin;
220 return 0;
221 }
222
223 const size_t rlen =
224 (encodingContext->payloadLength < size ? encodingContext->payloadLength : size);
225 if (rlen > INT32_MAX)
226 return -1;
227
228 ERR_clear_error();
229 status = BIO_read(bio, pBuffer, (int)rlen);
230 if (status <= 0)
231 {
232 if (status == 0)
233 {
234 if (!BIO_should_retry(bio))
235 return -1;
236 }
237 return status;
238 }
239
240 if ((size_t)status > encodingContext->payloadLength)
241 return status;
242
243 encodingContext->payloadLength -= (size_t)status;
244
245 if (encodingContext->payloadLength == 0)
246 encodingContext->state = WebsocketStateOpcodeAndFin;
247
248 return status;
249}
250
251WINPR_ATTR_NODISCARD
252static int websocket_read_wstream(BIO* bio, websocket_context* encodingContext)
253{
254 WINPR_ASSERT(bio);
255 WINPR_ASSERT(encodingContext);
256
257 wStream* s = encodingContext->responseStreamBuffer;
258 WINPR_ASSERT(s);
259
260 if (encodingContext->payloadLength == 0)
261 {
262 encodingContext->state = WebsocketStateOpcodeAndFin;
263 return 0;
264 }
265
266 if (!Stream_EnsureRemainingCapacity(s, encodingContext->payloadLength))
267 {
268 WLog_WARN(TAG,
269 "wStream::capacity [%" PRIuz "] != encodingContext::paylaodLangth [%" PRIuz "]",
270 Stream_GetRemainingCapacity(s), encodingContext->payloadLength);
271 return -1;
272 }
273
274 const int status = websocket_read_data(bio, Stream_Pointer(s), Stream_GetRemainingCapacity(s),
275 encodingContext);
276 if (status < 0)
277 return status;
278
279 if (!Stream_SafeSeek(s, (size_t)status))
280 return -1;
281
282 Stream_SealLength(s);
283 return status;
284}
285
286WINPR_ATTR_NODISCARD
287static BOOL websocket_reply_close(BIO* bio, websocket_context* context, wStream* s)
288{
289 WINPR_ASSERT(bio);
290
291 return websocket_context_write_wstream(context, bio, s, WebsocketCloseOpcode);
292}
293
294WINPR_ATTR_NODISCARD
295static BOOL websocket_reply_pong(BIO* bio, websocket_context* context, wStream* s)
296{
297 WINPR_ASSERT(bio);
298 WINPR_ASSERT(s);
299
300 if (Stream_GetPosition(s) != 0)
301 return websocket_context_write_wstream(context, bio, s, WebsocketPongOpcode);
302
303 return websocket_reply_close(bio, context, s);
304}
305
306WINPR_ATTR_NODISCARD
307static int websocket_handle_payload(BIO* bio, BYTE* pBuffer, size_t size,
308 websocket_context* encodingContext)
309{
310 int status = 0;
311
312 WINPR_ASSERT(bio);
313 WINPR_ASSERT(pBuffer);
314 WINPR_ASSERT(encodingContext);
315
316 const BYTE effectiveOpcode = ((encodingContext->opcode & 0xf) == WebsocketContinuationOpcode
317 ? encodingContext->fragmentOriginalOpcode & 0xf
318 : encodingContext->opcode & 0xf);
319
320 switch (effectiveOpcode)
321 {
322 case WebsocketBinaryOpcode:
323 {
324 status = websocket_read_data(bio, pBuffer, size, encodingContext);
325 if (status < 0)
326 return status;
327
328 return status;
329 }
330 case WebsocketPingOpcode:
331 {
332 status = websocket_read_wstream(bio, encodingContext);
333 if (status < 0)
334 return status;
335
336 if (encodingContext->payloadLength == 0)
337 {
338 if (!websocket_reply_pong(bio, encodingContext,
339 encodingContext->responseStreamBuffer))
340 return -1;
341 if (!Stream_Reset(encodingContext->responseStreamBuffer))
342 return -1;
343 }
344 }
345 break;
346 case WebsocketPongOpcode:
347 {
348 status = websocket_read_wstream(bio, encodingContext);
349 if (status < 0)
350 return status;
351 /* We don“t care about pong response data, discard. */
352 if (!Stream_Reset(encodingContext->responseStreamBuffer))
353 return -1;
354 }
355 break;
356 case WebsocketCloseOpcode:
357 {
358 status = websocket_read_wstream(bio, encodingContext);
359 if (status < 0)
360 return status;
361
362 if (encodingContext->payloadLength == 0)
363 {
364 if (!websocket_reply_close(bio, encodingContext,
365 encodingContext->responseStreamBuffer))
366 return -1;
367 encodingContext->closeSent = TRUE;
368 if (!Stream_Reset(encodingContext->responseStreamBuffer))
369 return -1;
370 }
371 }
372 break;
373 default:
374 WLog_WARN(TAG, "Unimplemented websocket opcode %" PRIx8 ". Dropping", effectiveOpcode);
375
376 status = websocket_read_wstream(bio, encodingContext);
377 if (status < 0)
378 return status;
379 if (!Stream_Reset(encodingContext->responseStreamBuffer))
380 return -1;
381 break;
382 }
383 /* return how many bytes have been written to pBuffer.
384 * Only WebsocketBinaryOpcode writes into it and it returns directly */
385 return 0;
386}
387
388int websocket_context_read(websocket_context* encodingContext, BIO* bio, BYTE* pBuffer, size_t size)
389{
390 int status = 0;
391 size_t effectiveDataLen = 0;
392
393 WINPR_ASSERT(bio);
394 WINPR_ASSERT(pBuffer);
395 WINPR_ASSERT(encodingContext);
396
397 while (TRUE)
398 {
399 switch (encodingContext->state)
400 {
401 case WebsocketStateOpcodeAndFin:
402 {
403 BYTE buffer[1] = WINPR_C_ARRAY_INIT;
404
405 ERR_clear_error();
406 status = BIO_read(bio, (char*)buffer, sizeof(buffer));
407 if (status <= 0)
408 return (effectiveDataLen > 0 ? WINPR_ASSERTING_INT_CAST(int, effectiveDataLen)
409 : status);
410
411 encodingContext->opcode = buffer[0];
412 if (((encodingContext->opcode & 0xf) != WebsocketContinuationOpcode) &&
413 (encodingContext->opcode & 0xf) < 0x08)
414 encodingContext->fragmentOriginalOpcode = encodingContext->opcode;
415 encodingContext->state = WebsocketStateLengthAndMasking;
416 }
417 break;
418 case WebsocketStateLengthAndMasking:
419 {
420 BYTE buffer[1] = WINPR_C_ARRAY_INIT;
421
422 ERR_clear_error();
423 status = BIO_read(bio, (char*)buffer, sizeof(buffer));
424 if (status <= 0)
425 return (effectiveDataLen > 0 ? WINPR_ASSERTING_INT_CAST(int, effectiveDataLen)
426 : status);
427
428 encodingContext->masking = ((buffer[0] & WEBSOCKET_MASK_BIT) == WEBSOCKET_MASK_BIT);
429 encodingContext->lengthAndMaskPosition = 0;
430 encodingContext->payloadLength = 0;
431 const BYTE len = buffer[0] & 0x7f;
432 if (len < 126)
433 {
434 encodingContext->payloadLength = len;
435 encodingContext->state = (encodingContext->masking ? WebSocketStateMaskingKey
436 : WebSocketStatePayload);
437 }
438 else if (len == 126)
439 encodingContext->state = WebsocketStateShortLength;
440 else
441 encodingContext->state = WebsocketStateLongLength;
442 }
443 break;
444 case WebsocketStateShortLength:
445 case WebsocketStateLongLength:
446 {
447 BYTE buffer[1] = WINPR_C_ARRAY_INIT;
448 const BYTE lenLength =
449 (encodingContext->state == WebsocketStateShortLength ? 2 : 8);
450 while (encodingContext->lengthAndMaskPosition < lenLength)
451 {
452 ERR_clear_error();
453 status = BIO_read(bio, (char*)buffer, sizeof(buffer));
454 if (status <= 0)
455 return (effectiveDataLen > 0
456 ? WINPR_ASSERTING_INT_CAST(int, effectiveDataLen)
457 : status);
458 if (status > UINT8_MAX)
459 return -1;
460 encodingContext->payloadLength =
461 (encodingContext->payloadLength) << 8 | buffer[0];
462 encodingContext->lengthAndMaskPosition +=
463 WINPR_ASSERTING_INT_CAST(BYTE, status);
464 }
465 if (encodingContext->payloadLength > RESPONSE_SIZE_LIMIT)
466 {
467 WLog_ERR(TAG, "received excessive payload size %" PRIuz ", aborting",
468 encodingContext->payloadLength);
469 /* fatal, callers must not take a stale retry flag for a blocked read */
470 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
471 return -1;
472 }
473 encodingContext->state =
474 (encodingContext->masking ? WebSocketStateMaskingKey : WebSocketStatePayload);
475 }
476 break;
477 case WebSocketStateMaskingKey:
478 {
479 WLog_WARN(
480 TAG, "Websocket Server sends data with masking key. This is against RFC 6455.");
481 /* fatal, callers must not take a stale retry flag for a blocked read */
482 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
483 return -1;
484 }
485 case WebSocketStatePayload:
486 {
487 status = websocket_handle_payload(bio, pBuffer, size, encodingContext);
488 if (status < 0)
489 return (effectiveDataLen > 0 ? WINPR_ASSERTING_INT_CAST(int, effectiveDataLen)
490 : status);
491
492 effectiveDataLen += WINPR_ASSERTING_INT_CAST(size_t, status);
493
494 if (WINPR_ASSERTING_INT_CAST(size_t, status) >= size)
495 return WINPR_ASSERTING_INT_CAST(int, effectiveDataLen);
496 pBuffer += status;
497 size -= WINPR_ASSERTING_INT_CAST(size_t, status);
498 }
499 break;
500 default:
501 break;
502 }
503 }
504 /* should be unreachable */
505}
506
507websocket_context* websocket_context_new(void)
508{
509 websocket_context* context = calloc(1, sizeof(websocket_context));
510 if (!context)
511 goto fail;
512
513 context->responseStreamBuffer = Stream_New(nullptr, 1024);
514 if (!context->responseStreamBuffer)
515 goto fail;
516
517 if (!websocket_context_reset(context))
518 goto fail;
519
520 return context;
521fail:
522 websocket_context_free(context);
523 return nullptr;
524}
525
526void websocket_context_free(websocket_context* context)
527{
528 if (!context)
529 return;
530
531 Stream_Free(context->responseStreamBuffer, TRUE);
532 free(context);
533}
534
535BOOL websocket_context_reset(websocket_context* context)
536{
537 WINPR_ASSERT(context);
538
539 context->state = WebsocketStateOpcodeAndFin;
540 return Stream_Reset(context->responseStreamBuffer);
541}