Introduce send_strerror().
[paraslash.git] / command.c
1 /*
2 * Copyright (C) 1997-2012 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 /** Commands including options must be shorter than this. */
40 #define MAX_COMMAND_LEN 32768
41
42 extern int mmd_mutex;
43 extern struct misc_meta_data *mmd;
44 extern struct sender senders[];
45 int send_afs_status(struct command_context *cc, int parser_friendly);
46
47 static void dummy(__a_unused int s)
48 {
49 }
50
51 static void mmd_dup(struct misc_meta_data *new_mmd)
52 {
53 mutex_lock(mmd_mutex);
54 *new_mmd = *mmd;
55 mutex_unlock(mmd_mutex);
56 }
57
58 /*
59 * Compute human readable string containing vss status for given integer value.
60 *
61 * We don't want to use vss_playing() and friends here because we take a
62 * snapshot of the mmd struct and use the copy for computing the state of the
63 * vss. If the real data were used, we would take the mmd lock for a rather
64 * long time or risk to get an inconsistent view.
65 */
66 static char *vss_status_tohuman(unsigned int flags)
67 {
68 if (flags & VSS_PLAYING)
69 return para_strdup("playing");
70 if (flags & VSS_NEXT)
71 return para_strdup("stopped");
72 return para_strdup("paused");
73 }
74
75 /*
76 * return human readable permission string. Never returns NULL.
77 */
78 static char *cmd_perms_itohuman(unsigned int perms)
79 {
80 char *msg = para_malloc(5 * sizeof(char));
81
82 msg[0] = perms & AFS_READ? 'a' : '-';
83 msg[1] = perms & AFS_WRITE? 'A' : '-';
84 msg[2] = perms & VSS_READ? 'v' : '-';
85 msg[3] = perms & VSS_WRITE? 'V' : '-';
86 msg[4] = '\0';
87 return msg;
88 }
89
90 /*
91 * Never returns NULL.
92 */
93 static char *vss_get_status_flags(unsigned int flags)
94 {
95 char *msg = para_malloc(5 * sizeof(char));
96
97 msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
98 msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
99 msg[2] = (flags & VSS_NEXT)? 'N' : '_';
100 msg[3] = (flags & VSS_REPOS)? 'R' : '_';
101 msg[4] = '\0';
102 return msg;
103 }
104
105 static unsigned get_status(struct misc_meta_data *nmmd, int parser_friendly,
106 char **result)
107 {
108 char mtime[30] = "";
109 char *status, *flags; /* vss status info */
110 /* nobody updates our version of "now" */
111 char *ut = get_server_uptime_str(NULL);
112 long offset = (nmmd->offset + 500) / 1000;
113 struct timeval current_time;
114 struct tm mtime_tm;
115 struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
116
117 /* report real status */
118 status = vss_status_tohuman(nmmd->vss_status_flags);
119 flags = vss_get_status_flags(nmmd->vss_status_flags);
120 if (nmmd->size) { /* parent currently has an audio file open */
121 localtime_r(&nmmd->mtime, &mtime_tm);
122 strftime(mtime, 29, "%b %d %Y", &mtime_tm);
123 }
124 gettimeofday(&current_time, NULL);
125 /*
126 * The calls to WRITE_STATUS_ITEM() below never fail because
127 * b->max_size is zero (unlimited), see para_printf(). However, clang
128 * is not smart enough to prove this and complains nevertheless.
129 * Casting the return value to void silences clang.
130 */
131 (void)WRITE_STATUS_ITEM(&b, SI_FILE_SIZE, "%zu\n", nmmd->size / 1024);
132 (void)WRITE_STATUS_ITEM(&b, SI_MTIME, "%s\n", mtime);
133 (void)WRITE_STATUS_ITEM(&b, SI_STATUS, "%s\n", status);
134 (void)WRITE_STATUS_ITEM(&b, SI_STATUS_FLAGS, "%s\n", flags);
135 (void)WRITE_STATUS_ITEM(&b, SI_OFFSET, "%li\n", offset);
136 (void)WRITE_STATUS_ITEM(&b, SI_AFS_MODE, "%s\n", mmd->afs_mode_string);
137 (void)WRITE_STATUS_ITEM(&b, SI_STREAM_START, "%lu.%lu\n",
138 (long unsigned)nmmd->stream_start.tv_sec,
139 (long unsigned)nmmd->stream_start.tv_usec);
140 (void)WRITE_STATUS_ITEM(&b, SI_CURRENT_TIME, "%lu.%lu\n",
141 (long unsigned)current_time.tv_sec,
142 (long unsigned)current_time.tv_usec);
143 free(flags);
144 free(status);
145 free(ut);
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 struct sb_buffer sbb = SBB_INIT(band, buf, numbytes);
222 sb_transformation trafo = band < SBD_PROCEED? NULL : sc_trafo;
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 int send_strerror(struct command_context *cc, int err)
260 {
261 return sc_send_va_buffer(&cc->scc, "%s\n", para_strerror(err));
262 }
263
264 /**
265 * Send a sideband packet through a blocking file descriptor.
266 *
267 * \param scc fd and crypto keys.
268 * \param expected_band The expected band designator.
269 * \param max_size Passed to \ref sb_new_recv().
270 * \param result Body of the sideband packet is returned here.
271 *
272 * If \a expected_band is not \p SBD_ANY, the band designator of the received
273 * sideband packet is compared to \a expected_band and a mismatch is considered
274 * an error.
275 *
276 * \return Standard.
277 */
278 int recv_sb(struct stream_cipher_context *scc,
279 enum sb_designator expected_band,
280 size_t max_size, struct iovec *result)
281 {
282 int ret;
283 struct sb_context *sbc;
284 struct iovec iov;
285 struct sb_buffer sbb;
286 sb_transformation trafo;
287
288 trafo = expected_band != SBD_ANY && expected_band < SBD_PROCEED?
289 NULL : sc_trafo;
290 sbc = sb_new_recv(max_size, trafo, scc->recv);
291 for (;;) {
292 sb_get_recv_buffer(sbc, &iov);
293 ret = recv_bin_buffer(scc->fd, iov.iov_base, iov.iov_len);
294 if (ret == 0)
295 ret = -E_EOF;
296 if (ret < 0)
297 goto fail;
298 ret = sb_received(sbc, ret, &sbb);
299 if (ret < 0)
300 goto fail;
301 if (ret > 0)
302 break;
303 }
304 ret = -E_BAD_BAND;
305 if (expected_band != SBD_ANY && sbb.band != expected_band)
306 goto fail;
307 *result = sbb.iov;
308 return 1;
309 fail:
310 sb_free(sbc);
311 return ret;
312 }
313
314 int com_sender(struct command_context *cc)
315 {
316 int i, ret;
317 char *msg = NULL;
318 struct sender_command_data scd;
319
320 if (cc->argc < 2) {
321 for (i = 0; senders[i].name; i++) {
322 char *tmp = make_message("%s%s\n",
323 msg? msg : "", senders[i].name);
324 free(msg);
325 msg = tmp;
326 }
327 ret = sc_send_buffer(&cc->scc, msg);
328 free(msg);
329 return ret;
330 }
331 ret = check_sender_args(cc->argc, cc->argv, &scd);
332 if (ret < 0) {
333 if (scd.sender_num < 0)
334 return ret;
335 msg = senders[scd.sender_num].help();
336 ret = sc_send_buffer(&cc->scc, msg);
337 free(msg);
338 return ret;
339 }
340
341 switch (scd.cmd_num) {
342 case SENDER_ADD:
343 case SENDER_DELETE:
344 assert(senders[scd.sender_num].resolve_target);
345 ret = senders[scd.sender_num].resolve_target(cc->argv[3], &scd);
346 if (ret < 0)
347 return ret;
348 }
349
350 for (i = 0; i < 10; i++) {
351 mutex_lock(mmd_mutex);
352 if (mmd->sender_cmd_data.cmd_num >= 0) {
353 mutex_unlock(mmd_mutex);
354 usleep(100 * 1000);
355 continue;
356 }
357 memcpy(&mmd->sender_cmd_data, &scd, sizeof(scd));
358 mutex_unlock(mmd_mutex);
359 break;
360 }
361 return (i < 10)? 1 : -E_LOCK;
362 }
363
364 /* server info */
365 int com_si(struct command_context *cc)
366 {
367 int i, ret;
368 char *ut;
369 char *sender_info = NULL;
370
371 if (cc->argc != 1)
372 return -E_COMMAND_SYNTAX;
373 mutex_lock(mmd_mutex);
374 for (i = 0; senders[i].name; i++) {
375 char *info = senders[i].info();
376 sender_info = para_strcat(sender_info, info);
377 free(info);
378 }
379 ut = get_server_uptime_str(now);
380 ret = sc_send_va_buffer(&cc->scc, "version: " GIT_VERSION "\n"
381 "up: %s\nplayed: %u\n"
382 "server_pid: %d\n"
383 "afs_pid: %d\n"
384 "connections (active/accepted/total): %u/%u/%u\n"
385 "current loglevel: %s\n"
386 "supported audio formats: %s\n"
387 "%s",
388 ut, mmd->num_played,
389 (int)getppid(),
390 (int)mmd->afs_pid,
391 mmd->active_connections,
392 mmd->num_commands,
393 mmd->num_connects,
394 conf.loglevel_arg,
395 SERVER_AUDIO_FORMATS,
396 sender_info
397 );
398 mutex_unlock(mmd_mutex);
399 free(ut);
400 free(sender_info);
401 return ret;
402 }
403
404 /* version */
405 int com_version(struct command_context *cc)
406 {
407 if (cc->argc != 1)
408 return -E_COMMAND_SYNTAX;
409 return sc_send_buffer(&cc->scc, VERSION_TEXT("server")
410 "built: " BUILD_DATE "\n"
411 UNAME_RS ", " CC_VERSION "\n"
412 );
413 }
414
415 #define EMPTY_STATUS_ITEMS \
416 ITEM(PATH) \
417 ITEM(DIRECTORY) \
418 ITEM(BASENAME) \
419 ITEM(SCORE) \
420 ITEM(ATTRIBUTES_BITMAP) \
421 ITEM(ATTRIBUTES_TXT) \
422 ITEM(HASH) \
423 ITEM(IMAGE_ID) \
424 ITEM(IMAGE_NAME) \
425 ITEM(LYRICS_ID) \
426 ITEM(LYRICS_NAME) \
427 ITEM(BITRATE) \
428 ITEM(FORMAT) \
429 ITEM(FREQUENCY) \
430 ITEM(CHANNELS) \
431 ITEM(DURATION) \
432 ITEM(SECONDS_TOTAL) \
433 ITEM(NUM_PLAYED) \
434 ITEM(LAST_PLAYED) \
435 ITEM(TECHINFO) \
436 ITEM(ARTIST) \
437 ITEM(TITLE) \
438 ITEM(YEAR) \
439 ITEM(ALBUM) \
440 ITEM(COMMENT) \
441 ITEM(AMPLIFICATION)
442
443 /**
444 * Write a list of audio-file related status items with empty values.
445 *
446 * This is used by vss when currently no audio file is open.
447 */
448 static char *empty_status_items(int parser_friendly)
449 {
450 if (parser_friendly)
451 return make_message(
452 #define ITEM(x) "0004 %02x:\n"
453 EMPTY_STATUS_ITEMS
454 #undef ITEM
455 #define ITEM(x) , SI_ ## x
456 EMPTY_STATUS_ITEMS
457 #undef ITEM
458 );
459 return make_message(
460 #define ITEM(x) "%s:\n"
461 EMPTY_STATUS_ITEMS
462 #undef ITEM
463 #define ITEM(x) ,status_item_list[SI_ ## x]
464 EMPTY_STATUS_ITEMS
465 #undef ITEM
466 );
467 }
468 #undef EMPTY_STATUS_ITEMS
469
470 /* stat */
471 int com_stat(struct command_context *cc)
472 {
473 int i, ret;
474 struct misc_meta_data tmp, *nmmd = &tmp;
475 char *s;
476 int32_t num = 0;
477 int parser_friendly = 0;
478
479 para_sigaction(SIGUSR1, dummy);
480
481 for (i = 1; i < cc->argc; i++) {
482 const char *arg = cc->argv[i];
483 if (arg[0] != '-')
484 break;
485 if (!strcmp(arg, "--")) {
486 i++;
487 break;
488 }
489 if (!strncmp(arg, "-n=", 3)) {
490 ret = para_atoi32(arg + 3, &num);
491 if (ret < 0)
492 return ret;
493 continue;
494 }
495 if (!strcmp(arg, "-p")) {
496 parser_friendly = 1;
497 continue;
498 }
499 return -E_COMMAND_SYNTAX;
500 }
501 if (i != cc->argc)
502 return -E_COMMAND_SYNTAX;
503 for (;;) {
504 mmd_dup(nmmd);
505 ret = get_status(nmmd, parser_friendly, &s);
506 ret = sc_send_bin_buffer(&cc->scc, s, ret);
507 free(s);
508 if (ret < 0)
509 goto out;
510 if (nmmd->vss_status_flags & VSS_NEXT) {
511 static char *esi;
512 if (!esi)
513 esi = empty_status_items(parser_friendly);
514 ret = sc_send_buffer(&cc->scc, esi);
515 if (ret < 0)
516 goto out;
517 } else
518 send_afs_status(cc, parser_friendly);
519 ret = 1;
520 if (num > 0 && !--num)
521 goto out;
522 sleep(50);
523 if (getppid() == 1)
524 return -E_SERVER_CRASH;
525 }
526 out:
527 return ret;
528 }
529
530 static int send_list_of_commands(struct stream_cipher_context *scc, struct server_command *cmd,
531 const char *handler)
532 {
533 int ret, i;
534
535 for (i = 1; cmd->name; cmd++, i++) {
536 char *perms = cmd_perms_itohuman(cmd->perms);
537 ret = sc_send_va_buffer(scc, "%s\t%s\t%s\t%s\n", cmd->name,
538 handler,
539 perms,
540 cmd->description);
541 free(perms);
542 if (ret < 0)
543 return ret;
544 }
545 return 1;
546 }
547
548 /* returns string that must be freed by the caller */
549 static struct server_command *get_cmd_ptr(const char *name, char **handler)
550 {
551 struct server_command *cmd;
552
553 for (cmd = server_cmds; cmd->name; cmd++)
554 if (!strcmp(cmd->name, name)) {
555 if (handler)
556 *handler = para_strdup("server"); /* server commands */
557 return cmd;
558 }
559 /* not found, look for commands supported by afs */
560 for (cmd = afs_cmds; cmd->name; cmd++)
561 if (!strcmp(cmd->name, name)) {
562 if (handler)
563 *handler = para_strdup("afs");
564 return cmd;
565 }
566 return NULL;
567 }
568
569 /* help */
570 int com_help(struct command_context *cc)
571 {
572 struct server_command *cmd;
573 char *perms, *handler;
574 int ret;
575
576 if (cc->argc < 2) {
577 /* no argument given, print list of commands */
578 if ((ret = send_list_of_commands(&cc->scc, server_cmds, "server")) < 0)
579 return ret;
580 return send_list_of_commands(&cc->scc, afs_cmds, "afs");
581 }
582 /* argument given for help */
583 cmd = get_cmd_ptr(cc->argv[1], &handler);
584 if (!cmd)
585 return -E_BAD_CMD;
586 perms = cmd_perms_itohuman(cmd->perms);
587 ret = sc_send_va_buffer(&cc->scc,
588 "%s - %s\n\n"
589 "handler: %s\n"
590 "permissions: %s\n"
591 "usage: %s\n\n"
592 "%s\n",
593 cc->argv[1],
594 cmd->description,
595 handler,
596 perms,
597 cmd->usage,
598 cmd->help
599 );
600 free(perms);
601 free(handler);
602 return ret;
603 }
604
605 /* hup */
606 int com_hup(struct command_context *cc)
607 {
608 if (cc->argc != 1)
609 return -E_COMMAND_SYNTAX;
610 kill(getppid(), SIGHUP);
611 return 1;
612 }
613
614 /* term */
615 int com_term(struct command_context *cc)
616 {
617 if (cc->argc != 1)
618 return -E_COMMAND_SYNTAX;
619 kill(getppid(), SIGTERM);
620 return 1;
621 }
622
623 int com_play(struct command_context *cc)
624 {
625 if (cc->argc != 1)
626 return -E_COMMAND_SYNTAX;
627 mutex_lock(mmd_mutex);
628 mmd->new_vss_status_flags |= VSS_PLAYING;
629 mmd->new_vss_status_flags &= ~VSS_NOMORE;
630 mutex_unlock(mmd_mutex);
631 return 1;
632 }
633
634 /* stop */
635 int com_stop(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_REPOS;
642 mmd->new_vss_status_flags |= VSS_NEXT;
643 mutex_unlock(mmd_mutex);
644 return 1;
645 }
646
647 /* pause */
648 int com_pause(struct command_context *cc)
649 {
650 if (cc->argc != 1)
651 return -E_COMMAND_SYNTAX;
652 mutex_lock(mmd_mutex);
653 if (!vss_paused() && !vss_stopped()) {
654 mmd->events++;
655 mmd->new_vss_status_flags &= ~VSS_PLAYING;
656 mmd->new_vss_status_flags &= ~VSS_NEXT;
657 }
658 mutex_unlock(mmd_mutex);
659 return 1;
660 }
661
662 /* next */
663 int com_next(struct command_context *cc)
664 {
665 if (cc->argc != 1)
666 return -E_COMMAND_SYNTAX;
667 mutex_lock(mmd_mutex);
668 mmd->events++;
669 mmd->new_vss_status_flags |= VSS_NEXT;
670 mutex_unlock(mmd_mutex);
671 return 1;
672 }
673
674 /* nomore */
675 int com_nomore(struct command_context *cc)
676 {
677 if (cc->argc != 1)
678 return -E_COMMAND_SYNTAX;
679 mutex_lock(mmd_mutex);
680 if (vss_playing() || vss_paused())
681 mmd->new_vss_status_flags |= VSS_NOMORE;
682 mutex_unlock(mmd_mutex);
683 return 1;
684 }
685
686 /* ff */
687 int com_ff(struct command_context *cc)
688 {
689 long promille;
690 int ret, backwards = 0;
691 unsigned i;
692 char c;
693
694 if (cc->argc != 2)
695 return -E_COMMAND_SYNTAX;
696 if (!(ret = sscanf(cc->argv[1], "%u%c", &i, &c)))
697 return -E_COMMAND_SYNTAX;
698 if (ret > 1 && c == '-')
699 backwards = 1; /* jmp backwards */
700 mutex_lock(mmd_mutex);
701 ret = -E_NO_AUDIO_FILE;
702 if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
703 goto out;
704 promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
705 if (backwards)
706 promille -= 1000 * i / mmd->afd.afhi.seconds_total;
707 else
708 promille += 1000 * i / mmd->afd.afhi.seconds_total;
709 if (promille < 0)
710 promille = 0;
711 if (promille > 1000) {
712 mmd->new_vss_status_flags |= VSS_NEXT;
713 goto out;
714 }
715 mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
716 mmd->new_vss_status_flags |= VSS_REPOS;
717 mmd->new_vss_status_flags &= ~VSS_NEXT;
718 mmd->events++;
719 ret = 1;
720 out:
721 mutex_unlock(mmd_mutex);
722 return ret;
723 }
724
725 /* jmp */
726 int com_jmp(struct command_context *cc)
727 {
728 long unsigned int i;
729 int ret;
730
731 if (cc->argc != 2)
732 return -E_COMMAND_SYNTAX;
733 if (sscanf(cc->argv[1], "%lu", &i) <= 0)
734 return -E_COMMAND_SYNTAX;
735 mutex_lock(mmd_mutex);
736 ret = -E_NO_AUDIO_FILE;
737 if (!mmd->afd.afhi.chunks_total)
738 goto out;
739 if (i > 100)
740 i = 100;
741 PARA_INFO_LOG("jumping to %lu%%\n", i);
742 mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50)/ 100;
743 PARA_INFO_LOG("sent: %lu, offset before jmp: %lu\n",
744 mmd->chunks_sent, mmd->offset);
745 mmd->new_vss_status_flags |= VSS_REPOS;
746 mmd->new_vss_status_flags &= ~VSS_NEXT;
747 ret = 1;
748 mmd->events++;
749 out:
750 mutex_unlock(mmd_mutex);
751 return ret;
752 }
753
754 /*
755 * check if perms are sufficient to exec a command having perms cmd_perms.
756 * Returns 0 if perms are sufficient, -E_PERM otherwise.
757 */
758 static int check_perms(unsigned int perms, struct server_command *cmd_ptr)
759 {
760 PARA_DEBUG_LOG("checking permissions\n");
761 return (cmd_ptr->perms & perms) < cmd_ptr->perms ? -E_PERM : 0;
762 }
763
764 /*
765 * Parse first string from *cmd and lookup in table of valid commands.
766 * On error, NULL is returned.
767 */
768 static struct server_command *parse_cmd(const char *cmdstr)
769 {
770 char buf[255];
771 int n = 0;
772
773 sscanf(cmdstr, "%200s%n", buf, &n);
774 if (!n)
775 return NULL;
776 buf[n] = '\0';
777 return get_cmd_ptr(buf, NULL);
778 }
779
780 static int read_command(struct stream_cipher_context *scc, char **result)
781 {
782 int ret;
783 char buf[4096];
784 char *command = NULL;
785
786 for (;;) {
787 size_t numbytes;
788 char *p;
789
790 ret = sc_recv_buffer(scc, buf, sizeof(buf));
791 if (ret < 0)
792 goto out;
793 if (!ret)
794 break;
795 numbytes = ret;
796 ret = -E_COMMAND_SYNTAX;
797 if (command && numbytes + strlen(command) > MAX_COMMAND_LEN) /* DOS */
798 goto out;
799 command = para_strcat(command, buf);
800 p = strstr(command, EOC_MSG);
801 if (p) {
802 *p = '\0';
803 break;
804 }
805 }
806 ret = command? 1 : -E_COMMAND_SYNTAX;
807 out:
808 if (ret < 0)
809 free(command);
810 else
811 *result = command;
812 return ret;
813
814 }
815
816 static void reset_signals(void)
817 {
818 para_sigaction(SIGCHLD, SIG_IGN);
819 para_sigaction(SIGINT, SIG_DFL);
820 para_sigaction(SIGTERM, SIG_DFL);
821 para_sigaction(SIGHUP, SIG_DFL);
822 }
823
824 static int parse_auth_request(char *buf, int len, struct user **u,
825 bool *use_sideband)
826 {
827 int ret;
828 char *p, *username, **features = NULL;
829 size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
830
831 *u = NULL;
832 *use_sideband = false;
833 if (len < auth_rq_len + 2)
834 return -E_AUTH_REQUEST;
835 if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
836 return -E_AUTH_REQUEST;
837 username = buf + auth_rq_len;
838 p = strchr(username, ' ');
839 if (p) {
840 int i;
841 if (p == username)
842 return -E_AUTH_REQUEST;
843 *p = '\0';
844 p++;
845 create_argv(p, ",", &features);
846 for (i = 0; features[i]; i++) {
847 if (strcmp(features[i], "sideband") == 0)
848 *use_sideband = true;
849 else {
850 ret = -E_BAD_FEATURE;
851 goto out;
852 }
853 }
854 }
855 PARA_DEBUG_LOG("received auth request for user %s (sideband = %s)\n",
856 username, *use_sideband? "true" : "false");
857 *u = lookup_user(username);
858 ret = 1;
859 out:
860 free_argv(features);
861 return ret;
862 }
863
864 #define HANDSHAKE_BUFSIZE 4096
865
866 static int parse_sb_command(struct command_context *cc, struct iovec *iov)
867 {
868 int ret, i;
869 char *p, *end;
870
871 ret = -E_BAD_CMD;
872 if (iov->iov_base == NULL || iov->iov_len == 0)
873 goto out;
874 p = iov->iov_base;
875 p[iov->iov_len - 1] = '\0'; /* just to be sure */
876 cc->cmd = get_cmd_ptr(p, NULL);
877 if (!cc->cmd)
878 goto out;
879 ret = check_perms(cc->u->perms, cc->cmd);
880 if (ret < 0)
881 goto out;
882 end = iov->iov_base + iov->iov_len;
883 for (i = 0, p = iov->iov_base; p < end; i++)
884 p += strlen(p) + 1;
885 cc->argc = i;
886 cc->argv = para_malloc((cc->argc + 1) * sizeof(char *));
887 for (i = 0, p = iov->iov_base; p < end; i++) {
888 cc->argv[i] = para_strdup(p);
889 p += strlen(p) + 1;
890 }
891 cc->argv[cc->argc] = NULL;
892 ret = cc->argc;
893 out:
894 free(iov->iov_base);
895 return ret;
896 }
897
898 /**
899 * Perform user authentication and execute a command.
900 *
901 * \param fd The file descriptor to send output to.
902 * \param peername Identifies the connecting peer.
903 *
904 * Whenever para_server accepts an incoming tcp connection on
905 * the port it listens on, it forks and the resulting child
906 * calls this function.
907 *
908 * An RSA-based challenge/response is used to authenticate
909 * the peer. It that authentication succeeds, a random
910 * session key is generated and sent back to the peer,
911 * encrypted with its RSA public key. From this point on,
912 * all transfers are crypted with this session key.
913 *
914 * Next it is checked if the peer supplied a valid server command or a command
915 * for the audio file selector. If yes, and if the user has sufficient
916 * permissions to execute that command, the function calls the corresponding
917 * command handler which does argument checking and further processing.
918 *
919 * In order to cope with a DOS attacks, a timeout is set up
920 * which terminates the function if the connection was not
921 * authenticated when the timeout expires.
922 *
923 * \sa alarm(2), crypt.c, crypt.h
924 */
925 __noreturn void handle_connect(int fd, const char *peername)
926 {
927 int ret;
928 unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
929 unsigned char challenge_hash[HASH_SIZE];
930 char *p, *command = NULL, *buf = para_malloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
931 size_t numbytes;
932 struct command_context cc_struct = {.peer = peername}, *cc = &cc_struct;
933
934 cc->scc.fd = fd;
935 reset_signals();
936 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
937 ret = mark_fd_blocking(fd);
938 if (ret < 0)
939 goto net_err;
940 /* send Welcome message */
941 ret = write_va_buffer(fd, "This is para_server, version "
942 PACKAGE_VERSION ".\n"
943 "Features: sideband,foo\n"
944 );
945 if (ret < 0)
946 goto net_err;
947 /* recv auth request line */
948 ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
949 if (ret < 0)
950 goto net_err;
951 ret = parse_auth_request(buf, ret, &cc->u, &cc->use_sideband);
952 if (ret < 0)
953 goto net_err;
954 p = buf + strlen(AUTH_REQUEST_MSG);
955 PARA_DEBUG_LOG("received auth request for user %s\n", p);
956 cc->u = lookup_user(p);
957 if (cc->u) {
958 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
959 ret = pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
960 (unsigned char *)buf);
961 if (ret < 0)
962 goto net_err;
963 numbytes = ret;
964 } else {
965 /*
966 * We don't want to reveal our user names, so we send a
967 * challenge to the client even if the user does not exist, and
968 * fail the authentication later.
969 */
970 numbytes = 256;
971 get_random_bytes_or_die((unsigned char *)buf, numbytes);
972 }
973 PARA_DEBUG_LOG("sending %u byte challenge + rc4 keys (%zu bytes)\n",
974 CHALLENGE_SIZE, numbytes);
975 if (cc->use_sideband) {
976 struct iovec iov;
977 ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
978 buf = NULL;
979 if (ret < 0)
980 goto net_err;
981 ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
982 HANDSHAKE_BUFSIZE, &iov);
983 if (ret < 0)
984 goto net_err;
985 buf = iov.iov_base;
986 numbytes = iov.iov_len;
987 } else {
988 ret = write_all(fd, buf, numbytes);
989 if (ret < 0)
990 goto net_err;
991 /* recv challenge response */
992 ret = recv_bin_buffer(fd, buf, HASH_SIZE);
993 if (ret < 0)
994 goto net_err;
995 numbytes = ret;
996 }
997 PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
998 ret = -E_BAD_USER;
999 if (!cc->u)
1000 goto net_err;
1001 /*
1002 * The correct response is the hash of the first CHALLENGE_SIZE bytes
1003 * of the random data.
1004 */
1005 ret = -E_BAD_AUTH;
1006 if (numbytes != HASH_SIZE)
1007 goto net_err;
1008 hash_function((char *)rand_buf, CHALLENGE_SIZE, challenge_hash);
1009 if (memcmp(challenge_hash, buf, HASH_SIZE))
1010 goto net_err;
1011 /* auth successful */
1012 alarm(0);
1013 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
1014 /* init stream cipher keys with the second part of the random buffer */
1015 cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
1016 cc->scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN, SESSION_KEY_LEN);
1017 if (cc->use_sideband)
1018 ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
1019 else
1020 ret = sc_send_buffer(&cc->scc, PROCEED_MSG);
1021 if (ret < 0)
1022 goto net_err;
1023 if (cc->use_sideband) {
1024 struct iovec iov;
1025 ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
1026 if (ret < 0)
1027 goto net_err;
1028 ret = parse_sb_command(cc, &iov);
1029 if (ret < 0)
1030 goto err_out;
1031 cc->argc = ret;
1032 } else {
1033 ret = read_command(&cc->scc, &command);
1034 if (ret == -E_COMMAND_SYNTAX)
1035 goto err_out;
1036 if (ret < 0)
1037 goto net_err;
1038 ret = -E_BAD_CMD;
1039 cc->cmd = parse_cmd(command);
1040 if (!cc->cmd)
1041 goto err_out;
1042 /* valid command, check permissions */
1043 ret = check_perms(cc->u->perms, cc->cmd);
1044 if (ret < 0)
1045 goto err_out;
1046 /* valid command and sufficient perms */
1047 ret = create_argv(command, "\n", &cc->argv);
1048 if (ret < 0)
1049 goto err_out;
1050 cc->argc = ret;
1051 }
1052 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cc->cmd->name,
1053 cc->u->name, peername);
1054 ret = cc->cmd->handler(cc);
1055 free_argv(cc->argv);
1056 mutex_lock(mmd_mutex);
1057 mmd->num_commands++;
1058 mutex_unlock(mmd_mutex);
1059 if (ret >= 0)
1060 goto out;
1061 err_out:
1062 send_strerror(cc, -ret);
1063 net_err:
1064 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1065 out:
1066 free(buf);
1067 free(command);
1068 sc_free(cc->scc.recv);
1069 sc_free(cc->scc.send);
1070 mutex_lock(mmd_mutex);
1071 if (cc->cmd && (cc->cmd->perms & AFS_WRITE) && ret >= 0)
1072 mmd->events++;
1073 mmd->active_connections--;
1074 mutex_unlock(mmd_mutex);
1075 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
1076 }