]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/http/http_lib.c
Generalize the HTTP client so far implemented mostly in crypto/ocsp/ocsp_ht.c
[thirdparty/openssl.git] / crypto / http / http_lib.c
1 /*
2 * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10 #include <openssl/http.h>
11 #include <openssl/httperr.h>
12 #include <openssl/err.h>
13 #include <string.h>
14
15 /*
16 * Parse a URL and split it up into host, port and path components and
17 * whether it indicates SSL/TLS. Return 1 on success, 0 on error.
18 */
19
20 int OSSL_HTTP_parse_url(const char *url, char **phost, char **pport,
21 char **ppath, int *pssl)
22 {
23 char *p, *buf;
24 char *host;
25 char *port = "80";
26
27 if (url == NULL) {
28 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
29 return 0;
30 }
31
32 if (phost != NULL)
33 *phost = NULL;
34 if (pport != NULL)
35 *pport = NULL;
36 if (ppath != NULL)
37 *ppath = NULL;
38 if (pssl != NULL)
39 *pssl = 0;
40
41 /* dup the buffer since we are going to mess with it */
42 if ((buf = OPENSSL_strdup(url)) == NULL)
43 goto err;
44
45 /* Check for initial colon */
46 p = strchr(buf, ':');
47 if (p == NULL || p - buf > 5 /* strlen("https") */) {
48 p = buf;
49 } else {
50 *(p++) = '\0';
51
52 if (strcmp(buf, "https") == 0) {
53 if (pssl != NULL)
54 *pssl = 1;
55 port = "443";
56 } else if (strcmp(buf, "http") != 0) {
57 goto parse_err;
58 }
59
60 /* Check for double slash */
61 if ((p[0] != '/') || (p[1] != '/'))
62 goto parse_err;
63 p += 2;
64 }
65 host = p;
66
67 /* Check for trailing part of path */
68 p = strchr(p, '/');
69 if (ppath != NULL && (*ppath = OPENSSL_strdup(p == NULL ? "/" : p)) == NULL)
70 goto err;
71 if (p != NULL)
72 *p = '\0'; /* Set start of path to 0 so hostname[:port] is valid */
73
74 p = host;
75 if (host[0] == '[') {
76 /* ipv6 literal */
77 host++;
78 p = strchr(host, ']');
79 if (p == NULL)
80 goto parse_err;
81 *p = '\0';
82 p++;
83 }
84
85 /* Look for optional ':' for port number */
86 if ((p = strchr(p, ':'))) {
87 *p = '\0';
88 port = p + 1;
89 }
90 if (phost != NULL && (*phost = OPENSSL_strdup(host)) == NULL)
91 goto err;
92 if (pport != NULL && (*pport = OPENSSL_strdup(port)) == NULL)
93 goto err;
94
95 OPENSSL_free(buf);
96 return 1;
97
98 parse_err:
99 HTTPerr(0, HTTP_R_ERROR_PARSING_URL);
100
101 err:
102 if (ppath != NULL) {
103 OPENSSL_free(*ppath);
104 *ppath = NULL;
105 }
106 if (pport != NULL) {
107 OPENSSL_free(*pport);
108 *pport = NULL;
109 }
110 if (phost != NULL) {
111 OPENSSL_free(*phost);
112 *phost = NULL;
113 }
114 OPENSSL_free(buf);
115 return 0;
116 }