From f44cfcb1cec1223c25578b311887f5ce6ca81c97 Mon Sep 17 00:00:00 2001 From: MrMelon Date: Sat, 24 Apr 2021 11:18:56 +0100 Subject: [PATCH] Add refresh peers binary --- src/impl/refresh-peers/main.c | 93 +++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 src/impl/refresh-peers/main.c diff --git a/src/impl/refresh-peers/main.c b/src/impl/refresh-peers/main.c new file mode 100644 index 0000000..a1eda6d --- /dev/null +++ b/src/impl/refresh-peers/main.c @@ -0,0 +1,93 @@ +#include +#include +#include +#include +#include +#include + +#include "mjson.h" +#include "unix_sockets.h" +#include "melon_vpn_sock.h" + +#define JBUF_SIZE 5000 +#define NAME_MAX 25 +#define IP_MAX 15 +#define DEV_MAX 25 + +struct dev_t { + char name[NAME_MAX]; + char ip[IP_MAX]; +}; + +struct devlist_t { + int ndevices; + struct dev_t list[DEV_MAX]; +}; + +static struct devlist_t devicelist; + +static int json_devicelist_read(const char *buf) { + const struct json_attr_t json_attrs_subdevice[] = { + {"Name",t_string,STRUCTOBJECT(struct dev_t,name),.len=NAME_MAX}, + {"IP",t_string,STRUCTOBJECT(struct dev_t,ip),.len=IP_MAX}, + {NULL}, + }; + const struct json_attr_t json_attrs_devices[] = { + {"devices", t_array, STRUCTARRAY(devicelist.list,json_attrs_subdevice,&devicelist.ndevices)}, + {NULL}, + }; + + int status; + + memset(&devicelist, '\0', sizeof(devicelist)); + status = json_read_object(buf, json_attrs_devices, NULL); + if (status != 0) return status; + return 0; +} + +void send_to_daemon(char*, ssize_t); + +int main(int argc, char *argv[]) { + char jbuf[JBUF_SIZE]; + char ibuf[JBUF_SIZE]; + + strcpy(jbuf, "{\"devices\":"); + read(STDIN_FILENO, ibuf, JBUF_SIZE); + strcat(jbuf, ibuf); + strcat(jbuf, "}"); + + int status = json_devicelist_read(jbuf); + if (status != 0) { + puts(json_error_string(status)); + } else { + ssize_t l=0; + char obuf[JBUF_SIZE]; + obuf[JBUF_SIZE-1]=0; + strcpy(obuf, ""); + + for (int i = 0; i < devicelist.ndevices; i++) { + l += strlen(devicelist.list[i].name)+strlen(devicelist.list[i].ip)+2; + strcat(obuf, devicelist.list[i].name); + strcat(obuf, "\t"); + strcat(obuf, devicelist.list[i].ip); + strcat(obuf, "\n"); + obuf[l]=0; + fprintf(stderr, "l: %d\nobuf: %d\n",l,strlen(obuf)); + } + + send_to_daemon(obuf,l); + } +} + +void send_to_daemon(char *buf, ssize_t n) { + int sfd = unix_socket_client_start(SV_RPEERS_SOCK_PATH); + if(sfd==-1) { + return; + } + + write(sfd, buf, n); + + // Closes our socket; server sees EOF. + exit(EXIT_SUCCESS); + fprintf(stderr, "Closed connection to socket"); +}