vendor/bq_websocket/bq_websocket.c

filter: Statementstmt 39.1% 609 / 1557 Branchbran 27.9% 287 / 1026 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 34.6% 896 / 2583 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 81 static bqws_timestamp bqws_get_timestamp()
98 {
99 81 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 141 static void ws_log(bqws_socket *ws, const char *str)
497 {
498 141 ▶ 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 141 141
499 141 }
500  
501 5 static void ws_log2(bqws_socket *ws, const char *a, const char *b)
502 {
503 5 ▶ if (!ws->log_fn) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->log_fn) return; 5 0 5
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 5 static void ws_fail(bqws_socket *ws, bqws_error err)
537 {
538 5 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 5 ▶ if (!ws->err) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->err) { 5 0 5
546 5 should_report = true;
547  
548 // vvv Breakpoint here to stop on first error
549 5 ws->err = err;
550  
551 bqws_mutex_unlock(&ws->err_mutex);
552  
553 5 ws_log2(ws, "Fail: ", bqws_error_str(err));
554  
555 // Try to send an error close message
556 5 ▶ 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) { 5 0 5
if (ws->state.state == BQWS_STATE_OPEN && !ws->state.close_to_send) { 5 0 5
557 5 bqws_msg_imp *close_msg = (bqws_msg_imp*)ws->state.error_msg_data;
558 5 close_msg->magic = BQWS_MSG_MAGIC;
559 5 close_msg->allocator.free_fn = &null_free;
560 5 close_msg->owner = ws;
561 5 close_msg->prev = NULL;
562 5 close_msg->msg.socket = ws;
563 5 close_msg->msg.capacity = sizeof(bqws_err_close_data);
564 5 close_msg->msg.size = sizeof(bqws_err_close_data);
565 5 close_msg->msg.type = BQWS_MSG_CONTROL_CLOSE;
566  
567 bqws_close_reason reason;
568 5 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 4 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 4 reason = BQWS_CLOSE_PROTOCOL_ERROR;
580 4 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 5 bqws_err_close_data *data = (bqws_err_close_data*)close_msg->msg.data;
592 5 data->code_be[0] = (uint8_t)(reason >> 8);
593 5 data->code_be[1] = (uint8_t)(reason >> 0);
594 5 memcpy(data->magic, "BQWS", 4);
595 5 data->error_be[0] = (uint8_t)(err >> 24);
596 5 data->error_be[1] = (uint8_t)(err >> 16);
597 5 data->error_be[2] = (uint8_t)(err >> 8);
598 5 data->error_be[3] = (uint8_t)(err >> 0);
599  
600 5 ws->state.close_to_send = close_msg;
601 5 ws->state.state = BQWS_STATE_CLOSING;
602 5 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 5 ▶ 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 5 5
618 5 ▶ 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 5 5
619  
620 bqws_mutex_unlock(&ws->state.mutex);
621  
622 5 ▶ if (ws->error_fn && should_report) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->error_fn && should_report) { 0 5 5
if (ws->error_fn && should_report) { 0 0 0
623 0 ws->error_fn(ws->error_user, ws, err);
624 }
625 5 }
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 86 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 86 bqws_mem_stream *s = (bqws_mem_stream*)user;
639 86 size_t left = s->end - s->ptr;
640 86 size_t to_copy = size;
641 86 ▶ if (to_copy > left) to_copy = left;
Branch: 1 branch
BranchTrueFalseTotal
if (to_copy > left) to_copy = left; 0 86 86
642 86 memcpy(s->ptr, data, to_copy);
643 86 s->ptr += to_copy;
644 86 return to_copy;
645 }
646  
647 83 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 83 bqws_mem_stream *s = (bqws_mem_stream*)user;
651 83 size_t left = s->end - s->ptr;
652 83 size_t to_copy = max_size;
653 83 ▶ if (to_copy > left) to_copy = left;
Branch: 1 branch
BranchTrueFalseTotal
if (to_copy > left) to_copy = left; 82 1 83
654 83 memcpy(data, s->ptr, to_copy);
655 83 s->ptr += to_copy;
656 83 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 261 void bqws_allocator_free(const bqws_allocator *at, void *ptr, size_t size)
710 {
711 261 ▶ if (size == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (size == 0) return; 110 151 261
712 bqws_assert(ptr != NULL);
713  
714 151 ▶ if (at->free_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (at->free_fn) { 0 151 151
715 // Use defined free directly
716 0 at->free_fn(at->user, ptr, size);
717 151 ▶ } else if (at->realloc_fn) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (at->realloc_fn) { 0 151 151
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 151 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 96 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 96 bool ok = (size <= ws->limits.max_memory_used - ws->alloc.memory_used);
737 96 ▶ if (ok) {
Branch: 1 branch
BranchTrueFalseTotal
if (ok) { 96 0 96
738 96 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 96 return ok;
745 }
746  
747 206 static void ws_remove_memory_used(bqws_socket *ws, size_t size)
748 {
749 206 ▶ if (size == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (size == 0) return; 110 96 206
750  
751 // TODO: Atomics
752 bqws_mutex_lock(&ws->alloc.mutex);
753  
754 bqws_assert(ws->alloc.memory_used >= size);
755 96 ws->alloc.memory_used -= size;
756  
757 bqws_mutex_unlock(&ws->alloc.mutex);
758 }
759  
760 96 static void *ws_alloc(bqws_socket *ws, size_t size)
761 {
762 96 ▶ if (!ws_add_memory_used(ws, size)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws_add_memory_used(ws, size)) return NULL; 0 96 96
763  
764 96 void *ptr = bqws_allocator_alloc(&ws->allocator, size);
765 96 ▶ if (!ptr) ws_fail(ws, BQWS_ERR_ALLOCATOR);
Branch: 1 branch
BranchTrueFalseTotal
if (!ptr) ws_fail(ws, BQWS_ERR_ALLOCATOR); 0 96 96
766  
767 96 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 110 static void ws_free(bqws_socket *ws, void *ptr, size_t size)
782 {
783 110 ws_remove_memory_used(ws, size);
784 110 bqws_allocator_free(&ws->allocator, ptr, size);
785 110 }
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 110 static void ws_free_str(bqws_socket *ws, char *ptr)
797 {
798 110 ▶ if (!ptr) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!ptr) return; 110 0 110
799 0 ws_free(ws, ptr, strlen(ptr) + 1);
800 }
801  
802 // Message allocation
803  
804 96 static bqws_msg_imp *msg_alloc(bqws_socket *ws, bqws_msg_type type, size_t size)
805 {
806 96 size_t capacity = size;
807  
808 // Space for NULL-terminator
809 96 ▶ if (type & BQWS_MSG_TEXT) capacity += 1;
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_TEXT) capacity += 1; 38 58 96
810  
811 96 size_t alloc_size = sizeof(bqws_msg_imp) + capacity;
812 96 bqws_msg_imp *msg = (bqws_msg_imp*)ws_alloc(ws, alloc_size);
813 96 ▶ if (!msg) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg) return NULL; 0 96 96
814  
815 96 msg->magic = BQWS_MSG_MAGIC;
816 96 msg->owner = ws;
817 96 msg->allocator = ws->allocator;
818 96 msg->prev = NULL;
819 96 msg->msg.socket = ws;
820 96 msg->msg.type = type;
821 96 msg->msg.size = size;
822 96 msg->msg.capacity = capacity;
823  
824 96 ▶ if (type & BQWS_MSG_TEXT) {
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_TEXT) { 38 58 96
825 38 msg->msg.data[size] = '\0';
826 }
827  
828 96 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 56 static void msg_free_owned(bqws_socket *ws, bqws_msg_imp *msg)
859 {
860 56 ▶ if (!msg) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg) return; 0 56 56
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 56 msg->magic = BQWS_DELETED_MAGIC;
866 56 msg->owner = NULL;
867  
868 56 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 56 ▶ if ((char*)msg != ws->state.error_msg_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ((char*)msg != ws->state.error_msg_data) { 51 5 56
872 51 ws_remove_memory_used(ws, size);
873  
874 51 bqws_allocator at = msg->allocator;
875 51 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 297 static bqws_msg_imp *msg_dequeue(bqws_msg_queue *mq)
906 {
907 bqws_mutex_lock(&mq->mutex);
908  
909 297 bqws_msg_imp *msg = mq->first;
910  
911 297 ▶ if (msg) {
Branch: 1 branch
BranchTrueFalseTotal
if (msg) { 65 232 297
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 297 return msg;
937 }
938  
939 165 static void msg_init_queue(bqws_socket *ws, bqws_msg_queue *mq)
940 {
941 bqws_mutex_init(&mq->mutex);
942 165 }
943  
944 165 static void msg_free_queue(bqws_socket *ws, bqws_msg_queue *mq)
945 {
946 bqws_msg_imp *imp;
947 166 ▶ while ((imp = msg_dequeue(mq)) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
while ((imp = msg_dequeue(mq)) != 0) { 1 165 166
948 1 msg_free_owned(ws, imp);
949 }
950  
951 bqws_mutex_free(&mq->mutex);
952 165 }
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 53 static void mask_apply(void *data, size_t size, uint32_t mask)
996 {
997 53 size_t left = size;
998  
999 // Process SIMD width at a time
1000 53 char *data_simd = (char*)data;
1001 #if defined(BQWS_USE_SSE)
1002 {
1003 53 __m128i sse_mask = _mm_set1_epi32(mask);
1004 53 ▶ while (left >= 16) {
Branch: 1 branch
BranchTrueFalseTotal
while (left >= 16) { 0 53 53
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 53 uint32_t *dst32 = (uint32_t*)data_simd;
1016 108 ▶ while (left >= 4) {
Branch: 1 branch
BranchTrueFalseTotal
while (left >= 4) { 55 53 108
1017 55 *dst32++ ^= mask;
1018 55 left -= 4;
1019 }
1020  
1021 // Mask rest
1022 53 ▶ if (left > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (left > 0) { 42 11 53
1023 bqws_assert(left < 4);
1024 uint8_t mask_bytes[4];
1025 42 memcpy(mask_bytes, &mask, 4);
1026 42 uint8_t *dst8 = (uint8_t*)dst32;
1027 42 uint8_t *src = mask_bytes;
1028 115 ▶ while (left > 0) {
Branch: 1 branch
BranchTrueFalseTotal
while (left > 0) { 73 42 115
1029 73 *dst8++ ^= *src++;
1030 73 left--;
1031 }
1032 }
1033 53 }
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 12 static bool lews_bqws_valid_close_code(uint16_t code)
1515 {
1516 12 ▶ return ((code >= 1000 && code <= 1014)
Branch: 1 branch
BranchTrueFalseTotal
return ((code >= 1000 && code <= 1014) 12 0 12
1517 12 ▶ && code != 1004 && code != 1005 && code != 1006)
Branch: 3 branches
BranchTrueFalseTotal
&& code != 1004 && code != 1005 && code != 1006) 12 0 12
&& code != 1004 && code != 1005 && code != 1006) 11 1 12
&& code != 1004 && code != 1005 && code != 1006) 0 11 11
1518 24 ▶ || (code >= 3000 && code <= 4999);
Branch: 3 branches
BranchTrueFalseTotal
|| (code >= 3000 && code <= 4999); 12 0 12
|| (code >= 3000 && code <= 4999); 0 1 1
|| (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 18 static void ws_handle_control(bqws_socket *ws, bqws_msg_imp *msg)
1577 {
1578 18 bqws_msg_type type = msg->msg.type;
1579 18 bqws_msg_imp *msg_to_enqueue = msg;
1580  
1581 18 ▶ if (type == BQWS_MSG_CONTROL_CLOSE) {
Branch: 1 branch
BranchTrueFalseTotal
if (type == BQWS_MSG_CONTROL_CLOSE) { 13 5 18
1582  
1583 13 ▶ if (msg->msg.size == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (msg->msg.size == 1) { 1 12 13
1584 1 msg_free_owned(ws, msg);
1585 1 ws_fail(ws, BQWS_ERR_BAD_CLOSE);
1586 1 return;
1587 }
1588 12 ▶ if (msg->msg.size >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (msg->msg.size >= 2) { 12 0 12
1589 12 uint16_t code = (uint16_t)(
1590 12 ((uint16_t)(uint8_t)msg->msg.data[0] << 8)
1591 12 | (uint16_t)(uint8_t)msg->msg.data[1]);
1592 12 ▶ if (!lews_bqws_valid_close_code(code)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!lews_bqws_valid_close_code(code)) { 1 11 12
1593 1 msg_free_owned(ws, msg);
1594 1 ws_fail(ws, BQWS_ERR_BAD_CLOSE);
1595 1 return;
1596 }
1597 11 ▶ if (!lews_bqws_valid_utf8(
Branch: 1 branch
BranchTrueFalseTotal
if (!lews_bqws_valid_utf8( 1 10 11
1598 11 (const uint8_t *)msg->msg.data + 2,
1599 11 msg->msg.size - 2)) {
1600 1 msg_free_owned(ws, msg);
1601 1 ws_fail(ws, BQWS_ERR_BAD_UTF8);
1602 1 return;
1603 }
1604 }
1605  
1606 /*
1607 * Upstream retains the incoming Close object for the automatic echo.
1608 * Only copy a validated Close for application delivery. Allocating the
1609 * copy before validation leaks it on rejected Close frames.
1610 */
1611 10 ▶ if (ws->recv_control_messages) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->recv_control_messages) { 10 0 10
1612 10 bqws_msg_imp *copy = msg_alloc(ws, type, msg->msg.size);
1613 10 ▶ if (!copy) {
Branch: 1 branch
BranchTrueFalseTotal
if (!copy) { 0 10 10
1614 0 msg_free_owned(ws, msg);
1615 0 return;
1616 }
1617 10 memcpy(copy->msg.data, msg->msg.data, msg->msg.size);
1618 10 msg_to_enqueue = copy;
1619 }
1620  
1621 bqws_mutex_lock(&ws->state.mutex);
1622  
1623 // Set peer close reason from the message
1624 10 ▶ if (msg->msg.size >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (msg->msg.size >= 2) { 10 0 10
1625 10 ws->state.peer_reason = (bqws_close_reason)(
1626 10 ((uint32_t)(uint8_t)msg->msg.data[0] << 8) |
1627 10 ((uint32_t)(uint8_t)msg->msg.data[1] << 0) );
1628 } else {
1629 0 ws->state.peer_reason = BQWS_CLOSE_NO_REASON;
1630 }
1631  
1632 // Set unknown error if the connection was closed with an error
1633 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
1634 0 ws->state.peer_err = BQWS_ERR_UNKNOWN;
1635 }
1636  
1637 // Potentially patch bqws-specific info
1638 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
1639 2 bqws_err_close_data *data = (bqws_err_close_data*)msg->msg.data;
1640 2 ▶ if (!memcmp(data->magic, "BQWS", 4)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!memcmp(data->magic, "BQWS", 4)) { 0 2 2
1641 0 ws->state.peer_err = (bqws_error)(
1642 0 ((uint32_t)(uint8_t)data->error_be[0] << 24) |
1643 0 ((uint32_t)(uint8_t)data->error_be[1] << 16) |
1644 0 ((uint32_t)(uint8_t)data->error_be[2] << 8) |
1645 0 ((uint32_t)(uint8_t)data->error_be[3] << 0) );
1646 }
1647 }
1648  
1649 // Echo the close message back
1650 10 ▶ if (!ws->state.close_to_send) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->state.close_to_send) { 10 0 10
1651 10 ws->state.close_to_send = msg;
1652  
1653 // Don't free the message as it will be re-sent
1654 10 msg = NULL;
1655 }
1656  
1657 // Peer has closed connection so we go directly to CLOSED
1658 10 ▶ if (ws->state.state == BQWS_STATE_OPEN) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.state == BQWS_STATE_OPEN) { 5 5 10
1659 5 ws_log(ws, "State: CLOSING (received Close from peer)");
1660 5 ws->state.start_closing_ts = bqws_get_timestamp();
1661 5 ws->state.state = BQWS_STATE_CLOSING;
1662 }
1663  
1664 10 ws->state.stop_read = true;
1665 10 ws->state.close_received = true;
1666 10 ▶ if (ws->state.close_sent) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.close_sent) { 5 5 10
1667 5 ws_close(ws);
1668 }
1669  
1670 bqws_mutex_unlock(&ws->state.mutex);
1671  
1672 5 ▶ } else if (type == BQWS_MSG_CONTROL_PING) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (type == BQWS_MSG_CONTROL_PING) { 4 1 5
1673 4 ▶ if (ws->recv_control_messages) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->recv_control_messages) { 4 0 4
1674 // We want to re-use the PING message to send it back
1675 // so we need to copy it for receiving
1676 4 bqws_msg_imp *copy = msg_alloc(ws, type, msg->msg.size);
1677 4 ▶ if (!copy) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!copy) return; 0 4 4
1678 4 memcpy(copy->msg.data, msg->msg.data, msg->msg.size);
1679 4 msg_to_enqueue = copy;
1680 }
1681  
1682 // Turn every PING into a PONG. Upstream intentionally retains only
1683 // the latest PONG; retain all of them so each received PING can be
1684 // answered independently.
1685 4 msg->msg.type = BQWS_MSG_CONTROL_PONG;
1686 4 ws_enqueue_send(ws, msg);
1687  
1688 // Don't free the message as it is now owned by the send queue.
1689 4 msg = NULL;
1690  
1691 } else if (type == BQWS_MSG_CONTROL_PONG) {
1692 // PONG messages don't require any kind of handling
1693 } else {
1694 bqws_assert(0 && "Unexpected control message");
1695 }
1696  
1697 // Receive control messages
1698 15 ▶ if (ws->recv_control_messages) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->recv_control_messages) { 15 0 15
1699 15 ws_enqueue_recv(ws, msg_to_enqueue);
1700 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
1701 0 msg_free_owned(ws, msg);
1702 }
1703 0 ▶ } else if (msg) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (msg) { 0 0 0
1704 0 msg_free_owned(ws, msg);
1705 }
1706 }
1707  
1708 // Input / output
1709  
1710 // Read data into a buffer, returns amount of bytes used read.
1711 // Returns 0 and sets `ws->err` if parsing fails.
1712  
1713 0 static size_t ws_recv_from_handshake_overflow(void *user, bqws_socket *ws, void *data, size_t max_size, size_t min_size)
1714 {
1715 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
1716 bqws_assert_locked(&ws->io.mutex);
1717  
1718 0 size_t offset = ws->io.handshake_overflow.read_offset;
1719 0 size_t left = ws->io.handshake_overflow.size - offset;
1720 0 size_t to_copy = max_size;
1721 0 ▶ if (to_copy > left) to_copy = left;
Branch: 1 branch
BranchTrueFalseTotal
if (to_copy > left) to_copy = left; 0 0 0
1722 0 memcpy(data, ws->io.handshake_overflow.data + offset, to_copy);
1723 0 ws->io.handshake_overflow.read_offset += to_copy;
1724 0 return to_copy;
1725 }
1726  
1727 0 static bool ws_read_handshake(bqws_socket *ws, bqws_io_recv_fn recv_fn, void *user)
1728 {
1729 bqws_assert_locked(&ws->io.mutex);
1730  
1731 0 for (;;) {
1732 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
1733 // Grow the buffer geometrically up to `max_handshake_size`
1734 0 size_t new_cap = ws->io.handshake.capacity * 2;
1735 0 ▶ if (new_cap == 0) new_cap = 512;
Branch: 1 branch
BranchTrueFalseTotal
if (new_cap == 0) new_cap = 512; 0 0 0
1736 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
1737 0 ▶ if (new_cap == ws->io.handshake.capacity) {
Branch: 1 branch
BranchTrueFalseTotal
if (new_cap == ws->io.handshake.capacity) { 0 0 0
1738 0 ws_fail(ws, BQWS_ERR_LIMIT_MAX_HANDSHAKE_SIZE);
1739 0 return false;
1740 }
1741  
1742 0 char *data = (char*)ws_realloc(ws, ws->io.handshake.data, ws->io.handshake.capacity, new_cap);
1743 0 ▶ if (!data) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!data) return false; 0 0 0
1744 0 ws->io.handshake.data = data;
1745 0 ws->io.handshake.capacity = new_cap;
1746 }
1747  
1748 // TODO: min_size can be up to 4 depending on the suffix of the buffer
1749  
1750 // Read some data
1751 0 size_t to_read = ws->io.handshake.capacity - ws->io.handshake.size;
1752 0 size_t num_read = recv_fn(user, ws, ws->io.handshake.data + ws->io.handshake.size, to_read, 1);
1753 0 ▶ if (num_read == 0) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == 0) return false; 0 0 0
1754 0 ▶ if (num_read == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == SIZE_MAX) { 0 0 0
1755 0 ws_fail(ws, BQWS_ERR_IO_READ);
1756 0 return false;
1757 }
1758 bqws_assert(num_read <= to_read);
1759 0 ws->io.handshake.size += num_read;
1760  
1761 // Scan for \r\n\r\n
1762 0 ptrdiff_t begin = (ptrdiff_t)ws->io.handshake.size - num_read - 4;
1763 0 ▶ if (begin < 0) begin = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (begin < 0) begin = 0; 0 0 0
1764 0 char *ptr = ws->io.handshake.data + begin;
1765 0 char *end = ws->io.handshake.data + ws->io.handshake.size;
1766 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
1767 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
1768 0 return true;
1769 } else {
1770 0 ptr++;
1771 }
1772 }
1773  
1774 0 ▶ if (num_read != to_read) break;
Branch: 1 branch
BranchTrueFalseTotal
if (num_read != to_read) break; 0 0 0
1775 }
1776  
1777 0 return false;
1778 }
1779  
1780 98 static bool ws_read_data(bqws_socket *ws, bqws_io_recv_fn recv_fn, void *user)
1781 {
1782 bqws_assert_locked(&ws->io.mutex);
1783 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
1784  
1785 98 bqws_msg_buffer *buf = &ws->io.recv_buf;
1786  
1787 bqws_state state;
1788  
1789 bqws_mutex_lock(&ws->state.mutex);
1790 98 ▶ if (ws->state.stop_read) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.stop_read) { 10 88 98
1791 bqws_mutex_unlock(&ws->state.mutex);
1792 10 return false;
1793 }
1794 88 state = ws->state.state;
1795 bqws_mutex_unlock(&ws->state.mutex);
1796  
1797 88 ▶ if (state == BQWS_STATE_CONNECTING) {
Branch: 1 branch
BranchTrueFalseTotal
if (state == BQWS_STATE_CONNECTING) { 0 88 88
1798  
1799 0 ▶ if (ws->is_server) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->is_server) { 0 0 0
1800 // Server: read the client handshake first, after it's done wait for
1801 // `ws_write_data()` to set `ws->state == BQWS_STATE_OPEN`
1802 0 ▶ if (!ws->io.client_handshake_done) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->io.client_handshake_done) { 0 0 0
1803 // Read the client handshake
1804 0 ▶ if (ws_read_handshake(ws, recv_fn, user)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws_read_handshake(ws, recv_fn, user)) { 0 0 0
1805 0 ▶ if (!hs_parse_client_handshake(ws)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hs_parse_client_handshake(ws)) { 0 0 0
1806 0 ws_fail(ws, BQWS_ERR_HEADER_PARSE);
1807 0 return false;
1808 }
1809 0 ws->io.client_handshake_done = true;
1810  
1811 // Re-use the handshake buffer for the response, but copy
1812 // remaining data to be read later
1813 0 hs_store_handshake_overflow(ws);
1814 0 ws->io.handshake.size = 0;
1815  
1816 // Notify IO that there is a handshake to send
1817 0 ▶ if (ws->user_io.notify_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.notify_fn) { 0 0 0
1818 0 ws->user_io.notify_fn(ws->user_io.user, ws);
1819 }
1820 }
1821 }
1822  
1823 // Wait that the response is sent
1824 0 return false;
1825 } else {
1826 // Client: Send the request first before trying to read the response
1827 0 ▶ if (!ws->io.client_handshake_done) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->io.client_handshake_done) return false; 0 0 0
1828 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
1829  
1830 0 ▶ if (!hs_parse_server_handshake(ws)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hs_parse_server_handshake(ws)) { 0 0 0
1831 0 ws_fail(ws, BQWS_ERR_HEADER_PARSE);
1832 0 return false;
1833 }
1834  
1835 // Store remaining data before deleting the handshake
1836 0 hs_store_handshake_overflow(ws);
1837  
1838 // Client handshake is done!
1839 0 hs_finish_handshake(ws);
1840 }
1841 }
1842  
1843 // If there's still data in the handshake buffer empty it before
1844 // reading any new data
1845 88 ▶ 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 88 88
if (ws->io.handshake_overflow.data && recv_fn != &ws_recv_from_handshake_overflow) { 0 0 0
1846  
1847 // Read from the handshake until we reach the end
1848 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
1849 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
1850 0 return false;
1851 }
1852 }
1853  
1854 0 ▶ if (ws->err) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return false; 0 0 0
1855  
1856 // Free the handshake
1857 0 ws_free(ws, ws->io.handshake_overflow.data, ws->io.handshake_overflow.capacity);
1858 0 ws->io.handshake_overflow.data = NULL;
1859 0 ws->io.handshake_overflow.size = 0;
1860 0 ws->io.handshake_overflow.capacity = 0;
1861  
1862 // Continue with reading from the actual data source
1863 }
1864  
1865 // Header has not been parsed yet
1866 88 ▶ if (!buf->msg) {
Branch: 1 branch
BranchTrueFalseTotal
if (!buf->msg) { 87 1 88
1867  
1868 // Check if we can fit a new message to the receive queue
1869 87 ▶ 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 87 0 87
1870 87 ▶ || 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 87 87
1871 0 return false;
1872 }
1873  
1874 // We need to read at least two bytes to determine
1875 // the header size
1876 87 ▶ if (buf->header_size == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_size == 0) { 87 0 87
1877 87 ▶ if (buf->header_offset < 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_offset < 2) { 81 6 87
1878 81 size_t to_read = sizeof(ws->io.recv_header) - buf->header_offset;
1879 81 size_t min_read = 2 - buf->header_offset;
1880 81 size_t num_read = recv_fn(user, ws, ws->io.recv_header + buf->header_offset, to_read, min_read);
1881 81 ▶ if (num_read == 0) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == 0) return false; 34 47 81
1882 47 ▶ if (num_read == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == SIZE_MAX) { 0 47 47
1883 0 ws_fail(ws, BQWS_ERR_IO_READ);
1884 0 return false;
1885 }
1886 bqws_assert(num_read <= to_read);
1887 47 buf->header_offset += num_read;
1888  
1889 47 ▶ if (ws->ping_interval != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->ping_interval != SIZE_MAX) { 0 47 47
1890 0 ws->io.last_read_ts = bqws_get_timestamp();
1891 }
1892 }
1893  
1894 53 ▶ if (buf->header_offset < 2) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_offset < 2) return false; 0 53 53
1895  
1896 53 uint8_t mask_len = ws->io.recv_header[1];
1897 53 uint32_t len = mask_len & 0x7f;
1898  
1899 // Minimum header size
1900 53 size_t header_size = 2;
1901  
1902 // MASK bit set: contains 32-bit mask field
1903 53 ▶ if (mask_len & 0x80) header_size += 4;
Branch: 1 branch
BranchTrueFalseTotal
if (mask_len & 0x80) header_size += 4; 43 10 53
1904  
1905 // 16/64-bit message length
1906 53 ▶ if (len == 126) header_size += 2;
Branch: 1 branch
BranchTrueFalseTotal
if (len == 126) header_size += 2; 0 53 53
1907 53 ▶ else if (len == 127) header_size += 8;
Branch: 1 branch
BranchTrueFalseTotal
else if (len == 127) header_size += 8; 0 53 53
1908  
1909 53 buf->header_size = header_size;
1910 bqws_assert(buf->header_size <= sizeof(ws->io.recv_header));
1911 }
1912  
1913 // Read more header data if we need it
1914 53 ▶ if (buf->header_offset < buf->header_size) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_offset < buf->header_size) { 0 53 53
1915 0 size_t to_read = sizeof(ws->io.recv_header) - buf->header_offset;
1916 0 size_t min_read = buf->header_size - buf->header_offset;
1917 0 size_t num_read = recv_fn(user, ws, ws->io.recv_header + buf->header_offset, to_read, min_read);
1918 0 ▶ if (num_read == 0) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == 0) return false; 0 0 0
1919 0 ▶ if (num_read == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == SIZE_MAX) { 0 0 0
1920 0 ws_fail(ws, BQWS_ERR_IO_READ);
1921 0 return false;
1922 }
1923 bqws_assert(num_read <= to_read);
1924 0 buf->header_offset += num_read;
1925  
1926 0 ▶ if (ws->ping_interval != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->ping_interval != SIZE_MAX) { 0 0 0
1927 0 ws->io.last_read_ts = bqws_get_timestamp();
1928 }
1929  
1930 0 return false;
1931 }
1932  
1933 53 ▶ if (buf->header_offset < buf->header_size) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_offset < buf->header_size) return false; 0 53 53
1934  
1935 // Parse the header and allocate the message
1936 53 const uint8_t *h = (const uint8_t*)ws->io.recv_header;
1937  
1938 // Static header bits
1939 53 bool fin = (h[0] & 0x80) != 0;
1940 53 ▶ if (h[0] & 0x70) {
Branch: 1 branch
BranchTrueFalseTotal
if (h[0] & 0x70) { 0 53 53
1941 // Reserved bits RSV1-3
1942 0 ws_fail(ws, BQWS_ERR_RESERVED_BIT);
1943 0 return false;
1944 }
1945 53 uint32_t opcode = (uint32_t)(h[0] & 0x0f);
1946 53 uint32_t mask = (uint32_t)(h[1] & 0x80) != 0;
1947 53 uint64_t payload_length = (uint64_t)(h[1] & 0x7f);
1948 53 h += 2;
1949  
1950 // Extended length: Read 2 or 8 bytes of big
1951 // endian payload length.
1952 53 size_t payload_ext = 0;
1953 53 ▶ if (payload_length == 126) {
Branch: 1 branch
BranchTrueFalseTotal
if (payload_length == 126) { 0 53 53
1954 0 payload_ext = 2;
1955 0 payload_length = 0;
1956 53 ▶ } else if (payload_length == 127) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (payload_length == 127) { 0 53 53
1957 0 payload_ext = 8;
1958 0 payload_length = 0;
1959 }
1960 53 ▶ for (size_t i = 0; i < payload_ext; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < payload_ext; i++) { 0 53 53
1961 0 size_t shift = (payload_ext - i - 1) * 8;
1962 0 payload_length |= (uint64_t)h[i] << shift;
1963 }
1964 53 h += payload_ext;
1965  
1966 // RFC 6455 control frames are limited to 125 payload octets.
1967 // Reject them before payload processing so invalid PING/CLOSE frames
1968 // cannot produce a PONG or echoed CLOSE first.
1969 53 ▶ if (opcode >= 0x8 && payload_length > 125) {
Branch: 2 branches
BranchTrueFalseTotal
if (opcode >= 0x8 && payload_length > 125) { 18 35 53
if (opcode >= 0x8 && payload_length > 125) { 0 18 18
1970 0 ws_fail(ws, BQWS_ERR_PARTIAL_CONTROL);
1971 0 return false;
1972 }
1973  
1974 // Check the payload length and cast to `size_t`
1975 53 ▶ 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 53 53
1976 0 ws_fail(ws, BQWS_ERR_LIMIT_MAX_RECV_MSG_SIZE);
1977 0 return false;
1978 }
1979 53 size_t msg_size = (size_t)payload_length;
1980  
1981 // Masking key
1982 53 buf->masked = mask;
1983 53 ▶ if (mask) {
Branch: 1 branch
BranchTrueFalseTotal
if (mask) { 43 10 53
1984 43 memcpy(&buf->mask_key, h, 4);
1985 43 h += 4;
1986 }
1987  
1988 bqws_assert((size_t)((const char*)h - ws->io.recv_header) == buf->header_size);
1989  
1990 53 bqws_msg_type type = BQWS_MSG_INVALID;
1991  
1992 // Resolve the type of the message
1993 53 ▶ if (opcode == 0x0) {
Branch: 1 branch
BranchTrueFalseTotal
if (opcode == 0x0) { 3 50 53
1994 // Continuation frame
1995  
1996 3 ▶ if (buf->partial_type == BQWS_MSG_INVALID) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->partial_type == BQWS_MSG_INVALID) { 1 2 3
1997 // Continuation frame without a prior partial frame
1998 1 ws_fail(ws, BQWS_ERR_BAD_CONTINUATION);
1999 1 return false;
2000 }
2001  
2002 2 type = (bqws_msg_type)(buf->partial_type | BQWS_MSG_PARTIAL_BIT);
2003 2 ▶ if (fin) {
Branch: 1 branch
BranchTrueFalseTotal
if (fin) { 2 0 2
2004 2 type = (bqws_msg_type)(type | BQWS_MSG_FINAL_BIT);
2005 2 buf->partial_type = BQWS_MSG_INVALID;
2006 }
2007  
2008 50 ▶ } else if (opcode == 0x1 || opcode == 0x2) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (opcode == 0x1 || opcode == 0x2) { 23 27 50
} else if (opcode == 0x1 || opcode == 0x2) { 5 18 23
2009 // Text or Binary
2010 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
2011  
2012 // A new data message cannot begin until the current fragmented
2013 // message has received its final continuation frame.
2014 32 ▶ if (buf->partial_type != BQWS_MSG_INVALID) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->partial_type != BQWS_MSG_INVALID) { 1 31 32
2015 1 ws_fail(ws, BQWS_ERR_UNFINISHED_PARTIAL);
2016 1 return false;
2017 }
2018  
2019 31 ▶ if (!fin) {
Branch: 1 branch
BranchTrueFalseTotal
if (!fin) { 3 28 31
2020 3 buf->partial_type = type;
2021 3 type = (bqws_msg_type)(type | BQWS_MSG_PARTIAL_BIT);
2022 }
2023 18 ▶ } else if (opcode >= 0x8 && opcode <= 0xa) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (opcode >= 0x8 && opcode <= 0xa) { 18 0 18
} else if (opcode >= 0x8 && opcode <= 0xa) { 18 0 18
2024 // Control frames
2025 18 ▶ if (opcode == 0x8) type = BQWS_MSG_CONTROL_CLOSE;
Branch: 1 branch
BranchTrueFalseTotal
if (opcode == 0x8) type = BQWS_MSG_CONTROL_CLOSE; 13 5 18
2026 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
2027 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
2028  
2029 18 ▶ if (!fin) {
Branch: 1 branch
BranchTrueFalseTotal
if (!fin) { 0 18 18
2030 // Control frames may not be fragmented
2031 0 ws_fail(ws, BQWS_ERR_PARTIAL_CONTROL);
2032 0 return false;
2033 }
2034 } else {
2035 // Unsupported opcode
2036 0 ws_fail(ws, BQWS_ERR_BAD_OPCODE);
2037 0 return false;
2038 }
2039 bqws_assert(type != BQWS_MSG_INVALID);
2040  
2041 // All good, allocate the message
2042 51 bqws_msg_imp *imp = msg_alloc(ws, type, msg_size);
2043 51 ▶ if (!imp) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!imp) return false; 0 51 51
2044  
2045 51 buf->msg = imp;
2046 51 buf->offset = 0;
2047  
2048 // Copy rest of the header bytes to the message
2049 51 size_t offset = buf->header_size;
2050 51 size_t left = buf->header_offset - offset;
2051 51 ▶ if (left > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (left > 0) { 51 0 51
2052 51 size_t to_copy = left;
2053 51 ▶ 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 45 51
2054 51 memcpy(imp->msg.data, ws->io.recv_header + offset, to_copy);
2055 51 buf->offset += to_copy;
2056 51 offset += to_copy;
2057 51 left -= to_copy;
2058 }
2059  
2060 // If there's still some data shift it as the next header
2061 51 ▶ if (left > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (left > 0) { 6 45 51
2062 6 memmove(ws->io.recv_header, ws->io.recv_header + offset, left);
2063 }
2064 51 buf->header_offset = left;
2065 }
2066  
2067 52 bqws_msg_imp *msg = buf->msg;
2068  
2069 // Read message data if the message is not empty
2070 bqws_assert(buf->offset <= msg->msg.size);
2071 52 ▶ if (msg->msg.size > 0 && buf->offset < msg->msg.size) {
Branch: 2 branches
BranchTrueFalseTotal
if (msg->msg.size > 0 && buf->offset < msg->msg.size) { 52 0 52
if (msg->msg.size > 0 && buf->offset < msg->msg.size) { 2 50 52
2072  
2073 2 size_t to_read = msg->msg.size - buf->offset;
2074 2 size_t num_read = recv_fn(user, ws, msg->msg.data + buf->offset, to_read, to_read);
2075 2 ▶ if (num_read == 0) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == 0) return false; 1 1 2
2076 1 ▶ if (num_read == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_read == SIZE_MAX) { 0 1 1
2077 0 ws_fail(ws, BQWS_ERR_IO_READ);
2078 0 return false;
2079 }
2080 bqws_assert(num_read <= to_read);
2081  
2082 1 ▶ if (ws->ping_interval != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->ping_interval != SIZE_MAX) { 0 1 1
2083 0 ws->io.last_read_ts = bqws_get_timestamp();
2084 }
2085  
2086 1 buf->offset += num_read;
2087 1 ▶ if (num_read < to_read) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (num_read < to_read) return false; 0 1 1
2088 }
2089  
2090 51 ▶ if (buf->masked) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->masked) { 41 10 51
2091 41 mask_apply(msg->msg.data, msg->msg.size, buf->mask_key);
2092 }
2093  
2094 bqws_assert(buf->offset == msg->msg.size);
2095  
2096 // Peek at all incoming messages before processing
2097 51 ▶ if (ws->peek_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->peek_fn) { 0 51 51
2098 0 ws->peek_fn(ws->peek_user, ws, &msg->msg, true);
2099 }
2100  
2101 // If we copied the last bytes of the message we can push it
2102 // to the queue and clear the buffer.
2103 51 bqws_msg_type type = msg->msg.type;
2104  
2105 51 ▶ if (ws->log_recv) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->log_recv) { 0 51 51
2106 0 ws_log2(ws, "Received: ", bqws_msg_type_str(buf->msg->msg.type));
2107 }
2108  
2109 51 ▶ 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 46 51
if ((type & BQWS_MSG_PARTIAL_BIT) != 0 && !ws->recv_partial_messages) { 5 0 5
2110  
2111 // Only allow partial messages that combine up to the maximum message size
2112 bqws_assert(msg->msg.size <= ws->limits.max_recv_msg_size);
2113 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
2114 0 ws_fail(ws, BQWS_ERR_LIMIT_MAX_RECV_MSG_SIZE);
2115 0 return false;
2116 }
2117  
2118 5 ws->io.recv_partial_size += msg->msg.size;
2119  
2120 // If we dont expose partial messages collect them to `recv_partial_queue`.
2121 5 ▶ if (type & BQWS_MSG_FINAL_BIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_FINAL_BIT) { 2 3 5
2122 // If this is the final message concatenate all the partial messages
2123 // in the queue and enqueue the final one>
2124  
2125 2 bqws_msg_type base_type = (bqws_msg_type)(msg->msg.type & BQWS_MSG_TYPE_MASK);
2126 2 bqws_msg_imp *combined = msg_alloc(ws, base_type, ws->io.recv_partial_size);
2127 2 ▶ if (!combined) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!combined) return false; 0 2 2
2128  
2129 2 size_t offset = 0;
2130  
2131 // `recv_queue` with this message as the last part.
2132 bqws_msg_imp *part;
2133 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
2134 bqws_assert(part->magic == BQWS_MSG_MAGIC);
2135 bqws_assert((part->msg.type & BQWS_MSG_TYPE_MASK) == base_type);
2136  
2137 2 memcpy(combined->msg.data + offset, part->msg.data, part->msg.size);
2138 2 offset += part->msg.size;
2139  
2140 // Delete the part
2141 2 msg_free_owned(ws, part);
2142 }
2143  
2144 // Final part
2145 2 memcpy(combined->msg.data + offset, msg->msg.data, msg->msg.size);
2146 2 offset += msg->msg.size;
2147 2 msg_free_owned(ws, msg);
2148  
2149 bqws_assert(offset == combined->msg.size);
2150  
2151 2 ws_enqueue_recv(ws, combined);
2152  
2153 // Clear the partial total size
2154 2 ws->io.recv_partial_size = 0;
2155 } else {
2156  
2157 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
2158 0 ws_fail(ws, BQWS_ERR_LIMIT_MAX_PARTIAL_MESSAGE_PARTS);
2159 0 return false;
2160 }
2161  
2162 3 msg_enqueue(&ws->recv_partial_queue, msg);
2163 }
2164  
2165 } else {
2166 46 ▶ if (type & BQWS_MSG_CONTROL_MASK) {
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_CONTROL_MASK) { 18 28 46
2167 // Control message, handle it. `ws_handle_control()` enqueues the
2168 // message to `recv_queue` internally if required.
2169 18 ws_handle_control(ws, msg);
2170 } else {
2171 // Non-partial data message
2172 28 ws_enqueue_recv(ws, msg);
2173 }
2174 }
2175 51 buf->offset = 0;
2176 51 buf->header_size = 0;
2177 51 buf->msg = NULL;
2178  
2179 51 return true;
2180 }
2181  
2182 0 static bool ws_write_handshake(bqws_socket *ws, bqws_io_send_fn *send_fn, void *user)
2183 {
2184 bqws_assert_locked(&ws->io.mutex);
2185  
2186 0 size_t to_send = ws->io.handshake.size - ws->io.handshake.write_offset;
2187 0 size_t sent = send_fn(user, ws, ws->io.handshake.data + ws->io.handshake.write_offset, to_send);
2188 0 ▶ if (sent == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (sent == SIZE_MAX) { 0 0 0
2189 0 ws_fail(ws, BQWS_ERR_IO_WRITE);
2190 0 return false;
2191 }
2192  
2193 bqws_assert(sent <= to_send);
2194 0 ws->io.handshake.write_offset += sent;
2195 0 return sent == to_send;
2196 }
2197  
2198 105 static bool ws_write_data(bqws_socket *ws, bqws_io_send_fn *send_fn, void *user)
2199 {
2200 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2201 bqws_assert_locked(&ws->io.mutex);
2202  
2203 105 bqws_msg_buffer *buf = &ws->io.send_buf;
2204  
2205 bqws_state state;
2206 char *protocol;
2207  
2208 bqws_mutex_lock(&ws->state.mutex);
2209 105 ▶ if (ws->state.stop_write) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.stop_write) { 17 88 105
2210 bqws_mutex_unlock(&ws->state.mutex);
2211 17 return false;
2212 }
2213 88 state = ws->state.state;
2214 88 protocol = ws->state.chosen_protocol;
2215 bqws_mutex_unlock(&ws->state.mutex);
2216  
2217 88 ▶ if (state == BQWS_STATE_CONNECTING) {
Branch: 1 branch
BranchTrueFalseTotal
if (state == BQWS_STATE_CONNECTING) { 0 88 88
2218  
2219 0 ▶ if (ws->is_server) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->is_server) { 0 0 0
2220 // Server: read the client handshake first
2221 0 ▶ if (!ws->io.client_handshake_done) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->io.client_handshake_done) return false; 0 0 0
2222  
2223 // Wait for the user to accept/reject the connection
2224 0 ▶ if (!protocol) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!protocol) return false; 0 0 0
2225  
2226 // Write the server handshake on demand
2227 0 ▶ if (ws->io.handshake.size == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->io.handshake.size == 0) { 0 0 0
2228 0 hs_server_handshake(ws);
2229 0 ▶ if (ws->err) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return false; 0 0 0
2230 }
2231  
2232 // Write the server handshake
2233 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
2234  
2235 // Server handshake is done!
2236 0 hs_finish_handshake(ws);
2237  
2238 } else {
2239 // Client: Send the request and always wait for response
2240 0 ▶ if (!ws->io.client_handshake_done) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->io.client_handshake_done) { 0 0 0
2241 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
2242  
2243 // Re-use the handshake buffer for the response,
2244 0 ws->io.handshake.size = 0;
2245 0 ws->io.client_handshake_done = true;
2246 }
2247  
2248 0 return false;
2249 }
2250 }
2251  
2252 88 ▶ if (!buf->msg) {
Branch: 1 branch
BranchTrueFalseTotal
if (!buf->msg) { 88 0 88
2253 // No message: Send high priority messages first.
2254  
2255 bqws_mutex_lock(&ws->state.mutex);
2256  
2257 88 ▶ if (ws->state.close_to_send && !ws->state.close_sent) {
Branch: 2 branches
BranchTrueFalseTotal
if (ws->state.close_to_send && !ws->state.close_sent) { 26 62 88
if (ws->state.close_to_send && !ws->state.close_sent) { 26 0 26
2258 // First priority: Send close message
2259 26 buf->msg = ws->state.close_to_send;
2260 26 ws->state.close_to_send = NULL;
2261 26 bqws_assert(buf->msg->msg.type == BQWS_MSG_CONTROL_CLOSE);
2262 62 ▶ } else if (ws->state.state != BQWS_STATE_OPEN) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (ws->state.state != BQWS_STATE_OPEN) { 41 21 62
2263 // Stop sending anything if the state is not open
2264 41 ▶ } else if (ws->state.pong_to_send) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (ws->state.pong_to_send) { 0 41 41
2265 // Try to respond to PING messages fast
2266 0 buf->msg = ws->state.pong_to_send;
2267 0 ws->state.pong_to_send = NULL;
2268 bqws_assert(buf->msg->msg.type == BQWS_MSG_CONTROL_PONG);
2269 } else {
2270 // Send user message if there is one
2271 41 buf->msg = msg_dequeue(&ws->send_queue);
2272 }
2273  
2274 bqws_mutex_unlock(&ws->state.mutex);
2275  
2276 // Did not find any message
2277 88 ▶ if (!buf->msg) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!buf->msg) return false; 45 43 88
2278  
2279 bqws_assert(buf->msg && buf->msg->magic == BQWS_MSG_MAGIC);
2280  
2281 }
2282 43 bqws_msg_imp *msg = buf->msg;
2283 bqws_assert(msg && msg->magic == BQWS_MSG_MAGIC);
2284  
2285 // Re-assign the public socket to be this one for the callback
2286 43 msg->msg.socket = ws;
2287  
2288 // Peek at all outgoing messages before processing
2289 43 ▶ if (ws->peek_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->peek_fn) { 0 43 43
2290 0 ws->peek_fn(ws->peek_user, ws, &msg->msg, false);
2291 }
2292  
2293 43 ▶ if (ws->send_message_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->send_message_fn) { 0 43 43
2294 0 msg_release_ownership(ws, msg);
2295 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
2296 0 ▶ if (ws->log_send) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->log_send) { 0 0 0
2297 0 ws_log2(ws, "Direct send: ", bqws_msg_type_str(msg->msg.type));
2298 }
2299 0 buf->msg = NULL;
2300 0 return true;
2301 } else {
2302 0 msg_acquire_ownership(ws, msg);
2303 0 return false;
2304 }
2305 }
2306  
2307 43 ▶ if (ws->ping_interval != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->ping_interval != SIZE_MAX) { 0 43 43
2308 0 ws->io.last_write_ts = bqws_get_timestamp();
2309 }
2310  
2311 43 ▶ if (buf->header_size == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_size == 0) { 43 0 43
2312 43 bqws_msg_type type = msg->msg.type;
2313 43 ▶ 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; 31 12 43
2314 43 bool fin = true;
2315 43 uint32_t opcode = ~0u;
2316  
2317 43 ▶ if (type & BQWS_MSG_TYPE_MASK) {
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_TYPE_MASK) { 12 31 43
2318 12 bqws_msg_type base_type = (bqws_msg_type)(type & BQWS_MSG_TYPE_MASK);
2319 12 ▶ opcode = base_type == BQWS_MSG_TEXT ? 0x1 : 0x2;
Branch: 1 branch
BranchTrueFalseTotal
opcode = base_type == BQWS_MSG_TEXT ? 0x1 : 0x2; 9 3 12
2320  
2321 12 ▶ if (type & BQWS_MSG_PARTIAL_BIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_PARTIAL_BIT) { 0 12 12
2322 0 ▶ if (buf->partial_type != BQWS_MSG_INVALID) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->partial_type != BQWS_MSG_INVALID) { 0 0 0
2323 // Partial continuation
2324 bqws_assert(buf->partial_type == base_type);
2325 0 opcode = 0x0;
2326 }
2327  
2328 0 ▶ if (type & BQWS_MSG_FINAL_BIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (type & BQWS_MSG_FINAL_BIT) { 0 0 0
2329 // This can be either the end of a partial message
2330 // or just a single-part partial message.
2331 0 buf->partial_type = BQWS_MSG_INVALID;
2332 } else {
2333 // Partial begin or continuation
2334 0 buf->partial_type = base_type;
2335 0 fin = false;
2336 }
2337 }
2338  
2339 31 ▶ } else if (type & BQWS_MSG_CONTROL_MASK) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (type & BQWS_MSG_CONTROL_MASK) { 31 0 31
2340 // Control message
2341 31 ▶ if (type == BQWS_MSG_CONTROL_CLOSE) opcode = 0x8;
Branch: 1 branch
BranchTrueFalseTotal
if (type == BQWS_MSG_CONTROL_CLOSE) opcode = 0x8; 26 5 31
2342 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
2343 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
2344 } else {
2345 bqws_assert(0 && "Trying to send non-data non-control message");
2346 }
2347  
2348 bqws_assert(opcode != ~0u);
2349  
2350 // Use the smallest payload length representation
2351 43 size_t payload_ext = 0;
2352 43 size_t payload_len = msg->msg.size;
2353 43 ▶ if (payload_len > 65535u) {
Branch: 1 branch
BranchTrueFalseTotal
if (payload_len > 65535u) { 0 43 43
2354 0 payload_len = 127;
2355 0 payload_ext = 8;
2356 43 ▶ } else if (payload_len > 125) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (payload_len > 125) { 0 43 43
2357 0 payload_len = 126;
2358 0 payload_ext = 2;
2359 }
2360  
2361 43 uint8_t *h = (uint8_t*)ws->io.send_header;
2362 // Static header bits
2363 43 ▶ h[0] = (fin ? 0x80 : 0x0) | (uint8_t)opcode;
Branch: 1 branch
BranchTrueFalseTotal
h[0] = (fin ? 0x80 : 0x0) | (uint8_t)opcode; 43 0 43
2364 43 ▶ h[1] = (mask ? 0x80 : 0x0) | (uint8_t)payload_len;
Branch: 1 branch
BranchTrueFalseTotal
h[1] = (mask ? 0x80 : 0x0) | (uint8_t)payload_len; 12 31 43
2365 43 h += 2;
2366  
2367 // Extended length: Read 2 or 8 bytes of big
2368 // endian payload length.
2369 43 ▶ for (size_t i = 0; i < payload_ext; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < payload_ext; i++) { 0 43 43
2370 0 size_t shift = (payload_ext - i - 1) * 8;
2371 0 h[i] = (uint8_t)((uint64_t)msg->msg.size >> shift);
2372 }
2373 43 h += payload_ext;
2374  
2375 // Masking key
2376 43 buf->masked = mask;
2377 43 ▶ if (mask) {
Branch: 1 branch
BranchTrueFalseTotal
if (mask) { 12 31 43
2378 12 uint32_t mask_key = mask_make_key(ws);
2379 12 buf->mask_key = mask_key;
2380 12 memcpy(h, &buf->mask_key, 4);
2381 12 h += 4;
2382  
2383 // Apply the mask
2384 12 mask_apply(msg->msg.data, msg->msg.size, mask_key);
2385 }
2386  
2387 43 buf->header_size = (char*)h - ws->io.send_header;
2388 bqws_assert(buf->header_size <= sizeof(ws->io.send_header));
2389 }
2390  
2391 // Send the header
2392 43 ▶ if (buf->header_offset < buf->header_size) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf->header_offset < buf->header_size) { 43 0 43
2393 43 size_t to_send = buf->header_size - buf->header_offset;
2394 43 size_t sent = send_fn(user, ws, ws->io.send_header + buf->header_offset, to_send);
2395 43 ▶ if (sent == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (sent == SIZE_MAX) { 0 43 43
2396 0 ws_fail(ws, BQWS_ERR_IO_WRITE);
2397 0 return false;
2398 }
2399 bqws_assert(sent <= to_send);
2400 43 buf->header_offset += sent;
2401 43 ▶ if (sent < to_send) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (sent < to_send) return false; 0 43 43
2402 }
2403  
2404 // Send the message
2405 {
2406 43 size_t to_send = msg->msg.size - buf->offset;
2407 43 size_t sent = send_fn(user, ws, msg->msg.data + buf->offset, to_send);
2408 43 ▶ if (sent == SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (sent == SIZE_MAX) { 0 43 43
2409 0 ws_fail(ws, BQWS_ERR_IO_WRITE);
2410 0 return false;
2411 }
2412 bqws_assert(sent <= to_send);
2413 43 buf->offset += sent;
2414 43 ▶ if (sent < to_send) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (sent < to_send) return false; 0 43 43
2415 }
2416  
2417 43 ▶ if (ws->log_send) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->log_send) { 0 43 43
2418 0 ws_log2(ws, "Sent: ", bqws_msg_type_str(buf->msg->msg.type));
2419 }
2420  
2421 // Mark close as been sent
2422 43 ▶ if (msg->msg.type == BQWS_MSG_CONTROL_CLOSE) {
Branch: 1 branch
BranchTrueFalseTotal
if (msg->msg.type == BQWS_MSG_CONTROL_CLOSE) { 26 17 43
2423 bqws_mutex_lock(&ws->state.mutex);
2424 26 ▶ if (ws->state.state == BQWS_STATE_OPEN) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.state == BQWS_STATE_OPEN) { 0 26 26
2425 0 ws_log(ws, "State: CLOSING (queued user close)");
2426 0 ws->state.state = BQWS_STATE_CLOSING;
2427 0 ws->state.start_closing_ts = bqws_get_timestamp();
2428 }
2429 26 ws->state.close_sent = true;
2430 26 ▶ if (ws->state.close_received) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.close_received) { 5 21 26
2431 5 ws_close(ws);
2432 }
2433 bqws_mutex_unlock(&ws->state.mutex);
2434 }
2435  
2436 // Delete the message
2437 43 msg_free_owned(ws, msg);
2438  
2439 // Sent everything, clear status
2440 43 buf->offset = 0;
2441 43 buf->header_offset = 0;
2442 43 buf->header_size = 0;
2443 43 buf->msg = NULL;
2444 43 return true;
2445 }
2446  
2447 // WebSocket initialization
2448  
2449 0 static char *verify_filter_str(bqws_verify_filter *f, size_t *offset, const char *str)
2450 {
2451 0 ▶ if (!str) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!str) return NULL; 0 0 0
2452 0 size_t len = strlen(str) + 1;
2453 0 char *dst = f->text_data + *offset;
2454 0 memcpy(dst, str, len);
2455 0 *offset += len;
2456 0 return dst;
2457 }
2458  
2459 0 static void bqws_internal_filter_verify(void *user, bqws_socket *ws, const bqws_client_opts *opts)
2460 {
2461 0 bqws_verify_filter *f = (bqws_verify_filter*)user;
2462 0 bool ok = true;
2463  
2464 // Check common headers
2465 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
2466 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
2467 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
2468  
2469 0 const char *protocol = NULL;
2470 0 ▶ if (f->num_protocols > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (f->num_protocols > 0) { 0 0 0
2471 // If the filter has protocols try to find one
2472 // O(n^2) but bounded by BQWS_MAX_PROTOCOLS
2473 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
2474 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
2475 0 ▶ if (!strcmp(f->protocols[fi], opts->protocols[ci])) {
Branch: 1 branch
BranchTrueFalseTotal
if (!strcmp(f->protocols[fi], opts->protocols[ci])) { 0 0 0
2476 0 protocol = f->protocols[fi];
2477 0 break;
2478 }
2479 }
2480 }
2481 0 ▶ ok = ok && protocol != NULL;
Branch: 2 branches
BranchTrueFalseTotal
ok = ok && protocol != NULL; 0 0 0
ok = ok && protocol != NULL; 0 0 0
2482 } else {
2483 // If not don't use any protocol name
2484 0 protocol = "";
2485 }
2486  
2487 0 ▶ if (ok) {
Branch: 1 branch
BranchTrueFalseTotal
if (ok) { 0 0 0
2488 bqws_assert(protocol != NULL);
2489 0 ▶ if (f->verify_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (f->verify_fn) { 0 0 0
2490 0 f->verify_fn(f->verify_user, ws, opts);
2491 } else {
2492 0 bqws_server_accept(ws, protocol);
2493 }
2494 } else {
2495 0 bqws_server_reject(ws);
2496 }
2497 0 }
2498  
2499 55 static void ws_expand_default_limits(bqws_limits *limits)
2500 {
2501 #define WS_DEFAULT(p_name, p_value) if (!limits->p_name) limits->p_name = p_value
2502  
2503 55 ▶ WS_DEFAULT(max_memory_used, 262144);
Branch: 1 branch
BranchTrueFalseTotal
WS_DEFAULT(max_memory_used, 262144); 0 55 55
2504 55 ▶ WS_DEFAULT(max_recv_msg_size, 262144);
Branch: 1 branch
BranchTrueFalseTotal
WS_DEFAULT(max_recv_msg_size, 262144); 0 55 55
2505 55 ▶ WS_DEFAULT(max_handshake_size, 262144);
Branch: 1 branch
BranchTrueFalseTotal
WS_DEFAULT(max_handshake_size, 262144); 55 0 55
2506 55 ▶ WS_DEFAULT(max_recv_queue_messages, 1024);
Branch: 1 branch
BranchTrueFalseTotal
WS_DEFAULT(max_recv_queue_messages, 1024); 0 55 55
2507 55 ▶ WS_DEFAULT(max_recv_queue_size, 262144);
Branch: 1 branch
BranchTrueFalseTotal
WS_DEFAULT(max_recv_queue_size, 262144); 0 55 55
2508 55 ▶ WS_DEFAULT(max_partial_message_parts, 16384);
Branch: 1 branch
BranchTrueFalseTotal
WS_DEFAULT(max_partial_message_parts, 16384); 0 55 55
2509  
2510 #undef WS_DEFAULT
2511 55 }
2512  
2513 55 static bqws_socket *ws_new_socket(const bqws_opts *opts, bool is_server)
2514 {
2515 bqws_opts null_opts;
2516 55 ▶ if (!opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (!opts) { 0 55 55
2517 0 memset(&null_opts, 0, sizeof(null_opts));
2518 0 opts = &null_opts;
2519 }
2520  
2521 55 bqws_socket *ws = (bqws_socket*)bqws_allocator_alloc(&opts->allocator, sizeof(bqws_socket) + opts->user_size);
2522 55 ▶ if (!ws) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws) return NULL; 0 55 55
2523  
2524 55 memset(ws, 0, sizeof(bqws_socket));
2525 55 ws->magic = BQWS_SOCKET_MAGIC;
2526 55 ws->is_server = is_server;
2527 55 ws->allocator = opts->allocator;
2528 55 ws->user_io = opts->io;
2529 55 ws->limits = opts->limits;
2530 55 ws->recv_partial_messages = opts->recv_partial_messages;
2531 55 ws->recv_control_messages = opts->recv_control_messages;
2532 55 ws->mask_server = opts->mask_server;
2533 55 ws->message_fn = opts->message_fn;
2534 55 ws->message_user = opts->message_user;
2535 55 ws->peek_fn = opts->peek_fn;
2536 55 ws->peek_user = opts->peek_user;
2537 55 ws->log_fn = opts->log_fn;
2538 55 ws->log_user = opts->log_user;
2539 55 ws->log_send = opts->log_send;
2540 55 ws->log_recv = opts->log_recv;
2541 55 ws->error_fn = opts->error_fn;
2542 55 ws->error_user = opts->error_user;
2543 55 ws->send_message_fn = opts->send_message_fn;
2544 55 ws->send_message_user = opts->send_message_user;
2545 55 ws->user_size = opts->user_size;
2546  
2547 55 ws_expand_default_limits(&ws->limits);
2548  
2549 bqws_mutex_init(&ws->err_mutex);
2550 bqws_mutex_init(&ws->state.mutex);
2551 bqws_mutex_init(&ws->io.mutex);
2552 bqws_mutex_init(&ws->alloc.mutex);
2553 bqws_mutex_init(&ws->partial.mutex);
2554  
2555 55 msg_init_queue(ws, &ws->recv_queue);
2556 55 msg_init_queue(ws, &ws->recv_partial_queue);
2557 55 msg_init_queue(ws, &ws->send_queue);
2558  
2559 55 ▶ if (opts->ping_interval) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->ping_interval) { 55 0 55
2560 55 ws->ping_interval = opts->ping_interval;
2561 } else {
2562 0 ▶ ws->ping_interval = is_server ? 20000 : 10000;
Branch: 1 branch
BranchTrueFalseTotal
ws->ping_interval = is_server ? 20000 : 10000; 0 0 0
2563 }
2564  
2565 55 ▶ ws->connect_timeout = opts->connect_timeout ? opts->connect_timeout : 10000;
Branch: 1 branch
BranchTrueFalseTotal
ws->connect_timeout = opts->connect_timeout ? opts->connect_timeout : 10000; 55 0 55
2566 55 ▶ ws->close_timeout = opts->close_timeout ? opts->close_timeout : 5000;
Branch: 1 branch
BranchTrueFalseTotal
ws->close_timeout = opts->close_timeout ? opts->close_timeout : 5000; 55 0 55
2567 55 ▶ 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; 55 0 55
2568  
2569 bqws_assert(ws->ping_interval > 0);
2570 55 ▶ 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) { 55 0 55
if (ws->ping_interval != SIZE_MAX || ws->connect_timeout != SIZE_MAX) { 0 55 55
2571 0 bqws_timestamp ts = bqws_get_timestamp();
2572 0 ws->io.start_connect_ts = ts;
2573 0 ws->io.last_write_ts = ts;
2574 0 ws->io.last_read_ts = ts;
2575 0 ws->io.last_ping_ts = ts;
2576 }
2577  
2578 // Copy or zero-init user data
2579 55 ▶ if (opts->user_size > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->user_size > 0) { 0 55 55
2580 0 ▶ if (opts->user_data) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->user_data) { 0 0 0
2581 0 memcpy(ws->user_data, opts->user_data, opts->user_size);
2582 } else {
2583 0 memset(ws->user_data, 0, opts->user_size);
2584 }
2585 }
2586  
2587 55 ▶ 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 55 55
2588  
2589 55 ▶ if (opts->skip_handshake) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->skip_handshake) { 55 0 55
2590 55 ws_log(ws, "State: OPEN (skip handhake)");
2591 55 ws->state.state = BQWS_STATE_OPEN;
2592 } else {
2593 0 ws_log(ws, "State: CONNECTING");
2594 0 ws->state.state = BQWS_STATE_CONNECTING;
2595 }
2596  
2597 55 ws->io.mask_random_state = (uint32_t)(uintptr_t)ws ^ (uint32_t)time(NULL);
2598 55 ws->io.mask_random_stream = (uint32_t)bqws_get_timestamp() | 1u;
2599  
2600 55 ▶ if (ws->err) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) { 0 55 55
2601 0 bqws_free_socket(ws);
2602 0 return NULL;
2603 }
2604  
2605 55 return ws;
2606 }
2607  
2608 // -- API
2609  
2610 13 bqws_socket *bqws_new_client(const bqws_opts *opts, const bqws_client_opts *client_opts)
2611 {
2612 13 bqws_socket *ws = ws_new_socket(opts, false);
2613 13 ▶ if (!ws) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws) return NULL; 0 13 13
2614  
2615 // Setup client handshake immediately if the socket is not open already
2616 13 ▶ if (ws->state.state == BQWS_STATE_CONNECTING) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->state.state == BQWS_STATE_CONNECTING) { 0 13 13
2617 bqws_client_opts null_opts;
2618 0 ▶ if (!client_opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (!client_opts) { 0 0 0
2619 0 memset(&null_opts, 0, sizeof(null_opts));
2620 0 client_opts = &null_opts;
2621 }
2622  
2623 bqws_mutex_lock(&ws->io.mutex);
2624 0 hs_client_handshake(ws, client_opts);
2625 bqws_mutex_unlock(&ws->io.mutex);
2626  
2627 // Notify IO that there's a client handshake to send
2628 0 ▶ if (ws->user_io.notify_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.notify_fn) { 0 0 0
2629 0 ws->user_io.notify_fn(ws->user_io.user, ws);
2630 }
2631 }
2632  
2633 13 return ws;
2634 }
2635  
2636 42 bqws_socket *bqws_new_server(const bqws_opts *opts, const bqws_server_opts *server_opts)
2637 {
2638 42 bqws_socket *ws = ws_new_socket(opts, true);
2639 42 ▶ if (!ws) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws) return NULL; 0 42 42
2640  
2641 {
2642 bqws_server_opts null_opts;
2643 42 ▶ if (!server_opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (!server_opts) { 42 0 42
2644 42 memset(&null_opts, 0, sizeof(null_opts));
2645 42 server_opts = &null_opts;
2646 }
2647  
2648 42 ws->verify_fn = server_opts->verify_fn;
2649 42 ws->verify_user = server_opts->verify_user;
2650  
2651 // Setup automatic verify filter if needed
2652 42 ▶ if (server_opts->verify_filter) {
Branch: 1 branch
BranchTrueFalseTotal
if (server_opts->verify_filter) { 0 42 42
2653 0 bqws_client_opts *filter = server_opts->verify_filter;
2654 0 size_t text_size = 0;
2655  
2656 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
2657 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
2658 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
2659 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
2660 bqws_assert(filter->protocols[i] && *filter->protocols[i]);
2661 0 text_size += strlen(filter->protocols[i]) + 1;
2662 }
2663  
2664 0 bqws_verify_filter *copy = (bqws_verify_filter*)ws_alloc(ws, sizeof(bqws_verify_filter) + text_size);
2665 0 ▶ if (!copy) {
Branch: 1 branch
BranchTrueFalseTotal
if (!copy) { 0 0 0
2666 0 bqws_free_socket(ws);
2667 0 return NULL;
2668 }
2669  
2670 0 memset(copy, 0, sizeof(bqws_verify_filter));
2671 0 copy->magic = BQWS_FILTER_MAGIC;
2672 0 copy->text_size = text_size;
2673 0 size_t offset = 0;
2674  
2675 0 copy->path = verify_filter_str(copy, &offset, filter->path);
2676 0 copy->host = verify_filter_str(copy, &offset, filter->host);
2677 0 copy->origin = verify_filter_str(copy, &offset, filter->origin);
2678 0 copy->num_protocols = filter->num_protocols;
2679 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
2680 0 copy->protocols[i] = verify_filter_str(copy, &offset, filter->protocols[i]);
2681 }
2682  
2683 bqws_assert(offset == text_size);
2684  
2685 0 copy->verify_fn = ws->verify_fn;
2686 0 copy->verify_user = ws->verify_user;
2687 0 ws->verify_fn = &bqws_internal_filter_verify;
2688 0 ws->verify_user = copy;
2689 }
2690 }
2691  
2692 42 return ws;
2693 }
2694  
2695 16 void bqws_close(bqws_socket *ws, bqws_close_reason reason, const void *data, size_t size)
2696 {
2697 16 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 16 16
2698  
2699 bqws_mutex_lock(&ws->state.mutex);
2700  
2701 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2702 bqws_assert(size == 0 || data);
2703 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
2704 bqws_mutex_unlock(&ws->state.mutex);
2705 0 return;
2706 }
2707  
2708 16 bqws_msg_imp *imp = msg_alloc(ws, BQWS_MSG_CONTROL_CLOSE, size + 2);
2709 16 ▶ if (imp) {
Branch: 1 branch
BranchTrueFalseTotal
if (imp) { 16 0 16
2710 16 imp->msg.data[0] = (uint8_t)(reason >> 8);
2711 16 imp->msg.data[1] = (uint8_t)(reason & 0xff);
2712 16 memcpy(imp->msg.data + 2, data, size);
2713  
2714 16 ws->state.close_to_send = imp;
2715 16 ws->state.start_closing_ts = bqws_get_timestamp();
2716 16 ws->state.state = BQWS_STATE_CLOSING;
2717  
2718 16 ws_log(ws, "State: CLOSING (user close)");
2719 }
2720  
2721 bqws_mutex_unlock(&ws->state.mutex);
2722 }
2723  
2724 0 void bqws_queue_close(bqws_socket *ws, bqws_close_reason reason, const void *data, size_t size)
2725 {
2726 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
2727  
2728 bqws_mutex_lock(&ws->state.mutex);
2729  
2730 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2731 bqws_assert(size == 0 || data);
2732 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
2733 bqws_mutex_unlock(&ws->state.mutex);
2734 0 return;
2735 }
2736  
2737 0 bqws_msg_imp *imp = msg_alloc(ws, BQWS_MSG_CONTROL_CLOSE, size + 2);
2738 0 ▶ if (imp) {
Branch: 1 branch
BranchTrueFalseTotal
if (imp) { 0 0 0
2739 0 imp->msg.data[0] = (uint8_t)(reason >> 8);
2740 0 imp->msg.data[1] = (uint8_t)(reason & 0xff);
2741 0 memcpy(imp->msg.data + 2, data, size);
2742 0 ws_enqueue_send(ws, imp);
2743 }
2744  
2745 bqws_mutex_unlock(&ws->state.mutex);
2746 }
2747  
2748 55 void bqws_free_socket(bqws_socket *ws)
2749 {
2750 55 ▶ if (!ws) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!ws) return; 0 55 55
2751 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2752  
2753 55 ws_log(ws, "Freed");
2754  
2755 55 ▶ 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 55 55
if (ws->user_io.close_fn && !ws->state.io_closed) { 0 0 0
2756 0 ws->user_io.close_fn(ws->user_io.user, ws);
2757 }
2758  
2759 // Free everything, as the socket may have errored it can
2760 // be in almost any state
2761  
2762 // Pending messages
2763 55 msg_free_queue(ws, &ws->recv_queue);
2764 55 msg_free_queue(ws, &ws->recv_partial_queue);
2765 55 msg_free_queue(ws, &ws->send_queue);
2766 55 ▶ 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 55 55
2767 55 ▶ 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 50 55
2768  
2769 // Read/write buffers
2770 55 ws_free(ws, ws->io.handshake.data, ws->io.handshake.capacity);
2771 55 ws_free(ws, ws->io.handshake_overflow.data, ws->io.handshake_overflow.capacity);
2772 55 ▶ 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 55 55
2773 55 ▶ 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 55 55
2774 55 ▶ 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 55 55
2775  
2776 // Misc buffers
2777 55 ▶ 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 55 55
2778  
2779 // String copies
2780 55 ws_free_str(ws, ws->state.chosen_protocol);
2781 55 ws_free_str(ws, ws->name);
2782  
2783 // Verify filter copy
2784 55 ▶ if (ws->verify_fn == &bqws_internal_filter_verify) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->verify_fn == &bqws_internal_filter_verify) { 0 55 55
2785 0 bqws_verify_filter *filter = (bqws_verify_filter*)ws->verify_user;
2786 bqws_assert(filter->magic == BQWS_FILTER_MAGIC);
2787 0 filter->magic = BQWS_DELETED_MAGIC;
2788 0 ws_free(ws, filter, sizeof(bqws_verify_filter) + filter->text_size);
2789 }
2790  
2791 // Mutexes
2792 bqws_mutex_free(&ws->err_mutex);
2793 bqws_mutex_free(&ws->state.mutex);
2794 bqws_mutex_free(&ws->io.mutex);
2795 bqws_mutex_free(&ws->alloc.mutex);
2796 bqws_mutex_free(&ws->partial.mutex);
2797  
2798 bqws_assert(ws->alloc.memory_used == 0);
2799  
2800 55 ws->magic = BQWS_DELETED_MAGIC;
2801  
2802 55 bqws_allocator at = ws->allocator;
2803 55 bqws_allocator_free(&at, ws, sizeof(bqws_socket) + ws->user_size);
2804 }
2805  
2806 0 bqws_client_opts *bqws_server_get_client_opts(bqws_socket *ws)
2807 {
2808 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2809 bqws_assert(ws->is_server);
2810 // no-mutex(state): There's an inherent race condition with multiple accepts
2811 bqws_assert(ws->state.state == BQWS_STATE_CONNECTING);
2812  
2813 bqws_mutex_lock(&ws->io.mutex);
2814 0 bqws_client_opts *opts = ws->io.opts_from_client;
2815 bqws_mutex_unlock(&ws->io.mutex);
2816  
2817 0 return opts;
2818 }
2819  
2820 0 void bqws_server_accept(bqws_socket *ws, const char *protocol)
2821 {
2822 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2823 bqws_assert(ws->is_server);
2824 // no-mutex(state): There's an inherent race condition with multiple accepts
2825 bqws_assert(ws->state.state == BQWS_STATE_CONNECTING);
2826 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
2827  
2828 // Use emtpy string to differentiate from not set
2829 0 ▶ if (!protocol) protocol = "";
Branch: 1 branch
BranchTrueFalseTotal
if (!protocol) protocol = ""; 0 0 0
2830  
2831 bqws_mutex_lock(&ws->state.mutex);
2832 0 ▶ if (!ws->state.chosen_protocol) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->state.chosen_protocol) { 0 0 0
2833 0 ws->state.chosen_protocol = ws_copy_str(ws, protocol);
2834 }
2835 bqws_mutex_unlock(&ws->state.mutex);
2836 }
2837  
2838 0 void bqws_server_reject(bqws_socket *ws)
2839 {
2840 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2841 bqws_assert(ws->is_server);
2842  
2843 0 ws_fail(ws, BQWS_ERR_SERVER_REJECT);
2844 0 }
2845  
2846 42 bqws_state bqws_get_state(const bqws_socket *ws)
2847 {
2848 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2849 // no-mutex(state): We can always underestimate the state
2850 42 bqws_state state = ws->state.state, override_state = ws->state.override_state;
2851 42 ▶ if (override_state > state) state = override_state;
Branch: 1 branch
BranchTrueFalseTotal
if (override_state > state) state = override_state; 0 42 42
2852 42 return state;
2853 }
2854  
2855 107 bqws_error bqws_get_error(const bqws_socket *ws)
2856 {
2857 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2858 107 return ws->err;
2859 }
2860  
2861 0 bool bqws_is_connecting(const bqws_socket *ws)
2862 {
2863 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2864 // no-mutex(state): We can always underestimate the state
2865 0 bqws_state state = ws->state.state, override_state = ws->state.override_state;
2866 0 ▶ if (override_state > state) state = override_state;
Branch: 1 branch
BranchTrueFalseTotal
if (override_state > state) state = override_state; 0 0 0
2867 0 return state == BQWS_STATE_CONNECTING;
2868 }
2869  
2870 0 bool bqws_is_closed(const bqws_socket *ws)
2871 {
2872 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2873 // no-mutex(state): We can always underestimate the state
2874 0 bqws_state state = ws->state.state, override_state = ws->state.override_state;
2875 0 ▶ if (override_state > state) state = override_state;
Branch: 1 branch
BranchTrueFalseTotal
if (override_state > state) state = override_state; 0 0 0
2876 0 return state == BQWS_STATE_CLOSED;
2877 }
2878  
2879 3 size_t bqws_get_memory_used(const bqws_socket *ws)
2880 {
2881 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2882 // no-mutex(alloc): This doesn't need to be accurate
2883 3 return ws->alloc.memory_used;
2884 }
2885  
2886 0 bool bqws_is_server(const bqws_socket *ws)
2887 {
2888 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2889 0 return ws->is_server;
2890 }
2891  
2892 0 void *bqws_user_data(const bqws_socket *ws)
2893 {
2894 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2895 0 return (void*)ws->user_data;
2896 }
2897  
2898 0 size_t bqws_user_data_size(const bqws_socket *ws)
2899 {
2900 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2901 0 return ws->user_size;
2902 }
2903  
2904 0 const char *bqws_get_name(const bqws_socket *ws)
2905 {
2906 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2907 0 return ws->name;
2908 }
2909  
2910 0 bqws_stats bqws_get_stats(const bqws_socket *ws)
2911 {
2912 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2913  
2914 bqws_stats stats;
2915 0 msg_queue_get_stats((bqws_msg_queue*)&ws->recv_queue, &stats.recv);
2916 0 msg_queue_get_stats((bqws_msg_queue*)&ws->send_queue, &stats.send);
2917 0 return stats;
2918 }
2919  
2920 0 void *bqws_get_io_user(const bqws_socket *ws)
2921 {
2922 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2923  
2924 0 return ws->user_io.user;
2925 }
2926  
2927 0 bool bqws_get_io_closed(const bqws_socket *ws)
2928 {
2929 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2930  
2931 // no-mutex(state): This can be inaccurate
2932 0 return ws->state.io_closed;
2933 }
2934  
2935 0 bqws_limits bqws_get_limits(const bqws_socket *ws)
2936 {
2937 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2938 0 return ws->limits;
2939 }
2940  
2941 0 void bqws_set_limits(bqws_socket *ws, const bqws_limits *limits)
2942 {
2943 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2944 bqws_assert(limits);
2945  
2946 0 bqws_limits copy = *limits;
2947 0 ws_expand_default_limits(&copy);
2948 0 ws->limits = copy;
2949 0 }
2950  
2951 0 bqws_close_reason bqws_get_peer_close_reason(const bqws_socket *ws)
2952 {
2953 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2954  
2955 bqws_mutex_lock((bqws_mutex*)&ws->state.mutex);
2956 0 bqws_close_reason reason = ws->state.peer_reason;
2957 bqws_mutex_unlock((bqws_mutex*)&ws->state.mutex);
2958  
2959 0 return reason;
2960 }
2961  
2962 0 bqws_error bqws_get_peer_error(const bqws_socket *ws)
2963 {
2964 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2965  
2966 bqws_mutex_lock((bqws_mutex*)&ws->state.mutex);
2967 0 bqws_error err = ws->state.peer_err;
2968 bqws_mutex_unlock((bqws_mutex*)&ws->state.mutex);
2969  
2970 0 return err;
2971 }
2972  
2973 0 const char *bqws_get_protocol(const bqws_socket *ws)
2974 {
2975 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2976  
2977 // TODO: Cache this pointer outside of the state mutex
2978 bqws_mutex_lock((bqws_mutex*)&ws->state.mutex);
2979 0 const char *protocol = ws->state.chosen_protocol;
2980 bqws_mutex_unlock((bqws_mutex*)&ws->state.mutex);
2981  
2982 0 return protocol;
2983 }
2984  
2985 91 bqws_msg *bqws_recv(bqws_socket *ws)
2986 {
2987 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
2988 91 ▶ if (ws->err) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return NULL; 5 86 91
2989  
2990 // Messages are re-combined in `recv_queue` if
2991 // `recv_partial_messages` is disabled.
2992  
2993 86 bqws_msg_imp *imp = msg_dequeue(&ws->recv_queue);
2994 86 ▶ if (!imp) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!imp) return NULL; 41 45 86
2995 bqws_assert(imp->magic == BQWS_MSG_MAGIC);
2996  
2997 45 msg_release_ownership(ws, imp);
2998 45 return &imp->msg;
2999 }
3000  
3001 45 void bqws_free_msg(bqws_msg *msg)
3002 {
3003 45 ▶ if (!msg) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg) return; 0 45 45
3004  
3005 45 bqws_msg_imp *imp = msg_imp(msg);
3006 bqws_assert(imp->magic == BQWS_MSG_MAGIC);
3007 bqws_assert(imp->owner == NULL);
3008  
3009 45 imp->magic = BQWS_DELETED_MAGIC;
3010  
3011 45 bqws_allocator at = imp->allocator;
3012 45 bqws_allocator_free(&at, imp, msg_alloc_size(msg));
3013 }
3014  
3015 13 void bqws_send(bqws_socket *ws, bqws_msg_type type, const void *data, size_t size)
3016 {
3017 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3018 bqws_assert((type & BQWS_MSG_PARTIAL_BIT) == 0);
3019 13 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 13 13
3020 bqws_assert(size == 0 || data);
3021  
3022 13 bqws_msg_imp *imp = msg_alloc(ws, type, size);
3023 13 ▶ if (!imp) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!imp) return; 0 13 13
3024  
3025 13 memcpy(imp->msg.data, data, size);
3026 13 ws_enqueue_send(ws, imp);
3027 }
3028  
3029 0 void bqws_send_binary(bqws_socket *ws, const void *data, size_t size)
3030 {
3031 0 bqws_send(ws, BQWS_MSG_BINARY, data, size);
3032 0 }
3033  
3034 0 void bqws_send_text(bqws_socket *ws, const char *str)
3035 {
3036 bqws_assert(str);
3037 0 bqws_send(ws, BQWS_MSG_TEXT, str, strlen(str));
3038 0 }
3039  
3040 0 void bqws_send_text_len(bqws_socket *ws, const void *str, size_t len)
3041 {
3042 0 bqws_send(ws, BQWS_MSG_TEXT, str, len);
3043 0 }
3044  
3045 0 bqws_msg *bqws_allocate_msg(bqws_socket *ws, bqws_msg_type type, size_t size)
3046 {
3047 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3048 0 ▶ if (ws->err) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return NULL; 0 0 0
3049  
3050 0 bqws_msg_imp *imp = msg_alloc(ws, type, size);
3051 0 ▶ if (!imp) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!imp) return NULL; 0 0 0
3052  
3053 0 msg_release_ownership(ws, imp);
3054 0 return &imp->msg;
3055 }
3056  
3057 0 void bqws_send_msg(bqws_socket *ws, bqws_msg *msg)
3058 {
3059 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3060 bqws_assert(msg && (msg->type == BQWS_MSG_TEXT || msg->type == BQWS_MSG_BINARY));
3061 bqws_assert(msg->size <= msg->capacity);
3062  
3063 0 bqws_msg_imp *imp = msg_imp(msg);
3064 bqws_assert(imp->magic == BQWS_MSG_MAGIC);
3065  
3066 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
3067  
3068 0 ▶ if (!msg_acquire_ownership(ws, imp)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg_acquire_ownership(ws, imp)) return; 0 0 0
3069  
3070 0 ws_enqueue_send(ws, imp);
3071 }
3072  
3073 0 void bqws_send_begin(bqws_socket *ws, bqws_msg_type type)
3074 {
3075 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3076 bqws_assert(type == BQWS_MSG_TEXT || type == BQWS_MSG_BINARY);
3077 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
3078  
3079 bqws_mutex_lock(&ws->partial.mutex);
3080  
3081 bqws_assert(ws->partial.send_partial_type == BQWS_MSG_INVALID);
3082 bqws_assert(ws->partial.next_partial_to_send == NULL);
3083  
3084 0 ws->partial.send_partial_type = type;
3085  
3086 bqws_mutex_unlock(&ws->partial.mutex);
3087 }
3088  
3089 0 void bqws_send_append(bqws_socket *ws, const void *data, size_t size)
3090 {
3091 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3092 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
3093  
3094 bqws_mutex_lock(&ws->partial.mutex);
3095  
3096 bqws_assert(ws->partial.send_partial_type != BQWS_MSG_INVALID);
3097  
3098 0 ▶ if (ws->partial.next_partial_to_send) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->partial.next_partial_to_send) { 0 0 0
3099 bqws_assert(ws->partial.next_partial_to_send->magic == BQWS_MSG_MAGIC);
3100 0 ws_enqueue_send(ws, ws->partial.next_partial_to_send);
3101 }
3102  
3103 0 bqws_msg_type partial_type = (bqws_msg_type)(ws->partial.send_partial_type | BQWS_MSG_PARTIAL_BIT);
3104 0 bqws_msg_imp *imp = msg_alloc(ws, partial_type, size);
3105 0 ▶ if (imp) {
Branch: 1 branch
BranchTrueFalseTotal
if (imp) { 0 0 0
3106 0 memcpy(imp->msg.data, data, size);
3107 0 ws->partial.next_partial_to_send = imp;
3108 }
3109  
3110 bqws_mutex_unlock(&ws->partial.mutex);
3111 }
3112  
3113 0 void bqws_send_append_str(bqws_socket *ws, const char *str)
3114 {
3115 0 bqws_send_append(ws, str, strlen(str));
3116 0 }
3117  
3118 0 void bqws_send_append_msg(bqws_socket *ws, bqws_msg *msg)
3119 {
3120 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3121 bqws_assert(msg->type == BQWS_MSG_TEXT || msg->type == BQWS_MSG_BINARY);
3122 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
3123  
3124 bqws_mutex_lock(&ws->partial.mutex);
3125  
3126 bqws_assert(ws->partial.send_partial_type != BQWS_MSG_INVALID);
3127 bqws_assert((ws->partial.send_partial_type & BQWS_MSG_TYPE_MASK) == msg->type);
3128  
3129 0 ▶ if (ws->partial.next_partial_to_send) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->partial.next_partial_to_send) { 0 0 0
3130 bqws_assert(ws->partial.next_partial_to_send->magic == BQWS_MSG_MAGIC);
3131 0 ws_enqueue_send(ws, ws->partial.next_partial_to_send);
3132 }
3133  
3134 0 bqws_msg_imp *imp = msg_imp(msg);
3135 0 ▶ if (!msg_acquire_ownership(ws, imp)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg_acquire_ownership(ws, imp)) return; 0 0 0
3136  
3137 0 msg->type = (bqws_msg_type)(ws->partial.send_partial_type | BQWS_MSG_PARTIAL_BIT);
3138 0 ws->partial.next_partial_to_send = imp;
3139  
3140 bqws_mutex_unlock(&ws->partial.mutex);
3141 }
3142  
3143 0 void bqws_send_finish(bqws_socket *ws)
3144 {
3145 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3146 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
3147  
3148 bqws_mutex_lock(&ws->partial.mutex);
3149  
3150 bqws_assert(ws->partial.send_partial_type != BQWS_MSG_INVALID);
3151  
3152 0 ▶ if (ws->partial.next_partial_to_send) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->partial.next_partial_to_send) { 0 0 0
3153 bqws_assert(ws->partial.next_partial_to_send->magic == BQWS_MSG_MAGIC);
3154 0 bqws_msg_type type = ws->partial.next_partial_to_send->msg.type;
3155 0 ws->partial.next_partial_to_send->msg.type = (bqws_msg_type)(type | BQWS_MSG_FINAL_BIT);
3156 0 ws_enqueue_send(ws, ws->partial.next_partial_to_send);
3157 0 ws->partial.next_partial_to_send = NULL;
3158 }
3159  
3160 0 ws->partial.send_partial_type = BQWS_MSG_INVALID;
3161  
3162 bqws_mutex_unlock(&ws->partial.mutex);
3163 }
3164  
3165 1 void bqws_send_ping(bqws_socket *ws, const void *data, size_t size)
3166 {
3167 1 bqws_send(ws, BQWS_MSG_CONTROL_PING, data, size);
3168 1 }
3169  
3170 0 void bqws_send_pong(bqws_socket *ws, const void *data, size_t size)
3171 {
3172 0 bqws_send(ws, BQWS_MSG_CONTROL_PONG, data, size);
3173 0 }
3174  
3175 0 void bqws_update(bqws_socket *ws)
3176 {
3177 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3178  
3179 0 bqws_update_state(ws);
3180 0 bqws_update_io(ws);
3181 0 }
3182  
3183 0 void bqws_update_state(bqws_socket *ws)
3184 {
3185 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3186  
3187 bqws_mutex_lock(&ws->state.mutex);
3188 0 bqws_state state = ws->state.state;
3189 0 char *protocol = ws->state.chosen_protocol;
3190 0 bqws_timestamp start_closing_ts = ws->state.start_closing_ts;
3191 bqws_mutex_unlock(&ws->state.mutex);
3192  
3193 bqws_mutex_lock(&ws->io.mutex);
3194  
3195 0 ▶ if (state == BQWS_STATE_CONNECTING) {
Branch: 1 branch
BranchTrueFalseTotal
if (state == BQWS_STATE_CONNECTING) { 0 0 0
3196  
3197 // If we're connecting but haven't set a protocol and the user
3198 // has provided a verify function or filter run it here.
3199 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
3200 bqws_assert(ws->is_server);
3201 bqws_assert(ws->io.opts_from_client);
3202 0 ws->verify_fn(ws->verify_user, ws, ws->io.opts_from_client);
3203 }
3204  
3205 // Connect timeout
3206 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
3207 0 bqws_timestamp time = bqws_get_timestamp();
3208 0 size_t delta = bqws_timestamp_delta_to_ms(ws->io.start_connect_ts, time);
3209 0 ▶ if (delta > ws->connect_timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (delta > ws->connect_timeout) { 0 0 0
3210 0 ws_fail(ws, BQWS_ERR_CONNECT_TIMEOUT);
3211  
3212 bqws_mutex_lock(&ws->state.mutex);
3213 0 ws_close(ws);
3214 bqws_mutex_unlock(&ws->state.mutex);
3215 }
3216 }
3217  
3218 0 ▶ } else if (state == BQWS_STATE_OPEN) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (state == BQWS_STATE_OPEN) { 0 0 0
3219  
3220 // Automatic PING send
3221 0 ▶ if (ws->ping_interval != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->ping_interval != SIZE_MAX) { 0 0 0
3222 0 bqws_timestamp time = bqws_get_timestamp();
3223 0 size_t delta_read = bqws_timestamp_delta_to_ms(ws->io.last_read_ts, time);
3224 0 size_t delta_ping = bqws_timestamp_delta_to_ms(ws->io.last_ping_ts, time);
3225 0 size_t delta_write = bqws_timestamp_delta_to_ms(ws->io.last_write_ts, time);
3226  
3227 0 size_t delta = delta_read >= delta_write ? delta_read : delta_write;
3228 0 size_t delta_from_ping = delta <= delta_ping ? delta : delta_ping;
3229  
3230 0 ▶ if (delta_from_ping > ws->ping_interval) {
Branch: 1 branch
BranchTrueFalseTotal
if (delta_from_ping > ws->ping_interval) { 0 0 0
3231 0 ws->io.last_ping_ts = time;
3232 // Maybe send PONG only?
3233 0 bqws_send_ping(ws, NULL, 0);
3234 }
3235  
3236 0 ▶ if (ws->ping_response_timeout != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->ping_response_timeout != SIZE_MAX) { 0 0 0
3237 0 ▶ if (delta >= ws->ping_response_timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (delta >= ws->ping_response_timeout) { 0 0 0
3238 0 ws_fail(ws, BQWS_ERR_PING_TIMEOUT);
3239  
3240 bqws_mutex_lock(&ws->state.mutex);
3241 0 ws_close(ws);
3242 bqws_mutex_unlock(&ws->state.mutex);
3243 }
3244 }
3245 }
3246  
3247 0 ▶ } else if (state == BQWS_STATE_CLOSING) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (state == BQWS_STATE_CLOSING) { 0 0 0
3248  
3249 // Close timeout
3250 0 ▶ if (ws->close_timeout != SIZE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->close_timeout != SIZE_MAX) { 0 0 0
3251 0 bqws_timestamp time = bqws_get_timestamp();
3252 0 size_t delta = bqws_timestamp_delta_to_ms(start_closing_ts, time);
3253 0 ▶ if (delta > ws->close_timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (delta > ws->close_timeout) { 0 0 0
3254 0 ws_fail(ws, BQWS_ERR_CLOSE_TIMEOUT);
3255  
3256 bqws_mutex_lock(&ws->state.mutex);
3257 0 ws_close(ws);
3258 bqws_mutex_unlock(&ws->state.mutex);
3259 }
3260 }
3261  
3262 }
3263  
3264 bqws_mutex_unlock(&ws->io.mutex);
3265 0 }
3266  
3267 0 void bqws_update_io(bqws_socket *ws)
3268 {
3269 0 bqws_update_io_write(ws);
3270 0 bqws_update_io_read(ws);
3271 0 }
3272  
3273 0 void bqws_update_io_read(bqws_socket *ws)
3274 {
3275 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3276  
3277 0 bool do_read = true;
3278  
3279 bqws_mutex_lock(&ws->io.mutex);
3280  
3281 // If read and write are stopped close the IO
3282 bqws_mutex_lock(&ws->state.mutex);
3283 0 ▶ if (!ws->state.io_started) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->state.io_started) { 0 0 0
3284 0 ▶ if (ws->user_io.init_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.init_fn) { 0 0 0
3285 0 ws->user_io.init_fn(ws->user_io.user, ws);
3286 }
3287 0 ws->state.io_started = true;
3288 }
3289 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
3290 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
3291 0 ws->user_io.close_fn(ws->user_io.user, ws);
3292 }
3293 0 ws->state.io_closed = true;
3294 }
3295 0 do_read = !ws->state.stop_read;
3296 bqws_mutex_unlock(&ws->state.mutex);
3297  
3298 // TODO: Throttle reads
3299 0 ▶ if (do_read) {
Branch: 1 branch
BranchTrueFalseTotal
if (do_read) { 0 0 0
3300 0 ▶ if (ws->user_io.recv_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.recv_fn) { 0 0 0
3301 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
3302 // Keep reading as long as there is space
3303 }
3304 }
3305 }
3306  
3307 bqws_mutex_unlock(&ws->io.mutex);
3308 0 }
3309  
3310 0 void bqws_update_io_write(bqws_socket *ws)
3311 {
3312 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3313  
3314 0 bool do_write = true;
3315  
3316 bqws_mutex_lock(&ws->io.mutex);
3317  
3318 // If read and write are stopped close the IO
3319 bqws_mutex_lock(&ws->state.mutex);
3320 0 ▶ if (!ws->state.io_started) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ws->state.io_started) { 0 0 0
3321 0 ▶ if (ws->user_io.init_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.init_fn) { 0 0 0
3322 0 ws->user_io.init_fn(ws->user_io.user, ws);
3323 }
3324 0 ws->state.io_started = true;
3325 }
3326 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
3327 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
3328 0 ws->user_io.close_fn(ws->user_io.user, ws);
3329 }
3330 0 ws->state.io_closed = true;
3331 }
3332 0 do_write = !ws->state.stop_write;
3333 bqws_mutex_unlock(&ws->state.mutex);
3334  
3335 0 ▶ if (do_write) {
Branch: 1 branch
BranchTrueFalseTotal
if (do_write) { 0 0 0
3336 0 ▶ if (ws->user_io.send_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.send_fn) { 0 0 0
3337 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
3338 // Keep writing as long as there is space
3339 }
3340 }
3341  
3342 // Re-check if we should stop write if the socket got closed
3343 bqws_mutex_lock(&ws->state.mutex);
3344 0 do_write = !ws->state.stop_write;
3345 bqws_mutex_unlock(&ws->state.mutex);
3346  
3347 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
3348 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
3349 0 ws_fail(ws, BQWS_ERR_IO_WRITE);
3350 }
3351 }
3352 }
3353  
3354 bqws_mutex_unlock(&ws->io.mutex);
3355 0 }
3356  
3357 47 size_t bqws_read_from(bqws_socket *ws, const void *data, size_t size)
3358 {
3359 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3360 bqws_assert(!ws->user_io.recv_fn);
3361  
3362 bqws_mutex_lock(&ws->io.mutex);
3363  
3364 bqws_mem_stream s;
3365 47 s.ptr = (char*)data;
3366 47 s.end = s.ptr + size;
3367  
3368 98 ▶ while (ws_read_data(ws, &mem_stream_recv, &s)) {
Branch: 1 branch
BranchTrueFalseTotal
while (ws_read_data(ws, &mem_stream_recv, &s)) { 51 47 98
3369 // Keep reading as long as there is space
3370 }
3371  
3372 bqws_mutex_unlock(&ws->io.mutex);
3373  
3374 47 return s.ptr - (char*)data;
3375 }
3376  
3377 62 size_t bqws_write_to(bqws_socket *ws, void *data, size_t size)
3378 {
3379 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3380 bqws_assert(!ws->user_io.send_fn);
3381  
3382 bqws_mutex_lock(&ws->io.mutex);
3383  
3384 bqws_mem_stream s;
3385 62 s.ptr = (char*)data;
3386 62 s.end = s.ptr + size;
3387  
3388 105 ▶ while (ws_write_data(ws, &mem_stream_send, &s)) {
Branch: 1 branch
BranchTrueFalseTotal
while (ws_write_data(ws, &mem_stream_send, &s)) { 43 62 105
3389 // Keep writing as long as there is space
3390 }
3391  
3392 62 ▶ if (ws->user_io.flush_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->user_io.flush_fn) { 0 62 62
3393 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
3394 0 ws_fail(ws, BQWS_ERR_IO_WRITE);
3395 }
3396 }
3397  
3398 bqws_mutex_unlock(&ws->io.mutex);
3399  
3400 62 return s.ptr - (char*)data;
3401 }
3402  
3403 0 void bqws_direct_push_msg(bqws_socket *ws, bqws_msg *msg)
3404 {
3405 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3406 bqws_assert(msg && msg->size <= msg->capacity);
3407  
3408 0 bqws_msg_imp *imp = msg_imp(msg);
3409 bqws_assert(imp->magic == BQWS_MSG_MAGIC);
3410  
3411 0 ▶ if (ws->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ws->err) return; 0 0 0
3412  
3413 0 ▶ if (!msg_acquire_ownership(ws, imp)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg_acquire_ownership(ws, imp)) return; 0 0 0
3414  
3415 0 ▶ if (ws->log_recv) {
Branch: 1 branch
BranchTrueFalseTotal
if (ws->log_recv) { 0 0 0
3416 0 ws_log2(ws, "Direct recv: ", bqws_msg_type_str(msg->type));
3417 }
3418  
3419 0 ws_enqueue_recv(ws, imp);
3420 }
3421  
3422 0 void bqws_direct_set_override_state(bqws_socket *ws, bqws_state state)
3423 {
3424 bqws_assert(ws && ws->magic == BQWS_SOCKET_MAGIC);
3425  
3426 0 ws_log2(ws, "Override state: ", bqws_state_str(state));
3427  
3428 bqws_mutex_lock(&ws->state.mutex);
3429 0 ws->state.override_state = state;
3430 bqws_mutex_unlock(&ws->state.mutex);
3431 0 }
3432  
3433 0 void bqws_direct_fail(bqws_socket *ws, bqws_error err)
3434 {
3435 0 ws_fail(ws, err);
3436 0 }
3437  
3438 0 bool bqws_parse_url(bqws_url *url, const char *str)
3439 {
3440 // Format [wss://][host.example.com][:1234][/path]
3441  
3442 0 const char *scheme = str;
3443 0 const char *scheme_end = strstr(scheme, "://");
3444 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
3445 0 const char *port_start = host;
3446 0 ▶ if (*host == '[') {
Branch: 1 branch
BranchTrueFalseTotal
if (*host == '[') { 0 0 0
3447 // Skip IPv6 address
3448 0 port_start = strstr(host, "]");
3449 0 ▶ if (!port_start) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (!port_start) return false; 0 0 0
3450 }
3451 0 const char *port = strstr(port_start, ":");
3452 0 const char *path = strstr(port_start, "/");
3453 0 ▶ if (!path) path = port_start + strlen(port_start);
Branch: 1 branch
BranchTrueFalseTotal
if (!path) path = port_start + strlen(port_start); 0 0 0
3454 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
3455 0 ▶ const char *host_end = port ? port : path;
Branch: 1 branch
BranchTrueFalseTotal
const char *host_end = port ? port : path; 0 0 0
3456  
3457 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
3458 0 size_t host_len = host_end - host;
3459 0 ▶ if (scheme_len >= sizeof(url->scheme)) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (scheme_len >= sizeof(url->scheme)) return false; 0 0 0
3460 0 ▶ if (host_len >= sizeof(url->host)) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (host_len >= sizeof(url->host)) return false; 0 0 0
3461  
3462 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
3463  
3464 int port_num;
3465 0 ▶ if (port) {
Branch: 1 branch
BranchTrueFalseTotal
if (port) { 0 0 0
3466 char *port_end;
3467 0 port_num = (int)strtol(port + 1, &port_end, 10);
3468 0 ▶ if (port_end != path) return false;
Branch: 1 branch
BranchTrueFalseTotal
if (port_end != path) return false; 0 0 0
3469 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
3470 0 port_num = (uint16_t)port_num;
3471 } else {
3472 0 ▶ port_num = secure ? 443 : 80;
Branch: 1 branch
BranchTrueFalseTotal
port_num = secure ? 443 : 80; 0 0 0
3473 }
3474  
3475 // vv No fails below, no writes above ^^
3476  
3477 0 url->port = (uint16_t)port_num;
3478  
3479 0 memcpy(url->scheme, scheme, scheme_len);
3480 0 url->scheme[scheme_len] = '\0';
3481  
3482 0 memcpy(url->host, host, host_len);
3483 0 url->host[host_len] = '\0';
3484  
3485 0 ▶ url->path = *path ? path : "/";
Branch: 1 branch
BranchTrueFalseTotal
url->path = *path ? path : "/"; 0 0 0
3486  
3487 0 url->secure = secure;
3488  
3489 0 return true;
3490 }
3491  
3492 31 const char *bqws_error_str(bqws_error error)
3493 {
3494 31 switch (error) {
3495 21 case BQWS_OK: return "OK";
3496 0 case BQWS_ERR_UNKNOWN: return "UNKNOWN";
3497 0 case BQWS_ERR_SERVER_REJECT: return "SERVER_REJECT";
3498 0 case BQWS_ERR_LIMIT_MAX_MEMORY_USED: return "LIMIT_MAX_MEMORY_USED";
3499 0 case BQWS_ERR_LIMIT_MAX_RECV_MSG_SIZE: return "LIMIT_MAX_RECV_MSG_SIZE";
3500 0 case BQWS_ERR_LIMIT_MAX_HANDSHAKE_SIZE: return "LIMIT_MAX_HANDSHAKE_SIZE";
3501 0 case BQWS_ERR_LIMIT_MAX_PARTIAL_MESSAGE_PARTS: return "LIMIT_MAX_PARTIAL_MESSAGE_PARTS";
3502 0 case BQWS_ERR_CONNECT_TIMEOUT: return "BQWS_ERR_CONNECT_TIMEOUT";
3503 0 case BQWS_ERR_PING_TIMEOUT: return "BQWS_ERR_PING_TIMEOUT";
3504 0 case BQWS_ERR_CLOSE_TIMEOUT: return "BQWS_ERR_CLOSE_TIMEOUT";
3505 0 case BQWS_ERR_ALLOCATOR: return "ALLOCATOR";
3506 2 case BQWS_ERR_BAD_CONTINUATION: return "BAD_CONTINUATION";
3507 2 case BQWS_ERR_UNFINISHED_PARTIAL: return "UNFINISHED_PARTIAL";
3508 0 case BQWS_ERR_PARTIAL_CONTROL: return "PARTIAL_CONTROL";
3509 0 case BQWS_ERR_BAD_OPCODE: return "BAD_OPCODE";
3510 0 case BQWS_ERR_RESERVED_BIT: return "RESERVED_BIT";
3511 4 case BQWS_ERR_BAD_CLOSE: return "BAD_CLOSE";
3512 2 case BQWS_ERR_BAD_UTF8: return "BAD_UTF8";
3513 0 case BQWS_ERR_IO_WRITE: return "IO_WRITE";
3514 0 case BQWS_ERR_IO_READ: return "IO_READ";
3515 0 case BQWS_ERR_BAD_HANDSHAKE: return "BAD_HANDSHAKE";
3516 0 case BQWS_ERR_UNSUPPORTED_VERSION: return "UNSUPPORTED_VERSION";
3517 0 case BQWS_ERR_TOO_MANY_HEADERS: return "TOO_MANY_HEADERS";
3518 0 case BQWS_ERR_TOO_MANY_PROTOCOLS: return "TOO_MANY_PROTOCOLS";
3519 0 case BQWS_ERR_HEADER_KEY_TOO_LONG: return "HEADER_KEY_TOO_LONG";
3520 0 case BQWS_ERR_HEADER_BAD_ACCEPT: return "HEADER_BAD_ACCEPT";
3521 0 case BQWS_ERR_HEADER_PARSE: return "HEADER_PARSE";
3522 0 default: return "(unknown)";
3523 }
3524 }
3525  
3526 0 const char *bqws_msg_type_str(bqws_msg_type type)
3527 {
3528 0 switch (type) {
3529 0 case BQWS_MSG_TEXT: return "TEXT";
3530 0 case BQWS_MSG_BINARY: return "BINARY";
3531 0 case BQWS_MSG_PARTIAL_TEXT: return "PARTIAL_TEXT";
3532 0 case BQWS_MSG_PARTIAL_BINARY: return "PARTIAL_BINARY";
3533 0 case BQWS_MSG_FINAL_TEXT: return "FINAL_TEXT";
3534 0 case BQWS_MSG_FINAL_BINARY: return "FINAL_BINARY";
3535 0 case BQWS_MSG_CONTROL_CLOSE: return "CONTROL_CLOSE";
3536 0 case BQWS_MSG_CONTROL_PING: return "CONTROL_PING";
3537 0 case BQWS_MSG_CONTROL_PONG: return "CONTROL_PONG";
3538 0 default: return "(unknown)";
3539 }
3540 }
3541  
3542 0 const char *bqws_state_str(bqws_state state)
3543 {
3544 0 switch (state) {
3545 0 case BQWS_STATE_INVALID: return "INVALID";
3546 0 case BQWS_STATE_CONNECTING: return "CONNECTING";
3547 0 case BQWS_STATE_OPEN: return "OPEN";
3548 0 case BQWS_STATE_CLOSING: return "CLOSING";
3549 0 case BQWS_STATE_CLOSED: return "CLOSED";
3550 0 default: return "(unknown)";
3551 }
3552 }
3553  
3554 // TODO: Add a define for this
3555  
3556 /* ================ sha1.c ================ */
3557 /*
3558 SHA-1 in C
3559 By Steve Reid <steve@edmweb.com>
3560 100% Public Domain
3561 Test Vectors (from FIPS PUB 180-1)
3562 "abc"
3563 A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
3564 "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
3565 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
3566 A million repetitions of "a"
3567 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
3568 */
3569  
3570 typedef struct {
3571 uint32_t state[5];
3572 uint32_t count[2];
3573 unsigned char buffer[64];
3574 } SHA1_CTX;
3575  
3576 #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
3577  
3578 /* blk0() and blk() perform the initial expand. */
3579 /* I got the idea of expanding during the round function from SSLeay */
3580 #define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
3581 |(rol(block->l[i],8)&0x00FF00FF))
3582 #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
3583 ^block->l[(i+2)&15]^block->l[i&15],1))
3584  
3585 /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
3586 #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
3587 #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
3588 #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
3589 #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
3590 #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
3591  
3592 /* Hash a single 512-bit block. This is the core of the algorithm. */
3593  
3594 0 static void SHA1Transform(uint32_t state[5], const void *buffer)
3595 {
3596 uint32_t a, b, c, d, e;
3597 typedef union {
3598 unsigned char c[64];
3599 uint32_t l[16];
3600 } CHAR64LONG16;
3601 0 CHAR64LONG16 block_buf, *block = &block_buf;
3602 0 memcpy(block, buffer, 64);
3603 /* Copy context->state[] to working vars */
3604 0 a = state[0];
3605 0 b = state[1];
3606 0 c = state[2];
3607 0 d = state[3];
3608 0 e = state[4];
3609 /* 4 rounds of 20 operations each. Loop unrolled. */
3610 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);
3611 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);
3612 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);
3613 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);
3614 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);
3615 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);
3616 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);
3617 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);
3618 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);
3619 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);
3620 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);
3621 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);
3622 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);
3623 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);
3624 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);
3625 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);
3626 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);
3627 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);
3628 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);
3629 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);
3630 /* Add the working vars back into context.state[] */
3631 0 state[0] += a;
3632 0 state[1] += b;
3633 0 state[2] += c;
3634 0 state[3] += d;
3635 0 state[4] += e;
3636 0 }
3637  
3638 /* SHA1Init - Initialize new context */
3639  
3640 0 static void SHA1Init(SHA1_CTX* context)
3641 {
3642 /* SHA1 initialization constants */
3643 0 context->state[0] = 0x67452301;
3644 0 context->state[1] = 0xEFCDAB89;
3645 0 context->state[2] = 0x98BADCFE;
3646 0 context->state[3] = 0x10325476;
3647 0 context->state[4] = 0xC3D2E1F0;
3648 0 context->count[0] = context->count[1] = 0;
3649 0 }
3650  
3651 /* Run your data through this. */
3652  
3653 0 static void SHA1Update(SHA1_CTX* context, const void* data, uint32_t len)
3654 {
3655 uint32_t i, j;
3656 0 const char *bytes = (const char *)data;
3657  
3658 0 j = context->count[0];
3659 0 ▶ if ((context->count[0] += len << 3) < j)
Branch: 1 branch
BranchTrueFalseTotal
if ((context->count[0] += len << 3) < j) 0 0 0
3660 0 context->count[1]++;
3661 0 context->count[1] += (len>>29);
3662 0 j = (j >> 3) & 63;
3663 0 ▶ if ((j + len) > 63) {
Branch: 1 branch
BranchTrueFalseTotal
if ((j + len) > 63) { 0 0 0
3664 0 memcpy(&context->buffer[j], data, (i = 64-j));
3665 0 SHA1Transform(context->state, context->buffer);
3666 0 ▶ for ( ; i + 63 < len; i += 64) {
Branch: 1 branch
BranchTrueFalseTotal
for ( ; i + 63 < len; i += 64) { 0 0 0
3667 0 SHA1Transform(context->state, &bytes[i]);
3668 }
3669 0 j = 0;
3670 }
3671 0 else i = 0;
3672 0 memcpy(&context->buffer[j], &bytes[i], len - i);
3673 0 }
3674  
3675  
3676 /* Add padding and return the message digest. */
3677  
3678 0 static void SHA1Final(unsigned char digest[20], SHA1_CTX* context)
3679 {
3680 unsigned i;
3681 unsigned char finalcount[8];
3682 unsigned char c;
3683  
3684 0 ▶ for (i = 0; i < 8; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 8; i++) { 0 0 0
3685 0 finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
3686 0 >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */
3687 }
3688 0 c = 0200;
3689 0 SHA1Update(context, &c, 1);
3690 0 ▶ while ((context->count[0] & 504) != 448) {
Branch: 1 branch
BranchTrueFalseTotal
while ((context->count[0] & 504) != 448) { 0 0 0
3691 0 c = 0000;
3692 0 SHA1Update(context, &c, 1);
3693 }
3694 0 SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */
3695 0 ▶ for (i = 0; i < 20; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 20; i++) { 0 0 0
3696 0 digest[i] = (unsigned char)
3697 0 ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
3698 }
3699 0 }
3700 /* ================ end of sha1.c ================ */
3701  
3702 0 static void bqws_sha1(uint8_t digest[20], const void *data, size_t size)
3703 {
3704 SHA1_CTX ctx;
3705 0 SHA1Init(&ctx);
3706 0 SHA1Update(&ctx, data, (uint32_t)size);
3707 0 SHA1Final((unsigned char*)digest, &ctx);
3708 0 }
3709  
« blib/lib/Linux/Event/WebSocket/_BQ.pm ↑ Summary WebSocket.xs »