From 977fb516245183b6388053b9c53056a3164fb5a8 Mon Sep 17 00:00:00 2001 From: Martin Mares Date: Wed, 19 Jul 2017 12:46:39 +0200 Subject: [PATCH] We have a command table --- client/subauth.c | 2 ++ server/cmd.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++ server/subauthd.c | 2 +- server/subauthd.h | 1 + 4 files changed, 51 insertions(+), 1 deletion(-) diff --git a/client/subauth.c b/client/subauth.c index e597b76..42b9003 100644 --- a/client/subauth.c +++ b/client/subauth.c @@ -51,6 +51,8 @@ int main(int argc UNUSED, char **argv) struct json_context *js = json_new(); struct json_node *rq = json_new_object(js); + json_object_set(rq, "cmd", json_new_string(js, "nop")); + bprintf(out, ">>> Request:\n"); json_write(js, out, rq); bflush(out); diff --git a/server/cmd.c b/server/cmd.c index 5e8b898..a53622e 100644 --- a/server/cmd.c +++ b/server/cmd.c @@ -13,4 +13,51 @@ void cmd_error(struct client *c, const char *err) json_object_set(c->reply, "error", json_new_string(c->json, err)); } +static void cmd_ok(struct client *c) +{ + cmd_error(c, ""); +} + +static const char *get_string(struct json_node *n, const char *key) +{ + struct json_node *s = json_object_get(n, key); + if (s && s->type == JSON_STRING) + return s->string; + else + return NULL; +} + +static void cmd_nop(struct client *c) +{ + cmd_ok(c); +} +struct command { + const char *cmd; + void (*handler)(struct client *c); +}; + +static const struct command command_table[] = { + { "nop", cmd_nop }, +}; + +void cmd_dispatch(struct client *c) +{ + struct json_node *rq = c->request; + const char *cmd; + + if (rq->type != JSON_OBJECT || !(cmd = get_string(rq, "cmd"))) + { + cmd_error(c, "Malformed request"); + return; + } + + for (uint i=0; i < ARRAY_SIZE(command_table); i++) + if (!strcmp(cmd, command_table[i].cmd)) + { + command_table[i].handler(c); + return; + } + + cmd_error(c, "No such command"); +} diff --git a/server/subauthd.c b/server/subauthd.c index 56d142f..cd6376f 100644 --- a/server/subauthd.c +++ b/server/subauthd.c @@ -115,7 +115,7 @@ static void received_packet(struct client *c, byte *pkt, int len) } TRANS_END; - cmd_error(c, "OK"); + cmd_dispatch(c); send_reply(c); } diff --git a/server/subauthd.h b/server/subauthd.h index 4a104ec..66d792e 100644 --- a/server/subauthd.h +++ b/server/subauthd.h @@ -25,3 +25,4 @@ struct client { /* cmd.c */ void cmd_error(struct client *c, const char *err); +void cmd_dispatch(struct client *c); -- 2.39.2