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