Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 /*
18 * This is mostly copied from gmid' iri.c, with minor changes. Bugs
19 * fixed here should be ported to gmid and vice-versa.
20 */
22 #include <config.h>
23 #include <url.h>
25 #include <ctype.h>
26 #include <stdint.h>
27 #include <stdio.h>
28 #include <string.h>
30 struct shallow_url {
31 char *scheme;
32 char *host;
33 char *port;
34 uint16_t port_no;
35 char *path;
36 char *query;
37 char *fragment;
38 };
40 struct parser {
41 char buf[GEMINI_URL_LEN+1];
42 char *iri;
43 struct shallow_url *parsed;
44 const char *err;
45 };
47 static inline int
48 unreserved(int p)
49 {
50 return isalnum(p)
51 || p == '-'
52 || p == '.'
53 || p == '_'
54 || p == '~';
55 }
57 static inline int
58 sub_delimiters(int p)
59 {
60 return p == '!'
61 || p == '$'
62 || p == '&'
63 || p == '\''
64 || p == '('
65 || p == ')'
66 || p == '*'
67 || p == '+'
68 || p == ','
69 || p == ';'
70 || p == '=';
71 }
73 static int
74 valid_pct_enc_string(char *s)
75 {
76 if (*s != '%')
77 return 1;
79 if (!isxdigit(s[1]) || !isxdigit(s[2]))
80 return 0;
82 if (s[1] == '0' && s[2] == '0')
83 return 0;
85 return 1;
86 }
88 static int
89 valid_pct_encoded(struct parser *p)
90 {
91 if (p->iri[0] != '%')
92 return 0;
94 if (!valid_pct_enc_string(p->iri)) {
95 p->err = "illegal percent-encoding";
96 return 0;
97 }
99 p->iri += 2;
100 return 1;
103 static void
104 pct_decode(char *s)
106 sscanf(s+1, "%2hhx", s);
107 memmove(s+1, s+3, strlen(s+3)+1);
110 static int
111 parse_pct_encoded(struct parser *p)
113 if (p->iri[0] != '%')
114 return 0;
116 if (!valid_pct_enc_string(p->iri)) {
117 p->err = "illegal percent-encoding";
118 return 0;
121 pct_decode(p->iri);
122 if (*p->iri == '\0') {
123 p->err = "illegal percent-encoding";
124 return 0;
127 return 1;
130 /*
131 * ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) "://"
132 * or
133 * "//"
134 */
135 static int
136 parse_scheme(struct parser *p)
138 p->parsed->scheme = p->iri;
140 if (p->iri[0] == '/' && p->iri[1] == '/') {
141 *p->iri = '\0';
142 p->iri += 2;
143 return 1;
146 if (!isalpha(*p->iri)) {
147 p->err = "illegal character in scheme";
148 return 0;
151 do {
152 /* normalize the scheme (i.e. lowercase it)
154 * XXX: since we cannot have good things, tolower
155 * behaviour depends on the LC_CTYPE locale. The good
156 * news is that we're sure p->iri points to something
157 * that's in the ASCII range, so tolower can't
158 * mis-behave on some systems due to the locale. */
159 *p->iri = tolower(*p->iri);
160 p->iri++;
161 } while (isalnum(*p->iri)
162 || *p->iri == '+'
163 || *p->iri == '-'
164 || *p->iri == '.');
166 if (*p->iri != ':') {
167 p->err = "illegal character in scheme";
168 return 0;
171 *p->iri = '\0';
172 if (p->iri[1] != '/' || p->iri[2] != '/') {
173 p->err = "invalid marker after scheme";
174 return 0;
177 p->iri += 3;
178 return 1;
181 /* *DIGIT */
182 static int
183 parse_port(struct parser *p)
185 uint32_t i = 0;
187 p->parsed->port = p->iri;
189 for (; isdigit(*p->iri); p->iri++) {
190 i = i * 10 + *p->iri - '0';
191 if (i > UINT16_MAX) {
192 p->err = "port number too large";
193 return 0;
197 if (*p->iri != '/' && *p->iri != '\0') {
198 p->err = "illegal character in port number";
199 return 0;
202 p->parsed->port_no = i;
204 if (*p->iri != '\0') {
205 *p->iri = '\0';
206 p->iri++;
209 return 1;
212 /* TODO: add support for ip-literal and ipv4addr ? */
213 /* *( unreserved / sub-delims / pct-encoded ) */
214 static int
215 parse_authority(struct parser *p)
217 p->parsed->host = p->iri;
219 while (unreserved(*p->iri)
220 || sub_delimiters(*p->iri)
221 || parse_pct_encoded(p)) {
222 /* normalize the host name. */
223 if (*p->iri < 0x7F)
224 *p->iri = tolower(*p->iri);
225 p->iri++;
228 if (p->err != NULL)
229 return 0;
231 if (*p->iri == ':') {
232 *p->iri = '\0';
233 p->iri++;
234 return parse_port(p);
235 } else
236 p->parsed->port_no = 1965;
238 if (*p->iri == '/') {
239 *p->iri = '\0';
240 p->iri++;
241 return 1;
244 if (*p->iri == '\0')
245 return 1;
247 p->err = "illegal character in authority section";
248 return 0;
251 /* Routine for path_clean. Elide the pointed .. with the preceding
252 * element. Return 0 if it's not possible. incr is the length of
253 * the increment, 3 for ../ and 2 for .. */
254 static int
255 path_elide_dotdot(char *path, char *i, int incr)
257 char *j;
259 if (i == path)
260 return 0;
261 for (j = i-2; j != path && *j != '/'; j--)
262 /* noop */ ;
263 if (*j == '/')
264 j++;
265 i += incr;
266 memmove(j, i, strlen(i)+1);
267 return 1;
270 /*
271 * Use an algorithm similar to the one implemented in go' path.Clean:
273 * 1. Replace multiple slashes with a single slash
274 * 2. Eliminate each . path name element
275 * 3. Eliminate each inner .. along with the non-.. element that precedes it
276 * 4. Eliminate trailing .. if possible or error (go would only discard)
278 * Unlike path.Clean, this function return the empty string if the
279 * original path is equivalent to "/".
280 */
281 static int
282 path_clean(char *path)
284 char *i;
286 /* 1. replace multiple slashes with a single one */
287 for (i = path; *i; ++i) {
288 if (*i == '/' && *(i+1) == '/') {
289 memmove(i, i+1, strlen(i)); /* move also the \0 */
290 i--;
294 /* 2. eliminate each . path name element */
295 for (i = path; *i; ++i) {
296 if ((i == path || *i == '/') &&
297 *i != '.' && i[1] == '.' && i[2] == '/') {
298 /* move also the \0 */
299 memmove(i, i+2, strlen(i)-1);
300 i--;
303 if (!strcmp(path, ".") || !strcmp(path, "/.")) {
304 *path = '\0';
305 return 1;
308 /* 3. eliminate each inner .. along with the preceding non-.. */
309 for (i = strstr(path, "../"); i != NULL; i = strstr(path, ".."))
310 if (!path_elide_dotdot(path, i, 3))
311 return 0;
313 /* 4. eliminate trailing ..*/
314 if ((i = strstr(path, "..")) != NULL)
315 if (!path_elide_dotdot(path, i, 2))
316 return 0;
318 return 1;
321 static int
322 parse_query(struct parser *p)
324 p->parsed->query = p->iri;
325 if (*p->iri == '\0')
326 return 1;
328 while (unreserved(*p->iri)
329 || sub_delimiters(*p->iri)
330 || *p->iri == '/'
331 || *p->iri == '?'
332 || *p->iri == ':'
333 || *p->iri == '@'
334 || valid_pct_encoded(p))
335 p->iri++;
337 if (p->err != NULL)
338 return 0;
340 if (*p->iri != '\0' && *p->iri != '#') {
341 p->err = "illegal character in query";
342 return 0;
345 if (*p->iri != '\0') {
346 *p->iri = '\0';
347 p->iri++;
350 return 1;
353 /* don't even bother */
354 static int
355 parse_fragment(struct parser *p)
357 p->parsed->fragment = p->iri;
358 return 1;
361 /* XXX: is it too broad? */
362 /* *(pchar / "/") */
363 static int
364 parse_path(struct parser *p)
366 char c;
368 /* trim initial slashes */
369 while (*p->iri == '/')
370 p->iri++;
372 p->parsed->path = p->iri;
373 if (*p->iri == '\0') {
374 p->parsed->query = p->parsed->fragment = p->iri;
375 return 1;
378 while (unreserved(*p->iri)
379 || sub_delimiters(*p->iri)
380 || *p->iri == '/'
381 || parse_pct_encoded(p))
382 p->iri++;
384 if (p->err != NULL)
385 return 0;
387 if (*p->iri != '\0' && *p->iri != '?' && *p->iri != '#') {
388 p->err = "illegal character in path";
389 return 0;
392 if (*p->iri != '\0') {
393 c = *p->iri;
394 *p->iri = '\0';
395 p->iri++;
397 if (c == '#') {
398 if (!parse_fragment(p))
399 return 0;
400 } else
401 if (!parse_query(p) || !parse_fragment(p))
402 return 0;
405 if (!path_clean(p->parsed->path)) {
406 p->err = "illegal path";
407 return 0;
410 return 1;
413 int
414 url_parse(const char *data, struct url *url, const char **err)
416 struct shallow_url u;
417 struct parser p;
419 memset(url, 0, sizeof(*url));
420 memset(&p, 0, sizeof(p));
421 memset(&u, 0, sizeof(u));
423 strlcpy(p.buf, data, sizeof(p.buf));
424 p.iri = p.buf;
425 p.parsed = &u;
427 if (!parse_scheme(&p) || !parse_authority(&p) || !parse_path(&p)) {
428 *err = p.err;
429 return 0;
432 /* XXX: hack around our not complete compliance with RFC 3986 */
433 /* if (u.scheme != NULL) */
434 strlcpy(url->scheme, "gemini", sizeof(url->scheme));
436 if (u.host != NULL)
437 strlcpy(url->host, u.host, sizeof(url->host));
438 if (u.port != NULL)
439 strlcpy(url->port, u.port, sizeof(url->port));
440 if (u.path != NULL)
441 strlcpy(url->path, u.path, sizeof(url->path));
442 if (u.query != NULL)
443 strlcpy(url->query, u.query, sizeof(url->query));
444 if (u.fragment != NULL)
445 strlcpy(url->fragment, u.fragment, sizeof(url->fragment));
447 return 1;
450 int
451 url_resolve_from(struct url *url, const char *str, const char **err)
453 char *marker, *query, *hash, *i;
455 marker = strstr(str, "//");
456 query = strchr(str, '?');
457 hash = strchr(str, '#');
459 /* full URL */
460 if (marker != NULL
461 && (query == NULL || marker < query)
462 && (hash == NULL || marker < hash))
463 return url_parse(str, url, err);
465 /* TODO: reuse more of the above */
467 /* absolute url */
468 if (*str == '/') {
469 strlcpy(url->path, str, sizeof(url->path));
471 if ((hash = strchr(url->path, '#')) != NULL) {
472 *hash = '\0';
473 hash++;
474 strlcpy(url->fragment, hash,
475 sizeof(url->fragment));
478 if ((query = strchr(url->path, '?')) != NULL) {
479 *query = '\0';
480 query++;
481 strlcpy(url->query, query,
482 sizeof(url->query));
484 return 1;
487 /* local url */
488 for (i = strchr(url->path, '\0'); i >= url->path; --i) {
489 if (*i == '/')
490 break;
493 if (*i == '/')
494 i++;
495 *i = '\0';
497 strlcat(url->path, str, sizeof(url->path));
498 return 1;
501 int
502 url_set_query(struct url *url, const char *query)
504 /* TODO: pct-encode! */
505 memcpy(&url->query, query, strlen(query)+1);
506 return 1;
509 void
510 url_unparse(struct url *url, char *buf, size_t len)
512 strlcpy(buf, url->scheme, len);
513 strlcat(buf, "://", len);
514 strlcat(buf, url->host, len);
516 if (*url->path == '\0' && *url->query == '\0')
517 return;
519 strlcat(buf, "/", len);
521 if (*url->path != '\0')
522 strlcat(buf, url->path, len);
523 if (*url->query != '\0') {
524 strlcat(buf, "?", len);
525 strlcat(buf, url->query, len);