NEWS,md: Add introductory text for v0.5.7.
[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 /*
79 * Compute human readable vss status text.
80 *
81 * We can't call vss_playing() and friends here because those functions read
82 * the flags from the primary mmd structure, so calling them from command
83 * handler context would require to take the mmd lock. At the time the function
84 * is called we already took a copy of the mmd structure and want to use the
85 * flags value of the copy for computing the vss status text.
86 */
87 static char *vss_status_tohuman(unsigned int flags)
88 {
89 if (flags & VSS_PLAYING)
90 return para_strdup("playing");
91 if (flags & VSS_NEXT)
92 return para_strdup("stopped");
93 return para_strdup("paused");
94 }
95
96 /*
97 * return human readable permission string. Never returns NULL.
98 */
99 static char *cmd_perms_itohuman(unsigned int perms)
100 {
101 char *msg = para_malloc(5 * sizeof(char));
102
103 msg[0] = perms & AFS_READ? 'a' : '-';
104 msg[1] = perms & AFS_WRITE? 'A' : '-';
105 msg[2] = perms & VSS_READ? 'v' : '-';
106 msg[3] = perms & VSS_WRITE? 'V' : '-';
107 msg[4] = '\0';
108 return msg;
109 }
110
111 /*
112 * Never returns NULL.
113 */
114 static char *vss_get_status_flags(unsigned int flags)
115 {
116 char *msg = para_malloc(5 * sizeof(char));
117
118 msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
119 msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
120 msg[2] = (flags & VSS_NEXT)? 'N' : '_';
121 msg[3] = (flags & VSS_REPOS)? 'R' : '_';
122 msg[4] = '\0';
123 return msg;
124 }
125
126 static unsigned get_status(struct misc_meta_data *nmmd, int parser_friendly,
127 char **result)
128 {
129 char *status, *flags; /* vss status info */
130 /* nobody updates our version of "now" */
131 long offset = (nmmd->offset + 500) / 1000;
132 struct timeval current_time;
133 struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
134
135 /* report real status */
136 status = vss_status_tohuman(nmmd->vss_status_flags);
137 flags = vss_get_status_flags(nmmd->vss_status_flags);
138 clock_get_realtime(&current_time);
139 /*
140 * The calls to WRITE_STATUS_ITEM() below never fail because
141 * b->max_size is zero (unlimited), see para_printf(). However, clang
142 * is not smart enough to prove this and complains nevertheless.
143 * Casting the return value to void silences clang.
144 */
145 (void)WRITE_STATUS_ITEM(&b, SI_STATUS, "%s\n", status);
146 (void)WRITE_STATUS_ITEM(&b, SI_STATUS_FLAGS, "%s\n", flags);
147 (void)WRITE_STATUS_ITEM(&b, SI_OFFSET, "%li\n", offset);
148 (void)WRITE_STATUS_ITEM(&b, SI_AFS_MODE, "%s\n", mmd->afs_mode_string);
149 (void)WRITE_STATUS_ITEM(&b, SI_STREAM_START, "%lu.%lu\n",
150 (long unsigned)nmmd->stream_start.tv_sec,
151 (long unsigned)nmmd->stream_start.tv_usec);
152 (void)WRITE_STATUS_ITEM(&b, SI_CURRENT_TIME, "%lu.%lu\n",
153 (long unsigned)current_time.tv_sec,
154 (long unsigned)current_time.tv_usec);
155 free(flags);
156 free(status);
157 *result = b.buf;
158 return b.offset;
159 }
160
161 static int check_sender_args(int argc, char * const * argv, struct sender_command_data *scd)
162 {
163 int i;
164
165 const char *subcmds[] = {SENDER_SUBCOMMANDS NULL};
166 scd->sender_num = -1;
167 if (argc < 3)
168 return -E_COMMAND_SYNTAX;
169 for (i = 0; senders[i].name; i++)
170 if (!strcmp(senders[i].name, argv[1]))
171 break;
172 PARA_DEBUG_LOG("%d:%s\n", argc, argv[1]);
173 if (!senders[i].name)
174 return -E_COMMAND_SYNTAX;
175 scd->sender_num = i;
176 for (i = 0; subcmds[i]; i++)
177 if (!strcmp(subcmds[i], argv[2]))
178 break;
179 if (!subcmds[i])
180 return -E_COMMAND_SYNTAX;
181 scd->cmd_num = i;
182 if (!senders[scd->sender_num].client_cmds[scd->cmd_num])
183 return -E_SENDER_CMD;
184 switch (scd->cmd_num) {
185 case SENDER_on:
186 case SENDER_off:
187 if (argc != 3)
188 return -E_COMMAND_SYNTAX;
189 break;
190 case SENDER_deny:
191 case SENDER_allow:
192 if (argc != 4 || parse_cidr(argv[3], scd->host,
193 sizeof(scd->host), &scd->netmask) == NULL)
194 return -E_COMMAND_SYNTAX;
195 break;
196 case SENDER_add:
197 case SENDER_delete:
198 if (argc != 4)
199 return -E_COMMAND_SYNTAX;
200 return parse_fec_url(argv[3], scd);
201 default:
202 return -E_COMMAND_SYNTAX;
203 }
204 return 1;
205 }
206
207 /**
208 * Send a sideband packet through a blocking file descriptor.
209 *
210 * \param scc fd and crypto keys.
211 * \param buf The buffer to send.
212 * \param numbytes The size of \a buf.
213 * \param band The sideband designator of this packet.
214 * \param dont_free If true, never deallocate \a buf.
215 *
216 * The nonblock flag must be disabled for the file descriptor given by \a scc.
217 *
218 * Stream cipher encryption is automatically activated if necessary via the
219 * sideband transformation, depending on the value of \a band.
220 *
221 * \return Standard.
222 *
223 * \sa \ref send_sb_va().
224 */
225 int send_sb(struct stream_cipher_context *scc, void *buf, size_t numbytes,
226 int band, bool dont_free)
227 {
228 int ret;
229 struct sb_context *sbc;
230 struct iovec iov[2];
231 sb_transformation trafo = band < SBD_PROCEED? NULL : sc_trafo;
232 struct sb_buffer sbb = SBB_INIT(band, buf, numbytes);
233
234 sbc = sb_new_send(&sbb, dont_free, trafo, scc->send);
235 do {
236 ret = sb_get_send_buffers(sbc, iov);
237 ret = xwritev(scc->fd, iov, ret);
238 if (ret < 0)
239 goto fail;
240 } while (sb_sent(sbc, ret) == false);
241 return 1;
242 fail:
243 sb_free(sbc);
244 return ret;
245 }
246
247 /**
248 * Create a variable sized buffer and send it as a sideband packet.
249 *
250 * \param scc Passed to \ref send_sb.
251 * \param band See \ref send_sb.
252 * \param fmt The format string.
253 *
254 * \return The return value of the underlying call to \ref send_sb.
255 */
256 __printf_3_4 int send_sb_va(struct stream_cipher_context *scc, int band,
257 const char *fmt, ...)
258 {
259 va_list ap;
260 char *msg;
261 int ret;
262
263 va_start(ap, fmt);
264 ret = xvasprintf(&msg, fmt, ap);
265 va_end(ap);
266 return send_sb(scc, msg, ret, band, false);
267 }
268
269 /**
270 * Send an error message to a client.
271 *
272 * \param cc Client info.
273 * \param err The (positive) error code.
274 *
275 * \return The return value of the underlying call to send_sb_va().
276 */
277 int send_strerror(struct command_context *cc, int err)
278 {
279 return send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", para_strerror(err));
280 }
281
282 /**
283 * Send a sideband packet through a blocking file descriptor.
284 *
285 * \param scc fd and crypto keys.
286 * \param expected_band The expected band designator.
287 * \param max_size Passed to \ref sb_new_recv().
288 * \param result Body of the sideband packet is returned here.
289 *
290 * If \a expected_band is not \p SBD_ANY, the band designator of the received
291 * sideband packet is compared to \a expected_band and a mismatch is considered
292 * an error.
293 *
294 * \return Standard.
295 */
296 int recv_sb(struct stream_cipher_context *scc,
297 enum sb_designator expected_band,
298 size_t max_size, struct iovec *result)
299 {
300 int ret;
301 struct sb_context *sbc;
302 struct iovec iov;
303 struct sb_buffer sbb;
304 sb_transformation trafo;
305
306 trafo = expected_band != SBD_ANY && expected_band < SBD_PROCEED?
307 NULL : sc_trafo;
308 sbc = sb_new_recv(max_size, trafo, scc->recv);
309 for (;;) {
310 sb_get_recv_buffer(sbc, &iov);
311 ret = recv_bin_buffer(scc->fd, iov.iov_base, iov.iov_len);
312 if (ret == 0)
313 ret = -E_EOF;
314 if (ret < 0)
315 goto fail;
316 ret = sb_received(sbc, ret, &sbb);
317 if (ret < 0)
318 goto fail;
319 if (ret > 0)
320 break;
321 }
322 ret = -E_BAD_BAND;
323 if (expected_band != SBD_ANY && sbb.band != expected_band)
324 goto fail;
325 *result = sbb.iov;
326 return 1;
327 fail:
328 sb_free(sbc);
329 return ret;
330 }
331
332 static int com_sender(struct command_context *cc)
333 {
334 int i, ret = 0;
335 char *msg = NULL;
336 struct sender_command_data scd;
337
338 if (cc->argc < 2) {
339 for (i = 0; senders[i].name; i++) {
340 char *tmp;
341 ret = xasprintf(&tmp, "%s%s\n", msg? msg : "",
342 senders[i].name);
343 free(msg);
344 msg = tmp;
345 }
346 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
347 }
348 ret = check_sender_args(cc->argc, cc->argv, &scd);
349 if (ret < 0) {
350 if (scd.sender_num < 0)
351 return ret;
352 if (strcmp(cc->argv[2], "status") == 0)
353 msg = senders[scd.sender_num].status();
354 else
355 msg = senders[scd.sender_num].help();
356 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
357 }
358
359 switch (scd.cmd_num) {
360 case SENDER_add:
361 case SENDER_delete:
362 assert(senders[scd.sender_num].resolve_target);
363 ret = senders[scd.sender_num].resolve_target(cc->argv[3], &scd);
364 if (ret < 0)
365 return ret;
366 }
367
368 for (i = 0; i < 10; i++) {
369 mutex_lock(mmd_mutex);
370 if (mmd->sender_cmd_data.cmd_num >= 0) {
371 /* another sender command is active, retry in 100ms */
372 struct timespec ts = {.tv_nsec = 100 * 1000 * 1000};
373 mutex_unlock(mmd_mutex);
374 nanosleep(&ts, NULL);
375 continue;
376 }
377 mmd->sender_cmd_data = scd;
378 mutex_unlock(mmd_mutex);
379 break;
380 }
381 return (i < 10)? 1 : -E_LOCK;
382 }
383
384 /* server info */
385 static int com_si(struct command_context *cc)
386 {
387 int ret;
388 char *msg, *ut;
389
390 if (cc->argc != 1)
391 return -E_COMMAND_SYNTAX;
392 mutex_lock(mmd_mutex);
393 ut = daemon_get_uptime_str(now);
394 ret = xasprintf(&msg,
395 "up: %s\nplayed: %u\n"
396 "server_pid: %d\n"
397 "afs_pid: %d\n"
398 "connections (active/accepted/total): %u/%u/%u\n"
399 "current loglevel: %s\n"
400 "supported audio formats: %s\n",
401 ut, mmd->num_played,
402 (int)getppid(),
403 (int)mmd->afs_pid,
404 mmd->active_connections,
405 mmd->num_commands,
406 mmd->num_connects,
407 conf.loglevel_arg,
408 AUDIO_FORMAT_HANDLERS
409 );
410 mutex_unlock(mmd_mutex);
411 free(ut);
412 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
413 }
414
415 /* version */
416 static int com_version(struct command_context *cc)
417 {
418 char *msg;
419 size_t len;
420
421 if (cc->argc > 1 && strcmp(cc->argv[1], "-v") == 0)
422 len = xasprintf(&msg, "%s", version_text("server"));
423 else
424 len = xasprintf(&msg, "%s\n", version_single_line("server"));
425 return send_sb(&cc->scc, msg, len, SBD_OUTPUT, false);
426 }
427
428 /** These status items are cleared if no audio file is currently open. */
429 #define EMPTY_STATUS_ITEMS \
430 ITEM(PATH) \
431 ITEM(DIRECTORY) \
432 ITEM(BASENAME) \
433 ITEM(SCORE) \
434 ITEM(ATTRIBUTES_BITMAP) \
435 ITEM(ATTRIBUTES_TXT) \
436 ITEM(HASH) \
437 ITEM(IMAGE_ID) \
438 ITEM(IMAGE_NAME) \
439 ITEM(LYRICS_ID) \
440 ITEM(LYRICS_NAME) \
441 ITEM(BITRATE) \
442 ITEM(FORMAT) \
443 ITEM(FREQUENCY) \
444 ITEM(CHANNELS) \
445 ITEM(DURATION) \
446 ITEM(SECONDS_TOTAL) \
447 ITEM(NUM_PLAYED) \
448 ITEM(LAST_PLAYED) \
449 ITEM(TECHINFO) \
450 ITEM(ARTIST) \
451 ITEM(TITLE) \
452 ITEM(YEAR) \
453 ITEM(ALBUM) \
454 ITEM(COMMENT) \
455 ITEM(MTIME) \
456 ITEM(FILE_SIZE) \
457 ITEM(CHUNK_TIME) \
458 ITEM(NUM_CHUNKS) \
459 ITEM(AMPLIFICATION) \
460
461 /**
462 * Write a list of audio-file related status items with empty values.
463 *
464 * This is used by vss when currently no audio file is open.
465 */
466 static unsigned empty_status_items(int parser_friendly, char **result)
467 {
468 char *esi;
469 unsigned len;
470
471 if (parser_friendly)
472 len = xasprintf(&esi,
473 #define ITEM(x) "0004 %02x:\n"
474 EMPTY_STATUS_ITEMS
475 #undef ITEM
476 #define ITEM(x) , (unsigned) SI_ ## x
477 EMPTY_STATUS_ITEMS
478 #undef ITEM
479 );
480 else
481 len = xasprintf(&esi,
482 #define ITEM(x) "%s:\n"
483 EMPTY_STATUS_ITEMS
484 #undef ITEM
485 #define ITEM(x) ,status_item_list[SI_ ## x]
486 EMPTY_STATUS_ITEMS
487 #undef ITEM
488 );
489 *result = esi;
490 return len;
491 }
492 #undef EMPTY_STATUS_ITEMS
493
494 /* stat */
495 static int com_stat(struct command_context *cc)
496 {
497 int i, ret;
498 struct misc_meta_data tmp, *nmmd = &tmp;
499 char *s;
500 int32_t num = 0;
501 int parser_friendly = 0;
502
503 para_sigaction(SIGUSR1, dummy);
504
505 for (i = 1; i < cc->argc; i++) {
506 const char *arg = cc->argv[i];
507 if (arg[0] != '-')
508 break;
509 if (!strcmp(arg, "--")) {
510 i++;
511 break;
512 }
513 if (!strncmp(arg, "-n=", 3)) {
514 ret = para_atoi32(arg + 3, &num);
515 if (ret < 0)
516 return ret;
517 continue;
518 }
519 if (!strcmp(arg, "-p")) {
520 parser_friendly = 1;
521 continue;
522 }
523 return -E_COMMAND_SYNTAX;
524 }
525 if (i != cc->argc)
526 return -E_COMMAND_SYNTAX;
527 for (;;) {
528 /*
529 * Copy the mmd structure to minimize the time we hold the mmd
530 * lock.
531 */
532 mutex_lock(mmd_mutex);
533 *nmmd = *mmd;
534 mutex_unlock(mmd_mutex);
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: %li\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 aes_ctr128_requested;
811 };
812
813 static int parse_auth_request(char *buf, int len, struct user **u,
814 struct connection_features *cf)
815 {
816 int ret;
817 char *p, *username, **features = NULL;
818 size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
819
820 *u = NULL;
821 memset(cf, 0, sizeof(*cf));
822 if (len < auth_rq_len + 2)
823 return -E_AUTH_REQUEST;
824 if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
825 return -E_AUTH_REQUEST;
826 username = buf + auth_rq_len;
827 p = strchr(username, ' ');
828 if (p) {
829 int i;
830 if (p == username)
831 return -E_AUTH_REQUEST;
832 *p = '\0';
833 p++;
834 create_argv(p, ",", &features);
835 for (i = 0; features[i]; i++) {
836 if (strcmp(features[i], "sideband") == 0)
837 continue;
838 if (strcmp(features[i], "aes_ctr128") == 0)
839 cf->aes_ctr128_requested = true;
840 else {
841 ret = -E_BAD_FEATURE;
842 goto out;
843 }
844 }
845 }
846 PARA_DEBUG_LOG("received auth request for user %s\n", username);
847 *u = lookup_user(username);
848 ret = 1;
849 out:
850 free_argv(features);
851 return ret;
852 }
853
854 #define HANDSHAKE_BUFSIZE 4096
855
856 static int run_command(struct command_context *cc, struct iovec *iov,
857 const char *peername)
858 {
859 int ret, i;
860 char *p, *end;
861 struct server_command *cmd;
862
863 if (iov->iov_base == NULL || iov->iov_len == 0)
864 return -E_BAD_CMD;
865 p = iov->iov_base;
866 p[iov->iov_len - 1] = '\0'; /* just to be sure */
867 cmd = get_cmd_ptr(p, NULL);
868 if (!cmd)
869 return -E_BAD_CMD;
870 ret = check_perms(cc->u->perms, cmd);
871 if (ret < 0)
872 return ret;
873 end = iov->iov_base + iov->iov_len;
874 for (i = 0; p < end; i++)
875 p += strlen(p) + 1;
876 cc->argc = i;
877 cc->argv = para_malloc((cc->argc + 1) * sizeof(char *));
878 for (i = 0, p = iov->iov_base; p < end; i++) {
879 cc->argv[i] = para_strdup(p);
880 p += strlen(p) + 1;
881 }
882 cc->argv[cc->argc] = NULL;
883 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cmd->name,
884 cc->u->name, peername);
885 ret = cmd->handler(cc);
886 free_argv(cc->argv);
887 mutex_lock(mmd_mutex);
888 mmd->num_commands++;
889 if (ret >= 0 && (cmd->perms & AFS_WRITE))
890 mmd->events++;
891 mutex_unlock(mmd_mutex);
892 return ret;
893 }
894
895 /**
896 * Perform user authentication and execute a command.
897 *
898 * \param fd The file descriptor to send output to.
899 * \param peername Identifies the connecting peer.
900 *
901 * Whenever para_server accepts an incoming tcp connection on the port it
902 * listens on, it forks and the resulting child calls this function.
903 *
904 * An RSA-based challenge/response is used to authenticate the peer. It that
905 * authentication succeeds, a random session key is generated and sent back to
906 * the peer, encrypted with its RSA public key. From this point on, all
907 * transfers are crypted with this session key.
908 *
909 * Next it is checked if the peer supplied a valid server command or a command
910 * for the audio file selector. If yes, and if the user has sufficient
911 * permissions to execute that command, the function calls the corresponding
912 * command handler which does argument checking and further processing.
913 *
914 * In order to cope with a DOS attacks, a timeout is set up which terminates
915 * the function if the connection was not authenticated when the timeout
916 * expires.
917 *
918 * \sa alarm(2), crypt.c, crypt.h
919 */
920 __noreturn void handle_connect(int fd, const char *peername)
921 {
922 int ret;
923 unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
924 unsigned char challenge_hash[HASH_SIZE];
925 char *command = NULL, *buf = para_malloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
926 size_t numbytes;
927 struct command_context cc_struct = {.peer = peername}, *cc = &cc_struct;
928 struct iovec iov;
929 struct connection_features cf;
930
931 cc->scc.fd = fd;
932 reset_signals();
933 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
934 ret = mark_fd_blocking(fd);
935 if (ret < 0)
936 goto net_err;
937 /* send Welcome message */
938 ret = write_va_buffer(fd, "This is para_server, version "
939 PACKAGE_VERSION ".\n"
940 "Features: sideband,aes_ctr128\n"
941 );
942 if (ret < 0)
943 goto net_err;
944 /* recv auth request line */
945 ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
946 if (ret < 0)
947 goto net_err;
948 ret = parse_auth_request(buf, ret, &cc->u, &cf);
949 if (ret < 0)
950 goto net_err;
951 if (cc->u) {
952 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
953 ret = pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
954 (unsigned char *)buf);
955 if (ret < 0)
956 goto net_err;
957 numbytes = ret;
958 } else {
959 /*
960 * We don't want to reveal our user names, so we send a
961 * challenge to the client even if the user does not exist, and
962 * fail the authentication later.
963 */
964 numbytes = 256;
965 get_random_bytes_or_die((unsigned char *)buf, numbytes);
966 }
967 PARA_DEBUG_LOG("sending %d byte challenge + session key (%zu bytes)\n",
968 CHALLENGE_SIZE, numbytes);
969 ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
970 buf = NULL;
971 if (ret < 0)
972 goto net_err;
973 ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
974 HANDSHAKE_BUFSIZE, &iov);
975 if (ret < 0)
976 goto net_err;
977 buf = iov.iov_base;
978 numbytes = iov.iov_len;
979 PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
980 ret = -E_BAD_USER;
981 if (!cc->u)
982 goto net_err;
983 /*
984 * The correct response is the hash of the first CHALLENGE_SIZE bytes
985 * of the random data.
986 */
987 ret = -E_BAD_AUTH;
988 if (numbytes != HASH_SIZE)
989 goto net_err;
990 hash_function((char *)rand_buf, CHALLENGE_SIZE, challenge_hash);
991 if (memcmp(challenge_hash, buf, HASH_SIZE))
992 goto net_err;
993 /* auth successful */
994 alarm(0);
995 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
996 /* init stream cipher keys with the second part of the random buffer */
997 cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN,
998 cf.aes_ctr128_requested);
999 cc->scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN,
1000 SESSION_KEY_LEN, cf.aes_ctr128_requested);
1001 ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
1002 if (ret < 0)
1003 goto net_err;
1004 ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
1005 if (ret < 0)
1006 goto net_err;
1007 ret = run_command(cc, &iov, peername);
1008 free(iov.iov_base);
1009 if (ret < 0)
1010 goto err_out;
1011 if (ret >= 0)
1012 goto out;
1013 err_out:
1014 if (send_strerror(cc, -ret) >= 0)
1015 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
1016 net_err:
1017 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1018 out:
1019 free(buf);
1020 free(command);
1021 mutex_lock(mmd_mutex);
1022 mmd->active_connections--;
1023 mutex_unlock(mmd_mutex);
1024 if (ret >= 0) {
1025 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1026 if (ret < 0)
1027 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1028 }
1029 sc_free(cc->scc.recv);
1030 sc_free(cc->scc.send);
1031 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
1032 }