Doxify error2.c and add GPL header.
[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 assert(msg);
558 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
559 }
560
561 /* returns string that must be freed by the caller */
562 static struct server_command *get_cmd_ptr(const char *name, char **handler)
563 {
564 struct server_command *cmd;
565
566 for (cmd = server_cmds; cmd->name; cmd++)
567 if (!strcmp(cmd->name, name)) {
568 if (handler)
569 *handler = para_strdup("server"); /* server commands */
570 return cmd;
571 }
572 /* not found, look for commands supported by afs */
573 for (cmd = afs_cmds; cmd->name; cmd++)
574 if (!strcmp(cmd->name, name)) {
575 if (handler)
576 *handler = para_strdup("afs");
577 return cmd;
578 }
579 return NULL;
580 }
581
582 /* help */
583 static int com_help(struct command_context *cc)
584 {
585 struct server_command *cmd;
586 char *perms, *handler, *buf;
587 int ret;
588
589 if (cc->argc < 2) {
590 /* no argument given, print list of commands */
591 if ((ret = send_list_of_commands(cc, server_cmds, "server")) < 0)
592 return ret;
593 return send_list_of_commands(cc, afs_cmds, "afs");
594 }
595 /* argument given for help */
596 cmd = get_cmd_ptr(cc->argv[1], &handler);
597 if (!cmd)
598 return -E_BAD_CMD;
599 perms = cmd_perms_itohuman(cmd->perms);
600 ret = xasprintf(&buf, "%s - %s\n\n"
601 "handler: %s\n"
602 "permissions: %s\n"
603 "usage: %s\n\n"
604 "%s\n",
605 cc->argv[1],
606 cmd->description,
607 handler,
608 perms,
609 cmd->usage,
610 cmd->help
611 );
612 free(perms);
613 free(handler);
614 return send_sb(&cc->scc, buf, ret, SBD_OUTPUT, false);
615 }
616
617 /* hup */
618 static int com_hup(struct command_context *cc)
619 {
620 if (cc->argc != 1)
621 return -E_COMMAND_SYNTAX;
622 kill(getppid(), SIGHUP);
623 return 1;
624 }
625
626 /* term */
627 static int com_term(struct command_context *cc)
628 {
629 if (cc->argc != 1)
630 return -E_COMMAND_SYNTAX;
631 kill(getppid(), SIGTERM);
632 return 1;
633 }
634
635 static int com_play(struct command_context *cc)
636 {
637 if (cc->argc != 1)
638 return -E_COMMAND_SYNTAX;
639 mutex_lock(mmd_mutex);
640 mmd->new_vss_status_flags |= VSS_PLAYING;
641 mmd->new_vss_status_flags &= ~VSS_NOMORE;
642 mutex_unlock(mmd_mutex);
643 return 1;
644 }
645
646 /* stop */
647 static int com_stop(struct command_context *cc)
648 {
649 if (cc->argc != 1)
650 return -E_COMMAND_SYNTAX;
651 mutex_lock(mmd_mutex);
652 mmd->new_vss_status_flags &= ~VSS_PLAYING;
653 mmd->new_vss_status_flags &= ~VSS_REPOS;
654 mmd->new_vss_status_flags |= VSS_NEXT;
655 mutex_unlock(mmd_mutex);
656 return 1;
657 }
658
659 /* pause */
660 static int com_pause(struct command_context *cc)
661 {
662 if (cc->argc != 1)
663 return -E_COMMAND_SYNTAX;
664 mutex_lock(mmd_mutex);
665 if (!vss_paused() && !vss_stopped()) {
666 mmd->events++;
667 mmd->new_vss_status_flags &= ~VSS_PLAYING;
668 mmd->new_vss_status_flags &= ~VSS_NEXT;
669 }
670 mutex_unlock(mmd_mutex);
671 return 1;
672 }
673
674 /* next */
675 static int com_next(struct command_context *cc)
676 {
677 if (cc->argc != 1)
678 return -E_COMMAND_SYNTAX;
679 mutex_lock(mmd_mutex);
680 mmd->events++;
681 mmd->new_vss_status_flags |= VSS_NEXT;
682 mutex_unlock(mmd_mutex);
683 return 1;
684 }
685
686 /* nomore */
687 static int com_nomore(struct command_context *cc)
688 {
689 if (cc->argc != 1)
690 return -E_COMMAND_SYNTAX;
691 mutex_lock(mmd_mutex);
692 if (vss_playing() || vss_paused())
693 mmd->new_vss_status_flags |= VSS_NOMORE;
694 mutex_unlock(mmd_mutex);
695 return 1;
696 }
697
698 /* ff */
699 static int com_ff(struct command_context *cc)
700 {
701 long promille;
702 int ret, backwards = 0;
703 unsigned i;
704 char c;
705
706 if (cc->argc != 2)
707 return -E_COMMAND_SYNTAX;
708 if (!(ret = sscanf(cc->argv[1], "%u%c", &i, &c)))
709 return -E_COMMAND_SYNTAX;
710 if (ret > 1 && c == '-')
711 backwards = 1; /* jmp backwards */
712 mutex_lock(mmd_mutex);
713 ret = -E_NO_AUDIO_FILE;
714 if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
715 goto out;
716 promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
717 if (backwards)
718 promille -= 1000 * i / mmd->afd.afhi.seconds_total;
719 else
720 promille += 1000 * i / mmd->afd.afhi.seconds_total;
721 if (promille < 0)
722 promille = 0;
723 if (promille > 1000) {
724 mmd->new_vss_status_flags |= VSS_NEXT;
725 goto out;
726 }
727 mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
728 mmd->new_vss_status_flags |= VSS_REPOS;
729 mmd->new_vss_status_flags &= ~VSS_NEXT;
730 mmd->events++;
731 ret = 1;
732 out:
733 mutex_unlock(mmd_mutex);
734 return ret;
735 }
736
737 /* jmp */
738 static int com_jmp(struct command_context *cc)
739 {
740 long unsigned int i;
741 int ret;
742
743 if (cc->argc != 2)
744 return -E_COMMAND_SYNTAX;
745 if (sscanf(cc->argv[1], "%lu", &i) <= 0)
746 return -E_COMMAND_SYNTAX;
747 mutex_lock(mmd_mutex);
748 ret = -E_NO_AUDIO_FILE;
749 if (!mmd->afd.afhi.chunks_total)
750 goto out;
751 if (i > 100)
752 i = 100;
753 PARA_INFO_LOG("jumping to %lu%%\n", i);
754 mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50)/ 100;
755 PARA_INFO_LOG("sent: %lu, offset before jmp: %lu\n",
756 mmd->chunks_sent, mmd->offset);
757 mmd->new_vss_status_flags |= VSS_REPOS;
758 mmd->new_vss_status_flags &= ~VSS_NEXT;
759 ret = 1;
760 mmd->events++;
761 out:
762 mutex_unlock(mmd_mutex);
763 return ret;
764 }
765
766 /*
767 * check if perms are sufficient to exec a command having perms cmd_perms.
768 * Returns 0 if perms are sufficient, -E_PERM otherwise.
769 */
770 static int check_perms(unsigned int perms, struct server_command *cmd_ptr)
771 {
772 PARA_DEBUG_LOG("checking permissions\n");
773 return (cmd_ptr->perms & perms) < cmd_ptr->perms ? -E_PERM : 0;
774 }
775
776 static void reset_signals(void)
777 {
778 para_sigaction(SIGCHLD, SIG_IGN);
779 para_sigaction(SIGINT, SIG_DFL);
780 para_sigaction(SIGTERM, SIG_DFL);
781 para_sigaction(SIGHUP, SIG_DFL);
782 }
783
784 static int parse_auth_request(char *buf, int len, struct user **u)
785 {
786 int ret;
787 char *p, *username, **features = NULL;
788 size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
789 bool sideband_requested = false;
790
791 *u = NULL;
792 if (len < auth_rq_len + 2)
793 return -E_AUTH_REQUEST;
794 if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
795 return -E_AUTH_REQUEST;
796 username = buf + auth_rq_len;
797 p = strchr(username, ' ');
798 if (p) {
799 int i;
800 if (p == username)
801 return -E_AUTH_REQUEST;
802 *p = '\0';
803 p++;
804 create_argv(p, ",", &features);
805 for (i = 0; features[i]; i++) {
806 if (strcmp(features[i], "sideband") == 0)
807 sideband_requested = true;
808 else {
809 ret = -E_BAD_FEATURE;
810 goto out;
811 }
812 }
813 }
814 if (sideband_requested == false) { /* sideband is mandatory */
815 PARA_ERROR_LOG("client did not request sideband\n");
816 ret = -E_BAD_FEATURE;
817 goto out;
818 }
819 PARA_DEBUG_LOG("received auth request for user %s\n", username);
820 *u = lookup_user(username);
821 ret = 1;
822 out:
823 free_argv(features);
824 return ret;
825 }
826
827 #define HANDSHAKE_BUFSIZE 4096
828
829 static int parse_sb_command(struct command_context *cc, struct iovec *iov)
830 {
831 int ret, i;
832 char *p, *end;
833
834 ret = -E_BAD_CMD;
835 if (iov->iov_base == NULL || iov->iov_len == 0)
836 goto out;
837 p = iov->iov_base;
838 p[iov->iov_len - 1] = '\0'; /* just to be sure */
839 cc->cmd = get_cmd_ptr(p, NULL);
840 if (!cc->cmd)
841 goto out;
842 ret = check_perms(cc->u->perms, cc->cmd);
843 if (ret < 0)
844 goto out;
845 end = iov->iov_base + iov->iov_len;
846 for (i = 0; p < end; i++)
847 p += strlen(p) + 1;
848 cc->argc = i;
849 cc->argv = para_malloc((cc->argc + 1) * sizeof(char *));
850 for (i = 0, p = iov->iov_base; p < end; i++) {
851 cc->argv[i] = para_strdup(p);
852 p += strlen(p) + 1;
853 }
854 cc->argv[cc->argc] = NULL;
855 ret = cc->argc;
856 out:
857 free(iov->iov_base);
858 return ret;
859 }
860
861 /**
862 * Perform user authentication and execute a command.
863 *
864 * \param fd The file descriptor to send output to.
865 * \param peername Identifies the connecting peer.
866 *
867 * Whenever para_server accepts an incoming tcp connection on
868 * the port it listens on, it forks and the resulting child
869 * calls this function.
870 *
871 * An RSA-based challenge/response is used to authenticate
872 * the peer. It that authentication succeeds, a random
873 * session key is generated and sent back to the peer,
874 * encrypted with its RSA public key. From this point on,
875 * all transfers are crypted with this session key.
876 *
877 * Next it is checked if the peer supplied a valid server command or a command
878 * for the audio file selector. If yes, and if the user has sufficient
879 * permissions to execute that command, the function calls the corresponding
880 * command handler which does argument checking and further processing.
881 *
882 * In order to cope with a DOS attacks, a timeout is set up
883 * which terminates the function if the connection was not
884 * authenticated when the timeout expires.
885 *
886 * \sa alarm(2), crypt.c, crypt.h
887 */
888 __noreturn void handle_connect(int fd, const char *peername)
889 {
890 int ret;
891 unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
892 unsigned char challenge_hash[HASH_SIZE];
893 char *p, *command = NULL, *buf = para_malloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
894 size_t numbytes;
895 struct command_context cc_struct = {.peer = peername}, *cc = &cc_struct;
896 struct iovec iov;
897
898 cc->scc.fd = fd;
899 reset_signals();
900 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
901 ret = mark_fd_blocking(fd);
902 if (ret < 0)
903 goto net_err;
904 /* send Welcome message */
905 ret = write_va_buffer(fd, "This is para_server, version "
906 PACKAGE_VERSION ".\n"
907 "Features: sideband\n"
908 );
909 if (ret < 0)
910 goto net_err;
911 /* recv auth request line */
912 ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
913 if (ret < 0)
914 goto net_err;
915 ret = parse_auth_request(buf, ret, &cc->u);
916 if (ret < 0)
917 goto net_err;
918 p = buf + strlen(AUTH_REQUEST_MSG);
919 PARA_DEBUG_LOG("received auth request for user %s\n", p);
920 cc->u = lookup_user(p);
921 if (cc->u) {
922 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
923 ret = pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
924 (unsigned char *)buf);
925 if (ret < 0)
926 goto net_err;
927 numbytes = ret;
928 } else {
929 /*
930 * We don't want to reveal our user names, so we send a
931 * challenge to the client even if the user does not exist, and
932 * fail the authentication later.
933 */
934 numbytes = 256;
935 get_random_bytes_or_die((unsigned char *)buf, numbytes);
936 }
937 PARA_DEBUG_LOG("sending %u byte challenge + rc4 keys (%zu bytes)\n",
938 CHALLENGE_SIZE, numbytes);
939 ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
940 buf = NULL;
941 if (ret < 0)
942 goto net_err;
943 ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
944 HANDSHAKE_BUFSIZE, &iov);
945 if (ret < 0)
946 goto net_err;
947 buf = iov.iov_base;
948 numbytes = iov.iov_len;
949 PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
950 ret = -E_BAD_USER;
951 if (!cc->u)
952 goto net_err;
953 /*
954 * The correct response is the hash of the first CHALLENGE_SIZE bytes
955 * of the random data.
956 */
957 ret = -E_BAD_AUTH;
958 if (numbytes != HASH_SIZE)
959 goto net_err;
960 hash_function((char *)rand_buf, CHALLENGE_SIZE, challenge_hash);
961 if (memcmp(challenge_hash, buf, HASH_SIZE))
962 goto net_err;
963 /* auth successful */
964 alarm(0);
965 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
966 /* init stream cipher keys with the second part of the random buffer */
967 cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
968 cc->scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN, SESSION_KEY_LEN);
969 ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
970 if (ret < 0)
971 goto net_err;
972 ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
973 if (ret < 0)
974 goto net_err;
975 ret = parse_sb_command(cc, &iov);
976 if (ret < 0)
977 goto err_out;
978 cc->argc = ret;
979 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cc->cmd->name,
980 cc->u->name, peername);
981 ret = cc->cmd->handler(cc);
982 free_argv(cc->argv);
983 mutex_lock(mmd_mutex);
984 mmd->num_commands++;
985 mutex_unlock(mmd_mutex);
986 if (ret >= 0)
987 goto out;
988 err_out:
989 if (send_strerror(cc, -ret) >= 0)
990 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
991 net_err:
992 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
993 out:
994 free(buf);
995 free(command);
996 mutex_lock(mmd_mutex);
997 if (cc->cmd && (cc->cmd->perms & AFS_WRITE) && ret >= 0)
998 mmd->events++;
999 mmd->active_connections--;
1000 mutex_unlock(mmd_mutex);
1001 if (ret >= 0) {
1002 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1003 if (ret < 0)
1004 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1005 }
1006 sc_free(cc->scc.recv);
1007 sc_free(cc->scc.send);
1008 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
1009 }