afs: Shutdown signals on exit.
[paraslash.git] / command.c
index 491ce3940422d1d14ab9b8fee0faf35e39df1810..aea48146a38cefd7aeb22ea2994c9d53b5633c08 100644 (file)
--- a/command.c
+++ b/command.c
@@ -1,8 +1,4 @@
-/*
- * Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>
- *
- * Licensed under the GPL v2. For licencing details see COPYING.
- */
+/* Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
 
 /** \file command.c Client authentication and server commands. */
 
 #include <netdb.h>
 #include <lopsub.h>
 
+#include "server.lsg.h"
 #include "para.h"
 #include "error.h"
 #include "crypt.h"
 #include "sideband.h"
 #include "command.h"
-#include "server.cmdline.h"
 #include "string.h"
 #include "afh.h"
 #include "afs.h"
@@ -37,7 +33,6 @@
 #include "ipc.h"
 #include "server_cmd.lsg.h"
 #include "user_list.h"
-#include "afs.command_list.h"
 #include "signal.h"
 #include "version.h"
 
@@ -48,37 +43,20 @@ static const unsigned server_command_perms[] = {LSG_SERVER_CMD_AUX_INFOS};
 static const char * const server_command_perms_txt[] = {LSG_SERVER_CMD_AUX_INFOS};
 #undef SERVER_CMD_AUX_INFO
 
-typedef int server_command_handler_t(struct command_context *);
-server_command_handler_t AFS_COMMAND_HANDLERS;
-
-/* Defines one command of para_server. */
-struct server_command {
-       /* The name of the command. */
-       const char *name;
-       /* Pointer to the function that handles the command. */
-       server_command_handler_t *handler;
-       /* The privileges a user must have to execute this command. */
-       unsigned int perms;
-       /* One-line description of the command. */
-       const char *description;
-       /* Summary of the command line options. */
-       const char *usage;
-       /* The long help text. */
-       const char *help;
-};
-
-static struct server_command afs_cmds[] = {DEFINE_AFS_CMD_ARRAY};
-
 /** Commands including options must be shorter than this. */
 #define MAX_COMMAND_LEN 32768
 
 extern int mmd_mutex;
 extern struct misc_meta_data *mmd;
-extern struct sender senders[];
 int send_afs_status(struct command_context *cc, int parser_friendly);
+static bool subcmd_should_die;
 
-static void dummy(__a_unused int s)
+static void command_handler_sighandler(int s)
 {
+       if (s != SIGTERM)
+               return;
+       PARA_EMERG_LOG("terminating on signal %d\n", SIGTERM);
+       subcmd_should_die = true;
 }
 
 /*
@@ -129,18 +107,18 @@ static unsigned get_status(struct misc_meta_data *nmmd, bool parser_friendly,
        clock_get_realtime(&current_time);
        /*
         * The calls to WRITE_STATUS_ITEM() below never fail because
-        * b->max_size is zero (unlimited), see para_printf(). However, clang
-        * is not smart enough to prove this and complains nevertheless.
+        * b->max_size is zero (unlimited), see \ref para_printf(). However,
+        * clang is not smart enough to prove this and complains nevertheless.
         * Casting the return value to void silences clang.
         */
