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