]> mj.ucw.cz Git - subauth.git/blob - server/cmd.c
a53622e8522f498e433f51bf746f6315fb47427e
[subauth.git] / server / cmd.c
1 /*
2  *      Sub-authentication Daemon: Commands
3  *
4  *      (c) 2017 Martin Mares <mj@ucw.cz>
5  */
6
7 #include <ucw/lib.h>
8
9 #include "subauthd.h"
10
11 void cmd_error(struct client *c, const char *err)
12 {
13   json_object_set(c->reply, "error", json_new_string(c->json, err));
14 }
15
16 static void cmd_ok(struct client *c)
17 {
18   cmd_error(c, "");
19 }
20
21 static const char *get_string(struct json_node *n, const char *key)
22 {
23   struct json_node *s = json_object_get(n, key);
24   if (s && s->type == JSON_STRING)
25     return s->string;
26   else
27     return NULL;
28 }
29
30 static void cmd_nop(struct client *c)
31 {
32   cmd_ok(c);
33 }
34
35 struct command {
36   const char *cmd;
37   void (*handler)(struct client *c);
38 };
39
40 static const struct command command_table[] = {
41   { "nop",              cmd_nop },
42 };
43
44 void cmd_dispatch(struct client *c)
45 {
46   struct json_node *rq = c->request;
47   const char *cmd;
48
49   if (rq->type != JSON_OBJECT || !(cmd = get_string(rq, "cmd")))
50     {
51       cmd_error(c, "Malformed request");
52       return;
53     }
54
55   for (uint i=0; i < ARRAY_SIZE(command_table); i++)
56     if (!strcmp(cmd, command_table[i].cmd))
57       {
58         command_table[i].handler(c);
59         return;
60       }
61
62   cmd_error(c, "No such command");
63 }