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