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