]> mj.ucw.cz Git - subauth.git/blob - server/cmd.c
Database of users
[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 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 bool get_uint(struct json_node *n, const char *key, uint *dest)
31 {
32   struct json_node *s = json_object_get(n, key);
33   if (s && s->type == JSON_NUMBER)
34     {
35       uint u = (uint) s->number;
36       if ((double) u == s->number)
37         {
38           *dest = u;
39           return 1;
40         }
41     }
42   *dest = 0;
43   return 0;
44 }
45
46 struct json_node **get_array(struct json_node *n, const char *key)
47 {
48   struct json_node *s = json_object_get(n, key);
49   if (s && s->type == JSON_ARRAY)
50     return s->elements;
51   else
52     return NULL;
53 }
54
55 struct json_node *get_object(struct json_node *n, const char *key)
56 {
57   struct json_node *s = json_object_get(n, key);
58   if (s && s->type == JSON_OBJECT)
59     return s;
60   else
61     return NULL;
62 }
63
64 static void cmd_nop(struct client *c)
65 {
66   cmd_ok(c);
67 }
68
69 struct command {
70   const char *cmd;
71   void (*handler)(struct client *c);
72 };
73
74 static const struct command command_table[] = {
75   { "nop",              cmd_nop },
76 };
77
78 void cmd_dispatch(struct client *c)
79 {
80   struct json_node *rq = c->request;
81   const char *cmd;
82
83   if (rq->type != JSON_OBJECT || !(cmd = get_string(rq, "cmd")))
84     {
85       cmd_error(c, "Malformed request");
86       return;
87     }
88
89   for (uint i=0; i < ARRAY_SIZE(command_table); i++)
90     if (!strcmp(cmd, command_table[i].cmd))
91       {
92         command_table[i].handler(c);
93         return;
94       }
95
96   cmd_error(c, "No such command");
97 }