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