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