From fcdadf5df39e1d72f9ac79fa384fc6b98be0b1aa Mon Sep 17 00:00:00 2001 From: dzwdz Date: Mon, 22 Aug 2022 18:14:31 +0200 Subject: user/netstack: ip_parse --- src/user/app/netstack/fs.c | 19 ++++++++++++------- src/user/app/netstack/util.c | 17 +++++++++++++++++ src/user/app/netstack/util.h | 2 ++ 3 files changed, 31 insertions(+), 7 deletions(-) (limited to 'src/user/app/netstack') diff --git a/src/user/app/netstack/fs.c b/src/user/app/netstack/fs.c index 4d1e38c..19e5bfd 100644 --- a/src/user/app/netstack/fs.c +++ b/src/user/app/netstack/fs.c @@ -96,15 +96,21 @@ static void fs_open(handle_t reqh, char *path) { } char *save; - const char *srcip_s, *dstip_s, *verb, *proto, *port_s; + const char *verb, *proto, *port_s; - srcip_s = strtok_r(path, "/", &save); - if (strcmp(srcip_s, "0.0.0.0") != 0) + uint32_t srcip, dstip; + if (ip_parse(strtok_r(path, "/", &save), &srcip) < 0) respond(NULL, -1); + if (srcip != 0) { + eprintf("unimplemented"); + respond(NULL, -1); + } verb = strtok_r(NULL, "/", &save); + if (!verb) respond(NULL, -1); if (strcmp(verb, "listen") == 0) { proto = strtok_r(NULL, "/", &save); + if (!proto) respond(NULL, -1); if (strcmp(proto, "udp") == 0) { port_s = strtok_r(NULL, "/", &save); if (port_s) { @@ -119,11 +125,10 @@ static void fs_open(handle_t reqh, char *path) { } } } else if (strcmp(verb, "connect") == 0) { - dstip_s = strtok_r(NULL, "/", &save); - // TODO proper ip parsing - // 0xc0a80001 == 192.168.0.1 - uint32_t dstip = strtol(dstip_s, NULL, 0); + if (ip_parse(strtok_r(NULL, "/", &save), &dstip) < 0) + respond(NULL, -1); proto = strtok_r(NULL, "/", &save); + if (!proto) respond(NULL, -1); if (strcmp(proto, "udp") == 0) { port_s = strtok_r(NULL, "/", &save); if (port_s) { diff --git a/src/user/app/netstack/util.c b/src/user/app/netstack/util.c index 9981aa3..e9d3118 100644 --- a/src/user/app/netstack/util.c +++ b/src/user/app/netstack/util.c @@ -29,3 +29,20 @@ uint16_t ip_checksum(const uint8_t *buf, size_t len) { c = (c & 0xFFFF) + (c >> 16); return ~c; } + +int ip_parse(const char *s, uint32_t *dest) { + if (!s) return -1; + + uint32_t ip = strtol(s, (char**)&s, 0); + int parts = 1; + for (; parts < 4; parts++) { + if (!*s) break; + if (*s++ != '.') return -1; + ip <<= 8; + ip += strtol(s, (char**)&s, 0); + } + if (parts > 1) + ip = ((ip & 0xFFFFFF00) << 8 * (4 - parts)) | (ip & 0xFF); + *dest = ip; + return 0; +} diff --git a/src/user/app/netstack/util.h b/src/user/app/netstack/util.h index 5472b05..b8fa5c6 100644 --- a/src/user/app/netstack/util.h +++ b/src/user/app/netstack/util.h @@ -8,6 +8,8 @@ uint32_t crc32(const uint8_t *buf, size_t len); uint16_t ip_checksum(const uint8_t *buf, size_t len); +/* 0 on success, negative failure */ +int ip_parse(const char *s, uint32_t *ip); static inline void nput16(void *vbuf, uint16_t n) { uint8_t *b = vbuf; -- cgit v1.2.3