ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
acds_client.c
Go to the documentation of this file.
1
2/* Existing buffer budgets in bytes, including NUL for text storage. */
3#define ACDS_SIGNATURE_PREFIX_SIZE (sizeof(uint8_t) + sizeof(uint64_t))
4#define ACDS_CREATE_SIGNATURE_MESSAGE_SIZE (ACDS_SIGNATURE_PREFIX_SIZE + 2 * sizeof(uint8_t))
5
7#include <ascii-chat/common.h>
21
23#include <ascii-chat/buffer.h>
24#include <ascii-chat/common.h>
27#include <ascii-chat/log/log.h>
31#include <libplatform/socket.h>
35
38#include <string.h>
39#include <time.h>
40#include <errno.h>
41
42// Cryptographic Signature Helpers
43// ============================================================================
44
45asciichat_error_t acds_sign_session_create(const uint8_t identity_seckey[ED25519_PRIVATE_KEY_SIZE], uint64_t timestamp, uint8_t capabilities, uint8_t max_participants,
46 uint8_t signature_out[ED25519_SIGNATURE_SIZE]) {
47 if (!identity_seckey || !signature_out) {
48 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
49 }
50
51 // Build message: type (1 byte) || timestamp (8 bytes) || capabilities (1 byte) || max_participants (1 byte)
54
55 // Convert timestamp to network byte order and pack into message
56 uint64_t timestamp_net = HOST_TO_NET_U64(timestamp);
57 memcpy(&message[1], &timestamp_net, sizeof(timestamp_net));
58
59 message[9] = capabilities;
60 message[10] = max_participants;
61
62 // Sign using Ed25519
63 if (crypto_sign_detached(signature_out, NULL, message, sizeof(message), identity_seckey) != 0) {
64 return SET_ERRNO(ERROR_CRYPTO, "Ed25519 signature generation failed");
65 }
66
67 log_debug("Generated SESSION_CREATE signature (timestamp=%llu, caps=%u, max=%u)", (unsigned long long)timestamp, capabilities, max_participants);
68
69 return ASCIICHAT_OK;
70}
71
72asciichat_error_t acds_verify_session_create(const uint8_t identity_pubkey[ED25519_PUBLIC_KEY_SIZE], uint64_t timestamp, uint8_t capabilities, uint8_t max_participants,
73 const uint8_t signature[ED25519_SIGNATURE_SIZE]) {
74 if (!identity_pubkey || !signature) {
75 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
76 }
77
78 // Build message: type (1 byte) || timestamp (8 bytes) || capabilities (1 byte) || max_participants (1 byte)
81
82 // Convert timestamp to network byte order and pack into message
83 uint64_t timestamp_net = HOST_TO_NET_U64(timestamp);
84 memcpy(&message[1], &timestamp_net, sizeof(timestamp_net));
85
86 message[9] = capabilities;
87 message[10] = max_participants;
88
89 // Verify using Ed25519
90 if (crypto_sign_verify_detached(signature, message, sizeof(message), identity_pubkey) != 0) {
91 log_warn("SESSION_CREATE signature verification failed");
92 return SET_ERRNO(ERROR_CRYPTO_VERIFICATION, "Invalid SESSION_CREATE signature");
93 }
94
95 log_debug("SESSION_CREATE signature verified successfully");
96 return ASCIICHAT_OK;
97}
98
99asciichat_error_t acds_sign_session_join(const uint8_t identity_seckey[ED25519_PRIVATE_KEY_SIZE], uint64_t timestamp, const char *session_string, uint8_t signature_out[ED25519_SIGNATURE_SIZE]) {
100 if (!identity_seckey || !session_string || !signature_out) {
101 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
102 }
103
104 size_t session_len = strlen(session_string);
105 if (session_len > ACIP_MAX_SESSION_STRING_LEN) {
106 return SET_ERRNO(ERROR_INVALID_PARAM, "Session string too long (max 48 chars)");
107 }
108
109 // Build message: type (1 byte) || timestamp (8 bytes) || session_string (variable length)
112
113 // Convert timestamp to network byte order and pack into message
114 uint64_t timestamp_net = HOST_TO_NET_U64(timestamp);
115 memcpy(&message[1], &timestamp_net, sizeof(timestamp_net));
116
117 // Copy session string (copy exactly session_len bytes, no null terminator in signature)
118 memcpy(&message[9], session_string, session_len);
119
120 size_t message_len = ACDS_SIGNATURE_PREFIX_SIZE + session_len;
121
122 // Sign using Ed25519
123 if (crypto_sign_detached(signature_out, NULL, message, message_len, identity_seckey) != 0) {
124 return SET_ERRNO(ERROR_CRYPTO, "Ed25519 signature generation failed");
125 }
126
127 log_debug("Generated SESSION_JOIN signature (timestamp=%llu, session='%s')", (unsigned long long)timestamp, session_string);
128
129 return ASCIICHAT_OK;
130}
131
132asciichat_error_t acds_verify_session_join(const uint8_t identity_pubkey[ED25519_PUBLIC_KEY_SIZE], uint64_t timestamp, const char *session_string, const uint8_t signature[ED25519_SIGNATURE_SIZE]) {
133 if (!identity_pubkey || !session_string || !signature) {
134 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
135 }
136
137 size_t session_len = strlen(session_string);
138 if (session_len > ACIP_MAX_SESSION_STRING_LEN) {
139 return SET_ERRNO(ERROR_INVALID_PARAM, "Session string too long (max 48 chars)");
140 }
141
142 // Build message: type (1 byte) || timestamp (8 bytes) || session_string (variable length)
145
146 // Convert timestamp to network byte order and pack into message
147 uint64_t timestamp_net = HOST_TO_NET_U64(timestamp);
148 memcpy(&message[1], &timestamp_net, sizeof(timestamp_net));
149
150 // Copy session string (copy exactly session_len bytes, no null terminator in signature)
151 memcpy(&message[9], session_string, session_len);
152
153 size_t message_len = ACDS_SIGNATURE_PREFIX_SIZE + session_len;
154
155 // Verify using Ed25519
156 if (crypto_sign_verify_detached(signature, message, message_len, identity_pubkey) != 0) {
157 log_warn("SESSION_JOIN signature verification failed");
158 return SET_ERRNO(ERROR_CRYPTO_VERIFICATION, "Invalid SESSION_JOIN signature");
159 }
160
161 log_debug("SESSION_JOIN signature verified successfully");
162 return ASCIICHAT_OK;
163}
164
165bool acds_validate_timestamp(uint64_t timestamp_ms, uint32_t window_seconds) {
166 uint64_t now_ms = time_ns_to_ms(time_get_realtime_ns());
167 uint64_t window_ms = (uint64_t)window_seconds * 1000;
168
169 if (timestamp_ms > now_ms + 60000) {
170 int64_t skew = (int64_t)timestamp_ms - (int64_t)now_ms;
171 log_warn("Timestamp is in the future: %llu > %llu (skew: %lld ms)", (unsigned long long)timestamp_ms, (unsigned long long)now_ms, (long long)skew);
172 return false;
173 }
174
175 uint64_t min_valid_timestamp = (now_ms >= window_ms) ? (now_ms - window_ms) : 0;
176 if (timestamp_ms < min_valid_timestamp) {
177 int64_t age = (int64_t)now_ms - (int64_t)timestamp_ms;
178 log_warn("Timestamp is too old: %llu < %llu (age: %lld ms, max: %u seconds)", (unsigned long long)timestamp_ms, (unsigned long long)min_valid_timestamp, (long long)age, window_seconds);
179 return false;
180 }
181
182 int64_t age = (int64_t)now_ms - (int64_t)timestamp_ms;
183 log_debug("Timestamp validation passed (age: %lld ms, window: %u seconds)", (long long)age, window_seconds);
184 return true;
185}
187
188static asciichat_error_t protocol_fail(acds_protocol_t *p, asciichat_error_t error, const char *message, bool terminal) {
189 p->state = ACDS_FAILED;
190 p->terminal = terminal;
191 SAFE_STRNCPY(p->error, message, sizeof(p->error));
192 sodium_memzero(p->join.identity_seckey, sizeof(p->join.identity_seckey));
193 sodium_memzero(p->join.password, sizeof(p->join.password));
194 // Password rejection is presented by the joiner's retry dialog.
195 bool previous = false;
196 if (error == ERROR_INVALID_PASSWORD)
197 previous = errno_notifications_suppress(true);
198 asciichat_error_t result = SET_ERRNO(error, "%s", message);
199 if (error == ERROR_INVALID_PASSWORD)
201 return result;
202}
203
205 memset(p, 0, sizeof(*p));
206 p->send = send;
207 p->user_data = user_data;
208}
210 if (p)
211 sodium_memzero(p, sizeof(*p));
212}
213static asciichat_error_t protocol_send(acds_protocol_t *p, packet_type_t type, const void *data, size_t length) {
214 if (!p || !p->send)
215 return SET_ERRNO(ERROR_INVALID_PARAM, "Discovery transport missing");
216 asciichat_error_t result = p->send(p->user_data, type, data, length);
217 if (result != ASCIICHAT_OK)
218 return protocol_fail(p, result, "Discovery send failed", false);
219 return ASCIICHAT_OK;
220}
221static bool valid_name(const char *name) {
222 if (!name || !name[0] || strlen(name) > 47)
223 return false;
224 for (const char *c = name; *c; c++)
225 if (!(*c >= 'a' && *c <= 'z') && !(*c >= '0' && *c <= '9') && *c != '-')
226 return false;
227 return true;
228}
229
231 if (!p || !params)
232 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid discovery create parameters");
233 if (total_keys > MAX_SESSION_KEYS || key_index >= (total_keys ? total_keys : 1) || params->max_participants == 0 || params->max_participants > MAX_SESSION_PARTICIPANTS)
234 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid session key count/index or participant limit");
235 if (params->reserved_string && params->reserved_string[0])
236 return protocol_fail(p, ERROR_NOT_SUPPORTED, "Reserved session names are not supported", true);
237 acip_session_create_t req = {0};
238 memcpy(req.identity_pubkey, params->identity_pubkey, sizeof(req.identity_pubkey));
239 req.timestamp = time_ns_to_ms(time_get_realtime_ns());
240 req.capabilities = params->capabilities;
241 req.max_participants = params->max_participants;
242 req.session_type = params->session_type;
243 req.total_keys = total_keys;
244 req.key_index = key_index;
245 req.has_password = params->has_password;
246 req.expose_ip_publicly = params->acds_expose_ip;
247 SAFE_STRNCPY(req.server_address, params->server_address, sizeof(req.server_address));
248 req.server_port = params->server_port;
249 asciichat_error_t result = acds_sign_session_create(params->identity_seckey, req.timestamp, req.capabilities, req.max_participants, req.signature);
250 if (result != ASCIICHAT_OK)
251 return protocol_fail(p, result, "Could not sign session creation", true);
252 if (params->has_password &&
253 crypto_pwhash_str((char *)req.password_hash, params->password, strnlen(params->password, sizeof(params->password)), crypto_pwhash_OPSLIMIT_INTERACTIVE, crypto_pwhash_MEMLIMIT_INTERACTIVE) != 0)
254 return protocol_fail(p, ERROR_CRYPTO, "Could not hash session password", true);
255 p->state = ACDS_CREATING;
256 size_t endpoint_length = strnlen(params->webtransport_url, sizeof(params->webtransport_url));
257 if (endpoint_length == sizeof(params->webtransport_url) || (endpoint_length && (endpoint_length < 9 || strncmp(params->webtransport_url, "https://", sizeof("https://") - 1)))) {
258 sodium_memzero(&req, sizeof(req));
259 return protocol_fail(p, ERROR_INVALID_PARAM, "Invalid public WebTransport endpoint", true);
260 }
261 if (endpoint_length || params->quic_port) {
262 uint8_t payload[sizeof(req) + 10 + sizeof(params->webtransport_url)];
263 memcpy(payload, &req, sizeof(req));
264 uint8_t *extension = payload + sizeof(req);
265 memcpy(extension, "ACQT", sizeof("ACQT") - 1);
266 extension[4] = 1;
267 extension[5] = 0;
268 extension[6] = (uint8_t)(params->quic_port >> 8);
269 extension[7] = (uint8_t)params->quic_port;
270 extension[8] = (uint8_t)(endpoint_length >> 8);
271 extension[9] = (uint8_t)endpoint_length;
272 memcpy(extension + 10, params->webtransport_url, endpoint_length);
273 result = protocol_send(p, PACKET_TYPE_ACIP_SESSION_CREATE, payload, sizeof(req) + 10 + endpoint_length);
274 sodium_memzero(payload, sizeof(payload));
275 } else {
276 result = protocol_send(p, PACKET_TYPE_ACIP_SESSION_CREATE, &req, sizeof(req));
277 }
278 sodium_memzero(&req, sizeof(req));
279 return result;
280}
282 if (!p)
283 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing discovery protocol");
284 if (!valid_name(name))
285 return protocol_fail(p, ERROR_INVALID_PARAM, "Invalid session name", true);
286 acip_session_lookup_t req = {0};
287 req.session_string_len = (uint8_t)strlen(name);
288 memcpy(req.session_string, name, req.session_string_len);
289 SAFE_STRNCPY(p->name, name, sizeof(p->name));
291 return protocol_send(p, PACKET_TYPE_ACIP_SESSION_LOOKUP, &req, sizeof(req));
292}
294 if (!p || !params)
295 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid discovery join parameters");
296 if (!valid_name(params->session_string))
297 return protocol_fail(p, ERROR_INVALID_PARAM, "Invalid session name", true);
298 acip_session_join_t req = {0};
299 req.session_string_len = (uint8_t)strlen(params->session_string);
300 memcpy(req.session_string, params->session_string, req.session_string_len);
301 memcpy(req.identity_pubkey, params->identity_pubkey, sizeof(req.identity_pubkey));
302 req.timestamp = time_ns_to_ms(time_get_realtime_ns());
303 req.has_password = params->has_password;
304 if (params->has_password)
305 SAFE_STRNCPY(req.password, params->password, sizeof(req.password));
306 asciichat_error_t result = acds_sign_session_join(params->identity_seckey, req.timestamp, params->session_string, req.signature);
307 if (result != ASCIICHAT_OK)
308 return protocol_fail(p, result, "Could not sign session join", true);
309 p->state = ACDS_JOINING;
310 result = protocol_send(p, PACKET_TYPE_ACIP_SESSION_JOIN, &req, sizeof(req));
311 sodium_memzero(&req, sizeof(req));
312 return result;
313}
314asciichat_error_t acds_protocol_enter(acds_protocol_t *p, bool create, const char *name, const char *password) {
315 if (!p || !password)
316 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid discovery parameters");
317 if (strlen(password) > 127)
318 return protocol_fail(p, ERROR_INVALID_PARAM, "Password is too long", true);
319 if (crypto_sign_keypair(p->join.identity_pubkey, p->join.identity_seckey) != 0)
320 return protocol_fail(p, ERROR_CRYPTO, "Could not generate discovery identity", true);
321 p->auto_join = true;
322 p->require_webrtc = true;
323 p->join.has_password = password[0] != 0;
324 SAFE_STRNCPY(p->join.password, password, sizeof(p->join.password));
325 p->join.session_string = p->name;
326 if (!create)
327 return acds_protocol_lookup(p, name);
328 acds_session_create_params_t params = {.capabilities = 3, .max_participants = MAX_SESSION_PARTICIPANTS, .session_type = SESSION_TYPE_WEBRTC, .has_password = p->join.has_password};
329 memcpy(params.identity_pubkey, p->join.identity_pubkey, sizeof(params.identity_pubkey));
330 memcpy(params.identity_seckey, p->join.identity_seckey, sizeof(params.identity_seckey));
331 memcpy(params.password, p->join.password, sizeof(params.password));
332 asciichat_error_t result = acds_protocol_create(p, &params, 0, 0);
333 sodium_memzero(&params, sizeof(params));
334 return result;
335}
336asciichat_error_t acds_protocol_receive(acds_protocol_t *p, packet_type_t type, const void *payload, size_t length) {
337 if (!p || (!payload && length))
338 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid discovery packet");
339 if (p->state == ACDS_FAILED || p->state == ACDS_ENDED)
340 return SET_ERRNO(ERROR_INVALID_STATE, "Discovery session has ended");
341 if (type == PACKET_TYPE_ACIP_ERROR || type == PACKET_TYPE_ERROR_MESSAGE) {
342 asciichat_error_t result = network_error_decode(type, payload, length);
343 return protocol_fail(p, result, asciichat_error_string(result), true);
344 }
345 if (type == PACKET_TYPE_ACIP_SESSION_END) {
346 p->state = ACDS_ENDED;
347 p->terminal = true;
348 SAFE_STRNCPY(p->error, "Session ended", sizeof(p->error));
349 return SET_ERRNO(ERROR_NETWORK, "Session ended");
350 }
352 if (length < sizeof(p->created))
353 return protocol_fail(p, ERROR_NETWORK_PROTOCOL, "Truncated created session", true);
354 memcpy(&p->created, payload, sizeof(p->created));
355 if (!p->created.session_string_len || p->created.session_string_len > 47)
356 return protocol_fail(p, ERROR_NETWORK_PROTOCOL, "Invalid created session name", true);
357 memcpy(p->name, p->created.session_string, p->created.session_string_len);
358 p->name[p->created.session_string_len] = 0;
359 p->state = ACDS_CREATED;
360 if (p->auto_join)
361 return acds_protocol_join(p, &p->join);
362 return ASCIICHAT_OK;
363 }
365 if (length < sizeof(p->info))
366 return protocol_fail(p, ERROR_NETWORK_PROTOCOL, "Truncated session information", true);
367 memcpy(&p->info, payload, sizeof(p->info));
368 p->state = ACDS_FOUND;
369 if (!p->auto_join)
370 return ASCIICHAT_OK;
371 if (!p->info.found)
372 return protocol_fail(p, ERROR_NETWORK, "Session not found", true);
373 if (p->info.require_server_verify || p->info.require_client_verify)
374 return protocol_fail(p, ERROR_NOT_SUPPORTED, "This session requires an authorized identity", true);
375 if (p->info.has_password && !p->join.has_password)
376 return protocol_fail(p, ERROR_CRYPTO_AUTH, "This session requires a password", true);
377 return acds_protocol_join(p, &p->join);
378 }
380 if (length < sizeof(p->joined))
381 return protocol_fail(p, ERROR_NETWORK_PROTOCOL, "Truncated discovery join response", true);
382 memcpy(&p->joined, payload, sizeof(p->joined));
383 p->quic_port = 0;
384 p->webtransport_url[0] = 0;
385 if (length > sizeof(p->joined)) {
386 const uint8_t *extension = (const uint8_t *)payload + sizeof(p->joined);
387 size_t extra = length - sizeof(p->joined);
388 if (extra < 10 || memcmp(extension, "ACQT", sizeof("ACQT") - 1) || extension[4] != 1 || extension[5])
389 return protocol_fail(p, ERROR_NETWORK_PROTOCOL, "Invalid discovery transport extension", true);
390 size_t url_length = ((size_t)extension[8] << 8) | extension[9];
391 if (url_length >= sizeof(p->webtransport_url) || extra != 10 + url_length ||
392 (url_length && (url_length < 9 || memcmp(extension + 10, "https://", sizeof("https://") - 1) || memchr(extension + 10, 0, url_length))))
393 return protocol_fail(p, ERROR_NETWORK_PROTOCOL, "Invalid discovery WebTransport endpoint", true);
394 p->quic_port = (uint16_t)((uint16_t)extension[6] << 8 | extension[7]);
395 memcpy(p->webtransport_url, extension + 10, url_length);
396 p->webtransport_url[url_length] = 0;
397 }
398 p->joined.error_message[sizeof(p->joined.error_message) - 1] = 0;
399 p->joined.server_address[sizeof(p->joined.server_address) - 1] = 0;
400 p->joined.turn_username[sizeof(p->joined.turn_username) - 1] = 0;
401 p->joined.turn_password[sizeof(p->joined.turn_password) - 1] = 0;
402 if (!p->joined.success)
403 return protocol_fail(p, network_error_from_acip(p->joined.error_code), p->joined.error_message[0] ? p->joined.error_message : "Session join rejected", true);
404 if (p->require_webrtc && p->joined.session_type != SESSION_TYPE_WEBRTC && !p->webtransport_url[0])
405 return protocol_fail(p, ERROR_NOT_SUPPORTED, "This session does not offer WebTransport or WebRTC", true);
406 p->state = ACDS_JOINED;
407 sodium_memzero(p->join.identity_seckey, sizeof(p->join.identity_seckey));
408 sodium_memzero(p->join.password, sizeof(p->join.password));
409 return ASCIICHAT_OK;
410 }
411 // Signaling and participant notifications are delivered by the caller's transport adapter.
413 return ASCIICHAT_OK;
414 return protocol_fail(p, ERROR_NETWORK_PROTOCOL, "Unexpected discovery response", true);
415}
417 if (!p)
418 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing discovery protocol");
419 if (p->state != ACDS_JOINED)
420 return ASCIICHAT_OK;
421 acip_session_leave_t req = {0};
422 memcpy(req.session_id, p->joined.session_id, sizeof(req.session_id));
423 memcpy(req.participant_id, p->joined.participant_id, sizeof(req.participant_id));
424 p->state = ACDS_ENDED;
425 return protocol_send(p, PACKET_TYPE_ACIP_SESSION_LEAVE, &req, sizeof(req));
426}
429 protocol_version_packet_init(&version, mode);
430 return packet_send_via_transport(transport, PACKET_TYPE_PROTOCOL_VERSION, &version, sizeof(version), 0);
431}
432asciichat_error_t acds_handshake_receive(crypto_handshake_context_t *ctx, acip_transport_t *transport, packet_type_t type, const void *payload, size_t length) {
433 if (!ctx || !transport || (!payload && length))
434 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid handshake packet");
435 switch (type) {
437 if (ctx->state != CRYPTO_HANDSHAKE_INIT || length != sizeof(crypto_parameters_packet_t))
438 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid discovery crypto parameters");
439 if ((((const crypto_parameters_packet_t *)payload)->selected_cipher != CIPHER_ALGO_NONE) != ctx->crypto_ctx.encrypt_data)
440 return SET_ERRNO(ERROR_CRYPTO, "Discovery server changed requested encryption");
441 return crypto_handshake_set_parameters(ctx, payload);
443 return crypto_handshake_client_key_exchange(ctx, transport, type, payload, length);
445 return crypto_handshake_client_auth_response(ctx, transport, type, payload, length);
449 return crypto_handshake_client_complete(ctx, transport, type, payload, length);
450 default:
451 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Unexpected discovery handshake packet: %u", type);
452 }
453}
454
455asciichat_error_t acds_receive_packet(acip_transport_t *transport, packet_type_t *type, void **payload, size_t *length, void **allocation) {
456 asciichat_error_t result = packet_receive_via_transport(transport, type, payload, length, allocation);
457 if (result != ASCIICHAT_OK || acip_transport_get_type(transport) != ACIP_TRANSPORT_WEBSOCKET || !transport->crypto_ctx || !transport->crypto_ctx->encrypt_data)
458 return result;
459 if (*type != PACKET_TYPE_ENCRYPTED)
460 return SET_ERRNO(ERROR_CRYPTO, "Discovery signaling requires encrypted packets");
461 packet_envelope_t envelope = {.type = *type, .data = *payload, .len = *length, .allocated_buffer = *allocation};
462 result = packet_decrypt_envelope(&envelope, transport->crypto_ctx);
463 *allocation = envelope.allocated_buffer;
464 *type = envelope.type;
465 *payload = envelope.data;
466 *length = envelope.len;
467 if (result == ASCIICHAT_OK) {
468 const packet_header_t *inner = envelope.allocated_buffer;
469 if (NET_TO_HOST_U64(inner->magic) != PACKET_MAGIC || envelope.type == PACKET_TYPE_ENCRYPTED || asciichat_crc32(envelope.data, envelope.len) != NET_TO_HOST_U32(inner->crc32))
470 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid encrypted discovery packet");
471 }
472 return result;
473}
474
475asciichat_error_t acds_transport_metadata_encode(uint16_t port, const char *url, void *output, size_t capacity, size_t *length) {
476 if (!url || !output || !length)
477 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing discovery transport output");
478 *length = 0;
479 size_t size = strnlen(url, (size_t)512);
480 if (size >= 512 || capacity < 10 + size || (size && (size < 9 || strncmp(url, "https://", sizeof("https://") - 1))))
481 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid discovery transport endpoint or capacity");
482 uint8_t *bytes = output;
483 memcpy(bytes, "ACQT", sizeof("ACQT") - 1);
484 bytes[4] = 1;
485 bytes[5] = 0;
486 bytes[6] = (uint8_t)(port >> 8);
487 bytes[7] = (uint8_t)port;
488 bytes[8] = (uint8_t)(size >> 8);
489 bytes[9] = (uint8_t)size;
490 memcpy(bytes + 10, url, size);
491 *length = 10 + size;
492 return ASCIICHAT_OK;
493}
494
495asciichat_error_t acds_transport_metadata_decode(const void *data, size_t length, uint16_t *port, char *url, size_t capacity) {
496 if (!port || !url || !capacity || (!data && length))
497 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing discovery transport input or output");
498 *port = 0;
499 url[0] = 0;
500 if (!length)
501 return ASCIICHAT_OK;
502 const uint8_t *bytes = data;
503 if (length < 10 || memcmp(bytes, "ACQT", sizeof("ACQT") - 1) || bytes[4] != 1 || bytes[5])
504 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid discovery transport extension");
505 size_t size = ((size_t)bytes[8] << 8) | bytes[9];
506 if (size >= 512 || size >= capacity || length != 10 + size || (size && (size < 9 || memcmp(bytes + 10, "https://", sizeof("https://") - 1) || memchr(bytes + 10, 0, size))))
507 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid discovery WebTransport endpoint");
508 *port = (uint16_t)((uint16_t)bytes[6] << 8 | bytes[7]);
509 memcpy(url, bytes + 10, size);
510 url[size] = 0;
511 return ASCIICHAT_OK;
512}
asciichat_error_t acds_transport_metadata_decode(const void *data, size_t length, uint16_t *port, char *url, size_t capacity)
asciichat_error_t acds_protocol_join(acds_protocol_t *p, const acds_session_join_params_t *params)
asciichat_error_t acds_verify_session_create(const uint8_t identity_pubkey[32], uint64_t timestamp, uint8_t capabilities, uint8_t max_participants, const uint8_t signature[64])
Verify SESSION_CREATE signature.
Definition acds_client.c:72
asciichat_error_t acds_transport_metadata_encode(uint16_t port, const char *url, void *output, size_t capacity, size_t *length)
#define ACDS_SIGNATURE_PREFIX_SIZE
Definition acds_client.c:3
void acds_protocol_init(acds_protocol_t *p, acds_protocol_send_fn send, void *user_data)
asciichat_error_t acds_verify_session_join(const uint8_t identity_pubkey[32], uint64_t timestamp, const char *session_string, const uint8_t signature[64])
Verify SESSION_JOIN signature.
void acds_protocol_destroy(acds_protocol_t *p)
asciichat_error_t acds_sign_session_join(const uint8_t identity_seckey[64], uint64_t timestamp, const char *session_string, uint8_t signature_out[64])
Sign a SESSION_JOIN message.
Definition acds_client.c:99
asciichat_error_t acds_protocol_lookup(acds_protocol_t *p, const char *name)
bool acds_validate_timestamp(uint64_t timestamp_ms, uint32_t window_seconds)
Check if timestamp is within acceptable window.
#define ACDS_CREATE_SIGNATURE_MESSAGE_SIZE
Definition acds_client.c:4
asciichat_error_t acds_sign_session_create(const uint8_t identity_seckey[64], uint64_t timestamp, uint8_t capabilities, uint8_t max_participants, uint8_t signature_out[64])
Sign a SESSION_CREATE message.
Definition acds_client.c:45
asciichat_error_t acds_handshake_begin(acip_transport_t *transport, uint8_t mode)
asciichat_error_t acds_handshake_receive(crypto_handshake_context_t *ctx, acip_transport_t *transport, packet_type_t type, const void *payload, size_t length)
asciichat_error_t acds_protocol_create(acds_protocol_t *p, const acds_session_create_params_t *params, uint8_t total_keys, uint8_t key_index)
asciichat_error_t acds_protocol_receive(acds_protocol_t *p, packet_type_t type, const void *payload, size_t length)
asciichat_error_t acds_protocol_enter(acds_protocol_t *p, bool create, const char *name, const char *password)
asciichat_error_t acds_receive_packet(acip_transport_t *transport, packet_type_t *type, void **payload, size_t *length, void **allocation)
asciichat_error_t acds_protocol_leave(acds_protocol_t *p)
ACIP client-side protocol library and ACDS client connection API.
@ ACDS_FAILED
@ ACDS_FOUND
@ ACDS_JOINED
@ ACDS_ENDED
@ ACDS_JOINING
@ ACDS_CREATING
@ ACDS_LOOKING_UP
@ ACDS_CREATED
struct acds_protocol acds_protocol_t
asciichat_error_t(* acds_protocol_send_fn)(void *, packet_type_t, const void *, size_t)
#define ACIP_MAX_SESSION_STRING_LEN
Definition acds_sizes.h:10
bool errno_notifications_suppress(bool suppress)
#define SET_ERRNO(code,...)
Hardware-Accelerated CRC32 Checksum Computation.
asciichat_error_t crypto_handshake_set_parameters(crypto_handshake_context_t *ctx, const crypto_parameters_packet_t *params)
Set crypto parameters from crypto_parameters_packet_t.
Named object registry for debugging — log identifiable resource names.
🔄 Network byte order conversion helpers
#define NET_TO_HOST_U64(val)
Definition endian.h:232
#define HOST_TO_NET_U64(val)
Definition endian.h:217
#define NET_TO_HOST_U32(val)
Definition endian.h:85
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
unsigned long long uint64_t
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_INVALID_PASSWORD
Definition error_codes.h:87
@ ERROR_NETWORK
Definition error_codes.h:76
@ ERROR_CRYPTO_VERIFICATION
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:80
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CRYPTO_AUTH
Definition error_codes.h:99
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
@ ERROR_NOT_SUPPORTED
Definition error_codes.h:73
#define MAX_SESSION_PARTICIPANTS
#define MAX_SESSION_KEYS
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
acip_session_join_t
Definition acds.h:408
acip_session_lookup_t
Definition acds.h:309
acip_session_create_t
Definition acds.h:226
acip_session_leave_t
Definition acds.h:529
@ SESSION_TYPE_WEBRTC
WebRTC P2P mesh with STUN/TURN relay.
Definition acds.h:151
void protocol_version_packet_init(protocol_version_packet_t *version, uint8_t supports_encryption)
Initialize a protocol version packet with the current wire version.
Definition packet.c:37
asciichat_error_t packet_decrypt_envelope(packet_envelope_t *envelope, void *crypto_ctx)
Send a clear console packet.
Definition packet.c:639
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
#define CIPHER_ALGO_NONE
No encryption (plaintext mode).
Definition packet.h:1143
#define PACKET_MAGIC
Packet magic number (alias for MAGIC_PACKET_VALID).
Definition packet.h:284
@ PACKET_TYPE_ACIP_SESSION_INFO
Session info response (Discovery Server -> Client).
Definition packet.h:451
@ PACKET_TYPE_CRYPTO_HANDSHAKE_COMPLETE
Server -> Client: "encryption ready" (UNENCRYPTED).
Definition packet.h:352
@ PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT
Server -> Client: {server_pubkey[32]} (UNENCRYPTED).
Definition packet.h:340
@ PACKET_TYPE_ACIP_ERROR
Generic error response (Discovery Server -> Client).
Definition packet.h:547
@ PACKET_TYPE_CRYPTO_AUTH_FAILED
Server -> Client: "authentication failed" (UNENCRYPTED).
Definition packet.h:348
@ PACKET_TYPE_ENCRYPTED
Encrypted packet (after handshake completion).
Definition packet.h:369
@ PACKET_TYPE_CRYPTO_SERVER_AUTH_RESP
Server -> Client: {HMAC[32]} server proves knowledge (UNENCRYPTED).
Definition packet.h:350
@ PACKET_TYPE_PROTOCOL_VERSION
Protocol version and capabilities negotiation.
Definition packet.h:317
@ PACKET_TYPE_ACIP_SESSION_CREATE
Create new session (Client -> Discovery Server).
Definition packet.h:445
@ PACKET_TYPE_CRYPTO_AUTH_CHALLENGE
Server -> Client: {nonce[32]} (UNENCRYPTED).
Definition packet.h:344
@ PACKET_TYPE_CRYPTO_PARAMETERS
Server -> Client: Chosen algorithms + data sizes (UNENCRYPTED).
Definition packet.h:338
@ PACKET_TYPE_ACIP_SESSION_LOOKUP
Lookup session by string (Client -> Discovery Server).
Definition packet.h:449
@ PACKET_TYPE_ACIP_SESSION_LEAVE
Leave session (Client -> Discovery Server).
Definition packet.h:457
@ PACKET_TYPE_ACIP_SESSION_JOIN
Join existing session (Client -> Discovery Server).
Definition packet.h:453
@ PACKET_TYPE_ACIP_SESSION_CREATED
Session created response (Discovery Server -> Client).
Definition packet.h:447
@ PACKET_TYPE_ERROR_MESSAGE
Error packet with asciichat_error_t code and human-readable message.
Definition packet.h:388
@ PACKET_TYPE_ACIP_SESSION_JOINED
Session joined response (Discovery Server -> Client).
Definition packet.h:455
@ PACKET_TYPE_ACIP_SESSION_END
End session (Host -> Discovery Server).
Definition packet.h:459
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
#define asciichat_crc32(data, len)
Main CRC32 dispatcher macro - use this in application code.
Definition crc32.h:151
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Client-side handshake functions.
@ ACIP_TRANSPORT_WEBSOCKET
WebSocket over TCP.
Network error handling utilities.
asciichat_error_t crypto_handshake_client_complete(crypto_handshake_context_t *ctx, acip_transport_t *transport, packet_type_t packet_type, const uint8_t *payload, size_t payload_len)
Client: Wait for handshake complete confirmation.
asciichat_error_t crypto_handshake_client_key_exchange(crypto_handshake_context_t *ctx, acip_transport_t *transport, packet_type_t packet_type, const uint8_t *payload, size_t payload_len)
Client: Process server's public key and send our public key.
asciichat_error_t crypto_handshake_client_auth_response(crypto_handshake_context_t *ctx, acip_transport_t *transport, packet_type_t packet_type, const uint8_t *payload, size_t payload_len)
Client: Process auth challenge and send response.
asciichat_error_t network_error_decode(packet_type_t type, const void *payload, size_t size)
asciichat_error_t network_error_from_acip(uint8_t code)
📝 Logging API with multiple log levels and terminal output control
Parallel IPv4/IPv6 connection with race-to-connect semantics.
asciichat_error_t packet_receive_via_transport(acip_transport_t *transport, packet_type_t *type, void **payload, size_t *payload_len, void **alloc_buffer)
Receive a packet via transport with header parsing and validation.
Definition send.c:192
asciichat_error_t packet_send_via_transport(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, uint32_t client_id)
Definition send.c:183
ACIP shared/bidirectional packet sending functions.
#define ED25519_SIGNATURE_SIZE
Ed25519 signature size in bytes.
Definition sizes.h:41
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37
#define ED25519_PRIVATE_KEY_SIZE
Ed25519 private key size (seed + public) in bytes.
Definition sizes.h:39
🔤 String Manipulation and Shell Escaping Utilities
acip_session_joined_t joined
acip_session_created_t created
char webtransport_url[512]
acds_session_join_params_t join
acip_session_info_t info
acds_protocol_send_fn send
uint16_t quic_port
acds_protocol_state_t state
char error[256]
Session creation request parameters.
const char * reserved_string
Optional reserved string (NULL = auto-generate).
uint16_t server_port
Server port where clients should connect.
bool acds_expose_ip
Explicitly allow public IP disclosure (–acds-expose-ip opt-in).
uint8_t identity_seckey[64]
Ed25519 secret key (for signing).
uint8_t max_participants
Maximum participants (1-128).
uint8_t identity_pubkey[32]
Ed25519 public key (host identity).
char server_address[64]
connect
bool has_password
Password protection enabled.
uint8_t capabilities
Bit 0: video, Bit 1: audio.
char password[128]
Optional password (if has_password).
uint8_t session_type
acds_session_type_t: 0=DIRECT_TCP (default), 1=WEBRTC
Session join parameters.
uint8_t identity_pubkey[32]
Participant's Ed25519 public key.
bool has_password
Password provided.
char password[128]
Password (if has_password).
const char * session_string
Session to join.
uint8_t identity_seckey[64]
Ed25519 secret key (for signing).
crypto_context_t * crypto_ctx
Optional encryption context.
Cryptographic handshake context structure.
Crypto parameters packet structure (Packet Type 15).
Definition packet.h:1056
Packet envelope containing received packet data.
Definition packet.h:1204
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641
uint64_t magic
Magic number (PACKET_MAGIC = 0xA5C11C4A1 "ASCIICHAT" in hex) for packet validation.
Definition packet.h:643
uint32_t crc32
CRC32 checksum of payload data (0 if length == 0).
Definition packet.h:649
Protocol version negotiation packet structure (Packet Type 1).
Definition packet.h:871
⏱️ High-precision timing utilities using sokol_time.h and uthash