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