]> git.tuebingen.mpg.de Git - paraslash.git/blob - command.c
Merge topic branch t/overflow into master
[paraslash.git] / command.c
1 /* Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file command.c Client authentication and server commands. */
4
5 #include <netinet/in.h>
6 #include <sys/socket.h>
7 #include <regex.h>
8 #include <signal.h>
9 #include <arpa/inet.h>
10 #include <netdb.h>
11 #include <lopsub.h>
12
13 #include "para.h"
14 #include "error.h"
15 #include "lsu.h"
16 #include "crypt.h"
17 #include "sideband.h"
18 #include "command.h"
19 #include "string.h"
20 #include "afh.h"
21 #include "net.h"
22 #include "server.h"
23 #include "list.h"
24 #include "sched.h"
25 #include "send.h"
26 #include "vss.h"
27 #include "daemon.h"
28 #include "fd.h"
29 #include "ipc.h"
30 #include "server_cmd.lsg.h"
31 #include "user_list.h"
32 #include "signal.h"
33 #include "version.h"
34
35 #define SERVER_CMD_AUX_INFO(_arg) _arg,
36 static const unsigned server_command_perms[] = {LSG_SERVER_CMD_AUX_INFOS};
37 #undef SERVER_CMD_AUX_INFO
38 #define SERVER_CMD_AUX_INFO(_arg) #_arg,
39 static const char * const server_command_perms_txt[] = {LSG_SERVER_CMD_AUX_INFOS};
40 #undef SERVER_CMD_AUX_INFO
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 int send_afs_status(struct command_context *cc, int parser_friendly);
48 static bool subcmd_should_die;
49
50 static void command_handler_sighandler(int s)
51 {
52         if (s != SIGTERM)
53                 return;
54         PARA_EMERG_LOG("terminating on signal %d\n", SIGTERM);
55         subcmd_should_die = true;
56 }
57
58 /*
59  * Compute human readable vss status text.
60  *
61  * We can't call vss_playing() and friends here because those functions read
62  * the flags from the primary mmd structure, so calling them from command
63  * handler context would require to take the mmd lock. At the time the function
64  * is called we already took a copy of the mmd structure and want to use the
65  * flags value of the copy for computing the vss status text.
66  */
67 static char *vss_status_tohuman(unsigned int flags)
68 {
69         if (flags & VSS_PLAYING)
70                 return para_strdup("playing");
71         if (flags & VSS_NEXT)
72                 return para_strdup("stopped");
73         return para_strdup("paused");
74 }
75
76 /*
77  * Never returns NULL.
78  */
79 static char *vss_get_status_flags(unsigned int flags)
80 {
81         char *msg = alloc(5 * sizeof(char));
82
83         msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
84         msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
85         msg[2] = (flags & VSS_NEXT)? 'N' : '_';
86         msg[3] = (flags & VSS_REPOS)? 'R' : '_';
87         msg[4] = '\0';
88         return msg;
89 }
90
91 static unsigned get_status(struct misc_meta_data *nmmd, bool parser_friendly,
92                 char **result)
93 {
94         char *status, *flags; /* vss status info */
95         /* nobody updates our version of "now" */
96         long offset = (nmmd->offset + 500) / 1000;
97         struct timeval current_time;
98         struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
99
100         /* report real status */
101         status = vss_status_tohuman(nmmd->vss_status_flags);
102         flags = vss_get_status_flags(nmmd->vss_status_flags);
103         clock_get_realtime(&current_time);
104         /*
105          * The calls to WRITE_STATUS_ITEM() below never fail because
106          * b->max_size is zero (unlimited), see \ref para_printf(). However,
107          * clang is not smart enough to prove this and complains nevertheless.
108          * Casting the return value to void silences clang.
109          */
110         (void)WRITE_STATUS_ITEM(&b, SI_status, "%s\n", status);
111         (void)WRITE_STATUS_ITEM(&b, SI_status_flags, "%s\n", flags);
112         (void)WRITE_STATUS_ITEM(&b, SI_offset, "%li\n", offset);
113         (void)WRITE_STATUS_ITEM(&b, SI_afs_mode, "%s\n", mmd->afs_mode_string);
114         (void)WRITE_STATUS_ITEM(&b, SI_stream_start, "%lu.%lu\n",
115                 (long unsigned)nmmd->stream_start.tv_sec,
116                 (long unsigned)nmmd->stream_start.tv_usec);
117         (void)WRITE_STATUS_ITEM(&b, SI_current_time, "%lu.%lu\n",
118                 (long unsigned)current_time.tv_sec,
119                 (long unsigned)current_time.tv_usec);
120         free(flags);
121         free(status);
122         *result = b.buf;
123         return b.offset;
124 }
125
126 /**
127  * Send a sideband packet through a blocking file descriptor.
128  *
129  * \param scc fd and crypto keys.
130  * \param buf The buffer to send.
131  * \param numbytes The size of \a buf.
132  * \param band The sideband designator of this packet.
133  * \param dont_free If true, never deallocate \a buf.
134  *
135  * The nonblock flag must be disabled for the file descriptor given by \a scc.
136  *
137  * Stream cipher encryption is automatically activated if necessary via the
138  * sideband transformation, depending on the value of \a band.
139  *
140  * \return Standard.
141  *
142  * \sa \ref send_sb_va().
143  */
144 int send_sb(struct stream_cipher_context *scc, void *buf, size_t numbytes,
145                 int band, bool dont_free)
146 {
147         int ret;
148         struct sb_context *sbc;
149         struct iovec iov[2];
150         sb_transformation trafo = band < SBD_PROCEED? NULL : sc_trafo;
151         struct sb_buffer sbb = SBB_INIT(band, buf, numbytes);
152
153         sbc = sb_new_send(&sbb, dont_free, trafo, scc->send);
154         do {
155                 ret = sb_get_send_buffers(sbc, iov);
156                 ret = xwritev(scc->fd, iov, ret);
157                 if (ret < 0)
158                         goto fail;
159         } while (sb_sent(sbc, ret) == false);
160         return 1;
161 fail:
162         sb_free(sbc);
163         return ret;
164 }
165
166 /**
167  * Create a variable sized buffer and send it as a sideband packet.
168  *
169  * \param scc Passed to \ref send_sb.
170  * \param band See \ref send_sb.
171  * \param fmt The format string.
172  *
173  * \return The return value of the underlying call to \ref send_sb.
174  */
175 __printf_3_4 int send_sb_va(struct stream_cipher_context *scc, int band,
176                 const char *fmt, ...)
177 {
178         va_list ap;
179         char *msg;
180         int ret;
181
182         va_start(ap, fmt);
183         ret = xvasprintf(&msg, fmt, ap);
184         va_end(ap);
185         return send_sb(scc, msg, ret, band, false);
186 }
187
188 /**
189  * Send an error message to a client.
190  *
191  * \param cc Client info.
192  * \param err The (positive) error code.
193  *
194  * \return The return value of the underlying call to send_sb_va().
195  */
196 int send_strerror(struct command_context *cc, int err)
197 {
198         return send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", para_strerror(err));
199 }
200
201 /**
202  * Send an error context to a client,
203  *
204  * \param cc Client info.
205  * \param errctx The error context string.
206  *
207  * \return The return value of the underlying call to send_sb_va().
208  *
209  * This function frees the error context string after it was sent.
210  */
211 int send_errctx(struct command_context *cc, char *errctx)
212 {
213         int ret;
214
215         if (!errctx)
216                 return 0;
217         ret = send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", errctx);
218         free(errctx);
219         return ret;
220 }
221
222 static int check_sender_args(struct command_context *cc,
223                 struct lls_parse_result *lpr, struct sender_command_data *scd)
224 {
225         int i, ret;
226         const char * const subcmds[] = {SENDER_SUBCOMMANDS};
227         const char *arg;
228         char *errctx;
229         unsigned num_inputs = lls_num_inputs(lpr);
230
231         scd->sender_num = -1;
232         ret = lls(lls_check_arg_count(lpr, 2, INT_MAX, &errctx));
233         if (ret < 0) {
234                 send_errctx(cc, errctx);
235                 return ret;
236         }
237         arg = lls_input(0, lpr);
238         FOR_EACH_SENDER(i)
239                 if (strcmp(senders[i]->name, arg) == 0)
240                         break;
241         if (!senders[i])
242                 return -E_COMMAND_SYNTAX;
243         scd->sender_num = i;
244         arg = lls_input(1, lpr);
245         for (i = 0; i < NUM_SENDER_CMDS; i++)
246                 if (!strcmp(subcmds[i], arg))
247                         break;
248         if (i == NUM_SENDER_CMDS)
249                 return -E_COMMAND_SYNTAX;
250         scd->cmd_num = i;
251         if (!senders[scd->sender_num]->client_cmds[scd->cmd_num])
252                 return -E_SENDER_CMD;
253         switch (scd->cmd_num) {
254         case SENDER_on:
255         case SENDER_off:
256                 if (num_inputs != 2)
257                         return -E_COMMAND_SYNTAX;
258                 break;
259         case SENDER_deny:
260         case SENDER_allow:
261                 if (num_inputs != 3 || parse_cidr(lls_input(2, lpr), scd->host,
262                                 sizeof(scd->host), &scd->netmask) == NULL)
263                         return -E_COMMAND_SYNTAX;
264                 break;
265         case SENDER_add:
266         case SENDER_delete:
267                 if (num_inputs != 3)
268                         return -E_COMMAND_SYNTAX;
269                 return parse_fec_url(lls_input(2, lpr), scd);
270         default:
271                 return -E_COMMAND_SYNTAX;
272         }
273         return 1;
274 }
275
276 /**
277  * Receive a sideband packet from a blocking file descriptor.
278  *
279  * \param scc fd and crypto keys.
280  * \param expected_band The expected band designator.
281  * \param max_size Passed to \ref sb_new_recv().
282  * \param result Body of the sideband packet is returned here.
283  *
284  * If \a expected_band is not \p SBD_ANY, the band designator of the received
285  * sideband packet is compared to \a expected_band and a mismatch is considered
286  * an error.
287  *
288  * \return Standard.
289  */
290 int recv_sb(struct stream_cipher_context *scc,
291                 enum sb_designator expected_band,
292                 size_t max_size, struct iovec *result)
293 {
294         int ret;
295         struct sb_context *sbc;
296         struct iovec iov;
297         struct sb_buffer sbb;
298         sb_transformation trafo;
299
300         trafo = expected_band != SBD_ANY && expected_band < SBD_PROCEED?
301                 NULL : sc_trafo;
302         sbc = sb_new_recv(max_size, trafo, scc->recv);
303         for (;;) {
304                 sb_get_recv_buffer(sbc, &iov);
305                 ret = recv_bin_buffer(scc->fd, iov.iov_base, iov.iov_len);
306                 if (ret == 0)
307                         ret = -E_EOF;
308                 if (ret < 0)
309                         goto fail;
310                 ret = sb_received(sbc, ret, &sbb);
311                 if (ret < 0)
312                         goto fail;
313                 if (ret > 0)
314                         break;
315         }
316         ret = -E_BAD_BAND;
317         if (expected_band != SBD_ANY && sbb.band != expected_band)
318                 goto fail;
319         *result = sbb.iov;
320         return 1;
321 fail:
322         sb_free(sbc);
323         return ret;
324 }
325
326 static int com_sender(struct command_context *cc, struct lls_parse_result *lpr)
327 {
328         int i, ret = 0;
329         char *msg = NULL;
330         struct sender_command_data scd;
331
332         if (lls_num_inputs(lpr) == 0) {
333                 FOR_EACH_SENDER(i) {
334                         char *tmp;
335                         ret = xasprintf(&tmp, "%s%s\n", msg? msg : "",
336                                 senders[i]->name);
337                         free(msg);
338                         msg = tmp;
339                 }
340                 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
341         }
342         ret = check_sender_args(cc, lpr, &scd);
343         if (ret < 0) {
344                 if (scd.sender_num < 0)
345                         return ret;
346                 if (strcmp(lls_input(1, lpr), "status") == 0)
347                         msg = senders[scd.sender_num]->status();
348                 else
349                         msg = senders[scd.sender_num]->help();
350                 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
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(lls_input(2, lpr),
358                         &scd);
359                 if (ret < 0)
360                         return ret;
361         }
362
363         for (i = 0; i < 10; i++) {
364                 mutex_lock(mmd_mutex);
365                 if (mmd->sender_cmd_data.cmd_num >= 0) {
366                         /* another sender command is active, retry in 100ms */
367                         struct timespec ts = {.tv_nsec = 100 * 1000 * 1000};
368                         mutex_unlock(mmd_mutex);
369                         nanosleep(&ts, NULL);
370                         continue;
371                 }
372                 mmd->sender_cmd_data = scd;
373                 mutex_unlock(mmd_mutex);
374                 break;
375         }
376         return (i < 10)? 1 : -E_LOCK;
377 }
378 EXPORT_SERVER_CMD_HANDLER(sender);
379
380 static int com_si(struct command_context *cc,
381                 __a_unused struct lls_parse_result *lpr)
382 {
383         char *msg, *ut;
384         int ret;
385
386         ut = daemon_get_uptime_str(now);
387         mutex_lock(mmd_mutex);
388         ret = xasprintf(&msg,
389                 "up: %s\nplayed: %u\n"
390                 "server_pid: %d\n"
391                 "afs_pid: %d\n"
392                 "connections (active/accepted/total): %u/%u/%u\n"
393                 "supported audio formats: %s\n",
394                 ut, mmd->num_played,
395                 (int)getppid(),
396                 (int)afs_pid,
397                 mmd->active_connections,
398                 mmd->num_commands,
399                 mmd->num_connects,
400                 AUDIO_FORMAT_HANDLERS
401         );
402         mutex_unlock(mmd_mutex);
403         free(ut);
404         return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
405 }
406 EXPORT_SERVER_CMD_HANDLER(si);
407
408 static int com_version(struct command_context *cc, struct lls_parse_result *lpr)
409 {
410         char *msg;
411         size_t len;
412
413         if (SERVER_CMD_OPT_GIVEN(VERSION, VERBOSE, lpr))
414                 len = xasprintf(&msg, "%s", version_text("server"));
415         else
416                 len = xasprintf(&msg, "%s\n", version_single_line("server"));
417         return send_sb(&cc->scc, msg, len, SBD_OUTPUT, false);
418 }
419 EXPORT_SERVER_CMD_HANDLER(version);
420
421 /** These status items are cleared if no audio file is currently open. */
422 #define EMPTY_STATUS_ITEMS \
423         ITEM(path) \
424         ITEM(directory) \
425         ITEM(basename) \
426         ITEM(score) \
427         ITEM(attributes_bitmap) \
428         ITEM(attributes_txt) \
429         ITEM(hash) \
430         ITEM(image_id) \
431         ITEM(image_name) \
432         ITEM(lyrics_id) \
433         ITEM(lyrics_name) \
434         ITEM(bitrate) \
435         ITEM(format) \
436         ITEM(frequency) \
437         ITEM(channels) \
438         ITEM(duration) \
439         ITEM(seconds_total) \
440         ITEM(num_played) \
441         ITEM(last_played) \
442         ITEM(techinfo) \
443         ITEM(artist) \
444         ITEM(title) \
445         ITEM(year) \
446         ITEM(album) \
447         ITEM(comment) \
448         ITEM(mtime) \
449         ITEM(file_size) \
450         ITEM(chunk_time) \
451         ITEM(num_chunks) \
452         ITEM(amplification) \
453         ITEM(play_time) \
454
455 /*
456  * Create a set of audio-file related status items with empty values. These are
457  * written to stat clients when no audio file is open.
458  */
459 static unsigned empty_status_items(bool parser_friendly, char **result)
460 {
461         char *esi;
462         unsigned len;
463
464         if (parser_friendly)
465                 len = xasprintf(&esi,
466                         #define ITEM(x) "0004 %02x:\n"
467                         EMPTY_STATUS_ITEMS
468                         #undef ITEM
469                         #define ITEM(x) , (unsigned) SI_ ## x
470                         EMPTY_STATUS_ITEMS
471                         #undef ITEM
472                 );
473         else
474                 len = xasprintf(&esi,
475                         #define ITEM(x) "%s:\n"
476                         EMPTY_STATUS_ITEMS
477                         #undef ITEM
478                         #define ITEM(x) ,status_item_list[SI_ ## x]
479                         EMPTY_STATUS_ITEMS
480                         #undef ITEM
481                 );
482         *result = esi;
483         return len;
484 }
485 #undef EMPTY_STATUS_ITEMS
486
487 static int com_stat(struct command_context *cc, struct lls_parse_result *lpr)
488 {
489         int ret;
490         struct misc_meta_data tmp, *nmmd = &tmp;
491         char *s;
492         bool parser_friendly = SERVER_CMD_OPT_GIVEN(STAT, PARSER_FRIENDLY,
493                 lpr) > 0;
494         uint32_t num = SERVER_CMD_UINT32_VAL(STAT, NUM, lpr);
495         const struct timespec ts = {.tv_sec = 50, .tv_nsec = 0};
496
497         para_sigaction(SIGINT, SIG_IGN);
498         para_sigaction(SIGUSR1, command_handler_sighandler);
499         para_sigaction(SIGTERM, command_handler_sighandler);
500         /*
501          * Simply checking subcmd_should_die is racy because a signal may
502          * arrive after the check but before the subsequent call to sleep(3).
503          * If this happens, sleep(3) would not be interrupted by the signal.
504          * To avoid this we block SIGTERM here and allow it to arrive only
505          * while we sleep.
506          */
507         para_block_signal(SIGTERM);
508         for (;;) {
509                 sigset_t set;
510                 /*
511                  * Copy the mmd structure to minimize the time we hold the mmd
512                  * lock.
513                  */
514                 mutex_lock(mmd_mutex);
515                 *nmmd = *mmd;
516                 mutex_unlock(mmd_mutex);
517                 ret = get_status(nmmd, parser_friendly, &s);
518                 ret = send_sb(&cc->scc, s, ret, SBD_OUTPUT, false);
519                 if (ret < 0)
520                         goto out;
521                 if (nmmd->vss_status_flags & VSS_NEXT) {
522                         char *esi;
523                         ret = empty_status_items(parser_friendly, &esi);
524                         ret = send_sb(&cc->scc, esi, ret, SBD_OUTPUT, false);
525                         if (ret < 0)
526                                 goto out;
527                 } else
528                         send_afs_status(cc, parser_friendly);
529                 ret = 1;
530                 if (num > 0 && !--num)
531                         goto out;
532                 sigemptyset(&set); /* empty set means: unblock all signals */
533                 /*
534                  * pselect(2) allows to atomically unblock signals, then go to
535                  * sleep. Calling sigprocmask(2) followed by sleep(3) would
536                  * open a race window similar to the one described above.
537                  */
538                 pselect(1, NULL, NULL, NULL, &ts, &set);
539                 if (subcmd_should_die)
540                         goto out;
541                 ret = -E_SERVER_CRASH;
542                 if (getppid() == 1)
543                         goto out;
544         }
545 out:
546         return ret;
547 }
548 EXPORT_SERVER_CMD_HANDLER(stat);
549
550 static const char *aux_info_cb(unsigned cmd_num, bool verbose)
551 {
552         static char result[80];
553         unsigned perms = server_command_perms[cmd_num];
554
555         if (verbose) {
556                 /* permissions: VSS_READ | VSS_WRITE */
557                 sprintf(result, "permissions: %s",
558                         server_command_perms_txt[cmd_num]);
559         } else {
560                 result[0] = perms & AFS_READ? 'a' : '-';
561                 result[1] = perms & AFS_WRITE? 'A' : '-';
562                 result[2] = perms & VSS_READ? 'v' : '-';
563                 result[3] = perms & VSS_WRITE? 'V' : '-';
564                 result[4] = '\0';
565         }
566         return result;
567 }
568
569 static int com_help(struct command_context *cc, struct lls_parse_result *lpr)
570 {
571         char *buf;
572         int ret;
573         unsigned n;
574         bool long_help = SERVER_CMD_OPT_GIVEN(HELP, LONG, lpr);
575
576         lsu_com_help(long_help, lpr, server_cmd_suite, aux_info_cb, &buf, &n);
577         ret = send_sb(&cc->scc, buf, n, SBD_OUTPUT, false);
578         return ret;
579 }
580 EXPORT_SERVER_CMD_HANDLER(help);
581
582 static int com_hup(__a_unused struct command_context *cc,
583                 __a_unused struct lls_parse_result *lpr)
584 {
585         kill(getppid(), SIGHUP);
586         return 1;
587 }
588 EXPORT_SERVER_CMD_HANDLER(hup);
589
590 static int com_ll(struct command_context *cc, struct lls_parse_result *lpr)
591 {
592         unsigned ll, perms;
593         char *errctx;
594         const char *sev[] = {SEVERITIES}, *arg;
595         int ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
596
597         if (ret < 0) {
598                 send_errctx(cc, errctx);
599                 return ret;
600         }
601         if (lls_num_inputs(lpr) == 0) { /* reporting is an unprivileged op. */
602                 const char *severity;
603                 mutex_lock(mmd_mutex);
604                 severity = sev[mmd->loglevel];
605                 mutex_unlock(mmd_mutex);
606                 return send_sb_va(&cc->scc, SBD_OUTPUT, "%s\n", severity);
607         }
608         /*
609          * Changing the loglevel changes the state of both the afs and the vss,
610          * so we require both AFS_WRITE and VSS_WRITE.
611          */
612         perms = AFS_WRITE | VSS_WRITE;
613         if ((cc->u->perms & perms) != perms)
614                 return -ERRNO_TO_PARA_ERROR(EPERM);
615         arg = lls_input(0, lpr);
616         for (ll = 0; ll < NUM_LOGLEVELS; ll++)
617                 if (!strcmp(arg, sev[ll]))
618                         break;
619         if (ll >= NUM_LOGLEVELS)
620                 return -ERRNO_TO_PARA_ERROR(EINVAL);
621         PARA_INFO_LOG("new log level: %s\n", sev[ll]);
622         /* Ask the server and afs processes to adjust their log level. */
623         mutex_lock(mmd_mutex);
624         mmd->loglevel = ll;
625         mutex_unlock(mmd_mutex);
626         return 1;
627 }
628 EXPORT_SERVER_CMD_HANDLER(ll);
629
630 static int com_term(__a_unused struct command_context *cc,
631                 __a_unused struct lls_parse_result *lpr)
632 {
633         kill(getppid(), SIGTERM);
634         return 1;
635 }
636 EXPORT_SERVER_CMD_HANDLER(term);
637
638 static int com_play(__a_unused struct command_context *cc,
639                 __a_unused struct lls_parse_result *lpr)
640 {
641         mutex_lock(mmd_mutex);
642         mmd->new_vss_status_flags |= VSS_PLAYING;
643         mmd->new_vss_status_flags &= ~VSS_NOMORE;
644         mutex_unlock(mmd_mutex);
645         return 1;
646 }
647 EXPORT_SERVER_CMD_HANDLER(play);
648
649 static int com_stop(__a_unused struct command_context *cc,
650                 __a_unused struct lls_parse_result *lpr)
651 {
652         mutex_lock(mmd_mutex);
653         mmd->new_vss_status_flags &= ~VSS_PLAYING;
654         mmd->new_vss_status_flags &= ~VSS_REPOS;
655         mmd->new_vss_status_flags |= VSS_NEXT;
656         mutex_unlock(mmd_mutex);
657         return 1;
658 }
659 EXPORT_SERVER_CMD_HANDLER(stop);
660
661 static int com_pause(__a_unused struct command_context *cc,
662                 __a_unused struct lls_parse_result *lpr)
663 {
664         mutex_lock(mmd_mutex);
665         if (!vss_paused() && !vss_stopped()) {
666                 mmd->events++;
667                 mmd->new_vss_status_flags &= ~VSS_PLAYING;
668                 mmd->new_vss_status_flags &= ~VSS_NEXT;
669         }
670         mutex_unlock(mmd_mutex);
671         return 1;
672 }
673 EXPORT_SERVER_CMD_HANDLER(pause);
674
675 static int com_next(__a_unused struct command_context *cc,
676                 __a_unused struct lls_parse_result *lpr)
677 {
678         mutex_lock(mmd_mutex);
679         mmd->events++;
680         mmd->new_vss_status_flags |= VSS_NEXT;
681         mutex_unlock(mmd_mutex);
682         return 1;
683 }
684 EXPORT_SERVER_CMD_HANDLER(next);
685
686 static int com_nomore(__a_unused struct command_context *cc,
687                 __a_unused struct lls_parse_result *lpr)
688 {
689         mutex_lock(mmd_mutex);
690         if (vss_playing() || vss_paused())
691                 mmd->new_vss_status_flags |= VSS_NOMORE;
692         mutex_unlock(mmd_mutex);
693         return 1;
694 }
695 EXPORT_SERVER_CMD_HANDLER(nomore);
696
697 static int com_ff(struct command_context *cc, struct lls_parse_result *lpr)
698 {
699         long promille;
700         int i, ret;
701         char c, *errctx;
702
703         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
704         if (ret < 0) {
705                 send_errctx(cc, errctx);
706                 return ret;
707         }
708         ret = para_atoi32(lls_input(0, lpr), &i);
709         if (ret < 0) {
710                 if (ret != -E_ATOI_JUNK_AT_END)
711                         return ret;
712                 /*
713                  * Compatibility code to keep the historic syntax (ff 30-)
714                  * working. This can be removed after 0.7.0.
715                  */
716                 ret = sscanf(lls_input(0, lpr), "%i%c", &i, &c);
717                 if (ret <= 0)
718                         return -E_COMMAND_SYNTAX;
719                 if (ret > 1 && c == '-') {
720                         PARA_WARNING_LOG("use of obsolete syntax\n");
721                         i = -i;
722                 }
723         }
724         mutex_lock(mmd_mutex);
725         ret = -E_NO_AUDIO_FILE;
726         if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
727                 goto out;
728         ret = 1;
729         promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
730         /*
731          * We need this cast because without it the expression on the right
732          * hand side is of unsigned type.
733          */
734         promille += 1000 * i / (int)mmd->afd.afhi.seconds_total;
735         if (promille < 0)
736                 promille = 0;
737         if (promille > 1000) {
738                 mmd->new_vss_status_flags |= VSS_NEXT;
739                 goto out;
740         }
741         mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
742         mmd->new_vss_status_flags |= VSS_REPOS;
743         mmd->new_vss_status_flags &= ~VSS_NEXT;
744         mmd->events++;
745 out:
746         mutex_unlock(mmd_mutex);
747         return ret;
748 }
749 EXPORT_SERVER_CMD_HANDLER(ff);
750
751 static int com_jmp(struct command_context *cc, struct lls_parse_result *lpr)
752 {
753         int i, ret;
754         char *errctx;
755
756         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
757         if (ret < 0) {
758                 send_errctx(cc, errctx);
759                 return ret;
760         }
761         if (sscanf(lls_input(0, lpr), "%d", &i) <= 0)
762                 return -ERRNO_TO_PARA_ERROR(EINVAL);
763         if (i < 0 || i > 100)
764                 return -ERRNO_TO_PARA_ERROR(EINVAL);
765         mutex_lock(mmd_mutex);
766         ret = -E_NO_AUDIO_FILE;
767         if (!mmd->afd.afhi.chunks_total)
768                 goto out;
769         PARA_INFO_LOG("jumping to %d%%\n", i);
770         mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50) / 100;
771         mmd->new_vss_status_flags |= VSS_REPOS;
772         mmd->new_vss_status_flags &= ~VSS_NEXT;
773         ret = 1;
774         mmd->events++;
775 out:
776         mutex_unlock(mmd_mutex);
777         return ret;
778 }
779 EXPORT_SERVER_CMD_HANDLER(jmp);
780
781 static void reset_signals(void)
782 {
783         para_sigaction(SIGCHLD, SIG_IGN);
784         para_sigaction(SIGINT, SIG_DFL);
785         para_sigaction(SIGTERM, SIG_DFL);
786         para_sigaction(SIGHUP, SIG_DFL);
787 }
788
789 struct connection_features {
790         bool sha256_requested; /* can be removed after 0.7.0 */
791 };
792
793 static int parse_auth_request(char *buf, int len, const struct user **u,
794                 struct connection_features *cf)
795 {
796         int ret;
797         char *p, *username, **features = NULL;
798         size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
799
800         *u = NULL;
801         memset(cf, 0, sizeof(*cf));
802         if (len < auth_rq_len + 2)
803                 return -E_AUTH_REQUEST;
804         if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
805                 return -E_AUTH_REQUEST;
806         username = buf + auth_rq_len;
807         p = strchr(username, ' ');
808         if (p) {
809                 int i;
810                 if (p == username)
811                         return -E_AUTH_REQUEST;
812                 *p = '\0';
813                 p++;
814                 create_argv(p, ",", &features);
815                 /*
816                  * Still accept sideband and AES feature requests (as a no-op)
817                  * because some 0.6.x clients request them. The two checks
818                  * below may be removed after 0.7.1.
819                  */
820                 for (i = 0; features[i]; i++) {
821                         if (strcmp(features[i], "sideband") == 0)
822                                 continue;
823                         if (strcmp(features[i], "aes_ctr128") == 0)
824                                 continue;
825                         /*
826                          * ->sha256_requested can go away after 0.7.0 but the
827                          * check has to stay until 0.9.0.
828                          */
829                         if (strcmp(features[i], "sha256") == 0)
830                                 cf->sha256_requested = true;
831                         else {
832                                 ret = -E_BAD_FEATURE;
833                                 goto out;
834                         }
835                 }
836         }
837         PARA_DEBUG_LOG("received auth request for user %s\n", username);
838         *u = user_list_lookup(username);
839         ret = 1;
840 out:
841         free_argv(features);
842         return ret;
843 }
844
845 #define HANDSHAKE_BUFSIZE 4096
846
847 static int run_command(struct command_context *cc, struct iovec *iov)
848 {
849         int ret, i, argc;
850         char *p, *end, **argv;
851         const struct lls_command *lcmd = NULL;
852         unsigned perms;
853         struct lls_parse_result *lpr;
854         char *errctx;
855
856         if (iov->iov_base == NULL || iov->iov_len == 0)
857                 return -ERRNO_TO_PARA_ERROR(EINVAL);
858         p = iov->iov_base;
859         p[iov->iov_len - 1] = '\0'; /* just to be sure */
860
861         ret = lls(lls_lookup_subcmd(p, server_cmd_suite, &errctx));
862         if (ret < 0) {
863                 send_errctx(cc, errctx);
864                 return ret;
865         }
866         perms = server_command_perms[ret];
867         if ((perms & cc->u->perms) != perms)
868                 return -ERRNO_TO_PARA_ERROR(EPERM);
869         lcmd = lls_cmd(ret, server_cmd_suite);
870         end = iov->iov_base + iov->iov_len;
871         for (i = 0; p < end; i++)
872                 p += strlen(p) + 1;
873         argc = i;
874         argv = arr_alloc(argc + 1, sizeof(char *));
875         for (i = 0, p = iov->iov_base; p < end; i++) {
876                 argv[i] = para_strdup(p);
877                 p += strlen(p) + 1;
878         }
879         argv[argc] = NULL;
880         PARA_NOTICE_LOG("calling com_%s() for user %s\n",
881                 lls_command_name(lcmd), cc->u->name);
882         ret = lls(lls_parse(argc, argv, lcmd, &lpr, &errctx));
883         if (ret >= 0) {
884                 const struct server_cmd_user_data *ud = lls_user_data(lcmd);
885                 ret = ud->handler(cc, lpr);
886                 lls_free_parse_result(lpr, lcmd);
887         } else
888                 send_errctx(cc, errctx);
889         free_argv(argv);
890         mutex_lock(mmd_mutex);
891         mmd->num_commands++;
892         if (ret >= 0 && (perms & AFS_WRITE))
893                 mmd->events++;
894         mutex_unlock(mmd_mutex);
895         return ret;
896 }
897
898 /**
899  * Perform user authentication and execute a command.
900  *
901  * \param fd The file descriptor to send output to.
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. If the
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 encrypted with this session key using a stream cipher.
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 this command, the function calls the corresponding
914  * command handler which performs argument checking and further processing.
915  *
916  * To cope with DOS attacks, a timer is set up right after the fork. If the
917  * connection was still not authenticated when the timeout expires, the child
918  * process is terminated.
919  *
920  * \return Standard.
921  *
922  * \sa alarm(2), \ref openssl.c, \ref crypt.h.
923  */
924 int handle_connect(int fd)
925 {
926         int ret;
927         unsigned char rand_buf[APC_CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
928         unsigned char challenge_hash[HASH2_SIZE];
929         char *command = NULL, *buf = alloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
930         size_t numbytes;
931         struct command_context cc_struct = {.u = NULL}, *cc = &cc_struct;
932         struct iovec iov;
933         struct connection_features cf;
934
935         cc->scc.fd = fd;
936         reset_signals();
937         /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
938         ret = mark_fd_blocking(fd);
939         if (ret < 0)
940                 goto net_err;
941         /* send Welcome message */
942         ret = write_va_buffer(fd, "This is para_server, version "
943                 PACKAGE_VERSION ".\n"
944                 "Features: sha256\n" /* no longer announce this after 0.8.0 */
945         );
946         if (ret < 0)
947                 goto net_err;
948         /* recv auth request line */
949         ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
950         if (ret < 0)
951                 goto net_err;
952         ret = parse_auth_request(buf, ret, &cc->u, &cf);
953         if (ret < 0)
954                 goto net_err;
955         if (cc->u) {
956                 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
957                 ret = apc_pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
958                         (unsigned char *)buf);
959                 if (ret < 0)
960                         goto net_err;
961                 numbytes = ret;
962         } else {
963                 /*
964                  * We don't want to reveal our user names, so we send a
965                  * challenge to the client even if the user does not exist, and
966                  * fail the authentication later.
967                  */
968                 numbytes = 256;
969                 get_random_bytes_or_die((unsigned char *)buf, numbytes);
970         }
971         PARA_DEBUG_LOG("sending %d byte challenge + session key (%zu bytes)\n",
972                 APC_CHALLENGE_SIZE, numbytes);
973         ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
974         buf = NULL;
975         if (ret < 0)
976                 goto net_err;
977         ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
978                 HANDSHAKE_BUFSIZE, &iov);
979         if (ret < 0)
980                 goto net_err;
981         buf = iov.iov_base;
982         numbytes = iov.iov_len;
983         PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
984         ret = -E_BAD_USER;
985         if (!cc->u)
986                 goto net_err;
987         /*
988          * The correct response is the hash of the first APC_CHALLENGE_SIZE bytes
989          * of the random data.
990          */
991         ret = -E_BAD_AUTH;
992         if (cf.sha256_requested) {
993                 if (numbytes != HASH2_SIZE)
994                         goto net_err;
995                 hash2_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
996                 if (memcmp(challenge_hash, buf, HASH2_SIZE))
997                         goto net_err;
998         } else { /* old client. This can be removed after 0.7.0 */
999                 if (numbytes != HASH_SIZE)
1000                         goto net_err;
1001                 hash_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
1002                 if (memcmp(challenge_hash, buf, HASH_SIZE))
1003                         goto net_err;
1004         }
1005         /* auth successful */
1006         alarm(0);
1007         PARA_INFO_LOG("good auth for %s\n", cc->u->name);
1008         /* init stream cipher keys with the second part of the random buffer */
1009         cc->scc.recv = sc_new(rand_buf + APC_CHALLENGE_SIZE, SESSION_KEY_LEN);
1010         cc->scc.send = sc_new(rand_buf + APC_CHALLENGE_SIZE + SESSION_KEY_LEN,
1011                 SESSION_KEY_LEN);
1012         ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
1013         if (ret < 0)
1014                 goto net_err;
1015         ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
1016         if (ret < 0)
1017                 goto net_err;
1018         ret = run_command(cc, &iov);
1019         free(iov.iov_base);
1020         if (ret < 0)
1021                 goto err_out;
1022         if (ret >= 0)
1023                 goto out;
1024 err_out:
1025         if (send_strerror(cc, -ret) >= 0)
1026                 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
1027 net_err:
1028         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1029 out:
1030         free(buf);
1031         free(command);
1032         mutex_lock(mmd_mutex);
1033         mmd->active_connections--;
1034         mutex_unlock(mmd_mutex);
1035         if (ret >= 0) {
1036                 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1037                 if (ret < 0)
1038                         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1039         }
1040         sc_free(cc->scc.recv);
1041         sc_free(cc->scc.send);
1042         return ret;
1043 }