]> git.tuebingen.mpg.de Git - paraslash.git/blob - command.c
string: Introduce arr_alloc().
[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 = alloc(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 static void reset_signals(void)
745 {
746         para_sigaction(SIGCHLD, SIG_IGN);
747         para_sigaction(SIGINT, SIG_DFL);
748         para_sigaction(SIGTERM, SIG_DFL);
749         para_sigaction(SIGHUP, SIG_DFL);
750 }
751
752 struct connection_features {
753         bool sha256_requested; /* can be removed after 0.7.0 */
754 };
755
756 static int parse_auth_request(char *buf, int len, const struct user **u,
757                 struct connection_features *cf)
758 {
759         int ret;
760         char *p, *username, **features = NULL;
761         size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
762
763         *u = NULL;
764         memset(cf, 0, sizeof(*cf));
765         if (len < auth_rq_len + 2)
766                 return -E_AUTH_REQUEST;
767         if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
768                 return -E_AUTH_REQUEST;
769         username = buf + auth_rq_len;
770         p = strchr(username, ' ');
771         if (p) {
772                 int i;
773                 if (p == username)
774                         return -E_AUTH_REQUEST;
775                 *p = '\0';
776                 p++;
777                 create_argv(p, ",", &features);
778                 /*
779                  * Still accept sideband and AES feature requests (as a no-op)
780                  * because some 0.6.x clients request them. The two checks
781                  * below may be removed after 0.7.1.
782                  */
783                 for (i = 0; features[i]; i++) {
784                         if (strcmp(features[i], "sideband") == 0)
785                                 continue;
786                         if (strcmp(features[i], "aes_ctr128") == 0)
787                                 continue;
788                         /*
789                          * ->sha256_requested can go away after 0.7.0 but the
790                          * check has to stay until 0.9.0.
791                          */
792                         if (strcmp(features[i], "sha256") == 0)
793                                 cf->sha256_requested = true;
794                         else {
795                                 ret = -E_BAD_FEATURE;
796                                 goto out;
797                         }
798                 }
799         }
800         PARA_DEBUG_LOG("received auth request for user %s\n", username);
801         *u = user_list_lookup(username);
802         ret = 1;
803 out:
804         free_argv(features);
805         return ret;
806 }
807
808 #define HANDSHAKE_BUFSIZE 4096
809
810 static int run_command(struct command_context *cc, struct iovec *iov)
811 {
812         int ret, i, argc;
813         char *p, *end, **argv;
814         const struct lls_command *lcmd = NULL;
815         unsigned perms;
816         struct lls_parse_result *lpr;
817         char *errctx;
818
819         if (iov->iov_base == NULL || iov->iov_len == 0)
820                 return -ERRNO_TO_PARA_ERROR(EINVAL);
821         p = iov->iov_base;
822         p[iov->iov_len - 1] = '\0'; /* just to be sure */
823
824         ret = lls(lls_lookup_subcmd(p, server_cmd_suite, &errctx));
825         if (ret < 0) {
826                 send_errctx(cc, errctx);
827                 return ret;
828         }
829         perms = server_command_perms[ret];
830         if ((perms & cc->u->perms) != perms)
831                 return -ERRNO_TO_PARA_ERROR(EPERM);
832         lcmd = lls_cmd(ret, server_cmd_suite);
833         end = iov->iov_base + iov->iov_len;
834         for (i = 0; p < end; i++)
835                 p += strlen(p) + 1;
836         argc = i;
837         argv = arr_alloc(argc + 1, sizeof(char *));
838         for (i = 0, p = iov->iov_base; p < end; i++) {
839                 argv[i] = para_strdup(p);
840                 p += strlen(p) + 1;
841         }
842         argv[argc] = NULL;
843         PARA_NOTICE_LOG("calling com_%s() for user %s\n",
844                 lls_command_name(lcmd), cc->u->name);
845         ret = lls(lls_parse(argc, argv, lcmd, &lpr, &errctx));
846         if (ret >= 0) {
847                 const struct server_cmd_user_data *ud = lls_user_data(lcmd);
848                 ret = ud->handler(cc, lpr);
849                 lls_free_parse_result(lpr, lcmd);
850         } else
851                 send_errctx(cc, errctx);
852         free_argv(argv);
853         mutex_lock(mmd_mutex);
854         mmd->num_commands++;
855         if (ret >= 0 && (perms & AFS_WRITE))
856                 mmd->events++;
857         mutex_unlock(mmd_mutex);
858         return ret;
859 }
860
861 /**
862  * Perform user authentication and execute a command.
863  *
864  * \param fd The file descriptor to send output to.
865  *
866  * Whenever para_server accepts an incoming tcp connection on the port it
867  * listens on, it forks and the resulting child calls this function.
868  *
869  * An RSA-based challenge/response is used to authenticate the peer. If the
870  * authentication succeeds, a random session key is generated and sent back to
871  * the peer, encrypted with its RSA public key. From this point on, all
872  * transfers are encrypted with this session key using a stream cipher.
873  *
874  * Next it is checked if the peer supplied a valid server command or a command
875  * for the audio file selector. If yes, and if the user has sufficient
876  * permissions to execute this command, the function calls the corresponding
877  * command handler which performs argument checking and further processing.
878  *
879  * To cope with DOS attacks, a timer is set up right after the fork. If the
880  * connection was still not authenticated when the timeout expires, the child
881  * process is terminated.
882  *
883  * \return Standard.
884  *
885  * \sa alarm(2), \ref openssl.c, \ref crypt.h.
886  */
887 int handle_connect(int fd)
888 {
889         int ret;
890         unsigned char rand_buf[APC_CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
891         unsigned char challenge_hash[HASH2_SIZE];
892         char *command = NULL, *buf = alloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
893         size_t numbytes;
894         struct command_context cc_struct = {.u = NULL}, *cc = &cc_struct;
895         struct iovec iov;
896         struct connection_features cf;
897
898         cc->scc.fd = fd;
899         reset_signals();
900         /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
901         ret = mark_fd_blocking(fd);
902         if (ret < 0)
903                 goto net_err;
904         /* send Welcome message */
905         ret = write_va_buffer(fd, "This is para_server, version "
906                 PACKAGE_VERSION ".\n"
907                 "Features: sha256\n" /* no longer announce this after 0.8.0 */
908         );
909         if (ret < 0)
910                 goto net_err;
911         /* recv auth request line */
912         ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
913         if (ret < 0)
914                 goto net_err;
915         ret = parse_auth_request(buf, ret, &cc->u, &cf);
916         if (ret < 0)
917                 goto net_err;
918         if (cc->u) {
919                 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
920                 ret = apc_pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
921                         (unsigned char *)buf);
922                 if (ret < 0)
923                         goto net_err;
924                 numbytes = ret;
925         } else {
926                 /*
927                  * We don't want to reveal our user names, so we send a
928                  * challenge to the client even if the user does not exist, and
929                  * fail the authentication later.
930                  */
931                 numbytes = 256;
932                 get_random_bytes_or_die((unsigned char *)buf, numbytes);
933         }
934         PARA_DEBUG_LOG("sending %d byte challenge + session key (%zu bytes)\n",
935                 APC_CHALLENGE_SIZE, numbytes);
936         ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
937         buf = NULL;
938         if (ret < 0)
939                 goto net_err;
940         ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
941                 HANDSHAKE_BUFSIZE, &iov);
942         if (ret < 0)
943                 goto net_err;
944         buf = iov.iov_base;
945         numbytes = iov.iov_len;
946         PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
947         ret = -E_BAD_USER;
948         if (!cc->u)
949                 goto net_err;
950         /*
951          * The correct response is the hash of the first APC_CHALLENGE_SIZE bytes
952          * of the random data.
953          */
954         ret = -E_BAD_AUTH;
955         if (cf.sha256_requested) {
956                 if (numbytes != HASH2_SIZE)
957                         goto net_err;
958                 hash2_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
959                 if (memcmp(challenge_hash, buf, HASH2_SIZE))
960                         goto net_err;
961         } else { /* old client. This can be removed after 0.7.0 */
962                 if (numbytes != HASH_SIZE)
963                         goto net_err;
964                 hash_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
965                 if (memcmp(challenge_hash, buf, HASH_SIZE))
966                         goto net_err;
967         }
968         /* auth successful */
969         alarm(0);
970         PARA_INFO_LOG("good auth for %s\n", cc->u->name);
971         /* init stream cipher keys with the second part of the random buffer */
972         cc->scc.recv = sc_new(rand_buf + APC_CHALLENGE_SIZE, SESSION_KEY_LEN);
973         cc->scc.send = sc_new(rand_buf + APC_CHALLENGE_SIZE + SESSION_KEY_LEN,
974                 SESSION_KEY_LEN);
975         ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
976         if (ret < 0)
977                 goto net_err;
978         ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
979         if (ret < 0)
980                 goto net_err;
981         ret = run_command(cc, &iov);
982         free(iov.iov_base);
983         if (ret < 0)
984                 goto err_out;
985         if (ret >= 0)
986                 goto out;
987 err_out:
988         if (send_strerror(cc, -ret) >= 0)
989                 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
990 net_err:
991         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
992 out:
993         free(buf);
994         free(command);
995         mutex_lock(mmd_mutex);
996         mmd->active_connections--;
997         mutex_unlock(mmd_mutex);
998         if (ret >= 0) {
999                 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1000                 if (ret < 0)
1001                         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1002         }
1003         sc_free(cc->scc.recv);
1004         sc_free(cc->scc.send);
1005         return ret;
1006 }