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