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