Browse Source

support #600: hv_parser_url ipv6

ithewei 1 year ago
parent
commit
734a3429c3
3 changed files with 21 additions and 2 deletions
  1. 19 2
      base/hbase.c
  2. 1 0
      base/hbase.h
  3. 1 0
      unittest/hbase_test.c

+ 19 - 2
base/hbase.c

@@ -195,6 +195,17 @@ char* hv_strnchr(const char* s, char c, size_t n) {
     return NULL;
 }
 
+char* hv_strnrchr(const char* s, char c, size_t n) {
+    assert(s != NULL);
+    const char* p = s;
+    const char* last = NULL;
+    while (*p != '\0' && n-- > 0) {
+        if (*p == c) last = p;
+        ++p;
+    }
+    return (char*)last;
+}
+
 char* hv_strrchr_dir(const char* filepath) {
     char* p = (char*)filepath;
     while (*p) ++p;
@@ -474,7 +485,7 @@ int hv_parse_url(hurl_t* stURL, const char* strURL) {
         host = pos + 1;
     }
     // port
-    const char* port = hv_strnchr(host, ':', ep - host);
+    const char* port = hv_strnrchr(host, ':', ep - host);
     if (port) {
         stURL->fields[HV_URL_PORT].off = port + 1 - begin;
         stURL->fields[HV_URL_PORT].len = ep - port - 1;
@@ -493,8 +504,14 @@ int hv_parse_url(hurl_t* stURL, const char* strURL) {
         }
     }
     // host
+    unsigned short hostlen = port - host;
+    if (hostlen > 2 && host[0] == '[' && host[hostlen-1] == ']') {
+        // ipv6
+        host++;
+        hostlen -= 2;
+    }
     stURL->fields[HV_URL_HOST].off = host - begin;
-    stURL->fields[HV_URL_HOST].len = port - host;
+    stURL->fields[HV_URL_HOST].len = hostlen;
     if (ep == end) return 0;
     // /path
     sp = ep;

+ 1 - 0
base/hbase.h

@@ -82,6 +82,7 @@ HV_EXPORT char* hv_strncat(char* dest, const char* src, size_t n);
 #endif
 
 HV_EXPORT char* hv_strnchr(const char* s, char c, size_t n);
+HV_EXPORT char* hv_strnrchr(const char* s, char c, size_t n);
 
 #define hv_strrchr_dot(str) strrchr(str, '.')
 HV_EXPORT char* hv_strrchr_dir(const char* filepath);

+ 1 - 0
unittest/hbase_test.c

@@ -30,6 +30,7 @@ int main(int argc, char* argv[]) {
             4);
 
     const char* test_urls[] = {
+        "http://user:pswd@[www.example.com]:80/path?query#fragment",
         "http://user:pswd@www.example.com:80/path?query#fragment",
         "http://user:pswd@www.example.com/path?query#fragment",
         "http://www.example.com/path?query#fragment",