Replace gettimeofday() by clock_gettime().
[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, "version: " GIT_VERSION "\n"
399 "up: %s\nplayed: %u\n"
400 "server_pid: %d\n"
401 "afs_pid: %d\n"
402 "connections (active/accepted/total): %u/%u/%u\n"
403 "current loglevel: %s\n"
404 "supported audio formats: %s\n"
405 "%s",
406 ut, mmd->num_played,
407 (int)getppid(),
408 (int)mmd->afs_pid,
409 mmd->active_connections,
410 mmd->num_commands,
411 mmd->num_connects,
412 conf.loglevel_arg,
413 AUDIO_FORMAT_HANDLERS,
414 sender_info
415 );
416 mutex_unlock(mmd_mutex);
417 free(ut);
418 free(sender_info);
419 if (cc->use_sideband)
420 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
421 ret = sc_send_bin_buffer(&cc->scc, msg, ret);
422 free(msg);
423 return ret;
424 }
425
426 /* version */
427 static int com_version(struct command_context *cc)
428 {
429 char *msg;
430 size_t len;
431
432 if (cc->argc != 1)
433 return -E_COMMAND_SYNTAX;
434 msg = VERSION_TEXT("server") "built: " BUILD_DATE "\n" UNAME_RS
435 ", " CC_VERSION "\n";
436 len = strlen(msg);
437 if (cc->use_sideband)
438 return send_sb(&cc->scc, msg, len, SBD_OUTPUT, true);
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 static char *esi;
478 static unsigned len;
479
480 if (esi)
481 goto out;
482
483 if (parser_friendly)
484 len = xasprintf(&esi,
485 #define ITEM(x) "0004 %02x:\n"
486 EMPTY_STATUS_ITEMS
487 #undef ITEM
488 #define ITEM(x) , SI_ ## x
489 EMPTY_STATUS_ITEMS
490 #undef ITEM
491 );
492 else
493 len = xasprintf(&esi,
494 #define ITEM(x) "%s:\n"
495 EMPTY_STATUS_ITEMS
496 #undef ITEM
497 #define ITEM(x) ,status_item_list[SI_ ## x]
498 EMPTY_STATUS_ITEMS
499 #undef ITEM
500 );
501 out:
502 *result = esi;
503 return len;
504 }
505 #undef EMPTY_STATUS_ITEMS
506
507 /* stat */
508 static int com_stat(struct command_context *cc)
509 {
510 int i, ret;
511 struct misc_meta_data tmp, *nmmd = &tmp;
512 char *s, *esi = NULL;
513 int32_t num = 0;
514 int parser_friendly = 0;
515
516 para_sigaction(SIGUSR1, dummy);
517
518 for (i = 1; i < cc->argc; i++) {
519 const char *arg = cc->argv[i];
520 if (arg[0] != '-')
521 break;
522 if (!strcmp(arg, "--")) {
523 i++;
524 break;
525 }
526 if (!strncmp(arg, "-n=", 3)) {
527 ret = para_atoi32(arg + 3, &num);
528 if (ret < 0)
529 return ret;
530 continue;
531 }
532 if (!strcmp(arg, "-p")) {
533 parser_friendly = 1;
534 continue;
535 }
536 return -E_COMMAND_SYNTAX;
537 }
538 if (i != cc->argc)
539 return -E_COMMAND_SYNTAX;
540 for (;;) {
541 mmd_dup(nmmd);
542 ret = get_status(nmmd, parser_friendly, &s);
543 if (cc->use_sideband)
544 ret = send_sb(&cc->scc, s, ret, SBD_OUTPUT, false);
545 else {
546 ret = sc_send_bin_buffer(&cc->scc, s, ret);
547 free(s);
548 }
549 if (ret < 0)
550 goto out;
551 if (nmmd->vss_status_flags & VSS_NEXT) {
552 ret = empty_status_items(parser_friendly, &esi);
553 if (cc->use_sideband)
554 ret = send_sb(&cc->scc, esi, ret, SBD_OUTPUT,
555 true);
556 else
557 ret = sc_send_bin_buffer(&cc->scc, esi, ret);
558 if (ret < 0)
559 goto out;
560 } else
561 send_afs_status(cc, parser_friendly);
562 ret = 1;
563 if (num > 0 && !--num)
564 goto out;
565 sleep(50);
566 ret = -E_SERVER_CRASH;
567 if (getppid() == 1)
568 goto out;
569 }
570 out:
571 free(esi);
572 return ret;
573 }
574
575 static int send_list_of_commands(struct command_context *cc, struct server_command *cmd,
576 const char *handler)
577 {
578 int ret;
579 char *msg = NULL;
580
581 for (; cmd->name; cmd++) {
582 char *tmp, *perms = cmd_perms_itohuman(cmd->perms);
583 tmp = make_message("%s\t%s\t%s\t%s\n", cmd->name, handler,
584 perms, cmd->description);
585 free(perms);
586 msg = para_strcat(msg, tmp);
587 free(tmp);
588 }
589 if (cc->use_sideband)
590 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
591 ret = sc_send_buffer(&cc->scc, msg);
592 free(msg);
593 return ret;
594 }
595
596 /* returns string that must be freed by the caller */
597 static struct server_command *get_cmd_ptr(const char *name, char **handler)
598 {
599 struct server_command *cmd;
600
601 for (cmd = server_cmds; cmd->name; cmd++)
602 if (!strcmp(cmd->name, name)) {
603 if (handler)
604 *handler = para_strdup("server"); /* server commands */
605 return cmd;
606 }
607 /* not found, look for commands supported by afs */
608 for (cmd = afs_cmds; cmd->name; cmd++)
609 if (!strcmp(cmd->name, name)) {
610 if (handler)
611 *handler = para_strdup("afs");
612 return cmd;
613 }
614 return NULL;
615 }
616
617 /* help */
618 static int com_help(struct command_context *cc)
619 {
620 struct server_command *cmd;
621 char *perms, *handler, *buf;
622 int ret;
623
624 if (cc->argc < 2) {
625 /* no argument given, print list of commands */
626 if ((ret = send_list_of_commands(cc, server_cmds, "server")) < 0)
627 return ret;
628 return send_list_of_commands(cc, afs_cmds, "afs");
629 }
630 /* argument given for help */
631 cmd = get_cmd_ptr(cc->argv[1], &handler);
632 if (!cmd)
633 return -E_BAD_CMD;
634 perms = cmd_perms_itohuman(cmd->perms);
635 ret = xasprintf(&buf, "%s - %s\n\n"
636 "handler: %s\n"
637 "permissions: %s\n"
638 "usage: %s\n\n"
639 "%s\n",
640 cc->argv[1],
641 cmd->description,
642 handler,
643 perms,
644 cmd->usage,
645 cmd->help
646 );
647 free(perms);
648 free(handler);
649 if (cc->use_sideband)
650 return send_sb(&cc->scc, buf, ret, SBD_OUTPUT, false);
651 ret = sc_send_buffer(&cc->scc, buf);
652 free(buf);
653 return ret;
654 }
655
656 /* hup */
657 static int com_hup(struct command_context *cc)
658 {
659 if (cc->argc != 1)
660 return -E_COMMAND_SYNTAX;
661 kill(getppid(), SIGHUP);
662 return 1;
663 }
664
665 /* term */
666 static int com_term(struct command_context *cc)
667 {
668 if (cc->argc != 1)
669 return -E_COMMAND_SYNTAX;
670 kill(getppid(), SIGTERM);
671 return 1;
672 }
673
674 static int com_play(struct command_context *cc)
675 {
676 if (cc->argc != 1)
677 return -E_COMMAND_SYNTAX;
678 mutex_lock(mmd_mutex);
679 mmd->new_vss_status_flags |= VSS_PLAYING;
680 mmd->new_vss_status_flags &= ~VSS_NOMORE;
681 mutex_unlock(mmd_mutex);
682 return 1;
683 }
684
685 /* stop */
686 static int com_stop(struct command_context *cc)
687 {
688 if (cc->argc != 1)
689 return -E_COMMAND_SYNTAX;
690 mutex_lock(mmd_mutex);
691 mmd->new_vss_status_flags &= ~VSS_PLAYING;
692 mmd->new_vss_status_flags &= ~VSS_REPOS;
693 mmd->new_vss_status_flags |= VSS_NEXT;
694 mutex_unlock(mmd_mutex);
695 return 1;
696 }
697
698 /* pause */
699 static int com_pause(struct command_context *cc)
700 {
701 if (cc->argc != 1)
702 return -E_COMMAND_SYNTAX;
703 mutex_lock(mmd_mutex);
704 if (!vss_paused() && !vss_stopped()) {
705 mmd->events++;
706 mmd->new_vss_status_flags &= ~VSS_PLAYING;
707 mmd->new_vss_status_flags &= ~VSS_NEXT;
708 }
709 mutex_unlock(mmd_mutex);
710 return 1;
711 }
712
713 /* next */
714 static int com_next(struct command_context *cc)
715 {
716 if (cc->argc != 1)
717 return -E_COMMAND_SYNTAX;
718 mutex_lock(mmd_mutex);
719 mmd->events++;
720 mmd->new_vss_status_flags |= VSS_NEXT;
721 mutex_unlock(mmd_mutex);
722 return 1;
723 }
724
725 /* nomore */
726 static int com_nomore(struct command_context *cc)
727 {
728 if (cc->argc != 1)
729 return -E_COMMAND_SYNTAX;
730 mutex_lock(mmd_mutex);
731 if (vss_playing() || vss_paused())
732 mmd->new_vss_status_flags |= VSS_NOMORE;
733 mutex_unlock(mmd_mutex);
734 return 1;
735 }
736
737 /* ff */
738 static int com_ff(struct command_context *cc)
739 {
740 long promille;
741 int ret, backwards = 0;
742 unsigned i;
743 char c;
744
745 if (cc->argc != 2)
746 return -E_COMMAND_SYNTAX;
747 if (!(ret = sscanf(cc->argv[1], "%u%c", &i, &c)))
748 return -E_COMMAND_SYNTAX;
749 if (ret > 1 && c == '-')
750 backwards = 1; /* jmp backwards */
751 mutex_lock(mmd_mutex);
752 ret = -E_NO_AUDIO_FILE;
753 if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
754 goto out;
755 promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
756 if (backwards)
757 promille -= 1000 * i / mmd->afd.afhi.seconds_total;
758 else
759 promille += 1000 * i / mmd->afd.afhi.seconds_total;
760 if (promille < 0)
761 promille = 0;
762 if (promille > 1000) {
763 mmd->new_vss_status_flags |= VSS_NEXT;
764 goto out;
765 }
766 mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
767 mmd->new_vss_status_flags |= VSS_REPOS;
768 mmd->new_vss_status_flags &= ~VSS_NEXT;
769 mmd->events++;
770 ret = 1;
771 out:
772 mutex_unlock(mmd_mutex);
773 return ret;
774 }
775
776 /* jmp */
777 static int com_jmp(struct command_context *cc)
778 {
779 long unsigned int i;
780 int ret;
781
782 if (cc->argc != 2)
783 return -E_COMMAND_SYNTAX;
784 if (sscanf(cc->argv[1], "%lu", &i) <= 0)
785 return -E_COMMAND_SYNTAX;
786 mutex_lock(mmd_mutex);
787 ret = -E_NO_AUDIO_FILE;
788 if (!mmd->afd.afhi.chunks_total)
789 goto out;
790 if (i > 100)
791 i = 100;
792 PARA_INFO_LOG("jumping to %lu%%\n", i);
793 mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50)/ 100;
794 PARA_INFO_LOG("sent: %lu, offset before jmp: %lu\n",
795 mmd->chunks_sent, mmd->offset);
796 mmd->new_vss_status_flags |= VSS_REPOS;
797 mmd->new_vss_status_flags &= ~VSS_NEXT;
798 ret = 1;
799 mmd->events++;
800 out:
801 mutex_unlock(mmd_mutex);
802 return ret;
803 }
804
805 /*
806 * check if perms are sufficient to exec a command having perms cmd_perms.
807 * Returns 0 if perms are sufficient, -E_PERM otherwise.
808 */
809 static int check_perms(unsigned int perms, struct server_command *cmd_ptr)
810 {
811 PARA_DEBUG_LOG("checking permissions\n");
812 return (cmd_ptr->perms & perms) < cmd_ptr->perms ? -E_PERM : 0;
813 }
814
815 /*
816 * Parse first string from *cmd and lookup in table of valid commands.
817 * On error, NULL is returned.
818 */
819 static struct server_command *parse_cmd(const char *cmdstr)
820 {
821 char buf[255];
822 int n = 0;
823
824 sscanf(cmdstr, "%200s%n", buf, &n);
825 if (!n)
826 return NULL;
827 buf[n] = '\0';
828 return get_cmd_ptr(buf, NULL);
829 }
830
831 static int read_command(struct stream_cipher_context *scc, char **result)
832 {
833 int ret;
834 char buf[4096];
835 char *command = NULL;
836
837 for (;;) {
838 size_t numbytes;
839 char *p;
840
841 ret = sc_recv_buffer(scc, buf, sizeof(buf));
842 if (ret < 0)
843 goto out;
844 if (!ret)
845 break;
846 numbytes = ret;
847 ret = -E_COMMAND_SYNTAX;
848 if (command && numbytes + strlen(command) > MAX_COMMAND_LEN) /* DOS */
849 goto out;
850 command = para_strcat(command, buf);
851 p = strstr(command, EOC_MSG);
852 if (p) {
853 *p = '\0';
854 break;
855 }
856 }
857 ret = command? 1 : -E_COMMAND_SYNTAX;
858 out:
859 if (ret < 0)
860 free(command);
861 else
862 *result = command;
863 return ret;
864
865 }
866
867 static void reset_signals(void)
868 {
869 para_sigaction(SIGCHLD, SIG_IGN);
870 para_sigaction(SIGINT, SIG_DFL);
871 para_sigaction(SIGTERM, SIG_DFL);
872 para_sigaction(SIGHUP, SIG_DFL);
873 }
874
875 static int parse_auth_request(char *buf, int len, struct user **u,
876 bool *use_sideband)
877 {
878 int ret;
879 char *p, *username, **features = NULL;
880 size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
881
882 *u = NULL;
883 *use_sideband = false;
884 if (len < auth_rq_len + 2)
885 return -E_AUTH_REQUEST;
886 if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
887 return -E_AUTH_REQUEST;
888 username = buf + auth_rq_len;
889 p = strchr(username, ' ');
890 if (p) {
891 int i;
892 if (p == username)
893 return -E_AUTH_REQUEST;
894 *p = '\0';
895 p++;
896 create_argv(p, ",", &features);
897 for (i = 0; features[i]; i++) {
898 if (strcmp(features[i], "sideband") == 0)
899 *use_sideband = true;
900 else {
901 ret = -E_BAD_FEATURE;
902 goto out;
903 }
904 }
905 }
906 PARA_DEBUG_LOG("received auth request for user %s (sideband = %s)\n",
907 username, *use_sideband? "true" : "false");
908 *u = lookup_user(username);
909 ret = 1;
910 out:
911 free_argv(features);
912 return ret;
913 }
914
915 #define HANDSHAKE_BUFSIZE 4096
916
917 static int parse_sb_command(struct command_context *cc, struct iovec *iov)
918 {
919 int ret, i;
920 char *p, *end;
921
922 ret = -E_BAD_CMD;
923 if (iov->iov_base == NULL || iov->iov_len == 0)
924 goto out;
925 p = iov->iov_base;
926 p[iov->iov_len - 1] = '\0'; /* just to be sure */
927 cc->cmd = get_cmd_ptr(p, NULL);
928 if (!cc->cmd)
929 goto out;
930 ret = check_perms(cc->u->perms, cc->cmd);
931 if (ret < 0)
932 goto out;
933 end = iov->iov_base + iov->iov_len;
934 for (i = 0, p = iov->iov_base; p < end; i++)
935 p += strlen(p) + 1;
936 cc->argc = i;
937 cc->argv = para_malloc((cc->argc + 1) * sizeof(char *));
938 for (i = 0, p = iov->iov_base; p < end; i++) {
939 cc->argv[i] = para_strdup(p);
940 p += strlen(p) + 1;
941 }
942 cc->argv[cc->argc] = NULL;
943 ret = cc->argc;
944 out:
945 free(iov->iov_base);
946 return ret;
947 }
948
949 /**
950 * Perform user authentication and execute a command.
951 *
952 * \param fd The file descriptor to send output to.
953 * \param peername Identifies the connecting peer.
954 *
955 * Whenever para_server accepts an incoming tcp connection on
956 * the port it listens on, it forks and the resulting child
957 * calls this function.
958 *
959 * An RSA-based challenge/response is used to authenticate
960 * the peer. It that authentication succeeds, a random
961 * session key is generated and sent back to the peer,
962 * encrypted with its RSA public key. From this point on,
963 * all transfers are crypted with this session key.
964 *
965 * Next it is checked if the peer supplied a valid server command or a command
966 * for the audio file selector. If yes, and if the user has sufficient
967 * permissions to execute that command, the function calls the corresponding
968 * command handler which does argument checking and further processing.
969 *
970 * In order to cope with a DOS attacks, a timeout is set up
971 * which terminates the function if the connection was not
972 * authenticated when the timeout expires.
973 *
974 * \sa alarm(2), crypt.c, crypt.h
975 */
976 __noreturn void handle_connect(int fd, const char *peername)
977 {
978 int ret;
979 unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
980 unsigned char challenge_hash[HASH_SIZE];
981 char *p, *command = NULL, *buf = para_malloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
982 size_t numbytes;
983 struct command_context cc_struct = {.peer = peername}, *cc = &cc_struct;
984
985 cc->scc.fd = fd;
986 reset_signals();
987 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
988 ret = mark_fd_blocking(fd);
989 if (ret < 0)
990 goto net_err;
991 /* send Welcome message */
992 ret = write_va_buffer(fd, "This is para_server, version "
993 PACKAGE_VERSION ".\n"
994 "Features: sideband\n"
995 );
996 if (ret < 0)
997 goto net_err;
998 /* recv auth request line */
999 ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
1000 if (ret < 0)
1001 goto net_err;
1002 ret = parse_auth_request(buf, ret, &cc->u, &cc->use_sideband);
1003 if (ret < 0)
1004 goto net_err;
1005 p = buf + strlen(AUTH_REQUEST_MSG);
1006 PARA_DEBUG_LOG("received auth request for user %s\n", p);
1007 cc->u = lookup_user(p);
1008 if (cc->u) {
1009 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
1010 ret = pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
1011 (unsigned char *)buf);
1012 if (ret < 0)
1013 goto net_err;
1014 numbytes = ret;
1015 } else {
1016 /*
1017 * We don't want to reveal our user names, so we send a
1018 * challenge to the client even if the user does not exist, and
1019 * fail the authentication later.
1020 */
1021 numbytes = 256;
1022 get_random_bytes_or_die((unsigned char *)buf, numbytes);
1023 }
1024 PARA_DEBUG_LOG("sending %u byte challenge + rc4 keys (%zu bytes)\n",
1025 CHALLENGE_SIZE, numbytes);
1026 if (cc->use_sideband) {
1027 struct iovec iov;
1028 ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
1029 buf = NULL;
1030 if (ret < 0)
1031 goto net_err;
1032 ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
1033 HANDSHAKE_BUFSIZE, &iov);
1034 if (ret < 0)
1035 goto net_err;
1036 buf = iov.iov_base;
1037 numbytes = iov.iov_len;
1038 } else {
1039 ret = write_all(fd, buf, numbytes);
1040 if (ret < 0)
1041 goto net_err;
1042 /* recv challenge response */
1043 ret = recv_bin_buffer(fd, buf, HASH_SIZE);
1044 if (ret < 0)
1045 goto net_err;
1046 numbytes = ret;
1047 }
1048 PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
1049 ret = -E_BAD_USER;
1050 if (!cc->u)
1051 goto net_err;
1052 /*
1053 * The correct response is the hash of the first CHALLENGE_SIZE bytes
1054 * of the random data.
1055 */
1056 ret = -E_BAD_AUTH;
1057 if (numbytes != HASH_SIZE)
1058 goto net_err;
1059 hash_function((char *)rand_buf, CHALLENGE_SIZE, challenge_hash);
1060 if (memcmp(challenge_hash, buf, HASH_SIZE))
1061 goto net_err;
1062 /* auth successful */
1063 alarm(0);
1064 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
1065 /* init stream cipher keys with the second part of the random buffer */
1066 cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
1067 cc->scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN, SESSION_KEY_LEN);
1068 if (cc->use_sideband)
1069 ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
1070 else
1071 ret = sc_send_buffer(&cc->scc, PROCEED_MSG);
1072 if (ret < 0)
1073 goto net_err;
1074 if (cc->use_sideband) {
1075 struct iovec iov;
1076 ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
1077 if (ret < 0)
1078 goto net_err;
1079 ret = parse_sb_command(cc, &iov);
1080 if (ret < 0)
1081 goto err_out;
1082 cc->argc = ret;
1083 } else {
1084 ret = read_command(&cc->scc, &command);
1085 if (ret == -E_COMMAND_SYNTAX)
1086 goto err_out;
1087 if (ret < 0)
1088 goto net_err;
1089 ret = -E_BAD_CMD;
1090 cc->cmd = parse_cmd(command);
1091 if (!cc->cmd)
1092 goto err_out;
1093 /* valid command, check permissions */
1094 ret = check_perms(cc->u->perms, cc->cmd);
1095 if (ret < 0)
1096 goto err_out;
1097 /* valid command and sufficient perms */
1098 ret = create_argv(command, "\n", &cc->argv);
1099 if (ret < 0)
1100 goto err_out;
1101 cc->argc = ret;
1102 }
1103 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cc->cmd->name,
1104 cc->u->name, peername);
1105 ret = cc->cmd->handler(cc);
1106 free_argv(cc->argv);
1107 mutex_lock(mmd_mutex);
1108 mmd->num_commands++;
1109 mutex_unlock(mmd_mutex);
1110 if (ret >= 0)
1111 goto out;
1112 err_out:
1113 if (send_strerror(cc, -ret) >= 0 && cc->use_sideband)
1114 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
1115 net_err:
1116 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1117 out:
1118 free(buf);
1119 free(command);
1120 mutex_lock(mmd_mutex);
1121 if (cc->cmd && (cc->cmd->perms & AFS_WRITE) && ret >= 0)
1122 mmd->events++;
1123 mmd->active_connections--;
1124 mutex_unlock(mmd_mutex);
1125 if (ret >= 0 && cc->use_sideband) {
1126 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1127 if (ret < 0)
1128 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1129 }
1130 sc_free(cc->scc.recv);
1131 sc_free(cc->scc.send);
1132 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
1133 }