Merge /fml/ag-raetsch/home/maan/scm/paraslash_meins/paraslash/
[paraslash.git] / command.c
1 /*
2 * Copyright (C) 1997-2007 Andre Noll <maan@systemlinux.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
17 */
18
19 /** \file command.c does client authentication and executes server commands */
20
21 #include <sys/time.h> /* gettimeofday */
22 #include "server.cmdline.h"
23 #include "db.h"
24 #include "server.h"
25 #include "vss.h"
26 #include "send.h"
27 #include "rc4.h"
28 #include <openssl/rc4.h>
29 #include "error.h"
30 #include "net.h"
31 #include "daemon.h"
32 #include "string.h"
33 #include "fd.h"
34 #include "user_list.h"
35 #include "server_command_list.h"
36
37 static RC4_KEY rc4_recv_key;
38 static RC4_KEY rc4_send_key;
39 static unsigned char rc4_buf[2 * RC4_KEY_LEN];
40
41 extern const char *status_item_list[NUM_STAT_ITEMS];
42 extern struct misc_meta_data *mmd;
43 extern struct audio_file_selector selectors[];
44 extern struct sender senders[];
45 extern char *user_list;
46
47 static void dummy(__a_unused int s)
48 {}
49
50 static void mmd_dup(struct misc_meta_data *new_mmd)
51 {
52 mmd_lock();
53 *new_mmd = *mmd;
54 mmd_unlock();
55 }
56
57 /*
58 * compute human readable string containing
59 * vss status for given integer value
60 */
61 static char *vss_status_tohuman(unsigned int flags)
62 {
63 if (flags & VSS_PLAYING)
64 return para_strdup("playing");
65 else if (flags & VSS_NEXT)
66 return para_strdup("stopped");
67 else
68 return para_strdup("paused");
69 }
70
71 /*
72 * return human readable permission string. Never returns NULL.
73 */
74 static char *cmd_perms_itohuman(unsigned int perms)
75 {
76 char *msg = para_malloc(5 * sizeof(char));
77
78 msg[0] = perms & DB_READ? 'a' : '-';
79 msg[1] = perms & DB_WRITE? 'A' : '-';
80 msg[2] = perms & VSS_READ? 'v' : '-';
81 msg[3] = perms & VSS_WRITE? 'V' : '-';
82 msg[4] = '\0';
83 return msg;
84 }
85
86 /*
87 * Never returns NULL.
88 */
89 static char *vss_get_status_flags(unsigned int flags)
90 {
91 char *msg = para_malloc(5 * sizeof(char));
92
93 msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
94 msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
95 msg[2] = (flags & VSS_NEXT)? 'N' : '_';
96 msg[3] = (flags & VSS_REPOS)? 'R' : '_';
97 msg[4] = '\0';
98 return msg;
99 }
100
101 /*
102 * compute status bar string. Never returns NULL
103 */
104 static char *get_sb_string(struct misc_meta_data *nmmd)
105 {
106 char *base, *ret;
107 long long unsigned secs = 0, rsecs = 0, percent = 0;
108
109 base = para_basename(nmmd->filename);
110 if (!base)
111 return para_strdup("");
112 if (!base[0])
113 return base;
114 if (nmmd->chunks_total) {
115 secs = (long long) nmmd->seconds_total * nmmd->chunks_sent
116 / nmmd->chunks_total;
117 rsecs = (long long) nmmd->seconds_total *
118 (nmmd->chunks_total - nmmd->chunks_sent)
119 / nmmd->chunks_total;
120 percent = 100 * ((nmmd->chunks_sent + 5) / 10)
121 / ((nmmd->chunks_total + 5) / 10);
122 }
123 ret = make_message("%llu:%02llu [%llu:%02llu] (%llu%%) %s",
124 secs / 60, secs % 60,
125 rsecs / 60, rsecs % 60,
126 percent,
127 base
128 );
129 free(base);
130 return ret;
131 }
132
133 static char *get_status(struct misc_meta_data *nmmd)
134 {
135 char *bar, *ret, mtime[30] = "";
136 char *status, *flags; /* vss status info */
137 char *ut = uptime_str();
138 long offset = (nmmd->offset + 500) / 1000;
139 struct timeval now;
140 struct tm mtime_tm;
141
142 if (nmmd->audio_format >= 0) {
143 localtime_r(&nmmd->mtime, &mtime_tm);
144 strftime(mtime, 29, "%a %b %d %Y", &mtime_tm);
145 }
146 /* report real status */
147 status = vss_status_tohuman(nmmd->vss_status_flags);
148 flags = vss_get_status_flags(nmmd->vss_status_flags);
149 bar = para_basename(nmmd->filename);
150 gettimeofday(&now, NULL);
151 ret = make_message(
152 "%s:%lu\n" "%s:%s\n" "%s:%i\n" "%s:%u\n"
153 "%s:%s\n" "%s:%s\n" "%s:%s\n" "%s:%s\n"
154 "%s:%li\n" "%s:%s\n" "%s" "%s"
155 "%s:%s\n" "%s:%lu.%lu\n" "%s:%lu.%lu\n",
156 status_item_list[SI_FILE_SIZE], nmmd->size / 1024,
157 status_item_list[SI_MTIME], mtime,
158 status_item_list[SI_LENGTH], nmmd->seconds_total,
159 status_item_list[SI_NUM_PLAYED], nmmd->num_played,
160
161 status_item_list[SI_STATUS_BAR], bar ? bar : "(none)",
162 status_item_list[SI_STATUS], status,
163 status_item_list[SI_STATUS_FLAGS], flags,
164 status_item_list[SI_SELECTOR], selectors[nmmd->selector_num].name,
165
166 status_item_list[SI_OFFSET], offset,
167 status_item_list[SI_FORMAT], audio_format_name(nmmd->audio_format),
168 nmmd->selector_info,
169 nmmd->audio_file_info,
170
171 status_item_list[SI_UPTIME], ut,
172 status_item_list[SI_STREAM_START],
173 (long unsigned)nmmd->stream_start.tv_sec,
174 (long unsigned)nmmd->stream_start.tv_usec,
175 status_item_list[SI_CURRENT_TIME],
176 (long unsigned)now.tv_sec,
177 (long unsigned)now.tv_usec
178
179 );
180 free(bar);
181 free(flags);
182 free(status);
183 free(ut);
184 return ret;
185 }
186
187 static int check_sender_args(int argc, char **argv, struct sender_command_data *scd)
188 {
189 int i;
190 /* this has to match sender.h */
191 const char *subcmds[] = {"add", "delete", "allow", "deny", "on", "off", NULL};
192
193 scd->sender_num = -1;
194 if (argc < 2)
195 return -E_COMMAND_SYNTAX;
196 for (i = 0; senders[i].name; i++)
197 if (!strcmp(senders[i].name, argv[1]))
198 break;
199 PARA_DEBUG_LOG("%d:%s\n", argc, argv[1]);
200 if (!senders[i].name)
201 return -E_COMMAND_SYNTAX;
202 scd->sender_num = i;
203 for (i = 0; subcmds[i]; i++)
204 if (!strcmp(subcmds[i], argv[2]))
205 break;
206 if (!subcmds[i])
207 return -E_COMMAND_SYNTAX;
208 scd->cmd_num = i;
209 mmd_lock();
210 if (!senders[scd->sender_num].client_cmds[scd->cmd_num]) {
211 mmd_unlock();
212 return -E_SENDER_CMD;
213 }
214 mmd_unlock();
215 switch (scd->cmd_num) {
216 case SENDER_ON:
217 case SENDER_OFF:
218 if (argc != 3)
219 return -E_COMMAND_SYNTAX;
220 break;
221 case SENDER_DENY:
222 case SENDER_ALLOW:
223 if (argc != 4 && argc != 5)
224 return -E_COMMAND_SYNTAX;
225 if (!inet_aton(argv[3], &scd->addr))
226 return -E_COMMAND_SYNTAX;
227 scd->netmask = 32;
228 if (argc == 5) {
229 scd->netmask = atoi(argv[4]);
230 if (scd->netmask < 0 || scd->netmask > 32)
231 return -E_COMMAND_SYNTAX;
232 }
233 break;
234 case SENDER_ADD:
235 case SENDER_DELETE:
236 if (argc != 4 && argc != 5)
237 return -E_COMMAND_SYNTAX;
238 if (!inet_aton(argv[3], &scd->addr))
239 return -E_COMMAND_SYNTAX;
240 scd->port = -1;
241 if (argc == 5) {
242 scd->port = atoi(argv[4]);
243 if (scd->port < 0 || scd->port > 65535)
244 return -E_COMMAND_SYNTAX;
245 }
246 break;
247 default:
248 return -E_COMMAND_SYNTAX;
249 }
250 return 1;
251 }
252
253 int com_sender(int fd, int argc, char **argv)
254 {
255 int i, ret;
256 struct sender_command_data scd;
257
258 if (argc < 2) {
259 char *msg = NULL;
260 for (i = 0; senders[i].name; i++) {
261 char *tmp = make_message("%s%s\n",
262 msg? msg : "", senders[i].name);
263 free(msg);
264 msg = tmp;
265 }
266 ret = send_buffer(fd, msg);
267 free(msg);
268 return ret;
269 }
270 ret = check_sender_args(argc, argv, &scd);
271 if (ret < 0) {
272 char *msg;
273 if (scd.sender_num < 0)
274 return ret;
275 msg = senders[scd.sender_num].help();
276 send_buffer(fd, msg);
277 free(msg);
278 return 1;
279 }
280 for (i = 0; i < 10; i++) {
281 mmd_lock();
282 if (mmd->sender_cmd_data.cmd_num >= 0) {
283 mmd_unlock();
284 usleep(100 * 1000);
285 continue;
286 }
287 mmd->sender_cmd_data = scd;
288 mmd_unlock();
289 break;
290 }
291 return (i < 10)? 1 : -E_LOCK;
292 }
293
294 /* server info */
295 int com_si(int fd, int argc, __a_unused char **argv)
296 {
297 int i, ret;
298 char *ut;
299 char *selector_string = NULL, *sender_info = NULL, *sender_list = NULL;
300
301 if (argc != 1)
302 return -E_COMMAND_SYNTAX;
303 mmd_lock();
304 for (i = 0; selectors[i].name; i++) {
305 selector_string = para_strcat(selector_string, selectors[i].name);
306 selector_string = para_strcat(selector_string, " ");
307 }
308 for (i = 0; senders[i].name; i++) {
309 char *info = senders[i].info();
310 sender_info = para_strcat(sender_info, info);
311 free(info);
312 sender_list = para_strcat(sender_list, senders[i].name);
313 sender_list = para_strcat(sender_list, " ");
314 }
315 ut = uptime_str();
316 ret = send_va_buffer(fd, "up: %s\nplayed: %u\n"
317 "pid: %d\n"
318 "connections (active/accepted/total): %u/%u/%u\n"
319 "current loglevel: %i\n"
320 "supported audio file selectors: %s\n"
321 "supported audio formats: %s\n"
322 "supported senders: %s\n"
323 "%s",
324 ut, mmd->num_played,
325 getppid(),
326 mmd->active_connections,
327 mmd->num_commands,
328 mmd->num_connects,
329 conf.loglevel_arg,
330 selector_string,
331 supported_audio_formats(),
332 sender_list,
333 sender_info
334 );
335 mmd_unlock();
336 free(ut);
337 free(selector_string);
338 free(sender_list);
339 free(sender_info);
340 return ret;
341 }
342
343 /* version */
344 int com_version(int socket_fd, int argc, __a_unused char **argv)
345 {
346 if (argc != 1)
347 return -E_COMMAND_SYNTAX;
348 return send_buffer(socket_fd, VERSION_TEXT("server")
349 "built: " BUILD_DATE "\n"
350 SYSTEM ", " CC_VERSION "\n"
351 );
352 }
353
354 /* sc */
355 int com_sc(int socket_fd, int argc, char **argv)
356 {
357 char *name = NULL;
358 int ret, old = 0, count = -1; /* print af change forever */
359
360 if (argc > 1)
361 count = atoi(argv[1]);
362 repeat:
363 mmd_lock();
364 if (old != mmd->num_played) {
365 old = mmd->num_played;
366 name = para_strdup(mmd->filename);
367 }
368 mmd_unlock();
369 if (name) {
370 ret = send_va_buffer(socket_fd, "%s\n", name);
371 free(name);
372 name = NULL;
373 if (ret < 0)
374 return ret;
375 if (argc > 1 && !--count)
376 return 1;
377 }
378 usleep(500000);
379 goto repeat;
380 }
381
382 /* sb */
383 int com_sb(int socket_fd, int argc, char **argv)
384 {
385 char *sb;
386 int ret, nr = -1; /* status bar will be printed that many
387 * times. Negative value means: print
388 * forever
389 */
390 if (argc > 1)
391 nr = atoi(argv[1]);
392 while (nr) {
393 mmd_lock();
394 sb = get_sb_string(mmd);
395 mmd_unlock();
396 ret = send_va_buffer(socket_fd, "%s\n", sb);
397 free(sb);
398 if (ret < 0)
399 return ret;
400 if (nr == 1)
401 return 1;
402 usleep(500000);
403 if (nr > 0)
404 nr--;
405 }
406 return 1;
407 }
408
409 /* stat */
410 int com_stat(int socket_fd, int argc, char **argv)
411 {
412 int ret, num = 0;/* status will be printed that many
413 * times. num <= 0 means: print forever
414 */
415 struct misc_meta_data tmp, *nmmd = &tmp;
416 char *s;
417
418 signal(SIGUSR1, dummy);
419
420 if (argc > 1)
421 num = atoi(argv[1]);
422 for (;;) {
423
424 mmd_dup(nmmd);
425 s = get_status(nmmd);
426 ret = send_buffer(socket_fd, s);
427 free(s);
428 if (ret < 0)
429 goto out;
430 ret = 1;
431 if (num == 1)
432 goto out;
433 sleep(50);
434 if (getppid() == 1)
435 return -E_SERVER_CRASH;
436 }
437 out:
438 return ret;
439 }
440
441 static int send_list_of_commands(int fd, struct server_command *cmd,
442 const char *handler)
443 {
444 int ret, i;
445
446 for (i = 1; cmd->name; cmd++, i++) {
447 char *perms = cmd_perms_itohuman(cmd->perms);
448 ret = send_va_buffer(fd, "%s\t%s\t%s\t%s\n", cmd->name,
449 handler,
450 perms,
451 cmd->description);
452 free(perms);
453 if (ret < 0)
454 return ret;
455 }
456 return 1;
457 }
458
459 /* always returns string that must be freed by the caller in handler */
460 static struct server_command *get_cmd_ptr(char *name, char **handler)
461 {
462 struct server_command *cmd;
463
464 for (cmd = server_cmds; cmd->name; cmd++)
465 if (!strcmp(cmd->name, name)) {
466 if (handler)
467 *handler = para_strdup("para_server"); /* server commands */
468 return cmd;
469 }
470 /* not found, look for commands supported by the current selector */
471 mmd_lock();
472 if (handler)
473 *handler = make_message("the %s selector",
474 selectors[mmd->selector_num].name);
475 cmd = selectors[mmd->selector_num].cmd_list;
476 mmd_unlock();
477 for (; cmd->name; cmd++)
478 if (!strcmp(cmd->name, name))
479 return cmd;
480 return NULL;
481 }
482
483 /* help */
484 int com_help(int fd, int argc, char **argv)
485 {
486 struct server_command *cmd;
487 char *perms, *handler;
488 int ret;
489
490 if (argc < 2) {
491 /* no argument given, print list of commands */
492 if ((ret = send_list_of_commands(fd, server_cmds, "server")) < 0)
493 return ret;
494 mmd_lock();
495 handler = para_strdup(selectors[mmd->selector_num].name);
496 cmd = selectors[mmd->selector_num].cmd_list;
497 mmd_unlock();
498 ret = send_list_of_commands(fd, cmd, handler);
499 free(handler);
500 return ret;
501 }
502 /* argument given for help */
503 cmd = get_cmd_ptr(argv[1], &handler);
504 if (!cmd) {
505 free(handler);
506 return -E_BAD_CMD;
507 }
508 perms = cmd_perms_itohuman(cmd->perms);
509 ret = send_va_buffer(fd,
510 "%s - %s\n\n"
511 "handler: %s\n"
512 "permissions: %s\n"
513 "usage: %s\n\n"
514 "%s\n",
515 argv[1],
516 cmd->description,
517 handler,
518 perms,
519 cmd->usage,
520 cmd->help
521 );
522 free(perms);
523 free(handler);
524 return ret;
525 }
526
527 /* hup */
528 int com_hup(__a_unused int socket_fd, int argc, __a_unused char **argv)
529 {
530 if (argc != 1)
531 return -E_COMMAND_SYNTAX;
532 kill(getppid(), SIGHUP);
533 return 1;
534 }
535
536 /* term */
537 int com_term(__a_unused int socket_fd, int argc, __a_unused char **argv)
538 {
539 if (argc != 1)
540 return -E_COMMAND_SYNTAX;
541 kill(getppid(), SIGTERM);
542 return 1;
543 }
544
545 int com_play(__a_unused int socket_fd, int argc, __a_unused char **argv)
546 {
547 if (argc != 1)
548 return -E_COMMAND_SYNTAX;
549 mmd_lock();
550 mmd->new_vss_status_flags |= VSS_PLAYING;
551 mmd->new_vss_status_flags &= ~VSS_NOMORE;
552 mmd_unlock();
553 return 1;
554
555 }
556
557 /* stop */
558 int com_stop(__a_unused int socket_fd, int argc, __a_unused char **argv)
559 {
560 if (argc != 1)
561 return -E_COMMAND_SYNTAX;
562 mmd_lock();
563 mmd->new_vss_status_flags &= ~VSS_PLAYING;
564 mmd->new_vss_status_flags &= ~VSS_REPOS;
565 mmd->new_vss_status_flags |= VSS_NEXT;
566 mmd_unlock();
567 return 1;
568 }
569
570 /* pause */
571 int com_pause(__a_unused int socket_fd, int argc, __a_unused char **argv)
572 {
573 if (argc != 1)
574 return -E_COMMAND_SYNTAX;
575 mmd_lock();
576 if (!vss_paused())
577 mmd->events++;
578 mmd->new_vss_status_flags &= ~VSS_PLAYING;
579 mmd->new_vss_status_flags &= ~VSS_NEXT;
580 mmd_unlock();
581 return 1;
582 }
583
584 int com_chs(int fd, int argc, char **argv)
585 {
586 int i, ret;
587
588 if (argc == 1) {
589 char *selector;
590 mmd_lock();
591 selector = para_strdup(selectors[mmd->selector_num].name);
592 mmd_unlock();
593 ret = send_va_buffer(fd, "%s\n", selector);
594 free(selector);
595 return ret;
596 }
597 for (i = 0; selectors[i].name; i++) {
598 if (strcmp(selectors[i].name, argv[1]))
599 continue;
600 mmd_lock();
601 mmd->selector_change = i;
602 mmd->events++;
603 mmd_unlock();
604 return 1;
605 }
606 return -E_BAD_SELECTOR;
607 }
608
609 /* next */
610 int com_next(__a_unused int socket_fd, int argc, __a_unused char **argv)
611 {
612 if (argc != 1)
613 return -E_COMMAND_SYNTAX;
614 mmd_lock();
615 mmd->events++;
616 mmd->new_vss_status_flags |= VSS_NEXT;
617 mmd_unlock();
618 return 1;
619 }
620
621 /* nomore */
622 int com_nomore(__a_unused int socket_fd, int argc, __a_unused char **argv)
623 {
624 if (argc != 1)
625 return -E_COMMAND_SYNTAX;
626 mmd_lock();
627 if (vss_playing() || vss_paused())
628 mmd->new_vss_status_flags |= VSS_NOMORE;
629 mmd_unlock();
630 return 1;
631 }
632
633 /* ff */
634 int com_ff(__a_unused int socket_fd, int argc, char **argv)
635 {
636 long promille;
637 int ret, backwards = 0;
638 unsigned i;
639 char c;
640
641 if (argc != 2)
642 return -E_COMMAND_SYNTAX;
643 if (!(ret = sscanf(argv[1], "%u%c", &i, &c)))
644 return -E_COMMAND_SYNTAX;
645 if (ret > 1 && c == '-')
646 backwards = 1; /* jmp backwards */
647 mmd_lock();
648 ret = -E_NO_AUDIO_FILE;
649 if (!mmd->chunks_total || !mmd->seconds_total)
650 goto out;
651 promille = (1000 * mmd->current_chunk) / mmd->chunks_total;
652 if (backwards)
653 promille -= 1000 * i / mmd->seconds_total;
654 else
655 promille += 1000 * i / mmd->seconds_total;
656 if (promille < 0)
657 promille = 0;
658 if (promille > 1000) {
659 mmd->new_vss_status_flags |= VSS_NEXT;
660 goto out;
661 }
662 mmd->repos_request = (mmd->chunks_total * promille) / 1000;
663 mmd->new_vss_status_flags |= VSS_REPOS;
664 mmd->new_vss_status_flags &= ~VSS_NEXT;
665 mmd->events++;
666 ret = 1;
667 out:
668 mmd_unlock();
669 return ret;
670 }
671
672 /* jmp */
673 int com_jmp(__a_unused int socket_fd, int argc, char **argv)
674 {
675 long unsigned int i;
676 int ret;
677
678 if (argc != 2)
679 return -E_COMMAND_SYNTAX;
680 if (sscanf(argv[1], "%lu", &i) <= 0)
681 return -E_COMMAND_SYNTAX;
682 mmd_lock();
683 ret = -E_NO_AUDIO_FILE;
684 if (!mmd->chunks_total)
685 goto out;
686 if (i > 100)
687 i = 100;
688 PARA_INFO_LOG("jumping to %lu%%\n", i);
689 mmd->repos_request = (mmd->chunks_total * i + 50)/ 100;
690 PARA_INFO_LOG("sent: %lu, offset before jmp: %lu\n",
691 mmd->chunks_sent, mmd->offset);
692 mmd->new_vss_status_flags |= VSS_REPOS;
693 mmd->new_vss_status_flags &= ~VSS_NEXT;
694 ret = 1;
695 mmd->events++;
696 out:
697 mmd_unlock();
698 return ret;
699 }
700
701 /*
702 * check if perms are sufficient to exec a command having perms cmd_perms.
703 * Returns 0 if perms are sufficient, -E_PERM otherwise.
704 */
705 static int check_perms(unsigned int perms, struct server_command *cmd_ptr)
706 {
707 PARA_DEBUG_LOG("%s", "checking permissions\n");
708 return (cmd_ptr->perms & perms) < cmd_ptr->perms ? -E_PERM : 0;
709 }
710
711 /*
712 * Parse first string from *cmd and lookup in table of valid commands.
713 * On error, NULL is returned.
714 */
715 static struct server_command *parse_cmd(const char *cmdstr)
716 {
717 char buf[255];
718 int n = 0;
719
720 sscanf(cmdstr, "%200s%n", buf, &n);
721 if (!n)
722 return NULL;
723 buf[n] = '\0';
724 return get_cmd_ptr(buf, NULL);
725 }
726
727 static long int para_rand(long unsigned max)
728 {
729 return (long int) ((max + 0.0) * (random() / (RAND_MAX + 1.0)));
730 }
731
732 static void init_rc4_keys(void)
733 {
734 int i;
735
736 for (i = 0; i < 2 * RC4_KEY_LEN; i++)
737 rc4_buf[i] = para_rand(256);
738 PARA_DEBUG_LOG("rc4 keys initialized (%u:%u)\n",
739 (unsigned char) rc4_buf[0],
740 (unsigned char) rc4_buf[RC4_KEY_LEN]);
741 RC4_set_key(&rc4_recv_key, RC4_KEY_LEN, rc4_buf);
742 RC4_set_key(&rc4_send_key, RC4_KEY_LEN, rc4_buf + RC4_KEY_LEN);
743 }
744
745 static void rc4_recv(unsigned long len, const unsigned char *indata,
746 unsigned char *outdata, __a_unused void *private_data)
747 {
748 RC4(&rc4_recv_key, len, indata, outdata);
749 }
750
751 static void rc4_send(unsigned long len, const unsigned char *indata,
752 unsigned char *outdata, __a_unused void *private_data)
753 {
754 RC4(&rc4_send_key, len, indata, outdata);
755 }
756
757 /**
758 * perform user authentication and execute a command
759 *
760 * \param fd the file descriptor to send output to
761 * \param addr socket address info of peer
762 *
763 * \return EXIT_SUCCESS or EXIT_FAILURE
764 *
765 * Whenever para_server accepts an incoming tcp connection on
766 * the port it listens on, it forks and the resulting child
767 * calls this function.
768 *
769 * An RSA-based challenge/response is used to authenticate
770 * the peer. It that authentication succeeds, a random RC4
771 * session key is generated and sent back to the peer,
772 * encrypted with its RSA public key. From this point on,
773 * all transfers are crypted with this session key.
774 *
775 * Next it is checked if the peer supplied a valid server
776 * command or a command for the audio file selector currently
777 * in use. If yes, and if the user has sufficient
778 * permissions to execute that command, the function calls
779 * the corresponding command handler which does argument
780 * checking and further processing.
781 *
782 * In order to cope with a DOS attacks, a timeout is set up
783 * which terminates the function if the connection was not
784 * authenticated when the timeout expires.
785 *
786 * \sa alarm(2), rc4(3), crypt.c, crypt.h
787 */
788 int handle_connect(int fd, struct sockaddr_in *addr)
789 {
790 int numbytes, ret, argc, use_rc4 = 0;
791 char buf[STRINGSIZE];
792 unsigned char crypt_buf[MAXLINE];
793 struct user u;
794 struct server_command *cmd = NULL;
795 long unsigned challenge_nr, chall_response;
796 char **argv = NULL;
797 char *p, *command = NULL;
798
799 signal(SIGCHLD, SIG_IGN);
800 signal(SIGINT, SIG_DFL);
801 signal(SIGTERM, SIG_DFL);
802 signal(SIGHUP, SIG_DFL);
803 signal(SIGUSR1, SIG_IGN);
804
805 challenge_nr = random();
806 /* send Welcome message */
807 ret = send_va_buffer(fd, "This is para_server, version "
808 PACKAGE_VERSION ".\n" );
809 if (ret < 0)
810 goto err_out;
811 /* recv auth request line */
812 ret = recv_buffer(fd, buf, sizeof(buf));
813 if (ret < 0)
814 goto err_out;
815 if (ret <= 6) {
816 ret = -E_AUTH;
817 goto err_out;
818 }
819 numbytes = ret;
820 ret = -E_AUTH;
821 if (strncmp(buf, "auth ", 5))
822 goto err_out;
823
824 if (numbytes < 9 || strncmp(buf, "auth rc4 ", 9))
825 u.name = para_strdup(buf + 5); /* client version < 0.2.6 */
826 else {
827 u.name = para_strdup(buf + 9); /* client version >= 0.2.6 */
828 use_rc4 = 1;
829 }
830 PARA_DEBUG_LOG("received %s request for user %s\n",
831 use_rc4? "rc4" : "auth", u.name);
832 if ((ret = lookup_user(&u)) < 0)
833 goto err_out;
834 ret = para_encrypt_challenge(u.rsa, challenge_nr, crypt_buf);
835 if (ret <= 0)
836 goto err_out;
837 numbytes = ret;
838 PARA_DEBUG_LOG("sending %d byte challenge\n", numbytes);
839 /* We can't use send_buffer here since buf may contain null bytes */
840 ret = send_bin_buffer(fd,(char *) crypt_buf, numbytes);
841 if (ret < 0)
842 goto err_out;
843 /* recv decrypted number */
844 numbytes = recv_buffer(fd, buf, sizeof(buf));
845 ret = numbytes;
846 if (ret < 0)
847 goto err_out;
848 ret = -E_AUTH;
849 if (!numbytes)
850 goto err_out;
851 if (sscanf(buf, CHALLENGE_RESPONSE_MSG "%lu", &chall_response) < 1
852 || chall_response != challenge_nr)
853 goto err_out;
854 /* auth successful. Send 'Proceed' message */
855 PARA_INFO_LOG("good auth for %s (%lu)\n", u.name, challenge_nr);
856 sprintf(buf, "%s", PROCEED_MSG);
857 if (use_rc4) {
858 init_rc4_keys();
859 ret = para_encrypt_buffer(u.rsa, rc4_buf, 2 * RC4_KEY_LEN,
860 (unsigned char *)buf + PROCEED_MSG_LEN + 1);
861 if (ret <= 0)
862 goto err_out;
863 numbytes = ret + strlen(PROCEED_MSG) + 1;
864 } else
865 numbytes = strlen(buf);
866 ret = send_bin_buffer(fd, buf, numbytes);
867 if (ret < 0)
868 goto err_out;
869 if (use_rc4)
870 enable_crypt(fd, rc4_recv, rc4_send, NULL);
871 /* read command */
872 while ((numbytes = recv_buffer(fd, buf, sizeof(buf))) > 0) {
873 // PARA_INFO_LOG("recvd: %s (%d)\n", buf, numbytes);
874 ret = -E_COMMAND_SYNTAX;
875 if (command && numbytes + strlen(command) > STRINGSIZE) /* DOS */
876 goto err_out;
877 command = para_strcat(command, buf);
878 if ((p = strstr(command, EOC_MSG))) {
879 *p = '\0';
880 break;
881 }
882 }
883 ret = numbytes;
884 if (ret < 0)
885 goto err_out;
886 ret = -E_BAD_CMD;
887 /* parse command */
888 if (!(cmd = parse_cmd(command)))
889 goto err_out;
890 /* valid command, check permissions */
891 ret = check_perms(u.perms, cmd);
892 if (ret < 0)
893 goto err_out;
894 /* valid command and sufficient perms */
895 alarm(0);
896 argc = split_args(command, &argv, "\n");
897 mmd_lock();
898 mmd->num_commands++;
899 mmd_unlock();
900 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cmd->name, u.name,
901 inet_ntoa(addr->sin_addr));
902 ret = cmd->handler(fd, argc, argv);
903 if (ret >= 0) {
904 ret = EXIT_SUCCESS;
905 goto out;
906 }
907 err_out:
908 if (ret != -E_SEND && ret != -E_RECV) {
909 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-ret));
910 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
911 }
912 ret = EXIT_FAILURE;
913 out:
914 free(command);
915 free(argv);
916 mmd_lock();
917 if (cmd && (cmd->perms & DB_WRITE) && ret >= 0)
918 mmd->events++;
919 mmd->active_connections--;
920 mmd_unlock();
921 return ret;
922 }