ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
url.c
Go to the documentation of this file.
1
9
11#include <ascii-chat/util/url.h>
12#include <ascii-chat/util/ip.h>
13#include <unicode/uidna.h>
14#ifdef __EMSCRIPTEN__
15#include <unicode/udata.h>
16#include <libplatform/lifecycle.h>
17extern const unsigned char asciichat_icu_idna_data[];
18static lifecycle_t g_icu_idna_data_lc = LIFECYCLE_INIT;
19#endif
20#include <ascii-chat/common.h>
22#include <pcre2.h>
23#include <string.h>
24#include <stdlib.h>
25#include <stdio.h>
26
27static bool diagnostic_url_end(char c) {
28 return !c || (unsigned char)c <= 32 || c == '"' || c == '\'' || c == '<' || c == '>';
29}
30
31void url_redact_diagnostic(char *text, bool truncated) {
32 if (!text)
33 return;
34 char *search = text;
35 while ((search = strstr(search, "://"))) {
36 char *authority = search + 3;
37 char *end = authority;
38 char *at = NULL;
39 while (!diagnostic_url_end(*end) && *end != '/' && *end != '?' && *end != '#') {
40 if (*end == '@')
41 at = end;
42 ++end;
43 }
44 // A truncated authority may end before its '@'; do not export a partial
45 // userinfo value when the caller's diagnostic buffer was cut short.
46 if (at)
47 memset(authority, '*', (size_t)(at - authority));
48 else if (truncated && !*end)
49 memset(authority, '*', (size_t)(end - authority));
50 char *url_end = end;
51 char *query = NULL;
52 while (!diagnostic_url_end(*url_end)) {
53 if (!query && (*url_end == '?' || *url_end == '#'))
54 query = url_end;
55 ++url_end;
56 }
57 if (query)
58 memset(query + 1, '*', (size_t)(url_end - query - 1));
59 search = url_end;
60 }
61}
62
63/* ═══════════════════════════════════════════════════════════════════════════
64 * PRODUCTION-GRADE URL REGEX (Diego Perini, MIT License, extended for WebSocket)
65 *
66 * Supports: http/https/ws/wss, public IPv4, IPv6 with zone IDs, hostnames, localhost
67 * Rejects: Private IPs, schemeless URLs, non-http(s)/ws(s) schemes
68 * ═══════════════════════════════════════════════════════════════════════════ */
69
70static const char *URL_REGEX_PATTERN =
71 // SCHEME: http, https, ws, wss, or tcp (case-insensitive)
72 "^(?<scheme>https?|wss?|tcp)://(?:(?<userinfo>\\S+(?::\\S*)?)@)?"
73 // HOST: one of three alternatives below
74 "(?<host>"
75 "(?:"
76 // IPv4 ADDRESS: e.g. 192.168.1.1
77 // Negative lookaheads reject multicast (224-239) and broadcast (255.255.255.255)
78 "(?!(?:22[4-9]|23\\d)(?:\\.\\d{1,3}){3})(?!255\\.255\\.255\\.255)"
79 // First octet: 0-255
80 "(?:[0-9]\\d?|1\\d\\d|2[01]\\d|22[0-3]|24\\d|25[0-5])"
81 // Second and third octets: 0-255 (repeated twice)
82 "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}"
83 // Fourth octet: 0-255
84 "(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-5]))"
85 ")"
86 // IPv6 ADDRESS: e.g. [::1] or [fe80::1%eth0]
87 // Supports zone IDs (e.g. %25eth0 for link-local addresses)
88 "|(?:\\[(?<ipv6>[a-fA-F0-9:.]+(?:%25[a-zA-Z0-9._~!$&'()*+,;=-]+)?)\\])"
89 // Hostname syntax and DNS lengths are checked by ICU after IDNA mapping.
90 // Exclude ambiguous numeric-only hostnames and invalid IPv4 spellings.
91 "|(?!\\d+(?:\\.\\d+)*(?:[:/"
92 "?#]|$))[a-z0-9_.\\x{00a1}-\\x{10ffff}-]+"
93 ")"
94 // PORT: optional :port (1-5 digits, e.g. :8080, :443)
95 "(?::(?<port>\\d{1,5}))?"
96 // PATH/QUERY/FRAGMENT: optional /path, ?query, or #fragment
97 "(?<path_query_fragment>[/?#]\\S*)?$";
98
99/* ═══════════════════════════════════════════════════════════════════════════
100 * PUBLIC API IMPLEMENTATION
101 * ═══════════════════════════════════════════════════════════════════════════ */
102
103asciichat_error_t hostname_to_ascii(const char *hostname, char *output, size_t capacity) {
104 if (!hostname || !*hostname || !output || capacity == 0)
105 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing hostname or output buffer");
106 size_t length = strlen(hostname);
107 if (length > INT32_MAX)
108 return SET_ERRNO(ERROR_INVALID_PARAM, "Hostname input exceeds ICU length range");
109
110 // IP literals are addresses, not IDNA labels; preserve IPv6 zones and brackets.
111 if (length < HOSTNAME_BUFFER_SIZE && (is_valid_ipv4(hostname) || is_valid_ipv6(hostname))) {
112 if (length >= capacity)
113 return SET_ERRNO(ERROR_INVALID_PARAM, "Address exceeds output capacity");
114 memmove(output, hostname, length + 1);
115 return ASCIICHAT_OK;
116 }
117
118 UErrorCode status = U_ZERO_ERROR;
119#ifdef __EMSCRIPTEN__
120 while (!lifecycle_is_initialized(&g_icu_idna_data_lc)) {
121 if (lifecycle_init_once(&g_icu_idna_data_lc)) {
122 udata_setCommonData(asciichat_icu_idna_data, &status);
123 if (U_FAILURE(status)) {
124 lifecycle_init_abort(&g_icu_idna_data_lc);
125 return SET_ERRNO(ERROR_INIT, "Could not load ICU IDNA data: %s", u_errorName(status));
126 }
127 lifecycle_init_commit(&g_icu_idna_data_lc);
128 }
129 }
130#endif
131 UIDNA *idna = uidna_openUTS46(UIDNA_NONTRANSITIONAL_TO_ASCII | UIDNA_CHECK_BIDI | UIDNA_CHECK_CONTEXTJ | UIDNA_CHECK_CONTEXTO, &status);
132 if (U_FAILURE(status) || !idna)
133 return SET_ERRNO(ERROR_INIT, "Could not initialize ICU IDNA: %s", u_errorName(status));
134 char ascii[HOSTNAME_BUFFER_SIZE];
135 UIDNAInfo info = UIDNA_INFO_INITIALIZER;
136 int32_t written = uidna_nameToASCII_UTF8(idna, hostname, (int32_t)length, ascii, sizeof(ascii), &info, &status);
137 uidna_close(idna);
138 // A trailing root dot is allowed, but does not count towards the DNS name limit.
139 size_t max_length = MAX_HOSTNAME_LENGTH;
140 if (written > 0 && written < (int32_t)sizeof(ascii) && ascii[written - 1] == '.')
141 ++max_length;
142 if (U_FAILURE(status) || info.errors || written <= 0 || (size_t)written > max_length || (size_t)written >= sizeof(ascii) || (size_t)written >= capacity)
143 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IDNA hostname or insufficient capacity (ICU %s, errors 0x%x)", u_errorName(status), (unsigned)info.errors);
144 // Retain underscore hostnames used by local services, but reject other
145 // non-DNS ASCII punctuation permitted by ICU when STD3 rules are disabled.
146 for (int32_t i = 0; i < written; ++i) {
147 char c = ascii[i];
148 if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_'))
149 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ASCII character in IDNA hostname");
150 }
151 memcpy(output, ascii, (size_t)written);
152 output[written] = '\0';
153 return ASCIICHAT_OK;
154}
155
156bool url_is_valid(const char *url) {
157 url_parts_t parts = {0};
158 asciichat_error_t result = url_parse(url, &parts);
159 url_parts_destroy(&parts);
160 return result == ASCIICHAT_OK;
161}
162
163asciichat_error_t url_parse(const char *url, url_parts_t *parts_out) {
164 if (!url || !*url) {
165 return SET_ERRNO(ERROR_INVALID_PARAM, "URL is NULL or empty");
166 }
167
168 if (!parts_out) {
169 return SET_ERRNO(ERROR_INVALID_PARAM, "parts_out is NULL");
170 }
171
172 /* Clear output structure */
173 memset(parts_out, 0, sizeof(*parts_out));
174
175 /* Check if URL needs http:// prefix (bare hostname or IP) */
176 char url_with_scheme[URL_BUFFER_SIZE];
177 const char *url_to_match = url;
178 const char *original_url = url;
179
180 if (!strstr(url, "://")) {
181 /* No scheme - check if it looks like a bare hostname/IP */
182 if (strchr(url, '@'))
183 return SET_ERRNO(ERROR_INVALID_PARAM, "Ambiguous email address without URL scheme");
184
185 /* Reject bare scheme words like "http", "https", "ftp" */
186 if (strcmp(url, "http") == 0 || strcmp(url, "https") == 0 || strcmp(url, "ftp") == 0 || strcmp(url, "ftps") == 0) {
187 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid URL format: %s", url);
188 }
189
190 /* Reject URLs that look like malformed schemes (http/ instead of http://) */
191 if (strncmp(url, "http/", 5) == 0 || strncmp(url, "https/", 6) == 0) {
192 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid URL format (looks like malformed scheme): %s", url);
193 }
194
195 /* Reject pure hex strings (raw keys, not hostnames) */
196 if (strlen(url) == 64) {
197 bool all_hex = true;
198 for (const char *p = url; *p && all_hex; p++) {
199 if (!((*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') || (*p >= 'A' && *p <= 'F'))) {
200 all_hex = false;
201 }
202 }
203 if (all_hex) {
204 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid URL: appears to be raw hex data, not a URL");
205 }
206 }
207
208 const char *colon_pos = strchr(url, ':');
209 if (colon_pos) {
210 /* Has colon - check if what follows is numeric (port) */
211 const char *after_colon = colon_pos + 1;
212 bool looks_like_port = true;
213 for (const char *p = after_colon; *p && *p != '/'; p++) {
214 if (!(*p >= '0' && *p <= '9')) {
215 looks_like_port = false;
216 break;
217 }
218 }
219 if (!looks_like_port) {
220 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid URL format (invalid scheme): %s", url);
221 }
222 }
223
224 /* Looks like a bare hostname/IP - prepend http:// */
225 int result = snprintf(url_with_scheme, sizeof(url_with_scheme), "http://%s", url);
226 if (result < 0 || result >= (int)sizeof(url_with_scheme)) {
227 return SET_ERRNO(ERROR_INVALID_PARAM, "URL too long");
228 }
229 url_to_match = url_with_scheme;
230 }
231
232 int compile_error;
233 PCRE2_SIZE error_offset;
234 pcre2_code *regex = pcre2_compile((PCRE2_SPTR)URL_REGEX_PATTERN, PCRE2_ZERO_TERMINATED, PCRE2_CASELESS | PCRE2_UCP | PCRE2_UTF, &compile_error, &error_offset, NULL);
235 if (!regex) {
236 return SET_ERRNO(ERROR_CONFIG, "URL validator compilation failed at offset %zu (PCRE2 error %d)", (size_t)error_offset, compile_error);
237 }
238
239 pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(regex, NULL);
240 if (!match_data) {
241 pcre2_code_free(regex);
242 return SET_ERRNO(ERROR_MEMORY, "Failed to create match data");
243 }
244
245 /* Match using the interpreted pattern. */
246 int rc = asciichat_pcre2_match(regex, (PCRE2_SPTR)url_to_match, strlen(url_to_match), 0, /* startoffset */
247 0, /* options */
248 match_data, NULL); /* mcontext */
249
250 if (rc < 0) {
251 pcre2_match_data_free(match_data);
252 pcre2_code_free(regex);
253 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid URL format: %s", original_url);
254 }
255
256 /* Extract named groups */
257 parts_out->scheme = asciichat_pcre2_extract_named_group(regex, match_data, "scheme", url_to_match);
258 parts_out->userinfo = asciichat_pcre2_extract_named_group(regex, match_data, "userinfo", url_to_match);
259 parts_out->host = asciichat_pcre2_extract_named_group(regex, match_data, "host", url_to_match);
260 parts_out->ipv6 = asciichat_pcre2_extract_named_group(regex, match_data, "ipv6", url_to_match);
261 parts_out->path = asciichat_pcre2_extract_named_group(regex, match_data, "path_query_fragment", url_to_match);
262
263 /* Extract port number */
264 parts_out->port = 0;
265 char *port_str = asciichat_pcre2_extract_named_group(regex, match_data, "port", url_to_match);
266 if (port_str) {
267 parts_out->port = (int)strtol(port_str, NULL, 10);
268 SAFE_FREE(port_str);
269 if (parts_out->port <= 0 || parts_out->port > UINT16_MAX) {
270 pcre2_match_data_free(match_data);
271 pcre2_code_free(regex);
272 url_parts_destroy(parts_out);
273 return SET_ERRNO(ERROR_INVALID_PARAM, "URL port must be in the range 1-65535");
274 }
275 }
276
277 pcre2_match_data_free(match_data);
278 pcre2_code_free(regex);
279
280 /* Verify we got required fields */
281 if (!parts_out->scheme || !parts_out->host) {
282 url_parts_destroy(parts_out);
283 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing required URL components");
284 }
285
286 if (!parts_out->ipv6) {
287 char ascii[HOSTNAME_BUFFER_SIZE];
288 asciichat_error_t result = hostname_to_ascii(parts_out->host, ascii, sizeof(ascii));
289 if (result != ASCIICHAT_OK) {
290 url_parts_destroy(parts_out);
291 return result;
292 }
293 SAFE_FREE(parts_out->host);
294 SAFE_STRDUP(parts_out->host, ascii);
295 }
296 return ASCIICHAT_OK;
297}
298
300 if (!parts) {
301 SET_ERRNO(ERROR_INVALID_PARAM, "parts is NULL");
302 return;
303 }
304
305 SAFE_FREE(parts->scheme);
306 SAFE_FREE(parts->userinfo);
307 SAFE_FREE(parts->host);
308 SAFE_FREE(parts->ipv6);
309 SAFE_FREE(parts->path);
310 parts->port = 0;
311
312 memset(parts, 0, sizeof(*parts));
313}
314
315bool url_is_websocket_scheme(const char *scheme) {
316 if (!scheme || !*scheme) {
317 SET_ERRNO(ERROR_INVALID_PARAM, "scheme is NULL or empty");
318 return false;
319 }
320
321 /* Case-insensitive comparison for "ws" or "wss" */
322 return (strcasecmp(scheme, "ws") == 0 || strcasecmp(scheme, "wss") == 0);
323}
324
325bool url_is_websocket(const char *url) {
326 if (!url || !*url) {
327 SET_ERRNO(ERROR_INVALID_PARAM, "url is NULL or empty");
328 return false;
329 }
330
331 /* Parse URL to validate and check scheme */
332 url_parts_t parts = {0};
333 asciichat_error_t result = url_parse(url, &parts);
334 bool is_ws = (result == ASCIICHAT_OK && url_is_websocket_scheme(parts.scheme));
335 url_parts_destroy(&parts);
336
337 return is_ws;
338}
339
340bool url_looks_like_websocket(const char *url) {
341 if (!url || !*url) {
342 SET_ERRNO(ERROR_INVALID_PARAM, "url is NULL or empty");
343 return false;
344 }
345
346 /* Quick check for ws:// or wss:// prefix (case-insensitive) */
347 return (strncasecmp(url, "ws://", 5) == 0 || strncasecmp(url, "wss://", 6) == 0);
348}
349
350bool url_is_tcp_scheme(const char *scheme) {
351 if (!scheme || !*scheme) {
352 SET_ERRNO(ERROR_INVALID_PARAM, "scheme is NULL or empty");
353 return false;
354 }
355
356 /* Case-insensitive comparison for "tcp" */
357 return (strcasecmp(scheme, "tcp") == 0);
358}
359
360bool url_is_tcp(const char *url) {
361 if (!url || !*url) {
362 SET_ERRNO(ERROR_INVALID_PARAM, "url is NULL or empty");
363 return false;
364 }
365
366 /* Parse URL to validate and check scheme */
367 url_parts_t parts = {0};
368 asciichat_error_t result = url_parse(url, &parts);
369 bool is_tcp = (result == ASCIICHAT_OK && url_is_tcp_scheme(parts.scheme));
370 url_parts_destroy(&parts);
371
372 return is_tcp;
373}
374
375bool url_looks_like_tcp(const char *url) {
376 if (!url || !*url) {
377 SET_ERRNO(ERROR_INVALID_PARAM, "url is NULL or empty");
378 return false;
379 }
380
381 /* Quick check for tcp:// prefix (case-insensitive) */
382 return (strncasecmp(url, "tcp://", 6) == 0);
383}
#define SET_ERRNO(code,...)
Error and exit codes - unified status values (0-255).
#define SAFE_FREE(ptr)
#define SAFE_STRDUP(dst, src)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INIT
Definition error_codes.h:60
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_INVALID_PARAM
#define URL_BUFFER_SIZE
#define HOSTNAME_BUFFER_SIZE
#define MAX_HOSTNAME_LENGTH
bool url_looks_like_tcp(const char *url)
Quick check if a string is a TCP URL.
Definition url.c:375
void url_parts_destroy(url_parts_t *parts)
Free parsed URL components.
Definition url.c:299
bool url_is_tcp_scheme(const char *scheme)
Check if URL scheme is TCP.
Definition url.c:350
int is_valid_ipv4(const char *ip)
Check if a string is a valid IPv4 address.
Definition ip.c:32
int is_valid_ipv6(const char *ip)
Check if a string is a valid IPv6 address.
Definition ip.c:63
bool url_is_valid(const char *url)
URL validation using shared parsing and ICU hostname checks.
Definition url.c:156
bool url_is_websocket_scheme(const char *scheme)
Check if URL scheme is WebSocket (ws or wss).
Definition url.c:315
bool url_is_websocket(const char *url)
Check if a URL string is a valid WebSocket URL.
Definition url.c:325
asciichat_error_t url_parse(const char *url, url_parts_t *parts_out)
Parse HTTP(S), WebSocket, and TCP URL into components.
Definition url.c:163
bool url_is_tcp(const char *url)
Check if a URL string is a valid TCP URL.
Definition url.c:360
bool url_looks_like_websocket(const char *url)
Quick check if a string is a WebSocket URL.
Definition url.c:340
void url_redact_diagnostic(char *text, bool truncated)
Definition url.c:31
asciichat_error_t hostname_to_ascii(const char *hostname, char *output, size_t capacity)
Definition url.c:103
⚙️ Common definitions, error codes, macros, and types shared throughout the application
🌍 IP Address Parsing and Formatting Utilities
int asciichat_pcre2_match(const pcre2_code *code, PCRE2_SPTR subject, PCRE2_SIZE length, PCRE2_SIZE startoffset, uint32_t options, pcre2_match_data *match_data, pcre2_match_context *context)
Definition pcre2.c:161
char * asciichat_pcre2_extract_named_group(pcre2_code *regex, pcre2_match_data *match_data, const char *group_name, const char *subject)
Extract named substring from PCRE2 match data.
Definition pcre2.c:34
PCRE2 compilation and match helpers.
🔤 String Manipulation and Shell Escaping Utilities
Structure containing parsed URL components.
Definition url.h:69
char * userinfo
Optional userinfo (user:pass) - may be NULL (allocated if present).
Definition url.h:71
char * path
Extracted path, query, and fragment (allocated if present, may be NULL).
Definition url.h:75
char * ipv6
IPv6 address if host is bracketed IPv6 - may be NULL (allocated if present).
Definition url.h:73
char * scheme
Extracted scheme: "http" or "https" (allocated).
Definition url.h:70
char * host
Canonical ASCII hostname or IP address (allocated).
Definition url.h:72
int port
Extracted port number (0 if not specified).
Definition url.h:74
🌐 Production-Grade URL Validation and Parsing