vendor/bq_websocket/bq_websocket.c

filter: Statementstmt 44.2% 719 / 1624 Branchbran 34.2% 347 / 1012 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 40.4% 1066 / 2636 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« blib/lib/Unblock/WebSocket/_UTF8.pm ↑ Summary WebSocket.xs »
1 #include "bq_websocket.h"
2  
3 /*
4 ------------------------------------------------------------------------------
5 This software is available under 2 licenses -- choose whichever you prefer.
6 ------------------------------------------------------------------------------
7 ALTERNATIVE A - MIT License
8 Copyright (c) 2020 Samuli Raivio
9 Permission is hereby granted, free of charge, to any person obtaining a copy of
10 this software and associated documentation files (the "Software"), to deal in
11 the Software without restriction, including without limitation the rights to
12 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
13 of the Software, and to permit persons to whom the Software is furnished to do
14 so, subject to the following conditions:
15 The above copyright notice and this permission notice shall be included in all
16 copies or substantial portions of the Software.
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 SOFTWARE.
24 ------------------------------------------------------------------------------
25 ALTERNATIVE B - Public Domain (www.unlicense.org)
26 This is free and unencumbered software released into the public domain.
27 Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
28 software, either in source code form or as a compiled binary, for any purpose,
29 commercial or non-commercial, and by any means.
30 In jurisdictions that recognize copyright laws, the author or authors of this
31 software dedicate any and all copyright interest in the software to the public
32 domain. We make this dedication for the benefit of the public at large and to
33 the detriment of our heirs and successors. We intend this dedication to be an
34 overt act of relinquishment in perpetuity of all present and future rights to
35 this software under copyright law.
36 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
39 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
40 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
41 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
42 ----------------------------------------
43 */
44  
45 #include <stdlib.h>
46 #include <string.h>
47 #include <time.h>
48 #include <ctype.h>
49 #include <stdarg.h>
50 #include <errno.h>
51  
52 // -- Config
53  
54 #if defined(_MSC_VER)
55 #define bqws_forceinline __forceinline
56  
57 #if defined(_M_IX86) || defined(_M_X64)
58 #include <intrin.h>
59 #include <xmmintrin.h>
60 #define BQWS_USE_SSE 1
61 #endif
62  
63 #elif defined(__GNUC__) || defined(__clang__)
64 #define bqws_forceinline __attribute__((always_inline)) inline
65  
66 #if defined(__i386__) || defined(__x86_64__)
67 #include <x86intrin.h>
68 #include <xmmintrin.h>
69 #define BQWS_USE_SSE 1
70 #endif
71  
72 #else
73 #define bqws_forceinline
74 #endif
75  
76 #ifndef bqws_assert
77 #include <assert.h>
78 #define bqws_assert(x) assert(x)
79 #endif
80  
81 #ifndef bqws_malloc
82 #define bqws_malloc(size) malloc((size))
83 #endif
84  
85 #ifndef bqws_realloc
86 #define bqws_realloc(ptr, old_size, new_size) realloc((ptr), (new_size))
87 #endif
88  
89 #ifndef bqws_free
90 #define bqws_free(ptr, size) free((ptr))
91 #endif
92  
93 // TODO: QueryPerformanceCounter() or clock_gettime() might be faster
94 typedef clock_t bqws_timestamp;
95  
96 85 static bqws_timestamp bqws_get_timestamp()
97 {
98 85 return clock();
99 }
100  
101 0 static size_t bqws_timestamp_delta_to_ms(bqws_timestamp begin, bqws_timestamp end)
102 {
103 0 return (size_t)((double)(end - begin) * 1000.0 / (double)CLOCKS_PER_SEC);
104 }
105  
106 #ifndef BQWS_DEBUG
107 #if defined(NDEBUG)
108 #define BQWS_DEBUG 0
109 #else
110 #define BQWS_DEBUG 1
111 #endif
112 #endif
113  
114 #ifndef BQWS_SINGLE_THREAD
115 #define BQWS_SINGLE_THREAD 0
116 #endif
117  
118 #ifndef bqws_mutex
119  
120 #if defined(_WIN32) && !BQWS_SINGLE_THREAD
121  
122 #define WIN32_LEAN_AND_MEAN
123 #define NOMINMAX
124 #include <Windows.h>
125  
126 typedef struct {
127 CRITICAL_SECTION cs;
128 #if BQWS_DEBUG
129 DWORD thread;
130 #endif
131 } bqws_mutex;
132  
133 static void bqws_mutex_init(bqws_mutex *m)
134 {
135 InitializeCriticalSection(&m->cs);
136 #if BQWS_DEBUG
137 m->thread = 0;
138 #endif
139 }
140  
141 static void bqws_mutex_free(bqws_mutex *m)
142 {
143 #if BQWS_DEBUG
144 m->thread = 0;
145 #endif
146 DeleteCriticalSection(&m->cs);
147 }
148  
149 static void bqws_mutex_lock(bqws_mutex *m)
150 {
151 EnterCriticalSection(&m->cs);
152 #if BQWS_DEBUG
153 m->thread = GetCurrentThreadId();
154 #endif
155 }
156  
157 static void bqws_mutex_unlock(bqws_mutex *m)
158 {
159 #if BQWS_DEBUG
160 m->thread = 0;
161 #endif
162 LeaveCriticalSection(&m->cs);
163 }
164  
165 #if BQWS_DEBUG
166 #define bqws_assert_locked(m) bqws_assert((m)->thread == GetCurrentThreadId());
167 #else
168 #define bqws_assert_locked(m) (void)0
169 #endif
170  
171 #elif (defined(__APPLE__) || defined(__linux__) || defined(__unix__)) && (!defined(__EMSCRIPTEN__) || defined(__EMSCRIPTEN_PTHREADS__)) && !BQWS_SINGLE_THREAD
172  
173 #include <pthread.h>
174  
175 typedef struct {
176 pthread_mutex_t mutex;
177 #if BQWS_DEBUG
178 bool locked;
179 pthread_t thread;
180 #endif
181 } bqws_mutex;
182  
183 static void bqws_mutex_init(bqws_mutex *m)
184 {
185 pthread_mutex_init(&m->mutex, NULL);
186 #if BQWS_DEBUG
187 m->locked = false;
188 #endif
189 }
190  
191 static void bqws_mutex_free(bqws_mutex *m)
192 {
193 #if BQWS_DEBUG
194 m->locked = false;
195 #endif
196 pthread_mutex_destroy(&m->mutex);
197 }
198  
199 static void bqws_mutex_lock(bqws_mutex *m)
200 {
201 pthread_mutex_lock(&m->mutex);
202 #if BQWS_DEBUG
203 m->locked = true;
204 m->thread = pthread_self();
205 #endif
206 }
207  
208 static void bqws_mutex_unlock(bqws_mutex *m)
209 {
210 #if BQWS_DEBUG
211 m->locked = false;
212 #endif
213 pthread_mutex_unlock(&m->mutex);
214 }
215  
216 #if BQWS_DEBUG
217 #define bqws_assert_locked(m) ((m)->locked && (m)->thread == pthread_self())
218 #else
219 #define bqws_assert_locked(m) (void)0
220 #endif
221  
222 #else
223  
224 typedef struct {
225 bool is_locked;
226 } bqws_mutex;
227  
228 static void bqws_mutex_init(bqws_mutex *m)
229 {
230 m->is_locked = false;
231 }
232  
233 static void bqws_mutex_free(bqws_mutex *m)
234 {
235 bqws_assert(!m->is_locked);
236 }
237  
238 static void bqws_mutex_lock(bqws_mutex *m)
239 {
240 bqws_assert(!m->is_locked);
241 m->is_locked = true;
242 }
243 static void bqws_mutex_unlock(bqws_mutex *m)
244 {
245 bqws_assert(m->is_locked);
246 m->is_locked = false;
247 }
248  
249 #define bqws_assert_locked(m) bqws_assert((m)->is_locked)
250  
251 #endif
252  
253 #else // not defined bqws_mutex
254  
255 #ifndef bqws_assert_locked
256 #define bqws_assert_locked(m) (void)0
257 #endif
258  
259 #endif // not defined bqws_mutex
260  
261 // -- Magic constants
262  
263 #define BQWS_DELETED_MAGIC 0xbdbdbdbd
264 #define BQWS_SOCKET_MAGIC 0x7773636b
265 #define BQWS_MSG_MAGIC 0x776d7367
266 #define BQWS_FILTER_MAGIC 0x77666c74
267  
268 // -- Types
269  
270 // Message implementation struct, message data is always allocated
271 // to follow the struct in memory.
272  
273 typedef struct bqws_msg_imp bqws_msg_imp;
274 struct bqws_msg_imp {
275 uint32_t magic; // = BQWS_MSG_MAGIC
276 bool compressed;
277  
278 // Socket that is responsible of freeing this message
279 // or NULL if it's owned by the user.
280 bqws_socket *owner;
281  
282 // Allocator used to allocate this message
283 bqws_allocator allocator;
284  
285 // Linked list in `bqws_msg_queue`
286 bqws_msg_imp *prev;
287  
288 bqws_msg msg;
289 };
290  
291 #define msg_imp(msg) (bqws_msg_imp*)((char*)msg - offsetof(bqws_msg_imp, msg))
292 #define msg_alloc_size(msg) (sizeof(bqws_msg_imp) + (msg)->capacity)
293  
294 typedef struct {
295 bqws_mutex mutex;
296 bqws_msg_imp *first, *last;
297  
298 size_t num_messages;
299 size_t byte_size;
300  
301 uint64_t total_messages;
302 uint64_t total_size;
303 } bqws_msg_queue;
304  
305 typedef struct {
306 uint32_t codepoint;
307 uint32_t minimum;
308 uint8_t remaining;
309 uint8_t next_min;
310 uint8_t next_max;
311 } unblock_bqws_utf8_state;
312  
313 typedef struct {
314 bqws_msg_imp *msg;
315 size_t offset;
316 size_t header_offset;
317 size_t header_size;
318 bool finished;
319 bool masked;
320 bool validate_utf8;
321 bool partial_compressed;
322 uint32_t mask_key;
323 bqws_msg_type partial_type;
324 unblock_bqws_utf8_state utf8;
325 } bqws_msg_buffer;
326  
327 typedef struct {
328 char *data;
329 size_t size;
330 size_t capacity;
331 size_t write_offset;
332 size_t read_offset;
333 } bqws_handshake_buffer;
334  
335 typedef struct {
336 uint32_t magic;
337  
338 const char *path;
339 const char *host;
340 const char *origin;
341  
342 const char *protocols[BQWS_MAX_PROTOCOLS];
343 size_t num_protocols;
344  
345 bqws_verify_fn *verify_fn;
346 void *verify_user;
347  
348 size_t text_size;
349 char text_data[];
350 } bqws_verify_filter;
351  
352 // Random entropy source
353 typedef struct {
354 void (*function_pointer)(bqws_socket *ws, const bqws_client_opts *opts);
355 void *stack_pointer;
356 void *heap_pointer;
357 clock_t clock;
358 time_t time;
359 uint32_t mask_key;
360 } bqws_random_entropy;
361  
362 typedef struct {
363 uint8_t code_be[2];
364 uint8_t magic[4];
365 uint8_t error_be[4];
366 } bqws_err_close_data;
367  
368 // Main socket/context type, passed everywhere as the first argument.
369  
370 struct bqws_socket {
371  
372 // -- Constant data
373  
374 uint32_t magic; // = BQWS_SOCKET_MAGIC
375 char *name; // Name high up for debugging
376 bool is_server;
377  
378 // Copied from `opts`
379 bqws_allocator allocator;
380 bqws_io user_io;
381 bqws_limits limits;
382 bool recv_partial_messages;
383 bool recv_control_messages;
384 bool mask_server;
385 bool unsafe_dont_mask_client;
386 bool allow_rsv1;
387 bqws_verify_fn *verify_fn;
388 void *verify_user;
389 bqws_message_fn *message_fn;
390 void *message_user;
391 bqws_peek_fn *peek_fn;
392 void *peek_user;
393 bqws_log_fn *log_fn;
394 void *log_user;
395 bool log_send;
396 bool log_recv;
397 bqws_error_fn *error_fn;
398 void *error_user;
399 bqws_send_message_fn *send_message_fn;
400 void *send_message_user;
401 size_t user_size;
402 size_t ping_interval;
403 size_t connect_timeout;
404 size_t close_timeout;
405 size_t ping_response_timeout;
406  
407 // -- Internally synchronized
408  
409 // Current error state, set to the first error that occurs
410 // Error writes are protected by `err_mutex` checking `err` can
411 // be done without a mutex to check for errors from the same thread.
412 bqws_mutex err_mutex;
413 bqws_error err;
414  
415 // Message queues
416 bqws_msg_queue recv_partial_queue;
417 bqws_msg_queue recv_queue;
418 bqws_msg_queue send_queue;
419  
420 // -- State of the socket, errors
421 struct {
422 bqws_mutex mutex;
423  
424 // Connection state
425 bqws_state state;
426 bqws_state override_state;
427  
428 // Pre-allocated error close message storage
429 void *pointer_align;
430 char error_msg_data[sizeof(bqws_msg_imp) + sizeof(bqws_err_close_data)];
431 bqws_close_reason peer_reason;
432 bqws_error peer_err;
433 bool stop_write;
434 bool stop_read;
435 bool close_sent;
436 bool close_received;
437 bool io_started;
438 bool io_closed;
439  
440 char *chosen_protocol;
441  
442 bqws_timestamp start_closing_ts;
443  
444 // Priority messages
445 bqws_msg_imp *close_to_send;
446 bqws_msg_imp *pong_to_send;
447
448 } state;
449  
450 // -- Allocation
451 struct {
452 bqws_mutex mutex;
453  
454 // TODO: Make this atomic?
455 // Total memory allocated through `allocator` at the moment
456 size_t memory_used;
457 } alloc;
458  
459 // -- IO
460 struct {
461 bqws_mutex mutex;
462  
463 bqws_timestamp start_connect_ts;
464 bqws_timestamp last_write_ts;
465 bqws_timestamp last_read_ts;
466 bqws_timestamp last_ping_ts;
467 size_t recv_partial_size;
468  
469 // Handshake
470 bqws_handshake_buffer handshake;
471 bqws_handshake_buffer handshake_overflow;
472 bqws_client_opts *opts_from_client;
473 char client_key_base64[32];
474 bool client_handshake_done;
475 bool client_has_protocol;
476  
477 // Masking random state
478 uint64_t mask_random_state;
479 uint64_t mask_random_stream;
480  
481 // Write/read buffers `recv_header` is also used to buffer
482 // multiple small messages
483 char recv_header[512];
484 bqws_msg_buffer recv_buf;
485 char send_header[16];
486 bqws_msg_buffer send_buf;
487 } io;
488  
489 // -- API
490 struct {
491 bqws_mutex mutex;
492  
493 bqws_msg_imp *next_partial_to_send;
494 bqws_msg_type send_partial_type;
495 } partial;
496  
497 // User data follows in memory
498 char user_data[];
499 };
500  
501 // -- Utility
502  
503 // Mark the socket as failed with an error. Only updates the
504 // error flag if it's not set.
505  
506 0 static void null_free(void *user, void *ptr, size_t size) { }
507  
508 128 static void ws_log(bqws_socket *ws, const char *str)
509 {
510 128 ▶ if (ws->log_fn) ws->log_fn(ws->log_user, ws, str);
Branch: 1 branch
BranchTrueFalseTotal
if (ws->log_fn) ws->log_fn(ws->log_user, ws, str); 0 128 128
511 128 }
512  
513 19 static void ws_log2(bqws_socket *ws, const char *a, const char *b)
514 {
515 19 ▶ if (!ws->log_fn) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->log_fn) return; 19 0 19
516  
517 char line[256];
518 0 size_t len_a = strlen(a);
519 0 size_t len_b = strlen(b);
520 bqws_assert(len_a + len_b < sizeof(line));
521  
522 0 char *ptr = line;
523 0 memcpy(ptr, a, len_a); ptr += len_a;
524 0 memcpy(ptr, b, len_b); ptr += len_b;
525 0 *ptr = '\0';
526  
527 0 ws->log_fn(ws->log_user, ws, line);
528 }
529  
530 11 static void ws_close(bqws_socket *ws)
531 {
532 bqws_assert_locked(&ws->state.mutex);
533  
534 11 ▶ if (ws->state.state != BQWS_STATE_CLOSED) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.state != BQWS_STATE_CLOSED) { 11 0 11
535 11 ws_log(ws, "State: CLOSED");
536  
537 11 ▶ if (ws->user_io.close_fn && !ws->state.io_closed) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->user_io.close_fn && !ws->state.io_closed) { 0 11 11
if (ws->user_io.close_fn && !ws->state.io_closed) { 0 0 0
538 0 ws->user_io.close_fn(ws->user_io.user, ws);
539 }
540 11 ws->state.io_closed = true;
541  
542 11 ws->state.state = BQWS_STATE_CLOSED;
543 11 ws->state.stop_read = true;
544 11 ws->state.stop_write = true;
545 }
546 11 }
547  
548 19 static void ws_fail(bqws_socket *ws, bqws_error err)
549 {
550 19 bool should_report = false;
551  
552 bqws_mutex_lock(&ws->state.mutex);
553  
554 bqws_assert(err != BQWS_OK);
555  
556 bqws_mutex_lock(&ws->err_mutex);
557 19 ▶ if (!ws->err) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->err) { 19 0 19
558 19 should_report = true;
559  
560 // vvv Breakpoint here to stop on first error
561 19 ws->err = err;
562  
563 bqws_mutex_unlock(&ws->err_mutex);
564  
565 19 ws_log2(ws, "Fail: ", bqws_error_str(err));
566  
567 // Try to send an error close message
568 19 ▶ if (ws->state.state == BQWS_STATE_OPEN && !ws->state.close_to_send) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->state.state == BQWS_STATE_OPEN && !ws->state.close_to_send) { 19 0 19
if (ws->state.state == BQWS_STATE_OPEN && !ws->state.close_to_send) { 19 0 19
569 19 bqws_msg_imp *close_msg = (bqws_msg_imp*)ws->state.error_msg_data;
570 19 close_msg->magic = BQWS_MSG_MAGIC;
571 19 close_msg->compressed = false;
572 19 close_msg->allocator.free_fn = &null_free;
573 19 close_msg->owner = ws;
574 19 close_msg->prev = NULL;
575 19 close_msg->msg.socket = ws;
576 19 close_msg->msg.capacity = sizeof(bqws_err_close_data);
577 19 close_msg->msg.size = sizeof(bqws_err_close_data);
578 19 close_msg->msg.type = BQWS_MSG_CONTROL_CLOSE;
579  
580 bqws_close_reason reason;
581 19 switch (err) {
582 2 case BQWS_ERR_LIMIT_MAX_RECV_MSG_SIZE:
583 2 reason = BQWS_CLOSE_MESSAGE_TOO_BIG;
584 2 break;
585  
586 12 case BQWS_ERR_BAD_CONTINUATION:
587 case BQWS_ERR_UNFINISHED_PARTIAL:
588 case BQWS_ERR_PARTIAL_CONTROL:
589 case BQWS_ERR_BAD_OPCODE:
590 case BQWS_ERR_RESERVED_BIT:
591 case BQWS_ERR_BAD_CLOSE:
592 12 reason = BQWS_CLOSE_PROTOCOL_ERROR;
593 12 break;
594  
595 5 case BQWS_ERR_BAD_UTF8:
596 5 reason = BQWS_CLOSE_BAD_DATA;
597 5 break;
598  
599 0 default:
600 0 reason = BQWS_CLOSE_SERVER_ERROR;
601 0 break;
602 }
603  
604 19 bqws_err_close_data *data = (bqws_err_close_data*)close_msg->msg.data;
605 19 data->code_be[0] = (uint8_t)(reason >> 8);
606 19 data->code_be[1] = (uint8_t)(reason >> 0);
607 19 memcpy(data->magic, "BQWS", 4);
608 19 data->error_be[0] = (uint8_t)(err >> 24);
609 19 data->error_be[1] = (uint8_t)(err >> 16);
610 19 data->error_be[2] = (uint8_t)(err >> 8);
611 19 data->error_be[3] = (uint8_t)(err >> 0);
612  
613 19 ws->state.close_to_send = close_msg;
614 19 ws->state.state = BQWS_STATE_CLOSING;
615 19 ws->state.start_closing_ts = bqws_get_timestamp();
616  
617 0 ▶ } else if (ws->state.state == BQWS_STATE_CONNECTING) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (ws->state.state == BQWS_STATE_CONNECTING) { 0 0 0
618  
619 // If there's an error during connection close
620 // the connection immediately
621 0 ws_close(ws);
622  
623 }
624  
625 } else {
626 bqws_mutex_unlock(&ws->err_mutex);
627 }
628  
629 // IO errors should close their respective channels
630 19 ▶ if (err == BQWS_ERR_IO_READ) ws->state.stop_read = true;
Branch: 1 branch
BranchTrueFalseTotal
if (err == BQWS_ERR_IO_READ) ws->state.stop_read = true; 0 19 19
631 19 ▶ if (err == BQWS_ERR_IO_WRITE) ws->state.stop_write = true;
Branch: 1 branch
BranchTrueFalseTotal
if (err == BQWS_ERR_IO_WRITE) ws->state.stop_write = true; 0 19 19
632  
633 bqws_mutex_unlock(&ws->state.mutex);
634  
635 19 ▶ if (ws->error_fn && should_report) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->error_fn && should_report) { 0 19 19
if (ws->error_fn && should_report) { 0 0 0
636 0 ws->error_fn(ws->error_user, ws, err);
637 }
638 19 }
639  
640 static void bqws_sha1(uint8_t digest[20], const void *data, size_t size);
641  
642 // Callback writer
643  
644 typedef struct {
645 char *ptr, *end;
646 } bqws_mem_stream;
647  
648 112 static size_t mem_stream_send(void *user, bqws_socket *ws, const void *data, size_t size)
649 {
650 // Copy as many bytes as fit in the stream
651 112 bqws_mem_stream *s = (bqws_mem_stream*)user;
652 112 size_t left = s->end - s->ptr;
653 112 size_t to_copy = size;
654 112 ▶ if (to_copy > left) to_copy = left;
Branch: 1 branch
BranchTrueFalseTotal
if (to_copy > left) to_copy = left; 0 112 112
655 112 memcpy(s->ptr, data, to_copy);
656 112 s->ptr += to_copy;
657 112 return to_copy;
658 }
659  
660 96 static size_t mem_stream_recv(void *user, bqws_socket *ws, void *data, size_t max_size, size_t min_size)
661 {
662 // Copy as many bytes as fit in the stream
663 96 bqws_mem_stream *s = (bqws_mem_stream*)user;
664 96 size_t left = s->end - s->ptr;
665 96 size_t to_copy = max_size;
666 96 ▶ if (to_copy > left) to_copy = left;
Branch: 1 branch
BranchTrueFalseTotal
if (to_copy > left) to_copy = left; 96 0 96
667 96 memcpy(data, s->ptr, to_copy);
668 96 s->ptr += to_copy;
669 96 return to_copy;
670 }
671  
672 // -- Allocation
673  
674 // Direct allocator functions. Prefer using `ws_alloc()` if there is an `bqws_socket`
675 // avaialable (which there should almost always be). These functions just call the
676 // user callbacks or defaults passing in the user pointer.
677  
678 165 void *bqws_allocator_alloc(const bqws_allocator *at, size_t size)
679 {
680 165 ▶ if (at->alloc_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (at->alloc_fn) { 0 165 165
681 // User defined alloc directly
682 0 return at->alloc_fn(at->user, size);
683 165 ▶ } else if (at->realloc_fn) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (at->realloc_fn) { 0 165 165
684 // Realloc with zero initial size
685 0 return at->realloc_fn(at->user, NULL, 0, size);
686 } else {
687 // Default: malloc()
688 165 return bqws_malloc(size);
689 }
690 }
691  
692 0 void *bqws_allocator_realloc(const bqws_allocator *at, void *ptr, size_t old_size, size_t new_size)
693 {
694 0 ▶ if (old_size == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (old_size == 0) { 0 0 0
695 // Realloc with `old_size==0` is equivalent to malloc
696 0 return bqws_allocator_alloc(at, new_size);
697 0 ▶ } else if (new_size == 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (new_size == 0) { 0 0 0
698 // Realloc with `new_size==0` is equivalent to free
699 0 bqws_allocator_free(at, ptr, old_size);
700 0 return NULL;
701 }
702  
703 0 ▶ if (at->realloc_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (at->realloc_fn) { 0 0 0
704 // User defined realloc directly
705 0 return at->realloc_fn(at->user, ptr, old_size, new_size);
706 0 ▶ } else if (at->alloc_fn) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (at->alloc_fn) { 0 0 0
707 // No realloc, but alloc is defined. Allocate and copy the data
708 // if it succeeded and free the old pointer (if free is defined)
709 0 void *new_ptr = at->alloc_fn(at->user, new_size);
710 0 ▶ if (!new_ptr) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!new_ptr) return NULL; 0 0 0
711 0 memcpy(new_ptr, ptr, old_size);
712 0 ▶ if (at->free_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (at->free_fn) { 0 0 0
713 0 at->free_fn(at->user, ptr, old_size);
714 }
715 0 return new_ptr;
716 } else {
717 // Default: realloc()
718 0 return bqws_realloc(ptr, old_size, new_size);
719 }
720 }
721  
722 267 void bqws_allocator_free(const bqws_allocator *at, void *ptr, size_t size)
723 {
724 267 ▶ if (size == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (size == 0) return; 102 165 267
725 bqws_assert(ptr != NULL);
726  
727 165 ▶ if (at->free_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (at->free_fn) { 0 165 165
728 // Use defined free directly
729 0 at->free_fn(at->user, ptr, size);
730 165 ▶ } else if (at->realloc_fn) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (at->realloc_fn) { 0 165 165
731 // Use realloc with zero new size
732 0 at->realloc_fn(at->user, ptr, size, 0);
733 } else {
734 bqws_assert(at->alloc_fn == NULL);
735  
736 // Default: free(), only if there is no user defined allocator
737 165 bqws_free(ptr, size);
738 }
739 }
740  
741 // WebSocket allocation functions. These keep track of total used memory and
742 // update the error flag.
743  
744 114 static bool ws_add_memory_used(bqws_socket *ws, size_t size)
745 {
746 // TODO: Atomics
747 bqws_mutex_lock(&ws->alloc.mutex);
748  
749 114 bool ok = (size <= ws->limits.max_memory_used - ws->alloc.memory_used);
750 114 ▶ if (ok) {
Branch: 1 branch
BranchTrueFalseTotal
if (ok) { 114 0 114
751 114 ws->alloc.memory_used += size;
752 } else {
753 0 ws_fail(ws, BQWS_ERR_LIMIT_MAX_MEMORY_USED);
754 }
755  
756 bqws_mutex_unlock(&ws->alloc.mutex);
757 114 return ok;
758 }
759  
760 216 static void ws_remove_memory_used(bqws_socket *ws, size_t size)
761 {
762 216 ▶ if (size == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (size == 0) return; 102 114 216
763  
764 // TODO: Atomics
765 bqws_mutex_lock(&ws->alloc.mutex);
766  
767 bqws_assert(ws->alloc.memory_used >= size);
768 114 ws->alloc.memory_used -= size;
769  
770 bqws_mutex_unlock(&ws->alloc.mutex);
771 }
772  
773 114 static void *ws_alloc(bqws_socket *ws, size_t size)
774 {
775 114 ▶ if (!ws_add_memory_used(ws, size)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws_add_memory_used(ws, size)) return NULL; 0 114 114
776  
777 114 void *ptr = bqws_allocator_alloc(&ws->allocator, size);
778 114 ▶ if (!ptr) ws_fail(ws, BQWS_ERR_ALLOCATOR);
Branch: 1 branch
BranchTrueFalseTotal
if (!ptr) ws_fail(ws, BQWS_ERR_ALLOCATOR); 0 114 114
779  
780 114 return ptr;
781 }
782  
783 0 static void *ws_realloc(bqws_socket *ws, void *ptr, size_t old_size, size_t new_size)
784 {
785 0 ▶ if (!ws_add_memory_used(ws, new_size)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws_add_memory_used(ws, new_size)) return NULL; 0 0 0
786 0 ws_remove_memory_used(ws, old_size);
787  
788 0 void *new_ptr = bqws_allocator_realloc(&ws->allocator, ptr, old_size, new_size);
789 0 ▶ if (!new_ptr) ws_fail(ws, BQWS_ERR_ALLOCATOR);
Branch: 1 branch
BranchTrueFalseTotal
if (!new_ptr) ws_fail(ws, BQWS_ERR_ALLOCATOR); 0 0 0
790  
791 0 return new_ptr;
792 }
793  
794 102 static void ws_free(bqws_socket *ws, void *ptr, size_t size)
795 {
796 102 ws_remove_memory_used(ws, size);
797 102 bqws_allocator_free(&ws->allocator, ptr, size);
798 102 }
799  
800 0 static char *ws_copy_str(bqws_socket *ws, const char *str)
801 {
802 0 size_t len = strlen(str) + 1;
803 0 char *dst = (char*)ws_alloc(ws, len);
804 0 ▶ if (!dst) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!dst) return NULL; 0 0 0
805 0 memcpy(dst, str, len);
806 0 return dst;
807 }
808  
809 102 static void ws_free_str(bqws_socket *ws, char *ptr)
810 {
811 102 ▶ if (!ptr) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!ptr) return; 102 0 102
812 0 ws_free(ws, ptr, strlen(ptr) + 1);
813 }
814  
815 // Message allocation
816  
817 114 static bqws_msg_imp *msg_alloc(bqws_socket *ws, bqws_msg_type type, size_t size)
818 {
819 114 size_t capacity = size;
820  
821 // Space for NULL-terminator
822 114 ▶ if (type & BQWS_MSG_TEXT) capacity += 1;
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_TEXT) capacity += 1; 42 72 114
823  
824 114 size_t alloc_size = sizeof(bqws_msg_imp) + capacity;
825 114 bqws_msg_imp *msg = (bqws_msg_imp*)ws_alloc(ws, alloc_size);
826 114 ▶ if (!msg) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg) return NULL; 0 114 114
827  
828 114 msg->magic = BQWS_MSG_MAGIC;
829 114 msg->compressed = false;
830 114 msg->owner = ws;
831 114 msg->allocator = ws->allocator;
832 114 msg->prev = NULL;
833 114 msg->msg.socket = ws;
834 114 msg->msg.type = type;
835 114 msg->msg.size = size;
836 114 msg->msg.capacity = capacity;
837  
838 114 ▶ if (type & BQWS_MSG_TEXT) {
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_TEXT) { 42 72 114
839 42 msg->msg.data[size] = '\0';
840 }
841  
842 114 return msg;
843 }
844  
845 48 static void msg_release_ownership(bqws_socket *ws, bqws_msg_imp *msg)
846 {
847 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
848 bqws_assert(msg && msg->magic == BQWS_MSG_MAGIC);
849 bqws_assert(msg->owner == ws);
850  
851 48 ws_remove_memory_used(ws, msg_alloc_size(&msg->msg));
852  
853 48 msg->owner = NULL;
854 48 }
855  
856 0 static bool msg_acquire_ownership(bqws_socket *ws, bqws_msg_imp *msg)
857 {
858 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
859 bqws_assert(msg && msg->magic == BQWS_MSG_MAGIC);
860 bqws_assert(msg->owner == NULL);
861  
862 0 ▶ if (!ws_add_memory_used(ws, msg_alloc_size(&msg->msg))) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws_add_memory_used(ws, msg_alloc_size(&msg->msg))) { 0 0 0
863 // We still own the message so need to delete it
864 0 bqws_free_msg(&msg->msg);
865 0 return false;
866 }
867 0 msg->owner = ws;
868  
869 0 return true;
870 }
871  
872 85 static void msg_free_owned(bqws_socket *ws, bqws_msg_imp *msg)
873 {
874 85 ▶ if (!msg) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg) return; 0 85 85
875 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
876 bqws_assert(msg->magic == BQWS_MSG_MAGIC);
877 bqws_assert(msg->owner == ws);
878  
879 85 msg->magic = BQWS_DELETED_MAGIC;
880 85 msg->owner = NULL;
881  
882 85 size_t size = msg_alloc_size(&msg->msg);
883  
884 // no-mutex(state): We are only referring to the address of `error_msg_data`
885 85 ▶ if ((char*)msg != ws->state.error_msg_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ((char*)msg != ws->state.error_msg_data) { 66 19 85
886 66 ws_remove_memory_used(ws, size);
887  
888 66 bqws_allocator at = msg->allocator;
889 66 bqws_allocator_free(&at, msg, size);
890 }
891 }
892  
893 80 static void msg_enqueue(bqws_msg_queue *mq, bqws_msg_imp *msg)
894 {
895 bqws_mutex_lock(&mq->mutex);
896  
897 // Adjust the last message to point to `msg` and replace
898 // it as the last in the queue
899 bqws_assert(msg && msg->magic == BQWS_MSG_MAGIC && msg->prev == NULL);
900 80 ▶ if (mq->last) {
Branch: 1 branch
BranchTrueFalseTotal
if (mq->last) { 7 73 80
901 bqws_assert(mq->first);
902 bqws_assert(mq->last->magic == BQWS_MSG_MAGIC && mq->last->prev == NULL);
903 7 mq->last->prev = msg;
904 } else {
905 bqws_assert(!mq->first);
906 73 mq->first = msg;
907 }
908 80 mq->last = msg;
909  
910 80 mq->byte_size += msg->msg.size;
911 80 mq->num_messages++;
912  
913 80 mq->total_size += msg->msg.size;
914 80 mq->total_messages++;
915  
916 bqws_mutex_unlock(&mq->mutex);
917 80 }
918  
919 334 static bqws_msg_imp *msg_dequeue(bqws_msg_queue *mq)
920 {
921 bqws_mutex_lock(&mq->mutex);
922  
923 334 bqws_msg_imp *msg = mq->first;
924  
925 334 ▶ if (msg) {
Branch: 1 branch
BranchTrueFalseTotal
if (msg) { 80 254 334
926 bqws_assert(mq->last);
927 bqws_assert(msg->magic == BQWS_MSG_MAGIC);
928  
929 80 bqws_msg_imp *prev = msg->prev;
930 80 msg->prev = NULL;
931 80 mq->first = prev;
932 80 ▶ if (prev) {
Branch: 1 branch
BranchTrueFalseTotal
if (prev) { 73 7 80
933 bqws_assert(prev->magic == BQWS_MSG_MAGIC);
934 } else {
935 bqws_assert(mq->last == msg);
936 73 mq->last = NULL;
937 }
938  
939 bqws_assert(mq->byte_size >= msg->msg.size);
940 bqws_assert(mq->num_messages > 0);
941 80 mq->byte_size -= msg->msg.size;
942 80 mq->num_messages--;
943  
944 } else {
945 bqws_assert(!mq->last);
946 }
947  
948 bqws_mutex_unlock(&mq->mutex);
949  
950 334 return msg;
951 }
952  
953 153 static void msg_init_queue(bqws_socket *ws, bqws_msg_queue *mq)
954 {
955 bqws_mutex_init(&mq->mutex);
956 153 }
957  
958 153 static void msg_free_queue(bqws_socket *ws, bqws_msg_queue *mq)
959 {
960 bqws_msg_imp *imp;
961 157 ▶ while ((imp = msg_dequeue(mq)) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
while ((imp = msg_dequeue(mq)) != 0) { 4 153 157
962 4 msg_free_owned(ws, imp);
963 }
964  
965 bqws_mutex_free(&mq->mutex);
966 153 }
967  
968 0 static void msg_queue_add_to_total(bqws_msg_queue *mq, size_t size)
969 {
970 bqws_mutex_lock(&mq->mutex);
971 0 mq->total_messages++;
972 0 mq->total_size += size;
973 bqws_mutex_unlock(&mq->mutex);
974 0 }
975  
976 0 static void msg_queue_get_stats(bqws_msg_queue *mq, bqws_io_stats *stats)
977 {
978 bqws_mutex_lock(&mq->mutex);
979  
980 0 stats->total_bytes = mq->total_size;
981 0 stats->total_messages = mq->total_messages;
982  
983 0 stats->queued_bytes = mq->byte_size;
984 0 stats->queued_messages = mq->num_messages;
985  
986 bqws_mutex_unlock(&mq->mutex);
987 0 }
988  
989 // Masking
990  
991 13 static uint32_t mask_make_key(bqws_socket *ws)
992 {
993 13 uint32_t key = 0;
994  
995 bqws_assert_locked(&ws->io.mutex);
996 13 ▶ if (!unblock_ws_secure_random(&key, sizeof(key))) {
Branch: 1 branch
BranchTrueFalseTotal
if (!unblock_ws_secure_random(&key, sizeof(key))) { 0 13 13
997 0 ws_fail(ws, BQWS_ERR_IO_WRITE);
998 0 return 0;
999 }
1000  
1001 13 return key;
1002 }
1003  
1004 61 static void mask_apply(void *data, size_t size, uint32_t mask)
1005 {
1006 61 size_t left = size;
1007  
1008 // Process SIMD width at a time
1009 61 char *data_simd = (char*)data;
1010 #if defined(BQWS_USE_SSE)
1011 {
1012 61 __m128i sse_mask = _mm_set1_epi32(mask);
1013 69 ▶ while (left >= 16) {
Branch: 1 branch
BranchTrueFalseTotal
while (left >= 16) { 8 61 69
1014 8 __m128i w = _mm_loadu_si128((__m128i*)data_simd);
1015 8 w = _mm_xor_si128(w, sse_mask);
1016 _mm_storeu_si128((__m128i*)data_simd, w);
1017 8 data_simd += 16;
1018 8 left -= 16;
1019 }
1020 }
1021 #endif
1022  
1023 // Process word at a time
1024 61 uint32_t *dst32 = (uint32_t*)data_simd;
1025 130 ▶ while (left >= 4) {
Branch: 1 branch
BranchTrueFalseTotal
while (left >= 4) { 69 61 130
1026 69 *dst32++ ^= mask;
1027 69 left -= 4;
1028 }
1029  
1030 // Mask rest
1031 61 ▶ if (left > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (left > 0) { 53 8 61
1032 bqws_assert(left < 4);
1033 uint8_t mask_bytes[4];
1034 53 memcpy(mask_bytes, &mask, 4);
1035 53 uint8_t *dst8 = (uint8_t*)dst32;
1036 53 uint8_t *src = mask_bytes;
1037 148 ▶ while (left > 0) {
Branch: 1 branch
BranchTrueFalseTotal
while (left > 0) { 95 53 148
1038 95 *dst8++ ^= *src++;
1039 95 left--;
1040 }
1041 }
1042 61 }
1043  
1044 // -- Handshake
1045  
1046 static bqws_forceinline bool str_nonempty(const char *s)
1047 {
1048 0 ▶ return s && *s;
Branch: 3 branches
BranchTrueFalseTotal
return s && *s; 0 0 0
return s && *s; 0 0 0
return s && *s; 0 0 0
1049 }
1050  
1051 0 static void hs_push_size(bqws_socket *ws, const char *data, size_t size)
1052 {
1053 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
1054  
1055 bqws_assert_locked(&ws->io.mutex);
1056  
1057 0 ▶ if (size > ws->io.handshake.capacity - ws->io.handshake.size) {
Branch: 1 branch
BranchTrueFalseTotal
if (size > ws->io.handshake.capacity - ws->io.handshake.size) { 0 0 0
1058 // Grow the buffer geometrically up to `max_handshake_size`
1059 0 size_t new_cap = ws->io.handshake.capacity * 2;
1060 0 ▶ if (new_cap == 0) new_cap = 512;
Branch: 1 branch
BranchTrueFalseTotal
if (new_cap == 0) new_cap = 512; 0 0 0
1061 0 ▶ if (new_cap > ws->limits.max_handshake_size) new_cap = ws->limits.max_handshake_size;
Branch: 1 branch
BranchTrueFalseTotal
if (new_cap > ws->limits.max_handshake_size) new_cap = ws->limits.max_handshake_size; 0 0 0
1062 0 ▶ if (new_cap == ws->io.handshake.capacity) {
Branch: 1 branch
BranchTrueFalseTotal
if (new_cap == ws->io.handshake.capacity) { 0 0 0
1063 0 ws_fail(ws, BQWS_ERR_LIMIT_MAX_HANDSHAKE_SIZE);
1064 0 return;
1065 }
1066  
1067 0 char *new_data = (char*)ws_realloc(ws, ws->io.handshake.data, ws->io.handshake.capacity, new_cap);
1068 0 ▶ if (!new_data) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!new_data) return; 0 0 0
1069 0 ws->io.handshake.data = new_data;
1070 0 ws->io.handshake.capacity = new_cap;
1071 }
1072  
1073 0 memcpy(ws->io.handshake.data + ws->io.handshake.size, data, size);
1074 0 ws->io.handshake.size += size;
1075 }
1076  
1077 0 static void hs_push(bqws_socket *ws, const char *a)
1078 {
1079 0 hs_push_size(ws, a, strlen(a));
1080 0 }
1081  
1082 0 static void hs_push2(bqws_socket *ws, const char *a, const char *b)
1083 {
1084 0 hs_push(ws, a); hs_push(ws, b);
1085 0 }
1086  
1087 0 static void hs_push3(bqws_socket *ws, const char *a, const char *b, const char *c)
1088 {
1089 0 hs_push(ws, a); hs_push(ws, b); hs_push(ws, c);
1090 0 }
1091  
1092 static const char *base64_tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1093 0 static bool hs_to_base64(void *buf, size_t buf_size, const void *data, size_t size)
1094 {
1095 bqws_assert(size == 0 || data);
1096 0 const uint8_t *b = (const uint8_t*)data;
1097  
1098 0 char *dst = (char*)buf, *end = dst + buf_size;
1099 0 ptrdiff_t left = (ptrdiff_t)size;
1100 0 ▶ while (left > 0) {
Branch: 1 branch
BranchTrueFalseTotal
while (left > 0) { 0 0 0
1101 0 ▶ if (end - dst < 5) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (end - dst < 5) return false; 0 0 0
1102  
1103 0 uint32_t a = (uint32_t)b[0] << 16u
1104 0 ▶ | (left >= 2 ? (uint32_t)b[1] : 0u) << 8u
Branch: 1 branch
BranchTrueFalseTotal
| (left >= 2 ? (uint32_t)b[1] : 0u) << 8u 0 0 0
1105 0 ▶ | (left >= 3 ? (uint32_t)b[2] : 0u);
Branch: 1 branch
BranchTrueFalseTotal
| (left >= 3 ? (uint32_t)b[2] : 0u); 0 0 0
1106 0 dst[0] = base64_tab[a >> 18];
1107 0 dst[1] = base64_tab[(a >> 12) & 0x3f];
1108 0 ▶ dst[2] = left >= 2 ? base64_tab[(a >> 6) & 0x3f] : '=';
Branch: 1 branch
BranchTrueFalseTotal
dst[2] = left >= 2 ? base64_tab[(a >> 6) & 0x3f] : '='; 0 0 0
1109 0 ▶ dst[3] = left >= 3 ? base64_tab[a & 0x3f] : '=';
Branch: 1 branch
BranchTrueFalseTotal
dst[3] = left >= 3 ? base64_tab[a & 0x3f] : '='; 0 0 0
1110  
1111 0 dst += 4;
1112 0 b += 3;
1113 0 left -= 3;
1114 }
1115  
1116 0 *dst = '\0';
1117  
1118 0 return true;
1119 }
1120  
1121 static const char *key_guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
1122 0 static void hs_solve_challenge(char dst[32], const char *key_base64)
1123 {
1124 char challenge[128];
1125 0 size_t base64_len = strlen(key_base64);
1126 0 size_t guid_len = strlen(key_guid);
1127 0 size_t challenge_len = base64_len + guid_len;
1128 bqws_assert(challenge_len <= sizeof(challenge));
1129 0 memcpy(challenge, key_base64, base64_len);
1130 0 memcpy(challenge + base64_len, key_guid, guid_len);
1131  
1132 uint8_t digest[20];
1133 0 bqws_sha1(digest, challenge, challenge_len);
1134  
1135 0 bool ret = hs_to_base64(dst, 32, digest, sizeof(digest));
1136 bqws_assert(ret == true); // 32 bytes should always be enough
1137 0 }
1138  
1139 0 static void hs_client_handshake(bqws_socket *ws, const bqws_client_opts *opts)
1140 {
1141 bqws_assert_locked(&ws->io.mutex);
1142  
1143 bqws_assert(!ws->is_server);
1144  
1145 0 ▶ const char *path = str_nonempty(opts->path) ? opts->path : "/";
Branch: 2 branches
BranchTrueFalseTotal
const char *path = str_nonempty(opts->path) ? opts->path : "/"; 0 0 0
const char *path = str_nonempty(opts->path) ? opts->path : "/"; 0 0 0
1146 0 hs_push3(ws, "GET ", path, " HTTP/1.1\r\n");
1147  
1148 // Static headers
1149 0 hs_push(ws,
1150 "Connection: Upgrade\r\n"
1151 "Upgrade: websocket\r\n"
1152 );
1153  
1154 // User headers
1155 0 ▶ if (str_nonempty(opts->host)) hs_push3(ws, "Host: ", opts->host, "\r\n");
Branch: 2 branches
BranchTrueFalseTotal
if (str_nonempty(opts->host)) hs_push3(ws, "Host: ", opts->host, "\r\n"); 0 0 0
if (str_nonempty(opts->host)) hs_push3(ws, "Host: ", opts->host, "\r\n"); 0 0 0
1156 0 ▶ if (str_nonempty(opts->origin)) hs_push3(ws, "Origin: ", opts->origin, "\r\n");
Branch: 2 branches
BranchTrueFalseTotal
if (str_nonempty(opts->origin)) hs_push3(ws, "Origin: ", opts->origin, "\r\n"); 0 0 0
if (str_nonempty(opts->origin)) hs_push3(ws, "Origin: ", opts->origin, "\r\n"); 0 0 0
1157 0 ▶ if (opts->num_protocols > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->num_protocols > 0) { 0 0 0
1158 0 hs_push(ws, "Sec-WebSocket-Protocol: ");
1159 0 ▶ for (size_t i = 0; i < opts->num_protocols; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < opts->num_protocols; i++) { 0 0 0
1160 0 ▶ hs_push2(ws, i > 0 ? ", " : "", opts->protocols[i]);
Branch: 1 branch
BranchTrueFalseTotal
hs_push2(ws, i > 0 ? ", " : "", opts->protocols[i]); 0 0 0
1161 }
1162 0 hs_push(ws, "\r\n");
1163 }
1164  
1165 // Version (fixed currently, TODO multi-version support)
1166 0 hs_push(ws, "Sec-WebSocket-Version: 13\r\n");
1167  
1168 // Random key
1169 bqws_random_entropy entropy;
1170 0 entropy.clock = clock();
1171 0 entropy.time = time(NULL);
1172 0 entropy.function_pointer = &hs_client_handshake;
1173 0 entropy.stack_pointer = &entropy;
1174 0 entropy.heap_pointer = ws;
1175 0 entropy.mask_key = mask_make_key(ws);
1176  
1177 uint8_t digest[20];
1178 0 bqws_sha1(digest, &entropy, sizeof(entropy));
1179 0 const uint8_t *key = digest;
1180  
1181 0 ▶ if (opts->use_random_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->use_random_key) { 0 0 0
1182 0 key = (const uint8_t*)opts->random_key;
1183 }
1184  
1185 // We need to retain the key until we have parsed the server handshake
1186 0 bool ret = hs_to_base64(ws->io.client_key_base64, sizeof(ws->io.client_key_base64), key, 16);
1187 bqws_assert(ret == true); // 32 bytes should always be enough
1188 0 hs_push3(ws, "Sec-WebSocket-Key: ", ws->io.client_key_base64, "\r\n");
1189  
1190 // Final CRLF
1191 0 hs_push(ws, "\r\n");
1192 0 }
1193  
1194  
1195 0 static void hs_server_handshake(bqws_socket *ws)
1196 {
1197 bqws_assert_locked(&ws->io.mutex);
1198  
1199 bqws_assert(ws->is_server);
1200 bqws_assert(ws->io.opts_from_client);
1201  
1202 // Fixed header
1203 0 hs_push(ws,
1204 "HTTP/1.1 101 Switching Protocols\r\n"
1205 "Upgrade: websocket\r\n"
1206 "Connection: Upgrade\r\n"
1207 );
1208  
1209 // Protocol
1210 bqws_mutex_lock(&ws->state.mutex);
1211 0 const char *protocol = ws->state.chosen_protocol;
1212 bqws_mutex_unlock(&ws->state.mutex);
1213  
1214 bqws_assert(protocol);
1215 0 ▶ if (*protocol && ws->io.client_has_protocol) {
Branch: 2 branches
BranchTrueFalseTotal
if (*protocol && ws->io.client_has_protocol) { 0 0 0
if (*protocol && ws->io.client_has_protocol) { 0 0 0
1216 0 hs_push3(ws, "Sec-WebSocket-Protocol: ", protocol, "\r\n");
1217 }
1218  
1219 // SHA-1 challenge
1220 char accept[32];
1221 0 hs_solve_challenge(accept, ws->io.client_key_base64);
1222 0 hs_push3(ws, "Sec-WebSocket-Accept: ", accept, "\r\n");
1223  
1224 // Final CRLF
1225 0 hs_push(ws, "\r\n");
1226  
1227 // Free the handshake state
1228 0 ws_free(ws, ws->io.opts_from_client, sizeof(bqws_client_opts));
1229 0 ws->io.opts_from_client = NULL;
1230 0 }
1231  
1232 // -- Handshake parsing
1233  
1234 0 static bool hs_parse_literal(bqws_socket *ws, size_t *pos, const char *str)
1235 {
1236 bqws_assert_locked(&ws->io.mutex);
1237  
1238 0 size_t len = strlen(str);
1239 0 ▶ if (ws->io.handshake.size - *pos < len) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->io.handshake.size - *pos < len) return false; 0 0 0
1240 0 const char *ref = ws->io.handshake.data + *pos;
1241 0 ▶ if (memcmp(ref, str, len) != 0) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (memcmp(ref, str, len) != 0) return false; 0 0 0
1242 0 *pos += len;
1243 0 return true;
1244 }
1245  
1246 0 static char *hs_parse_token(bqws_socket *ws, size_t *pos, char end)
1247 {
1248 bqws_assert_locked(&ws->io.mutex);
1249  
1250 0 size_t begin = *pos, p = begin;
1251 0 ▶ while (p != ws->io.handshake.size) {
Branch: 1 branch
BranchTrueFalseTotal
while (p != ws->io.handshake.size) { 0 0 0
1252 0 char c = ws->io.handshake.data[p];
1253 0 ▶ if (c == end) {
Branch: 1 branch
BranchTrueFalseTotal
if (c == end) { 0 0 0
1254 0 ws->io.handshake.data[p] = '\0';
1255 0 *pos = p + 1;
1256 0 return ws->io.handshake.data + begin;
1257 }
1258 0 ▶ if (c == '\r' || c == '\n') return NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (c == '\r' || c == '\n') return NULL; 0 0 0
if (c == '\r' || c == '\n') return NULL; 0 0 0
1259 0 p++;
1260 }
1261 0 return NULL;
1262 }
1263  
1264 0 static void hs_skip_space(bqws_socket *ws, size_t *pos)
1265 {
1266 bqws_assert_locked(&ws->io.mutex);
1267  
1268 0 ▶ while (*pos < ws->io.handshake.size) {
Branch: 1 branch
BranchTrueFalseTotal
while (*pos < ws->io.handshake.size) { 0 0 0
1269 0 char c = ws->io.handshake.data[*pos];
1270 0 ▶ if (c != ' ' && c != '\t') break;
Branch: 2 branches
BranchTrueFalseTotal
if (c != ' ' && c != '\t') break; 0 0 0
if (c != ' ' && c != '\t') break; 0 0 0
1271 0 ++*pos;
1272 }
1273 0 }
1274  
1275 // Case-insensitive (ASCII) string compare
1276 0 static bool streq_ic(const char *sa, const char *sb)
1277 {
1278 0 for (;;) {
1279 0 char a = *sa++, b = *sb++;
1280 0 ▶ if ((unsigned)(unsigned char)a < 0x80u) a = (char)tolower(a);
Branch: 1 branch
BranchTrueFalseTotal
if ((unsigned)(unsigned char)a < 0x80u) a = (char)tolower(a); 0 0 0
1281 0 ▶ if ((unsigned)(unsigned char)b < 0x80u) b = (char)tolower(b);
Branch: 1 branch
BranchTrueFalseTotal
if ((unsigned)(unsigned char)b < 0x80u) b = (char)tolower(b); 0 0 0
1282 0 ▶ if (a != b) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (a != b) return false; 0 0 0
1283 0 ▶ if (a == 0) return true;
Branch: 1 branch
BranchTrueFalseTotal
if (a == 0) return true; 0 0 0
1284 }
1285 }
1286  
1287 0 static bool hs_parse_client_handshake(bqws_socket *ws)
1288 {
1289 bqws_assert_locked(&ws->io.mutex);
1290  
1291 bqws_assert(ws->is_server);
1292 bqws_assert(!ws->io.opts_from_client);
1293  
1294 0 size_t pos = 0;
1295  
1296 0 bqws_client_opts *opts = (bqws_client_opts*)ws_alloc(ws, sizeof(bqws_client_opts));
1297 0 ▶ if (!opts) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!opts) return false; 0 0 0
1298 0 memset(opts, 0, sizeof(bqws_client_opts));
1299 0 ws->io.opts_from_client = opts;
1300  
1301 // GET /path HTTP/1.1
1302 0 ▶ if (!hs_parse_literal(ws, &pos, "GET")) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!hs_parse_literal(ws, &pos, "GET")) return false; 0 0 0
1303 0 hs_skip_space(ws, &pos);
1304 0 opts->path = hs_parse_token(ws, &pos, ' ');
1305 0 ▶ if (!opts->path) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!opts->path) return false; 0 0 0
1306 0 hs_skip_space(ws, &pos);
1307 0 ▶ if (!hs_parse_literal(ws, &pos, "HTTP/1.1\r\n")) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!hs_parse_literal(ws, &pos, "HTTP/1.1\r\n")) return false; 0 0 0
1308  
1309 // Headers
1310 0 ▶ while (!hs_parse_literal(ws, &pos, "\r\n")) {
Branch: 1 branch
BranchTrueFalseTotal
while (!hs_parse_literal(ws, &pos, "\r\n")) { 0 0 0
1311 0 ▶ if (opts->num_headers >= BQWS_MAX_HEADERS) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->num_headers >= BQWS_MAX_HEADERS) { 0 0 0
1312 0 ws_fail(ws, BQWS_ERR_TOO_MANY_HEADERS);
1313 0 return false;
1314 }
1315  
1316 0 bqws_header *header = &opts->headers[opts->num_headers];
1317 0 header->name = hs_parse_token(ws, &pos, ':');
1318 0 hs_skip_space(ws, &pos);
1319  
1320 0 size_t value_pos = pos;
1321 0 header->value = hs_parse_token(ws, &pos, '\r');
1322 0 ▶ if (!header->name || !header->value) return false;
Branch: 2 branches
BranchTrueFalseTotal
if (!header->name || !header->value) return false; 0 0 0
if (!header->name || !header->value) return false; 0 0 0
1323 0 ▶ if (!hs_parse_literal(ws, &pos, "\n")) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!hs_parse_literal(ws, &pos, "\n")) return false; 0 0 0
1324  
1325 0 ▶ if (streq_ic(header->name, "Host")) {
Branch: 1 branch
BranchTrueFalseTotal
if (streq_ic(header->name, "Host")) { 0 0 0
1326 0 opts->host = header->value;
1327 0 opts->num_headers++;
1328 0 ▶ } else if (streq_ic(header->name, "Origin")) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (streq_ic(header->name, "Origin")) { 0 0 0
1329 0 opts->origin = header->value;
1330 0 opts->num_headers++;
1331 0 ▶ } else if (streq_ic(header->name, "Sec-Websocket-Protocol")) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (streq_ic(header->name, "Sec-Websocket-Protocol")) { 0 0 0
1332 0 size_t cur_pos = pos;
1333 0 ws->io.client_has_protocol = true;
1334  
1335 // Parse protocols
1336 0 pos = value_pos;
1337 0 ▶ while (pos < cur_pos) {
Branch: 1 branch
BranchTrueFalseTotal
while (pos < cur_pos) { 0 0 0
1338 // Either token ',' or final token that is zero-terminated
1339 // already since it's the last thing in `header->value`.
1340 0 char *protocol = hs_parse_token(ws, &pos, ',');
1341 0 hs_skip_space(ws, &pos);
1342 0 ▶ if (!protocol) {
Branch: 1 branch
BranchTrueFalseTotal
if (!protocol) { 0 0 0
1343 0 protocol = ws->io.handshake.data + pos;
1344 0 pos = cur_pos;
1345 }
1346  
1347 0 ▶ if (opts->num_protocols >= BQWS_MAX_PROTOCOLS) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->num_protocols >= BQWS_MAX_PROTOCOLS) { 0 0 0
1348 0 ws_fail(ws, BQWS_ERR_TOO_MANY_PROTOCOLS);
1349 0 return false;
1350 }
1351 0 opts->protocols[opts->num_protocols++] = protocol;
1352 }
1353  
1354 0 pos = cur_pos;
1355 0 ▶ } else if (streq_ic(header->name, "Sec-Websocket-Key")) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (streq_ic(header->name, "Sec-Websocket-Key")) { 0 0 0
1356 0 size_t len = strlen(header->value) + 1;
1357 0 ▶ if (len > sizeof(ws->io.client_key_base64)) {
Branch: 1 branch
BranchTrueFalseTotal
if (len > sizeof(ws->io.client_key_base64)) { 0 0 0
1358 0 ws_fail(ws, BQWS_ERR_HEADER_KEY_TOO_LONG);
1359 0 return false;
1360 }
1361 0 memcpy(ws->io.client_key_base64, header->value, len);
1362 0 ▶ } else if (streq_ic(header->name, "Sec-Websocket-Version")) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (streq_ic(header->name, "Sec-Websocket-Version")) { 0 0 0
1363 // TODO: Version negotiatoin
1364 0 ▶ if (strcmp(header->value, "13") != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (strcmp(header->value, "13") != 0) { 0 0 0
1365 0 ws_fail(ws, BQWS_ERR_UNSUPPORTED_VERSION);
1366 0 return false;
1367 }
1368 } else {
1369 0 opts->num_headers++;
1370 }
1371 }
1372  
1373 // Store the end of the parsed header in case we read past the
1374 // header in the beginning.
1375 0 ws->io.handshake.read_offset = pos;
1376  
1377 0 ▶ if (!opts->host) opts->host = "";
Branch: 1 branch
BranchTrueFalseTotal
if (!opts->host) opts->host = ""; 0 0 0
1378 0 ▶ if (!opts->origin) opts->origin = "";
Branch: 1 branch
BranchTrueFalseTotal
if (!opts->origin) opts->origin = ""; 0 0 0
1379  
1380 0 return true;
1381 }
1382  
1383 0 static bool hs_parse_server_handshake(bqws_socket *ws)
1384 {
1385 bqws_assert_locked(&ws->io.mutex);
1386  
1387 bqws_assert(!ws->is_server);
1388  
1389 0 size_t pos = 0;
1390  
1391 // HTTP/1.1 101 Switching Protocols
1392 0 ▶ if (!hs_parse_literal(ws, &pos, "HTTP/1.1 101")) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!hs_parse_literal(ws, &pos, "HTTP/1.1 101")) return false; 0 0 0
1393 0 hs_parse_token(ws, &pos, '\r'); // Skip description
1394 0 ▶ if (!hs_parse_literal(ws, &pos, "\n")) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!hs_parse_literal(ws, &pos, "\n")) return false; 0 0 0
1395  
1396 // Headers
1397 0 ▶ while (!hs_parse_literal(ws, &pos, "\r\n")) {
Branch: 1 branch
BranchTrueFalseTotal
while (!hs_parse_literal(ws, &pos, "\r\n")) { 0 0 0
1398 // TODO: Keep headers?
1399  
1400 bqws_header header;
1401 0 header.name = hs_parse_token(ws, &pos, ':');
1402 0 hs_skip_space(ws, &pos);
1403  
1404 0 header.value = hs_parse_token(ws, &pos, '\r');
1405 0 ▶ if (!header.name || !header.value) return false;
Branch: 2 branches
BranchTrueFalseTotal
if (!header.name || !header.value) return false; 0 0 0
if (!header.name || !header.value) return false; 0 0 0
1406 0 ▶ if (!hs_parse_literal(ws, &pos, "\n")) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!hs_parse_literal(ws, &pos, "\n")) return false; 0 0 0
1407  
1408 0 ▶ if (streq_ic(header.name, "Sec-Websocket-Accept")) {
Branch: 1 branch
BranchTrueFalseTotal
if (streq_ic(header.name, "Sec-Websocket-Accept")) { 0 0 0
1409  
1410 // Check the SHA of the challenge
1411 char reference[32];
1412 0 hs_solve_challenge(reference, ws->io.client_key_base64);
1413 0 ▶ if (strcmp(header.value, reference) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (strcmp(header.value, reference) != 0) { 0 0 0
1414 0 ws_fail(ws, BQWS_ERR_HEADER_BAD_ACCEPT);
1415 0 return false;
1416 }
1417  
1418 0 ▶ } else if (streq_ic(header.name, "Sec-Websocket-Protocol")) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (streq_ic(header.name, "Sec-Websocket-Protocol")) { 0 0 0
1419 // Protocol that the server chose
1420  
1421 // Keep the first one if there's duplicates
1422 bqws_mutex_lock(&ws->state.mutex);
1423 0 ▶ if (!ws->state.chosen_protocol) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->state.chosen_protocol) { 0 0 0
1424 0 char *copy = ws_copy_str(ws, header.value);
1425  
1426 0 ▶ if (!ws->state.chosen_protocol) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->state.chosen_protocol) { 0 0 0
1427 0 ws->state.chosen_protocol = copy;
1428 } else {
1429 0 ws_free_str(ws, copy);
1430 }
1431 }
1432 bqws_mutex_unlock(&ws->state.mutex);
1433 }
1434 }
1435  
1436 // Store the end of the parsed header in case we read past the
1437 // header in the beginning.
1438 0 ws->io.handshake.read_offset = pos;
1439  
1440 // If the server didn't choose any protocol set it as ""
1441 bqws_mutex_lock(&ws->state.mutex);
1442 0 ▶ if (!ws->state.chosen_protocol) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->state.chosen_protocol) { 0 0 0
1443 0 char *copy = ws_copy_str(ws, "");
1444  
1445 0 ▶ if (!ws->state.chosen_protocol) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->state.chosen_protocol) { 0 0 0
1446 0 ws->state.chosen_protocol = copy;
1447 } else {
1448 0 ws_free_str(ws, copy);
1449 }
1450 }
1451 bqws_mutex_unlock(&ws->state.mutex);
1452  
1453 0 return true;
1454 }
1455  
1456 0 static void hs_finish_handshake(bqws_socket *ws)
1457 {
1458 bqws_assert_locked(&ws->io.mutex);
1459  
1460 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
1461  
1462 0 ws_log(ws, "State: OPEN");
1463  
1464 bqws_mutex_lock(&ws->state.mutex);
1465 0 ws->state.state = BQWS_STATE_OPEN;
1466 bqws_mutex_unlock(&ws->state.mutex);
1467  
1468 // Free the handshake buffer
1469 0 ws_free(ws, ws->io.handshake.data, ws->io.handshake.capacity);
1470 0 ws->io.handshake.data = NULL;
1471 0 ws->io.handshake.size = 0;
1472 0 ws->io.handshake.capacity = 0;
1473  
1474 // Notify IO that the connection is open
1475 0 ▶ if (ws->user_io.notify_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.notify_fn) { 0 0 0
1476 0 ws->user_io.notify_fn(ws->user_io.user, ws);
1477 }
1478 }
1479  
1480 0 static void hs_store_handshake_overflow(bqws_socket *ws)
1481 {
1482 bqws_assert_locked(&ws->io.mutex);
1483  
1484 0 size_t offset = ws->io.handshake.read_offset;
1485 0 size_t left = ws->io.handshake.size - offset;
1486 0 ▶ if (left == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (left == 0) return; 0 0 0
1487  
1488 0 ws->io.handshake_overflow.data = (char*)ws_alloc(ws, left);
1489 0 ▶ if (!ws->io.handshake_overflow.data) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->io.handshake_overflow.data) return; 0 0 0
1490 0 memcpy(ws->io.handshake_overflow.data, ws->io.handshake.data + offset, left);
1491 0 ws->io.handshake_overflow.capacity = left;
1492 0 ws->io.handshake_overflow.size = left;
1493 }
1494  
1495 // Control messages
1496  
1497 25 static void ws_enqueue_send(bqws_socket *ws, bqws_msg_imp *msg)
1498 {
1499 25 msg_enqueue(&ws->send_queue, msg);
1500  
1501 25 ▶ if (ws->user_io.notify_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.notify_fn) { 0 25 25
1502 0 ws->user_io.notify_fn(ws->user_io.user, ws);
1503 }
1504 25 }
1505  
1506 48 static void ws_enqueue_recv(bqws_socket *ws, bqws_msg_imp *msg)
1507 {
1508 // If the user callback returns true the message won't be
1509 // enqueued to the receive queue.
1510 48 ▶ if (ws->message_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->message_fn) { 0 48 48
1511 0 msg_release_ownership(ws, msg);
1512 0 ▶ if (ws->message_fn(ws->message_user, ws, &msg->msg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->message_fn(ws->message_user, ws, &msg->msg)) { 0 0 0
1513 // Message was consumed and won't be processed so add
1514 // it to the total count
1515 0 msg_queue_add_to_total(&ws->recv_queue, msg->msg.size);
1516 }
1517 0 ▶ if (!msg_acquire_ownership(ws, msg)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg_acquire_ownership(ws, msg)) return; 0 0 0
1518 }
1519  
1520 48 msg_enqueue(&ws->recv_queue, msg);
1521 }
1522  
1523 25 static bool unblock_bqws_valid_close_code(uint16_t code)
1524 {
1525 25 ▶ return ((code >= 1000 && code <= 1014)
Branch: 1 branch
BranchTrueFalseTotal
return ((code >= 1000 && code <= 1014) 25 0 25
1526 25 ▶ && code != 1004 && code != 1005 && code != 1006)
Branch: 3 branches
BranchTrueFalseTotal
&& code != 1004 && code != 1005 && code != 1006) 25 0 25
&& code != 1004 && code != 1005 && code != 1006) 23 2 25
&& code != 1004 && code != 1005 && code != 1006) 0 23 23
1527 50 ▶ || (code >= 3000 && code <= 4999);
Branch: 3 branches
BranchTrueFalseTotal
|| (code >= 3000 && code <= 4999); 25 0 25
|| (code >= 3000 && code <= 4999); 0 2 2
|| (code >= 3000 && code <= 4999); 0 0 0
1528 }
1529  
1530 90 static void unblock_bqws_utf8_reset(unblock_bqws_utf8_state *state)
1531 {
1532 90 memset(state, 0, sizeof(*state));
1533 90 state->next_min = 0x80;
1534 90 state->next_max = 0xbf;
1535 90 }
1536  
1537 390 static bool unblock_bqws_utf8_feed_byte(
1538 unblock_bqws_utf8_state *state, uint8_t byte)
1539 {
1540 390 ▶ if (state->remaining == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (state->remaining == 0) { 366 24 390
1541 366 ▶ if (byte <= 0x7f) return true;
Branch: 1 branch
BranchTrueFalseTotal
if (byte <= 0x7f) return true; 346 20 366
1542  
1543 20 state->next_min = 0x80;
1544 20 state->next_max = 0xbf;
1545  
1546 20 ▶ if (byte >= 0xc2 && byte <= 0xdf) {
Branch: 2 branches
BranchTrueFalseTotal
if (byte >= 0xc2 && byte <= 0xdf) { 20 0 20
if (byte >= 0xc2 && byte <= 0xdf) { 8 12 20
1547 8 state->codepoint = (uint32_t)(byte & 0x1f);
1548 8 state->minimum = 0x80;
1549 8 state->remaining = 1;
1550 12 ▶ } else if (byte >= 0xe0 && byte <= 0xef) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (byte >= 0xe0 && byte <= 0xef) { 12 0 12
} else if (byte >= 0xe0 && byte <= 0xef) { 7 5 12
1551 7 state->codepoint = (uint32_t)(byte & 0x0f);
1552 7 state->minimum = 0x800;
1553 7 state->remaining = 2;
1554 7 ▶ if (byte == 0xe0) state->next_min = 0xa0;
Branch: 1 branch
BranchTrueFalseTotal
if (byte == 0xe0) state->next_min = 0xa0; 0 7 7
1555 7 ▶ if (byte == 0xed) state->next_max = 0x9f;
Branch: 1 branch
BranchTrueFalseTotal
if (byte == 0xed) state->next_max = 0x9f; 0 7 7
1556 5 ▶ } else if (byte >= 0xf0 && byte <= 0xf4) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (byte >= 0xf0 && byte <= 0xf4) { 5 0 5
} else if (byte >= 0xf0 && byte <= 0xf4) { 2 3 5
1557 2 state->codepoint = (uint32_t)(byte & 0x07);
1558 2 state->minimum = 0x10000;
1559 2 state->remaining = 3;
1560 2 ▶ if (byte == 0xf0) state->next_min = 0x90;
Branch: 1 branch
BranchTrueFalseTotal
if (byte == 0xf0) state->next_min = 0x90; 0 2 2
1561 2 ▶ if (byte == 0xf4) state->next_max = 0x8f;
Branch: 1 branch
BranchTrueFalseTotal
if (byte == 0xf4) state->next_max = 0x8f; 2 0 2
1562 } else {
1563 3 return false;
1564 }
1565 17 return true;
1566 }
1567  
1568 24 ▶ if (byte < state->next_min || byte > state->next_max)
Branch: 2 branches
BranchTrueFalseTotal
if (byte < state->next_min || byte > state->next_max) 24 0 24
if (byte < state->next_min || byte > state->next_max) 2 22 24
1569 2 return false;
1570  
1571 22 state->codepoint = (state->codepoint << 6) | (uint32_t)(byte & 0x3f);
1572 22 state->remaining--;
1573 22 state->next_min = 0x80;
1574 22 state->next_max = 0xbf;
1575  
1576 22 ▶ if (state->remaining == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (state->remaining == 0) { 15 7 22
1577 15 ▶ if (state->codepoint < state->minimum
Branch: 1 branch
BranchTrueFalseTotal
if (state->codepoint < state->minimum 15 0 15
1578 15 ▶ || state->codepoint > 0x10ffff
Branch: 1 branch
BranchTrueFalseTotal
|| state->codepoint > 0x10ffff 15 0 15
1579 15 ▶ || (state->codepoint >= 0xd800
Branch: 1 branch
BranchTrueFalseTotal
|| (state->codepoint >= 0xd800 0 15 15
1580 0 ▶ && state->codepoint <= 0xdfff)) {
Branch: 1 branch
BranchTrueFalseTotal
&& state->codepoint <= 0xdfff)) { 0 0 0
1581 0 return false;
1582 }
1583 }
1584  
1585 22 return true;
1586 }
1587  
1588 109 static uint8_t unblock_bqws_unmask_byte(
1589 uint8_t byte, uint32_t mask, size_t offset)
1590 {
1591 uint8_t mask_bytes[4];
1592 109 memcpy(mask_bytes, &mask, sizeof(mask_bytes));
1593 109 return (uint8_t)(byte ^ mask_bytes[offset & 3]);
1594 }
1595  
1596 20 static bool unblock_bqws_utf8_feed_payload(
1597 bqws_msg_buffer *buf,
1598 const char *data,
1599 size_t payload_offset,
1600 size_t size)
1601 {
1602 159 ▶ for (size_t i = 0; i < size; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < size; i++) { 142 17 159
1603 142 uint8_t byte = (uint8_t)data[i];
1604 142 ▶ if (buf->masked) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->masked) { 109 33 142
1605 109 byte = unblock_bqws_unmask_byte(
1606 byte, buf->mask_key, payload_offset + i);
1607 }
1608 142 ▶ if (!unblock_bqws_utf8_feed_byte(&buf->utf8, byte))
Branch: 1 branch
BranchTrueFalseTotal
if (!unblock_bqws_utf8_feed_byte(&buf->utf8, byte)) 3 139 142
1609 3 return false;
1610 }
1611 17 return true;
1612 }
1613  
1614 44 static bool unblock_bqws_valid_utf8(const uint8_t *s, size_t n)
1615 {
1616 unblock_bqws_utf8_state state;
1617 44 unblock_bqws_utf8_reset(&state);
1618  
1619 290 ▶ for (size_t i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < n; i++) { 248 42 290
1620 248 ▶ if (!unblock_bqws_utf8_feed_byte(&state, s[i]))
Branch: 1 branch
BranchTrueFalseTotal
if (!unblock_bqws_utf8_feed_byte(&state, s[i])) 2 246 248
1621 2 return false;
1622 }
1623  
1624 42 return state.remaining == 0;
1625 }
1626  
1627 27 static void ws_handle_control(bqws_socket *ws, bqws_msg_imp *msg)
1628 {
1629 27 bqws_msg_type type = msg->msg.type;
1630 27 bqws_msg_imp *msg_to_enqueue = msg;
1631  
1632 27 ▶ if (type == BQWS_MSG_CONTROL_CLOSE) {
Branch: 1 branch
BranchTrueFalseTotal
if (type == BQWS_MSG_CONTROL_CLOSE) { 17 10 27
1633  
1634 17 ▶ if (msg->msg.size == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (msg->msg.size == 1) { 2 15 17
1635 2 msg_free_owned(ws, msg);
1636 2 ws_fail(ws, BQWS_ERR_BAD_CLOSE);
1637 2 return;
1638 }
1639 15 ▶ if (msg->msg.size >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (msg->msg.size >= 2) { 15 0 15
1640 15 uint16_t code = (uint16_t)(
1641 15 ((uint16_t)(uint8_t)msg->msg.data[0] << 8)
1642 15 | (uint16_t)(uint8_t)msg->msg.data[1]);
1643 15 ▶ if (!unblock_bqws_valid_close_code(code)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!unblock_bqws_valid_close_code(code)) { 2 13 15
1644 2 msg_free_owned(ws, msg);
1645 2 ws_fail(ws, BQWS_ERR_BAD_CLOSE);
1646 2 return;
1647 }
1648 13 ▶ if (!unblock_bqws_valid_utf8(
Branch: 1 branch
BranchTrueFalseTotal
if (!unblock_bqws_valid_utf8( 2 11 13
1649 13 (const uint8_t *)msg->msg.data + 2,
1650 13 msg->msg.size - 2)) {
1651 2 msg_free_owned(ws, msg);
1652 2 ws_fail(ws, BQWS_ERR_BAD_UTF8);
1653 2 return;
1654 }
1655 }
1656  
1657 /*
1658 * Upstream retains the incoming Close object for the automatic echo.
1659 * Only copy a validated Close for application delivery. Allocating the
1660 * copy before validation leaks it on rejected Close frames.
1661 */
1662 11 ▶ if (ws->recv_control_messages) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->recv_control_messages) { 11 0 11
1663 11 bqws_msg_imp *copy = msg_alloc(ws, type, msg->msg.size);
1664 11 ▶ if (!copy) {
Branch: 1 branch
BranchTrueFalseTotal
if (!copy) { 0 11 11
1665 0 msg_free_owned(ws, msg);
1666 0 return;
1667 }
1668 11 memcpy(copy->msg.data, msg->msg.data, msg->msg.size);
1669 11 msg_to_enqueue = copy;
1670 }
1671  
1672 bqws_mutex_lock(&ws->state.mutex);
1673  
1674 // Set peer close reason from the message
1675 11 ▶ if (msg->msg.size >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (msg->msg.size >= 2) { 11 0 11
1676 11 ws->state.peer_reason = (bqws_close_reason)(
1677 11 ((uint32_t)(uint8_t)msg->msg.data[0] << 8) |
1678 11 ((uint32_t)(uint8_t)msg->msg.data[1] << 0) );
1679 } else {
1680 0 ws->state.peer_reason = BQWS_CLOSE_NO_REASON;
1681 }
1682  
1683 // Set unknown error if the connection was closed with an error
1684 11 ▶ if (ws->state.peer_reason != BQWS_CLOSE_NORMAL && ws->state.peer_reason != BQWS_CLOSE_GOING_AWAY) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->state.peer_reason != BQWS_CLOSE_NORMAL && ws->state.peer_reason != BQWS_CLOSE_GOING_AWAY) { 0 11 11
if (ws->state.peer_reason != BQWS_CLOSE_NORMAL && ws->state.peer_reason != BQWS_CLOSE_GOING_AWAY) { 0 0 0
1685 0 ws->state.peer_err = BQWS_ERR_UNKNOWN;
1686 }
1687  
1688 // Potentially patch bqws-specific info
1689 11 ▶ if (msg->msg.size == sizeof(bqws_err_close_data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (msg->msg.size == sizeof(bqws_err_close_data)) { 0 11 11
1690 0 bqws_err_close_data *data = (bqws_err_close_data*)msg->msg.data;
1691 0 ▶ if (!memcmp(data->magic, "BQWS", 4)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!memcmp(data->magic, "BQWS", 4)) { 0 0 0
1692 0 ws->state.peer_err = (bqws_error)(
1693 0 ((uint32_t)(uint8_t)data->error_be[0] << 24) |
1694 0 ((uint32_t)(uint8_t)data->error_be[1] << 16) |
1695 0 ((uint32_t)(uint8_t)data->error_be[2] << 8) |
1696 0 ((uint32_t)(uint8_t)data->error_be[3] << 0) );
1697 }
1698 }
1699  
1700 // Echo the close message back
1701 11 ▶ if (!ws->state.close_to_send) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->state.close_to_send) { 11 0 11
1702 11 ws->state.close_to_send = msg;
1703  
1704 // Don't free the message as it will be re-sent
1705 11 msg = NULL;
1706 }
1707  
1708 // Peer has closed connection so we go directly to CLOSED
1709 11 ▶ if (ws->state.state == BQWS_STATE_OPEN) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.state == BQWS_STATE_OPEN) { 5 6 11
1710 5 ws_log(ws, "State: CLOSING (received Close from peer)");
1711 5 ws->state.start_closing_ts = bqws_get_timestamp();
1712 5 ws->state.state = BQWS_STATE_CLOSING;
1713 }
1714  
1715 11 ws->state.stop_read = true;
1716 11 ws->state.close_received = true;
1717 11 ▶ if (ws->state.close_sent) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.close_sent) { 6 5 11
1718 6 ws_close(ws);
1719 }
1720  
1721 bqws_mutex_unlock(&ws->state.mutex);
1722  
1723 10 ▶ } else if (type == BQWS_MSG_CONTROL_PING) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (type == BQWS_MSG_CONTROL_PING) { 8 2 10
1724 8 ▶ if (ws->recv_control_messages) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->recv_control_messages) { 8 0 8
1725 // We want to re-use the PING message to send it back
1726 // so we need to copy it for receiving
1727 8 bqws_msg_imp *copy = msg_alloc(ws, type, msg->msg.size);
1728 8 ▶ if (!copy) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!copy) return; 0 8 8
1729 8 memcpy(copy->msg.data, msg->msg.data, msg->msg.size);
1730 8 msg_to_enqueue = copy;
1731 }
1732  
1733 // Turn every PING into a PONG. Upstream intentionally retains only
1734 // the latest PONG; retain all of them so each received PING can be
1735 // answered independently.
1736 8 msg->msg.type = BQWS_MSG_CONTROL_PONG;
1737 8 ws_enqueue_send(ws, msg);
1738  
1739 // Don't free the message as it is now owned by the send queue.
1740 8 msg = NULL;
1741  
1742 } else if (type == BQWS_MSG_CONTROL_PONG) {
1743 // PONG messages don't require any kind of handling
1744 } else {
1745 bqws_assert(0 && "Unexpected control message");
1746 }
1747  
1748 // Receive control messages
1749 21 ▶ if (ws->recv_control_messages) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->recv_control_messages) { 21 0 21
1750 21 ws_enqueue_recv(ws, msg_to_enqueue);
1751 21 ▶ if (msg && msg != msg_to_enqueue) {
Branch: 2 branches
BranchTrueFalseTotal
if (msg && msg != msg_to_enqueue) { 2 19 21
if (msg && msg != msg_to_enqueue) { 0 2 2
1752 0 msg_free_owned(ws, msg);
1753 }
1754 0 ▶ } else if (msg) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (msg) { 0 0 0
1755 0 msg_free_owned(ws, msg);
1756 }
1757 }
1758  
1759 // Input / output
1760  
1761 // Read data into a buffer, returns amount of bytes used read.
1762 // Returns 0 and sets `ws->err` if parsing fails.
1763  
1764 0 static size_t ws_recv_from_handshake_overflow(void *user, bqws_socket *ws, void *data, size_t max_size, size_t min_size)
1765 {
1766 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
1767 bqws_assert_locked(&ws->io.mutex);
1768  
1769 0 size_t offset = ws->io.handshake_overflow.read_offset;
1770 0 size_t left = ws->io.handshake_overflow.size - offset;
1771 0 size_t to_copy = max_size;
1772 0 ▶ if (to_copy > left) to_copy = left;
Branch: 1 branch
BranchTrueFalseTotal
if (to_copy > left) to_copy = left; 0 0 0
1773 0 memcpy(data, ws->io.handshake_overflow.data + offset, to_copy);
1774 0 ws->io.handshake_overflow.read_offset += to_copy;
1775 0 return to_copy;
1776 }
1777  
1778 0 static bool ws_read_handshake(bqws_socket *ws, bqws_io_recv_fn recv_fn, void *user)
1779 {
1780 bqws_assert_locked(&ws->io.mutex);
1781  
1782 0 for (;;) {
1783 0 ▶ if (ws->io.handshake.size == ws->io.handshake.capacity) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->io.handshake.size == ws->io.handshake.capacity) { 0 0 0
1784 // Grow the buffer geometrically up to `max_handshake_size`
1785 0 size_t new_cap = ws->io.handshake.capacity * 2;
1786 0 ▶ if (new_cap == 0) new_cap = 512;
Branch: 1 branch
BranchTrueFalseTotal
if (new_cap == 0) new_cap = 512; 0 0 0
1787 0 ▶ if (new_cap > ws->limits.max_handshake_size) new_cap = ws->limits.max_handshake_size;
Branch: 1 branch
BranchTrueFalseTotal
if (new_cap > ws->limits.max_handshake_size) new_cap = ws->limits.max_handshake_size; 0 0 0
1788 0 ▶ if (new_cap == ws->io.handshake.capacity) {
Branch: 1 branch
BranchTrueFalseTotal
if (new_cap == ws->io.handshake.capacity) { 0 0 0
1789 0 ws_fail(ws, BQWS_ERR_LIMIT_MAX_HANDSHAKE_SIZE);
1790 0 return false;
1791 }
1792  
1793 0 char *data = (char*)ws_realloc(ws, ws->io.handshake.data, ws->io.handshake.capacity, new_cap);
1794 0 ▶ if (!data) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!data) return false; 0 0 0
1795 0 ws->io.handshake.data = data;
1796 0 ws->io.handshake.capacity = new_cap;
1797 }
1798  
1799 // TODO: min_size can be up to 4 depending on the suffix of the buffer
1800  
1801 // Read some data
1802 0 size_t to_read = ws->io.handshake.capacity - ws->io.handshake.size;
1803 0 size_t num_read = recv_fn(user, ws, ws->io.handshake.data + ws->io.handshake.size, to_read, 1);
1804 0 ▶ if (num_read == 0) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == 0) return false; 0 0 0
1805 0 ▶ if (num_read == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == SIZE_MAX) { 0 0 0
1806 0 ws_fail(ws, BQWS_ERR_IO_READ);
1807 0 return false;
1808 }
1809 bqws_assert(num_read <= to_read);
1810 0 ws->io.handshake.size += num_read;
1811  
1812 // Scan for \r\n\r\n
1813 0 ptrdiff_t begin = (ptrdiff_t)ws->io.handshake.size - num_read - 4;
1814 0 ▶ if (begin < 0) begin = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (begin < 0) begin = 0; 0 0 0
1815 0 char *ptr = ws->io.handshake.data + begin;
1816 0 char *end = ws->io.handshake.data + ws->io.handshake.size;
1817 0 ▶ while ((ptr = (char*)memchr(ptr, '\r', end - ptr)) != NULL) {
Branch: 1 branch
BranchTrueFalseTotal
while ((ptr = (char*)memchr(ptr, '\r', end - ptr)) != NULL) { 0 0 0
1818 0 ▶ if (end - ptr >= 4 && !memcmp(ptr, "\r\n\r\n", 4)) {
Branch: 2 branches
BranchTrueFalseTotal
if (end - ptr >= 4 && !memcmp(ptr, "\r\n\r\n", 4)) { 0 0 0
if (end - ptr >= 4 && !memcmp(ptr, "\r\n\r\n", 4)) { 0 0 0
1819 0 return true;
1820 } else {
1821 0 ptr++;
1822 }
1823 }
1824  
1825 0 ▶ if (num_read != to_read) break;
Branch: 1 branch
BranchTrueFalseTotal
if (num_read != to_read) break; 0 0 0
1826 }
1827  
1828 0 return false;
1829 }
1830  
1831 121 static bool ws_read_data(bqws_socket *ws, bqws_io_recv_fn recv_fn, void *user)
1832 {
1833 bqws_assert_locked(&ws->io.mutex);
1834 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
1835  
1836 121 bqws_msg_buffer *buf = &ws->io.recv_buf;
1837  
1838 bqws_state state;
1839  
1840 bqws_mutex_lock(&ws->state.mutex);
1841 121 ▶ if (ws->state.stop_read) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.stop_read) { 11 110 121
1842 bqws_mutex_unlock(&ws->state.mutex);
1843 11 return false;
1844 }
1845 110 state = ws->state.state;
1846 bqws_mutex_unlock(&ws->state.mutex);
1847  
1848 110 ▶ if (state == BQWS_STATE_CONNECTING) {
Branch: 1 branch
BranchTrueFalseTotal
if (state == BQWS_STATE_CONNECTING) { 0 110 110
1849  
1850 0 ▶ if (ws->is_server) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->is_server) { 0 0 0
1851 // Server: read the client handshake first, after it's done wait for
1852 // `ws_write_data()` to set `ws->state == BQWS_STATE_OPEN`
1853 0 ▶ if (!ws->io.client_handshake_done) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->io.client_handshake_done) { 0 0 0
1854 // Read the client handshake
1855 0 ▶ if (ws_read_handshake(ws, recv_fn, user)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws_read_handshake(ws, recv_fn, user)) { 0 0 0
1856 0 ▶ if (!hs_parse_client_handshake(ws)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hs_parse_client_handshake(ws)) { 0 0 0
1857 0 ws_fail(ws, BQWS_ERR_HEADER_PARSE);
1858 0 return false;
1859 }
1860 0 ws->io.client_handshake_done = true;
1861  
1862 // Re-use the handshake buffer for the response, but copy
1863 // remaining data to be read later
1864 0 hs_store_handshake_overflow(ws);
1865 0 ws->io.handshake.size = 0;
1866  
1867 // Notify IO that there is a handshake to send
1868 0 ▶ if (ws->user_io.notify_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.notify_fn) { 0 0 0
1869 0 ws->user_io.notify_fn(ws->user_io.user, ws);
1870 }
1871 }
1872 }
1873  
1874 // Wait that the response is sent
1875 0 return false;
1876 } else {
1877 // Client: Send the request first before trying to read the response
1878 0 ▶ if (!ws->io.client_handshake_done) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->io.client_handshake_done) return false; 0 0 0
1879 0 ▶ if (!ws_read_handshake(ws, recv_fn, user)) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws_read_handshake(ws, recv_fn, user)) return false; 0 0 0
1880  
1881 0 ▶ if (!hs_parse_server_handshake(ws)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hs_parse_server_handshake(ws)) { 0 0 0
1882 0 ws_fail(ws, BQWS_ERR_HEADER_PARSE);
1883 0 return false;
1884 }
1885  
1886 // Store remaining data before deleting the handshake
1887 0 hs_store_handshake_overflow(ws);
1888  
1889 // Client handshake is done!
1890 0 hs_finish_handshake(ws);
1891 }
1892 }
1893  
1894 // If there's still data in the handshake buffer empty it before
1895 // reading any new data
1896 110 ▶ if (ws->io.handshake_overflow.data && recv_fn != &ws_recv_from_handshake_overflow) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->io.handshake_overflow.data && recv_fn != &ws_recv_from_handshake_overflow) { 0 110 110
if (ws->io.handshake_overflow.data && recv_fn != &ws_recv_from_handshake_overflow) { 0 0 0
1897  
1898 // Read from the handshake until we reach the end
1899 0 ▶ while (!ws->err && ws->io.handshake_overflow.read_offset < ws->io.handshake_overflow.size) {
Branch: 2 branches
BranchTrueFalseTotal
while (!ws->err && ws->io.handshake_overflow.read_offset < ws->io.handshake_overflow.size) { 0 0 0
while (!ws->err && ws->io.handshake_overflow.read_offset < ws->io.handshake_overflow.size) { 0 0 0
1900 0 ▶ if (!ws_read_data(ws, &ws_recv_from_handshake_overflow, NULL)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws_read_data(ws, &ws_recv_from_handshake_overflow, NULL)) { 0 0 0
1901 0 return false;
1902 }
1903 }
1904  
1905 0 ▶ if (ws->err) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return false; 0 0 0
1906  
1907 // Free the handshake
1908 0 ws_free(ws, ws->io.handshake_overflow.data, ws->io.handshake_overflow.capacity);
1909 0 ws->io.handshake_overflow.data = NULL;
1910 0 ws->io.handshake_overflow.size = 0;
1911 0 ws->io.handshake_overflow.capacity = 0;
1912  
1913 // Continue with reading from the actual data source
1914 }
1915  
1916 // Header has not been parsed yet
1917 110 ▶ if (!buf->msg) {
Branch: 1 branch
BranchTrueFalseTotal
if (!buf->msg) { 109 1 110
1918  
1919 // Check if we can fit a new message to the receive queue
1920 109 ▶ if (ws->recv_queue.num_messages >= ws->limits.max_recv_queue_messages
Branch: 1 branch
BranchTrueFalseTotal
if (ws->recv_queue.num_messages >= ws->limits.max_recv_queue_messages 109 0 109
1921 109 ▶ || ws->recv_queue.byte_size >= ws->limits.max_recv_queue_size) {
Branch: 1 branch
BranchTrueFalseTotal
|| ws->recv_queue.byte_size >= ws->limits.max_recv_queue_size) { 0 109 109
1922 0 return false;
1923 }
1924  
1925 // We need to read at least two bytes to determine
1926 // the header size
1927 109 ▶ if (buf->header_size == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_size == 0) { 109 0 109
1928 109 ▶ if (buf->header_offset < 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_offset < 2) { 94 15 109
1929 94 size_t to_read = sizeof(ws->io.recv_header) - buf->header_offset;
1930 94 size_t min_read = 2 - buf->header_offset;
1931 94 size_t num_read = recv_fn(user, ws, ws->io.recv_header + buf->header_offset, to_read, min_read);
1932 94 ▶ if (num_read == 0) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == 0) return false; 35 59 94
1933 59 ▶ if (num_read == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == SIZE_MAX) { 0 59 59
1934 0 ws_fail(ws, BQWS_ERR_IO_READ);
1935 0 return false;
1936 }
1937 bqws_assert(num_read <= to_read);
1938 59 buf->header_offset += num_read;
1939  
1940 59 ▶ if (ws->ping_interval != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->ping_interval != SIZE_MAX) { 0 59 59
1941 0 ws->io.last_read_ts = bqws_get_timestamp();
1942 }
1943 }
1944  
1945 74 ▶ if (buf->header_offset < 2) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_offset < 2) return false; 0 74 74
1946  
1947 74 uint8_t mask_len = ws->io.recv_header[1];
1948 74 uint32_t len = mask_len & 0x7f;
1949  
1950 // Minimum header size
1951 74 size_t header_size = 2;
1952  
1953 // MASK bit set: contains 32-bit mask field
1954 74 ▶ if (mask_len & 0x80) header_size += 4;
Branch: 1 branch
BranchTrueFalseTotal
if (mask_len & 0x80) header_size += 4; 60 14 74
1955  
1956 // 16/64-bit message length
1957 74 ▶ if (len == 126) header_size += 2;
Branch: 1 branch
BranchTrueFalseTotal
if (len == 126) header_size += 2; 0 74 74
1958 74 ▶ else if (len == 127) header_size += 8;
Branch: 1 branch
BranchTrueFalseTotal
else if (len == 127) header_size += 8; 0 74 74
1959  
1960 74 buf->header_size = header_size;
1961 bqws_assert(buf->header_size <= sizeof(ws->io.recv_header));
1962 }
1963  
1964 // Read more header data if we need it
1965 74 ▶ if (buf->header_offset < buf->header_size) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_offset < buf->header_size) { 0 74 74
1966 0 size_t to_read = sizeof(ws->io.recv_header) - buf->header_offset;
1967 0 size_t min_read = buf->header_size - buf->header_offset;
1968 0 size_t num_read = recv_fn(user, ws, ws->io.recv_header + buf->header_offset, to_read, min_read);
1969 0 ▶ if (num_read == 0) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == 0) return false; 0 0 0
1970 0 ▶ if (num_read == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == SIZE_MAX) { 0 0 0
1971 0 ws_fail(ws, BQWS_ERR_IO_READ);
1972 0 return false;
1973 }
1974 bqws_assert(num_read <= to_read);
1975 0 buf->header_offset += num_read;
1976  
1977 0 ▶ if (ws->ping_interval != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->ping_interval != SIZE_MAX) { 0 0 0
1978 0 ws->io.last_read_ts = bqws_get_timestamp();
1979 }
1980  
1981 0 return false;
1982 }
1983  
1984 74 ▶ if (buf->header_offset < buf->header_size) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_offset < buf->header_size) return false; 0 74 74
1985  
1986 // Parse the header and allocate the message
1987 74 const uint8_t *h = (const uint8_t*)ws->io.recv_header;
1988  
1989 // Static header bits
1990 74 bool fin = (h[0] & 0x80) != 0;
1991 74 bool rsv1 = (h[0] & 0x40) != 0;
1992 74 uint32_t opcode = (uint32_t)(h[0] & 0x0f);
1993  
1994 // RSV2/RSV3 are never negotiated here. RSV1 is reserved for
1995 // permessage-deflate and is valid only on the first data frame.
1996 74 ▶ if (h[0] & 0x30) {
Branch: 1 branch
BranchTrueFalseTotal
if (h[0] & 0x30) { 2 72 74
1997 2 ws_fail(ws, BQWS_ERR_RESERVED_BIT);
1998 2 return false;
1999 }
2000 72 ▶ if (rsv1 && (!ws->allow_rsv1 || opcode == 0x0 || opcode >= 0x8)) {
Branch: 4 branches
BranchTrueFalseTotal
if (rsv1 && (!ws->allow_rsv1 || opcode == 0x0 || opcode >= 0x8)) { 16 56 72
if (rsv1 && (!ws->allow_rsv1 || opcode == 0x0 || opcode >= 0x8)) { 14 2 16
if (rsv1 && (!ws->allow_rsv1 || opcode == 0x0 || opcode >= 0x8)) { 13 1 14
if (rsv1 && (!ws->allow_rsv1 || opcode == 0x0 || opcode >= 0x8)) { 1 12 13
2001 4 ws_fail(ws, BQWS_ERR_RESERVED_BIT);
2002 4 return false;
2003 }
2004  
2005 68 uint32_t mask = (uint32_t)(h[1] & 0x80) != 0;
2006 68 uint64_t payload_length = (uint64_t)(h[1] & 0x7f);
2007 68 h += 2;
2008  
2009 // Extended length: Read 2 or 8 bytes of big
2010 // endian payload length.
2011 68 size_t payload_ext = 0;
2012 68 ▶ if (payload_length == 126) {
Branch: 1 branch
BranchTrueFalseTotal
if (payload_length == 126) { 0 68 68
2013 0 payload_ext = 2;
2014 0 payload_length = 0;
2015 68 ▶ } else if (payload_length == 127) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (payload_length == 127) { 0 68 68
2016 0 payload_ext = 8;
2017 0 payload_length = 0;
2018 }
2019 68 ▶ for (size_t i = 0; i < payload_ext; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < payload_ext; i++) { 0 68 68
2020 0 size_t shift = (payload_ext - i - 1) * 8;
2021 0 payload_length |= (uint64_t)h[i] << shift;
2022 }
2023 68 h += payload_ext;
2024  
2025 // RFC 6455 control frames are limited to 125 payload octets.
2026 // Reject them before payload processing so invalid PING/CLOSE frames
2027 // cannot produce a PONG or echoed CLOSE first.
2028 68 ▶ if (opcode >= 0x8 && payload_length > 125) {
Branch: 2 branches
BranchTrueFalseTotal
if (opcode >= 0x8 && payload_length > 125) { 27 41 68
if (opcode >= 0x8 && payload_length > 125) { 0 27 27
2029 0 ws_fail(ws, BQWS_ERR_PARTIAL_CONTROL);
2030 0 return false;
2031 }
2032  
2033 // Data-message limits are independent of the RFC control-frame
2034 // limit. Control frames may contain up to 125 octets even when the
2035 // configured application message limit is smaller.
2036 68 ▶ if (opcode < 0x8
Branch: 1 branch
BranchTrueFalseTotal
if (opcode < 0x8 41 27 68
2037 41 ▶ && payload_length > (uint64_t)ws->limits.max_recv_msg_size) {
Branch: 1 branch
BranchTrueFalseTotal
&& payload_length > (uint64_t)ws->limits.max_recv_msg_size) { 1 40 41
2038 1 ws_fail(ws, BQWS_ERR_LIMIT_MAX_RECV_MSG_SIZE);
2039 1 return false;
2040 }
2041 67 size_t msg_size = (size_t)payload_length;
2042  
2043 // Masking key
2044 67 buf->masked = mask;
2045 67 ▶ if (mask) {
Branch: 1 branch
BranchTrueFalseTotal
if (mask) { 53 14 67
2046 53 memcpy(&buf->mask_key, h, 4);
2047 53 h += 4;
2048 }
2049  
2050 bqws_assert((size_t)((const char*)h - ws->io.recv_header) == buf->header_size);
2051  
2052 67 bqws_msg_type type = BQWS_MSG_INVALID;
2053 67 bool compressed = false;
2054  
2055 // Resolve the type of the message
2056 67 ▶ if (opcode == 0x0) {
Branch: 1 branch
BranchTrueFalseTotal
if (opcode == 0x0) { 6 61 67
2057 // Continuation frame
2058  
2059 6 ▶ if (buf->partial_type == BQWS_MSG_INVALID) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->partial_type == BQWS_MSG_INVALID) { 1 5 6
2060 // Continuation frame without a prior partial frame
2061 1 ws_fail(ws, BQWS_ERR_BAD_CONTINUATION);
2062 1 return false;
2063 }
2064  
2065 5 compressed = buf->partial_compressed;
2066 5 type = (bqws_msg_type)(buf->partial_type | BQWS_MSG_PARTIAL_BIT);
2067 5 ▶ if (fin) {
Branch: 1 branch
BranchTrueFalseTotal
if (fin) { 4 1 5
2068 4 type = (bqws_msg_type)(type | BQWS_MSG_FINAL_BIT);
2069 4 buf->partial_type = BQWS_MSG_INVALID;
2070 4 buf->partial_compressed = false;
2071 }
2072  
2073 61 ▶ } else if (opcode == 0x1 || opcode == 0x2) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (opcode == 0x1 || opcode == 0x2) { 36 25 61
} else if (opcode == 0x1 || opcode == 0x2) { 9 27 36
2074 // Text or Binary
2075 34 ▶ type = opcode == 0x1 ? BQWS_MSG_TEXT : BQWS_MSG_BINARY;
Branch: 1 branch
BranchTrueFalseTotal
type = opcode == 0x1 ? BQWS_MSG_TEXT : BQWS_MSG_BINARY; 25 9 34
2076 34 compressed = rsv1;
2077  
2078 // A new data message cannot begin until the current fragmented
2079 // message has received its final continuation frame.
2080 34 ▶ if (buf->partial_type != BQWS_MSG_INVALID) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->partial_type != BQWS_MSG_INVALID) { 1 33 34
2081 1 ws_fail(ws, BQWS_ERR_UNFINISHED_PARTIAL);
2082 1 return false;
2083 }
2084  
2085 33 ▶ if (!fin) {
Branch: 1 branch
BranchTrueFalseTotal
if (!fin) { 7 26 33
2086 7 buf->partial_type = type;
2087 7 buf->partial_compressed = compressed;
2088 7 type = (bqws_msg_type)(type | BQWS_MSG_PARTIAL_BIT);
2089 }
2090 27 ▶ } else if (opcode >= 0x8 && opcode <= 0xa) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (opcode >= 0x8 && opcode <= 0xa) { 27 0 27
} else if (opcode >= 0x8 && opcode <= 0xa) { 27 0 27
2091 // Control frames
2092 27 ▶ if (opcode == 0x8) type = BQWS_MSG_CONTROL_CLOSE;
Branch: 1 branch
BranchTrueFalseTotal
if (opcode == 0x8) type = BQWS_MSG_CONTROL_CLOSE; 17 10 27
2093 10 ▶ else if (opcode == 0x9) type = BQWS_MSG_CONTROL_PING;
Branch: 1 branch
BranchTrueFalseTotal
else if (opcode == 0x9) type = BQWS_MSG_CONTROL_PING; 8 2 10
2094 2 ▶ else if (opcode == 0xa) type = BQWS_MSG_CONTROL_PONG;
Branch: 1 branch
BranchTrueFalseTotal
else if (opcode == 0xa) type = BQWS_MSG_CONTROL_PONG; 2 0 2
2095  
2096 27 ▶ if (!fin) {
Branch: 1 branch
BranchTrueFalseTotal
if (!fin) { 0 27 27
2097 // Control frames may not be fragmented
2098 0 ws_fail(ws, BQWS_ERR_PARTIAL_CONTROL);
2099 0 return false;
2100 }
2101 } else {
2102 // Unsupported opcode
2103 0 ws_fail(ws, BQWS_ERR_BAD_OPCODE);
2104 0 return false;
2105 }
2106 bqws_assert(type != BQWS_MSG_INVALID);
2107  
2108 // Validate text incrementally as payload bytes arrive. The UTF-8
2109 // state survives continuation-frame boundaries, while control frames
2110 // leave it untouched.
2111 65 buf->validate_utf8 =
2112 65 (type & BQWS_MSG_TYPE_MASK) == BQWS_MSG_TEXT
2113 65 ▶ && !compressed;
Branch: 2 branches
BranchTrueFalseTotal
&& !compressed; 29 36 65
&& !compressed; 19 10 29
2114 65 ▶ if (opcode == 0x1) {
Branch: 1 branch
BranchTrueFalseTotal
if (opcode == 0x1) { 25 40 65
2115 25 unblock_bqws_utf8_reset(&buf->utf8);
2116 40 ▶ } else if (opcode == 0x2) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (opcode == 0x2) { 8 32 40
2117 8 unblock_bqws_utf8_reset(&buf->utf8);
2118 }
2119  
2120 // All good, allocate the message
2121 65 bqws_msg_imp *imp = msg_alloc(ws, type, msg_size);
2122 65 ▶ if (!imp) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!imp) return false; 0 65 65
2123  
2124 65 imp->compressed = compressed;
2125 65 buf->msg = imp;
2126 65 buf->offset = 0;
2127  
2128 // Copy rest of the header bytes to the message
2129 65 size_t offset = buf->header_size;
2130 65 size_t left = buf->header_offset - offset;
2131 65 ▶ if (left > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (left > 0) { 65 0 65
2132 65 size_t to_copy = left;
2133 65 ▶ if (to_copy > imp->msg.size) to_copy = imp->msg.size;
Branch: 1 branch
BranchTrueFalseTotal
if (to_copy > imp->msg.size) to_copy = imp->msg.size; 15 50 65
2134 65 memcpy(imp->msg.data, ws->io.recv_header + offset, to_copy);
2135 65 ▶ if (buf->validate_utf8 && to_copy > 0
Branch: 2 branches
BranchTrueFalseTotal
if (buf->validate_utf8 && to_copy > 0 19 46 65
if (buf->validate_utf8 && to_copy > 0 19 0 19
2136 19 ▶ && !unblock_bqws_utf8_feed_payload(
Branch: 1 branch
BranchTrueFalseTotal
&& !unblock_bqws_utf8_feed_payload( 2 17 19
2137 19 buf, imp->msg.data, 0, to_copy)) {
2138 2 ws_fail(ws, BQWS_ERR_BAD_UTF8);
2139 2 return false;
2140 }
2141 63 buf->offset += to_copy;
2142 63 offset += to_copy;
2143 63 left -= to_copy;
2144 }
2145  
2146 // If there's still some data shift it as the next header
2147 63 ▶ if (left > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (left > 0) { 15 48 63
2148 15 memmove(ws->io.recv_header, ws->io.recv_header + offset, left);
2149 }
2150 63 buf->header_offset = left;
2151 }
2152  
2153 64 bqws_msg_imp *msg = buf->msg;
2154  
2155 // Read message data if the message is not empty
2156 bqws_assert(buf->offset <= msg->msg.size);
2157 64 ▶ if (msg->msg.size > 0 && buf->offset < msg->msg.size) {
Branch: 2 branches
BranchTrueFalseTotal
if (msg->msg.size > 0 && buf->offset < msg->msg.size) { 64 0 64
if (msg->msg.size > 0 && buf->offset < msg->msg.size) { 2 62 64
2158  
2159 2 size_t to_read = msg->msg.size - buf->offset;
2160 2 size_t read_offset = buf->offset;
2161 2 size_t num_read = recv_fn(user, ws, msg->msg.data + buf->offset, to_read, to_read);
2162 2 ▶ if (num_read == 0) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == 0) return false; 1 1 2
2163 1 ▶ if (num_read == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == SIZE_MAX) { 0 1 1
2164 0 ws_fail(ws, BQWS_ERR_IO_READ);
2165 0 return false;
2166 }
2167 bqws_assert(num_read <= to_read);
2168  
2169 1 ▶ if (ws->ping_interval != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->ping_interval != SIZE_MAX) { 0 1 1
2170 0 ws->io.last_read_ts = bqws_get_timestamp();
2171 }
2172  
2173 1 ▶ if (buf->validate_utf8 && num_read > 0
Branch: 2 branches
BranchTrueFalseTotal
if (buf->validate_utf8 && num_read > 0 1 0 1
if (buf->validate_utf8 && num_read > 0 1 0 1
2174 1 ▶ && !unblock_bqws_utf8_feed_payload(
Branch: 1 branch
BranchTrueFalseTotal
&& !unblock_bqws_utf8_feed_payload( 1 0 1
2175 1 buf, msg->msg.data + read_offset, read_offset, num_read)) {
2176 1 ws_fail(ws, BQWS_ERR_BAD_UTF8);
2177 1 return false;
2178 }
2179  
2180 0 buf->offset += num_read;
2181 0 ▶ if (num_read < to_read) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (num_read < to_read) return false; 0 0 0
2182 }
2183  
2184 62 ▶ if (buf->masked) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->masked) { 48 14 62
2185 48 mask_apply(msg->msg.data, msg->msg.size, buf->mask_key);
2186 }
2187  
2188 bqws_assert(buf->offset == msg->msg.size);
2189  
2190 62 ▶ if (buf->validate_utf8) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->validate_utf8) { 16 46 62
2191 16 bqws_msg_type utf8_type = msg->msg.type;
2192 16 bool logical_final =
2193 16 (utf8_type & BQWS_MSG_PARTIAL_BIT) == 0
2194 16 ▶ || (utf8_type & BQWS_MSG_FINAL_BIT) != 0;
Branch: 2 branches
BranchTrueFalseTotal
|| (utf8_type & BQWS_MSG_FINAL_BIT) != 0; 4 12 16
|| (utf8_type & BQWS_MSG_FINAL_BIT) != 0; 1 3 4
2195 16 ▶ if (logical_final) {
Branch: 1 branch
BranchTrueFalseTotal
if (logical_final) { 13 3 16
2196 13 ▶ if (buf->utf8.remaining != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->utf8.remaining != 0) { 0 13 13
2197 0 ws_fail(ws, BQWS_ERR_BAD_UTF8);
2198 0 return false;
2199 }
2200 13 unblock_bqws_utf8_reset(&buf->utf8);
2201 }
2202 }
2203  
2204 // Peek at all incoming messages before processing
2205 62 ▶ if (ws->peek_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->peek_fn) { 0 62 62
2206 0 ws->peek_fn(ws->peek_user, ws, &msg->msg, true);
2207 }
2208  
2209 // If we copied the last bytes of the message we can push it
2210 // to the queue and clear the buffer.
2211 62 bqws_msg_type type = msg->msg.type;
2212  
2213 62 ▶ if (ws->log_recv) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->log_recv) { 0 62 62
2214 0 ws_log2(ws, "Received: ", bqws_msg_type_str(buf->msg->msg.type));
2215 }
2216  
2217 62 ▶ if ((type & BQWS_MSG_PARTIAL_BIT) != 0 && !ws->recv_partial_messages) {
Branch: 2 branches
BranchTrueFalseTotal
if ((type & BQWS_MSG_PARTIAL_BIT) != 0 && !ws->recv_partial_messages) { 11 51 62
if ((type & BQWS_MSG_PARTIAL_BIT) != 0 && !ws->recv_partial_messages) { 11 0 11
2218  
2219 // Only allow partial messages that combine up to the maximum message size
2220 bqws_assert(msg->msg.size <= ws->limits.max_recv_msg_size);
2221 11 ▶ if (ws->io.recv_partial_size >= ws->limits.max_recv_msg_size - msg->msg.size) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->io.recv_partial_size >= ws->limits.max_recv_msg_size - msg->msg.size) { 1 10 11
2222 1 ws_fail(ws, BQWS_ERR_LIMIT_MAX_RECV_MSG_SIZE);
2223 1 return false;
2224 }
2225  
2226 10 ws->io.recv_partial_size += msg->msg.size;
2227  
2228 // If we dont expose partial messages collect them to `recv_partial_queue`.
2229 10 ▶ if (type & BQWS_MSG_FINAL_BIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_FINAL_BIT) { 3 7 10
2230 // If this is the final message concatenate all the partial messages
2231 // in the queue and enqueue the final one>
2232  
2233 3 bqws_msg_type base_type = (bqws_msg_type)(msg->msg.type & BQWS_MSG_TYPE_MASK);
2234 3 bqws_msg_imp *combined = msg_alloc(ws, base_type, ws->io.recv_partial_size);
2235 3 ▶ if (!combined) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!combined) return false; 0 3 3
2236 3 combined->compressed = msg->compressed;
2237  
2238 3 size_t offset = 0;
2239  
2240 // `recv_queue` with this message as the last part.
2241 bqws_msg_imp *part;
2242 6 ▶ while ((part = msg_dequeue(&ws->recv_partial_queue)) != NULL) {
Branch: 1 branch
BranchTrueFalseTotal
while ((part = msg_dequeue(&ws->recv_partial_queue)) != NULL) { 3 3 6
2243 bqws_assert(part->magic == BQWS_MSG_MAGIC);
2244 bqws_assert((part->msg.type & BQWS_MSG_TYPE_MASK) == base_type);
2245 bqws_assert(part->compressed == combined->compressed);
2246  
2247 3 memcpy(combined->msg.data + offset, part->msg.data, part->msg.size);
2248 3 offset += part->msg.size;
2249  
2250 // Delete the part
2251 3 msg_free_owned(ws, part);
2252 }
2253  
2254 // Final part
2255 3 memcpy(combined->msg.data + offset, msg->msg.data, msg->msg.size);
2256 3 offset += msg->msg.size;
2257 3 msg_free_owned(ws, msg);
2258  
2259 bqws_assert(offset == combined->msg.size);
2260  
2261 3 ws_enqueue_recv(ws, combined);
2262  
2263 // Clear the partial total size
2264 3 ws->io.recv_partial_size = 0;
2265 } else {
2266  
2267 7 ▶ if (ws->recv_partial_queue.num_messages >= ws->limits.max_partial_message_parts) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->recv_partial_queue.num_messages >= ws->limits.max_partial_message_parts) { 0 7 7
2268 0 ws_fail(ws, BQWS_ERR_LIMIT_MAX_PARTIAL_MESSAGE_PARTS);
2269 0 return false;
2270 }
2271  
2272 7 msg_enqueue(&ws->recv_partial_queue, msg);
2273 }
2274  
2275 } else {
2276 51 ▶ if (type & BQWS_MSG_CONTROL_MASK) {
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_CONTROL_MASK) { 27 24 51
2277 // Control message, handle it. `ws_handle_control()` enqueues the
2278 // message to `recv_queue` internally if required.
2279 27 ws_handle_control(ws, msg);
2280 } else {
2281 // Non-partial data message
2282 24 ws_enqueue_recv(ws, msg);
2283 }
2284 }
2285 61 buf->offset = 0;
2286 61 buf->header_size = 0;
2287 61 buf->validate_utf8 = false;
2288 61 buf->msg = NULL;
2289  
2290 61 return true;
2291 }
2292  
2293 0 static bool ws_write_handshake(bqws_socket *ws, bqws_io_send_fn *send_fn, void *user)
2294 {
2295 bqws_assert_locked(&ws->io.mutex);
2296  
2297 0 size_t to_send = ws->io.handshake.size - ws->io.handshake.write_offset;
2298 0 size_t sent = send_fn(user, ws, ws->io.handshake.data + ws->io.handshake.write_offset, to_send);
2299 0 ▶ if (sent == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (sent == SIZE_MAX) { 0 0 0
2300 0 ws_fail(ws, BQWS_ERR_IO_WRITE);
2301 0 return false;
2302 }
2303  
2304 bqws_assert(sent <= to_send);
2305 0 ws->io.handshake.write_offset += sent;
2306 0 return sent == to_send;
2307 }
2308  
2309 133 static bool ws_write_data(bqws_socket *ws, bqws_io_send_fn *send_fn, void *user)
2310 {
2311 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2312 bqws_assert_locked(&ws->io.mutex);
2313  
2314 133 bqws_msg_buffer *buf = &ws->io.send_buf;
2315  
2316 bqws_state state;
2317 char *protocol;
2318  
2319 bqws_mutex_lock(&ws->state.mutex);
2320 133 ▶ if (ws->state.stop_write) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.stop_write) { 10 123 133
2321 bqws_mutex_unlock(&ws->state.mutex);
2322 10 return false;
2323 }
2324 123 state = ws->state.state;
2325 123 protocol = ws->state.chosen_protocol;
2326 bqws_mutex_unlock(&ws->state.mutex);
2327  
2328 123 ▶ if (state == BQWS_STATE_CONNECTING) {
Branch: 1 branch
BranchTrueFalseTotal
if (state == BQWS_STATE_CONNECTING) { 0 123 123
2329  
2330 0 ▶ if (ws->is_server) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->is_server) { 0 0 0
2331 // Server: read the client handshake first
2332 0 ▶ if (!ws->io.client_handshake_done) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->io.client_handshake_done) return false; 0 0 0
2333  
2334 // Wait for the user to accept/reject the connection
2335 0 ▶ if (!protocol) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!protocol) return false; 0 0 0
2336  
2337 // Write the server handshake on demand
2338 0 ▶ if (ws->io.handshake.size == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->io.handshake.size == 0) { 0 0 0
2339 0 hs_server_handshake(ws);
2340 0 ▶ if (ws->err) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return false; 0 0 0
2341 }
2342  
2343 // Write the server handshake
2344 0 ▶ if (!ws_write_handshake(ws, send_fn, user)) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws_write_handshake(ws, send_fn, user)) return false; 0 0 0
2345  
2346 // Server handshake is done!
2347 0 hs_finish_handshake(ws);
2348  
2349 } else {
2350 // Client: Send the request and always wait for response
2351 0 ▶ if (!ws->io.client_handshake_done) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->io.client_handshake_done) { 0 0 0
2352 0 ▶ if (!ws_write_handshake(ws, send_fn, user)) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws_write_handshake(ws, send_fn, user)) return false; 0 0 0
2353  
2354 // Re-use the handshake buffer for the response,
2355 0 ws->io.handshake.size = 0;
2356 0 ws->io.client_handshake_done = true;
2357 }
2358  
2359 0 return false;
2360 }
2361 }
2362  
2363 123 ▶ if (!buf->msg) {
Branch: 1 branch
BranchTrueFalseTotal
if (!buf->msg) { 123 0 123
2364 // No message: Send high priority messages first.
2365  
2366 bqws_mutex_lock(&ws->state.mutex);
2367  
2368 123 ▶ if (ws->state.close_to_send && !ws->state.close_sent) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->state.close_to_send && !ws->state.close_sent) { 31 92 123
if (ws->state.close_to_send && !ws->state.close_sent) { 31 0 31
2369 // First priority: Send close message
2370 31 buf->msg = ws->state.close_to_send;
2371 31 ws->state.close_to_send = NULL;
2372 31 bqws_assert(buf->msg->msg.type == BQWS_MSG_CONTROL_CLOSE);
2373 92 ▶ } else if (ws->state.state != BQWS_STATE_OPEN) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (ws->state.state != BQWS_STATE_OPEN) { 63 29 92
2374 // Stop sending anything if the state is not open
2375 63 ▶ } else if (ws->state.pong_to_send) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (ws->state.pong_to_send) { 0 63 63
2376 // Try to respond to PING messages fast
2377 0 buf->msg = ws->state.pong_to_send;
2378 0 ws->state.pong_to_send = NULL;
2379 bqws_assert(buf->msg->msg.type == BQWS_MSG_CONTROL_PONG);
2380 } else {
2381 // Send user message if there is one
2382 63 buf->msg = msg_dequeue(&ws->send_queue);
2383 }
2384  
2385 bqws_mutex_unlock(&ws->state.mutex);
2386  
2387 // Did not find any message
2388 123 ▶ if (!buf->msg) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!buf->msg) return false; 67 56 123
2389  
2390 bqws_assert(buf->msg && buf->msg->magic == BQWS_MSG_MAGIC);
2391  
2392 }
2393 56 bqws_msg_imp *msg = buf->msg;
2394 bqws_assert(msg && msg->magic == BQWS_MSG_MAGIC);
2395  
2396 // Re-assign the public socket to be this one for the callback
2397 56 msg->msg.socket = ws;
2398  
2399 // Peek at all outgoing messages before processing
2400 56 ▶ if (ws->peek_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->peek_fn) { 0 56 56
2401 0 ws->peek_fn(ws->peek_user, ws, &msg->msg, false);
2402 }
2403  
2404 56 ▶ if (ws->send_message_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->send_message_fn) { 0 56 56
2405 0 msg_release_ownership(ws, msg);
2406 0 ▶ if (ws->send_message_fn(ws->send_message_user, ws, &msg->msg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->send_message_fn(ws->send_message_user, ws, &msg->msg)) { 0 0 0
2407 0 ▶ if (ws->log_send) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->log_send) { 0 0 0
2408 0 ws_log2(ws, "Direct send: ", bqws_msg_type_str(msg->msg.type));
2409 }
2410 0 buf->msg = NULL;
2411 0 return true;
2412 } else {
2413 0 msg_acquire_ownership(ws, msg);
2414 0 return false;
2415 }
2416 }
2417  
2418 56 ▶ if (ws->ping_interval != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->ping_interval != SIZE_MAX) { 0 56 56
2419 0 ws->io.last_write_ts = bqws_get_timestamp();
2420 }
2421  
2422 56 ▶ if (buf->header_size == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_size == 0) { 56 0 56
2423 56 bqws_msg_type type = msg->msg.type;
2424 56 ▶ bool mask = ws->is_server ? ws->mask_server : !ws->unsafe_dont_mask_client;
Branch: 1 branch
BranchTrueFalseTotal
bool mask = ws->is_server ? ws->mask_server : !ws->unsafe_dont_mask_client; 43 13 56
2425 56 bool fin = true;
2426 56 uint32_t opcode = ~0u;
2427  
2428 56 ▶ if (type & BQWS_MSG_TYPE_MASK) {
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_TYPE_MASK) { 15 41 56
2429 15 bqws_msg_type base_type = (bqws_msg_type)(type & BQWS_MSG_TYPE_MASK);
2430 15 ▶ opcode = base_type == BQWS_MSG_TEXT ? 0x1 : 0x2;
Branch: 1 branch
BranchTrueFalseTotal
opcode = base_type == BQWS_MSG_TEXT ? 0x1 : 0x2; 10 5 15
2431  
2432 15 ▶ if (type & BQWS_MSG_PARTIAL_BIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_PARTIAL_BIT) { 0 15 15
2433 0 ▶ if (buf->partial_type != BQWS_MSG_INVALID) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->partial_type != BQWS_MSG_INVALID) { 0 0 0
2434 // Partial continuation
2435 bqws_assert(buf->partial_type == base_type);
2436 0 opcode = 0x0;
2437 }
2438  
2439 0 ▶ if (type & BQWS_MSG_FINAL_BIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_FINAL_BIT) { 0 0 0
2440 // This can be either the end of a partial message
2441 // or just a single-part partial message.
2442 0 buf->partial_type = BQWS_MSG_INVALID;
2443 } else {
2444 // Partial begin or continuation
2445 0 buf->partial_type = base_type;
2446 0 fin = false;
2447 }
2448 }
2449  
2450 41 ▶ } else if (type & BQWS_MSG_CONTROL_MASK) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (type & BQWS_MSG_CONTROL_MASK) { 41 0 41
2451 // Control message
2452 41 ▶ if (type == BQWS_MSG_CONTROL_CLOSE) opcode = 0x8;
Branch: 1 branch
BranchTrueFalseTotal
if (type == BQWS_MSG_CONTROL_CLOSE) opcode = 0x8; 31 10 41
2453 10 ▶ else if (type == BQWS_MSG_CONTROL_PING) opcode = 0x9;
Branch: 1 branch
BranchTrueFalseTotal
else if (type == BQWS_MSG_CONTROL_PING) opcode = 0x9; 2 8 10
2454 8 ▶ else if (type == BQWS_MSG_CONTROL_PONG) opcode = 0xa;
Branch: 1 branch
BranchTrueFalseTotal
else if (type == BQWS_MSG_CONTROL_PONG) opcode = 0xa; 8 0 8
2455 } else {
2456 bqws_assert(0 && "Trying to send non-data non-control message");
2457 }
2458  
2459 bqws_assert(opcode != ~0u);
2460  
2461 // Use the smallest payload length representation
2462 56 size_t payload_ext = 0;
2463 56 size_t payload_len = msg->msg.size;
2464 56 ▶ if (payload_len > 65535u) {
Branch: 1 branch
BranchTrueFalseTotal
if (payload_len > 65535u) { 0 56 56
2465 0 payload_len = 127;
2466 0 payload_ext = 8;
2467 56 ▶ } else if (payload_len > 125) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (payload_len > 125) { 0 56 56
2468 0 payload_len = 126;
2469 0 payload_ext = 2;
2470 }
2471  
2472 56 uint8_t *h = (uint8_t*)ws->io.send_header;
2473 // Static header bits
2474 56 h[0] = (fin ? 0x80 : 0x0)
2475 56 ▶ | ((msg->compressed && opcode != 0x0 && opcode < 0x8) ? 0x40 : 0x0)
Branch: 4 branches
BranchTrueFalseTotal
| ((msg->compressed && opcode != 0x0 && opcode < 0x8) ? 0x40 : 0x0) 56 0 56
| ((msg->compressed && opcode != 0x0 && opcode < 0x8) ? 0x40 : 0x0) 4 52 56
| ((msg->compressed && opcode != 0x0 && opcode < 0x8) ? 0x40 : 0x0) 4 0 4
| ((msg->compressed && opcode != 0x0 && opcode < 0x8) ? 0x40 : 0x0) 4 0 4
2476 56 | (uint8_t)opcode;
2477 56 ▶ h[1] = (mask ? 0x80 : 0x0) | (uint8_t)payload_len;
Branch: 1 branch
BranchTrueFalseTotal
h[1] = (mask ? 0x80 : 0x0) | (uint8_t)payload_len; 13 43 56
2478 56 h += 2;
2479  
2480 // Extended length: Read 2 or 8 bytes of big
2481 // endian payload length.
2482 56 ▶ for (size_t i = 0; i < payload_ext; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < payload_ext; i++) { 0 56 56
2483 0 size_t shift = (payload_ext - i - 1) * 8;
2484 0 h[i] = (uint8_t)((uint64_t)msg->msg.size >> shift);
2485 }
2486 56 h += payload_ext;
2487  
2488 // Masking key
2489 56 buf->masked = mask;
2490 56 ▶ if (mask) {
Branch: 1 branch
BranchTrueFalseTotal
if (mask) { 13 43 56
2491 13 uint32_t mask_key = mask_make_key(ws);
2492 13 buf->mask_key = mask_key;
2493 13 memcpy(h, &buf->mask_key, 4);
2494 13 h += 4;
2495  
2496 // Apply the mask
2497 13 mask_apply(msg->msg.data, msg->msg.size, mask_key);
2498 }
2499  
2500 56 buf->header_size = (char*)h - ws->io.send_header;
2501 bqws_assert(buf->header_size <= sizeof(ws->io.send_header));
2502 }
2503  
2504 // Send the header
2505 56 ▶ if (buf->header_offset < buf->header_size) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_offset < buf->header_size) { 56 0 56
2506 56 size_t to_send = buf->header_size - buf->header_offset;
2507 56 size_t sent = send_fn(user, ws, ws->io.send_header + buf->header_offset, to_send);
2508 56 ▶ if (sent == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (sent == SIZE_MAX) { 0 56 56
2509 0 ws_fail(ws, BQWS_ERR_IO_WRITE);
2510 0 return false;
2511 }
2512 bqws_assert(sent <= to_send);
2513 56 buf->header_offset += sent;
2514 56 ▶ if (sent < to_send) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (sent < to_send) return false; 0 56 56
2515 }
2516  
2517 // Send the message
2518 {
2519 56 size_t to_send = msg->msg.size - buf->offset;
2520 56 size_t sent = send_fn(user, ws, msg->msg.data + buf->offset, to_send);
2521 56 ▶ if (sent == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (sent == SIZE_MAX) { 0 56 56
2522 0 ws_fail(ws, BQWS_ERR_IO_WRITE);
2523 0 return false;
2524 }
2525 bqws_assert(sent <= to_send);
2526 56 buf->offset += sent;
2527 56 ▶ if (sent < to_send) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (sent < to_send) return false; 0 56 56
2528 }
2529  
2530 56 ▶ if (ws->log_send) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->log_send) { 0 56 56
2531 0 ws_log2(ws, "Sent: ", bqws_msg_type_str(buf->msg->msg.type));
2532 }
2533  
2534 // Mark close as been sent
2535 56 ▶ if (msg->msg.type == BQWS_MSG_CONTROL_CLOSE) {
Branch: 1 branch
BranchTrueFalseTotal
if (msg->msg.type == BQWS_MSG_CONTROL_CLOSE) { 31 25 56
2536 bqws_mutex_lock(&ws->state.mutex);
2537 31 ▶ if (ws->state.state == BQWS_STATE_OPEN) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.state == BQWS_STATE_OPEN) { 0 31 31
2538 0 ws_log(ws, "State: CLOSING (queued user close)");
2539 0 ws->state.state = BQWS_STATE_CLOSING;
2540 0 ws->state.start_closing_ts = bqws_get_timestamp();
2541 }
2542 31 ws->state.close_sent = true;
2543 31 ▶ if (ws->state.close_received) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.close_received) { 5 26 31
2544 5 ws_close(ws);
2545 }
2546 bqws_mutex_unlock(&ws->state.mutex);
2547 }
2548  
2549 // Delete the message
2550 56 msg_free_owned(ws, msg);
2551  
2552 // Sent everything, clear status
2553 56 buf->offset = 0;
2554 56 buf->header_offset = 0;
2555 56 buf->header_size = 0;
2556 56 buf->msg = NULL;
2557 56 return true;
2558 }
2559  
2560 // WebSocket initialization
2561  
2562 0 static char *verify_filter_str(bqws_verify_filter *f, size_t *offset, const char *str)
2563 {
2564 0 ▶ if (!str) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!str) return NULL; 0 0 0
2565 0 size_t len = strlen(str) + 1;
2566 0 char *dst = f->text_data + *offset;
2567 0 memcpy(dst, str, len);
2568 0 *offset += len;
2569 0 return dst;
2570 }
2571  
2572 0 static void bqws_internal_filter_verify(void *user, bqws_socket *ws, const bqws_client_opts *opts)
2573 {
2574 0 bqws_verify_filter *f = (bqws_verify_filter*)user;
2575 0 bool ok = true;
2576  
2577 // Check common headers
2578 0 ▶ ok = ok && (!f->path || !strcmp(f->path, opts->path));
Branch: 3 branches
BranchTrueFalseTotal
ok = ok && (!f->path || !strcmp(f->path, opts->path)); 0 0 0
ok = ok && (!f->path || !strcmp(f->path, opts->path)); 0 0 0
ok = ok && (!f->path || !strcmp(f->path, opts->path)); 0 0 0
2579 0 ▶ ok = ok && (!f->host || streq_ic(f->host, opts->host));
Branch: 3 branches
BranchTrueFalseTotal
ok = ok && (!f->host || streq_ic(f->host, opts->host)); 0 0 0
ok = ok && (!f->host || streq_ic(f->host, opts->host)); 0 0 0
ok = ok && (!f->host || streq_ic(f->host, opts->host)); 0 0 0
2580 0 ▶ ok = ok && (!f->origin || streq_ic(f->origin, opts->origin));
Branch: 3 branches
BranchTrueFalseTotal
ok = ok && (!f->origin || streq_ic(f->origin, opts->origin)); 0 0 0
ok = ok && (!f->origin || streq_ic(f->origin, opts->origin)); 0 0 0
ok = ok && (!f->origin || streq_ic(f->origin, opts->origin)); 0 0 0
2581  
2582 0 const char *protocol = NULL;
2583 0 ▶ if (f->num_protocols > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (f->num_protocols > 0) { 0 0 0
2584 // If the filter has protocols try to find one
2585 // O(n^2) but bounded by BQWS_MAX_PROTOCOLS
2586 0 ▶ for (size_t ci = 0; ci < opts->num_protocols && !protocol; ci++) {
Branch: 2 branches
BranchTrueFalseTotal
for (size_t ci = 0; ci < opts->num_protocols && !protocol; ci++) { 0 0 0
for (size_t ci = 0; ci < opts->num_protocols && !protocol; ci++) { 0 0 0
2587 0 ▶ for (size_t fi = 0; fi < f->num_protocols; fi++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t fi = 0; fi < f->num_protocols; fi++) { 0 0 0
2588 0 ▶ if (!strcmp(f->protocols[fi], opts->protocols[ci])) {
Branch: 1 branch
BranchTrueFalseTotal
if (!strcmp(f->protocols[fi], opts->protocols[ci])) { 0 0 0
2589 0 protocol = f->protocols[fi];
2590 0 break;
2591 }
2592 }
2593 }
2594 0 ▶ ok = ok && protocol != NULL;
Branch: 2 branches
BranchTrueFalseTotal
ok = ok && protocol != NULL; 0 0 0
ok = ok && protocol != NULL; 0 0 0
2595 } else {
2596 // If not don't use any protocol name
2597 0 protocol = "";
2598 }
2599  
2600 0 ▶ if (ok) {
Branch: 1 branch
BranchTrueFalseTotal
if (ok) { 0 0 0
2601 bqws_assert(protocol != NULL);
2602 0 ▶ if (f->verify_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (f->verify_fn) { 0 0 0
2603 0 f->verify_fn(f->verify_user, ws, opts);
2604 } else {
2605 0 bqws_server_accept(ws, protocol);
2606 }
2607 } else {
2608 0 bqws_server_reject(ws);
2609 }
2610 0 }
2611  
2612 66 static void ws_expand_default_limits(bqws_limits *limits)
2613 {
2614 #define WS_DEFAULT(p_name, p_value) if (!limits->p_name) limits->p_name = p_value
2615  
2616 66 ▶ WS_DEFAULT(max_memory_used, 262144);
Branch: 1 branch
BranchTrueFalseTotal
WS_DEFAULT(max_memory_used, 262144); 0 66 66
2617 66 ▶ WS_DEFAULT(max_recv_msg_size, 262144);
Branch: 1 branch
BranchTrueFalseTotal
WS_DEFAULT(max_recv_msg_size, 262144); 0 66 66
2618 66 ▶ WS_DEFAULT(max_handshake_size, 262144);
Branch: 1 branch
BranchTrueFalseTotal
WS_DEFAULT(max_handshake_size, 262144); 51 15 66
2619 66 ▶ WS_DEFAULT(max_recv_queue_messages, 1024);
Branch: 1 branch
BranchTrueFalseTotal
WS_DEFAULT(max_recv_queue_messages, 1024); 0 66 66
2620 66 ▶ WS_DEFAULT(max_recv_queue_size, 262144);
Branch: 1 branch
BranchTrueFalseTotal
WS_DEFAULT(max_recv_queue_size, 262144); 0 66 66
2621 66 ▶ WS_DEFAULT(max_partial_message_parts, 16384);
Branch: 1 branch
BranchTrueFalseTotal
WS_DEFAULT(max_partial_message_parts, 16384); 0 66 66
2622  
2623 #undef WS_DEFAULT
2624 66 }
2625  
2626 51 static bqws_socket *ws_new_socket(const bqws_opts *opts, bool is_server)
2627 {
2628 bqws_opts null_opts;
2629 51 ▶ if (!opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (!opts) { 0 51 51
2630 0 memset(&null_opts, 0, sizeof(null_opts));
2631 0 opts = &null_opts;
2632 }
2633  
2634 51 bqws_socket *ws = (bqws_socket*)bqws_allocator_alloc(&opts->allocator, sizeof(bqws_socket) + opts->user_size);
2635 51 ▶ if (!ws) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws) return NULL; 0 51 51
2636  
2637 51 memset(ws, 0, sizeof(bqws_socket));
2638 51 ws->magic = BQWS_SOCKET_MAGIC;
2639 51 ws->is_server = is_server;
2640 51 ws->allocator = opts->allocator;
2641 51 ws->user_io = opts->io;
2642 51 ws->limits = opts->limits;
2643 51 ws->recv_partial_messages = opts->recv_partial_messages;
2644 51 ws->recv_control_messages = opts->recv_control_messages;
2645 51 ws->mask_server = opts->mask_server;
2646 51 ws->message_fn = opts->message_fn;
2647 51 ws->message_user = opts->message_user;
2648 51 ws->peek_fn = opts->peek_fn;
2649 51 ws->peek_user = opts->peek_user;
2650 51 ws->log_fn = opts->log_fn;
2651 51 ws->log_user = opts->log_user;
2652 51 ws->log_send = opts->log_send;
2653 51 ws->log_recv = opts->log_recv;
2654 51 ws->error_fn = opts->error_fn;
2655 51 ws->error_user = opts->error_user;
2656 51 ws->send_message_fn = opts->send_message_fn;
2657 51 ws->send_message_user = opts->send_message_user;
2658 51 ws->user_size = opts->user_size;
2659  
2660 51 ws_expand_default_limits(&ws->limits);
2661  
2662 bqws_mutex_init(&ws->err_mutex);
2663 bqws_mutex_init(&ws->state.mutex);
2664 bqws_mutex_init(&ws->io.mutex);
2665 bqws_mutex_init(&ws->alloc.mutex);
2666 bqws_mutex_init(&ws->partial.mutex);
2667  
2668 51 msg_init_queue(ws, &ws->recv_queue);
2669 51 msg_init_queue(ws, &ws->recv_partial_queue);
2670 51 msg_init_queue(ws, &ws->send_queue);
2671  
2672 51 ▶ if (opts->ping_interval) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->ping_interval) { 51 0 51
2673 51 ws->ping_interval = opts->ping_interval;
2674 } else {
2675 0 ▶ ws->ping_interval = is_server ? 20000 : 10000;
Branch: 1 branch
BranchTrueFalseTotal
ws->ping_interval = is_server ? 20000 : 10000; 0 0 0
2676 }
2677  
2678 51 ▶ ws->connect_timeout = opts->connect_timeout ? opts->connect_timeout : 10000;
Branch: 1 branch
BranchTrueFalseTotal
ws->connect_timeout = opts->connect_timeout ? opts->connect_timeout : 10000; 51 0 51
2679 51 ▶ ws->close_timeout = opts->close_timeout ? opts->close_timeout : 5000;
Branch: 1 branch
BranchTrueFalseTotal
ws->close_timeout = opts->close_timeout ? opts->close_timeout : 5000; 51 0 51
2680 51 ▶ ws->ping_response_timeout = opts->ping_response_timeout ? opts->ping_response_timeout : 4 * ws->ping_interval;
Branch: 1 branch
BranchTrueFalseTotal
ws->ping_response_timeout = opts->ping_response_timeout ? opts->ping_response_timeout : 4 * ws->ping_interval; 51 0 51
2681  
2682 bqws_assert(ws->ping_interval > 0);
2683 51 ▶ if (ws->ping_interval != SIZE_MAX || ws->connect_timeout != SIZE_MAX) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->ping_interval != SIZE_MAX || ws->connect_timeout != SIZE_MAX) { 51 0 51
if (ws->ping_interval != SIZE_MAX || ws->connect_timeout != SIZE_MAX) { 0 51 51
2684 0 bqws_timestamp ts = bqws_get_timestamp();
2685 0 ws->io.start_connect_ts = ts;
2686 0 ws->io.last_write_ts = ts;
2687 0 ws->io.last_read_ts = ts;
2688 0 ws->io.last_ping_ts = ts;
2689 }
2690  
2691 // Copy or zero-init user data
2692 51 ▶ if (opts->user_size > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->user_size > 0) { 0 51 51
2693 0 ▶ if (opts->user_data) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->user_data) { 0 0 0
2694 0 memcpy(ws->user_data, opts->user_data, opts->user_size);
2695 } else {
2696 0 memset(ws->user_data, 0, opts->user_size);
2697 }
2698 }
2699  
2700 51 ▶ if (opts->name) ws->name = ws_copy_str(ws, opts->name);
Branch: 1 branch
BranchTrueFalseTotal
if (opts->name) ws->name = ws_copy_str(ws, opts->name); 0 51 51
2701  
2702 51 ▶ if (opts->skip_handshake) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->skip_handshake) { 51 0 51
2703 51 ws_log(ws, "State: OPEN (skip handhake)");
2704 51 ws->state.state = BQWS_STATE_OPEN;
2705 } else {
2706 0 ws_log(ws, "State: CONNECTING");
2707 0 ws->state.state = BQWS_STATE_CONNECTING;
2708 }
2709  
2710 51 ws->io.mask_random_state = (uint32_t)(uintptr_t)ws ^ (uint32_t)time(NULL);
2711 51 ws->io.mask_random_stream = (uint32_t)bqws_get_timestamp() | 1u;
2712  
2713 51 ▶ if (ws->err) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) { 0 51 51
2714 0 bqws_free_socket(ws);
2715 0 return NULL;
2716 }
2717  
2718 51 return ws;
2719 }
2720  
2721 // -- API
2722  
2723 10 bqws_socket *bqws_new_client(const bqws_opts *opts, const bqws_client_opts *client_opts)
2724 {
2725 10 bqws_socket *ws = ws_new_socket(opts, false);
2726 10 ▶ if (!ws) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws) return NULL; 0 10 10
2727  
2728 // Setup client handshake immediately if the socket is not open already
2729 10 ▶ if (ws->state.state == BQWS_STATE_CONNECTING) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.state == BQWS_STATE_CONNECTING) { 0 10 10
2730 bqws_client_opts null_opts;
2731 0 ▶ if (!client_opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (!client_opts) { 0 0 0
2732 0 memset(&null_opts, 0, sizeof(null_opts));
2733 0 client_opts = &null_opts;
2734 }
2735  
2736 bqws_mutex_lock(&ws->io.mutex);
2737 0 hs_client_handshake(ws, client_opts);
2738 bqws_mutex_unlock(&ws->io.mutex);
2739  
2740 // Notify IO that there's a client handshake to send
2741 0 ▶ if (ws->user_io.notify_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.notify_fn) { 0 0 0
2742 0 ws->user_io.notify_fn(ws->user_io.user, ws);
2743 }
2744 }
2745  
2746 10 return ws;
2747 }
2748  
2749 41 bqws_socket *bqws_new_server(const bqws_opts *opts, const bqws_server_opts *server_opts)
2750 {
2751 41 bqws_socket *ws = ws_new_socket(opts, true);
2752 41 ▶ if (!ws) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws) return NULL; 0 41 41
2753  
2754 {
2755 bqws_server_opts null_opts;
2756 41 ▶ if (!server_opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (!server_opts) { 41 0 41
2757 41 memset(&null_opts, 0, sizeof(null_opts));
2758 41 server_opts = &null_opts;
2759 }
2760  
2761 41 ws->verify_fn = server_opts->verify_fn;
2762 41 ws->verify_user = server_opts->verify_user;
2763  
2764 // Setup automatic verify filter if needed
2765 41 ▶ if (server_opts->verify_filter) {
Branch: 1 branch
BranchTrueFalseTotal
if (server_opts->verify_filter) { 0 41 41
2766 0 bqws_client_opts *filter = server_opts->verify_filter;
2767 0 size_t text_size = 0;
2768  
2769 0 ▶ text_size += filter->path ? strlen(filter->path) + 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
text_size += filter->path ? strlen(filter->path) + 1 : 0; 0 0 0
2770 0 ▶ text_size += filter->host ? strlen(filter->host) + 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
text_size += filter->host ? strlen(filter->host) + 1 : 0; 0 0 0
2771 0 ▶ text_size += filter->origin ? strlen(filter->origin) + 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
text_size += filter->origin ? strlen(filter->origin) + 1 : 0; 0 0 0
2772 0 ▶ for (size_t i = 0; i < filter->num_protocols; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < filter->num_protocols; i++) { 0 0 0
2773 bqws_assert(filter->protocols[i] && *filter->protocols[i]);
2774 0 text_size += strlen(filter->protocols[i]) + 1;
2775 }
2776  
2777 0 bqws_verify_filter *copy = (bqws_verify_filter*)ws_alloc(ws, sizeof(bqws_verify_filter) + text_size);
2778 0 ▶ if (!copy) {
Branch: 1 branch
BranchTrueFalseTotal
if (!copy) { 0 0 0
2779 0 bqws_free_socket(ws);
2780 0 return NULL;
2781 }
2782  
2783 0 memset(copy, 0, sizeof(bqws_verify_filter));
2784 0 copy->magic = BQWS_FILTER_MAGIC;
2785 0 copy->text_size = text_size;
2786 0 size_t offset = 0;
2787  
2788 0 copy->path = verify_filter_str(copy, &offset, filter->path);
2789 0 copy->host = verify_filter_str(copy, &offset, filter->host);
2790 0 copy->origin = verify_filter_str(copy, &offset, filter->origin);
2791 0 copy->num_protocols = filter->num_protocols;
2792 0 ▶ for (size_t i = 0; i < filter->num_protocols; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < filter->num_protocols; i++) { 0 0 0
2793 0 copy->protocols[i] = verify_filter_str(copy, &offset, filter->protocols[i]);
2794 }
2795  
2796 bqws_assert(offset == text_size);
2797  
2798 0 copy->verify_fn = ws->verify_fn;
2799 0 copy->verify_user = ws->verify_user;
2800 0 ws->verify_fn = &bqws_internal_filter_verify;
2801 0 ws->verify_user = copy;
2802 }
2803 }
2804  
2805 41 return ws;
2806 }
2807  
2808 10 void bqws_close(bqws_socket *ws, bqws_close_reason reason, const void *data, size_t size)
2809 {
2810 10 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 10 10
2811  
2812 bqws_mutex_lock(&ws->state.mutex);
2813  
2814 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2815 bqws_assert(size == 0 || data);
2816 10 ▶ if (ws->state.close_to_send || ws->state.state >= BQWS_STATE_CLOSING) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->state.close_to_send || ws->state.state >= BQWS_STATE_CLOSING) { 10 0 10
if (ws->state.close_to_send || ws->state.state >= BQWS_STATE_CLOSING) { 0 10 10
2817 bqws_mutex_unlock(&ws->state.mutex);
2818 0 return;
2819 }
2820  
2821 10 bqws_msg_imp *imp = msg_alloc(ws, BQWS_MSG_CONTROL_CLOSE, size + 2);
2822 10 ▶ if (imp) {
Branch: 1 branch
BranchTrueFalseTotal
if (imp) { 10 0 10
2823 10 imp->msg.data[0] = (uint8_t)(reason >> 8);
2824 10 imp->msg.data[1] = (uint8_t)(reason & 0xff);
2825 10 memcpy(imp->msg.data + 2, data, size);
2826  
2827 10 ws->state.close_to_send = imp;
2828 10 ws->state.start_closing_ts = bqws_get_timestamp();
2829 10 ws->state.state = BQWS_STATE_CLOSING;
2830  
2831 10 ws_log(ws, "State: CLOSING (user close)");
2832 }
2833  
2834 bqws_mutex_unlock(&ws->state.mutex);
2835 }
2836  
2837 0 void bqws_queue_close(bqws_socket *ws, bqws_close_reason reason, const void *data, size_t size)
2838 {
2839 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
2840  
2841 bqws_mutex_lock(&ws->state.mutex);
2842  
2843 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2844 bqws_assert(size == 0 || data);
2845 0 ▶ if (ws->state.close_to_send || ws->state.state >= BQWS_STATE_CLOSING) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->state.close_to_send || ws->state.state >= BQWS_STATE_CLOSING) { 0 0 0
if (ws->state.close_to_send || ws->state.state >= BQWS_STATE_CLOSING) { 0 0 0
2846 bqws_mutex_unlock(&ws->state.mutex);
2847 0 return;
2848 }
2849  
2850 0 bqws_msg_imp *imp = msg_alloc(ws, BQWS_MSG_CONTROL_CLOSE, size + 2);
2851 0 ▶ if (imp) {
Branch: 1 branch
BranchTrueFalseTotal
if (imp) { 0 0 0
2852 0 imp->msg.data[0] = (uint8_t)(reason >> 8);
2853 0 imp->msg.data[1] = (uint8_t)(reason & 0xff);
2854 0 memcpy(imp->msg.data + 2, data, size);
2855 0 ws_enqueue_send(ws, imp);
2856 }
2857  
2858 bqws_mutex_unlock(&ws->state.mutex);
2859 }
2860  
2861 51 void bqws_free_socket(bqws_socket *ws)
2862 {
2863 51 ▶ if (!ws) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws) return; 0 51 51
2864 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2865  
2866 51 ws_log(ws, "Freed");
2867  
2868 51 ▶ if (ws->user_io.close_fn && !ws->state.io_closed) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->user_io.close_fn && !ws->state.io_closed) { 0 51 51
if (ws->user_io.close_fn && !ws->state.io_closed) { 0 0 0
2869 0 ws->user_io.close_fn(ws->user_io.user, ws);
2870 }
2871  
2872 // Free everything, as the socket may have errored it can
2873 // be in almost any state
2874  
2875 // Pending messages
2876 51 msg_free_queue(ws, &ws->recv_queue);
2877 51 msg_free_queue(ws, &ws->recv_partial_queue);
2878 51 msg_free_queue(ws, &ws->send_queue);
2879 51 ▶ if (ws->state.pong_to_send) msg_free_owned(ws, ws->state.pong_to_send);
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.pong_to_send) msg_free_owned(ws, ws->state.pong_to_send); 0 51 51
2880 51 ▶ if (ws->state.close_to_send) msg_free_owned(ws, ws->state.close_to_send);
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.close_to_send) msg_free_owned(ws, ws->state.close_to_send); 9 42 51
2881  
2882 // Read/write buffers
2883 51 ws_free(ws, ws->io.handshake.data, ws->io.handshake.capacity);
2884 51 ws_free(ws, ws->io.handshake_overflow.data, ws->io.handshake_overflow.capacity);
2885 51 ▶ if (ws->io.recv_buf.msg) msg_free_owned(ws, ws->io.recv_buf.msg);
Branch: 1 branch
BranchTrueFalseTotal
if (ws->io.recv_buf.msg) msg_free_owned(ws, ws->io.recv_buf.msg); 4 47 51
2886 51 ▶ if (ws->io.send_buf.msg) msg_free_owned(ws, ws->io.send_buf.msg);
Branch: 1 branch
BranchTrueFalseTotal
if (ws->io.send_buf.msg) msg_free_owned(ws, ws->io.send_buf.msg); 0 51 51
2887 51 ▶ if (ws->partial.next_partial_to_send) msg_free_owned(ws, ws->partial.next_partial_to_send);
Branch: 1 branch
BranchTrueFalseTotal
if (ws->partial.next_partial_to_send) msg_free_owned(ws, ws->partial.next_partial_to_send); 0 51 51
2888  
2889 // Misc buffers
2890 51 ▶ if (ws->io.opts_from_client) ws_free(ws, ws->io.opts_from_client, sizeof(bqws_client_opts));
Branch: 1 branch
BranchTrueFalseTotal
if (ws->io.opts_from_client) ws_free(ws, ws->io.opts_from_client, sizeof(bqws_client_opts)); 0 51 51
2891  
2892 // String copies
2893 51 ws_free_str(ws, ws->state.chosen_protocol);
2894 51 ws_free_str(ws, ws->name);
2895  
2896 // Verify filter copy
2897 51 ▶ if (ws->verify_fn == &bqws_internal_filter_verify) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->verify_fn == &bqws_internal_filter_verify) { 0 51 51
2898 0 bqws_verify_filter *filter = (bqws_verify_filter*)ws->verify_user;
2899 bqws_assert(filter->magic == BQWS_FILTER_MAGIC);
2900 0 filter->magic = BQWS_DELETED_MAGIC;
2901 0 ws_free(ws, filter, sizeof(bqws_verify_filter) + filter->text_size);
2902 }
2903  
2904 // Mutexes
2905 bqws_mutex_free(&ws->err_mutex);
2906 bqws_mutex_free(&ws->state.mutex);
2907 bqws_mutex_free(&ws->io.mutex);
2908 bqws_mutex_free(&ws->alloc.mutex);
2909 bqws_mutex_free(&ws->partial.mutex);
2910  
2911 bqws_assert(ws->alloc.memory_used == 0);
2912  
2913 51 ws->magic = BQWS_DELETED_MAGIC;
2914  
2915 51 bqws_allocator at = ws->allocator;
2916 51 bqws_allocator_free(&at, ws, sizeof(bqws_socket) + ws->user_size);
2917 }
2918  
2919 0 bqws_client_opts *bqws_server_get_client_opts(bqws_socket *ws)
2920 {
2921 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2922 bqws_assert(ws->is_server);
2923 // no-mutex(state): There's an inherent race condition with multiple accepts
2924 bqws_assert(ws->state.state == BQWS_STATE_CONNECTING);
2925  
2926 bqws_mutex_lock(&ws->io.mutex);
2927 0 bqws_client_opts *opts = ws->io.opts_from_client;
2928 bqws_mutex_unlock(&ws->io.mutex);
2929  
2930 0 return opts;
2931 }
2932  
2933 0 void bqws_server_accept(bqws_socket *ws, const char *protocol)
2934 {
2935 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2936 bqws_assert(ws->is_server);
2937 // no-mutex(state): There's an inherent race condition with multiple accepts
2938 bqws_assert(ws->state.state == BQWS_STATE_CONNECTING);
2939 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
2940  
2941 // Use emtpy string to differentiate from not set
2942 0 ▶ if (!protocol) protocol = "";
Branch: 1 branch
BranchTrueFalseTotal
if (!protocol) protocol = ""; 0 0 0
2943  
2944 bqws_mutex_lock(&ws->state.mutex);
2945 0 ▶ if (!ws->state.chosen_protocol) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->state.chosen_protocol) { 0 0 0
2946 0 ws->state.chosen_protocol = ws_copy_str(ws, protocol);
2947 }
2948 bqws_mutex_unlock(&ws->state.mutex);
2949 }
2950  
2951 0 void bqws_server_reject(bqws_socket *ws)
2952 {
2953 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2954 bqws_assert(ws->is_server);
2955  
2956 0 ws_fail(ws, BQWS_ERR_SERVER_REJECT);
2957 0 }
2958  
2959 41 bqws_state bqws_get_state(const bqws_socket *ws)
2960 {
2961 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2962 // no-mutex(state): We can always underestimate the state
2963 41 bqws_state state = ws->state.state, override_state = ws->state.override_state;
2964 41 ▶ if (override_state > state) state = override_state;
Branch: 1 branch
BranchTrueFalseTotal
if (override_state > state) state = override_state; 0 41 41
2965 41 return state;
2966 }
2967  
2968 231 bqws_error bqws_get_error(const bqws_socket *ws)
2969 {
2970 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2971 231 return ws->err;
2972 }
2973  
2974 0 bool bqws_is_connecting(const bqws_socket *ws)
2975 {
2976 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2977 // no-mutex(state): We can always underestimate the state
2978 0 bqws_state state = ws->state.state, override_state = ws->state.override_state;
2979 0 ▶ if (override_state > state) state = override_state;
Branch: 1 branch
BranchTrueFalseTotal
if (override_state > state) state = override_state; 0 0 0
2980 0 return state == BQWS_STATE_CONNECTING;
2981 }
2982  
2983 0 bool bqws_is_closed(const bqws_socket *ws)
2984 {
2985 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2986 // no-mutex(state): We can always underestimate the state
2987 0 bqws_state state = ws->state.state, override_state = ws->state.override_state;
2988 0 ▶ if (override_state > state) state = override_state;
Branch: 1 branch
BranchTrueFalseTotal
if (override_state > state) state = override_state; 0 0 0
2989 0 return state == BQWS_STATE_CLOSED;
2990 }
2991  
2992 7 size_t bqws_get_memory_used(const bqws_socket *ws)
2993 {
2994 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2995 // no-mutex(alloc): This doesn't need to be accurate
2996 7 return ws->alloc.memory_used;
2997 }
2998  
2999 0 bool bqws_is_server(const bqws_socket *ws)
3000 {
3001 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3002 0 return ws->is_server;
3003 }
3004  
3005 0 void *bqws_user_data(const bqws_socket *ws)
3006 {
3007 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3008 0 return (void*)ws->user_data;
3009 }
3010  
3011 0 size_t bqws_user_data_size(const bqws_socket *ws)
3012 {
3013 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3014 0 return ws->user_size;
3015 }
3016  
3017 0 const char *bqws_get_name(const bqws_socket *ws)
3018 {
3019 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3020 0 return ws->name;
3021 }
3022  
3023 0 bqws_stats bqws_get_stats(const bqws_socket *ws)
3024 {
3025 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3026  
3027 bqws_stats stats;
3028 0 msg_queue_get_stats((bqws_msg_queue*)&ws->recv_queue, &stats.recv);
3029 0 msg_queue_get_stats((bqws_msg_queue*)&ws->send_queue, &stats.send);
3030 0 return stats;
3031 }
3032  
3033 0 void *bqws_get_io_user(const bqws_socket *ws)
3034 {
3035 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3036  
3037 0 return ws->user_io.user;
3038 }
3039  
3040 0 bool bqws_get_io_closed(const bqws_socket *ws)
3041 {
3042 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3043  
3044 // no-mutex(state): This can be inaccurate
3045 0 return ws->state.io_closed;
3046 }
3047  
3048 15 bqws_limits bqws_get_limits(const bqws_socket *ws)
3049 {
3050 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3051 15 return ws->limits;
3052 }
3053  
3054 15 void bqws_set_limits(bqws_socket *ws, const bqws_limits *limits)
3055 {
3056 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3057 bqws_assert(limits);
3058  
3059 15 bqws_limits copy = *limits;
3060 15 ws_expand_default_limits(&copy);
3061 15 ws->limits = copy;
3062 15 }
3063  
3064 0 bqws_close_reason bqws_get_peer_close_reason(const bqws_socket *ws)
3065 {
3066 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3067  
3068 bqws_mutex_lock((bqws_mutex*)&ws->state.mutex);
3069 0 bqws_close_reason reason = ws->state.peer_reason;
3070 bqws_mutex_unlock((bqws_mutex*)&ws->state.mutex);
3071  
3072 0 return reason;
3073 }
3074  
3075 0 bqws_error bqws_get_peer_error(const bqws_socket *ws)
3076 {
3077 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3078  
3079 bqws_mutex_lock((bqws_mutex*)&ws->state.mutex);
3080 0 bqws_error err = ws->state.peer_err;
3081 bqws_mutex_unlock((bqws_mutex*)&ws->state.mutex);
3082  
3083 0 return err;
3084 }
3085  
3086 0 const char *bqws_get_protocol(const bqws_socket *ws)
3087 {
3088 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3089  
3090 // TODO: Cache this pointer outside of the state mutex
3091 bqws_mutex_lock((bqws_mutex*)&ws->state.mutex);
3092 0 const char *protocol = ws->state.chosen_protocol;
3093 bqws_mutex_unlock((bqws_mutex*)&ws->state.mutex);
3094  
3095 0 return protocol;
3096 }
3097  
3098 108 bqws_msg *bqws_recv(bqws_socket *ws)
3099 {
3100 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3101  
3102 // Preserve messages that were fully received before a later frame in the
3103 // same input batch failed validation. No new messages are queued after the
3104 // error, but already-validated messages remain observable in wire order.
3105 // Messages are re-combined in `recv_queue` if
3106 // `recv_partial_messages` is disabled.
3107  
3108 108 bqws_msg_imp *imp = msg_dequeue(&ws->recv_queue);
3109 108 ▶ if (!imp) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!imp) return NULL; 60 48 108
3110 bqws_assert(imp->magic == BQWS_MSG_MAGIC);
3111  
3112 48 msg_release_ownership(ws, imp);
3113 48 return &imp->msg;
3114 }
3115  
3116 48 void bqws_free_msg(bqws_msg *msg)
3117 {
3118 48 ▶ if (!msg) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg) return; 0 48 48
3119  
3120 48 bqws_msg_imp *imp = msg_imp(msg);
3121 bqws_assert(imp->magic == BQWS_MSG_MAGIC);
3122 bqws_assert(imp->owner == NULL);
3123  
3124 48 imp->magic = BQWS_DELETED_MAGIC;
3125  
3126 48 bqws_allocator at = imp->allocator;
3127 48 bqws_allocator_free(&at, imp, msg_alloc_size(msg));
3128 }
3129  
3130 2 void bqws_send(bqws_socket *ws, bqws_msg_type type, const void *data, size_t size)
3131 {
3132 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3133 bqws_assert((type & BQWS_MSG_PARTIAL_BIT) == 0);
3134 2 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 2 2
3135 bqws_assert(size == 0 || data);
3136  
3137 2 bqws_msg_imp *imp = msg_alloc(ws, type, size);
3138 2 ▶ if (!imp) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!imp) return; 0 2 2
3139  
3140 2 memcpy(imp->msg.data, data, size);
3141 2 ws_enqueue_send(ws, imp);
3142 }
3143  
3144 15 static void unblock_bqws_send_data(
3145 bqws_socket *ws,
3146 bqws_msg_type type,
3147 const void *data,
3148 size_t size,
3149 bool compressed)
3150 {
3151 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3152 bqws_assert(type == BQWS_MSG_TEXT || type == BQWS_MSG_BINARY);
3153 15 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 15 15
3154 bqws_assert(size == 0 || data);
3155  
3156 15 bqws_msg_imp *imp = msg_alloc(ws, type, size);
3157 15 ▶ if (!imp) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!imp) return; 0 15 15
3158  
3159 15 imp->compressed = compressed;
3160 15 memcpy(imp->msg.data, data, size);
3161 15 ws_enqueue_send(ws, imp);
3162 }
3163  
3164 0 void bqws_send_binary(bqws_socket *ws, const void *data, size_t size)
3165 {
3166 0 bqws_send(ws, BQWS_MSG_BINARY, data, size);
3167 0 }
3168  
3169 0 void bqws_send_text(bqws_socket *ws, const char *str)
3170 {
3171 bqws_assert(str);
3172 0 bqws_send(ws, BQWS_MSG_TEXT, str, strlen(str));
3173 0 }
3174  
3175 0 void bqws_send_text_len(bqws_socket *ws, const void *str, size_t len)
3176 {
3177 0 bqws_send(ws, BQWS_MSG_TEXT, str, len);
3178 0 }
3179  
3180 0 bqws_msg *bqws_allocate_msg(bqws_socket *ws, bqws_msg_type type, size_t size)
3181 {
3182 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3183 0 ▶ if (ws->err) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return NULL; 0 0 0
3184  
3185 0 bqws_msg_imp *imp = msg_alloc(ws, type, size);
3186 0 ▶ if (!imp) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!imp) return NULL; 0 0 0
3187  
3188 0 msg_release_ownership(ws, imp);
3189 0 return &imp->msg;
3190 }
3191  
3192 0 void bqws_send_msg(bqws_socket *ws, bqws_msg *msg)
3193 {
3194 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3195 bqws_assert(msg && (msg->type == BQWS_MSG_TEXT || msg->type == BQWS_MSG_BINARY));
3196 bqws_assert(msg->size <= msg->capacity);
3197  
3198 0 bqws_msg_imp *imp = msg_imp(msg);
3199 bqws_assert(imp->magic == BQWS_MSG_MAGIC);
3200  
3201 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
3202  
3203 0 ▶ if (!msg_acquire_ownership(ws, imp)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg_acquire_ownership(ws, imp)) return; 0 0 0
3204  
3205 0 ws_enqueue_send(ws, imp);
3206 }
3207  
3208 0 void bqws_send_begin(bqws_socket *ws, bqws_msg_type type)
3209 {
3210 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3211 bqws_assert(type == BQWS_MSG_TEXT || type == BQWS_MSG_BINARY);
3212 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
3213  
3214 bqws_mutex_lock(&ws->partial.mutex);
3215  
3216 bqws_assert(ws->partial.send_partial_type == BQWS_MSG_INVALID);
3217 bqws_assert(ws->partial.next_partial_to_send == NULL);
3218  
3219 0 ws->partial.send_partial_type = type;
3220  
3221 bqws_mutex_unlock(&ws->partial.mutex);
3222 }
3223  
3224 0 void bqws_send_append(bqws_socket *ws, const void *data, size_t size)
3225 {
3226 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3227 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
3228  
3229 bqws_mutex_lock(&ws->partial.mutex);
3230  
3231 bqws_assert(ws->partial.send_partial_type != BQWS_MSG_INVALID);
3232  
3233 0 ▶ if (ws->partial.next_partial_to_send) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->partial.next_partial_to_send) { 0 0 0
3234 bqws_assert(ws->partial.next_partial_to_send->magic == BQWS_MSG_MAGIC);
3235 0 ws_enqueue_send(ws, ws->partial.next_partial_to_send);
3236 }
3237  
3238 0 bqws_msg_type partial_type = (bqws_msg_type)(ws->partial.send_partial_type | BQWS_MSG_PARTIAL_BIT);
3239 0 bqws_msg_imp *imp = msg_alloc(ws, partial_type, size);
3240 0 ▶ if (imp) {
Branch: 1 branch
BranchTrueFalseTotal
if (imp) { 0 0 0
3241 0 memcpy(imp->msg.data, data, size);
3242 0 ws->partial.next_partial_to_send = imp;
3243 }
3244  
3245 bqws_mutex_unlock(&ws->partial.mutex);
3246 }
3247  
3248 0 void bqws_send_append_str(bqws_socket *ws, const char *str)
3249 {
3250 0 bqws_send_append(ws, str, strlen(str));
3251 0 }
3252  
3253 0 void bqws_send_append_msg(bqws_socket *ws, bqws_msg *msg)
3254 {
3255 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3256 bqws_assert(msg->type == BQWS_MSG_TEXT || msg->type == BQWS_MSG_BINARY);
3257 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
3258  
3259 bqws_mutex_lock(&ws->partial.mutex);
3260  
3261 bqws_assert(ws->partial.send_partial_type != BQWS_MSG_INVALID);
3262 bqws_assert((ws->partial.send_partial_type & BQWS_MSG_TYPE_MASK) == msg->type);
3263  
3264 0 ▶ if (ws->partial.next_partial_to_send) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->partial.next_partial_to_send) { 0 0 0
3265 bqws_assert(ws->partial.next_partial_to_send->magic == BQWS_MSG_MAGIC);
3266 0 ws_enqueue_send(ws, ws->partial.next_partial_to_send);
3267 }
3268  
3269 0 bqws_msg_imp *imp = msg_imp(msg);
3270 0 ▶ if (!msg_acquire_ownership(ws, imp)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg_acquire_ownership(ws, imp)) return; 0 0 0
3271  
3272 0 msg->type = (bqws_msg_type)(ws->partial.send_partial_type | BQWS_MSG_PARTIAL_BIT);
3273 0 ws->partial.next_partial_to_send = imp;
3274  
3275 bqws_mutex_unlock(&ws->partial.mutex);
3276 }
3277  
3278 0 void bqws_send_finish(bqws_socket *ws)
3279 {
3280 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3281 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
3282  
3283 bqws_mutex_lock(&ws->partial.mutex);
3284  
3285 bqws_assert(ws->partial.send_partial_type != BQWS_MSG_INVALID);
3286  
3287 0 ▶ if (ws->partial.next_partial_to_send) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->partial.next_partial_to_send) { 0 0 0
3288 bqws_assert(ws->partial.next_partial_to_send->magic == BQWS_MSG_MAGIC);
3289 0 bqws_msg_type type = ws->partial.next_partial_to_send->msg.type;
3290 0 ws->partial.next_partial_to_send->msg.type = (bqws_msg_type)(type | BQWS_MSG_FINAL_BIT);
3291 0 ws_enqueue_send(ws, ws->partial.next_partial_to_send);
3292 0 ws->partial.next_partial_to_send = NULL;
3293 }
3294  
3295 0 ws->partial.send_partial_type = BQWS_MSG_INVALID;
3296  
3297 bqws_mutex_unlock(&ws->partial.mutex);
3298 }
3299  
3300 2 void bqws_send_ping(bqws_socket *ws, const void *data, size_t size)
3301 {
3302 2 bqws_send(ws, BQWS_MSG_CONTROL_PING, data, size);
3303 2 }
3304  
3305 0 void bqws_send_pong(bqws_socket *ws, const void *data, size_t size)
3306 {
3307 0 bqws_send(ws, BQWS_MSG_CONTROL_PONG, data, size);
3308 0 }
3309  
3310 0 void bqws_update(bqws_socket *ws)
3311 {
3312 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3313  
3314 0 bqws_update_state(ws);
3315 0 bqws_update_io(ws);
3316 0 }
3317  
3318 0 void bqws_update_state(bqws_socket *ws)
3319 {
3320 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3321  
3322 bqws_mutex_lock(&ws->state.mutex);
3323 0 bqws_state state = ws->state.state;
3324 0 char *protocol = ws->state.chosen_protocol;
3325 0 bqws_timestamp start_closing_ts = ws->state.start_closing_ts;
3326 bqws_mutex_unlock(&ws->state.mutex);
3327  
3328 bqws_mutex_lock(&ws->io.mutex);
3329  
3330 0 ▶ if (state == BQWS_STATE_CONNECTING) {
Branch: 1 branch
BranchTrueFalseTotal
if (state == BQWS_STATE_CONNECTING) { 0 0 0
3331  
3332 // If we're connecting but haven't set a protocol and the user
3333 // has provided a verify function or filter run it here.
3334 0 ▶ if (ws->io.client_handshake_done && !protocol && ws->verify_fn) {
Branch: 3 branches
BranchTrueFalseTotal
if (ws->io.client_handshake_done && !protocol && ws->verify_fn) { 0 0 0
if (ws->io.client_handshake_done && !protocol && ws->verify_fn) { 0 0 0
if (ws->io.client_handshake_done && !protocol && ws->verify_fn) { 0 0 0
3335 bqws_assert(ws->is_server);
3336 bqws_assert(ws->io.opts_from_client);
3337 0 ws->verify_fn(ws->verify_user, ws, ws->io.opts_from_client);
3338 }
3339  
3340 // Connect timeout
3341 0 ▶ if (ws->connect_timeout != SIZE_MAX && state == BQWS_STATE_CONNECTING) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->connect_timeout != SIZE_MAX && state == BQWS_STATE_CONNECTING) { 0 0 0
if (ws->connect_timeout != SIZE_MAX && state == BQWS_STATE_CONNECTING) { 0 0 0
3342 0 bqws_timestamp time = bqws_get_timestamp();
3343 0 size_t delta = bqws_timestamp_delta_to_ms(ws->io.start_connect_ts, time);
3344 0 ▶ if (delta > ws->connect_timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (delta > ws->connect_timeout) { 0 0 0
3345 0 ws_fail(ws, BQWS_ERR_CONNECT_TIMEOUT);
3346  
3347 bqws_mutex_lock(&ws->state.mutex);
3348 0 ws_close(ws);
3349 bqws_mutex_unlock(&ws->state.mutex);
3350 }
3351 }
3352  
3353 0 ▶ } else if (state == BQWS_STATE_OPEN) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (state == BQWS_STATE_OPEN) { 0 0 0
3354  
3355 // Automatic PING send
3356 0 ▶ if (ws->ping_interval != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->ping_interval != SIZE_MAX) { 0 0 0
3357 0 bqws_timestamp time = bqws_get_timestamp();
3358 0 size_t delta_read = bqws_timestamp_delta_to_ms(ws->io.last_read_ts, time);
3359 0 size_t delta_ping = bqws_timestamp_delta_to_ms(ws->io.last_ping_ts, time);
3360 0 size_t delta_write = bqws_timestamp_delta_to_ms(ws->io.last_write_ts, time);
3361  
3362 0 size_t delta = delta_read >= delta_write ? delta_read : delta_write;
3363 0 size_t delta_from_ping = delta <= delta_ping ? delta : delta_ping;
3364  
3365 0 ▶ if (delta_from_ping > ws->ping_interval) {
Branch: 1 branch
BranchTrueFalseTotal
if (delta_from_ping > ws->ping_interval) { 0 0 0
3366 0 ws->io.last_ping_ts = time;
3367 // Maybe send PONG only?
3368 0 bqws_send_ping(ws, NULL, 0);
3369 }
3370  
3371 0 ▶ if (ws->ping_response_timeout != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->ping_response_timeout != SIZE_MAX) { 0 0 0
3372 0 ▶ if (delta >= ws->ping_response_timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (delta >= ws->ping_response_timeout) { 0 0 0
3373 0 ws_fail(ws, BQWS_ERR_PING_TIMEOUT);
3374  
3375 bqws_mutex_lock(&ws->state.mutex);
3376 0 ws_close(ws);
3377 bqws_mutex_unlock(&ws->state.mutex);
3378 }
3379 }
3380 }
3381  
3382 0 ▶ } else if (state == BQWS_STATE_CLOSING) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (state == BQWS_STATE_CLOSING) { 0 0 0
3383  
3384 // Close timeout
3385 0 ▶ if (ws->close_timeout != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->close_timeout != SIZE_MAX) { 0 0 0
3386 0 bqws_timestamp time = bqws_get_timestamp();
3387 0 size_t delta = bqws_timestamp_delta_to_ms(start_closing_ts, time);
3388 0 ▶ if (delta > ws->close_timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (delta > ws->close_timeout) { 0 0 0
3389 0 ws_fail(ws, BQWS_ERR_CLOSE_TIMEOUT);
3390  
3391 bqws_mutex_lock(&ws->state.mutex);
3392 0 ws_close(ws);
3393 bqws_mutex_unlock(&ws->state.mutex);
3394 }
3395 }
3396  
3397 }
3398  
3399 bqws_mutex_unlock(&ws->io.mutex);
3400 0 }
3401  
3402 0 void bqws_update_io(bqws_socket *ws)
3403 {
3404 0 bqws_update_io_write(ws);
3405 0 bqws_update_io_read(ws);
3406 0 }
3407  
3408 0 void bqws_update_io_read(bqws_socket *ws)
3409 {
3410 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3411  
3412 0 bool do_read = true;
3413  
3414 bqws_mutex_lock(&ws->io.mutex);
3415  
3416 // If read and write are stopped close the IO
3417 bqws_mutex_lock(&ws->state.mutex);
3418 0 ▶ if (!ws->state.io_started) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->state.io_started) { 0 0 0
3419 0 ▶ if (ws->user_io.init_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.init_fn) { 0 0 0
3420 0 ws->user_io.init_fn(ws->user_io.user, ws);
3421 }
3422 0 ws->state.io_started = true;
3423 }
3424 0 ▶ if (ws->state.stop_read && ws->state.stop_write) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->state.stop_read && ws->state.stop_write) { 0 0 0
if (ws->state.stop_read && ws->state.stop_write) { 0 0 0
3425 0 ▶ if (ws->user_io.close_fn && !ws->state.io_closed) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->user_io.close_fn && !ws->state.io_closed) { 0 0 0
if (ws->user_io.close_fn && !ws->state.io_closed) { 0 0 0
3426 0 ws->user_io.close_fn(ws->user_io.user, ws);
3427 }
3428 0 ws->state.io_closed = true;
3429 }
3430 0 do_read = !ws->state.stop_read;
3431 bqws_mutex_unlock(&ws->state.mutex);
3432  
3433 // TODO: Throttle reads
3434 0 ▶ if (do_read) {
Branch: 1 branch
BranchTrueFalseTotal
if (do_read) { 0 0 0
3435 0 ▶ if (ws->user_io.recv_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.recv_fn) { 0 0 0
3436 0 ▶ while (ws_read_data(ws, ws->user_io.recv_fn, ws->user_io.user)) {
Branch: 1 branch
BranchTrueFalseTotal
while (ws_read_data(ws, ws->user_io.recv_fn, ws->user_io.user)) { 0 0 0
3437 // Keep reading as long as there is space
3438 }
3439 }
3440 }
3441  
3442 bqws_mutex_unlock(&ws->io.mutex);
3443 0 }
3444  
3445 0 void bqws_update_io_write(bqws_socket *ws)
3446 {
3447 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3448  
3449 0 bool do_write = true;
3450  
3451 bqws_mutex_lock(&ws->io.mutex);
3452  
3453 // If read and write are stopped close the IO
3454 bqws_mutex_lock(&ws->state.mutex);
3455 0 ▶ if (!ws->state.io_started) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->state.io_started) { 0 0 0
3456 0 ▶ if (ws->user_io.init_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.init_fn) { 0 0 0
3457 0 ws->user_io.init_fn(ws->user_io.user, ws);
3458 }
3459 0 ws->state.io_started = true;
3460 }
3461 0 ▶ if (ws->state.stop_read && ws->state.stop_write) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->state.stop_read && ws->state.stop_write) { 0 0 0
if (ws->state.stop_read && ws->state.stop_write) { 0 0 0
3462 0 ▶ if (ws->user_io.close_fn && !ws->state.io_closed) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->user_io.close_fn && !ws->state.io_closed) { 0 0 0
if (ws->user_io.close_fn && !ws->state.io_closed) { 0 0 0
3463 0 ws->user_io.close_fn(ws->user_io.user, ws);
3464 }
3465 0 ws->state.io_closed = true;
3466 }
3467 0 do_write = !ws->state.stop_write;
3468 bqws_mutex_unlock(&ws->state.mutex);
3469  
3470 0 ▶ if (do_write) {
Branch: 1 branch
BranchTrueFalseTotal
if (do_write) { 0 0 0
3471 0 ▶ if (ws->user_io.send_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.send_fn) { 0 0 0
3472 0 ▶ while (ws_write_data(ws, ws->user_io.send_fn, ws->user_io.user)) {
Branch: 1 branch
BranchTrueFalseTotal
while (ws_write_data(ws, ws->user_io.send_fn, ws->user_io.user)) { 0 0 0
3473 // Keep writing as long as there is space
3474 }
3475 }
3476  
3477 // Re-check if we should stop write if the socket got closed
3478 bqws_mutex_lock(&ws->state.mutex);
3479 0 do_write = !ws->state.stop_write;
3480 bqws_mutex_unlock(&ws->state.mutex);
3481  
3482 0 ▶ if (ws->user_io.flush_fn && do_write) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->user_io.flush_fn && do_write) { 0 0 0
if (ws->user_io.flush_fn && do_write) { 0 0 0
3483 0 ▶ if (!ws->user_io.flush_fn(ws->user_io.user, ws)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->user_io.flush_fn(ws->user_io.user, ws)) { 0 0 0
3484 0 ws_fail(ws, BQWS_ERR_IO_WRITE);
3485 }
3486 }
3487 }
3488  
3489 bqws_mutex_unlock(&ws->io.mutex);
3490 0 }
3491  
3492 60 size_t bqws_read_from(bqws_socket *ws, const void *data, size_t size)
3493 {
3494 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3495 bqws_assert(!ws->user_io.recv_fn);
3496  
3497 bqws_mutex_lock(&ws->io.mutex);
3498  
3499 bqws_mem_stream s;
3500 60 s.ptr = (char*)data;
3501 60 s.end = s.ptr + size;
3502  
3503 121 ▶ while (ws_read_data(ws, &mem_stream_recv, &s)) {
Branch: 1 branch
BranchTrueFalseTotal
while (ws_read_data(ws, &mem_stream_recv, &s)) { 61 60 121
3504 // Keep reading as long as there is space
3505 }
3506  
3507 bqws_mutex_unlock(&ws->io.mutex);
3508  
3509 60 return s.ptr - (char*)data;
3510 }
3511  
3512 77 size_t bqws_write_to(bqws_socket *ws, void *data, size_t size)
3513 {
3514 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3515 bqws_assert(!ws->user_io.send_fn);
3516  
3517 bqws_mutex_lock(&ws->io.mutex);
3518  
3519 bqws_mem_stream s;
3520 77 s.ptr = (char*)data;
3521 77 s.end = s.ptr + size;
3522  
3523 133 ▶ while (ws_write_data(ws, &mem_stream_send, &s)) {
Branch: 1 branch
BranchTrueFalseTotal
while (ws_write_data(ws, &mem_stream_send, &s)) { 56 77 133
3524 // Keep writing as long as there is space
3525 }
3526  
3527 77 ▶ if (ws->user_io.flush_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.flush_fn) { 0 77 77
3528 0 ▶ if (!ws->user_io.flush_fn(ws->user_io.user, ws)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->user_io.flush_fn(ws->user_io.user, ws)) { 0 0 0
3529 0 ws_fail(ws, BQWS_ERR_IO_WRITE);
3530 }
3531 }
3532  
3533 bqws_mutex_unlock(&ws->io.mutex);
3534  
3535 77 return s.ptr - (char*)data;
3536 }
3537  
3538 0 void bqws_direct_push_msg(bqws_socket *ws, bqws_msg *msg)
3539 {
3540 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3541 bqws_assert(msg && msg->size <= msg->capacity);
3542  
3543 0 bqws_msg_imp *imp = msg_imp(msg);
3544 bqws_assert(imp->magic == BQWS_MSG_MAGIC);
3545  
3546 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
3547  
3548 0 ▶ if (!msg_acquire_ownership(ws, imp)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg_acquire_ownership(ws, imp)) return; 0 0 0
3549  
3550 0 ▶ if (ws->log_recv) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->log_recv) { 0 0 0
3551 0 ws_log2(ws, "Direct recv: ", bqws_msg_type_str(msg->type));
3552 }
3553  
3554 0 ws_enqueue_recv(ws, imp);
3555 }
3556  
3557 0 void bqws_direct_set_override_state(bqws_socket *ws, bqws_state state)
3558 {
3559 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3560  
3561 0 ws_log2(ws, "Override state: ", bqws_state_str(state));
3562  
3563 bqws_mutex_lock(&ws->state.mutex);
3564 0 ws->state.override_state = state;
3565 bqws_mutex_unlock(&ws->state.mutex);
3566 0 }
3567  
3568 15 static void unblock_bqws_set_allow_rsv1(bqws_socket *ws, bool allow)
3569 {
3570 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3571 15 ws->allow_rsv1 = allow;
3572 15 }
3573  
3574 0 void bqws_direct_fail(bqws_socket *ws, bqws_error err)
3575 {
3576 0 ws_fail(ws, err);
3577 0 }
3578  
3579 0 bool bqws_parse_url(bqws_url *url, const char *str)
3580 {
3581 // Format [wss://][host.example.com][:1234][/path]
3582  
3583 0 const char *scheme = str;
3584 0 const char *scheme_end = strstr(scheme, "://");
3585 0 ▶ const char *host = scheme_end ? scheme_end + 3 : scheme;
Branch: 1 branch
BranchTrueFalseTotal
const char *host = scheme_end ? scheme_end + 3 : scheme; 0 0 0
3586 0 const char *port_start = host;
3587 0 ▶ if (*host == '[') {
Branch: 1 branch
BranchTrueFalseTotal
if (*host == '[') { 0 0 0
3588 // Skip IPv6 address
3589 0 port_start = strstr(host, "]");
3590 0 ▶ if (!port_start) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!port_start) return false; 0 0 0
3591 }
3592 0 const char *port = strstr(port_start, ":");
3593 0 const char *path = strstr(port_start, "/");
3594 0 ▶ if (!path) path = port_start + strlen(port_start);
Branch: 1 branch
BranchTrueFalseTotal
if (!path) path = port_start + strlen(port_start); 0 0 0
3595 0 ▶ if (port && port > path) port = NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (port && port > path) port = NULL; 0 0 0
if (port && port > path) port = NULL; 0 0 0
3596 0 ▶ const char *host_end = port ? port : path;
Branch: 1 branch
BranchTrueFalseTotal
const char *host_end = port ? port : path; 0 0 0
3597  
3598 0 ▶ size_t scheme_len = scheme_end ? scheme_end - scheme : 0;
Branch: 1 branch
BranchTrueFalseTotal
size_t scheme_len = scheme_end ? scheme_end - scheme : 0; 0 0 0
3599 0 size_t host_len = host_end - host;
3600 0 ▶ if (scheme_len >= sizeof(url->scheme)) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (scheme_len >= sizeof(url->scheme)) return false; 0 0 0
3601 0 ▶ if (host_len >= sizeof(url->host)) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (host_len >= sizeof(url->host)) return false; 0 0 0
3602  
3603 0 ▶ bool secure = scheme_len == 3 && !memcmp(scheme, "wss", 3);
Branch: 2 branches
BranchTrueFalseTotal
bool secure = scheme_len == 3 && !memcmp(scheme, "wss", 3); 0 0 0
bool secure = scheme_len == 3 && !memcmp(scheme, "wss", 3); 0 0 0
3604  
3605 int port_num;
3606 0 ▶ if (port) {
Branch: 1 branch
BranchTrueFalseTotal
if (port) { 0 0 0
3607 char *port_end;
3608 0 port_num = (int)strtol(port + 1, &port_end, 10);
3609 0 ▶ if (port_end != path) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (port_end != path) return false; 0 0 0
3610 0 ▶ if (port_num < 0 || port_num > UINT16_MAX) return false;
Branch: 2 branches
BranchTrueFalseTotal
if (port_num < 0 || port_num > UINT16_MAX) return false; 0 0 0
if (port_num < 0 || port_num > UINT16_MAX) return false; 0 0 0
3611 0 port_num = (uint16_t)port_num;
3612 } else {
3613 0 ▶ port_num = secure ? 443 : 80;
Branch: 1 branch
BranchTrueFalseTotal
port_num = secure ? 443 : 80; 0 0 0
3614 }
3615  
3616 // vv No fails below, no writes above ^^
3617  
3618 0 url->port = (uint16_t)port_num;
3619  
3620 0 memcpy(url->scheme, scheme, scheme_len);
3621 0 url->scheme[scheme_len] = '\0';
3622  
3623 0 memcpy(url->host, host, host_len);
3624 0 url->host[host_len] = '\0';
3625  
3626 0 ▶ url->path = *path ? path : "/";
Branch: 1 branch
BranchTrueFalseTotal
url->path = *path ? path : "/"; 0 0 0
3627  
3628 0 url->secure = secure;
3629  
3630 0 return true;
3631 }
3632  
3633 34 const char *bqws_error_str(bqws_error error)
3634 {
3635 34 switch (error) {
3636 0 case BQWS_OK: return "OK";
3637 0 case BQWS_ERR_UNKNOWN: return "UNKNOWN";
3638 0 case BQWS_ERR_SERVER_REJECT: return "SERVER_REJECT";
3639 0 case BQWS_ERR_LIMIT_MAX_MEMORY_USED: return "LIMIT_MAX_MEMORY_USED";
3640 4 case BQWS_ERR_LIMIT_MAX_RECV_MSG_SIZE: return "LIMIT_MAX_RECV_MSG_SIZE";
3641 0 case BQWS_ERR_LIMIT_MAX_HANDSHAKE_SIZE: return "LIMIT_MAX_HANDSHAKE_SIZE";
3642 0 case BQWS_ERR_LIMIT_MAX_PARTIAL_MESSAGE_PARTS: return "LIMIT_MAX_PARTIAL_MESSAGE_PARTS";
3643 0 case BQWS_ERR_CONNECT_TIMEOUT: return "BQWS_ERR_CONNECT_TIMEOUT";
3644 0 case BQWS_ERR_PING_TIMEOUT: return "BQWS_ERR_PING_TIMEOUT";
3645 0 case BQWS_ERR_CLOSE_TIMEOUT: return "BQWS_ERR_CLOSE_TIMEOUT";
3646 0 case BQWS_ERR_ALLOCATOR: return "ALLOCATOR";
3647 2 case BQWS_ERR_BAD_CONTINUATION: return "BAD_CONTINUATION";
3648 2 case BQWS_ERR_UNFINISHED_PARTIAL: return "UNFINISHED_PARTIAL";
3649 0 case BQWS_ERR_PARTIAL_CONTROL: return "PARTIAL_CONTROL";
3650 0 case BQWS_ERR_BAD_OPCODE: return "BAD_OPCODE";
3651 11 case BQWS_ERR_RESERVED_BIT: return "RESERVED_BIT";
3652 6 case BQWS_ERR_BAD_CLOSE: return "BAD_CLOSE";
3653 9 case BQWS_ERR_BAD_UTF8: return "BAD_UTF8";
3654 0 case BQWS_ERR_IO_WRITE: return "IO_WRITE";
3655 0 case BQWS_ERR_IO_READ: return "IO_READ";
3656 0 case BQWS_ERR_BAD_HANDSHAKE: return "BAD_HANDSHAKE";
3657 0 case BQWS_ERR_UNSUPPORTED_VERSION: return "UNSUPPORTED_VERSION";
3658 0 case BQWS_ERR_TOO_MANY_HEADERS: return "TOO_MANY_HEADERS";
3659 0 case BQWS_ERR_TOO_MANY_PROTOCOLS: return "TOO_MANY_PROTOCOLS";
3660 0 case BQWS_ERR_HEADER_KEY_TOO_LONG: return "HEADER_KEY_TOO_LONG";
3661 0 case BQWS_ERR_HEADER_BAD_ACCEPT: return "HEADER_BAD_ACCEPT";
3662 0 case BQWS_ERR_HEADER_PARSE: return "HEADER_PARSE";
3663 0 default: return "(unknown)";
3664 }
3665 }
3666  
3667 0 const char *bqws_msg_type_str(bqws_msg_type type)
3668 {
3669 0 switch (type) {
3670 0 case BQWS_MSG_TEXT: return "TEXT";
3671 0 case BQWS_MSG_BINARY: return "BINARY";
3672 0 case BQWS_MSG_PARTIAL_TEXT: return "PARTIAL_TEXT";
3673 0 case BQWS_MSG_PARTIAL_BINARY: return "PARTIAL_BINARY";
3674 0 case BQWS_MSG_FINAL_TEXT: return "FINAL_TEXT";
3675 0 case BQWS_MSG_FINAL_BINARY: return "FINAL_BINARY";
3676 0 case BQWS_MSG_CONTROL_CLOSE: return "CONTROL_CLOSE";
3677 0 case BQWS_MSG_CONTROL_PING: return "CONTROL_PING";
3678 0 case BQWS_MSG_CONTROL_PONG: return "CONTROL_PONG";
3679 0 default: return "(unknown)";
3680 }
3681 }
3682  
3683 0 const char *bqws_state_str(bqws_state state)
3684 {
3685 0 switch (state) {
3686 0 case BQWS_STATE_INVALID: return "INVALID";
3687 0 case BQWS_STATE_CONNECTING: return "CONNECTING";
3688 0 case BQWS_STATE_OPEN: return "OPEN";
3689 0 case BQWS_STATE_CLOSING: return "CLOSING";
3690 0 case BQWS_STATE_CLOSED: return "CLOSED";
3691 0 default: return "(unknown)";
3692 }
3693 }
3694  
3695 // TODO: Add a define for this
3696  
3697 /* ================ sha1.c ================ */
3698 /*
3699 SHA-1 in C
3700 By Steve Reid <steve@edmweb.com>
3701 100% Public Domain
3702 Test Vectors (from FIPS PUB 180-1)
3703 "abc"
3704 A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
3705 "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
3706 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
3707 A million repetitions of "a"
3708 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
3709 */
3710  
3711 typedef struct {
3712 uint32_t state[5];
3713 uint32_t count[2];
3714 unsigned char buffer[64];
3715 } SHA1_CTX;
3716  
3717 #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
3718  
3719 /* blk0() and blk() perform the initial expand. */
3720 /* I got the idea of expanding during the round function from SSLeay */
3721 #define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
3722 |(rol(block->l[i],8)&0x00FF00FF))
3723 #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
3724 ^block->l[(i+2)&15]^block->l[i&15],1))
3725  
3726 /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
3727 #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
3728 #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
3729 #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
3730 #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
3731 #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
3732  
3733 /* Hash a single 512-bit block. This is the core of the algorithm. */
3734  
3735 0 static void SHA1Transform(uint32_t state[5], const void *buffer)
3736 {
3737 uint32_t a, b, c, d, e;
3738 typedef union {
3739 unsigned char c[64];
3740 uint32_t l[16];
3741 } CHAR64LONG16;
3742 0 CHAR64LONG16 block_buf, *block = &block_buf;
3743 0 memcpy(block, buffer, 64);
3744 /* Copy context->state[] to working vars */
3745 0 a = state[0];
3746 0 b = state[1];
3747 0 c = state[2];
3748 0 d = state[3];
3749 0 e = state[4];
3750 /* 4 rounds of 20 operations each. Loop unrolled. */
3751 0 R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
3752 0 R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
3753 0 R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
3754 0 R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
3755 0 R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
3756 0 R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
3757 0 R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
3758 0 R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
3759 0 R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
3760 0 R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
3761 0 R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
3762 0 R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
3763 0 R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
3764 0 R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
3765 0 R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
3766 0 R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
3767 0 R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
3768 0 R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
3769 0 R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
3770 0 R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
3771 /* Add the working vars back into context.state[] */
3772 0 state[0] += a;
3773 0 state[1] += b;
3774 0 state[2] += c;
3775 0 state[3] += d;
3776 0 state[4] += e;
3777 0 }
3778  
3779 /* SHA1Init - Initialize new context */
3780  
3781 0 static void SHA1Init(SHA1_CTX* context)
3782 {
3783 /* SHA1 initialization constants */
3784 0 context->state[0] = 0x67452301;
3785 0 context->state[1] = 0xEFCDAB89;
3786 0 context->state[2] = 0x98BADCFE;
3787 0 context->state[3] = 0x10325476;
3788 0 context->state[4] = 0xC3D2E1F0;
3789 0 context->count[0] = context->count[1] = 0;
3790 0 }
3791  
3792 /* Run your data through this. */
3793  
3794 0 static void SHA1Update(SHA1_CTX* context, const void* data, uint32_t len)
3795 {
3796 uint32_t i, j;
3797 0 const char *bytes = (const char *)data;
3798  
3799 0 j = context->count[0];
3800 0 ▶ if ((context->count[0] += len << 3) < j)
Branch: 1 branch
BranchTrueFalseTotal
if ((context->count[0] += len << 3) < j) 0 0 0
3801 0 context->count[1]++;
3802 0 context->count[1] += (len>>29);
3803 0 j = (j >> 3) & 63;
3804 0 ▶ if ((j + len) > 63) {
Branch: 1 branch
BranchTrueFalseTotal
if ((j + len) > 63) { 0 0 0
3805 0 memcpy(&context->buffer[j], data, (i = 64-j));
3806 0 SHA1Transform(context->state, context->buffer);
3807 0 ▶ for ( ; i + 63 < len; i += 64) {
Branch: 1 branch
BranchTrueFalseTotal
for ( ; i + 63 < len; i += 64) { 0 0 0
3808 0 SHA1Transform(context->state, &bytes[i]);
3809 }
3810 0 j = 0;
3811 }
3812 0 else i = 0;
3813 0 memcpy(&context->buffer[j], &bytes[i], len - i);
3814 0 }
3815  
3816  
3817 /* Add padding and return the message digest. */
3818  
3819 0 static void SHA1Final(unsigned char digest[20], SHA1_CTX* context)
3820 {
3821 unsigned i;
3822 unsigned char finalcount[8];
3823 unsigned char c;
3824  
3825 0 ▶ for (i = 0; i < 8; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 8; i++) { 0 0 0
3826 0 finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
3827 0 >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */
3828 }
3829 0 c = 0200;
3830 0 SHA1Update(context, &c, 1);
3831 0 ▶ while ((context->count[0] & 504) != 448) {
Branch: 1 branch
BranchTrueFalseTotal
while ((context->count[0] & 504) != 448) { 0 0 0
3832 0 c = 0000;
3833 0 SHA1Update(context, &c, 1);
3834 }
3835 0 SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */
3836 0 ▶ for (i = 0; i < 20; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 20; i++) { 0 0 0
3837 0 digest[i] = (unsigned char)
3838 0 ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
3839 }
3840 0 }
3841 /* ================ end of sha1.c ================ */
3842  
3843 0 static void bqws_sha1(uint8_t digest[20], const void *data, size_t size)
3844 {
3845 SHA1_CTX ctx;
3846 0 SHA1Init(&ctx);
3847 0 SHA1Update(&ctx, data, (uint32_t)size);
3848 0 SHA1Final((unsigned char*)digest, &ctx);
3849 0 }
3850  
« blib/lib/Unblock/WebSocket/_UTF8.pm ↑ Summary WebSocket.xs »