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