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