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