aaaaaecf02084c188482214bebd3df433c54e72b
[paraslash.git] / command.c
1 /*
2 * Copyright (C) 1997-2013 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file command.c Client authentication and server commands. */
8
9 #include <regex.h>
10 #include <signal.h>
11 #include <sys/time.h>
12 #include <sys/types.h>
13 #include <osl.h>
14
15 #include "para.h"
16 #include "error.h"
17 #include "crypt.h"
18 #include "sideband.h"
19 #include "command.h"
20 #include "server.cmdline.h"
21 #include "string.h"
22 #include "afh.h"
23 #include "afs.h"
24 #include "server.h"
25 #include "list.h"
26 #include "send.h"
27 #include "sched.h"
28 #include "vss.h"
29 #include "net.h"
30 #include "daemon.h"
31 #include "fd.h"
32 #include "ipc.h"
33 #include "user_list.h"
34 #include "server_command_list.h"
35 #include "afs_command_list.h"
36 #include "signal.h"
37 #include "version.h"
38
39 struct server_command afs_cmds[] = {DEFINE_AFS_CMD_ARRAY};
40 struct server_command server_cmds[] = {DEFINE_SERVER_CMD_ARRAY};
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 extern struct sender senders[];
48 int send_afs_status(struct command_context *cc, int parser_friendly);
49
50 static void dummy(__a_unused int s)
51 {
52 }
53
54 static void mmd_dup(struct misc_meta_data *new_mmd)
55 {
56 mutex_lock(mmd_mutex);
57 *new_mmd = *mmd;
58 mutex_unlock(mmd_mutex);
59 }
60
61 /*
62 * Compute human readable string containing vss status for given integer value.
63 *
64 * We don't want to use vss_playing() and friends here because we take a
65 * snapshot of the mmd struct and use the copy for computing the state of the
66 * vss. If the real data were used, we would take the mmd lock for a rather
67 * long time or risk to get an inconsistent view.
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 * return human readable permission string. Never returns NULL.
80 */
81 static char *cmd_perms_itohuman(unsigned int perms)
82 {
83 char *msg = para_malloc(5 * sizeof(char));
84
85 msg[0] = perms & AFS_READ? 'a' : '-';
86 msg[1] = perms & AFS_WRITE? 'A' : '-';
87 msg[2] = perms & VSS_READ? 'v' : '-';
88 msg[3] = perms & VSS_WRITE? 'V' : '-';
89 msg[4] = '\0';
90 return msg;
91 }
92
93 /*
94 * Never returns NULL.
95 */
96 static char *vss_get_status_flags(unsigned int flags)
97 {
98 char *msg = para_malloc(5 * sizeof(char));
99
100 msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
101 msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
102 msg[2] = (flags & VSS_NEXT)? 'N' : '_';
103 msg[3] = (flags & VSS_REPOS)? 'R' : '_';
104 msg[4] = '\0';
105 return msg;
106 }
107
108 static unsigned get_status(struct misc_meta_data *nmmd, int parser_friendly,
109 char **result)
110 {
111 char mtime[30] = "";
112 char *status, *flags; /* vss status info */
113 /* nobody updates our version of "now" */
114 char *ut = get_server_uptime_str(NULL);
115 long offset = (nmmd->offset + 500) / 1000;
116 struct timeval current_time;
117 struct tm mtime_tm;
118 struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
119
120 /* report real status */
121 status = vss_status_tohuman(nmmd->vss_status_flags);
122 flags = vss_get_status_flags(nmmd->vss_status_flags);
123 if (nmmd->size) { /* parent currently has an audio file open */
124 localtime_r(&nmmd->mtime, &mtime_tm);
125 strftime(mtime, 29, "%b %d %Y", &mtime_tm);
126 }
127 gettimeofday(&current_time, NULL);
128 /*
129 * The calls to WRITE_STATUS_ITEM() below never fail because
130 * b->max_size is zero (unlimited), see para_printf(). However, clang
131 * is not smart enough to prove this and complains nevertheless.
132 * Casting the return value to void silences clang.
133 */
134 (void)WRITE_STATUS_ITEM(&b, SI_FILE_SIZE, "%zu\n", nmmd->size / 1024);
135 (void)WRITE_STATUS_ITEM(&b, SI_MTIME, "%s\n", mtime);
136 (void)WRITE_STATUS_ITEM(&b, SI_STATUS, "%s\n", status);
137 (void)WRITE_STATUS_ITEM(&b, SI_STATUS_FLAGS, "%s\n", flags);
138 (void)WRITE_STATUS_ITEM(&b, SI_OFFSET, "%li\n", offset);
139 (void)WRITE_STATUS_ITEM(&b, SI_AFS_MODE, "%s\n", mmd->afs_mode_string);
140 (void)WRITE_STATUS_ITEM(&b, SI_STREAM_START, "%lu.%lu\n",
141 (long unsigned)nmmd->stream_start.tv_sec,
142 (long unsigned)nmmd->stream_start.tv_usec);
143 (void)WRITE_STATUS_ITEM(&b, SI_CURRENT_TIME, "%lu.%lu\n",
144 (long unsigned)current_time.tv_sec,
145 (long unsigned)current_time.tv_usec);
146 free(flags);
147 free(status);
148 free(ut);
149 *result = b.buf;
150 return b.offset;
151 }
152
153 static int check_sender_args(int argc, char * const * argv, struct sender_command_data *scd)
154 {
155 int i;
156 /* this has to match sender.h */
157 const char *subcmds[] = {"add", "delete", "allow", "deny", "on", "off", NULL};
158
159 scd->sender_num = -1;
160 if (argc < 2)
161 return -E_COMMAND_SYNTAX;
162 for (i = 0; senders[i].name; i++)
163 if (!strcmp(senders[i].name, argv[1]))
164 break;
165 PARA_DEBUG_LOG("%d:%s\n", argc, argv[1]);
166 if (!senders[i].name)
167 return -E_COMMAND_SYNTAX;
168 scd->sender_num = i;
169 for (i = 0; subcmds[i]; i++)
170 if (!strcmp(subcmds[i], argv[2]))
171 break;
172 if (!subcmds[i])
173 return -E_COMMAND_SYNTAX;
174 scd->cmd_num = i;
175 if (!senders[scd->sender_num].client_cmds[scd->cmd_num])
176 return -E_SENDER_CMD;
177 switch (scd->cmd_num) {
178 case SENDER_ON:
179 case SENDER_OFF:
180 if (argc != 3)
181 return -E_COMMAND_SYNTAX;
182 break;
183 case SENDER_DENY:
184 case SENDER_ALLOW:
185 if (argc != 4 || parse_cidr(argv[3], scd->host,
186 sizeof(scd->host), &scd->netmask) == NULL)
187 return -E_COMMAND_SYNTAX;
188 break;
189 case SENDER_ADD:
190 case SENDER_DELETE:
191 if (argc != 4)
192 return -E_COMMAND_SYNTAX;
193 return parse_fec_url(argv[3], scd);
194 default:
195 return -E_COMMAND_SYNTAX;
196 }
197 return 1;
198 }
199
200 /**
201 * Send a sideband packet through a blocking file descriptor.
202 *
203 * \param scc fd and crypto keys.
204 * \param buf The buffer to send.
205 * \param numbytes The size of \a buf.
206 * \param band The sideband designator of this packet.
207 * \param dont_free If true, never deallocate \a buf.
208 *
209 * The nonblock flag must be disabled for the file descriptor given by \a scc.
210 *
211 * Stream cipher encryption is automatically activated if neccessary via the
212 * sideband transformation, depending on the value of \a band.
213 *
214 * \return Standard.
215 *
216 * \sa \ref send_sb_va().
217 */
218 int send_sb(struct stream_cipher_context *scc, void *buf, size_t numbytes,
219 int band, bool dont_free)
220 {
221 int ret;
222 struct sb_context *sbc;
223 struct iovec iov[2];
224 struct sb_buffer sbb = SBB_INIT(band, buf, numbytes);
225 sb_transformation trafo = band < SBD_PROCEED? NULL : sc_trafo;
226
227 sbc = sb_new_send(&sbb, dont_free, trafo, scc->send);
228 do {
229 ret = sb_get_send_buffers(sbc, iov);
230 ret = xwritev(scc->fd, iov, ret);
231 if (ret < 0)
232 goto fail;
233 } while (sb_sent(sbc, ret) == false);
234 return 1;
235 fail:
236 sb_free(sbc);
237 return ret;
238 }
239
240 /**
241 * Create a variable sized buffer and send it as a sideband packet.
242 *
243 * \param scc Passed to \ref send_sb.
244 * \param band See \ref send_sb.
245 * \param fmt The format string.
246 *
247 * \return The return value of the underlying call to \ref send_sb.
248 */
249 __printf_3_4 int send_sb_va(struct stream_cipher_context *scc, int band,
250 const char *fmt, ...)
251 {
252 va_list ap;
253 char *msg;
254 int ret;
255
256 va_start(ap, fmt);
257 ret = xvasprintf(&msg, fmt, ap);
258 va_end(ap);
259 return send_sb(scc, msg, ret, band, false);
260 }
261
262 /**
263 * Send an error message to a client.
264 *
265 * \param cc Client info.
266 * \param err The (positive) error code.
267 *
268 * \return The return value of the underlying call to send_sb_va().
269 */
270 int send_strerror(struct command_context *cc, int err)
271 {
272 return cc->use_sideband?
273 send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", para_strerror(err))
274 :
275 sc_send_va_buffer(&cc->scc, "%s\n", para_strerror(err));
276 }
277
278 /**
279 * Send a sideband packet through 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)
329 {
330 int i, ret = 0;
331 char *msg = NULL;
332 struct sender_command_data scd;
333
334 if (cc->argc < 2) {
335 for (i = 0; senders[i].name; 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 if (cc->use_sideband)
343 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
344 ret = sc_send_buffer(&cc->scc, msg);
345 free(msg);
346 return ret;
347 }
348 ret = check_sender_args(cc->argc, cc->argv, &scd);
349 if (ret < 0) {
350 if (scd.sender_num < 0)
351 return ret;
352 msg = senders[scd.sender_num].help();
353 if (cc->use_sideband)
354 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT,
355 false);
356 ret = sc_send_buffer(&cc->scc, msg);
357 free(msg);
358 return ret;
359 }
360
361 switch (scd.cmd_num) {
362 case SENDER_ADD:
363 case SENDER_DELETE:
364 assert(senders[scd.sender_num].resolve_target);
365 ret = senders[scd.sender_num].resolve_target(cc->argv[3], &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 mutex_unlock(mmd_mutex);
374 usleep(100 * 1000);
375 continue;
376 }
377 memcpy(&mmd->sender_cmd_data, &scd, sizeof(scd));
378 mutex_unlock(mmd_mutex);
379 break;
380 }
381 return (i < 10)? 1 : -E_LOCK;
382 }
383
384 /* server info */
385 static int com_si(struct command_context *cc)
386 {
387 int i, ret;
388 char *msg, *ut, *sender_info = NULL;
389
390 if (cc->argc != 1)
391 return -E_COMMAND_SYNTAX;
392 mutex_lock(mmd_mutex);
393 for (i = 0; senders[i].name; i++) {
394 char *info = senders[i].info();
395 sender_info = para_strcat(sender_info, info);
396 free(info);
397 }
398 ut = get_server_uptime_str(now);
399 ret = xasprintf(&msg, "version: " GIT_VERSION "\n"
400 "up: %s\nplayed: %u\n"
401 "server_pid: %d\n"
402 "afs_pid: %d\n"
403 "connections (active/accepted/total): %u/%u/%u\n"
404 "current loglevel: %s\n"
405 "supported audio formats: %s\n"
406 "%s",
407 ut, mmd->num_played,
408 (int)getppid(),
409 (int)mmd->afs_pid,
410 mmd->active_connections,
411 mmd->num_commands,
412 mmd->num_connects,
413 conf.loglevel_arg,
414 AUDIO_FORMAT_HANDLERS,
415 sender_info
416 );
417 mutex_unlock(mmd_mutex);
418 free(ut);
419 free(sender_info);
420 if (cc->use_sideband)
421 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
422 ret = sc_send_bin_buffer(&cc->scc, msg, ret);
423 free(msg);
424 return ret;
425 }
426
427 /* version */
428 static int com_version(struct command_context *cc)
429 {
430 char *msg;
431 size_t len;
432
433 if (cc->argc != 1)
434 return -E_COMMAND_SYNTAX;
435 msg = VERSION_TEXT("server") "built: " BUILD_DATE "\n" UNAME_RS
436 ", " CC_VERSION "\n";
437 len = strlen(msg);
438 if (cc->use_sideband)
439 return send_sb(&cc->scc, msg, len, SBD_OUTPUT, true);
440 return sc_send_bin_buffer(&cc->scc, msg, len);
441 }
442
443 #define EMPTY_STATUS_ITEMS \
444 ITEM(PATH) \
445 ITEM(DIRECTORY) \
446 ITEM(BASENAME) \
447 ITEM(SCORE) \
448 ITEM(ATTRIBUTES_BITMAP) \
449 ITEM(ATTRIBUTES_TXT) \
450 ITEM(HASH) \
451 ITEM(IMAGE_ID) \
452 ITEM(IMAGE_NAME) \
453 ITEM(LYRICS_ID) \
454 ITEM(LYRICS_NAME) \
455 ITEM(BITRATE) \
456 ITEM(FORMAT) \
457 ITEM(FREQUENCY) \
458 ITEM(CHANNELS) \
459 ITEM(DURATION) \
460 ITEM(SECONDS_TOTAL) \
461 ITEM(NUM_PLAYED) \
462 ITEM(LAST_PLAYED) \
463 ITEM(TECHINFO) \
464 ITEM(ARTIST) \
465 ITEM(TITLE) \
466 ITEM(YEAR) \
467 ITEM(ALBUM) \
468 ITEM(COMMENT) \
469 ITEM(AMPLIFICATION)
470
471 /**
472 * Write a list of audio-file related status items with empty values.
473 *
474 * This is used by vss when currently no audio file is open.
475 */
476 static unsigned empty_status_items(int parser_friendly, char **result)
477 {
478 static char *esi;
479 static unsigned len;
480
481 if (esi)
482 goto out;
483
484 if (parser_friendly)
485 len = xasprintf(&esi,
486 #define ITEM(x) "0004 %02x:\n"
487 EMPTY_STATUS_ITEMS
488 #undef ITEM
489 #define ITEM(x) , SI_ ## x
490 EMPTY_STATUS_ITEMS
491 #undef ITEM
492 );
493 else
494 len = xasprintf(&esi,
495 #define ITEM(x) "%s:\n"
496 EMPTY_STATUS_ITEMS
497 #undef ITEM
498 #define ITEM(x) ,status_item_list[SI_ ## x]
499 EMPTY_STATUS_ITEMS
500 #undef ITEM
501 );
502 out:
503 *result = esi;
504 return len;
505 }
506 #undef EMPTY_STATUS_ITEMS
507
508 /* stat */
509 static int com_stat(struct command_context *cc)
510 {
511 int i, ret;
512 struct misc_meta_data tmp, *nmmd = &tmp;
513 char *s, *esi = NULL;
514 int32_t num = 0;
515 int parser_friendly = 0;
516
517 para_sigaction(SIGUSR1, dummy);
518
519 for (i = 1; i < cc->argc; i++) {
520 const char *arg = cc->argv[i];
521 if (arg[0] != '-')
522 break;
523 if (!strcmp(arg, "--")) {
524 i++;
525 break;
526 }
527 if (!strncmp(arg, "-n=", 3)) {
528 ret = para_atoi32(arg + 3, &num);
529 if (ret < 0)
530 return ret;
531 continue;
532 }
533 if (!strcmp(arg, "-p")) {
534 parser_friendly = 1;
535 continue;
536 }
537 return -E_COMMAND_SYNTAX;
538 }
539 if (i != cc->argc)
540 return -E_COMMAND_SYNTAX;
541 for (;;) {
542 mmd_dup(nmmd);
543 ret = get_status(nmmd, parser_friendly, &s);
544 if (cc->use_sideband)
545 ret = send_sb(&cc->scc, s, ret, SBD_OUTPUT, false);
546 else {
547 ret = sc_send_bin_buffer(&cc->scc, s, ret);
548 free(s);
549 }
550 if (ret < 0)
551 goto out;
552 if (nmmd->vss_status_flags & VSS_NEXT) {
553 ret = empty_status_items(parser_friendly, &esi);
554 if (cc->use_sideband)
555 ret = send_sb(&cc->scc, esi, ret, SBD_OUTPUT,
556 true);
557 else
558 ret = sc_send_bin_buffer(&cc->scc, esi, ret);
559 if (ret < 0)
560 goto out;
561 } else
562 send_afs_status(cc, parser_friendly);
563 ret = 1;
564 if (num > 0 && !--num)
565 goto out;
566 sleep(50);
567 ret = -E_SERVER_CRASH;
568 if (getppid() == 1)
569 goto out;
570 }
571 out:
572 free(esi);
573 return ret;
574 }
575
576 static int send_list_of_commands(struct command_context *cc, struct server_command *cmd,
577 const char *handler)
578 {
579 int ret;
580 char *msg = NULL;
581
582 for (; cmd->name; cmd++) {
583 char *tmp, *perms = cmd_perms_itohuman(cmd->perms);
584 tmp = make_message("%s\t%s\t%s\t%s\n", cmd->name, handler,
585 perms, cmd->description);
586 free(perms);
587 msg = para_strcat(msg, tmp);
588 free(tmp);
589 }
590 if (cc->use_sideband)
591 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
592 ret = sc_send_buffer(&cc->scc, msg);
593 free(msg);
594 return ret;
595 }
596
597 /* returns string that must be freed by the caller */
598 static struct server_command *get_cmd_ptr(const char *name, char **handler)
599 {
600 struct server_command *cmd;
601
602 for (cmd = server_cmds; cmd->name; cmd++)
603 if (!strcmp(cmd->name, name)) {
604 if (handler)
605 *handler = para_strdup("server"); /* server commands */
606 return cmd;
607 }
608 /* not found, look for commands supported by afs */
609 for (cmd = afs_cmds; cmd->name; cmd++)
610 if (!strcmp(cmd->name, name)) {
611 if (handler)
612 *handler = para_strdup("afs");
613 return cmd;
614 }
615 return NULL;
616 }
617
618 /* help */
619 static int com_help(struct command_context *cc)
620 {
621 struct server_command *cmd;
622 char *perms, *handler, *buf;
623 int ret;
624
625 if (cc->argc < 2) {
626 /* no argument given, print list of commands */
627 if ((ret = send_list_of_commands(cc, server_cmds, "server")) < 0)
628 return ret;
629 return send_list_of_commands(cc, afs_cmds, "afs");
630 }
631 /* argument given for help */
632 cmd = get_cmd_ptr(cc->argv[1], &handler);
633 if (!cmd)
634 return -E_BAD_CMD;
635 perms = cmd_perms_itohuman(cmd->perms);
636 ret = xasprintf(&buf, "%s - %s\n\n"
637 "handler: %s\n"
638 "permissions: %s\n"
639 "usage: %s\n\n"
640 "%s\n",
641 cc->argv[1],
642 cmd->description,
643 handler,
644 perms,
645 cmd->usage,
646 cmd->help
647 );
648 free(perms);
649 free(handler);
650 if (cc->use_sideband)
651 return send_sb(&cc->scc, buf, ret, SBD_OUTPUT, false);
652 ret = sc_send_buffer(&cc->scc, buf);
653 free(buf);
654 return ret;
655 }
656
657 /* hup */
658 static int com_hup(struct command_context *cc)
659 {
660 if (cc->argc != 1)
661 return -E_COMMAND_SYNTAX;
662 kill(getppid(), SIGHUP);
663 return 1;
664 }
665
666 /* term */
667 static int com_term(struct command_context *cc)
668 {
669 if (cc->argc != 1)
670 return -E_COMMAND_SYNTAX;
671 kill(getppid(), SIGTERM);
672 return 1;
673 }
674
675 static int com_play(struct command_context *cc)
676 {
677 if (cc->argc != 1)
678 return -E_COMMAND_SYNTAX;
679 mutex_lock(mmd_mutex);
680 mmd->new_vss_status_flags |= VSS_PLAYING;
681 mmd->new_vss_status_flags &= ~VSS_NOMORE;
682 mutex_unlock(mmd_mutex);
683 return 1;
684 }
685
686 /* stop */
687 static int com_stop(struct command_context *cc)
688 {
689 if (cc->argc != 1)
690 return -E_COMMAND_SYNTAX;
691 mutex_lock(mmd_mutex);
692 mmd->new_vss_status_flags &= ~VSS_PLAYING;
693 mmd->new_vss_status_flags &= ~VSS_REPOS;
694 mmd->new_vss_status_flags |= VSS_NEXT;
695 mutex_unlock(mmd_mutex);
696 return 1;
697 }
698
699 /* pause */
700 static int com_pause(struct command_context *cc)
701 {
702 if (cc->argc != 1)
703 return -E_COMMAND_SYNTAX;
704 mutex_lock(mmd_mutex);
705 if (!vss_paused() && !vss_stopped()) {
706 mmd->events++;
707 mmd->new_vss_status_flags &= ~VSS_PLAYING;
708 mmd->new_vss_status_flags &= ~VSS_NEXT;
709 }
710 mutex_unlock(mmd_mutex);
711 return 1;
712 }
713
714 /* next */
715 static int com_next(struct command_context *cc)
716 {
717 if (cc->argc != 1)
718 return -E_COMMAND_SYNTAX;
719 mutex_lock(mmd_mutex);
720 mmd->events++;
721 mmd->new_vss_status_flags |= VSS_NEXT;
722 mutex_unlock(mmd_mutex);
723 return 1;
724 }
725
726 /* nomore */
727 static int com_nomore(struct command_context *cc)
728 {
729 if (cc->argc != 1)
730 return -E_COMMAND_SYNTAX;
731 mutex_lock(mmd_mutex);
732 if (vss_playing() || vss_paused())
733 mmd->new_vss_status_flags |= VSS_NOMORE;
734 mutex_unlock(mmd_mutex);
735 return 1;
736 }
737
738 /* ff */
739 static int com_ff(struct command_context *cc)
740 {
741 long promille;
742 int ret, backwards = 0;
743 unsigned i;
744 char c;
745
746 if (cc->argc != 2)
747 return -E_COMMAND_SYNTAX;
748 if (!(ret = sscanf(cc->argv[1], "%u%c", &i, &c)))
749 return -E_COMMAND_SYNTAX;
750 if (ret > 1 && c == '-')
751 backwards = 1; /* jmp backwards */
752 mutex_lock(mmd_mutex);
753 ret = -E_NO_AUDIO_FILE;
754 if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
755 goto out;
756 promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
757 if (backwards)
758 promille -= 1000 * i / mmd->afd.afhi.seconds_total;
759 else
760 promille += 1000 * i / mmd->afd.afhi.seconds_total;
761 if (promille < 0)
762 promille = 0;
763 if (promille > 1000) {
764 mmd->new_vss_status_flags |= VSS_NEXT;
765 goto out;
766 }
767 mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
768 mmd->new_vss_status_flags |= VSS_REPOS;
769 mmd->new_vss_status_flags &= ~VSS_NEXT;
770 mmd->events++;
771 ret = 1;
772 out:
773 mutex_unlock(mmd_mutex);
774 return ret;
775 }
776
777 /* jmp */
778 static int com_jmp(struct command_context *cc)
779 {
780 long unsigned int i;
781 int ret;
782
783 if (cc->argc != 2)
784 return -E_COMMAND_SYNTAX;
785 if (sscanf(cc->argv[1], "%lu", &i) <= 0)
786 return -E_COMMAND_SYNTAX;
787 mutex_lock(mmd_mutex);
788 ret = -E_NO_AUDIO_FILE;
789 if (!mmd->afd.afhi.chunks_total)
790 goto out;
791 if (i > 100)
792 i = 100;
793 PARA_INFO_LOG("jumping to %lu%%\n", i);
794 mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50)/ 100;
795 PARA_INFO_LOG("sent: %lu, offset before jmp: %lu\n",
796 mmd->chunks_sent, mmd->offset);
797 mmd->new_vss_status_flags |= VSS_REPOS;
798 mmd->new_vss_status_flags &= ~VSS_NEXT;
799 ret = 1;
800 mmd->events++;
801 out:
802 mutex_unlock(mmd_mutex);
803 return ret;
804 }
805
806 /*
807 * check if perms are sufficient to exec a command having perms cmd_perms.
808 * Returns 0 if perms are sufficient, -E_PERM otherwise.
809 */
810 static int check_perms(unsigned int perms, struct server_command *cmd_ptr)
811 {
812 PARA_DEBUG_LOG("checking permissions\n");
813 return (cmd_ptr->perms & perms) < cmd_ptr->perms ? -E_PERM : 0;
814 }
815
816 /*
817 * Parse first string from *cmd and lookup in table of valid commands.
818 * On error, NULL is returned.
819 */
820 static struct server_command *parse_cmd(const char *cmdstr)
821 {
822 char buf[255];
823 int n = 0;
824
825 sscanf(cmdstr, "%200s%n", buf, &n);
826 if (!n)
827 return NULL;
828 buf[n] = '\0';
829 return get_cmd_ptr(buf, NULL);
830 }
831
832 static int read_command(struct stream_cipher_context *scc, char **result)
833 {
834 int ret;
835 char buf[4096];
836 char *command = NULL;
837
838 for (;;) {
839 size_t numbytes;
840 char *p;
841
842 ret = sc_recv_buffer(scc, buf, sizeof(buf));
843 if (ret < 0)
844 goto out;
845 if (!ret)
846 break;
847 numbytes = ret;
848 ret = -E_COMMAND_SYNTAX;
849 if (command && numbytes + strlen(command) > MAX_COMMAND_LEN) /* DOS */
850 goto out;
851 command = para_strcat(command, buf);
852 p = strstr(command, EOC_MSG);
853 if (p) {
854 *p = '\0';
855 break;
856 }
857 }
858 ret = command? 1 : -E_COMMAND_SYNTAX;
859 out:
860 if (ret < 0)
861 free(command);
862 else
863 *result = command;
864 return ret;
865
866 }
867
868 static void reset_signals(void)
869 {
870 para_sigaction(SIGCHLD, SIG_IGN);
871 para_sigaction(SIGINT, SIG_DFL);
872 para_sigaction(SIGTERM, SIG_DFL);
873 para_sigaction(SIGHUP, SIG_DFL);
874 }
875
876 static int parse_auth_request(char *buf, int len, struct user **u,
877 bool *use_sideband)
878 {
879 int ret;
880 char *p, *username, **features = NULL;
881 size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
882
883 *u = NULL;
884 *use_sideband = false;
885 if (len < auth_rq_len + 2)
886 return -E_AUTH_REQUEST;
887 if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
888 return -E_AUTH_REQUEST;
889 username = buf + auth_rq_len;
890 p = strchr(username, ' ');
891 if (p) {
892 int i;
893 if (p == username)
894 return -E_AUTH_REQUEST;
895 *p = '\0';
896 p++;
897 create_argv(p, ",", &features);
898 for (i = 0; features[i]; i++) {
899 if (strcmp(features[i], "sideband") == 0)
900 *use_sideband = true;
901 else {
902 ret = -E_BAD_FEATURE;
903 goto out;
904 }
905 }
906 }
907 PARA_DEBUG_LOG("received auth request for user %s (sideband = %s)\n",
908 username, *use_sideband? "true" : "false");
909 *u = lookup_user(username);
910 ret = 1;
911 out:
912 free_argv(features);
913 return ret;
914 }
915
916 #define HANDSHAKE_BUFSIZE 4096
917
918 static int parse_sb_command(struct command_context *cc, struct iovec *iov)
919 {
920 int ret, i;
921 char *p, *end;
922
923 ret = -E_BAD_CMD;
924 if (iov->iov_base == NULL || iov->iov_len == 0)
925 goto out;
926 p = iov->iov_base;
927 p[iov->iov_len - 1] = '\0'; /* just to be sure */
928 cc->cmd = get_cmd_ptr(p, NULL);
929 if (!cc->cmd)
930 goto out;
931 ret = check_perms(cc->u->perms, cc->cmd);
932 if (ret < 0)
933 goto out;
934 end = iov->iov_base + iov->iov_len;
935 for (i = 0, p = iov->iov_base; p < end; i++)
936 p += strlen(p) + 1;
937 cc->argc = i;
938 cc->argv = para_malloc((cc->argc + 1) * sizeof(char *));
939 for (i = 0, p = iov->iov_base; p < end; i++) {
940 cc->argv[i] = para_strdup(p);
941 p += strlen(p) + 1;
942 }
943 cc->argv[cc->argc] = NULL;
944 ret = cc->argc;
945 out:
946 free(iov->iov_base);
947 return ret;
948 }
949
950 /**
951 * Perform user authentication and execute a command.
952 *
953 * \param fd The file descriptor to send output to.
954 * \param peername Identifies the connecting peer.
955 *
956 * Whenever para_server accepts an incoming tcp connection on
957 * the port it listens on, it forks and the resulting child
958 * calls this function.
959 *
960 * An RSA-based challenge/response is used to authenticate
961 * the peer. It that authentication succeeds, a random
962 * session key is generated and sent back to the peer,
963 * encrypted with its RSA public key. From this point on,
964 * all transfers are crypted with this session key.
965 *
966 * Next it is checked if the peer supplied a valid server command or a command
967 * for the audio file selector. If yes, and if the user has sufficient
968 * permissions to execute that command, the function calls the corresponding
969 * command handler which does argument checking and further processing.
970 *
971 * In order to cope with a DOS attacks, a timeout is set up
972 * which terminates the function if the connection was not
973 * authenticated when the timeout expires.
974 *
975 * \sa alarm(2), crypt.c, crypt.h
976 */
977 __noreturn void handle_connect(int fd, const char *peername)
978 {
979 int ret;
980 unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
981 unsigned char challenge_hash[HASH_SIZE];
982 char *p, *command = NULL, *buf = para_malloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
983 size_t numbytes;
984 struct command_context cc_struct = {.peer = peername}, *cc = &cc_struct;
985
986 cc->scc.fd = fd;
987 reset_signals();
988 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
989 ret = mark_fd_blocking(fd);
990 if (ret < 0)
991 goto net_err;
992 /* send Welcome message */
993 ret = write_va_buffer(fd, "This is para_server, version "
994 PACKAGE_VERSION ".\n"
995 "Features: sideband\n"
996 );
997 if (ret < 0)
998 goto net_err;
999 /* recv auth request line */
1000 ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
1001 if (ret < 0)
1002 goto net_err;
1003 ret = parse_auth_request(buf, ret, &cc->u, &cc->use_sideband);
1004 if (ret < 0)
1005 goto net_err;
1006 p = buf + strlen(AUTH_REQUEST_MSG);
1007 PARA_DEBUG_LOG("received auth request for user %s\n", p);
1008 cc->u = lookup_user(p);
1009 if (cc->u) {
1010 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
1011 ret = pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
1012 (unsigned char *)buf);
1013 if (ret < 0)
1014 goto net_err;
1015 numbytes = ret;
1016 } else {
1017 /*
1018 * We don't want to reveal our user names, so we send a
1019 * challenge to the client even if the user does not exist, and
1020 * fail the authentication later.
1021 */
1022 numbytes = 256;
1023 get_random_bytes_or_die((unsigned char *)buf, numbytes);
1024 }
1025 PARA_DEBUG_LOG("sending %u byte challenge + rc4 keys (%zu bytes)\n",
1026 CHALLENGE_SIZE, numbytes);
1027 if (cc->use_sideband) {
1028 struct iovec iov;
1029 ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
1030 buf = NULL;
1031 if (ret < 0)
1032 goto net_err;
1033 ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
1034 HANDSHAKE_BUFSIZE, &iov);
1035 if (ret < 0)
1036 goto net_err;
1037 buf = iov.iov_base;
1038 numbytes = iov.iov_len;
1039 } else {
1040 ret = write_all(fd, buf, numbytes);
1041 if (ret < 0)
1042 goto net_err;
1043 /* recv challenge response */
1044 ret = recv_bin_buffer(fd, buf, HASH_SIZE);
1045 if (ret < 0)
1046 goto net_err;
1047 numbytes = ret;
1048 }
1049 PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
1050 ret = -E_BAD_USER;
1051 if (!cc->u)
1052 goto net_err;
1053 /*
1054 * The correct response is the hash of the first CHALLENGE_SIZE bytes
1055 * of the random data.
1056 */
1057 ret = -E_BAD_AUTH;
1058 if (numbytes != HASH_SIZE)
1059 goto net_err;
1060 hash_function((char *)rand_buf, CHALLENGE_SIZE, challenge_hash);
1061 if (memcmp(challenge_hash, buf, HASH_SIZE))
1062 goto net_err;
1063 /* auth successful */
1064 alarm(0);
1065 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
1066 /* init stream cipher keys with the second part of the random buffer */
1067 cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
1068 cc->scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN, SESSION_KEY_LEN);
1069 if (cc->use_sideband)
1070 ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
1071 else
1072 ret = sc_send_buffer(&cc->scc, PROCEED_MSG);
1073 if (ret < 0)
1074 goto net_err;
1075 if (cc->use_sideband) {
1076 struct iovec iov;
1077 ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
1078 if (ret < 0)
1079 goto net_err;
1080 ret = parse_sb_command(cc, &iov);
1081 if (ret < 0)
1082 goto err_out;
1083 cc->argc = ret;
1084 } else {
1085 ret = read_command(&cc->scc, &command);
1086 if (ret == -E_COMMAND_SYNTAX)
1087 goto err_out;
1088 if (ret < 0)
1089 goto net_err;
1090 ret = -E_BAD_CMD;
1091 cc->cmd = parse_cmd(command);
1092 if (!cc->cmd)
1093 goto err_out;
1094 /* valid command, check permissions */
1095 ret = check_perms(cc->u->perms, cc->cmd);
1096 if (ret < 0)
1097 goto err_out;
1098 /* valid command and sufficient perms */
1099 ret = create_argv(command, "\n", &cc->argv);
1100 if (ret < 0)
1101 goto err_out;
1102 cc->argc = ret;
1103 }
1104 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cc->cmd->name,
1105 cc->u->name, peername);
1106 ret = cc->cmd->handler(cc);
1107 free_argv(cc->argv);
1108 mutex_lock(mmd_mutex);
1109 mmd->num_commands++;
1110 mutex_unlock(mmd_mutex);
1111 if (ret >= 0)
1112 goto out;
1113 err_out:
1114 if (send_strerror(cc, -ret) >= 0 && cc->use_sideband)
1115 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
1116 net_err:
1117 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1118 out:
1119 free(buf);
1120 free(command);
1121 mutex_lock(mmd_mutex);
1122 if (cc->cmd && (cc->cmd->perms & AFS_WRITE) && ret >= 0)
1123 mmd->events++;
1124 mmd->active_connections--;
1125 mutex_unlock(mmd_mutex);
1126 if (ret >= 0 && cc->use_sideband) {
1127 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1128 if (ret < 0)
1129 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1130 }
1131 sc_free(cc->scc.recv);
1132 sc_free(cc->scc.send);
1133 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
1134 }