pex: add support for sending endpoint notification from the wg port via raw socket
[project/unetd.git] / utils.c
diff --git a/utils.c b/utils.c
index 462ebbf15108b6171d27482d2087d60dbe8e9c5f..95ab08bb570b3d9360d96876eeb1a640242f4c48 100644 (file)
--- a/utils.c
+++ b/utils.c
@@ -1,11 +1,13 @@
-// SPDX-License-Identifier: GPL-2.0+
+// SPDX-License-Identifier: GPL-2.0-or-later
 /*
  * Copyright (C) 2022 Felix Fietkau <nbd@nbd.name>
  */
 #include <sys/types.h>
 #include <sys/socket.h>
+#include <sys/stat.h>
 #include <arpa/inet.h>
 #include <netdb.h>
+#include <stdio.h>
 #include "unetd.h"
 
 int network_get_endpoint(union network_endpoint *dest, const char *str,
@@ -27,7 +29,7 @@ int network_get_endpoint(union network_endpoint *dest, const char *str,
                host++;
                port = strchr(host, ']');
                if (!port)
-                       return -1;
+                       goto out;
 
                *(port++) = 0;
                if (!*port)
@@ -60,13 +62,16 @@ int network_get_endpoint(union network_endpoint *dest, const char *str,
 
 found:
        if (ai_cur->ai_addrlen > sizeof(*dest))
-               goto out;
+               goto free_ai;
 
        memcpy(dest, ai_cur->ai_addr, ai_cur->ai_addrlen);
        if (!port)
                dest->in.sin_port = htons(default_port);
        ret = 0;
 
+free_ai:
+       freeaddrinfo(ai);
+
 out:
        free(buf);
        return ret;
@@ -138,3 +143,39 @@ out:
        close(fd);
        return ret;
 }
+
+void *unet_read_file(const char *name, size_t *len)
+{
+       struct stat st;
+       void *data;
+       FILE *f;
+
+       f = fopen(name, "r");
+       if (!f)
+               goto error;
+
+       if (fstat(fileno(f), &st) < 0)
+               goto close;
+
+       if (*len && st.st_size > *len)
+               goto close;
+
+       data = malloc(st.st_size);
+       if (!data)
+               goto close;
+
+       if (fread(data, 1, st.st_size, f) != st.st_size) {
+               free(data);
+               goto close;
+       }
+       fclose(f);
+
+       *len = st.st_size;
+       return data;
+
+close:
+       fclose(f);
+error:
+       *len = 0;
+       return NULL;
+}