vendor/bq_websocket/bq_websocket.c

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