]> mj.ucw.cz Git - subauth.git/blob - client/subauth.c
Split to directories
[subauth.git] / client / subauth.c
1 /*
2  *      Sub-authentication Client
3  *
4  *      (c) 2017 Martin Mares <mj@ucw.cz>
5  */
6
7 #include <ucw/lib.h>
8 #include <ucw/opt.h>
9 #include <ucw-json/json.h>
10
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <sys/socket.h>
14 #include <sys/un.h>
15 #include <unistd.h>
16
17 #include "autoconf.h"
18
19 static char *socket_path = INSTALL_RUN_DIR "/subauthd.socket";
20
21 static const struct opt_section options = {
22   OPT_ITEMS {
23     OPT_HELP("A client to the sub-authentication daemon."),
24     OPT_HELP("Usage: subauth [options]"),
25     OPT_HELP(""),
26     OPT_HELP("Options:"),
27     OPT_HELP_OPTION,
28     OPT_END
29   }
30 };
31
32 int main(int argc UNUSED, char **argv)
33 {
34   opt_parse(&options, argv+1);
35
36   int sk = socket(PF_UNIX, SOCK_SEQPACKET, 0);
37   if (sk < 0)
38     die("socket(PF_UNIX, SOCK_SEQPACKET): %m");
39
40   struct sockaddr_un sun;
41   sun.sun_family = AF_UNIX;
42   if (strlen(socket_path) >= sizeof(sun.sun_path))
43     die("Socket path too long");
44   strcpy(sun.sun_path, socket_path);
45
46   if (connect(sk, (struct sockaddr *) &sun, sizeof(sun)) < 0)
47     die("Cannot connect to %s: %m", socket_path);
48
49   struct fastbuf *out = bfdopen(1, 4096);
50
51   struct json_context *js = json_new();
52   struct json_node *rq = json_new_object(js);
53
54   bprintf(out, ">>> Request:\n");
55   json_write(js, out, rq);
56   bflush(out);
57
58   struct fastbuf *rq_fb = fbgrow_create(4096);
59   json_write(js, rq_fb, rq);
60   byte *rq_buf;
61   uint rq_len = fbgrow_get_buf(rq_fb, &rq_buf);
62   if (send(sk, rq_buf, rq_len, 0) < 0)
63     die("Cannot send request: %m");
64   bclose(rq_fb);
65
66   byte rp_buf[4096];            // FIXME
67   int rp_len = recv(sk, rp_buf, sizeof(rp_buf), 0);
68   if (rp_len < 0)
69     die("Cannot receive reply: %m");
70
71   puts("Parsing reply");
72   struct fastbuf rp_fb;
73   fbbuf_init_read(&rp_fb, rp_buf, rp_len, 0);
74   struct json_node *rp = json_parse(js, &rp_fb);
75   bprintf(out, "<<< Reply:\n");
76   json_write(js, out, rp);
77   bflush(out);
78
79   return 0;
80 }