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