com_lsblob: Print an error message if no blob matched.
[paraslash.git] / command.c
1 /*
2 * Copyright (C) 1997-2011 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 #include <stdbool.h>
15
16 #include "para.h"
17 #include "error.h"
18 #include "crypt.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 "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 "sched.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 stream_cipher_context *scc, int parser_friendly);
46
47 const char *status_item_list[] = {STATUS_ITEM_ARRAY};
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 char *get_status(struct misc_meta_data *nmmd, int parser_friendly)
108 {
109 char mtime[30] = "";
110 char *status, *flags; /* vss status info */
111 /* nobody updates our version of "now" */
112 char *ut = get_server_uptime_str(NULL);
113 long offset = (nmmd->offset + 500) / 1000;
114 struct timeval current_time;
115 struct tm mtime_tm;
116 struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
117
118 /* report real status */
119 status = vss_status_tohuman(nmmd->vss_status_flags);
120 flags = vss_get_status_flags(nmmd->vss_status_flags);
121 if (nmmd->size) { /* parent currently has an audio file open */
122 localtime_r(&nmmd->mtime, &mtime_tm);
123 strftime(mtime, 29, "%b %d %Y", &mtime_tm);
124 }
125 gettimeofday(&current_time, NULL);
126 /*
127 * The calls to WRITE_STATUS_ITEM() below never fail because
128 * b->max_size is zero (unlimited), see para_printf(). However, clang
129 * is not smart enough to prove this and complains nevertheless.
130 * Casting the return value to void silences solves this.
131 */
132 (void)WRITE_STATUS_ITEM(&b, SI_FILE_SIZE, "%zu\n", nmmd->size / 1024);
133 (void)WRITE_STATUS_ITEM(&b, SI_MTIME, "%s\n", mtime);
134 (void)WRITE_STATUS_ITEM(&b, SI_STATUS, "%s\n", status);
135 (void)WRITE_STATUS_ITEM(&b, SI_STATUS_FLAGS, "%s\n", flags);
136 (void)WRITE_STATUS_ITEM(&b, SI_OFFSET, "%li\n", offset);
137 (void)WRITE_STATUS_ITEM(&b, SI_AFS_MODE, "%s\n", mmd->afs_mode_string);
138 (void)WRITE_STATUS_ITEM(&b, SI_STREAM_START, "%lu.%lu\n",
139 (long unsigned)nmmd->stream_start.tv_sec,
140 (long unsigned)nmmd->stream_start.tv_usec);
141 (void)WRITE_STATUS_ITEM(&b, SI_CURRENT_TIME, "%lu.%lu\n",
142 (long unsigned)current_time.tv_sec,
143 (long unsigned)current_time.tv_usec);
144 free(flags);
145 free(status);
146 free(ut);
147 return b.buf;
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 int com_sender(struct stream_cipher_context *scc, int argc, char * const * argv)
198 {
199 int i, ret;
200 char *msg = NULL;
201 struct sender_command_data scd;
202
203 if (argc < 2) {
204 for (i = 0; senders[i].name; i++) {
205 char *tmp = make_message("%s%s\n",
206 msg? msg : "", senders[i].name);
207 free(msg);
208 msg = tmp;
209 }
210 ret = sc_send_buffer(scc, msg);
211 free(msg);
212 return ret;
213 }
214 ret = check_sender_args(argc, argv, &scd);
215 if (ret < 0) {
216 if (scd.sender_num < 0)
217 return ret;
218 msg = senders[scd.sender_num].help();
219 ret = sc_send_buffer(scc, msg);
220 free(msg);
221 return ret;
222 }
223
224 switch (scd.cmd_num) {
225 case SENDER_ADD:
226 case SENDER_DELETE:
227 assert(senders[scd.sender_num].resolve_target);
228 ret = senders[scd.sender_num].resolve_target(argv[3], &scd);
229 if (ret < 0)
230 return ret;
231 }
232
233 for (i = 0; i < 10; i++) {
234 mutex_lock(mmd_mutex);
235 if (mmd->sender_cmd_data.cmd_num >= 0) {
236 mutex_unlock(mmd_mutex);
237 usleep(100 * 1000);
238 continue;
239 }
240 memcpy(&mmd->sender_cmd_data, &scd, sizeof(scd));
241 mutex_unlock(mmd_mutex);
242 break;
243 }
244 return (i < 10)? 1 : -E_LOCK;
245 }
246
247 /* server info */
248 int com_si(struct stream_cipher_context *scc, int argc, __a_unused char * const * argv)
249 {
250 int i, ret;
251 char *ut;
252 char *sender_info = NULL;
253
254 if (argc != 1)
255 return -E_COMMAND_SYNTAX;
256 mutex_lock(mmd_mutex);
257 for (i = 0; senders[i].name; i++) {
258 char *info = senders[i].info();
259 sender_info = para_strcat(sender_info, info);
260 free(info);
261 }
262 ut = get_server_uptime_str(now);
263 ret = sc_send_va_buffer(scc, "version: " GIT_VERSION "\n"
264 "up: %s\nplayed: %u\n"
265 "server_pid: %d\n"
266 "afs_pid: %d\n"
267 "connections (active/accepted/total): %u/%u/%u\n"
268 "current loglevel: %s\n"
269 "supported audio formats: %s\n"
270 "%s",
271 ut, mmd->num_played,
272 (int)getppid(),
273 (int)mmd->afs_pid,
274 mmd->active_connections,
275 mmd->num_commands,
276 mmd->num_connects,
277 conf.loglevel_arg,
278 SERVER_AUDIO_FORMATS,
279 sender_info
280 );
281 mutex_unlock(mmd_mutex);
282 free(ut);
283 free(sender_info);
284 return ret;
285 }
286
287 /* version */
288 int com_version(struct stream_cipher_context *scc, int argc, __a_unused char * const * argv)
289 {
290 if (argc != 1)
291 return -E_COMMAND_SYNTAX;
292 return sc_send_buffer(scc, VERSION_TEXT("server")
293 "built: " BUILD_DATE "\n"
294 UNAME_RS ", " CC_VERSION "\n"
295 );
296 }
297
298 #define EMPTY_STATUS_ITEMS \
299 ITEM(PATH) \
300 ITEM(DIRECTORY) \
301 ITEM(BASENAME) \
302 ITEM(SCORE) \
303 ITEM(ATTRIBUTES_BITMAP) \
304 ITEM(ATTRIBUTES_TXT) \
305 ITEM(HASH) \
306 ITEM(IMAGE_ID) \
307 ITEM(IMAGE_NAME) \
308 ITEM(LYRICS_ID) \
309 ITEM(LYRICS_NAME) \
310 ITEM(BITRATE) \
311 ITEM(FORMAT) \
312 ITEM(FREQUENCY) \
313 ITEM(CHANNELS) \
314 ITEM(DURATION) \
315 ITEM(SECONDS_TOTAL) \
316 ITEM(NUM_PLAYED) \
317 ITEM(LAST_PLAYED) \
318 ITEM(TECHINFO) \
319 ITEM(ARTIST) \
320 ITEM(TITLE) \
321 ITEM(YEAR) \
322 ITEM(ALBUM) \
323 ITEM(COMMENT) \
324 ITEM(AMPLIFICATION)
325
326 /**
327 * Write a list of audio-file related status items with empty values.
328 *
329 * This is used by vss when currently no audio file is open.
330 */
331 static char *empty_status_items(int parser_friendly)
332 {
333 if (parser_friendly)
334 return make_message(
335 #define ITEM(x) "0004 %02x:\n"
336 EMPTY_STATUS_ITEMS
337 #undef ITEM
338 #define ITEM(x) , SI_ ## x
339 EMPTY_STATUS_ITEMS
340 #undef ITEM
341 );
342 return make_message(
343 #define ITEM(x) "%s:\n"
344 EMPTY_STATUS_ITEMS
345 #undef ITEM
346 #define ITEM(x) ,status_item_list[SI_ ## x]
347 EMPTY_STATUS_ITEMS
348 #undef ITEM
349 );
350 }
351 #undef EMPTY_STATUS_ITEMS
352
353 /* stat */
354 int com_stat(struct stream_cipher_context *scc, int argc, char * const * argv)
355 {
356 int i, ret;
357 struct misc_meta_data tmp, *nmmd = &tmp;
358 char *s;
359 int32_t num = 0;
360 int parser_friendly = 0;
361
362 para_sigaction(SIGUSR1, dummy);
363
364 for (i = 1; i < argc; i++) {
365 const char *arg = argv[i];
366 if (arg[0] != '-')
367 break;
368 if (!strcmp(arg, "--")) {
369 i++;
370 break;
371 }
372 if (!strncmp(arg, "-n=", 3)) {
373 ret = para_atoi32(arg + 3, &num);
374 if (ret < 0)
375 return ret;
376 continue;
377 }
378 if (!strcmp(arg, "-p")) {
379 parser_friendly = 1;
380 continue;
381 }
382 return -E_COMMAND_SYNTAX;
383 }
384 if (i != argc)
385 return -E_COMMAND_SYNTAX;
386 for (;;) {
387 mmd_dup(nmmd);
388 s = get_status(nmmd, parser_friendly);
389 ret = sc_send_buffer(scc, s);
390 free(s);
391 if (ret < 0)
392 goto out;
393 if (nmmd->vss_status_flags & VSS_NEXT) {
394 static char *esi;
395 if (!esi)
396 esi = empty_status_items(parser_friendly);
397 ret = sc_send_buffer(scc, esi);
398 if (ret < 0)
399 goto out;
400 } else
401 send_afs_status(scc, parser_friendly);
402 ret = 1;
403 if (num > 0 && !--num)
404 goto out;
405 sleep(50);
406 if (getppid() == 1)
407 return -E_SERVER_CRASH;
408 }
409 out:
410 return ret;
411 }
412
413 static int send_list_of_commands(struct stream_cipher_context *scc, struct server_command *cmd,
414 const char *handler)
415 {
416 int ret, i;
417
418 for (i = 1; cmd->name; cmd++, i++) {
419 char *perms = cmd_perms_itohuman(cmd->perms);
420 ret = sc_send_va_buffer(scc, "%s\t%s\t%s\t%s\n", cmd->name,
421 handler,
422 perms,
423 cmd->description);
424 free(perms);
425 if (ret < 0)
426 return ret;
427 }
428 return 1;
429 }
430
431 /* returns string that must be freed by the caller */
432 static struct server_command *get_cmd_ptr(const char *name, char **handler)
433 {
434 struct server_command *cmd;
435
436 for (cmd = server_cmds; cmd->name; cmd++)
437 if (!strcmp(cmd->name, name)) {
438 if (handler)
439 *handler = para_strdup("server"); /* server commands */
440 return cmd;
441 }
442 /* not found, look for commands supported by afs */
443 for (cmd = afs_cmds; cmd->name; cmd++)
444 if (!strcmp(cmd->name, name)) {
445 if (handler)
446 *handler = para_strdup("afs");
447 return cmd;
448 }
449 return NULL;
450 }
451
452 /* help */
453 int com_help(struct stream_cipher_context *scc, int argc, char * const * argv)
454 {
455 struct server_command *cmd;
456 char *perms, *handler;
457 int ret;
458
459 if (argc < 2) {
460 /* no argument given, print list of commands */
461 if ((ret = send_list_of_commands(scc, server_cmds, "server")) < 0)
462 return ret;
463 return send_list_of_commands(scc, afs_cmds, "afs");
464 }
465 /* argument given for help */
466 cmd = get_cmd_ptr(argv[1], &handler);
467 if (!cmd)
468 return -E_BAD_CMD;
469 perms = cmd_perms_itohuman(cmd->perms);
470 ret = sc_send_va_buffer(scc,
471 "%s - %s\n\n"
472 "handler: %s\n"
473 "permissions: %s\n"
474 "usage: %s\n\n"
475 "%s\n",
476 argv[1],
477 cmd->description,
478 handler,
479 perms,
480 cmd->usage,
481 cmd->help
482 );
483 free(perms);
484 free(handler);
485 return ret;
486 }
487
488 /* hup */
489 int com_hup(__a_unused struct stream_cipher_context *scc, int argc, __a_unused char * const * argv)
490 {
491 if (argc != 1)
492 return -E_COMMAND_SYNTAX;
493 kill(getppid(), SIGHUP);
494 return 1;
495 }
496
497 /* term */
498 int com_term(__a_unused struct stream_cipher_context *scc, int argc, __a_unused char * const * argv)
499 {
500 if (argc != 1)
501 return -E_COMMAND_SYNTAX;
502 kill(getppid(), SIGTERM);
503 return 1;
504 }
505
506 int com_play(__a_unused struct stream_cipher_context *scc, int argc, __a_unused char * const * argv)
507 {
508 if (argc != 1)
509 return -E_COMMAND_SYNTAX;
510 mutex_lock(mmd_mutex);
511 mmd->new_vss_status_flags |= VSS_PLAYING;
512 mmd->new_vss_status_flags &= ~VSS_NOMORE;
513 mutex_unlock(mmd_mutex);
514 return 1;
515
516 }
517
518 /* stop */
519 int com_stop(__a_unused struct stream_cipher_context *scc, int argc, __a_unused char * const * argv)
520 {
521 if (argc != 1)
522 return -E_COMMAND_SYNTAX;
523 mutex_lock(mmd_mutex);
524 mmd->new_vss_status_flags &= ~VSS_PLAYING;
525 mmd->new_vss_status_flags &= ~VSS_REPOS;
526 mmd->new_vss_status_flags |= VSS_NEXT;
527 mutex_unlock(mmd_mutex);
528 return 1;
529 }
530
531 /* pause */
532 int com_pause(__a_unused struct stream_cipher_context *scc, int argc, __a_unused char * const * argv)
533 {
534 if (argc != 1)
535 return -E_COMMAND_SYNTAX;
536 mutex_lock(mmd_mutex);
537 if (!vss_paused() && !vss_stopped()) {
538 mmd->events++;
539 mmd->new_vss_status_flags &= ~VSS_PLAYING;
540 mmd->new_vss_status_flags &= ~VSS_NEXT;
541 }
542 mutex_unlock(mmd_mutex);
543 return 1;
544 }
545
546 /* next */
547 int com_next(__a_unused struct stream_cipher_context *scc, int argc, __a_unused char * const * argv)
548 {
549 if (argc != 1)
550 return -E_COMMAND_SYNTAX;
551 mutex_lock(mmd_mutex);
552 mmd->events++;
553 mmd->new_vss_status_flags |= VSS_NEXT;
554 mutex_unlock(mmd_mutex);
555 return 1;
556 }
557
558 /* nomore */
559 int com_nomore(__a_unused struct stream_cipher_context *scc, int argc, __a_unused char * const * argv)
560 {
561 if (argc != 1)
562 return -E_COMMAND_SYNTAX;
563 mutex_lock(mmd_mutex);
564 if (vss_playing() || vss_paused())
565 mmd->new_vss_status_flags |= VSS_NOMORE;
566 mutex_unlock(mmd_mutex);
567 return 1;
568 }
569
570 /* ff */
571 int com_ff(__a_unused struct stream_cipher_context *scc, int argc, char * const * argv)
572 {
573 long promille;
574 int ret, backwards = 0;
575 unsigned i;
576 char c;
577
578 if (argc != 2)
579 return -E_COMMAND_SYNTAX;
580 if (!(ret = sscanf(argv[1], "%u%c", &i, &c)))
581 return -E_COMMAND_SYNTAX;
582 if (ret > 1 && c == '-')
583 backwards = 1; /* jmp backwards */
584 mutex_lock(mmd_mutex);
585 ret = -E_NO_AUDIO_FILE;
586 if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
587 goto out;
588 promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
589 if (backwards)
590 promille -= 1000 * i / mmd->afd.afhi.seconds_total;
591 else
592 promille += 1000 * i / mmd->afd.afhi.seconds_total;
593 if (promille < 0)
594 promille = 0;
595 if (promille > 1000) {
596 mmd->new_vss_status_flags |= VSS_NEXT;
597 goto out;
598 }
599 mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
600 mmd->new_vss_status_flags |= VSS_REPOS;
601 mmd->new_vss_status_flags &= ~VSS_NEXT;
602 mmd->events++;
603 ret = 1;
604 out:
605 mutex_unlock(mmd_mutex);
606 return ret;
607 }
608
609 /* jmp */
610 int com_jmp(__a_unused struct stream_cipher_context *scc, int argc, char * const * argv)
611 {
612 long unsigned int i;
613 int ret;
614
615 if (argc != 2)
616 return -E_COMMAND_SYNTAX;
617 if (sscanf(argv[1], "%lu", &i) <= 0)
618 return -E_COMMAND_SYNTAX;
619 mutex_lock(mmd_mutex);
620 ret = -E_NO_AUDIO_FILE;
621 if (!mmd->afd.afhi.chunks_total)
622 goto out;
623 if (i > 100)
624 i = 100;
625 PARA_INFO_LOG("jumping to %lu%%\n", i);
626 mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50)/ 100;
627 PARA_INFO_LOG("sent: %lu, offset before jmp: %lu\n",
628 mmd->chunks_sent, mmd->offset);
629 mmd->new_vss_status_flags |= VSS_REPOS;
630 mmd->new_vss_status_flags &= ~VSS_NEXT;
631 ret = 1;
632 mmd->events++;
633 out:
634 mutex_unlock(mmd_mutex);
635 return ret;
636 }
637
638 /*
639 * check if perms are sufficient to exec a command having perms cmd_perms.
640 * Returns 0 if perms are sufficient, -E_PERM otherwise.
641 */
642 static int check_perms(unsigned int perms, struct server_command *cmd_ptr)
643 {
644 PARA_DEBUG_LOG("checking permissions\n");
645 return (cmd_ptr->perms & perms) < cmd_ptr->perms ? -E_PERM : 0;
646 }
647
648 /*
649 * Parse first string from *cmd and lookup in table of valid commands.
650 * On error, NULL is returned.
651 */
652 static struct server_command *parse_cmd(const char *cmdstr)
653 {
654 char buf[255];
655 int n = 0;
656
657 sscanf(cmdstr, "%200s%n", buf, &n);
658 if (!n)
659 return NULL;
660 buf[n] = '\0';
661 return get_cmd_ptr(buf, NULL);
662 }
663
664 static int read_command(struct stream_cipher_context *scc, char **result)
665 {
666 int ret;
667 char buf[4096];
668 char *command = NULL;
669
670 for (;;) {
671 size_t numbytes;
672 char *p;
673
674 ret = sc_recv_buffer(scc, buf, sizeof(buf));
675 if (ret < 0)
676 goto out;
677 if (!ret)
678 break;
679 numbytes = ret;
680 ret = -E_COMMAND_SYNTAX;
681 if (command && numbytes + strlen(command) > MAX_COMMAND_LEN) /* DOS */
682 goto out;
683 command = para_strcat(command, buf);
684 p = strstr(command, EOC_MSG);
685 if (p) {
686 *p = '\0';
687 break;
688 }
689 }
690 ret = command? 1 : -E_COMMAND_SYNTAX;
691 out:
692 if (ret < 0)
693 free(command);
694 else
695 *result = command;
696 return ret;
697
698 }
699
700 static void reset_signals(void)
701 {
702 para_sigaction(SIGCHLD, SIG_IGN);
703 para_sigaction(SIGINT, SIG_DFL);
704 para_sigaction(SIGTERM, SIG_DFL);
705 para_sigaction(SIGHUP, SIG_DFL);
706 }
707
708 /**
709 * Perform user authentication and execute a command.
710 *
711 * \param fd The file descriptor to send output to.
712 * \param peername Identifies the connecting peer.
713 *
714 * Whenever para_server accepts an incoming tcp connection on
715 * the port it listens on, it forks and the resulting child
716 * calls this function.
717 *
718 * An RSA-based challenge/response is used to authenticate
719 * the peer. It that authentication succeeds, a random
720 * session key is generated and sent back to the peer,
721 * encrypted with its RSA public key. From this point on,
722 * all transfers are crypted with this session key.
723 *
724 * Next it is checked if the peer supplied a valid server command or a command
725 * for the audio file selector. If yes, and if the user has sufficient
726 * permissions to execute that command, the function calls the corresponding
727 * command handler which does argument checking and further processing.
728 *
729 * In order to cope with a DOS attacks, a timeout is set up
730 * which terminates the function if the connection was not
731 * authenticated when the timeout expires.
732 *
733 * \sa alarm(2), crypt.c, crypt.h
734 */
735 __noreturn void handle_connect(int fd, const char *peername)
736 {
737 int ret, argc;
738 char buf[4096];
739 unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
740 unsigned char challenge_hash[HASH_SIZE];
741 struct user *u;
742 struct server_command *cmd = NULL;
743 char **argv = NULL;
744 char *p, *command = NULL;
745 size_t numbytes;
746 struct stream_cipher_context scc = {.fd = fd};
747
748 reset_signals();
749 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
750 ret = mark_fd_blocking(fd);
751 if (ret < 0)
752 goto net_err;
753 /* send Welcome message */
754 ret = send_va_buffer(fd, "This is para_server, version "
755 PACKAGE_VERSION ".\n" );
756 if (ret < 0)
757 goto net_err;
758 /* recv auth request line */
759 ret = recv_buffer(fd, buf, sizeof(buf));
760 if (ret < 0)
761 goto net_err;
762 if (ret < 10) {
763 ret = -E_AUTH_REQUEST;
764 goto net_err;
765 }
766 ret = -E_AUTH_REQUEST;
767 if (strncmp(buf, AUTH_REQUEST_MSG, strlen(AUTH_REQUEST_MSG)))
768 goto net_err;
769 p = buf + strlen(AUTH_REQUEST_MSG);
770 PARA_DEBUG_LOG("received auth request for user %s\n", p);
771 u = lookup_user(p);
772 if (u) {
773 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
774 ret = pub_encrypt(u->pubkey, rand_buf, sizeof(rand_buf),
775 (unsigned char *)buf);
776 if (ret < 0)
777 goto net_err;
778 numbytes = ret;
779 } else {
780 /*
781 * We don't want to reveal our user names, so we send a
782 * challenge to the client even if the user does not exist, and
783 * fail the authentication later.
784 */
785 numbytes = 256;
786 get_random_bytes_or_die((unsigned char *)buf, numbytes);
787 }
788 PARA_DEBUG_LOG("sending %u byte challenge + rc4 keys (%zu bytes)\n",
789 CHALLENGE_SIZE, numbytes);
790 ret = send_bin_buffer(fd, buf, numbytes);
791 if (ret < 0)
792 goto net_err;
793 /* recv challenge response */
794 ret = recv_bin_buffer(fd, buf, HASH_SIZE);
795 if (ret < 0)
796 goto net_err;
797 numbytes = ret;
798 PARA_DEBUG_LOG("received %d bytes challenge response\n", ret);
799 ret = -E_BAD_USER;
800 if (!u)
801 goto net_err;
802 /*
803 * The correct response is the hash of the first CHALLENGE_SIZE bytes
804 * of the random data.
805 */
806 ret = -E_BAD_AUTH;
807 if (numbytes != HASH_SIZE)
808 goto net_err;
809 hash_function((char *)rand_buf, CHALLENGE_SIZE, challenge_hash);
810 if (memcmp(challenge_hash, buf, HASH_SIZE))
811 goto net_err;
812 /* auth successful */
813 alarm(0);
814 PARA_INFO_LOG("good auth for %s\n", u->name);
815 /* init stream cipher keys with the second part of the random buffer */
816 scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
817 scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN, SESSION_KEY_LEN);
818 ret = sc_send_buffer(&scc, PROCEED_MSG);
819 if (ret < 0)
820 goto net_err;
821 ret = read_command(&scc, &command);
822 if (ret == -E_COMMAND_SYNTAX)
823 goto err_out;
824 if (ret < 0)
825 goto net_err;
826 ret = -E_BAD_CMD;
827 cmd = parse_cmd(command);
828 if (!cmd)
829 goto err_out;
830 /* valid command, check permissions */
831 ret = check_perms(u->perms, cmd);
832 if (ret < 0)
833 goto err_out;
834 /* valid command and sufficient perms */
835 ret = create_argv(command, "\n", &argv);
836 if (ret < 0)
837 goto err_out;
838 argc = ret;
839 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cmd->name, u->name,
840 peername);
841 ret = cmd->handler(&scc, argc, argv);
842 free_argv(argv);
843 mutex_lock(mmd_mutex);
844 mmd->num_commands++;
845 mutex_unlock(mmd_mutex);
846 if (ret >= 0)
847 goto out;
848 err_out:
849 sc_send_va_buffer(&scc, "%s\n", para_strerror(-ret));
850 net_err:
851 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
852 out:
853 free(command);
854 sc_free(scc.recv);
855 sc_free(scc.send);
856 mutex_lock(mmd_mutex);
857 if (cmd && (cmd->perms & AFS_WRITE) && ret >= 0)
858 mmd->events++;
859 mmd->active_connections--;
860 mutex_unlock(mmd_mutex);
861 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
862 }