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