Skip to content

Commit d59774d

Browse files
committed
don't use regcomp to check hostname validity
1 parent 72bce51 commit d59774d

File tree

1 file changed

+38
-7
lines changed

1 file changed

+38
-7
lines changed

shared-bindings/wifi/Radio.c

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,50 @@
2727
#include "shared-bindings/wifi/__init__.h"
2828
#include "shared-bindings/wifi/AuthMode.h"
2929

30-
#include <regex.h>
3130
#include <string.h>
3231

3332
#include "py/runtime.h"
3433
#include "py/objproperty.h"
3534

3635
#define MAC_ADDRESS_LENGTH 6
3736

37+
STATIC bool hostname_valid(const char *ptr, size_t len) {
38+
#if 0 // validated by mp_arg_validate_length_range
39+
if (len == 0 || len > 253) {
40+
// at most 253 characters long
41+
return false;
42+
}
43+
#endif
44+
int partlen = 0;
45+
while (len) {
46+
char c = *ptr++;
47+
len--;
48+
if (c == '.') {
49+
if (partlen == 0 || partlen > 63) {
50+
return false;
51+
}
52+
partlen = 0;
53+
continue;
54+
}
55+
partlen++;
56+
if (c == '-') {
57+
if (partlen == 1) {
58+
return false; // part cannot begin with a dash
59+
}
60+
continue;
61+
} else if (
62+
(c >= 'a' && c <= 'z') ||
63+
(c >= 'A' && c <= 'Z') ||
64+
(c >= '0' && c <= '9')) {
65+
continue;
66+
}
67+
return false;
68+
}
69+
// check length of last part
70+
return !(partlen > 63);
71+
}
72+
73+
3874
//| class Radio:
3975
//| """Native wifi radio.
4076
//|
@@ -89,14 +125,9 @@ STATIC mp_obj_t wifi_radio_set_hostname(mp_obj_t self_in, mp_obj_t hostname_in)
89125

90126
mp_arg_validate_length_range(hostname.len, 1, 253, MP_QSTR_hostname);
91127

92-
#if !(defined(CONFIG_IDF_TARGET_ESP32C3) || defined(RASPBERRYPI))
93-
regex_t regex; // validate hostname according to RFC 1123
94-
regcomp(&regex,"^(([a-z0-9]|[a-z0-9][a-z0-9\\-]{0,61}[a-z0-9])\\.)*([a-z0-9]|[a-z0-9][a-z0-9\\-]{0,61}[a-z0-9])$", REG_EXTENDED | REG_ICASE | REG_NOSUB);
95-
if (regexec(&regex, hostname.buf, 0, NULL, 0)) {
128+
if (!hostname_valid(hostname.buf, hostname.len)) {
96129
mp_raise_ValueError(translate("invalid hostname"));
97130
}
98-
regfree(&regex);
99-
#endif
100131

101132
wifi_radio_obj_t *self = MP_OBJ_TO_PTR(self_in);
102133
common_hal_wifi_radio_set_hostname(self, hostname.buf);

0 commit comments

Comments
 (0)