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