From e8485da6e6993ddd66077171de3dd4b5a8ce98d0 Mon Sep 17 00:00:00 2001 From: ngn Date: Sat, 13 Jul 2024 16:48:17 +0300 Subject: [PATCH] update: better way to handle parse_host function --- locale/tr/LC_MESSAGES/libmp.po | 2 +- src/ctx/serve.c | 4 ++-- src/util.c | 34 ++++++++++++++++++++++------------ 3 files changed, 25 insertions(+), 15 deletions(-) diff --git a/locale/tr/LC_MESSAGES/libmp.po b/locale/tr/LC_MESSAGES/libmp.po index c0be8fe..d0a00a0 100644 --- a/locale/tr/LC_MESSAGES/libmp.po +++ b/locale/tr/LC_MESSAGES/libmp.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-13 14:22+0300\n" +"POT-Creation-Date: 2024-07-13 16:47+0300\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" diff --git a/src/ctx/serve.c b/src/ctx/serve.c index a88fb7c..4b6da4d 100644 --- a/src/ctx/serve.c +++ b/src/ctx/serve.c @@ -101,8 +101,8 @@ bool lm_ctx_serve(lm_ctx_t *ctx, char *addr, uint8_t threads){ return false; } + char host[strlen(addr)+1]; struct sockaddr saddr; - char *host = NULL; lm_mptp_t packet; uint16_t port; int sock; @@ -118,7 +118,7 @@ bool lm_ctx_serve(lm_ctx_t *ctx, char *addr, uint8_t threads){ return false; } - if ((sock = lm_mptp_server_listen(addr, port)) < 0) + if ((sock = lm_mptp_server_listen(host, port)) < 0) return false; while (lm_mptp_server_recv(sock, &packet, &saddr)) { diff --git a/src/util.c b/src/util.c index 284b64a..4aef5fd 100644 --- a/src/util.c +++ b/src/util.c @@ -52,22 +52,32 @@ bool contains(char *str, char s) { } bool parse_host(char *addr, char *host, uint16_t *port) { - char *save = NULL, *portc = NULL; - int portint = 0; + char portc[strlen(addr) + 1]; + ssize_t hi = 0, pi = -1; + int portint = 0; - if ((host = strtok_r(addr, ":", &save)) == NULL) { - lm_error_set(LM_ERR_BadHost); + for (char *c = addr; *c != 0; c++) { + if (*c == ':') { + pi = 0; + continue; + } + + if (pi < 0) + host[hi++] = *c; + else + portc[pi++] = *c; + } + + host[hi] = 0; + portc[pi < 0 ? 0 : pi] = 0; + + if ((portint = atoi(portc)) < 0 || portint > UINT16_MAX) { + lm_error_set(LM_ERR_BadPort); return false; } - if ((portc = strtok_r(NULL, ":", &save)) == NULL) { - *port = 0; - return true; - } - - portint = atoi(portc); - if (portint <= 0 || portint > UINT16_MAX) { - lm_error_set(LM_ERR_BadPort); + if (hi <= 1) { + lm_error_set(LM_ERR_BadHost); return false; }