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