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