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