-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregex_url.c
More file actions
96 lines (78 loc) · 1.63 KB
/
regex_url.c
File metadata and controls
96 lines (78 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
#include "regex_url.h"
static inline int
regex_num_matches(regmatch_t *matches, size_t size)
{
int i, len;
for (i = 0, len = 0; i < size; i++)
{
if (matches[i].rm_so != -1)
len++;
}
return len;
}
int
parse_url(const char *url, char *protocol, char *host, int *port, char *uri)
{
const int max_matches = 6;
regex_t regex;
int reti, ret_val;
regmatch_t matches[max_matches];
*port = -1;
regcomp(®ex, "^([a-z]{1,7}):\\/\\/([a-zA-Z0-9.]{1,127}):?([0-9]{1,5})?(\\/.{0,254})$", REG_EXTENDED);
reti = regexec(®ex, url, max_matches, matches, 0);
if (reti == 0)
{
int num_matches = regex_num_matches(matches, max_matches);
if (num_matches != 4 && num_matches != 5)
{
ret_val = -1;
goto _exit;
}
int i, cur;
for (i = 0, cur = 0; i < max_matches; i++)
{
int start = matches[i].rm_so;
int end = matches[i].rm_eo;
if (start == -1)
continue; /* no match */
int len = end-start;
if (cur == 1) /* protocol */
{
memcpy(protocol, url+start, len);
protocol[len] = '\0';
}
else if(cur == 2) /* host */
{
memcpy(host, url+start, len);
host[len] = '\0';
}
else if((cur == 3 && num_matches == 4) || cur == 4) /* uri */
{
/* uri */
memcpy(uri, url+start, len);
uri[len] = '\0';
}
else if(cur == 3) /* port */
{
char buf[16];
memcpy(buf, url+start, len);
buf[len] = '\0';
*port = atoi(buf);
}
cur++;
}
ret_val = 0;
goto _exit;
}
else if (reti == REG_NOMATCH)
ret_val = -2;
else
ret_val = -3;
_exit:
regfree(®ex);
return ret_val;
}