Merge branch 't/clang'
[paraslash.git] / command.c
1 /*
2  * Copyright (C) 1997-2012 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file command.c Client authentication and server commands. */
8
9 #include <regex.h>
10 #include <signal.h>
11 #include <sys/time.h>
12 #include <sys/types.h>
13 #include <osl.h>
14
15 #include "para.h"
16 #include "error.h"
17 #include "crypt.h"
18 #include "sideband.h"
19 #include "command.h"
20 #include "server.cmdline.h"
21 #include "string.h"
22 #include "afh.h"
23 #include "afs.h"
24 #include "server.h"
25 #include "list.h"
26 #include "send.h"
27 #include "sched.h"
28 #include "vss.h"
29 #include "net.h"
30 #include "daemon.h"
31 #include "fd.h"
32 #include "ipc.h"
33 #include "user_list.h"
34 #include "server_command_list.h"
35 #include "afs_command_list.h"
36 #include "signal.h"
37 #include "version.h"
38
39 struct server_command afs_cmds[] = {DEFINE_AFS_CMD_ARRAY};
40 struct server_command server_cmds[] = {DEFINE_SERVER_CMD_ARRAY};
41
42 /** Commands including options must be shorter than this. */
43 #define MAX_COMMAND_LEN 32768
44
45 extern int mmd_mutex;
46 extern struct misc_meta_data *mmd;
47 extern struct sender senders[];
48 int send_afs_status(struct command_context *cc, int parser_friendly);
49
50 static void dummy(__a_unused int s)
51 {
52 }
53
54 static void mmd_dup(struct misc_meta_data *new_mmd)
55 {
56         mutex_lock(mmd_mutex);
57         *new_mmd = *mmd;
58         mutex_unlock(mmd_mutex);
59 }
60
61 /*
62  * Compute human readable string containing vss status for given integer value.
63  *
64  * We don't want to use vss_playing() and friends here because we take a
65  * snapshot of the mmd struct and use the copy for computing the state of the
66  * vss. If the real data were used, we would take the mmd lock for a rather
67  * long time or risk to get an inconsistent view.
68  */
69 static char *vss_status_tohuman(unsigned int flags)
70 {
71         if (flags & VSS_PLAYING)
72                 return para_strdup("playing");
73         if (flags & VSS_NEXT)
74                 return para_strdup("stopped");
75         return para_strdup("paused");
76 }
77
78 /*
79  * return human readable permission string. Never returns NULL.
80  */
81 static char *cmd_perms_itohuman(unsigned int perms)
82 {
83         char *msg = para_malloc(5 * sizeof(char));
84
85         msg[0] = perms & AFS_READ? 'a' : '-';
86         msg[1] = perms & AFS_WRITE? 'A' : '-';
87         msg[2] = perms & VSS_READ? 'v' : '-';
88         msg[3] = perms & VSS_WRITE? 'V' : '-';
89         msg[4] = '\0';
90         return msg;
91 }
92
93 /*
94  * Never returns NULL.
95  */
96 static char *vss_get_status_flags(unsigned int flags)
97 {
98         char *msg = para_malloc(5 * sizeof(char));
99
100         msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
101         msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
102         msg[2] = (flags & VSS_NEXT)? 'N' : '_';
103         msg[3] = (flags & VSS_REPOS)? 'R' : '_';
104         msg[4] = '\0';
105         return msg;
106 }
107
108 static unsigned get_status(struct misc_meta_data *nmmd, int parser_friendly,
109                 char **result)
110 {
111         char mtime[30] = "";
112         char *status, *flags; /* vss status info */
113         /* nobody updates our version of "now" */
114         char *ut = get_server_uptime_str(NULL);
115         long offset = (nmmd->offset + 500) / 1000;
116         struct timeval current_time;
117         struct tm mtime_tm;
118         struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
119
120         /* report real status */
121         status = vss_status_tohuman(nmmd->vss_status_flags);
122         flags = vss_get_status_flags(nmmd->vss_status_flags);
123         if (nmmd->size) { /* parent currently has an audio file open */
124                 localtime_r(&nmmd->mtime, &mtime_tm);
125                 strftime(mtime, 29, "%b %d %Y", &mtime_tm);
126         }
127         gettimeofday(&current_time, NULL);
128         /*
129          * The calls to WRITE_STATUS_ITEM() below never fail because
130          * b->max_size is zero (unlimited), see para_printf(). However, clang
131          * is not smart enough to prove this and complains nevertheless.
132          * Casting the return value to void silences clang.
133          */
134         (void)WRITE_STATUS_ITEM(&b, SI_FILE_SIZE, "%zu\n", nmmd->size / 1024);
135         (void)WRITE_STATUS_ITEM(&b, SI_MTIME, "%s\n", mtime);
136         (void)WRITE_STATUS_ITEM(&b, SI_STATUS, "%s\n", status);
137         (void)WRITE_STATUS_ITEM(&b, SI_STATUS_FLAGS, "%s\n", flags);
138         (void)WRITE_STATUS_ITEM(&b, SI_OFFSET, "%li\n", offset);
139         (void)WRITE_STATUS_ITEM(&b, SI_AFS_MODE, "%s\n", mmd->afs_mode_string);
140         (void)WRITE_STATUS_ITEM(&b, SI_STREAM_START, "%lu.%lu\n",
141                 (long unsigned)nmmd->stream_start.tv_sec,
142                 (long unsigned)nmmd->stream_start.tv_usec);
143         (void)WRITE_STATUS_ITEM(&b, SI_CURRENT_TIME, "%lu.%lu\n",
144                 (long unsigned)current_time.tv_sec,
145                 (long unsigned)current_time.tv_usec);
146         free(flags);
147         free(status);
148         free(ut);
149         *result = b.buf;
150         return b.offset;
151 }
152
153 static int check_sender_args(int argc, char * const * argv, struct sender_command_data *scd)
154 {
155         int i;
156         /* this has to match sender.h */
157         const char *subcmds[] = {"add", "delete", "allow", "deny", "on", "off", NULL};
158
159         scd->sender_num = -1;
160         if (argc < 2)
161                 return -E_COMMAND_SYNTAX;
162         for (i = 0; senders[i].name; i++)
163                 if (!strcmp(senders[i].name, argv[1]))
164                         break;
165         PARA_DEBUG_LOG("%d:%s\n", argc, argv[1]);
166         if (!senders[i].name)
167                 return -E_COMMAND_SYNTAX;
168         scd->sender_num = i;
169         for (i = 0; subcmds[i]; i++)
170                 if (!strcmp(subcmds[i], argv[2]))
171                         break;
172         if (!subcmds[i])
173                 return -E_COMMAND_SYNTAX;
174         scd->cmd_num = i;
175         if (!senders[scd->sender_num].client_cmds[scd->cmd_num])
176                 return -E_SENDER_CMD;
177         switch (scd->cmd_num) {
178         case SENDER_ON:
179         case SENDER_OFF:
180                 if (argc != 3)
181                         return -E_COMMAND_SYNTAX;
182                 break;
183         case SENDER_DENY:
184         case SENDER_ALLOW:
185                 if (argc != 4 || parse_cidr(argv[3], scd->host,
186                                 sizeof(scd->host), &scd->netmask) == NULL)
187                         return -E_COMMAND_SYNTAX;
188                 break;
189         case SENDER_ADD:
190         case SENDER_DELETE:
191                 if (argc != 4)
192                         return -E_COMMAND_SYNTAX;
193                 return parse_fec_url(argv[3], scd);
194         default:
195                 return -E_COMMAND_SYNTAX;
196         }
197         return 1;
198 }
199
200 /**
201  * Send a sideband packet through a blocking file descriptor.
202  *
203  * \param scc fd and crypto keys.
204  * \param buf The buffer to send.
205  * \param numbytes The size of \a buf.
206  * \param band The sideband designator of this packet.
207  * \param dont_free If true, never deallocate \a buf.
208  *
209  * The nonblock flag must be disabled for the file descriptor given by \a scc.
210  *
211  * Stream cipher encryption is automatically activated if neccessary via the
212  * sideband transformation, depending on the value of \a band.
213  *
214  * \return Standard.
215  *
216  * \sa \ref send_sb_va().
217  */
218 int send_sb(struct stream_cipher_context *scc, void *buf, size_t numbytes,
219                 int band, bool dont_free)
220 {
221         int ret;
222         struct sb_context *sbc;
223         struct iovec iov[2];
224         struct sb_buffer sbb = SBB_INIT(band, buf, numbytes);
225         sb_transformation trafo = band < SBD_PROCEED? NULL : sc_trafo;
226
227         sbc = sb_new_send(&sbb, dont_free, trafo, scc->send);
228         do {
229                 ret = sb_get_send_buffers(sbc, iov);
230                 ret = xwritev(scc->fd, iov, ret);
231                 if (ret < 0)
232                         goto fail;
233         } while (sb_sent(sbc, ret) == false);
234         return 1;
235 fail:
236         sb_free(sbc);
237         return ret;
238 }
239
240 /**
241  * Create a variable sized buffer and send it as a sideband packet.
242  *
243  * \param scc Passed to \ref send_sb.
244  * \param band See \ref send_sb.
245  * \param fmt The format string.
246  *
247  * \return The return value of the underlying call to \ref send_sb.
248  */
249 __printf_3_4 int send_sb_va(struct stream_cipher_context *scc, int band,
250                 const char *fmt, ...)
251 {
252         va_list ap;
253         char *msg;
254         int ret;
255
256         va_start(ap, fmt);
257         ret = xvasprintf(&msg, fmt, ap);
258         va_end(ap);
259         return send_sb(scc, msg, ret, band, false);
260 }
261
262 int send_strerror(struct command_context *cc, int err)
263 {
264         return cc->use_sideband?
265                 send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", para_strerror(err))
266         :
267                 sc_send_va_buffer(&cc->scc, "%s\n", para_strerror(err));
268 }
269
270 /**
271  * Send a sideband packet through a blocking file descriptor.
272  *
273  * \param scc fd and crypto keys.
274  * \param expected_band The expected band designator.
275  * \param max_size Passed to \ref sb_new_recv().
276  * \param result Body of the sideband packet is returned here.
277  *
278  * If \a expected_band is not \p SBD_ANY, the band designator of the received
279  * sideband packet is compared to \a expected_band and a mismatch is considered
280  * an error.
281  *
282  * \return Standard.
283  */
284 int recv_sb(struct stream_cipher_context *scc,
285                 enum sb_designator expected_band,
286                 size_t max_size, struct iovec *result)
287 {
288         int ret;
289         struct sb_context *sbc;
290         struct iovec iov;
291         struct sb_buffer sbb;
292         sb_transformation trafo;
293
294         trafo = expected_band != SBD_ANY && expected_band < SBD_PROCEED?
295                 NULL : sc_trafo;
296         sbc = sb_new_recv(max_size, trafo, scc->recv);
297         for (;;) {
298                 sb_get_recv_buffer(sbc, &iov);
299                 ret = recv_bin_buffer(scc->fd, iov.iov_base, iov.iov_len);
300                 if (ret == 0)
301                         ret = -E_EOF;
302                 if (ret < 0)
303                         goto fail;
304                 ret = sb_received(sbc, ret, &sbb);
305                 if (ret < 0)
306                         goto fail;
307                 if (ret > 0)
308                         break;
309         }
310         ret = -E_BAD_BAND;
311         if (expected_band != SBD_ANY && sbb.band != expected_band)
312                 goto fail;
313         *result = sbb.iov;
314         return 1;
315 fail:
316         sb_free(sbc);
317         return ret;
318 }
319
320 static int com_sender(struct command_context *cc)
321 {
322         int i, ret = 0;
323         char *msg = NULL;
324         struct sender_command_data scd;
325
326         if (cc->argc < 2) {
327                 for (i = 0; senders[i].name; i++) {
328                         char *tmp;
329                         ret = xasprintf(&tmp, "%s%s\n", msg? msg : "",
330                                 senders[i].name);
331                         free(msg);
332                         msg = tmp;
333                 }
334                 if (cc->use_sideband)
335                         return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
336                 ret = sc_send_buffer(&cc->scc, msg);
337                 free(msg);
338                 return ret;
339         }
340         ret = check_sender_args(cc->argc, cc->argv, &scd);
341         if (ret < 0) {
342                 if (scd.sender_num < 0)
343                         return ret;
344                 msg = senders[scd.sender_num].help();
345                 if (cc->use_sideband)
346                         return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT,
347                                 false);
348                 ret = sc_send_buffer(&cc->scc, msg);
349                 free(msg);
350                 return ret;
351         }
352
353         switch (scd.cmd_num) {
354         case SENDER_ADD:
355         case SENDER_DELETE:
356                 assert(senders[scd.sender_num].resolve_target);
357                 ret = senders[scd.sender_num].resolve_target(cc->argv[3], &scd);
358                 if (ret < 0)
359                         return ret;
360         }
361
362         for (i = 0; i < 10; i++) {
363                 mutex_lock(mmd_mutex);
364                 if (mmd->sender_cmd_data.cmd_num >= 0) {
365                         mutex_unlock(mmd_mutex);
366                         usleep(100 * 1000);
367                         continue;
368                 }
369                 memcpy(&mmd->sender_cmd_data, &scd, sizeof(scd));
370                 mutex_unlock(mmd_mutex);
371                 break;
372         }
373         return (i < 10)? 1 : -E_LOCK;
374 }
375
376 /* server info */
377 static int com_si(struct command_context *cc)
378 {
379         int i, ret;
380         char *msg, *ut, *sender_info = NULL;
381
382         if (cc->argc != 1)
383                 return -E_COMMAND_SYNTAX;
384         mutex_lock(mmd_mutex);
385         for (i = 0; senders[i].name; i++) {
386                 char *info = senders[i].info();
387                 sender_info = para_strcat(sender_info, info);
388                 free(info);
389         }
390         ut = get_server_uptime_str(now);
391         ret = xasprintf(&msg, "version: " GIT_VERSION "\n"
392                 "up: %s\nplayed: %u\n"
393                 "server_pid: %d\n"
394                 "afs_pid: %d\n"
395                 "connections (active/accepted/total): %u/%u/%u\n"
396                 "current loglevel: %s\n"
397                 "supported audio formats: %s\n"
398                 "%s",
399                 ut, mmd->num_played,
400                 (int)getppid(),
401                 (int)mmd->afs_pid,
402                 mmd->active_connections,
403                 mmd->num_commands,
404                 mmd->num_connects,
405                 conf.loglevel_arg,
406                 SERVER_AUDIO_FORMATS,
407                 sender_info
408         );
409         mutex_unlock(mmd_mutex);
410         free(ut);
411         free(sender_info);
412         if (cc->use_sideband)
413                 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
414         ret = sc_send_bin_buffer(&cc->scc, msg, ret);
415         free(msg);
416         return ret;
417 }
418
419 /* version */
420 static int com_version(struct command_context *cc)
421 {
422         char *msg;
423         size_t len;
424
425         if (cc->argc != 1)
426                 return -E_COMMAND_SYNTAX;
427         msg = VERSION_TEXT("server") "built: " BUILD_DATE "\n" UNAME_RS
428                 ", " CC_VERSION "\n";
429         len = strlen(msg);
430         if (cc->use_sideband)
431                 return send_sb(&cc->scc, msg, len, SBD_OUTPUT, true);
432         return sc_send_bin_buffer(&cc->scc, msg, len);
433 }
434
435 #define EMPTY_STATUS_ITEMS \
436         ITEM(PATH) \
437         ITEM(DIRECTORY) \
438         ITEM(BASENAME) \
439         ITEM(SCORE) \
440         ITEM(ATTRIBUTES_BITMAP) \
441         ITEM(ATTRIBUTES_TXT) \
442         ITEM(HASH) \
443         ITEM(IMAGE_ID) \
444         ITEM(IMAGE_NAME) \
445         ITEM(LYRICS_ID) \
446         ITEM(LYRICS_NAME) \
447         ITEM(BITRATE) \
448         ITEM(FORMAT) \
449         ITEM(FREQUENCY) \
450         ITEM(CHANNELS) \
451         ITEM(DURATION) \
452         ITEM(SECONDS_TOTAL) \
453         ITEM(NUM_PLAYED) \
454         ITEM(LAST_PLAYED) \
455         ITEM(TECHINFO) \
456         ITEM(ARTIST) \
457         ITEM(TITLE) \
458         ITEM(YEAR) \
459         ITEM(ALBUM) \
460         ITEM(COMMENT) \
461         ITEM(AMPLIFICATION)
462
463 /**
464  * Write a list of audio-file related status items with empty values.
465  *
466  * This is used by vss when currently no audio file is open.
467  */
468 static unsigned empty_status_items(int parser_friendly, char **result)
469 {
470         static char *esi;
471         static unsigned len;
472
473         if (esi)
474                 goto out;
475
476         if (parser_friendly)
477                 len = xasprintf(&esi,
478                         #define ITEM(x) "0004 %02x:\n"
479                         EMPTY_STATUS_ITEMS
480                         #undef ITEM
481                         #define ITEM(x) , SI_ ## x
482                         EMPTY_STATUS_ITEMS
483                         #undef ITEM
484                 );
485         else
486                 len = xasprintf(&esi,
487                         #define ITEM(x) "%s:\n"
488                         EMPTY_STATUS_ITEMS
489                         #undef ITEM
490                         #define ITEM(x) ,status_item_list[SI_ ## x]
491                         EMPTY_STATUS_ITEMS
492                         #undef ITEM
493                 );
494 out:
495         *result = esi;
496         return len;
497 }
498 #undef EMPTY_STATUS_ITEMS
499
500 /* stat */
501 static int com_stat(struct command_context *cc)
502 {
503         int i, ret;
504         struct misc_meta_data tmp, *nmmd = &tmp;
505         char *s, *esi = NULL;
506         int32_t num = 0;
507         int parser_friendly = 0;
508
509         para_sigaction(SIGUSR1, dummy);
510
511         for (i = 1; i < cc->argc; i++) {
512                 const char *arg = cc->argv[i];
513                 if (arg[0] != '-')
514                         break;
515                 if (!strcmp(arg, "--")) {
516                         i++;
517                         break;
518                 }
519                 if (!strncmp(arg, "-n=", 3)) {
520                         ret = para_atoi32(arg + 3, &num);
521                         if (ret < 0)
522                                 return ret;
523                         continue;
524                 }
525                 if (!strcmp(arg, "-p")) {
526                         parser_friendly = 1;
527                         continue;
528                 }
529                 return -E_COMMAND_SYNTAX;
530         }
531         if (i != cc->argc)
532                 return -E_COMMAND_SYNTAX;
533         for (;;) {
534                 mmd_dup(nmmd);
535                 ret = get_status(nmmd, parser_friendly, &s);
536                 if (cc->use_sideband)
537                         ret = send_sb(&cc->scc, s, ret, SBD_OUTPUT, false);
538                 else {
539                         ret = sc_send_bin_buffer(&cc->scc, s, ret);
540                         free(s);
541                 }
542                 if (ret < 0)
543                         goto out;
544                 if (nmmd->vss_status_flags & VSS_NEXT) {
545                         ret = empty_status_items(parser_friendly, &esi);
546                         if (cc->use_sideband)
547                                 ret = send_sb(&cc->scc, esi, ret, SBD_OUTPUT,
548                                         true);
549                         else
550                                 ret = sc_send_bin_buffer(&cc->scc, esi, ret);
551                         if (ret < 0)
552                                 goto out;
553                 } else
554                         send_afs_status(cc, parser_friendly);
555                 ret = 1;
556                 if (num > 0 && !--num)
557                         goto out;
558                 sleep(50);
559                 ret = -E_SERVER_CRASH;
560                 if (getppid() == 1)
561                         goto out;
562         }
563 out:
564         free(esi);
565         return ret;
566 }
567
568 static int send_list_of_commands(struct command_context *cc, struct server_command *cmd,
569                 const char *handler)
570 {
571         int ret;
572         char *msg = NULL;
573
574         for (; cmd->name; cmd++) {
575                 char *tmp, *perms = cmd_perms_itohuman(cmd->perms);
576                 tmp = make_message("%s\t%s\t%s\t%s\n", cmd->name, handler,
577                         perms, cmd->description);
578                 free(perms);
579                 msg = para_strcat(msg, tmp);
580                 free(tmp);
581         }
582         if (cc->use_sideband)
583                 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
584         ret = sc_send_buffer(&cc->scc, msg);
585         free(msg);
586         return ret;
587 }
588
589 /* returns string that must be freed by the caller */
590 static struct server_command *get_cmd_ptr(const char *name, char **handler)
591 {
592         struct server_command *cmd;
593
594         for (cmd = server_cmds; cmd->name; cmd++)
595                 if (!strcmp(cmd->name, name)) {
596                         if (handler)
597                                 *handler = para_strdup("server"); /* server commands */
598                         return cmd;
599                 }
600         /* not found, look for commands supported by afs */
601         for (cmd = afs_cmds; cmd->name; cmd++)
602                 if (!strcmp(cmd->name, name)) {
603                         if (handler)
604                                 *handler = para_strdup("afs");
605                         return cmd;
606                 }
607         return NULL;
608 }
609
610 /* help */
611 static int com_help(struct command_context *cc)
612 {
613         struct server_command *cmd;
614         char *perms, *handler, *buf;
615         int ret;
616
617         if (cc->argc < 2) {
618                 /* no argument given, print list of commands */
619                 if ((ret = send_list_of_commands(cc, server_cmds, "server")) < 0)
620                         return ret;
621                 return send_list_of_commands(cc, afs_cmds, "afs");
622         }
623         /* argument given for help */
624         cmd = get_cmd_ptr(cc->argv[1], &handler);
625         if (!cmd)
626                 return -E_BAD_CMD;
627         perms = cmd_perms_itohuman(cmd->perms);
628         ret = xasprintf(&buf, "%s - %s\n\n"
629                 "handler: %s\n"
630                 "permissions: %s\n"
631                 "usage: %s\n\n"
632                 "%s\n",
633                 cc->argv[1],
634                 cmd->description,
635                 handler,
636                 perms,
637                 cmd->usage,
638                 cmd->help
639         );
640         free(perms);
641         free(handler);
642         if (cc->use_sideband)
643                 return send_sb(&cc->scc, buf, ret, SBD_OUTPUT, false);
644         ret = sc_send_buffer(&cc->scc, buf);
645         free(buf);
646         return ret;
647 }
648
649 /* hup */
650 static int com_hup(struct command_context *cc)
651 {
652         if (cc->argc != 1)
653                 return -E_COMMAND_SYNTAX;
654         kill(getppid(), SIGHUP);
655         return 1;
656 }
657
658 /* term */
659 static int com_term(struct command_context *cc)
660 {
661         if (cc->argc != 1)
662                 return -E_COMMAND_SYNTAX;
663         kill(getppid(), SIGTERM);
664         return 1;
665 }
666
667 static int com_play(struct command_context *cc)
668 {
669         if (cc->argc != 1)
670                 return -E_COMMAND_SYNTAX;
671         mutex_lock(mmd_mutex);
672         mmd->new_vss_status_flags |= VSS_PLAYING;
673         mmd->new_vss_status_flags &= ~VSS_NOMORE;
674         mutex_unlock(mmd_mutex);
675         return 1;
676 }
677
678 /* stop */
679 static int com_stop(struct command_context *cc)
680 {
681         if (cc->argc != 1)
682                 return -E_COMMAND_SYNTAX;
683         mutex_lock(mmd_mutex);
684         mmd->new_vss_status_flags &= ~VSS_PLAYING;
685         mmd->new_vss_status_flags &= ~VSS_REPOS;
686         mmd->new_vss_status_flags |= VSS_NEXT;
687         mutex_unlock(mmd_mutex);
688         return 1;
689 }
690
691 /* pause */
692 static int com_pause(struct command_context *cc)
693 {
694         if (cc->argc != 1)
695                 return -E_COMMAND_SYNTAX;
696         mutex_lock(mmd_mutex);
697         if (!vss_paused() && !vss_stopped()) {
698                 mmd->events++;
699                 mmd->new_vss_status_flags &= ~VSS_PLAYING;
700                 mmd->new_vss_status_flags &= ~VSS_NEXT;
701         }
702         mutex_unlock(mmd_mutex);
703         return 1;
704 }
705
706 /* next */
707 static int com_next(struct command_context *cc)
708 {
709         if (cc->argc != 1)
710                 return -E_COMMAND_SYNTAX;
711         mutex_lock(mmd_mutex);
712         mmd->events++;
713         mmd->new_vss_status_flags |= VSS_NEXT;
714         mutex_unlock(mmd_mutex);
715         return 1;
716 }
717
718 /* nomore */
719 static int com_nomore(struct command_context *cc)
720 {
721         if (cc->argc != 1)
722                 return -E_COMMAND_SYNTAX;
723         mutex_lock(mmd_mutex);
724         if (vss_playing() || vss_paused())
725                 mmd->new_vss_status_flags |= VSS_NOMORE;
726         mutex_unlock(mmd_mutex);
727         return 1;
728 }
729
730 /* ff */
731 static int com_ff(struct command_context *cc)
732 {
733         long promille;
734         int ret, backwards = 0;
735         unsigned i;
736         char c;
737
738         if (cc->argc != 2)
739                 return -E_COMMAND_SYNTAX;
740         if (!(ret = sscanf(cc->argv[1], "%u%c", &i, &c)))
741                 return -E_COMMAND_SYNTAX;
742         if (ret > 1 && c == '-')
743                 backwards = 1; /* jmp backwards */
744         mutex_lock(mmd_mutex);
745         ret = -E_NO_AUDIO_FILE;
746         if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
747                 goto out;
748         promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
749         if (backwards)
750                 promille -= 1000 * i / mmd->afd.afhi.seconds_total;
751         else
752                 promille += 1000 * i / mmd->afd.afhi.seconds_total;
753         if (promille < 0)
754                 promille = 0;
755         if (promille >  1000) {
756                 mmd->new_vss_status_flags |= VSS_NEXT;
757                 goto out;
758         }
759         mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
760         mmd->new_vss_status_flags |= VSS_REPOS;
761         mmd->new_vss_status_flags &= ~VSS_NEXT;
762         mmd->events++;
763         ret = 1;
764 out:
765         mutex_unlock(mmd_mutex);
766         return ret;
767 }
768
769 /* jmp */
770 static int com_jmp(struct command_context *cc)
771 {
772         long unsigned int i;
773         int ret;
774
775         if (cc->argc != 2)
776                 return -E_COMMAND_SYNTAX;
777         if (sscanf(cc->argv[1], "%lu", &i) <= 0)
778                 return -E_COMMAND_SYNTAX;
779         mutex_lock(mmd_mutex);
780         ret = -E_NO_AUDIO_FILE;
781         if (!mmd->afd.afhi.chunks_total)
782                 goto out;
783         if (i > 100)
784                 i = 100;
785         PARA_INFO_LOG("jumping to %lu%%\n", i);
786         mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50)/ 100;
787         PARA_INFO_LOG("sent: %lu,  offset before jmp: %lu\n",
788                 mmd->chunks_sent, mmd->offset);
789         mmd->new_vss_status_flags |= VSS_REPOS;
790         mmd->new_vss_status_flags &= ~VSS_NEXT;
791         ret = 1;
792         mmd->events++;
793 out:
794         mutex_unlock(mmd_mutex);
795         return ret;
796 }
797
798 /*
799  * check if perms are sufficient to exec a command having perms cmd_perms.
800  * Returns 0 if perms are sufficient, -E_PERM otherwise.
801  */
802 static int check_perms(unsigned int perms, struct server_command *cmd_ptr)
803 {
804         PARA_DEBUG_LOG("checking permissions\n");
805         return (cmd_ptr->perms & perms) < cmd_ptr->perms ? -E_PERM : 0;
806 }
807
808 /*
809  * Parse first string from *cmd and lookup in table of valid commands.
810  * On error, NULL is returned.
811  */
812 static struct server_command *parse_cmd(const char *cmdstr)
813 {
814         char buf[255];
815         int n = 0;
816
817         sscanf(cmdstr, "%200s%n", buf, &n);
818         if (!n)
819                 return NULL;
820         buf[n] = '\0';
821         return get_cmd_ptr(buf, NULL);
822 }
823
824 static int read_command(struct stream_cipher_context *scc, char **result)
825 {
826         int ret;
827         char buf[4096];
828         char *command = NULL;
829
830         for (;;) {
831                 size_t numbytes;
832                 char *p;
833
834                 ret = sc_recv_buffer(scc, buf, sizeof(buf));
835                 if (ret < 0)
836                         goto out;
837                 if (!ret)
838                         break;
839                 numbytes = ret;
840                 ret = -E_COMMAND_SYNTAX;
841                 if (command && numbytes + strlen(command) > MAX_COMMAND_LEN) /* DOS */
842                         goto out;
843                 command = para_strcat(command, buf);
844                 p = strstr(command, EOC_MSG);
845                 if (p) {
846                         *p = '\0';
847                         break;
848                 }
849         }
850         ret = command? 1 : -E_COMMAND_SYNTAX;
851 out:
852         if (ret < 0)
853                 free(command);
854         else
855                 *result = command;
856         return ret;
857
858 }
859
860 static void reset_signals(void)
861 {
862         para_sigaction(SIGCHLD, SIG_IGN);
863         para_sigaction(SIGINT, SIG_DFL);
864         para_sigaction(SIGTERM, SIG_DFL);
865         para_sigaction(SIGHUP, SIG_DFL);
866 }
867
868 static int parse_auth_request(char *buf, int len, struct user **u,
869                 bool *use_sideband)
870 {
871         int ret;
872         char *p, *username, **features = NULL;
873         size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
874
875         *u = NULL;
876         *use_sideband = false;
877         if (len < auth_rq_len + 2)
878                 return -E_AUTH_REQUEST;
879         if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
880                 return -E_AUTH_REQUEST;
881         username = buf + auth_rq_len;
882         p = strchr(username, ' ');
883         if (p) {
884                 int i;
885                 if (p == username)
886                         return -E_AUTH_REQUEST;
887                 *p = '\0';
888                 p++;
889                 create_argv(p, ",", &features);
890                 for (i = 0; features[i]; i++) {
891                         if (strcmp(features[i], "sideband") == 0)
892                                 *use_sideband = true;
893                         else {
894                                 ret = -E_BAD_FEATURE;
895                                 goto out;
896                         }
897                 }
898         }
899         PARA_DEBUG_LOG("received auth request for user %s (sideband = %s)\n",
900                 username, *use_sideband? "true" : "false");
901         *u = lookup_user(username);
902         ret = 1;
903 out:
904         free_argv(features);
905         return ret;
906 }
907
908 #define HANDSHAKE_BUFSIZE 4096
909
910 static int parse_sb_command(struct command_context *cc, struct iovec *iov)
911 {
912         int ret, i;
913         char *p, *end;
914
915         ret = -E_BAD_CMD;
916         if (iov->iov_base == NULL || iov->iov_len == 0)
917                 goto out;
918         p = iov->iov_base;
919         p[iov->iov_len - 1] = '\0'; /* just to be sure */
920         cc->cmd = get_cmd_ptr(p, NULL);
921         if (!cc->cmd)
922                 goto out;
923         ret = check_perms(cc->u->perms, cc->cmd);
924         if (ret < 0)
925                 goto out;
926         end = iov->iov_base + iov->iov_len;
927         for (i = 0, p = iov->iov_base; p < end; i++)
928                 p += strlen(p) + 1;
929         cc->argc = i;
930         cc->argv = para_malloc((cc->argc + 1) * sizeof(char *));
931         for (i = 0, p = iov->iov_base; p < end; i++) {
932                 cc->argv[i] = para_strdup(p);
933                 p += strlen(p) + 1;
934         }
935         cc->argv[cc->argc] = NULL;
936         ret = cc->argc;
937 out:
938         free(iov->iov_base);
939         return ret;
940 }
941
942 /**
943  * Perform user authentication and execute a command.
944  *
945  * \param fd The file descriptor to send output to.
946  * \param peername Identifies the connecting peer.
947  *
948  * Whenever para_server accepts an incoming tcp connection on
949  * the port it listens on, it forks and the resulting child
950  * calls this function.
951  *
952  * An RSA-based challenge/response is used to authenticate
953  * the peer. It that authentication succeeds, a random
954  * session key is generated and sent back to the peer,
955  * encrypted with its RSA public key.  From this point on,
956  * all transfers are crypted with this session key.
957  *
958  * Next it is checked if the peer supplied  a valid server command or a command
959  * for the audio file selector.  If yes, and if the user has sufficient
960  * permissions to execute that command, the function calls the corresponding
961  * command handler which does argument checking and further processing.
962  *
963  * In order to cope with a DOS attacks, a timeout is set up
964  * which terminates the function if the connection was not
965  * authenticated when the timeout expires.
966  *
967  * \sa alarm(2), crypt.c, crypt.h
968  */
969 __noreturn void handle_connect(int fd, const char *peername)
970 {
971         int ret;
972         unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
973         unsigned char challenge_hash[HASH_SIZE];
974         char *p, *command = NULL, *buf = para_malloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
975         size_t numbytes;
976         struct command_context cc_struct = {.peer = peername}, *cc = &cc_struct;
977
978         cc->scc.fd = fd;
979         reset_signals();
980         /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
981         ret = mark_fd_blocking(fd);
982         if (ret < 0)
983                 goto net_err;
984         /* send Welcome message */
985         ret = write_va_buffer(fd, "This is para_server, version "
986                 PACKAGE_VERSION  ".\n"
987                 "Features: sideband,foo\n"
988         );
989         if (ret < 0)
990                 goto net_err;
991         /* recv auth request line */
992         ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
993         if (ret < 0)
994                 goto net_err;
995         ret = parse_auth_request(buf, ret, &cc->u, &cc->use_sideband);
996         if (ret < 0)
997                 goto net_err;
998         p = buf + strlen(AUTH_REQUEST_MSG);
999         PARA_DEBUG_LOG("received auth request for user %s\n", p);
1000         cc->u = lookup_user(p);
1001         if (cc->u) {
1002                 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
1003                 ret = pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
1004                         (unsigned char *)buf);
1005                 if (ret < 0)
1006                         goto net_err;
1007                 numbytes = ret;
1008         } else {
1009                 /*
1010                  * We don't want to reveal our user names, so we send a
1011                  * challenge to the client even if the user does not exist, and
1012                  * fail the authentication later.
1013                  */
1014                 numbytes = 256;
1015                 get_random_bytes_or_die((unsigned char *)buf, numbytes);
1016         }
1017         PARA_DEBUG_LOG("sending %u byte challenge + rc4 keys (%zu bytes)\n",
1018                 CHALLENGE_SIZE, numbytes);
1019         if (cc->use_sideband) {
1020                 struct iovec iov;
1021                 ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
1022                 buf = NULL;
1023                 if (ret < 0)
1024                         goto net_err;
1025                 ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
1026                         HANDSHAKE_BUFSIZE, &iov);
1027                 if (ret < 0)
1028                         goto net_err;
1029                 buf = iov.iov_base;
1030                 numbytes = iov.iov_len;
1031         } else {
1032                 ret = write_all(fd, buf, numbytes);
1033                 if (ret < 0)
1034                         goto net_err;
1035                 /* recv challenge response */
1036                 ret = recv_bin_buffer(fd, buf, HASH_SIZE);
1037                 if (ret < 0)
1038                         goto net_err;
1039                 numbytes = ret;
1040         }
1041         PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
1042         ret = -E_BAD_USER;
1043         if (!cc->u)
1044                 goto net_err;
1045         /*
1046          * The correct response is the hash of the first CHALLENGE_SIZE bytes
1047          * of the random data.
1048          */
1049         ret = -E_BAD_AUTH;
1050         if (numbytes != HASH_SIZE)
1051                 goto net_err;
1052         hash_function((char *)rand_buf, CHALLENGE_SIZE, challenge_hash);
1053         if (memcmp(challenge_hash, buf, HASH_SIZE))
1054                 goto net_err;
1055         /* auth successful */
1056         alarm(0);
1057         PARA_INFO_LOG("good auth for %s\n", cc->u->name);
1058         /* init stream cipher keys with the second part of the random buffer */
1059         cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
1060         cc->scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN, SESSION_KEY_LEN);
1061         if (cc->use_sideband)
1062                 ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
1063         else
1064                 ret = sc_send_buffer(&cc->scc, PROCEED_MSG);
1065         if (ret < 0)
1066                 goto net_err;
1067         if (cc->use_sideband) {
1068                 struct iovec iov;
1069                 ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
1070                 if (ret < 0)
1071                         goto net_err;
1072                 ret = parse_sb_command(cc, &iov);
1073                 if (ret < 0)
1074                         goto err_out;
1075                 cc->argc = ret;
1076         } else {
1077                 ret = read_command(&cc->scc, &command);
1078                 if (ret == -E_COMMAND_SYNTAX)
1079                         goto err_out;
1080                 if (ret < 0)
1081                         goto net_err;
1082                 ret = -E_BAD_CMD;
1083                 cc->cmd = parse_cmd(command);
1084                 if (!cc->cmd)
1085                         goto err_out;
1086                 /* valid command, check permissions */
1087                 ret = check_perms(cc->u->perms, cc->cmd);
1088                 if (ret < 0)
1089                         goto err_out;
1090                 /* valid command and sufficient perms */
1091                 ret = create_argv(command, "\n", &cc->argv);
1092                 if (ret < 0)
1093                         goto err_out;
1094                 cc->argc = ret;
1095         }
1096         PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cc->cmd->name,
1097                 cc->u->name, peername);
1098         ret = cc->cmd->handler(cc);
1099         free_argv(cc->argv);
1100         mutex_lock(mmd_mutex);
1101         mmd->num_commands++;
1102         mutex_unlock(mmd_mutex);
1103         if (ret >= 0)
1104                 goto out;
1105 err_out:
1106         if (send_strerror(cc, -ret) >= 0 && cc->use_sideband)
1107                 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
1108 net_err:
1109         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1110 out:
1111         free(buf);
1112         free(command);
1113         mutex_lock(mmd_mutex);
1114         if (cc->cmd && (cc->cmd->perms & AFS_WRITE) && ret >= 0)
1115                 mmd->events++;
1116         mmd->active_connections--;
1117         mutex_unlock(mmd_mutex);
1118         if (ret >= 0 && cc->use_sideband) {
1119                 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1120                 if (ret < 0)
1121                         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1122         }
1123         sc_free(cc->scc.recv);
1124         sc_free(cc->scc.send);
1125         exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
1126 }