add protocol for exchanging signed network data
[project/unetd.git] / utils.c
diff --git a/utils.c b/utils.c
index 083e4527b01eb11abaa43c1cb661667ec33f576c..95ab08bb570b3d9360d96876eeb1a640242f4c48 100644 (file)
--- a/utils.c
+++ b/utils.c
@@ -4,8 +4,10 @@
  */
 #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,
@@ -141,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;
+}