ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
rate_limit.c
Go to the documentation of this file.
1#include <ascii-chat/otel.h>
7
11#include <ascii-chat/log/log.h>
13#include <stdlib.h>
14#include <string.h>
15#include <time.h>
16
17// Event type strings for logging
18static const char *event_type_strings[RATE_EVENT_MAX] = {
19 [RATE_EVENT_SESSION_CREATE] = "session_create",
20 [RATE_EVENT_SESSION_LOOKUP] = "session_lookup",
21 [RATE_EVENT_SESSION_JOIN] = "session_join",
22 [RATE_EVENT_CONNECTION] = "connection",
23 [RATE_EVENT_IMAGE_FRAME] = "image_frame",
24 [RATE_EVENT_AUDIO] = "audio",
25 [RATE_EVENT_PING] = "ping",
26 [RATE_EVENT_CLIENT_JOIN] = "client_join",
27 [RATE_EVENT_CONTROL] = "control",
28 [RATE_EVENT_HTTP_REQUEST] = "http_request",
29};
30
31// Default rate limits: conservative defaults to prevent abuse
32// Debug builds have relaxed limits for development/testing
34// ACDS discovery server limits
35#ifdef NDEBUG
36 // Release mode: production limits (144 FPS video, 172 FPS audio)
37 [RATE_EVENT_SESSION_CREATE] = {.max_events = 10, .window_secs = 60}, // 10 creates per minute
38 [RATE_EVENT_SESSION_LOOKUP] = {.max_events = 30, .window_secs = 60}, // 30 lookups per minute
39 [RATE_EVENT_SESSION_JOIN] = {.max_events = 20, .window_secs = 60}, // 20 joins per minute
40 [RATE_EVENT_CONNECTION] = {.max_events = 50, .window_secs = 60}, // 50 connections per minute
41 [RATE_EVENT_IMAGE_FRAME] = {.max_events = 8640, .window_secs = 60}, // 8640 frames/min = 144 FPS
42 [RATE_EVENT_AUDIO] = {.max_events = 10320, .window_secs = 60}, // 10320 packets/min = 172 FPS
43 [RATE_EVENT_PING] = {.max_events = 120, .window_secs = 60}, // 120 pings/min = 2 Hz max
44 [RATE_EVENT_CLIENT_JOIN] = {.max_events = 10, .window_secs = 60}, // 10 joins per minute
45 [RATE_EVENT_CONTROL] = {.max_events = 100, .window_secs = 60}, // 100 control packets/min
46 [RATE_EVENT_HTTP_REQUEST] = {.max_events = 120, .window_secs = 60}, // 120 HTTP requests/minute
47#else
48 // Debug mode: slightly relaxed limits for development/testing (1.5x production limits)
49 [RATE_EVENT_SESSION_CREATE] = {.max_events = 15, .window_secs = 60}, // 15 creates per minute
50 [RATE_EVENT_SESSION_LOOKUP] = {.max_events = 45, .window_secs = 60}, // 45 lookups per minute
51 [RATE_EVENT_SESSION_JOIN] = {.max_events = 30, .window_secs = 60}, // 30 joins per minute
52 [RATE_EVENT_CONNECTION] = {.max_events = 75, .window_secs = 60}, // 75 connections per minute
53 [RATE_EVENT_IMAGE_FRAME] = {.max_events = 12960, .window_secs = 60}, // 12960 frames/min = 216 FPS
54 [RATE_EVENT_AUDIO] = {.max_events = 15480, .window_secs = 60}, // 15480 packets/min = 258 FPS
55 [RATE_EVENT_PING] = {.max_events = 180, .window_secs = 60}, // 180 pings/min = 3 Hz
56 [RATE_EVENT_CLIENT_JOIN] = {.max_events = 25, .window_secs = 60}, // 25 joins per minute (for testing reconnects)
57 [RATE_EVENT_CONTROL] = {.max_events = 150, .window_secs = 60}, // 150 control packets/min
58 [RATE_EVENT_HTTP_REQUEST] = {.max_events = 120, .window_secs = 60}, // 120 HTTP requests/minute
59#endif
60};
61
62// ============================================================================
63// Backend Interface
64// ============================================================================
65
78
79// ============================================================================
80// Public API Implementation
81// ============================================================================
82
84 rate_limiter_t *limiter = malloc(sizeof(rate_limiter_t));
85 if (!limiter) {
86 log_error("Failed to allocate rate limiter");
87 return NULL;
88 }
89
91 if (!limiter->backend_data) {
92 free(limiter);
93 return NULL;
94 }
95
96 limiter->ops = &memory_backend_ops;
97 return limiter;
98}
99
101 rate_limiter_t *limiter = malloc(sizeof(rate_limiter_t));
102 if (!limiter) {
103 log_error("Failed to allocate rate limiter");
104 return NULL;
105 }
106
107 limiter->backend_data = sqlite_backend_create(db_path);
108 if (!limiter->backend_data) {
109 free(limiter);
110 return NULL;
111 }
112
113 limiter->ops = &sqlite_backend_ops;
114 return limiter;
115}
116
118 if (!limiter || !limiter->backend_data) {
119 return;
120 }
121
122 // Call the SQLite backend function to set the database handle
123 sqlite_backend_set_db(limiter->backend_data, (sqlite3 *)db);
124}
125
127 if (!limiter) {
128 return;
129 }
130
131 if (limiter->ops && limiter->ops->destroy) {
132 limiter->ops->destroy(limiter->backend_data);
133 }
134
135 free(limiter);
136}
137
138asciichat_error_t rate_limiter_check(rate_limiter_t *limiter, const char *ip_address, rate_event_type_t event_type, const rate_limit_config_t *config, bool *allowed) {
139 ASCII_OTEL_SCOPE(RATE_LIMITER_CHECK);
140 if (!limiter || !limiter->ops || !limiter->ops->check) {
141 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid rate limiter");
142 }
143
144 if (!ip_address || !allowed) {
145 return SET_ERRNO(ERROR_INVALID_PARAM, "ip_address or allowed is NULL");
146 }
147
148 if (event_type >= RATE_EVENT_MAX) {
149 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid event_type: %d", event_type);
150 }
151
152 ASCII_OTEL_ATTR_STRING("rate_limit.event", rate_limiter_event_type_string(event_type));
153 asciichat_error_t result = limiter->ops->check(limiter->backend_data, ip_address, event_type, config, allowed);
154 if (result == ASCIICHAT_OK)
155 ASCII_OTEL_ATTR_INT("rate_limit.allowed", *allowed);
156 if (result == ASCIICHAT_OK && !*allowed)
158 return result;
159}
160
161asciichat_error_t rate_limiter_record(rate_limiter_t *limiter, const char *ip_address, rate_event_type_t event_type) {
162 if (!limiter || !limiter->ops || !limiter->ops->record) {
163 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid rate limiter");
164 }
165
166 if (!ip_address) {
167 return SET_ERRNO(ERROR_INVALID_PARAM, "ip_address is NULL");
168 }
169
170 if (event_type >= RATE_EVENT_MAX) {
171 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid event_type: %d", event_type);
172 }
173
174 return limiter->ops->record(limiter->backend_data, ip_address, event_type);
175}
176
178 ASCII_OTEL_SCOPE(RATE_LIMITER_PRUNE);
179 if (!limiter || !limiter->ops || !limiter->ops->cleanup) {
180 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid rate limiter");
181 }
182
183 return limiter->ops->cleanup(limiter->backend_data, max_age_secs);
184}
185
186// ============================================================================
187// Helper Functions (available to backends)
188// ============================================================================
189
194 if (event_type >= RATE_EVENT_MAX) {
195 return "unknown";
196 }
197 return event_type_strings[event_type];
198}
#define SET_ERRNO(code,...)
unsigned int uint32_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
@ STATS_COUNTER_RATE_LIMIT_REJECTIONS
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
📝 Logging API with multiple log levels and terminal output control
void * memory_backend_create(void)
Create memory backend instance.
Definition memory.c:254
const rate_limiter_backend_ops_t memory_backend_ops
Memory backend operations vtable.
Definition memory.c:274
🧠 In-memory rate limiting backend interface
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:77
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:72
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:71
asciichat_error_t rate_limiter_record(rate_limiter_t *limiter, const char *ip_address, rate_event_type_t event_type)
Record a rate limit event.
Definition rate_limit.c:161
void rate_limiter_destroy(rate_limiter_t *limiter)
Destroy rate limiter and free resources.
Definition rate_limit.c:126
void rate_limiter_set_sqlite_db(rate_limiter_t *limiter, void *db)
Set SQLite database handle for rate limiter.
Definition rate_limit.c:117
rate_limiter_t * rate_limiter_create_memory(void)
Create in-memory rate limiter.
Definition rate_limit.c:83
const char * rate_limiter_event_type_string(rate_event_type_t event_type)
Get event type string for logging.
Definition rate_limit.c:193
rate_limiter_t * rate_limiter_create_sqlite(const char *db_path)
Create SQLite-backed rate limiter.
Definition rate_limit.c:100
asciichat_error_t rate_limiter_check(rate_limiter_t *limiter, const char *ip_address, rate_event_type_t event_type, const rate_limit_config_t *config, bool *allowed)
Check if an event from an IP address should be rate limited.
Definition rate_limit.c:138
const rate_limit_config_t DEFAULT_RATE_LIMITS[RATE_EVENT_MAX]
Default rate limits for each event type.
Definition rate_limit.c:33
asciichat_error_t rate_limiter_prune(rate_limiter_t *limiter, uint32_t max_age_secs)
Clean up old rate limit events.
Definition rate_limit.c:177
🚦 Rate limiting API with pluggable backends
rate_event_type_t
One sliding-window rate-limit policy.
Definition rate_limit.h:52
@ RATE_EVENT_SESSION_LOOKUP
Session lookup.
Definition rate_limit.h:55
@ RATE_EVENT_CONTROL
Control packets (CAPABILITIES, STREAM_START/STOP, LEAVE).
Definition rate_limit.h:64
@ RATE_EVENT_SESSION_JOIN
Session join.
Definition rate_limit.h:56
@ RATE_EVENT_CONNECTION
New connection.
Definition rate_limit.h:59
@ RATE_EVENT_PING
Ping/pong keepalive (PACKET_TYPE_PING, PACKET_TYPE_PONG).
Definition rate_limit.h:62
@ RATE_EVENT_SESSION_CREATE
Session creation.
Definition rate_limit.h:54
@ RATE_EVENT_AUDIO
Audio packet (PACKET_TYPE_AUDIO, PACKET_TYPE_AUDIO_BATCH).
Definition rate_limit.h:61
@ RATE_EVENT_MAX
Sentinel value.
Definition rate_limit.h:67
@ RATE_EVENT_IMAGE_FRAME
Image frame from client (PACKET_TYPE_IMAGE_FRAME).
Definition rate_limit.h:60
@ RATE_EVENT_CLIENT_JOIN
Client join request (PACKET_TYPE_CLIENT_JOIN).
Definition rate_limit.h:63
@ RATE_EVENT_HTTP_REQUEST
HTTP requests from a client identity.
Definition rate_limit.h:65
struct rate_limiter_s rate_limiter_t
Opaque rate limiter handle.
Definition rate_limit.h:87
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:78
void sqlite_backend_set_db(void *backend_data, sqlite3 *db)
Set SQLite database handle for backend.
Definition sqlite.c:178
void * sqlite_backend_create(const char *db_path)
Create SQLite backend instance.
Definition sqlite.c:156
const rate_limiter_backend_ops_t sqlite_backend_ops
SQLite backend operations vtable.
Definition sqlite.c:185
💾 SQLite rate limiting backend interface
🔤 String Manipulation and Shell Escaping Utilities
One sliding-window rate-limit policy.
Definition rate_limit.h:77
Backend callbacks implementing rate-limit checks, recording, cleanup, and destruction.
Definition rate_limit.h:96
void(* destroy)(void *backend_data)
Definition rate_limit.h:103
asciichat_error_t(* cleanup)(void *backend_data, uint32_t max_age_secs)
Definition rate_limit.h:101
asciichat_error_t(* record)(void *backend_data, const char *ip_address, rate_event_type_t event_type)
Definition rate_limit.h:99
asciichat_error_t(* check)(void *backend_data, const char *ip_address, rate_event_type_t event_type, const rate_limit_config_t *config, bool *allowed)
Definition rate_limit.h:97
Private dispatch object joining a rate-limit backend to its operations table.
Definition rate_limit.c:74
void * backend_data
Backend-specific data.
Definition rate_limit.c:76
const rate_limiter_backend_ops_t * ops
Backend operations.
Definition rate_limit.c:75
⏱️ High-precision timing utilities using sokol_time.h and uthash