-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibwsv5.c
More file actions
3084 lines (2686 loc) · 117 KB
/
libwsv5.c
File metadata and controls
3084 lines (2686 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* libwsv5.c - OBS WebSocket v5 Protocol Library Implementation
*
* A robust C library for managing OBS connections via the WebSocket v5 protocol.
* Supports multiple concurrent connections, automatic reconnection, and thread-safe
* operations for streaming, recording, scene control, and live production setups.
*
* Author: Aidan A. Bradley
* Maintainer: Aidan A. Bradley
* License: MIT
*/
#define _POSIX_C_SOURCE 200809L
#define _DEFAULT_SOURCE
#ifdef __APPLE__
#define _DARWIN_C_SOURCE
#include <sys/types.h>
#endif
#include "libwsv5.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <poll.h>
#include <limits.h>
/* Third-party dependencies */
#include <libwebsockets.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <cjson/cJSON.h>
/* ============================================================================
* Constants and Macros
* ============================================================================ */
#define OBSWS_VERSION "1.0.0" /* Library version string */
#define OBSWS_PROTOCOL_VERSION 1 /* OBS WebSocket protocol version (v5 uses RPC version 1) */
/* Buffer sizing: 64KB is large enough for most OBS messages. Larger messages
(like scene lists with many scenes) might need bigger buffers, but this is
a reasonable default. We could make it dynamic, but that adds complexity.
The protocol itself doesn't define a max message size, so we have to choose. */
#define OBSWS_DEFAULT_BUFFER_SIZE 65536 /* 64KB buffer for WebSocket messages */
/* Pending requests tracking: We use a linked list to track requests waiting for
responses. 256 is a reasonable limit - you can have up to 256 requests in-flight
at once. In practice, most apps will have way fewer. We chose a limit to prevent
unbounded memory growth if something goes wrong and requests never complete. */
#define OBSWS_MAX_PENDING_REQUESTS 256
/* UUIDs are exactly 36 characters (8-4-4-4-12 hex digits with dashes) plus null terminator.
We use these to match requests with their responses in the asynchronous protocol. */
#define OBSWS_UUID_LENGTH 37
/* OBS WebSocket v5 OpCodes - message type identifiers in the protocol.
The OBS WebSocket v5 protocol uses opcodes to identify message types. The protocol
is based on a request-response model layered on top of WebSocket. Here's the flow:
1. Server sends HELLO (opcode 0) with auth challenge and salt
2. Client sends IDENTIFY (opcode 1) with auth response and client info
3. Server sends IDENTIFIED (opcode 2) if auth succeeded
4. Client can send REQUEST messages (opcode 6)
5. Server responds with REQUEST_RESPONSE (opcode 7)
6. Server sends EVENT messages (opcode 5) for things happening in OBS
Batch operations (opcodes 8-9) let you send multiple requests in one message,
but we don't use them in this library - each request is sent individually.
REIDENTIFY (opcode 3) is used if we lose connection and reconnect.
*/
#define OBSWS_OPCODE_HELLO 0 /* Server: Initial greeting with auth info */
#define OBSWS_OPCODE_IDENTIFY 1 /* Client: Authentication and protocol agreement */
#define OBSWS_OPCODE_IDENTIFIED 2 /* Server: Auth successful, ready for commands */
#define OBSWS_OPCODE_REIDENTIFY 3 /* Client: Re-authenticate after reconnect */
#define OBSWS_OPCODE_EVENT 5 /* Server: Something happened in OBS */
#define OBSWS_OPCODE_REQUEST 6 /* Client: Execute an operation in OBS */
#define OBSWS_OPCODE_REQUEST_RESPONSE 7 /* Server: Result of a client request */
#define OBSWS_OPCODE_REQUEST_BATCH 8 /* Client: Multiple requests at once (unused) */
#define OBSWS_OPCODE_REQUEST_BATCH_RESPONSE 9 /* Server: Responses to batch (unused) */
/* Event subscription flags - bitmask for which OBS event categories we subscribe to.
The OBS WebSocket protocol lets you specify which events you want to receive. This
avoids bandwidth waste - if you don't care about media playback events, don't subscribe.
We subscribe to most categories by default (using a bitmask), but you could modify
this to be more selective if needed.
We chose a bitmask (0x7FF for all) rather than subscribing/unsubscribing individually
because it's more efficient - one subscription message at connect-time instead of
many individual subscribe/unsubscribe messages.
*/
#define OBSWS_EVENT_GENERAL (1 << 0) /* General OBS events (startup, shutdown) */
#define OBSWS_EVENT_CONFIG (1 << 1) /* Configuration change events */
#define OBSWS_EVENT_SCENES (1 << 2) /* Scene-related events (scene switched, etc) */
#define OBSWS_EVENT_INPUTS (1 << 3) /* Input source events (muted, volume changed) */
#define OBSWS_EVENT_TRANSITIONS (1 << 4) /* Transition events (transition started) */
#define OBSWS_EVENT_FILTERS (1 << 5) /* Filter events (filter added, removed) */
#define OBSWS_EVENT_OUTPUTS (1 << 6) /* Output events (recording started, streaming stopped) */
#define OBSWS_EVENT_SCENE_ITEMS (1 << 7) /* Scene item events (source added to scene) */
#define OBSWS_EVENT_MEDIA_INPUTS (1 << 8) /* Media playback events (media finished) */
#define OBSWS_EVENT_VENDORS (1 << 9) /* Vendor-specific extensions */
#define OBSWS_EVENT_UI (1 << 10) /* UI events (Studio Mode toggled) */
#define OBSWS_EVENT_ALL 0x7FF /* Subscribe to all event types */
/* ============================================================================
* Internal Structures
* ============================================================================ */
/* Pending request tracking - manages asynchronous request/response pairs.
The OBS WebSocket protocol is asynchronous - when you send a request, you don't
wait for the response before continuing. Instead, responses come back later with
a request ID matching them to the original request.
This struct tracks one in-flight request. We keep a linked list of these, one for
each request waiting for a response. When a response arrives, we find the matching
pending_request by ID, populate the response field, and set completed=true. The
thread that sent the request is waiting on the condition variable, so it wakes up
and gets the response.
Why use a condition variable instead of polling? Because polling wastes CPU. A
thread waiting on a condition variable goes to sleep until the response arrives,
at which point it's woken up. Much more efficient.
Why use a timestamp? For timeout detection. If a response never arrives (OBS crashed,
network died, etc.), we detect it by checking if the request is older than the timeout.
*/
typedef struct pending_request {
char request_id[OBSWS_UUID_LENGTH]; /* Unique ID matching request to response */
obsws_response_t *response; /* Response data populated when received */
bool completed; /* Flag indicating response received */
pthread_mutex_t mutex; /* Protects the response/completed fields */
pthread_cond_t cond; /* Waiting thread sleeps here until response arrives */
time_t timestamp; /* When request was created - used for timeout detection */
struct pending_request *next; /* Linked list pointer to next pending request */
} pending_request_t;
/* Main connection structure - holds all state for an OBS WebSocket connection.
This is the main opaque type that users interact with. It holds everything needed
to manage one connection to OBS:
- Configuration (where to connect, timeouts, callbacks)
- WebSocket instance (from libwebsockets)
- Threading state (the event thread runs in the background)
- Buffers for sending/receiving messages
- Pending request tracking (for async request/response)
- Statistics (for monitoring)
- Authentication state (challenge/salt for password auth)
Why is it opaque (hidden in the .c file)? So we can change the internal structure
without breaking the API. Callers just use the pointer, they don't know what's inside.
Threading model: Each connection has one background thread (event_thread) that
processes WebSocket events, calls callbacks, etc. The main application thread sends
requests and gets responses. This avoids the app freezing while waiting for responses.
Synchronization: We use many mutexes because different parts of the connection
are accessed from different threads:
- state_mutex protects the connection state (so both threads see consistent state)
- send_mutex protects sending (prevents two threads from sending at the same time)
- requests_mutex protects the pending requests list
- stats_mutex protects the statistics counters
- scene_mutex protects the cached current scene name
The scene cache is an optimization - some operations need to know the current
scene. Instead of querying OBS every time, we cache it and update when we get
SceneChanged events.
*/
struct obsws_connection {
/* === Configuration and Setup === */
obsws_config_t config; /* User-provided config (copied at construction) */
/* === Connection State === */
obsws_state_t state; /* Current state (CONNECTED, CONNECTING, etc) */
pthread_mutex_t state_mutex; /* Protects state from concurrent access */
/* === WebSocket Layer === */
struct lws_context *lws_context; /* libwebsockets context (manages the WebSocket) */
struct lws *wsi; /* WebSocket instance - the actual connection */
/* === Message Buffers ===
We keep persistent buffers instead of allocating for every message because
it's more efficient and avoids memory fragmentation. */
char *recv_buffer; /* Buffer for incoming messages from OBS */
size_t recv_buffer_size; /* Total capacity of receive buffer */
size_t recv_buffer_used; /* How many bytes are currently in the buffer */
char *send_buffer; /* Buffer for outgoing messages to OBS */
size_t send_buffer_size; /* Total capacity of send buffer */
/* === Background Thread ===
The event thread continuously processes WebSocket events. This allows the
connection to receive messages and call callbacks without blocking the app. */
pthread_t event_thread; /* ID of the background thread */
pthread_mutex_t send_mutex; /* Prevents two threads from sending simultaneously */
bool thread_running; /* Is the thread currently running? */
bool should_exit; /* Signal to thread: time to stop */
/* === Async Request/Response Handling ===
When you send a request, it returns immediately with a request ID. When the
response comes back, we find the pending_request by ID and notify the waiter. */
pending_request_t *pending_requests; /* Linked list of in-flight requests */
pthread_mutex_t requests_mutex; /* Protects the linked list */
/* === Performance Monitoring === */
obsws_stats_t stats; /* Message counts, errors, latency, etc */
pthread_mutex_t stats_mutex; /* Protects stats from concurrent access */
/* === Keep-Alive / Health Monitoring ===
We send periodic pings to detect when the connection dies. If we don't get
a pong back within the timeout, we know something is wrong. */
time_t last_ping_sent; /* When we last sent a ping */
time_t last_pong_received; /* When we last got a pong back */
/* === Reconnection ===
If the connection drops and auto_reconnect is enabled, we try to reconnect.
We use exponential backoff - each attempt waits longer, up to a maximum. */
uint32_t reconnect_attempts; /* How many times have we tried reconnecting */
uint32_t current_reconnect_delay; /* How long we're waiting before next attempt */
/* === Authentication State ===
OBS uses a challenge-response authentication scheme. The server sends a
challenge and salt, we compute a response using SHA256, and send it back. */
bool auth_required; /* Does OBS need authentication? */
char *challenge; /* Challenge string from OBS HELLO */
char *salt; /* Salt string from OBS HELLO */
/* === Optimization Cache ===
We cache the current scene to avoid querying OBS unnecessarily. When we get
a SceneChanged event, we update the cache. */
char *current_scene; /* Cached name of active scene */
pthread_mutex_t scene_mutex; /* Protects the cache */
};
/* ============================================================================
* Global State
* ============================================================================ */
/* Global initialization flag - tracks whether obsws_init() has been called.
Why have global state at all? Some underlying libraries (like libwebsockets
and OpenSSL) need one-time initialization. We do that in obsws_init() and
make sure it only happens once, even if called multiple times. This flag
tracks whether we've done it.
We use a mutex to protect the flag because someone might call obsws_init()
from multiple threads simultaneously. The mutex ensures only one thread does
the initialization.
*/
static bool g_library_initialized = false; /* Have we called the init code yet? */
static obsws_log_level_t g_log_level = OBSWS_LOG_INFO; /* Global filtering level */
static obsws_debug_level_t g_debug_level = OBSWS_DEBUG_NONE; /* Global debug verbosity */
static pthread_mutex_t g_init_mutex = PTHREAD_MUTEX_INITIALIZER; /* Thread-safe initialization */
/* ============================================================================
* Advanced Logging System - Global State
* ============================================================================ */
/* Logging configuration context - manages file handles, rotation, colors, timestamps */
typedef struct {
bool enabled; /* Is file logging currently enabled? */
char log_directory[PATH_MAX]; /* Directory where log files are written */
FILE *current_file; /* Current open log file handle */
char current_filename[PATH_MAX]; /* Full path to current log file */
time_t current_file_date; /* Date when current file was created */
time_t last_rotation_check; /* Last time we checked for rotation */
int rotation_hour; /* Hour (0-23) when daily rotation occurs, -1 to disable */
size_t max_file_size; /* Max size in bytes before rotation, 0 to disable */
int color_mode; /* 0=force_off, 1=force_on, 2=auto_detect */
bool use_timestamps; /* Include timestamps in output? */
bool is_tty; /* Is output a TTY? (cached for efficiency) */
pthread_mutex_t mutex; /* Protects all fields above */
} obsws_log_context_t;
static obsws_log_context_t g_log_ctx = {
.enabled = false,
.log_directory = {0},
.current_file = NULL,
.current_filename = {0},
.current_file_date = 0,
.last_rotation_check = 0,
.rotation_hour = 0, /* Default: rotate at midnight */
.max_file_size = 0, /* Default: disabled */
.color_mode = 2, /* Default: auto-detect */
.use_timestamps = true, /* Default: enabled */
.is_tty = false,
.mutex = PTHREAD_MUTEX_INITIALIZER
};
/* ============================================================================
* Logging Implementation
* ============================================================================ */
/* Forward declarations for logging helper functions */
static void obsws_log_rotate_if_needed(void);
static int obsws_log_should_use_colors(void);
static void obsws_log_get_timestamp(char *buf, size_t size);
/**
* Internal function to create log directory with secure permissions.
* Creates directory if it doesn't exist, with mode 0700 (rwx------)
*/
static obsws_error_t obsws_log_create_directory(const char *path) {
if (mkdir(path, 0700) == 0) {
return OBSWS_OK; /* Created successfully */
}
if (errno == EEXIST) {
return OBSWS_OK; /* Already exists */
}
/* Failed to create */
return OBSWS_ERROR_CONNECTION_FAILED;
}
/**
* Generate default log directory path: ~/.config/libwsv5/logs
*/
static void obsws_log_get_default_directory(char *buf, size_t size) {
const char *home = getenv("HOME");
if (!home) {
home = "/tmp"; /* Fallback if HOME not set */
}
snprintf(buf, size, "%s/.config/libwsv5/logs", home);
}
/**
* Get current timestamp in format [YYYY-MM-DD HH:MM:SS.mmm]
*/
static void obsws_log_get_timestamp(char *buf, size_t size) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
struct tm *tm_info = localtime(&ts.tv_sec);
strftime(buf, size - 5, "[%Y-%m-%d %H:%M:%S", tm_info);
/* Add milliseconds */
int ms = ts.tv_nsec / 1000000;
size_t len = strlen(buf);
snprintf(buf + len, size - len, ".%03d]", ms);
}
/**
* Get current date in format YYYY-MM-DD
*/
static void obsws_log_get_date_str(char *buf, size_t size, time_t *date_out) {
time_t now;
time(&now);
*date_out = now;
struct tm *tm_info = localtime(&now);
strftime(buf, size, "%Y-%m-%d", tm_info);
}
/**
* Determine if we should use colors based on mode and TTY status
*/
static int obsws_log_should_use_colors(void) {
if (g_log_ctx.color_mode == 0) {
return 0; /* Force off */
}
if (g_log_ctx.color_mode == 1) {
return 1; /* Force on */
}
/* Auto-detect (mode == 2) */
return g_log_ctx.is_tty;
}
/**
* Open or create a new log file for the current day
*/
static FILE* obsws_log_open_file(void) {
char date_str[11]; /* "YYYY-MM-DD" + null */
time_t file_date;
obsws_log_get_date_str(date_str, sizeof(date_str), &file_date);
/* Build filename: libwsv5_YYYY-MM-DD.log */
snprintf(g_log_ctx.current_filename, sizeof(g_log_ctx.current_filename),
"%s/libwsv5_%s.log", g_log_ctx.log_directory, date_str);
/* Open file in append mode, create if doesn't exist */
FILE *f = fopen(g_log_ctx.current_filename, "a");
if (!f) {
fprintf(stderr, "[OBSWS-ERROR] Failed to open log file: %s (errno: %d)\n",
g_log_ctx.current_filename, errno);
return NULL;
}
/* Set to line-buffered mode for better performance */
setvbuf(f, NULL, _IOLBF, 0);
g_log_ctx.current_file_date = file_date;
return f;
}
/**
* Check if log file needs rotation and rotate if necessary
*/
static void obsws_log_rotate_if_needed(void) {
if (!g_log_ctx.enabled || !g_log_ctx.current_file) {
return;
}
time_t now;
time(&now);
/* Check daily rotation */
int should_rotate = 0;
if (g_log_ctx.rotation_hour >= 0) {
struct tm *now_tm = localtime(&now);
struct tm *file_tm = localtime(&g_log_ctx.current_file_date);
/* Rotate if: different day, OR same day but we crossed rotation hour */
if (now_tm->tm_yday != file_tm->tm_yday) {
should_rotate = 1;
}
}
/* Check size-based rotation */
if (!should_rotate && g_log_ctx.max_file_size > 0) {
struct stat st;
if (fstat(fileno(g_log_ctx.current_file), &st) == 0) {
if ((size_t)st.st_size > g_log_ctx.max_file_size) {
should_rotate = 1;
}
}
}
if (should_rotate) {
fclose(g_log_ctx.current_file);
g_log_ctx.current_file = obsws_log_open_file();
}
}
/**
* Format a log message with timestamp, colors, and connection info
*/
static void obsws_log_format_message(char *output, size_t out_size,
obsws_log_level_t level,
const char *message) {
output[0] = '\0';
int use_colors = obsws_log_should_use_colors();
const char *level_str[] = {"NONE", "ERROR", "WARN", "INFO", "DEBUG"};
const char *color_codes[] = {
"\x1b[0m", /* NONE: reset */
"\x1b[31m", /* ERROR: red */
"\x1b[33m", /* WARNING: yellow */
"\x1b[32m", /* INFO: green */
"\x1b[36m" /* DEBUG: cyan */
};
size_t pos = 0;
/* Add timestamp if enabled */
if (g_log_ctx.use_timestamps) {
char ts[32];
obsws_log_get_timestamp(ts, sizeof(ts));
pos += snprintf(output + pos, out_size - pos, "%s ", ts);
}
/* Add colored level indicator */
if (use_colors) {
pos += snprintf(output + pos, out_size - pos, "%s[%s]\x1b[0m ",
color_codes[level], level_str[level]);
} else {
pos += snprintf(output + pos, out_size - pos, "[%s] ", level_str[level]);
}
/* Add message */
snprintf(output + pos, out_size - pos, "%s", message);
}
/* ============================================================================
* Public Logging Configuration API
* ============================================================================ */
obsws_error_t obsws_enable_log_file(const char *directory) {
pthread_mutex_lock(&g_log_ctx.mutex);
/* Use default directory if none provided */
if (!directory) {
obsws_log_get_default_directory(g_log_ctx.log_directory,
sizeof(g_log_ctx.log_directory));
} else {
strncpy(g_log_ctx.log_directory, directory,
sizeof(g_log_ctx.log_directory) - 1);
g_log_ctx.log_directory[sizeof(g_log_ctx.log_directory) - 1] = '\0';
}
/* Create directory if it doesn't exist */
obsws_error_t err = obsws_log_create_directory(g_log_ctx.log_directory);
if (err != OBSWS_OK) {
pthread_mutex_unlock(&g_log_ctx.mutex);
return err;
}
/* Close existing file if open */
if (g_log_ctx.current_file) {
fclose(g_log_ctx.current_file);
}
/* Open new file */
g_log_ctx.current_file = obsws_log_open_file();
if (!g_log_ctx.current_file) {
pthread_mutex_unlock(&g_log_ctx.mutex);
return OBSWS_ERROR_CONNECTION_FAILED;
}
g_log_ctx.enabled = true;
pthread_mutex_unlock(&g_log_ctx.mutex);
return OBSWS_OK;
}
obsws_error_t obsws_disable_log_file(void) {
pthread_mutex_lock(&g_log_ctx.mutex);
if (g_log_ctx.current_file) {
fflush(g_log_ctx.current_file);
fclose(g_log_ctx.current_file);
g_log_ctx.current_file = NULL;
}
g_log_ctx.enabled = false;
pthread_mutex_unlock(&g_log_ctx.mutex);
return OBSWS_OK;
}
obsws_error_t obsws_set_log_rotation_hour(int hour) {
if (hour < -1 || hour > 23) {
return OBSWS_ERROR_INVALID_PARAM;
}
pthread_mutex_lock(&g_log_ctx.mutex);
g_log_ctx.rotation_hour = hour;
pthread_mutex_unlock(&g_log_ctx.mutex);
return OBSWS_OK;
}
obsws_error_t obsws_set_log_rotation_size(size_t max_size_bytes) {
pthread_mutex_lock(&g_log_ctx.mutex);
g_log_ctx.max_file_size = max_size_bytes;
pthread_mutex_unlock(&g_log_ctx.mutex);
return OBSWS_OK;
}
obsws_error_t obsws_set_log_colors(int mode) {
if (mode < 0 || mode > 2) {
return OBSWS_ERROR_INVALID_PARAM;
}
pthread_mutex_lock(&g_log_ctx.mutex);
g_log_ctx.color_mode = mode;
pthread_mutex_unlock(&g_log_ctx.mutex);
return OBSWS_OK;
}
obsws_error_t obsws_set_log_timestamps(bool enabled) {
pthread_mutex_lock(&g_log_ctx.mutex);
g_log_ctx.use_timestamps = enabled;
pthread_mutex_unlock(&g_log_ctx.mutex);
return OBSWS_OK;
}
const char* obsws_get_log_file_directory(void) {
if (!g_log_ctx.enabled || g_log_ctx.log_directory[0] == '\0') {
return NULL;
}
return g_log_ctx.log_directory;
}
/* ============================================================================
* Logging
* ============================================================================ */
/* Internal logging function - core logging infrastructure.
Design: We filter by log level (higher level = more verbose). If the message
is below the current level, we don't even format it (saves CPU). If there's a
user-provided callback, we use it; otherwise we print to stderr.
Why two parameters (conn and format)? So we can log from both the main thread
(with a connection object) and the global initialization code (without one).
*/
static void obsws_log(obsws_connection_t *conn, obsws_log_level_t level, const char *format, ...) {
/* Early exit if this message is too verbose */
if (level > g_log_level) {
return;
}
/* Format the message using printf-style arguments */
char message[1024];
va_list args;
va_start(args, format);
vsnprintf(message, sizeof(message), format, args);
va_end(args);
/* Route to user callback first (if provided) */
if (conn && conn->config.log_callback) {
conn->config.log_callback(level, message, conn->config.user_data);
}
/* Also handle advanced logging system (file, timestamps, colors, etc.) */
pthread_mutex_lock(&g_log_ctx.mutex);
/* Format message with advanced features */
char formatted[2048];
obsws_log_format_message(formatted, sizeof(formatted), level, message);
/* Write to file if enabled */
if (g_log_ctx.enabled && g_log_ctx.current_file) {
obsws_log_rotate_if_needed();
fprintf(g_log_ctx.current_file, "%s\n", formatted);
fflush(g_log_ctx.current_file);
}
/* Write to console if no user callback (backward compat) */
if (!conn || !conn->config.log_callback) {
fprintf(stderr, "%s\n", formatted);
}
pthread_mutex_unlock(&g_log_ctx.mutex);
}
/* Debug logging - finer control for protocol-level troubleshooting.
Separate from regular logging because debug messages are very verbose and
developers typically only enable them when debugging specific issues. The
debug level goes 0-3, with higher levels including all output from lower levels.
We use a larger buffer (4KB) because debug messages can include JSON payloads.
*/
static void obsws_debug(obsws_connection_t *conn, obsws_debug_level_t min_level, const char *format, ...) {
/* Only output if global debug level is at or above the minimum for this message */
if (g_debug_level < min_level) {
return;
}
/* Format with a larger buffer for JSON and other verbose output */
char message[4096];
va_list args;
va_start(args, format);
vsnprintf(message, sizeof(message), format, args);
va_end(args);
/* Route through the callback as DEBUG-level logs */
if (conn && conn->config.log_callback) {
conn->config.log_callback(OBSWS_LOG_DEBUG, message, conn->config.user_data);
}
/* Also handle advanced logging system for debug messages */
pthread_mutex_lock(&g_log_ctx.mutex);
const char *debug_level_str[] = {"NONE", "LOW", "MED", "HIGH"};
char debug_msg[2048];
snprintf(debug_msg, sizeof(debug_msg), "[DEBUG-%s] %s", debug_level_str[min_level], message);
char formatted[2560];
obsws_log_format_message(formatted, sizeof(formatted), OBSWS_LOG_DEBUG, debug_msg);
/* Write to file if enabled */
if (g_log_ctx.enabled && g_log_ctx.current_file) {
obsws_log_rotate_if_needed();
fprintf(g_log_ctx.current_file, "%s\n", formatted);
fflush(g_log_ctx.current_file);
}
/* Write to console if no user callback (backward compat) */
if (!conn || !conn->config.log_callback) {
fprintf(stderr, "%s\n", formatted);
}
pthread_mutex_unlock(&g_log_ctx.mutex);
}
/* ============================================================================
* Utility Functions
* ============================================================================ */
/* Generate a UUID v4 for request identification.
UUIDs uniquely identify each request, so when a response comes back, we can match
it to the original request. We use UUID v4 (random) because it's simple and the
uniqueness probability is astronomically high.
Note: This implementation uses rand() for simplicity. A production system might
use /dev/urandom for better randomness, but the current approach is fine for
most use cases. The protocol doesn't require cryptographically secure randomness.
Format: 8-4-4-4-12 hex digits with dashes, exactly 36 characters.
Example: 550e8400-e29b-41d4-a716-446655440000
The version bits (0x4) and variant bits (0x8-b) mark this as a v4 UUID.
*/
static void generate_uuid(char *uuid_out) {
unsigned int r1 = rand();
unsigned int r2 = rand();
unsigned int r3 = rand();
unsigned int r4 = rand();
sprintf(uuid_out, "%08x-%04x-%04x-%04x-%04x%08x",
r1, /* 8 hex digits */
r2 & 0xFFFF, /* 4 hex digits */
(r3 & 0x0FFF) | 0x4000, /* 4 hex digits (set version 4) */
(r4 & 0x3FFF) | 0x8000, /* 4 hex digits (set variant bits) */
rand() & 0xFFFF, /* 4 hex digits */
(unsigned int)rand()); /* 8 hex digits */
}
/* Base64 encode binary data using OpenSSL.
Why base64 and not hex? Hex would be twice as large. Base64 is a standard
encoding for binary data in text contexts (like WebSocket JSON messages).
We use OpenSSL's BIO (Basic I/O) interface for encoding because it's robust
and well-tested. The BIO_FLAGS_BASE64_NO_NL flag removes newlines that OpenSSL
normally adds for readability - we don't want those in JSON.
*/
static char* base64_encode(const unsigned char *input, size_t length) {
BIO *bio, *b64;
BUF_MEM *buffer_ptr;
/* Set up OpenSSL base64 encoder: b64 filter pushing to memory buffer */
b64 = BIO_new(BIO_f_base64());
bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
/* Disable newlines in output (OpenSSL adds them by default for readability) */
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
/* Encode the data */
BIO_write(bio, input, length);
BIO_flush(bio);
BIO_get_mem_ptr(bio, &buffer_ptr);
/* Copy result to our own allocated buffer and null-terminate */
char *result = malloc(buffer_ptr->length + 1);
if (!result) {
BIO_free_all(bio);
return NULL;
}
memcpy(result, buffer_ptr->data, buffer_ptr->length);
result[buffer_ptr->length] = '\0';
BIO_free_all(bio);
return result;
}
/* Compute SHA256 hash of a null-terminated string.
SHA256 is a cryptographic hash function. It's deterministic (same input always
produces same output) and has an avalanche property (changing one bit in the
input completely changes the output). This makes it perfect for authentication
protocols.
Why SHA256 instead of SHA1 or MD5? SHA256 is current-best-practice. SHA1 has
known collisions, and MD5 is even more broken. SHA256 is secure for the
foreseeable future.
Why use EVP (Envelope) API instead of raw SHA256 functions? EVP is higher-level
and more flexible - if we ever need to support different hash algorithms, we
just change one line.
*/
static void sha256_hash(const char *input, unsigned char *output) {
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
EVP_DigestInit_ex(ctx, EVP_sha256(), NULL);
EVP_DigestUpdate(ctx, input, strlen(input));
EVP_DigestFinal_ex(ctx, output, NULL);
EVP_MD_CTX_free(ctx);
}
/* Generate OBS WebSocket v5 authentication response using challenge-response protocol.
OBS WebSocket v5 uses a two-step authentication protocol:
1. Server sends challenge + salt
2. Client computes: secret = base64(sha256(password + salt))
3. Client computes: response = base64(sha256(secret + challenge))
4. Client sends response
5. Server verifies by computing the same thing
Why this design? The password never travels over the network. Instead, a hash
derived from the password (the secret) is combined with a fresh challenge each
time, preventing replay attacks. This is similar to HTTP Digest Authentication.
Why not use the password directly? That would be incredibly insecure. The
two-step approach means an eavesdropper who sees the response can't use it
again - the challenge was random and won't repeat.
*/
static char* generate_auth_response(const char *password, const char *salt, const char *challenge) {
unsigned char secret_hash[SHA256_DIGEST_LENGTH];
unsigned char auth_hash[SHA256_DIGEST_LENGTH];
/* Step 1: Compute secret = base64(sha256(password + salt)) */
char *password_salt = malloc(strlen(password) + strlen(salt) + 1);
if (!password_salt) {
return NULL;
}
sprintf(password_salt, "%s%s", password, salt);
sha256_hash(password_salt, secret_hash);
free(password_salt);
char *secret = base64_encode(secret_hash, SHA256_DIGEST_LENGTH);
if (!secret) {
return NULL;
}
/* Step 2: Compute auth response = base64(sha256(secret + challenge)) */
char *secret_challenge = malloc(strlen(secret) + strlen(challenge) + 1);
if (!secret_challenge) {
free(secret);
return NULL;
}
sprintf(secret_challenge, "%s%s", secret, challenge);
sha256_hash(secret_challenge, auth_hash);
free(secret_challenge);
free(secret);
/* Return the final response, base64-encoded */
char *auth_response = base64_encode(auth_hash, SHA256_DIGEST_LENGTH);
return auth_response;
}
/* ============================================================================
* State Management
* ============================================================================ */
/* Update connection state and notify callback if state changed.
This function is responsible for state transitions and notifying the user.
We lock the mutex, make the change, unlock it, then call the callback without
holding the lock. Why release the lock before calling the callback? Because
the callback might take a long time, and we don't want to hold a lock during
that time - it would prevent other threads from checking the state.
We only call the callback if the state actually changed. This prevents spurious
notifications if something tries to set the same state again.
*/
static void set_connection_state(obsws_connection_t *conn, obsws_state_t new_state) {
/* Acquire lock, save old state, set new state, release lock */
pthread_mutex_lock(&conn->state_mutex);
obsws_state_t old_state = conn->state;
conn->state = new_state;
pthread_mutex_unlock(&conn->state_mutex);
/* Call callback only if state actually changed (not a duplicate) */
if (old_state != new_state && conn->config.state_callback) {
conn->config.state_callback(conn, old_state, new_state, conn->config.user_data);
}
/* Log the transition for debugging/monitoring */
obsws_log(conn, OBSWS_LOG_INFO, "State changed: %s -> %s",
obsws_state_string(old_state), obsws_state_string(new_state));
}
/* ============================================================================
* Request Management
* ============================================================================ */
/* Create a new pending request and add it to the tracking list.
When we send a request to OBS, we need to track it so we can match the response
when it arrives. This function creates a pending_request_t struct and adds it
to the linked list. The request is initialized with the ID, a condition variable
for waiting, and a current timestamp for timeout detection.
*/
static pending_request_t* create_pending_request(obsws_connection_t *conn, const char *request_id) {
pending_request_t *req = calloc(1, sizeof(pending_request_t));
if (!req) return NULL;
/* Copy request ID and ensure null termination */
strncpy(req->request_id, request_id, OBSWS_UUID_LENGTH - 1);
req->request_id[OBSWS_UUID_LENGTH - 1] = '\0';
/* Initialize request structure */
req->response = calloc(1, sizeof(obsws_response_t));
if (!req->response) {
free(req);
return NULL;
}
req->completed = false;
req->timestamp = time(NULL);
pthread_mutex_init(&req->mutex, NULL);
pthread_cond_init(&req->cond, NULL);
/* Add to linked list of pending requests */
pthread_mutex_lock(&conn->requests_mutex);
req->next = conn->pending_requests;
conn->pending_requests = req;
pthread_mutex_unlock(&conn->requests_mutex);
return req;
}
/* Find a pending request by its UUID */
static pending_request_t* find_pending_request(obsws_connection_t *conn, const char *request_id) {
pthread_mutex_lock(&conn->requests_mutex);
pending_request_t *req = conn->pending_requests;
/* Search linked list for matching request ID */
while (req) {
if (strcmp(req->request_id, request_id) == 0) {
pthread_mutex_unlock(&conn->requests_mutex);
return req;
}
req = req->next;
}
pthread_mutex_unlock(&conn->requests_mutex);
return NULL;
}
/* Remove a pending request from the tracking list and free it */
static void remove_pending_request(obsws_connection_t *conn, pending_request_t *target) {
pthread_mutex_lock(&conn->requests_mutex);
pending_request_t **req = &conn->pending_requests;
/* Find and remove from linked list */
while (*req) {
if (*req == target) {
*req = target->next;
pthread_mutex_unlock(&conn->requests_mutex);
/* Clean up request resources */
pthread_mutex_destroy(&target->mutex);
pthread_cond_destroy(&target->cond);
free(target);
return;
}
req = &(*req)->next;
}
pthread_mutex_unlock(&conn->requests_mutex);
}
/* Clean up requests that have exceeded the timeout period */
static void cleanup_old_requests(obsws_connection_t *conn) {
time_t now = time(NULL);
pthread_mutex_lock(&conn->requests_mutex);
pending_request_t **req = &conn->pending_requests;
while (*req) {
/* Check if request has timed out (30 seconds) */
if (now - (*req)->timestamp > 30) {
pending_request_t *old = *req;
*req = old->next;
/* Mark as completed with timeout error */
pthread_mutex_lock(&old->mutex);
old->completed = true;
old->response->success = false;
old->response->error_message = strdup("Request timeout");
pthread_cond_broadcast(&old->cond); /* Wake waiting threads */
pthread_mutex_unlock(&old->mutex);
} else {
req = &(*req)->next;
}
}
pthread_mutex_unlock(&conn->requests_mutex);
}