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