From 4a490a4bc6a2c2bebbf1460208162ed5ebc561b7 Mon Sep 17 00:00:00 2001 From: Romain de Laage Date: Mon, 15 Feb 2021 21:07:24 +0100 Subject: [PATCH] Mostly finish url parser --- lib/url.c | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 81 insertions(+), 2 deletions(-) diff --git a/lib/url.c b/lib/url.c index 872ea52..9ea705b 100644 --- a/lib/url.c +++ b/lib/url.c @@ -79,17 +79,96 @@ urllib_parse (Url *url, const char *url_string) return 1; //parse IPv6, IPv4 or hostname + + cursor += 2; + if (cursor[0] == '[') // IPv6 + { + tmpcursor = strchr (cursor, ']'); + + if (tmpcursor == NULL) + return 1; + + len = tmpcursor - cursor + + for (i = 1; i < len - 1; i++)//verify + if (!isdigit (cursor[i]) && !(tolower(cursor[i]) >= 'a' && tolower(cursor[i]) <= 'f') && !(cursor[i] == ':')) + return 1; + } + else // IPv4 or hostname + { + tmpcursor = strchr (cursor, ':'); + + if (tmpcursor == NULL) + tmpcursor = strchr (cursor, '/'); + + if (tmpcursor == NULL) + return 1; + + //missing case when no tailing / and no : (only host) (test \0 ?, or len = strlen) + + len = tmpcursor - cursor; + + for (i = 0, i < len; i++) + if (!isalnum (cursor[i]) && !(cursor[i] == '.')) + return 1; + } + + url->host = malloc (sizeof (char) * (len + 1)); + if (url->host == NULL) + return 1; + + strncpy (url->host, cursor, len); + url->host[len] = '\0'; + //parse port (or not) + + cursor += len + 1; + if (cursor[0] == ':') + { + tmpcursor = strchr (cursor, '/'); + if (tmpcursor == NULL) + len = strlen (cursor); + else + len = tmpcursor - cursor; + + for (i = 1; i < len; i++) + if (!isdigit (cursor[i])) + return 1; + + url->port = malloc (sizeof (char) * len); + if (url->port == NULL) + return 1; + + strncpy (url->port, cursor + 1, len - 1); + + cursor += len; + } + //parse path + + len = strlen (cursor); + + if (len > 0) + { + url->path = malloc (sizeof (char) * (len + 1)); + if (url->path == NULL) + return 1; + + strncpy (url->path, cursor, len); + } + + return 0; + + //is there a path ? (test \0) } void urllib_tostring (Url *url, char *dest) { if (url->port == NULL) - sprintf (dest, "%s://%s/%s", url->scheme, url->host, url->path); + sprintf (dest, "%s://%s/%s\r\n", url->scheme, url->host, url->path); else - sprintf (dest, "%s://%s:%s/%s", url->scheme, url->host, url->port, url->path); + sprintf (dest, "%s://%s:%s/%s\r\n", url->scheme, url->host, url->port, url->path); } void