-       (void)WRITE_STATUS_ITEM(&b, SI_STATUS, "%s\n", status);
-       (void)WRITE_STATUS_ITEM(&b, SI_STATUS_FLAGS, "%s\n", flags);
-       (void)WRITE_STATUS_ITEM(&b, SI_OFFSET, "%li\n", offset);
-       (void)WRITE_STATUS_ITEM(&b, SI_AFS_MODE, "%s\n", mmd->afs_mode_string);
-       (void)WRITE_STATUS_ITEM(&b, SI_STREAM_START, "%lu.%lu\n",
+       (void)WRITE_STATUS_ITEM(&b, SI_status, "%s\n", status);
+       (void)WRITE_STATUS_ITEM(&b, SI_status_flags, "%s\n", flags);
+       (void)WRITE_STATUS_ITEM(&b, SI_offset, "%li\n", offset);
+       (void)WRITE_STATUS_ITEM(&b, SI_afs_mode, "%s\n", mmd->afs_mode_string);
+       (void)WRITE_STATUS_ITEM(&b, SI_stream_start, "%lu.%lu\n",
                (long unsigned)nmmd->stream_start.tv_sec,
                (long unsigned)nmmd->stream_start.tv_usec);
-       (void)WRITE_STATUS_ITEM(&b, SI_CURRENT_TIME, "%lu.%lu\n",
+       (void)WRITE_STATUS_ITEM(&b, SI_current_time, "%lu.%lu\n",
                (long unsigned)current_time.tv_sec,
                (long unsigned)current_time.tv_usec);
        free(flags);
@@ -249,7 +227,7 @@ static int check_sender_args(struct command_context *cc,
                struct lls_parse_result *lpr, struct sender_command_data *scd)
 {
        int i, ret;
-       const char *subcmds[] = {SENDER_SUBCOMMANDS};
+       const char * const subcmds[] = {SENDER_SUBCOMMANDS};
        const char *arg;
        char *errctx;
        unsigned num_inputs = lls_num_inputs(lpr);
@@ -261,20 +239,20 @@ static int check_sender_args(struct command_context *cc,
                return ret;
        }
        arg = lls_input(0, lpr);
-       for (i = 0; senders[i].name; i++)
-               if (!strcmp(senders[i].name, arg))
+       FOR_EACH_SENDER(i)
+               if (strcmp(senders[i]->name, arg) == 0)
                        break;
-       if (!senders[i].name)
+       if (!senders[i])
                return -E_COMMAND_SYNTAX;
        scd->sender_num = i;
        arg = lls_input(1, lpr);
-       for (i = 0; subcmds[i]; i++)
+       for (i = 0; i < NUM_SENDER_CMDS; i++)
                if (!strcmp(subcmds[i], arg))
                        break;
-       if (!subcmds[i])
+       if (i == NUM_SENDER_CMDS)
                return -E_COMMAND_SYNTAX;
        scd->cmd_num = i;
-       if (!senders[scd->sender_num].client_cmds[scd->cmd_num])
+       if (!senders[scd->sender_num]->client_cmds[scd->cmd_num])
                return -E_SENDER_CMD;
        switch (scd->cmd_num) {
        case SENDER_on:
@@ -356,10 +334,10 @@ static int com_sender(struct command_context *cc, struct lls_parse_result *lpr)
        struct sender_command_data scd;
 
        if (lls_num_inputs(lpr) == 0) {
-               for (i = 0; senders[i].name; i++) {
+               FOR_EACH_SENDER(i) {
                        char *tmp;
                        ret = xasprintf(&tmp, "%s%s\n", msg? msg : "",
-                               senders[i].name);
+                               senders[i]->name);
                        free(msg);
                        msg = tmp;
                }
@@ -370,17 +348,17 @@ static int com_sender(struct command_context *cc, struct lls_parse_result *lpr)
                if (scd.sender_num < 0)
                        return ret;
                if (strcmp(lls_input(1, lpr), "status") == 0)
-                       msg = senders[scd.sender_num].status();
+                       msg = senders[scd.sender_num]->status();
                else
-                       msg = senders[scd.sender_num].help();
+                       msg = senders[scd.sender_num]->help();
                return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
        }
 
        switch (scd.cmd_num) {
        case SENDER_add:
        case SENDER_delete:
-               assert(senders[scd.sender_num].resolve_target);
-               ret = senders[scd.sender_num].resolve_target(lls_input(2, lpr),
+               assert(senders[scd.sender_num]->resolve_target);
+               ret = senders[scd.sender_num]->resolve_target(lls_input(2, lpr),
                        &scd);
                if (ret < 0)
                        return ret;
@@ -420,11 +398,11 @@ static int com_si(struct command_context *cc,
                "supported audio formats: %s\n",
                ut, mmd->num_played,
                (int)getppid(),
-               (int)mmd->afs_pid,
+               (int)afs_pid,
                mmd->active_connections,
                mmd->num_commands,
                mmd->num_connects,
-               conf.loglevel_arg,
+               ENUM_STRING_VAL(LOGLEVEL),
                AUDIO_FORMAT_HANDLERS
        );
        mutex_unlock(mmd_mutex);
@@ -448,41 +426,40 @@ EXPORT_SERVER_CMD_HANDLER(version);
 
 /** These status items are cleared if no audio file is currently open. */
 #define EMPTY_STATUS_ITEMS \
-       ITEM(PATH) \
-       ITEM(DIRECTORY) \
-       ITEM(BASENAME) \
-       ITEM(SCORE) \
-       ITEM(ATTRIBUTES_BITMAP) \
-       ITEM(ATTRIBUTES_TXT) \
-       ITEM(HASH) \
-       ITEM(IMAGE_ID) \
-       ITEM(IMAGE_NAME) \
-       ITEM(LYRICS_ID) \
-       ITEM(LYRICS_NAME) \
-       ITEM(BITRATE) \
-       ITEM(FORMAT) \
-       ITEM(FREQUENCY) \
-       ITEM(CHANNELS) \
-       ITEM(DURATION) \
-       ITEM(SECONDS_TOTAL) \
-       ITEM(NUM_PLAYED) \
-       ITEM(LAST_PLAYED) \
-       ITEM(TECHINFO) \
-       ITEM(ARTIST) \
-       ITEM(TITLE) \
-       ITEM(YEAR) \
-       ITEM(ALBUM) \
-       ITEM(COMMENT) \
-       ITEM(MTIME) \
-       ITEM(FILE_SIZE) \
-       ITEM(CHUNK_TIME) \
-       ITEM(NUM_CHUNKS) \
-       ITEM(AMPLIFICATION) \
+       ITEM(path) \
+       ITEM(directory) \
+       ITEM(basename) \
+       ITEM(score) \
+       ITEM(attributes_bitmap) \
+       ITEM(attributes_txt) \
+       ITEM(hash) \
+       ITEM(image_id) \
+       ITEM(image_name) \
+       ITEM(lyrics_id) \
+       ITEM(lyrics_name) \
+       ITEM(bitrate) \
+       ITEM(format) \
+       ITEM(frequency) \
+       ITEM(channels) \
+       ITEM(duration) \
+       ITEM(seconds_total) \
+       ITEM(num_played) \
+       ITEM(last_played) \
+       ITEM(techinfo) \
+       ITEM(artist) \
+       ITEM(title) \
+       ITEM(year) \
+       ITEM(album) \
+       ITEM(comment) \
+       ITEM(mtime) \
+       ITEM(file_size) \
+       ITEM(chunk_time) \
+       ITEM(num_chunks) \
+       ITEM(amplification) \
 
-/**
- * Write a list of audio-file related status items with empty values.
- *
- * This is used by vss when currently no audio file is open.
+/*
+ * Create a set of audio-file related status items with empty values. These are
+ * written to stat clients when no audio file is open.
  */
 static unsigned empty_status_items(bool parser_friendly, char **result)
 {
@@ -520,9 +497,21 @@ static int com_stat(struct command_context *cc, struct lls_parse_result *lpr)
        bool parser_friendly = SERVER_CMD_OPT_GIVEN(STAT, PARSER_FRIENDLY,
                lpr) > 0;
        uint32_t num = SERVER_CMD_UINT32_VAL(STAT, NUM, lpr);
+       const struct timespec ts = {.tv_sec = 50, .tv_nsec = 0};
 
-       para_sigaction(SIGUSR1, dummy);
+       para_sigaction(SIGINT, SIG_IGN);
+       para_sigaction(SIGUSR1, command_handler_sighandler);
+       para_sigaction(SIGTERM, command_handler_sighandler);
+       /*
+        * Simply checking subcmd_should_die is racy because a signal may
+        * arrive after the check but before the subsequent call to sleep(3).
+        * If this happens, sleep(3) would not be interrupted by the signal.
+        * To avoid this we block SIGTERM here and allow it to arrive only
+        * while we sleep.
+        */
+       para_block_signal(SIGTERM);
        for (;;) {
+               sigset_t set;
                /*
                 * Copy the mmd structure to minimize the time we hold the mmd
                 * lock.
@@ -545,7 +534,15 @@ static int com_stat(struct command_context *cc, struct lls_parse_result *lpr)
                ret = 1;
                if (num > 0 && !--num)
                        goto out;
-               sleep(50);
+               sigemptyset(&set); /* empty set means: unblock all signals */
+               /*
+                * pselect(2) allows to atomically unblock signals, then go to
+                * sleep. Calling sigprocmask(2) followed by sleep(3) would
+                * open a race window similar to the one described above.
+                */
+               pselect(1, NULL, NULL, NULL, &ts, &set);
+               if (subcmd_should_die)
+                       goto out;
                ret = -E_SERVER_CRASH;
                if (getppid() == 1)
                        goto out;
@@ -584,21 +581,6 @@ static int send_list_of_commands(struct command_context *cc)
        return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
 }
 
-/* returns string that must be freed by the caller */
-static struct server_command *get_cmd_ptr(const char *name, char **handler)
-{
-       struct server_command *cmd;
-
-       /* not found, look for commands supported by afs */
-       for (cmd = afs_cmds; cmd->name; cmd++)
-               if (!strcmp(cmd->name, name)) {
-                       if (handler)
-                               *handler = para_strdup("afs");
-                       return cmd;
-               }
-       return NULL;
-}
-
 static int com_help(struct command_context *cc, struct lls_parse_result *lpr)
 {
        const char *perms;
@@ -782,25 +764,14 @@ out:
 }
 EXPORT_SERVER_CMD_HANDLER(jmp);
 
-static int com_tasks(struct command_context *cc,
+/* deprecated, does nothing */
+static int com_tasks(__a_unused struct command_context *cc,
                __a_unused struct lls_parse_result *lpr)
 {
-       char *tl = server_get_tasks();
-       assert(tl);
-       return send_sb(&cc->scc, tl, strlen(tl), SBD_OUTPUT, false);
+       return 1;
 }
 EXPORT_SERVER_CMD_HANDLER(tasks);
 
-/*
- * check if perms are sufficient to exec a command having perms cmd_perms.
- * Returns 0 if perms are sufficient, -E_PERM otherwise.
- */
-static int check_perms(unsigned int perms, const struct server_command *cmd_ptr)
-{
-       PARA_DEBUG_LOG("checking permissions\n");
-       return (cmd_ptr->perms & perms) < cmd_ptr->perms ? -E_PERM : 0;
-}
-
 static void reset_signals(void)
 {
        para_sigaction(SIGCHLD, SIG_IGN);
@@ -810,10 +781,10 @@ static void reset_signals(void)
 }
 
 struct connection_features {
-       bool aes_ctr128_requested;
+       int dummy; /* none at the moment */
 };
 
-static int parse_auth_request(char *buf, int len, struct user **u,
+static int parse_auth_request(char *buf, int len, const struct user **u,
                struct connection_features *cf)
 {
        int ret;
@@ -839,7 +810,7 @@ static int parse_auth_request(char *buf, int len, struct user **u,
                        if (strcmp(features[i], "sideband") == 0)
                                continue;
                        if (strcmp(features[i], "aes_ctr128") == 0)
-                               cf->aes_ctr128_requested = true;
+                               continue;
                        else {
                                ret = -E_BAD_FEATURE;
                                goto out;
@@ -847,7 +818,7 @@ static int parse_auth_request(char *buf, int len, struct user **u,
                }
        }
        PARA_DEBUG_LOG("received auth request for user %s\n", username);
-       *u = lookup_user(username);
+       *u = user_list_lookup(username);
        ret = 1;
 out:
        free_argv(features);
@@ -856,12 +827,10 @@ out:
 
 #define HANDSHAKE_BUFSIZE 4096
 
-static int run_command(struct command_context *cc, struct iovec *iov,
-               const char *peername)
+static int run_command(struct command_context *cc, struct iovec *iov)
 {
-       int ret, i;
-       char *p, *end;
-       struct server_command *cmd = NULL;
+       int ret, i, argc;
+       char *p, *end, **argv;
        const struct lls_command *lcmd = NULL;
        unsigned perms;
        struct lls_parse_result *lpr;
@@ -873,46 +842,34 @@ static int run_command(struct command_context *cc, struct iovec *iov,
        p[iov->iov_len - 1] = '\0'; /* just to be sure */
 
        ret = lls(lls_lookup_subcmd(p, server_cmd_suite, &errctx));
-       if (ret >= 0) {
-               perms = server_command_perms[ret];
-               if ((perms & cc->u->perms) != perms)
-                       return -E_PERM;
-               lcmd = lls_cmd(ret, server_cmd_suite);
-       } else {
-               cmd = get_cmd_ptr(p, NULL);
-               if (!cmd) {
-                       send_errctx(cc, errctx);
-                       return ret;
-               }
-               perms = cmd->perms;
-               ret = check_perms(cc->u->perms, cmd);
-               if (ret < 0)
-                       return ret;
+       if (ret < 0) {
+               send_errctx(cc, errctx);
+               return ret;
        }
+       perms = server_command_perms[ret];
+       if ((perms & cc->u->perms) != perms)
+               return -E_PERM;
+       lcmd = lls_cmd(ret, server_cmd_suite);
        end = iov->iov_base + iov->iov_len;
        for (i = 0; p < end; i++)
                p += strlen(p) + 1;
-       cc->argc = i;
-       cc->argv = para_malloc((cc->argc + 1) * sizeof(char *));
+       argc = i;
+       argv = para_malloc((argc + 1) * sizeof(char *));
        for (i = 0, p = iov->iov_base; p < end; i++) {
-               cc->argv[i] = para_strdup(p);
+               argv[i] = para_strdup(p);
                p += strlen(p) + 1;
        }
-       cc->argv[cc->argc] = NULL;
-       PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", lcmd?
-               lls_command_name(lcmd) : cmd->name, cc->u->name, peername);
-       if (lcmd) {
-               ret = lls(lls_parse(cc->argc, cc->argv, lcmd, &lpr, &errctx));
-               if (ret >= 0) {
-                       const struct server_cmd_user_data *ud = lls_user_data(lcmd);
-                       ret = ud->handler(cc, lpr);
-                       lls_free_parse_result(lpr, lcmd);
-               } else
-                       send_errctx(cc, errctx);
-       } else {
-               ret = cmd->handler(cc);
-       }
-       free_argv(cc->argv);
+       argv[argc] = NULL;
+       PARA_NOTICE_LOG("calling com_%s() for user %s\n",
+               lls_command_name(lcmd), cc->u->name);
+       ret = lls(lls_parse(argc, argv, lcmd, &lpr, &errctx));
+       if (ret >= 0) {
+               const struct server_cmd_user_data *ud = lls_user_data(lcmd);
+               ret = ud->handler(cc, lpr);
+               lls_free_parse_result(lpr, lcmd);
+       } else
+               send_errctx(cc, errctx);
+       free_argv(argv);
        mutex_lock(mmd_mutex);
        mmd->num_commands++;
        if (ret >= 0 && (perms & AFS_WRITE))
@@ -925,7 +882,6 @@ static int run_command(struct command_context *cc, struct iovec *iov,
  * Perform user authentication and execute a command.
  *
  * \param fd The file descriptor to send output to.
- * \param peername Identifies the connecting peer.
  *
  * Whenever para_server accepts an incoming tcp connection on the port it
  * listens on, it forks and the resulting child calls this function.
@@ -940,20 +896,20 @@ static int run_command(struct command_context *cc, struct iovec *iov,
  * permissions to execute that command, the function calls the corresponding
  * command handler which does argument checking and further processing.
  *
- * In order to cope with DOS attacks, a timeout is set up which terminates
+ * In order to cope with DOS attacks, a timeout is set up which terminates
  * the function if the connection was not authenticated when the timeout
  * expires.
  *
- * \sa alarm(2), crypt.c, crypt.h
+ * \sa alarm(2), \ref crypt.c, \ref crypt.h.
  */
-__noreturn void handle_connect(int fd, const char *peername)
+int handle_connect(int fd)
 {
        int ret;
        unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
        unsigned char challenge_hash[HASH_SIZE];
        char *command = NULL, *buf = para_malloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
        size_t numbytes;
-       struct command_context cc_struct = {.peer = peername}, *cc = &cc_struct;
+       struct command_context cc_struct = {.u = NULL}, *cc = &cc_struct;
        struct iovec iov;
        struct connection_features cf;
 
@@ -1023,17 +979,16 @@ __noreturn void handle_connect(int fd, const char *peername)
        alarm(0);
        PARA_INFO_LOG("good auth for %s\n", cc->u->name);
        /* init stream cipher keys with the second part of the random buffer */
-       cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN,
-               cf.aes_ctr128_requested);
+       cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
        cc->scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN,
-               SESSION_KEY_LEN, cf.aes_ctr128_requested);
+               SESSION_KEY_LEN);
        ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
        if (ret < 0)
                goto net_err;
        ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
        if (ret < 0)
                goto net_err;
-       ret = run_command(cc, &iov, peername);
+       ret = run_command(cc, &iov);
        free(iov.iov_base);
        if (ret < 0)
                goto err_out;
@@ -1057,5 +1012,5 @@ out:
        }
        sc_free(cc->scc.recv);
        sc_free(cc->scc.send);
-       exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
+       return ret;
 }