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