Revamp status item handling.
[paraslash.git] / command.c
1 /*
2 * Copyright (C) 1997-2009 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 <signal.h>
10 #include <sys/time.h>
11 #include <sys/types.h>
12 #include <dirent.h>
13 #include <openssl/rc4.h>
14 #include <osl.h>
15
16 #include "para.h"
17 #include "error.h"
18 #include "server.cmdline.h"
19 #include "string.h"
20 #include "afh.h"
21 #include "afs.h"
22 #include "server.h"
23 #include "vss.h"
24 #include "list.h"
25 #include "send.h"
26 #include "rc4.h"
27 #include "net.h"
28 #include "daemon.h"
29 #include "fd.h"
30 #include "ipc.h"
31 #include "user_list.h"
32 #include "server_command_list.h"
33 #include "afs_command_list.h"
34 #include "sched.h"
35 #include "signal.h"
36
37 /** Commands including options must be shorter than this. */
38 #define MAX_COMMAND_LEN 32768
39
40 static RC4_KEY rc4_recv_key;
41 static RC4_KEY rc4_send_key;
42 static unsigned char rc4_buf[2 * RC4_KEY_LEN];
43
44 extern int mmd_mutex;
45 extern struct misc_meta_data *mmd;
46 extern struct sender senders[];
47
48 static void dummy(__a_unused int s)
49 {
50 }
51
52 static void mmd_dup(struct misc_meta_data *new_mmd)
53 {
54 mutex_lock(mmd_mutex);
55 *new_mmd = *mmd;
56 mutex_unlock(mmd_mutex);
57 }
58
59 /*
60 * Compute human readable string containing vss status for given integer value.
61 *
62 * We don't want to use vss_playing() and friends here because we take a
63 * snapshot of the mmd struct and use the copy for computing the state of the
64 * vss. If the real data were used, we would take the mmd lock for a rather
65 * long time or risk to get an inconsistent view.
66 */
67 static char *vss_status_tohuman(unsigned int flags)
68 {
69 if (flags & VSS_PLAYING)
70 return para_strdup("playing");
71 if (flags & VSS_NEXT)
72 return para_strdup("stopped");
73 return para_strdup("paused");
74 }
75
76 /*
77 * return human readable permission string. Never returns NULL.
78 */
79 static char *cmd_perms_itohuman(unsigned int perms)
80 {
81 char *msg = para_malloc(5 * sizeof(char));
82
83 msg[0] = perms & AFS_READ? 'a' : '-';
84 msg[1] = perms & AFS_WRITE? 'A' : '-';
85 msg[2] = perms & VSS_READ? 'v' : '-';
86 msg[3] = perms & VSS_WRITE? 'V' : '-';
87 msg[4] = '\0';
88 return msg;
89 }
90
91 /*
92 * Never returns NULL.
93 */
94 static char *vss_get_status_flags(unsigned int flags)
95 {
96 char *msg = para_malloc(5 * sizeof(char));
97
98 msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
99 msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
100 msg[2] = (flags & VSS_NEXT)? 'N' : '_';
101 msg[3] = (flags & VSS_REPOS)? 'R' : '_';
102 msg[4] = '\0';
103 return msg;
104 }
105
106 static char *get_status(struct misc_meta_data *nmmd, int parser_friendly)
107 {
108 char mtime[30] = "";
109 char *status, *flags; /* vss status info */
110 char *ut = uptime_str();
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 WRITE_STATUS_ITEM(&b, SI_FILE_SIZE, "%zu\n", nmmd->size / 1024);
125 WRITE_STATUS_ITEM(&b, SI_MTIME, "%s\n", mtime);
126 WRITE_STATUS_ITEM(&b, SI_STATUS, "%s\n", status);
127 WRITE_STATUS_ITEM(&b, SI_STATUS_FLAGS, "%s\n", flags);
128 WRITE_STATUS_ITEM(&b, SI_OFFSET, "%li\n", offset);
129 WRITE_STATUS_ITEM(&b, SI_AFS_MODE, "%s\n", mmd->afs_mode_string);
130 WRITE_STATUS_ITEM(&b, SI_STREAM_START, "%lu.%lu\n",
131 (long unsigned)nmmd->stream_start.tv_sec,
132 (long unsigned)nmmd->stream_start.tv_usec);
133 WRITE_STATUS_ITEM(&b, SI_CURRENT_TIME, "%lu.%lu\n",
134 (long unsigned)current_time.tv_sec,
135 (long unsigned)current_time.tv_usec);
136 free(flags);
137 free(status);
138 free(ut);
139 return b.buf;
140 }
141
142 static int check_sender_args(int argc, char * const * argv, struct sender_command_data *scd)
143 {
144 int i;
145 /* this has to match sender.h */
146 const char *subcmds[] = {"add", "delete", "allow", "deny", "on", "off", NULL};
147
148 scd->sender_num = -1;
149 if (argc < 2)
150 return -E_COMMAND_SYNTAX;
151 for (i = 0; senders[i].name; i++)
152 if (!strcmp(senders[i].name, argv[1]))
153 break;
154 PARA_DEBUG_LOG("%d:%s\n", argc, argv[1]);
155 if (!senders[i].name)
156 return -E_COMMAND_SYNTAX;
157 scd->sender_num = i;
158 for (i = 0; subcmds[i]; i++)
159 if (!strcmp(subcmds[i], argv[2]))
160 break;
161 if (!subcmds[i])
162 return -E_COMMAND_SYNTAX;
163 scd->cmd_num = i;
164 if (!senders[scd->sender_num].client_cmds[scd->cmd_num])
165 return -E_SENDER_CMD;
166 switch (scd->cmd_num) {
167 case SENDER_ON:
168 case SENDER_OFF:
169 if (argc != 3)
170 return -E_COMMAND_SYNTAX;
171 break;
172 case SENDER_DENY:
173 case SENDER_ALLOW:
174 if (argc != 4 && argc != 5)
175 return -E_COMMAND_SYNTAX;
176 if (!is_valid_ipv4_address(argv[3]))
177 return -E_COMMAND_SYNTAX;
178 scd->netmask = 32;
179 if (argc == 5) {
180 scd->netmask = atoi(argv[4]);
181 if (scd->netmask < 0 || scd->netmask > 32)
182 return -E_COMMAND_SYNTAX;
183 }
184 strncpy(scd->host, argv[3], sizeof(scd->host));
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(int fd, int argc, char * const * argv)
198 {
199 int i, ret;
200 struct sender_command_data scd;
201
202 if (argc < 2) {
203 char *msg = NULL;
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 = send_buffer(fd, msg);
211 free(msg);
212 return ret;
213 }
214 ret = check_sender_args(argc, argv, &scd);
215 if (ret < 0) {
216 char *msg;
217 if (scd.sender_num < 0)
218 return ret;
219 msg = senders[scd.sender_num].help();
220 ret = send_buffer(fd, msg);
221 free(msg);
222 return ret;
223 }
224 for (i = 0; i < 10; i++) {
225 mutex_lock(mmd_mutex);
226 if (mmd->sender_cmd_data.cmd_num >= 0) {
227 mutex_unlock(mmd_mutex);
228 usleep(100 * 1000);
229 continue;
230 }
231 memcpy(&mmd->sender_cmd_data, &scd, sizeof(scd));
232 mutex_unlock(mmd_mutex);
233 break;
234 }
235 return (i < 10)? 1 : -E_LOCK;
236 }
237
238 /* server info */
239 int com_si(int fd, int argc, __a_unused char * const * argv)
240 {
241 int i, ret;
242 char *ut;
243 char *sender_info = NULL, *sender_list = NULL;
244
245 if (argc != 1)
246 return -E_COMMAND_SYNTAX;
247 mutex_lock(mmd_mutex);
248 for (i = 0; senders[i].name; i++) {
249 char *info = senders[i].info();
250 sender_info = para_strcat(sender_info, info);
251 free(info);
252 sender_list = para_strcat(sender_list, senders[i].name);
253 sender_list = para_strcat(sender_list, " ");
254 }
255 ut = uptime_str();
256 ret = send_va_buffer(fd, "up: %s\nplayed: %u\n"
257 "server_pid: %d\n"
258 "afs_pid: %d\n"
259 "connections (active/accepted/total): %u/%u/%u\n"
260 "current loglevel: %s\n"
261 "supported audio formats: %s\n"
262 "supported senders: %s\n"
263 "%s",
264 ut, mmd->num_played,
265 (int)getppid(),
266 (int)mmd->afs_pid,
267 mmd->active_connections,
268 mmd->num_commands,
269 mmd->num_connects,
270 conf.loglevel_arg,
271 supported_audio_formats(),
272 sender_list,
273 sender_info
274 );
275 mutex_unlock(mmd_mutex);
276 free(ut);
277 free(sender_list);
278 free(sender_info);
279 return ret;
280 }
281
282 /* version */
283 int com_version(int fd, int argc, __a_unused char * const * argv)
284 {
285 if (argc != 1)
286 return -E_COMMAND_SYNTAX;
287 return send_buffer(fd, 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(int fd, 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 }
378 if (i != argc)
379 return -E_COMMAND_SYNTAX;
380 for (;;) {
381 mmd_dup(nmmd);
382 s = get_status(nmmd, parser_friendly);
383 ret = send_buffer(fd, s);
384 free(s);
385 if (ret < 0)
386 goto out;
387 if (nmmd->vss_status_flags & VSS_NEXT) {
388 static char *esi;
389 if (!esi)
390 esi = empty_status_items(parser_friendly);
391 ret = send_buffer(fd, esi);
392 if (ret < 0)
393 goto out;
394 } else
395 send_afs_status(fd, parser_friendly);
396 ret = 1;
397 if (num > 0 && !--num)
398 goto out;
399 sleep(50);
400 if (getppid() == 1)
401 return -E_SERVER_CRASH;
402 }
403 out:
404 return ret;
405 }
406
407 static int send_list_of_commands(int fd, struct server_command *cmd,
408 const char *handler)
409 {
410 int ret, i;
411
412 for (i = 1; cmd->name; cmd++, i++) {
413 char *perms = cmd_perms_itohuman(cmd->perms);
414 ret = send_va_buffer(fd, "%s\t%s\t%s\t%s\n", cmd->name,
415 handler,
416 perms,
417 cmd->description);
418 free(perms);
419 if (ret < 0)
420 return ret;
421 }
422 return 1;
423 }
424
425 /* returns string that must be freed by the caller */
426 static struct server_command *get_cmd_ptr(const char *name, char **handler)
427 {
428 struct server_command *cmd;
429
430 for (cmd = server_cmds; cmd->name; cmd++)
431 if (!strcmp(cmd->name, name)) {
432 if (handler)
433 *handler = para_strdup("server"); /* server commands */
434 return cmd;
435 }
436 /* not found, look for commands supported by afs */
437 for (cmd = afs_cmds; cmd->name; cmd++)
438 if (!strcmp(cmd->name, name)) {
439 if (handler)
440 *handler = para_strdup("afs");
441 return cmd;
442 }
443 return NULL;
444 }
445
446 /* help */
447 int com_help(int fd, int argc, char * const * argv)
448 {
449 struct server_command *cmd;
450 char *perms, *handler;
451 int ret;
452
453 if (argc < 2) {
454 /* no argument given, print list of commands */
455 if ((ret = send_list_of_commands(fd, server_cmds, "server")) < 0)
456 return ret;
457 return send_list_of_commands(fd, afs_cmds, "afs");
458 }
459 /* argument given for help */
460 cmd = get_cmd_ptr(argv[1], &handler);
461 if (!cmd) {
462 free(handler);
463 return -E_BAD_CMD;
464 }
465 perms = cmd_perms_itohuman(cmd->perms);
466 ret = send_va_buffer(fd,
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 int fd, 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 int fd, 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 int fd, 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 int fd, 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 int fd, 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 int fd, 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 int fd, 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 int fd, 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 int fd, 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 void init_rc4_keys(void)
661 {
662 int i;
663
664 for (i = 0; i < 2 * RC4_KEY_LEN; i++)
665 rc4_buf[i] = para_random(256);
666 PARA_DEBUG_LOG("rc4 keys initialized (%u:%u)\n",
667 (unsigned char) rc4_buf[0],
668 (unsigned char) rc4_buf[RC4_KEY_LEN]);
669 RC4_set_key(&rc4_recv_key, RC4_KEY_LEN, rc4_buf);
670 RC4_set_key(&rc4_send_key, RC4_KEY_LEN, rc4_buf + RC4_KEY_LEN);
671 }
672
673 static void rc4_recv(unsigned long len, const unsigned char *indata,
674 unsigned char *outdata, __a_unused void *private_data)
675 {
676 RC4(&rc4_recv_key, len, indata, outdata);
677 }
678
679 static void rc4_send(unsigned long len, const unsigned char *indata,
680 unsigned char *outdata, __a_unused void *private_data)
681 {
682 RC4(&rc4_send_key, len, indata, outdata);
683 }
684
685 static int read_command(int fd, char **result)
686 {
687 int ret;
688 char buf[4096];
689 char *command = NULL;
690
691 for (;;) {
692 size_t numbytes;
693 char *p;
694
695 ret = recv_buffer(fd, buf, sizeof(buf));
696 if (ret < 0)
697 goto out;
698 if (!ret)
699 break;
700 numbytes = ret;
701 ret = -E_COMMAND_SYNTAX;
702 if (command && numbytes + strlen(command) > MAX_COMMAND_LEN) /* DOS */
703 goto out;
704 command = para_strcat(command, buf);
705 p = strstr(command, EOC_MSG);
706 if (p) {
707 *p = '\0';
708 break;
709 }
710 }
711 ret = command? 1 : -E_COMMAND_SYNTAX;
712 out:
713 if (ret < 0)
714 free(command);
715 else
716 *result = command;
717 return ret;
718
719 }
720
721 static void reset_signals(void)
722 {
723 para_sigaction(SIGCHLD, SIG_IGN);
724 para_sigaction(SIGINT, SIG_DFL);
725 para_sigaction(SIGTERM, SIG_DFL);
726 para_sigaction(SIGHUP, SIG_DFL);
727 }
728
729 /**
730 * Perform user authentication and execute a command.
731 *
732 * \param fd The file descriptor to send output to.
733 * \param peername Identifies the connecting peer.
734 *
735 * Whenever para_server accepts an incoming tcp connection on
736 * the port it listens on, it forks and the resulting child
737 * calls this function.
738 *
739 * An RSA-based challenge/response is used to authenticate
740 * the peer. It that authentication succeeds, a random RC4
741 * session key is generated and sent back to the peer,
742 * encrypted with its RSA public key. From this point on,
743 * all transfers are crypted with this session key.
744 *
745 * Next it is checked if the peer supplied a valid server command or a command
746 * for the audio file selector. If yes, and if the user has sufficient
747 * permissions to execute that command, the function calls the corresponding
748 * command handler which does argument checking and further processing.
749 *
750 * In order to cope with a DOS attacks, a timeout is set up
751 * which terminates the function if the connection was not
752 * authenticated when the timeout expires.
753 *
754 * \sa alarm(2), rc4(3), crypt.c, crypt.h
755 */
756 __noreturn void handle_connect(int fd, const char *peername)
757 {
758 int ret, argc, use_rc4 = 0;
759 char buf[4096];
760 unsigned char crypt_buf[MAXLINE];
761 struct user *u;
762 struct server_command *cmd = NULL;
763 long unsigned challenge_nr, chall_response;
764 char **argv = NULL;
765 char *p, *command = NULL;
766 size_t numbytes;
767
768 reset_signals();
769 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
770 ret = mark_fd_blocking(fd);
771 if (ret < 0)
772 goto err_out;
773 challenge_nr = random();
774 /* send Welcome message */
775 ret = send_va_buffer(fd, "This is para_server, version "
776 PACKAGE_VERSION ".\n" );
777 if (ret < 0)
778 goto err_out;
779 /* recv auth request line */
780 ret = recv_buffer(fd, buf, sizeof(buf));
781 if (ret < 0)
782 goto err_out;
783 if (ret <= 6) {
784 ret = -E_AUTH;
785 goto err_out;
786 }
787 numbytes = ret;
788 ret = -E_AUTH;
789 if (strncmp(buf, "auth ", 5))
790 goto err_out;
791
792 if (numbytes < 9 || strncmp(buf, "auth rc4 ", 9))
793 p = buf + 5; /* client version < 0.2.6 */
794 else {
795 p = buf + 9; /* client version >= 0.2.6 */
796 use_rc4 = 1;
797 }
798 PARA_DEBUG_LOG("received %s request for user %s\n",
799 use_rc4? "rc4" : "auth", p);
800 ret = -E_BAD_USER;
801 u = lookup_user(p);
802 if (!u)
803 goto err_out;
804 ret = para_encrypt_challenge(u->rsa, challenge_nr, crypt_buf);
805 if (ret <= 0)
806 goto err_out;
807 numbytes = ret;
808 PARA_DEBUG_LOG("sending %zu byte challenge\n", numbytes);
809 /* We can't use send_buffer here since buf may contain null bytes */
810 ret = send_bin_buffer(fd,(char *) crypt_buf, numbytes);
811 if (ret < 0)
812 goto net_err;
813 /* recv decrypted number */
814 ret = recv_buffer(fd, buf, sizeof(buf));
815 if (ret < 0)
816 goto net_err;
817 numbytes = ret;
818 ret = -E_AUTH;
819 if (!numbytes)
820 goto net_err;
821 if (sscanf(buf, CHALLENGE_RESPONSE_MSG "%lu", &chall_response) < 1
822 || chall_response != challenge_nr)
823 goto err_out;
824 /* auth successful, send 'Proceed' message */
825 PARA_INFO_LOG("good auth for %s (%lu)\n", u->name, challenge_nr);
826 sprintf(buf, "%s", PROCEED_MSG);
827 if (use_rc4) {
828 init_rc4_keys();
829 ret = para_encrypt_buffer(u->rsa, rc4_buf, 2 * RC4_KEY_LEN,
830 (unsigned char *)buf + PROCEED_MSG_LEN + 1);
831 if (ret <= 0)
832 goto err_out;
833 numbytes = ret + strlen(PROCEED_MSG) + 1;
834 } else
835 numbytes = strlen(buf);
836 ret = send_bin_buffer(fd, buf, numbytes);
837 if (ret < 0)
838 goto net_err;
839 if (use_rc4)
840 enable_crypt(fd, rc4_recv, rc4_send, NULL);
841 ret = read_command(fd, &command);
842 if (ret == -E_COMMAND_SYNTAX)
843 goto err_out;
844 if (ret < 0)
845 goto net_err;
846 ret = -E_BAD_CMD;
847 cmd = parse_cmd(command);
848 if (!cmd)
849 goto err_out;
850 /* valid command, check permissions */
851 ret = check_perms(u->perms, cmd);
852 if (ret < 0)
853 goto err_out;
854 /* valid command and sufficient perms */
855 alarm(0);
856 argc = split_args(command, &argv, "\n");
857 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cmd->name, u->name,
858 peername);
859 ret = cmd->handler(fd, argc, argv);
860 mutex_lock(mmd_mutex);
861 mmd->num_commands++;
862 mutex_unlock(mmd_mutex);
863 if (ret >= 0)
864 goto out;
865 err_out:
866 send_va_buffer(fd, "%s\n", para_strerror(-ret));
867 net_err:
868 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
869 out:
870 free(command);
871 free(argv);
872 mutex_lock(mmd_mutex);
873 if (cmd && (cmd->perms & AFS_WRITE) && ret >= 0)
874 mmd->events++;
875 mmd->active_connections--;
876 mutex_unlock(mmd_mutex);
877 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
878 }