]> git.tuebingen.mpg.de Git - paraslash.git/blob - command.c
server: Fix race condition in com_stat().
[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         para_block_signal(SIGUSR1);
518         for (;;) {
519                 sigset_t set;
520                 /*
521                  * Copy the mmd structure to minimize the time we hold the mmd
522                  * lock.
523                  */
524                 mutex_lock(mmd_mutex);
525                 *nmmd = *mmd;
526                 mutex_unlock(mmd_mutex);
527                 ret = get_status(nmmd, parser_friendly, &s);
528                 ret = send_sb(&cc->scc, s, ret, SBD_OUTPUT, false);
529                 if (ret < 0)
530                         goto out;
531                 if (nmmd->vss_status_flags & VSS_NEXT) {
532                         char *esi;
533                         ret = empty_status_items(parser_friendly, &esi);
534                         ret = send_sb(&cc->scc, esi, ret, SBD_OUTPUT, false);
535                         if (ret < 0)
536                                 goto out;
537                 } else
538                         send_afs_status(cc, parser_friendly);
539                 ret = 1;
540                 if (num > 0 && !--num)
541                         goto out;
542                 sigemptyset(&set); /* empty set means: unblock all signals */
543                 /*
544                  * pselect(2) allows to atomically unblock signals, then go to
545                  * sleep. Calling sigprocmask(2) followed by sleep(3) would
546                  * open a race window similar to the one described above.
547                  */
548                 pselect(1, NULL, NULL, NULL, &ts, &set);
549                 if (subcmd_should_die) {
550                         PARA_EMERG_LOG("terminating on SIGTERM\n");
551                         goto out;
552                 }
553                 ret = -E_SERVER_CRASH;
554                 if (getppid() == 1)
555                         goto out;
556         }
557 out:
558         return ret;
559 }
560 EXPORT_SERVER_CMD_HANDLER(stat);
561
562 static const char *aux_info_cb(unsigned cmd_num, bool verbose)
563 {
564         static char result[80];
565         unsigned perms = server_command_perms[cmd_num];
566
567         if (verbose) {
568                 /* permissions: VSS_READ | VSS_WRITE */
569                 sprintf(result, "permissions: %s",
570                         server_command_perms_txt[cmd_num]);
571         } else {
572                 result[0] = perms & AFS_READ? 'a' : '-';
573                 result[1] = perms & AFS_WRITE? 'A' : '-';
574                 result[2] = perms & VSS_READ? 'v' : '-';
575                 result[3] = perms & VSS_WRITE? 'V' : '-';
576                 result[4] = '\0';
577         }
578         return result;
579 }
580
581 static int com_help(struct command_context *cc, struct lls_parse_result *lpr)
582 {
583         char *buf;
584         int ret;
585         unsigned n;
586         bool long_help = SERVER_CMD_OPT_GIVEN(HELP, LONG, lpr);
587
588         lsu_com_help(long_help, lpr, server_cmd_suite, aux_info_cb, &buf, &n);
589         ret = send_sb(&cc->scc, buf, n, SBD_OUTPUT, false);
590         return ret;
591 }
592 EXPORT_SERVER_CMD_HANDLER(help);
593
594 static int com_hup(__a_unused struct command_context *cc,
595                 __a_unused struct lls_parse_result *lpr)
596 {
597         kill(getppid(), SIGHUP);
598         return 1;
599 }
600 EXPORT_SERVER_CMD_HANDLER(hup);
601
602 static int com_term(__a_unused struct command_context *cc,
603                 __a_unused struct lls_parse_result *lpr)
604 {
605         kill(getppid(), SIGTERM);
606         return 1;
607 }
608 EXPORT_SERVER_CMD_HANDLER(term);
609
610 static int com_play(__a_unused struct command_context *cc,
611                 __a_unused struct lls_parse_result *lpr)
612 {
613         mutex_lock(mmd_mutex);
614         mmd->new_vss_status_flags |= VSS_PLAYING;
615         mmd->new_vss_status_flags &= ~VSS_NOMORE;
616         mutex_unlock(mmd_mutex);
617         return 1;
618 }
619 EXPORT_SERVER_CMD_HANDLER(play);
620
621 static int com_stop(__a_unused struct command_context *cc,
622                 __a_unused struct lls_parse_result *lpr)
623 {
624         mutex_lock(mmd_mutex);
625         mmd->new_vss_status_flags &= ~VSS_PLAYING;
626         mmd->new_vss_status_flags &= ~VSS_REPOS;
627         mmd->new_vss_status_flags |= VSS_NEXT;
628         mutex_unlock(mmd_mutex);
629         return 1;
630 }
631 EXPORT_SERVER_CMD_HANDLER(stop);
632
633 static int com_pause(__a_unused struct command_context *cc,
634                 __a_unused struct lls_parse_result *lpr)
635 {
636         mutex_lock(mmd_mutex);
637         if (!vss_paused() && !vss_stopped()) {
638                 mmd->events++;
639                 mmd->new_vss_status_flags &= ~VSS_PLAYING;
640                 mmd->new_vss_status_flags &= ~VSS_NEXT;
641         }
642         mutex_unlock(mmd_mutex);
643         return 1;
644 }
645 EXPORT_SERVER_CMD_HANDLER(pause);
646
647 static int com_next(__a_unused struct command_context *cc,
648                 __a_unused struct lls_parse_result *lpr)
649 {
650         mutex_lock(mmd_mutex);
651         mmd->events++;
652         mmd->new_vss_status_flags |= VSS_NEXT;
653         mutex_unlock(mmd_mutex);
654         return 1;
655 }
656 EXPORT_SERVER_CMD_HANDLER(next);
657
658 static int com_nomore(__a_unused struct command_context *cc,
659                 __a_unused struct lls_parse_result *lpr)
660 {
661         mutex_lock(mmd_mutex);
662         if (vss_playing() || vss_paused())
663                 mmd->new_vss_status_flags |= VSS_NOMORE;
664         mutex_unlock(mmd_mutex);
665         return 1;
666 }
667 EXPORT_SERVER_CMD_HANDLER(nomore);
668
669 static int com_ff(struct command_context *cc, struct lls_parse_result *lpr)
670 {
671         long promille;
672         int i, ret;
673         char c, *errctx;
674
675         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
676         if (ret < 0) {
677                 send_errctx(cc, errctx);
678                 return ret;
679         }
680         ret = para_atoi32(lls_input(0, lpr), &i);
681         if (ret < 0) {
682                 if (ret != -E_ATOI_JUNK_AT_END)
683                         return ret;
684                 /*
685                  * Compatibility code to keep the historic syntax (ff 30-)
686                  * working. This can be removed after 0.7.0.
687                  */
688                 ret = sscanf(lls_input(0, lpr), "%i%c", &i, &c);
689                 if (ret <= 0)
690                         return -E_COMMAND_SYNTAX;
691                 if (ret > 1 && c == '-') {
692                         PARA_WARNING_LOG("use of obsolete syntax\n");
693                         i = -i;
694                 }
695         }
696         mutex_lock(mmd_mutex);
697         ret = -E_NO_AUDIO_FILE;
698         if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
699                 goto out;
700         ret = 1;
701         promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
702         /*
703          * We need this cast because without it the expression on the right
704          * hand side is of unsigned type.
705          */
706         promille += 1000 * i / (int)mmd->afd.afhi.seconds_total;
707         if (promille < 0)
708                 promille = 0;
709         if (promille > 1000) {
710                 mmd->new_vss_status_flags |= VSS_NEXT;
711                 goto out;
712         }
713         mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
714         mmd->new_vss_status_flags |= VSS_REPOS;
715         mmd->new_vss_status_flags &= ~VSS_NEXT;
716         mmd->events++;
717 out:
718         mutex_unlock(mmd_mutex);
719         return ret;
720 }
721 EXPORT_SERVER_CMD_HANDLER(ff);
722
723 static int com_jmp(struct command_context *cc, struct lls_parse_result *lpr)
724 {
725         int i, ret;
726         char *errctx;
727
728         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
729         if (ret < 0) {
730                 send_errctx(cc, errctx);
731                 return ret;
732         }
733         if (sscanf(lls_input(0, lpr), "%d", &i) <= 0)
734                 return -ERRNO_TO_PARA_ERROR(EINVAL);
735         if (i < 0 || i > 100)
736                 return -ERRNO_TO_PARA_ERROR(EINVAL);
737         mutex_lock(mmd_mutex);
738         ret = -E_NO_AUDIO_FILE;
739         if (!mmd->afd.afhi.chunks_total)
740                 goto out;
741         PARA_INFO_LOG("jumping to %d%%\n", i);
742         mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50) / 100;
743         mmd->new_vss_status_flags |= VSS_REPOS;
744         mmd->new_vss_status_flags &= ~VSS_NEXT;
745         ret = 1;
746         mmd->events++;
747 out:
748         mutex_unlock(mmd_mutex);
749         return ret;
750 }
751 EXPORT_SERVER_CMD_HANDLER(jmp);
752
753 /* deprecated, does nothing */
754 static int com_tasks(__a_unused struct command_context *cc,
755                 __a_unused struct lls_parse_result *lpr)
756 {
757         return 1;
758 }
759 EXPORT_SERVER_CMD_HANDLER(tasks);
760
761 static void reset_signals(void)
762 {
763         para_sigaction(SIGCHLD, SIG_IGN);
764         para_sigaction(SIGINT, SIG_DFL);
765         para_sigaction(SIGTERM, SIG_DFL);
766         para_sigaction(SIGHUP, SIG_DFL);
767 }
768
769 struct connection_features {
770         int dummy; /* none at the moment */
771 };
772
773 static int parse_auth_request(char *buf, int len, const struct user **u,
774                 struct connection_features *cf)
775 {
776         int ret;
777         char *p, *username, **features = NULL;
778         size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
779
780         *u = NULL;
781         memset(cf, 0, sizeof(*cf));
782         if (len < auth_rq_len + 2)
783                 return -E_AUTH_REQUEST;
784         if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
785                 return -E_AUTH_REQUEST;
786         username = buf + auth_rq_len;
787         p = strchr(username, ' ');
788         if (p) {
789                 int i;
790                 if (p == username)
791                         return -E_AUTH_REQUEST;
792                 *p = '\0';
793                 p++;
794                 create_argv(p, ",", &features);
795                 for (i = 0; features[i]; i++) {
796                         if (strcmp(features[i], "sideband") == 0)
797                                 continue;
798                         if (strcmp(features[i], "aes_ctr128") == 0)
799                                 continue;
800                         else {
801                                 ret = -E_BAD_FEATURE;
802                                 goto out;
803                         }
804                 }
805         }
806         PARA_DEBUG_LOG("received auth request for user %s\n", username);
807         *u = user_list_lookup(username);
808         ret = 1;
809 out:
810         free_argv(features);
811         return ret;
812 }
813
814 #define HANDSHAKE_BUFSIZE 4096
815
816 static int run_command(struct command_context *cc, struct iovec *iov)
817 {
818         int ret, i, argc;
819         char *p, *end, **argv;
820         const struct lls_command *lcmd = NULL;
821         unsigned perms;
822         struct lls_parse_result *lpr;
823         char *errctx;
824
825         if (iov->iov_base == NULL || iov->iov_len == 0)
826                 return -ERRNO_TO_PARA_ERROR(EINVAL);
827         p = iov->iov_base;
828         p[iov->iov_len - 1] = '\0'; /* just to be sure */
829
830         ret = lls(lls_lookup_subcmd(p, server_cmd_suite, &errctx));
831         if (ret < 0) {
832                 send_errctx(cc, errctx);
833                 return ret;
834         }
835         perms = server_command_perms[ret];
836         if ((perms & cc->u->perms) != perms)
837                 return -E_PERM;
838         lcmd = lls_cmd(ret, server_cmd_suite);
839         end = iov->iov_base + iov->iov_len;
840         for (i = 0; p < end; i++)
841                 p += strlen(p) + 1;
842         argc = i;
843         argv = para_malloc((argc + 1) * sizeof(char *));
844         for (i = 0, p = iov->iov_base; p < end; i++) {
845                 argv[i] = para_strdup(p);
846                 p += strlen(p) + 1;
847         }
848         argv[argc] = NULL;
849         PARA_NOTICE_LOG("calling com_%s() for user %s\n",
850                 lls_command_name(lcmd), cc->u->name);
851         ret = lls(lls_parse(argc, argv, lcmd, &lpr, &errctx));
852         if (ret >= 0) {
853                 const struct server_cmd_user_data *ud = lls_user_data(lcmd);
854                 ret = ud->handler(cc, lpr);
855                 lls_free_parse_result(lpr, lcmd);
856         } else
857                 send_errctx(cc, errctx);
858         free_argv(argv);
859         mutex_lock(mmd_mutex);
860         mmd->num_commands++;
861         if (ret >= 0 && (perms & AFS_WRITE))
862                 mmd->events++;
863         mutex_unlock(mmd_mutex);
864         return ret;
865 }
866
867 /**
868  * Perform user authentication and execute a command.
869  *
870  * \param fd The file descriptor to send output to.
871  *
872  * Whenever para_server accepts an incoming tcp connection on the port it
873  * listens on, it forks and the resulting child calls this function.
874  *
875  * An RSA-based challenge/response is used to authenticate the peer. If the
876  * authentication succeeds, a random session key is generated and sent back to
877  * the peer, encrypted with its RSA public key. From this point on, all
878  * transfers are encrypted with this session key using a stream cipher.
879  *
880  * Next it is checked if the peer supplied a valid server command or a command
881  * for the audio file selector. If yes, and if the user has sufficient
882  * permissions to execute this command, the function calls the corresponding
883  * command handler which performs argument checking and further processing.
884  *
885  * To cope with DOS attacks, a timer is set up right after the fork. If the
886  * connection was still not authenticated when the timeout expires, the child
887  * process is terminated.
888  *
889  * \return Standard.
890  *
891  * \sa alarm(2), \ref openssl.c, \ref crypt.h.
892  */
893 int handle_connect(int fd)
894 {
895         int ret;
896         unsigned char rand_buf[APC_CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
897         unsigned char challenge_hash[HASH_SIZE];
898         char *command = NULL, *buf = para_malloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
899         size_t numbytes;
900         struct command_context cc_struct = {.u = NULL}, *cc = &cc_struct;
901         struct iovec iov;
902         struct connection_features cf;
903
904         cc->scc.fd = fd;
905         reset_signals();
906         /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
907         ret = mark_fd_blocking(fd);
908         if (ret < 0)
909                 goto net_err;
910         /* send Welcome message */
911         ret = write_va_buffer(fd, "This is para_server, version "
912                 PACKAGE_VERSION ".\n"
913                 "Features: sideband,aes_ctr128\n"
914         );
915         if (ret < 0)
916                 goto net_err;
917         /* recv auth request line */
918         ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
919         if (ret < 0)
920                 goto net_err;
921         ret = parse_auth_request(buf, ret, &cc->u, &cf);
922         if (ret < 0)
923                 goto net_err;
924         if (cc->u) {
925                 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
926                 ret = apc_pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
927                         (unsigned char *)buf);
928                 if (ret < 0)
929                         goto net_err;
930                 numbytes = ret;
931         } else {
932                 /*
933                  * We don't want to reveal our user names, so we send a
934                  * challenge to the client even if the user does not exist, and
935                  * fail the authentication later.
936                  */
937                 numbytes = 256;
938                 get_random_bytes_or_die((unsigned char *)buf, numbytes);
939         }
940         PARA_DEBUG_LOG("sending %d byte challenge + session key (%zu bytes)\n",
941                 APC_CHALLENGE_SIZE, numbytes);
942         ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
943         buf = NULL;
944         if (ret < 0)
945                 goto net_err;
946         ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
947                 HANDSHAKE_BUFSIZE, &iov);
948         if (ret < 0)
949                 goto net_err;
950         buf = iov.iov_base;
951         numbytes = iov.iov_len;
952         PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
953         ret = -E_BAD_USER;
954         if (!cc->u)
955                 goto net_err;
956         /*
957          * The correct response is the hash of the first APC_CHALLENGE_SIZE bytes
958          * of the random data.
959          */
960         ret = -E_BAD_AUTH;
961         if (numbytes != HASH_SIZE)
962                 goto net_err;
963         hash_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
964         if (memcmp(challenge_hash, buf, HASH_SIZE))
965                 goto net_err;
966         /* auth successful */
967         alarm(0);
968         PARA_INFO_LOG("good auth for %s\n", cc->u->name);
969         /* init stream cipher keys with the second part of the random buffer */
970         cc->scc.recv = sc_new(rand_buf + APC_CHALLENGE_SIZE, SESSION_KEY_LEN);
971         cc->scc.send = sc_new(rand_buf + APC_CHALLENGE_SIZE + SESSION_KEY_LEN,
972                 SESSION_KEY_LEN);
973         ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
974         if (ret < 0)
975                 goto net_err;
976         ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
977         if (ret < 0)
978                 goto net_err;
979         ret = run_command(cc, &iov);
980         free(iov.iov_base);
981         if (ret < 0)
982                 goto err_out;
983         if (ret >= 0)
984                 goto out;
985 err_out:
986         if (send_strerror(cc, -ret) >= 0)
987                 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
988 net_err:
989         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
990 out:
991         free(buf);
992         free(command);
993         mutex_lock(mmd_mutex);
994         mmd->active_connections--;
995         mutex_unlock(mmd_mutex);
996         if (ret >= 0) {
997                 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
998                 if (ret < 0)
999                         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1000         }
1001         sc_free(cc->scc.recv);
1002         sc_free(cc->scc.send);
1003         return ret;
1004 }