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