2 * Copyright (C) 1997-2012 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file command.c Client authentication and server commands. */
12 #include <sys/types.h>
19 #include "server.cmdline.h"
32 #include "user_list.h"
33 #include "server_command_list.h"
34 #include "afs_command_list.h"
38 /** Commands including options must be shorter than this. */
39 #define MAX_COMMAND_LEN 32768
42 extern struct misc_meta_data *mmd;
43 extern struct sender senders[];
44 int send_afs_status(struct command_context *cc, int parser_friendly);
46 const char *status_item_list[] = {STATUS_ITEM_ARRAY};
48 static void dummy(__a_unused int s)
52 static void mmd_dup(struct misc_meta_data *new_mmd)
54 mutex_lock(mmd_mutex);
56 mutex_unlock(mmd_mutex);
60 * Compute human readable string containing vss status for given integer value.
62 * We don't want to use vss_playing() and friends here because we take a
63 * snapshot of the mmd struct and use the copy for computing the state of the
64 * vss. If the real data were used, we would take the mmd lock for a rather
65 * long time or risk to get an inconsistent view.
67 static char *vss_status_tohuman(unsigned int flags)
69 if (flags & VSS_PLAYING)
70 return para_strdup("playing");
72 return para_strdup("stopped");
73 return para_strdup("paused");
77 * return human readable permission string. Never returns NULL.
79 static char *cmd_perms_itohuman(unsigned int perms)
81 char *msg = para_malloc(5 * sizeof(char));
83 msg[0] = perms & AFS_READ? 'a' : '-';
84 msg[1] = perms & AFS_WRITE? 'A' : '-';
85 msg[2] = perms & VSS_READ? 'v' : '-';
86 msg[3] = perms & VSS_WRITE? 'V' : '-';
94 static char *vss_get_status_flags(unsigned int flags)
96 char *msg = para_malloc(5 * sizeof(char));
98 msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
99 msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
100 msg[2] = (flags & VSS_NEXT)? 'N' : '_';
101 msg[3] = (flags & VSS_REPOS)? 'R' : '_';
106 static char *get_status(struct misc_meta_data *nmmd, int parser_friendly)
109 char *status, *flags; /* vss status info */
110 /* nobody updates our version of "now" */
111 char *ut = get_server_uptime_str(NULL);
112 long offset = (nmmd->offset + 500) / 1000;
113 struct timeval current_time;
115 struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
117 /* report real status */
118 status = vss_status_tohuman(nmmd->vss_status_flags);
119 flags = vss_get_status_flags(nmmd->vss_status_flags);
120 if (nmmd->size) { /* parent currently has an audio file open */
121 localtime_r(&nmmd->mtime, &mtime_tm);
122 strftime(mtime, 29, "%b %d %Y", &mtime_tm);
124 gettimeofday(¤t_time, NULL);
126 * The calls to WRITE_STATUS_ITEM() below never fail because
127 * b->max_size is zero (unlimited), see para_printf(). However, clang
128 * is not smart enough to prove this and complains nevertheless.
129 * Casting the return value to void silences clang.
131 (void)WRITE_STATUS_ITEM(&b, SI_FILE_SIZE, "%zu\n", nmmd->size / 1024);
132 (void)WRITE_STATUS_ITEM(&b, SI_MTIME, "%s\n", mtime);
133 (void)WRITE_STATUS_ITEM(&b, SI_STATUS, "%s\n", status);
134 (void)WRITE_STATUS_ITEM(&b, SI_STATUS_FLAGS, "%s\n", flags);
135 (void)WRITE_STATUS_ITEM(&b, SI_OFFSET, "%li\n", offset);
136 (void)WRITE_STATUS_ITEM(&b, SI_AFS_MODE, "%s\n", mmd->afs_mode_string);
137 (void)WRITE_STATUS_ITEM(&b, SI_STREAM_START, "%lu.%lu\n",
138 (long unsigned)nmmd->stream_start.tv_sec,
139 (long unsigned)nmmd->stream_start.tv_usec);
140 (void)WRITE_STATUS_ITEM(&b, SI_CURRENT_TIME, "%lu.%lu\n",
141 (long unsigned)current_time.tv_sec,
142 (long unsigned)current_time.tv_usec);
149 static int check_sender_args(int argc, char * const * argv, struct sender_command_data *scd)
152 /* this has to match sender.h */
153 const char *subcmds[] = {"add", "delete", "allow", "deny", "on", "off", NULL};
155 scd->sender_num = -1;
157 return -E_COMMAND_SYNTAX;
158 for (i = 0; senders[i].name; i++)
159 if (!strcmp(senders[i].name, argv[1]))
161 PARA_DEBUG_LOG("%d:%s\n", argc, argv[1]);
162 if (!senders[i].name)
163 return -E_COMMAND_SYNTAX;
165 for (i = 0; subcmds[i]; i++)
166 if (!strcmp(subcmds[i], argv[2]))
169 return -E_COMMAND_SYNTAX;
171 if (!senders[scd->sender_num].client_cmds[scd->cmd_num])
172 return -E_SENDER_CMD;
173 switch (scd->cmd_num) {
177 return -E_COMMAND_SYNTAX;
181 if (argc != 4 || parse_cidr(argv[3], scd->host,
182 sizeof(scd->host), &scd->netmask) == NULL)
183 return -E_COMMAND_SYNTAX;
188 return -E_COMMAND_SYNTAX;
189 return parse_fec_url(argv[3], scd);
191 return -E_COMMAND_SYNTAX;
196 int com_sender(struct command_context *cc)
200 struct sender_command_data scd;
203 for (i = 0; senders[i].name; i++) {
204 char *tmp = make_message("%s%s\n",
205 msg? msg : "", senders[i].name);
209 ret = sc_send_buffer(&cc->scc, msg);
213 ret = check_sender_args(cc->argc, cc->argv, &scd);
215 if (scd.sender_num < 0)
217 msg = senders[scd.sender_num].help();
218 ret = sc_send_buffer(&cc->scc, msg);
223 switch (scd.cmd_num) {
226 assert(senders[scd.sender_num].resolve_target);
227 ret = senders[scd.sender_num].resolve_target(cc->argv[3], &scd);
232 for (i = 0; i < 10; i++) {
233 mutex_lock(mmd_mutex);
234 if (mmd->sender_cmd_data.cmd_num >= 0) {
235 mutex_unlock(mmd_mutex);
239 memcpy(&mmd->sender_cmd_data, &scd, sizeof(scd));
240 mutex_unlock(mmd_mutex);
243 return (i < 10)? 1 : -E_LOCK;
247 int com_si(struct command_context *cc)
251 char *sender_info = NULL;
254 return -E_COMMAND_SYNTAX;
255 mutex_lock(mmd_mutex);
256 for (i = 0; senders[i].name; i++) {
257 char *info = senders[i].info();
258 sender_info = para_strcat(sender_info, info);
261 ut = get_server_uptime_str(now);
262 ret = sc_send_va_buffer(&cc->scc, "version: " GIT_VERSION "\n"
263 "up: %s\nplayed: %u\n"
266 "connections (active/accepted/total): %u/%u/%u\n"
267 "current loglevel: %s\n"
268 "supported audio formats: %s\n"
273 mmd->active_connections,
277 SERVER_AUDIO_FORMATS,
280 mutex_unlock(mmd_mutex);
287 int com_version(struct command_context *cc)
290 return -E_COMMAND_SYNTAX;
291 return sc_send_buffer(&cc->scc, VERSION_TEXT("server")
292 "built: " BUILD_DATE "\n"
293 UNAME_RS ", " CC_VERSION "\n"
297 #define EMPTY_STATUS_ITEMS \
302 ITEM(ATTRIBUTES_BITMAP) \
303 ITEM(ATTRIBUTES_TXT) \
314 ITEM(SECONDS_TOTAL) \
326 * Write a list of audio-file related status items with empty values.
328 * This is used by vss when currently no audio file is open.
330 static char *empty_status_items(int parser_friendly)
334 #define ITEM(x) "0004 %02x:\n"
337 #define ITEM(x) , SI_ ## x
342 #define ITEM(x) "%s:\n"
345 #define ITEM(x) ,status_item_list[SI_ ## x]
350 #undef EMPTY_STATUS_ITEMS
353 int com_stat(struct command_context *cc)
356 struct misc_meta_data tmp, *nmmd = &tmp;
359 int parser_friendly = 0;
361 para_sigaction(SIGUSR1, dummy);
363 for (i = 1; i < cc->argc; i++) {
364 const char *arg = cc->argv[i];
367 if (!strcmp(arg, "--")) {
371 if (!strncmp(arg, "-n=", 3)) {
372 ret = para_atoi32(arg + 3, &num);
377 if (!strcmp(arg, "-p")) {
381 return -E_COMMAND_SYNTAX;
384 return -E_COMMAND_SYNTAX;
387 s = get_status(nmmd, parser_friendly);
388 ret = sc_send_buffer(&cc->scc, s);
392 if (nmmd->vss_status_flags & VSS_NEXT) {
395 esi = empty_status_items(parser_friendly);
396 ret = sc_send_buffer(&cc->scc, esi);
400 send_afs_status(cc, parser_friendly);
402 if (num > 0 && !--num)
406 return -E_SERVER_CRASH;
412 static int send_list_of_commands(struct stream_cipher_context *scc, struct server_command *cmd,
417 for (i = 1; cmd->name; cmd++, i++) {
418 char *perms = cmd_perms_itohuman(cmd->perms);
419 ret = sc_send_va_buffer(scc, "%s\t%s\t%s\t%s\n", cmd->name,
430 /* returns string that must be freed by the caller */
431 static struct server_command *get_cmd_ptr(const char *name, char **handler)
433 struct server_command *cmd;
435 for (cmd = server_cmds; cmd->name; cmd++)
436 if (!strcmp(cmd->name, name)) {
438 *handler = para_strdup("server"); /* server commands */
441 /* not found, look for commands supported by afs */
442 for (cmd = afs_cmds; cmd->name; cmd++)
443 if (!strcmp(cmd->name, name)) {
445 *handler = para_strdup("afs");
452 int com_help(struct command_context *cc)
454 struct server_command *cmd;
455 char *perms, *handler;
459 /* no argument given, print list of commands */
460 if ((ret = send_list_of_commands(&cc->scc, server_cmds, "server")) < 0)
462 return send_list_of_commands(&cc->scc, afs_cmds, "afs");
464 /* argument given for help */
465 cmd = get_cmd_ptr(cc->argv[1], &handler);
468 perms = cmd_perms_itohuman(cmd->perms);
469 ret = sc_send_va_buffer(&cc->scc,
488 int com_hup(struct command_context *cc)
491 return -E_COMMAND_SYNTAX;
492 kill(getppid(), SIGHUP);
497 int com_term(struct command_context *cc)
500 return -E_COMMAND_SYNTAX;
501 kill(getppid(), SIGTERM);
505 int com_play(struct command_context *cc)
508 return -E_COMMAND_SYNTAX;
509 mutex_lock(mmd_mutex);
510 mmd->new_vss_status_flags |= VSS_PLAYING;
511 mmd->new_vss_status_flags &= ~VSS_NOMORE;
512 mutex_unlock(mmd_mutex);
517 int com_stop(struct command_context *cc)
520 return -E_COMMAND_SYNTAX;
521 mutex_lock(mmd_mutex);
522 mmd->new_vss_status_flags &= ~VSS_PLAYING;
523 mmd->new_vss_status_flags &= ~VSS_REPOS;
524 mmd->new_vss_status_flags |= VSS_NEXT;
525 mutex_unlock(mmd_mutex);
530 int com_pause(struct command_context *cc)
533 return -E_COMMAND_SYNTAX;
534 mutex_lock(mmd_mutex);
535 if (!vss_paused() && !vss_stopped()) {
537 mmd->new_vss_status_flags &= ~VSS_PLAYING;
538 mmd->new_vss_status_flags &= ~VSS_NEXT;
540 mutex_unlock(mmd_mutex);
545 int com_next(struct command_context *cc)
548 return -E_COMMAND_SYNTAX;
549 mutex_lock(mmd_mutex);
551 mmd->new_vss_status_flags |= VSS_NEXT;
552 mutex_unlock(mmd_mutex);
557 int com_nomore(struct command_context *cc)
560 return -E_COMMAND_SYNTAX;
561 mutex_lock(mmd_mutex);
562 if (vss_playing() || vss_paused())
563 mmd->new_vss_status_flags |= VSS_NOMORE;
564 mutex_unlock(mmd_mutex);
569 int com_ff(struct command_context *cc)
572 int ret, backwards = 0;
577 return -E_COMMAND_SYNTAX;
578 if (!(ret = sscanf(cc->argv[1], "%u%c", &i, &c)))
579 return -E_COMMAND_SYNTAX;
580 if (ret > 1 && c == '-')
581 backwards = 1; /* jmp backwards */
582 mutex_lock(mmd_mutex);
583 ret = -E_NO_AUDIO_FILE;
584 if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
586 promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
588 promille -= 1000 * i / mmd->afd.afhi.seconds_total;
590 promille += 1000 * i / mmd->afd.afhi.seconds_total;
593 if (promille > 1000) {
594 mmd->new_vss_status_flags |= VSS_NEXT;
597 mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
598 mmd->new_vss_status_flags |= VSS_REPOS;
599 mmd->new_vss_status_flags &= ~VSS_NEXT;
603 mutex_unlock(mmd_mutex);
608 int com_jmp(struct command_context *cc)
614 return -E_COMMAND_SYNTAX;
615 if (sscanf(cc->argv[1], "%lu", &i) <= 0)
616 return -E_COMMAND_SYNTAX;
617 mutex_lock(mmd_mutex);
618 ret = -E_NO_AUDIO_FILE;
619 if (!mmd->afd.afhi.chunks_total)
623 PARA_INFO_LOG("jumping to %lu%%\n", i);
624 mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50)/ 100;
625 PARA_INFO_LOG("sent: %lu, offset before jmp: %lu\n",
626 mmd->chunks_sent, mmd->offset);
627 mmd->new_vss_status_flags |= VSS_REPOS;
628 mmd->new_vss_status_flags &= ~VSS_NEXT;
632 mutex_unlock(mmd_mutex);
637 * check if perms are sufficient to exec a command having perms cmd_perms.
638 * Returns 0 if perms are sufficient, -E_PERM otherwise.
640 static int check_perms(unsigned int perms, struct server_command *cmd_ptr)
642 PARA_DEBUG_LOG("checking permissions\n");
643 return (cmd_ptr->perms & perms) < cmd_ptr->perms ? -E_PERM : 0;
647 * Parse first string from *cmd and lookup in table of valid commands.
648 * On error, NULL is returned.
650 static struct server_command *parse_cmd(const char *cmdstr)
655 sscanf(cmdstr, "%200s%n", buf, &n);
659 return get_cmd_ptr(buf, NULL);
662 static int read_command(struct stream_cipher_context *scc, char **result)
666 char *command = NULL;
672 ret = sc_recv_buffer(scc, buf, sizeof(buf));
678 ret = -E_COMMAND_SYNTAX;
679 if (command && numbytes + strlen(command) > MAX_COMMAND_LEN) /* DOS */
681 command = para_strcat(command, buf);
682 p = strstr(command, EOC_MSG);
688 ret = command? 1 : -E_COMMAND_SYNTAX;
698 static void reset_signals(void)
700 para_sigaction(SIGCHLD, SIG_IGN);
701 para_sigaction(SIGINT, SIG_DFL);
702 para_sigaction(SIGTERM, SIG_DFL);
703 para_sigaction(SIGHUP, SIG_DFL);
707 * Perform user authentication and execute a command.
709 * \param fd The file descriptor to send output to.
710 * \param peername Identifies the connecting peer.
712 * Whenever para_server accepts an incoming tcp connection on
713 * the port it listens on, it forks and the resulting child
714 * calls this function.
716 * An RSA-based challenge/response is used to authenticate
717 * the peer. It that authentication succeeds, a random
718 * session key is generated and sent back to the peer,
719 * encrypted with its RSA public key. From this point on,
720 * all transfers are crypted with this session key.
722 * Next it is checked if the peer supplied a valid server command or a command
723 * for the audio file selector. If yes, and if the user has sufficient
724 * permissions to execute that command, the function calls the corresponding
725 * command handler which does argument checking and further processing.
727 * In order to cope with a DOS attacks, a timeout is set up
728 * which terminates the function if the connection was not
729 * authenticated when the timeout expires.
731 * \sa alarm(2), crypt.c, crypt.h
733 __noreturn void handle_connect(int fd, const char *peername)
737 unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
738 unsigned char challenge_hash[HASH_SIZE];
739 char *p, *command = NULL;
741 struct command_context cc_struct = {.peer = peername}, *cc = &cc_struct;
745 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
746 ret = mark_fd_blocking(fd);
749 /* send Welcome message */
750 ret = write_va_buffer(fd, "This is para_server, version "
751 PACKAGE_VERSION ".\n" );
754 /* recv auth request line */
755 ret = recv_buffer(fd, buf, sizeof(buf));
759 ret = -E_AUTH_REQUEST;
762 ret = -E_AUTH_REQUEST;
763 if (strncmp(buf, AUTH_REQUEST_MSG, strlen(AUTH_REQUEST_MSG)))
765 p = buf + strlen(AUTH_REQUEST_MSG);
766 PARA_DEBUG_LOG("received auth request for user %s\n", p);
767 cc->u = lookup_user(p);
769 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
770 ret = pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
771 (unsigned char *)buf);
777 * We don't want to reveal our user names, so we send a
778 * challenge to the client even if the user does not exist, and
779 * fail the authentication later.
782 get_random_bytes_or_die((unsigned char *)buf, numbytes);
784 PARA_DEBUG_LOG("sending %u byte challenge + rc4 keys (%zu bytes)\n",
785 CHALLENGE_SIZE, numbytes);
786 ret = write_all(fd, buf, numbytes);
789 /* recv challenge response */
790 ret = recv_bin_buffer(fd, buf, HASH_SIZE);
794 PARA_DEBUG_LOG("received %d bytes challenge response\n", ret);
799 * The correct response is the hash of the first CHALLENGE_SIZE bytes
800 * of the random data.
803 if (numbytes != HASH_SIZE)
805 hash_function((char *)rand_buf, CHALLENGE_SIZE, challenge_hash);
806 if (memcmp(challenge_hash, buf, HASH_SIZE))
808 /* auth successful */
810 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
811 /* init stream cipher keys with the second part of the random buffer */
812 cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
813 cc->scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN, SESSION_KEY_LEN);
814 ret = sc_send_buffer(&cc->scc, PROCEED_MSG);
817 ret = read_command(&cc->scc, &command);
818 if (ret == -E_COMMAND_SYNTAX)
823 cc->cmd = parse_cmd(command);
826 /* valid command, check permissions */
827 ret = check_perms(cc->u->perms, cc->cmd);
830 /* valid command and sufficient perms */
831 ret = create_argv(command, "\n", &cc->argv);
835 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cc->cmd->name,
836 cc->u->name, peername);
837 ret = cc->cmd->handler(cc);
839 mutex_lock(mmd_mutex);
841 mutex_unlock(mmd_mutex);
845 sc_send_va_buffer(&cc->scc, "%s\n", para_strerror(-ret));
847 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
850 sc_free(cc->scc.recv);
851 sc_free(cc->scc.send);
852 mutex_lock(mmd_mutex);
853 if (cc->cmd && (cc->cmd->perms & AFS_WRITE) && ret >= 0)
855 mmd->active_connections--;
856 mutex_unlock(mmd_mutex);
857 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);