com_stat(): Remove pointless uptime variable.
[paraslash.git] / command.c
1 /*
2 * Copyright (C) 1997-2014 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/types.h>
12 #include <osl.h>
13
14 #include "para.h"
15 #include "error.h"
16 #include "crypt.h"
17 #include "sideband.h"
18 #include "command.h"
19 #include "server.cmdline.h"
20 #include "string.h"
21 #include "afh.h"
22 #include "afs.h"
23 #include "server.h"
24 #include "list.h"
25 #include "send.h"
26 #include "sched.h"
27 #include "vss.h"
28 #include "net.h"
29 #include "daemon.h"
30 #include "fd.h"
31 #include "ipc.h"
32 #include "user_list.h"
33 #include "server_command_list.h"
34 #include "afs_command_list.h"
35 #include "signal.h"
36 #include "version.h"
37
38 static struct server_command afs_cmds[] = {DEFINE_AFS_CMD_ARRAY};
39 static struct server_command server_cmds[] = {DEFINE_SERVER_CMD_ARRAY};
40
41 /** Commands including options must be shorter than this. */
42 #define MAX_COMMAND_LEN 32768
43
44 extern int mmd_mutex;
45 extern struct misc_meta_data *mmd;
46 extern struct sender senders[];
47 int send_afs_status(struct command_context *cc, int parser_friendly);
48
49 static void dummy(__a_unused int s)
50 {
51 }
52
53 static void mmd_dup(struct misc_meta_data *new_mmd)
54 {
55 mutex_lock(mmd_mutex);
56 *new_mmd = *mmd;
57 mutex_unlock(mmd_mutex);
58 }
59
60 /*
61 * Compute human readable string containing vss status for given integer value.
62 *
63 * We don't want to use vss_playing() and friends here because we take a
64 * snapshot of the mmd struct and use the copy for computing the state of the
65 * vss. If the real data were used, we would take the mmd lock for a rather
66 * long time or risk to get an inconsistent view.
67 */
68 static char *vss_status_tohuman(unsigned int flags)
69 {
70 if (flags & VSS_PLAYING)
71 return para_strdup("playing");
72 if (flags & VSS_NEXT)
73 return para_strdup("stopped");
74 return para_strdup("paused");
75 }
76
77 /*
78 * return human readable permission string. Never returns NULL.
79 */
80 static char *cmd_perms_itohuman(unsigned int perms)
81 {
82 char *msg = para_malloc(5 * sizeof(char));
83
84 msg[0] = perms & AFS_READ? 'a' : '-';
85 msg[1] = perms & AFS_WRITE? 'A' : '-';
86 msg[2] = perms & VSS_READ? 'v' : '-';
87 msg[3] = perms & VSS_WRITE? 'V' : '-';
88 msg[4] = '\0';
89 return msg;
90 }
91
92 /*
93 * Never returns NULL.
94 */
95 static char *vss_get_status_flags(unsigned int flags)
96 {
97 char *msg = para_malloc(5 * sizeof(char));
98
99 msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
100 msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
101 msg[2] = (flags & VSS_NEXT)? 'N' : '_';
102 msg[3] = (flags & VSS_REPOS)? 'R' : '_';
103 msg[4] = '\0';
104 return msg;
105 }
106
107 static unsigned get_status(struct misc_meta_data *nmmd, int parser_friendly,
108 char **result)
109 {
110 char mtime[30] = "";
111 char *status, *flags; /* vss status info */
112 /* nobody updates our version of "now" */
113 long offset = (nmmd->offset + 500) / 1000;
114 struct timeval current_time;
115 struct tm mtime_tm;
116 struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
117
118 /* report real status */
119 status = vss_status_tohuman(nmmd->vss_status_flags);
120 flags = vss_get_status_flags(nmmd->vss_status_flags);
121 if (nmmd->size) { /* parent currently has an audio file open */
122 localtime_r(&nmmd->mtime, &mtime_tm);
123 strftime(mtime, 29, "%b %d %Y", &mtime_tm);
124 }
125 clock_get_realtime(&current_time);
126 /*
127 * The calls to WRITE_STATUS_ITEM() below never fail because
128 * b->max_size is zero (unlimited), see para_printf(). However, clang
129 * is not smart enough to prove this and complains nevertheless.
130 * Casting the return value to void silences clang.
131 */
132 (void)WRITE_STATUS_ITEM(&b, SI_FILE_SIZE, "%zu\n", nmmd->size / 1024);
133 (void)WRITE_STATUS_ITEM(&b, SI_MTIME, "%s\n", mtime);
134 (void)WRITE_STATUS_ITEM(&b, SI_STATUS, "%s\n", status);
135 (void)WRITE_STATUS_ITEM(&b, SI_STATUS_FLAGS, "%s\n", flags);
136 (void)WRITE_STATUS_ITEM(&b, SI_OFFSET, "%li\n", offset);
137 (void)WRITE_STATUS_ITEM(&b, SI_AFS_MODE, "%s\n", mmd->afs_mode_string);
138 (void)WRITE_STATUS_ITEM(&b, SI_STREAM_START, "%lu.%lu\n",
139 (long unsigned)nmmd->stream_start.tv_sec,
140 (long unsigned)nmmd->stream_start.tv_usec);
141 (void)WRITE_STATUS_ITEM(&b, SI_CURRENT_TIME, "%lu.%lu\n",
142 (long unsigned)current_time.tv_sec,
143 (long unsigned)current_time.tv_usec);
144 free(flags);
145 free(status);
146 *result = b.buf;
147 return b.offset;
148 }
149
150 static int check_sender_args(int argc, char * const * argv, struct sender_command_data *scd)
151 {
152 int i;
153 /* this has to match sender.h */
154 const char *subcmds[] = {"add", "delete", "allow", "deny", "on", "off", NULL};
155
156 scd->sender_num = -1;
157 if (argc < 2)
158 return -E_COMMAND_SYNTAX;
159 for (i = 0; senders[i].name; i++)
160 if (!strcmp(senders[i].name, argv[1]))
161 break;
162 PARA_DEBUG_LOG("%d:%s\n", argc, argv[1]);
163 if (!senders[i].name)
164 return -E_COMMAND_SYNTAX;
165 scd->sender_num = i;
166 for (i = 0; subcmds[i]; i++)
167 if (!strcmp(subcmds[i], argv[2]))
168 break;
169 if (!subcmds[i])
170 return -E_COMMAND_SYNTAX;
171 scd->cmd_num = i;
172 if (!senders[scd->sender_num].client_cmds[scd->cmd_num])
173 return -E_SENDER_CMD;
174 switch (scd->cmd_num) {
175 case SENDER_ON:
176 case SENDER_OFF:
177 if (argc != 3)
178 return -E_COMMAND_SYNTAX;
179 break;
180 case SENDER_DENY:
181 case SENDER_ALLOW:
182 if (argc != 4 || parse_cidr(argv[3], scd->host,
183 sizeof(scd->host), &scd->netmask) == NULL)
184 return -E_COMMAND_SYNTAX;
185 break;
186 case SENDER_ADD:
187 case SENDER_DELETE:
188 if (argc != 4)
189 return -E_COMMAND_SYNTAX;
190 return parse_fec_url(argv[3], scd);
191 default:
192 return -E_COMMAND_SYNTAX;
193 }
194 return 1;
195 }
196
197 /**
198 * Send a sideband packet through a blocking file descriptor.
199 *
200 * \param scc fd and crypto keys.
201 * \param buf The buffer to send.
202 * \param numbytes The size of \a buf.
203 * \param band The sideband designator of this packet.
204 * \param dont_free If true, never deallocate \a buf.
205 *
206 * The nonblock flag must be disabled for the file descriptor given by \a scc.
207 *
208 * Stream cipher encryption is automatically activated if neccessary via the
209 * sideband transformation, depending on the value of \a band.
210 *
211 * \return Standard.
212 *
213 * \sa \ref send_sb_va().
214 */
215 int send_sb(struct stream_cipher_context *scc, void *buf, size_t numbytes,
216 int band, bool dont_free)
217 {
218 int ret;
219 struct sb_context *sbc;
220 struct iovec iov[2];
221 sb_transformation trafo = band < SBD_PROCEED? NULL : sc_trafo;
222 struct sb_buffer sbb = SBB_INIT(band, buf, numbytes);
223
224 sbc = sb_new_send(&sbb, dont_free, trafo, scc->send);
225 do {
226 ret = sb_get_send_buffers(sbc, iov);
227 ret = xwritev(scc->fd, iov, ret);
228 if (ret < 0)
229 goto fail;
230 } while (sb_sent(sbc, ret) == false);
231 return 1;
232 fail:
233 sb_free(sbc);
234 return ret;
235 }
236
237 /**
238 * Create a variable sized buffer and send it as a sideband packet.
239 *
240 * \param scc Passed to \ref send_sb.
241 * \param band See \ref send_sb.
242 * \param fmt The format string.
243 *
244 * \return The return value of the underlying call to \ref send_sb.
245 */
246 __printf_3_4 int send_sb_va(struct stream_cipher_context *scc, int band,
247 const char *fmt, ...)
248 {
249 va_list ap;
250 char *msg;
251 int ret;
252
253 va_start(ap, fmt);
254 ret = xvasprintf(&msg, fmt, ap);
255 va_end(ap);
256 return send_sb(scc, msg, ret, band, false);
257 }
258
259 /**
260 * Send an error message to a client.
261 *
262 * \param cc Client info.
263 * \param err The (positive) error code.
264 *
265 * \return The return value of the underlying call to send_sb_va().
266 */
267 int send_strerror(struct command_context *cc, int err)
268 {
269 return send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", para_strerror(err));
270 }
271
272 /**
273 * Send a sideband packet through a blocking file descriptor.
274 *
275 * \param scc fd and crypto keys.
276 * \param expected_band The expected band designator.
277 * \param max_size Passed to \ref sb_new_recv().
278 * \param result Body of the sideband packet is returned here.
279 *
280 * If \a expected_band is not \p SBD_ANY, the band designator of the received
281 * sideband packet is compared to \a expected_band and a mismatch is considered
282 * an error.
283 *
284 * \return Standard.
285 */
286 int recv_sb(struct stream_cipher_context *scc,
287 enum sb_designator expected_band,
288 size_t max_size, struct iovec *result)
289 {
290 int ret;
291 struct sb_context *sbc;
292 struct iovec iov;
293 struct sb_buffer sbb;
294 sb_transformation trafo;
295
296 trafo = expected_band != SBD_ANY && expected_band < SBD_PROCEED?
297 NULL : sc_trafo;
298 sbc = sb_new_recv(max_size, trafo, scc->recv);
299 for (;;) {
300 sb_get_recv_buffer(sbc, &iov);
301 ret = recv_bin_buffer(scc->fd, iov.iov_base, iov.iov_len);
302 if (ret == 0)
303 ret = -E_EOF;
304 if (ret < 0)
305 goto fail;
306 ret = sb_received(sbc, ret, &sbb);
307 if (ret < 0)
308 goto fail;
309 if (ret > 0)
310 break;
311 }
312 ret = -E_BAD_BAND;
313 if (expected_band != SBD_ANY && sbb.band != expected_band)
314 goto fail;
315 *result = sbb.iov;
316 return 1;
317 fail:
318 sb_free(sbc);
319 return ret;
320 }
321
322 static int com_sender(struct command_context *cc)
323 {
324 int i, ret = 0;
325 char *msg = NULL;
326 struct sender_command_data scd;
327
328 if (cc->argc < 2) {
329 for (i = 0; senders[i].name; i++) {
330 char *tmp;
331 ret = xasprintf(&tmp, "%s%s\n", msg? msg : "",
332 senders[i].name);
333 free(msg);
334 msg = tmp;
335 }
336 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
337 }
338 ret = check_sender_args(cc->argc, cc->argv, &scd);
339 if (ret < 0) {
340 if (scd.sender_num < 0)
341 return ret;
342 msg = senders[scd.sender_num].help();
343 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
344 }
345
346 switch (scd.cmd_num) {
347 case SENDER_ADD:
348 case SENDER_DELETE:
349 assert(senders[scd.sender_num].resolve_target);
350 ret = senders[scd.sender_num].resolve_target(cc->argv[3], &scd);
351 if (ret < 0)
352 return ret;
353 }
354
355 for (i = 0; i < 10; i++) {
356 mutex_lock(mmd_mutex);
357 if (mmd->sender_cmd_data.cmd_num >= 0) {
358 mutex_unlock(mmd_mutex);
359 usleep(100 * 1000);
360 continue;
361 }
362 memcpy(&mmd->sender_cmd_data, &scd, sizeof(scd));
363 mutex_unlock(mmd_mutex);
364 break;
365 }
366 return (i < 10)? 1 : -E_LOCK;
367 }
368
369 /* server info */
370 static int com_si(struct command_context *cc)
371 {
372 int i, ret;
373 char *msg, *ut, *sender_info = NULL;
374
375 if (cc->argc != 1)
376 return -E_COMMAND_SYNTAX;
377 mutex_lock(mmd_mutex);
378 for (i = 0; senders[i].name; i++) {
379 char *info = senders[i].info();
380 sender_info = para_strcat(sender_info, info);
381 free(info);
382 }
383 ut = get_server_uptime_str(now);
384 ret = xasprintf(&msg,
385 "version: %s\n"
386 "up: %s\nplayed: %u\n"
387 "server_pid: %d\n"
388 "afs_pid: %d\n"
389 "connections (active/accepted/total): %u/%u/%u\n"
390 "current loglevel: %s\n"
391 "supported audio formats: %s\n"
392 "%s",
393 version_git(),
394 ut, mmd->num_played,
395 (int)getppid(),
396 (int)mmd->afs_pid,
397 mmd->active_connections,
398 mmd->num_commands,
399 mmd->num_connects,
400 conf.loglevel_arg,
401 AUDIO_FORMAT_HANDLERS,
402 sender_info
403 );
404 mutex_unlock(mmd_mutex);
405 free(ut);
406 free(sender_info);
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 /*
765 * check if perms are sufficient to exec a command having perms cmd_perms.
766 * Returns 0 if perms are sufficient, -E_PERM otherwise.
767 */
768 static int check_perms(unsigned int perms, struct server_command *cmd_ptr)
769 {
770 PARA_DEBUG_LOG("checking permissions\n");
771 return (cmd_ptr->perms & perms) < cmd_ptr->perms ? -E_PERM : 0;
772 }
773
774 static void reset_signals(void)
775 {
776 para_sigaction(SIGCHLD, SIG_IGN);
777 para_sigaction(SIGINT, SIG_DFL);
778 para_sigaction(SIGTERM, SIG_DFL);
779 para_sigaction(SIGHUP, SIG_DFL);
780 }
781
782 static int parse_auth_request(char *buf, int len, struct user **u)
783 {
784 int ret;
785 char *p, *username, **features = NULL;
786 size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
787 bool sideband_requested = false;
788
789 *u = NULL;
790 if (len < auth_rq_len + 2)
791 return -E_AUTH_REQUEST;
792 if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
793 return -E_AUTH_REQUEST;
794 username = buf + auth_rq_len;
795 p = strchr(username, ' ');
796 if (p) {
797 int i;
798 if (p == username)
799 return -E_AUTH_REQUEST;
800 *p = '\0';
801 p++;
802 create_argv(p, ",", &features);
803 for (i = 0; features[i]; i++) {
804 if (strcmp(features[i], "sideband") == 0)
805 sideband_requested = true;
806 else {
807 ret = -E_BAD_FEATURE;
808 goto out;
809 }
810 }
811 }
812 if (sideband_requested == false) { /* sideband is mandatory */
813 PARA_ERROR_LOG("client did not request sideband\n");
814 ret = -E_BAD_FEATURE;
815 goto out;
816 }
817 PARA_DEBUG_LOG("received auth request for user %s\n", username);
818 *u = lookup_user(username);
819 ret = 1;
820 out:
821 free_argv(features);
822 return ret;
823 }
824
825 #define HANDSHAKE_BUFSIZE 4096
826
827 static int parse_sb_command(struct command_context *cc, struct iovec *iov)
828 {
829 int ret, i;
830 char *p, *end;
831
832 ret = -E_BAD_CMD;
833 if (iov->iov_base == NULL || iov->iov_len == 0)
834 goto out;
835 p = iov->iov_base;
836 p[iov->iov_len - 1] = '\0'; /* just to be sure */
837 cc->cmd = get_cmd_ptr(p, NULL);
838 if (!cc->cmd)
839 goto out;
840 ret = check_perms(cc->u->perms, cc->cmd);
841 if (ret < 0)
842 goto out;
843 end = iov->iov_base + iov->iov_len;
844 for (i = 0; p < end; i++)
845 p += strlen(p) + 1;
846 cc->argc = i;
847 cc->argv = para_malloc((cc->argc + 1) * sizeof(char *));
848 for (i = 0, p = iov->iov_base; p < end; i++) {
849 cc->argv[i] = para_strdup(p);
850 p += strlen(p) + 1;
851 }
852 cc->argv[cc->argc] = NULL;
853 ret = cc->argc;
854 out:
855 free(iov->iov_base);
856 return ret;
857 }
858
859 /**
860 * Perform user authentication and execute a command.
861 *
862 * \param fd The file descriptor to send output to.
863 * \param peername Identifies the connecting peer.
864 *
865 * Whenever para_server accepts an incoming tcp connection on
866 * the port it listens on, it forks and the resulting child
867 * calls this function.
868 *
869 * An RSA-based challenge/response is used to authenticate
870 * the peer. It that authentication succeeds, a random
871 * session key is generated and sent back to the peer,
872 * encrypted with its RSA public key. From this point on,
873 * all transfers are crypted with this session key.
874 *
875 * Next it is checked if the peer supplied a valid server command or a command
876 * for the audio file selector. If yes, and if the user has sufficient
877 * permissions to execute that command, the function calls the corresponding
878 * command handler which does argument checking and further processing.
879 *
880 * In order to cope with a DOS attacks, a timeout is set up
881 * which terminates the function if the connection was not
882 * authenticated when the timeout expires.
883 *
884 * \sa alarm(2), crypt.c, crypt.h
885 */
886 __noreturn void handle_connect(int fd, const char *peername)
887 {
888 int ret;
889 unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
890 unsigned char challenge_hash[HASH_SIZE];
891 char *p, *command = NULL, *buf = para_malloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
892 size_t numbytes;
893 struct command_context cc_struct = {.peer = peername}, *cc = &cc_struct;
894 struct iovec iov;
895
896 cc->scc.fd = fd;
897 reset_signals();
898 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
899 ret = mark_fd_blocking(fd);
900 if (ret < 0)
901 goto net_err;
902 /* send Welcome message */
903 ret = write_va_buffer(fd, "This is para_server, version "
904 PACKAGE_VERSION ".\n"
905 "Features: sideband\n"
906 );
907 if (ret < 0)
908 goto net_err;
909 /* recv auth request line */
910 ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
911 if (ret < 0)
912 goto net_err;
913 ret = parse_auth_request(buf, ret, &cc->u);
914 if (ret < 0)
915 goto net_err;
916 p = buf + strlen(AUTH_REQUEST_MSG);
917 PARA_DEBUG_LOG("received auth request for user %s\n", p);
918 cc->u = lookup_user(p);
919 if (cc->u) {
920 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
921 ret = pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
922 (unsigned char *)buf);
923 if (ret < 0)
924 goto net_err;
925 numbytes = ret;
926 } else {
927 /*
928 * We don't want to reveal our user names, so we send a
929 * challenge to the client even if the user does not exist, and
930 * fail the authentication later.
931 */
932 numbytes = 256;
933 get_random_bytes_or_die((unsigned char *)buf, numbytes);
934 }
935 PARA_DEBUG_LOG("sending %u byte challenge + rc4 keys (%zu bytes)\n",
936 CHALLENGE_SIZE, numbytes);
937 ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
938 buf = NULL;
939 if (ret < 0)
940 goto net_err;
941 ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
942 HANDSHAKE_BUFSIZE, &iov);
943 if (ret < 0)
944 goto net_err;
945 buf = iov.iov_base;
946 numbytes = iov.iov_len;
947 PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
948 ret = -E_BAD_USER;
949 if (!cc->u)
950 goto net_err;
951 /*
952 * The correct response is the hash of the first CHALLENGE_SIZE bytes
953 * of the random data.
954 */
955 ret = -E_BAD_AUTH;
956 if (numbytes != HASH_SIZE)
957 goto net_err;
958 hash_function((char *)rand_buf, CHALLENGE_SIZE, challenge_hash);
959 if (memcmp(challenge_hash, buf, HASH_SIZE))
960 goto net_err;
961 /* auth successful */
962 alarm(0);
963 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
964 /* init stream cipher keys with the second part of the random buffer */
965 cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
966 cc->scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN, SESSION_KEY_LEN);
967 ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
968 if (ret < 0)
969 goto net_err;
970 ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
971 if (ret < 0)
972 goto net_err;
973 ret = parse_sb_command(cc, &iov);
974 if (ret < 0)
975 goto err_out;
976 cc->argc = ret;
977 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cc->cmd->name,
978 cc->u->name, peername);
979 ret = cc->cmd->handler(cc);
980 free_argv(cc->argv);
981 mutex_lock(mmd_mutex);
982 mmd->num_commands++;
983 mutex_unlock(mmd_mutex);
984 if (ret >= 0)
985 goto out;
986 err_out:
987 if (send_strerror(cc, -ret) >= 0)
988 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
989 net_err:
990 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
991 out:
992 free(buf);
993 free(command);
994 mutex_lock(mmd_mutex);
995 if (cc->cmd && (cc->cmd->perms & AFS_WRITE) && ret >= 0)
996 mmd->events++;
997 mmd->active_connections--;
998 mutex_unlock(mmd_mutex);
999 if (ret >= 0) {
1000 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1001 if (ret < 0)
1002 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1003 }
1004 sc_free(cc->scc.recv);
1005 sc_free(cc->scc.send);
1006 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
1007 }