command.c: add documentation of handle_connect()
[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 struct sockaddr_in *in_addr;
47
48 static void dummy(__a_unused int s)
49 {}
50
51 static void mmd_dup(struct misc_meta_data *new_mmd)
52 {
53 mmd_lock();
54 *new_mmd = *mmd;
55 mmd_unlock();
56 }
57
58 /*
59 * compute human readable string containing
60 * vss status for given integer value
61 */
62 static char *vss_status_tohuman(unsigned int flags)
63 {
64 if (flags & VSS_PLAYING)
65 return para_strdup("playing");
66 else if (flags & VSS_NEXT)
67 return para_strdup("stopped");
68 else
69 return para_strdup("paused");
70 }
71
72 /*
73 * return human readable permission string. Never returns NULL.
74 */
75 static char *cmd_perms_itohuman(unsigned int perms)
76 {
77 char *msg = para_malloc(5 * sizeof(char));
78
79 msg[0] = perms & DB_READ? 'a' : '-';
80 msg[1] = perms & DB_WRITE? 'A' : '-';
81 msg[2] = perms & VSS_READ? 'v' : '-';
82 msg[3] = perms & VSS_WRITE? 'V' : '-';
83 msg[4] = '\0';
84 return msg;
85 }
86
87 /*
88 * Never returns NULL.
89 */
90 static char *vss_get_status_flags(unsigned int flags)
91 {
92 char *msg = para_malloc(5 * sizeof(char));
93
94 msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
95 msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
96 msg[2] = (flags & VSS_NEXT)? 'N' : '_';
97 msg[3] = (flags & VSS_REPOS)? 'R' : '_';
98 msg[4] = '\0';
99 return msg;
100 }
101
102 /*
103 * compute status bar string. Never returns NULL
104 */
105 static char *get_sb_string(struct misc_meta_data *nmmd)
106 {
107 char *base, *ret;
108 long long unsigned secs = 0, rsecs = 0, percent = 0;
109
110 base = para_basename(nmmd->filename);
111 if (!base)
112 return para_strdup("");
113 if (!base[0])
114 return base;
115 if (nmmd->chunks_total) {
116 secs = (long long) nmmd->seconds_total * nmmd->chunks_sent
117 / nmmd->chunks_total;
118 rsecs = (long long) nmmd->seconds_total *
119 (nmmd->chunks_total - nmmd->chunks_sent)
120 / nmmd->chunks_total;
121 percent = 100 * ((nmmd->chunks_sent + 5) / 10)
122 / ((nmmd->chunks_total + 5) / 10);
123 }
124 ret = make_message("%llu:%02llu [%llu:%02llu] (%llu%%) %s",
125 secs / 60, secs % 60,
126 rsecs / 60, rsecs % 60,
127 percent,
128 base
129 );
130 free(base);
131 return ret;
132 }
133
134 static char *get_status(struct misc_meta_data *nmmd)
135 {
136 char *bar, *ret, mtime[30] = "";
137 char *status, *flags; /* vss status info */
138 char *ut = uptime_str();
139 long offset = (nmmd->offset + 500) / 1000;
140 struct timeval now;
141 struct tm mtime_tm;
142
143 if (nmmd->audio_format >= 0) {
144 localtime_r(&nmmd->mtime, &mtime_tm);
145 strftime(mtime, 29, "%a %b %d %Y", &mtime_tm);
146 }
147 /* report real status */
148 status = vss_status_tohuman(nmmd->vss_status_flags);
149 flags = vss_get_status_flags(nmmd->vss_status_flags);
150 bar = para_basename(nmmd->filename);
151 gettimeofday(&now, NULL);
152 ret = make_message(
153 "%s:%lu\n" "%s:%s\n" "%s:%i\n" "%s:%u\n"
154 "%s:%s\n" "%s:%s\n" "%s:%s\n" "%s:%s\n"
155 "%s:%li\n" "%s:%s\n" "%s" "%s"
156 "%s:%s\n" "%s:%lu.%lu\n" "%s:%lu.%lu\n",
157 status_item_list[SI_FILE_SIZE], nmmd->size / 1024,
158 status_item_list[SI_MTIME], mtime,
159 status_item_list[SI_LENGTH], nmmd->seconds_total,
160 status_item_list[SI_NUM_PLAYED], nmmd->num_played,
161
162 status_item_list[SI_STATUS_BAR], bar ? bar : "(none)",
163 status_item_list[SI_STATUS], status,
164 status_item_list[SI_STATUS_FLAGS], flags,
165 status_item_list[SI_SELECTOR], selectors[nmmd->selector_num].name,
166
167 status_item_list[SI_OFFSET], offset,
168 status_item_list[SI_FORMAT], audio_format_name(nmmd->audio_format),
169 nmmd->selector_info,
170 nmmd->audio_file_info,
171
172 status_item_list[SI_UPTIME], ut,
173 status_item_list[SI_STREAM_START],
174 (long unsigned)nmmd->stream_start.tv_sec,
175 (long unsigned)nmmd->stream_start.tv_usec,
176 status_item_list[SI_CURRENT_TIME],
177 (long unsigned)now.tv_sec,
178 (long unsigned)now.tv_usec
179
180 );
181 free(bar);
182 free(flags);
183 free(status);
184 free(ut);
185 return ret;
186 }
187
188 static int check_sender_args(int argc, char **argv, struct sender_command_data *scd)
189 {
190 int i;
191 /* this has to match sender.h */
192 const char *subcmds[] = {"add", "delete", "allow", "deny", "on", "off", NULL};
193
194 scd->sender_num = -1;
195 if (argc < 2)
196 return -E_COMMAND_SYNTAX;
197 for (i = 0; senders[i].name; i++)
198 if (!strcmp(senders[i].name, argv[1]))
199 break;
200 PARA_DEBUG_LOG("%d:%s\n", argc, argv[1]);
201 if (!senders[i].name)
202 return -E_COMMAND_SYNTAX;
203 scd->sender_num = i;
204 for (i = 0; subcmds[i]; i++)
205 if (!strcmp(subcmds[i], argv[2]))
206 break;
207 if (!subcmds[i])
208 return -E_COMMAND_SYNTAX;
209 scd->cmd_num = i;
210 mmd_lock();
211 if (!senders[scd->sender_num].client_cmds[scd->cmd_num]) {
212 mmd_unlock();
213 return -E_SENDER_CMD;
214 }
215 mmd_unlock();
216 switch (scd->cmd_num) {
217 case SENDER_ON:
218 case SENDER_OFF:
219 if (argc != 3)
220 return -E_COMMAND_SYNTAX;
221 break;
222 case SENDER_DENY:
223 case SENDER_ALLOW:
224 if (argc != 4 && argc != 5)
225 return -E_COMMAND_SYNTAX;
226 if (!inet_aton(argv[3], &scd->addr))
227 return -E_COMMAND_SYNTAX;
228 scd->netmask = 32;
229 if (argc == 5) {
230 scd->netmask = atoi(argv[4]);
231 if (scd->netmask < 0 || scd->netmask > 32)
232 return -E_COMMAND_SYNTAX;
233 }
234 break;
235 case SENDER_ADD:
236 case SENDER_DELETE:
237 if (argc != 4 && argc != 5)
238 return -E_COMMAND_SYNTAX;
239 if (!inet_aton(argv[3], &scd->addr))
240 return -E_COMMAND_SYNTAX;
241 scd->port = -1;
242 if (argc == 5) {
243 scd->port = atoi(argv[4]);
244 if (scd->port < 0 || scd->port > 65535)
245 return -E_COMMAND_SYNTAX;
246 }
247 break;
248 default:
249 return -E_COMMAND_SYNTAX;
250 }
251 return 1;
252 }
253
254 int com_sender(int fd, int argc, char **argv)
255 {
256 int i, ret;
257 struct sender_command_data scd;
258
259 if (argc < 2) {
260 char *msg = NULL;
261 for (i = 0; senders[i].name; i++) {
262 char *tmp = make_message("%s%s\n",
263 msg? msg : "", senders[i].name);
264 free(msg);
265 msg = tmp;
266 }
267 ret = send_buffer(fd, msg);
268 free(msg);
269 return ret;
270 }
271 ret = check_sender_args(argc, argv, &scd);
272 if (ret < 0) {
273 char *msg;
274 if (scd.sender_num < 0)
275 return ret;
276 msg = senders[scd.sender_num].help();
277 send_buffer(fd, msg);
278 free(msg);
279 return 1;
280 }
281 for (i = 0; i < 10; i++) {
282 mmd_lock();
283 if (mmd->sender_cmd_data.cmd_num >= 0) {
284 mmd_unlock();
285 usleep(100 * 1000);
286 continue;
287 }
288 mmd->sender_cmd_data = scd;
289 mmd_unlock();
290 break;
291 }
292 return (i < 10)? 1 : -E_LOCK;
293 }
294
295 /* server info */
296 int com_si(int fd, int argc, __a_unused char **argv)
297 {
298 int i, ret;
299 char *ut;
300 char *selector_string = NULL, *sender_info = NULL, *sender_list = NULL;
301
302 if (argc != 1)
303 return -E_COMMAND_SYNTAX;
304 mmd_lock();
305 for (i = 0; selectors[i].name; i++) {
306 selector_string = para_strcat(selector_string, selectors[i].name);
307 selector_string = para_strcat(selector_string, " ");
308 }
309 for (i = 0; senders[i].name; i++) {
310 char *info = senders[i].info();
311 sender_info = para_strcat(sender_info, info);
312 free(info);
313 sender_list = para_strcat(sender_list, senders[i].name);
314 sender_list = para_strcat(sender_list, " ");
315 }
316 ut = uptime_str();
317 ret = send_va_buffer(fd, "up: %s\nplayed: %u\n"
318 "pid: %d\n"
319 "connections (active/accepted/total): %u/%u/%u\n"
320 "current loglevel: %i\n"
321 "supported audio file selectors: %s\n"
322 "supported audio formats: %s\n"
323 "supported senders: %s\n"
324 "%s",
325 ut, mmd->num_played,
326 getppid(),
327 mmd->active_connections,
328 mmd->num_commands,
329 mmd->num_connects,
330 conf.loglevel_arg,
331 selector_string,
332 supported_audio_formats(),
333 sender_list,
334 sender_info
335 );
336 mmd_unlock();
337 free(ut);
338 free(selector_string);
339 free(sender_list);
340 free(sender_info);
341 return ret;
342 }
343
344 /* version */
345 int com_version(int socket_fd, int argc, __a_unused char **argv)
346 {
347 if (argc != 1)
348 return -E_COMMAND_SYNTAX;
349 return send_buffer(socket_fd, "para_server-" PACKAGE_VERSION ", \""
350 CODENAME "\"\n"
351 COPYRIGHT "\n"
352 "built: " BUILD_DATE "\n"
353 SYSTEM ", " CC_VERSION "\n"
354 );
355 }
356
357 /* sc */
358 int com_sc(int socket_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(socket_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 socket_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(socket_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 socket_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(socket_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 socket_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 socket_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 socket_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 socket_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 socket_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 socket_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 socket_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 socket_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 socket_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[STRINGSIZE];
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 in_addr = addr;
809 challenge_nr = random();
810 /* send Welcome message */
811 ret = send_va_buffer(fd, "This is para_server, version "
812 PACKAGE_VERSION ".\n" );
813 if (ret < 0)
814 goto err_out;
815 /* recv auth request line */
816 ret = recv_buffer(fd, buf, sizeof(buf));
817 if (ret < 0)
818 goto err_out;
819 if (ret <= 6) {
820 ret = -E_AUTH;
821 goto err_out;
822 }
823 numbytes = ret;
824 ret = -E_AUTH;
825 if (strncmp(buf, "auth ", 5))
826 goto err_out;
827
828 if (numbytes < 9 || strncmp(buf, "auth rc4 ", 9))
829 u.name = para_strdup(buf + 5); /* client version < 0.2.6 */
830 else {
831 u.name = para_strdup(buf + 9); /* client version >= 0.2.6 */
832 use_rc4 = 1;
833 }
834 PARA_DEBUG_LOG("received %s request for user %s\n",
835 use_rc4? "rc4" : "auth", u.name);
836 if ((ret = lookup_user(&u)) < 0)
837 goto err_out;
838 ret = para_encrypt_challenge(u.rsa, challenge_nr, crypt_buf);
839 if (ret <= 0)
840 goto err_out;
841 numbytes = ret;
842 PARA_DEBUG_LOG("sending %d byte challenge\n", numbytes);
843 /* We can't use send_buffer here since buf may contain null bytes */
844 ret = send_bin_buffer(fd,(char *) crypt_buf, numbytes);
845 if (ret < 0)
846 goto err_out;
847 /* recv decrypted number */
848 numbytes = recv_buffer(fd, buf, sizeof(buf));
849 ret = numbytes;
850 if (ret < 0)
851 goto err_out;
852 ret = -E_AUTH;
853 if (!numbytes)
854 goto err_out;
855 if (sscanf(buf, CHALLENGE_RESPONSE_MSG "%lu", &chall_response) < 1
856 || chall_response != challenge_nr)
857 goto err_out;
858 /* auth successful. Send 'Proceed' message */
859 PARA_INFO_LOG("good auth for %s (%lu)\n", u.name, challenge_nr);
860 sprintf(buf, "%s", PROCEED_MSG);
861 if (use_rc4) {
862 init_rc4_keys();
863 ret = para_encrypt_buffer(u.rsa, rc4_buf, 2 * RC4_KEY_LEN,
864 (unsigned char *)buf + PROCEED_MSG_LEN + 1);
865 if (ret <= 0)
866 goto err_out;
867 numbytes = ret + strlen(PROCEED_MSG) + 1;
868 } else
869 numbytes = strlen(buf);
870 ret = send_bin_buffer(fd, buf, numbytes);
871 if (ret < 0)
872 goto err_out;
873 if (use_rc4)
874 enable_crypt(fd, rc4_recv, rc4_send, NULL);
875 /* read command */
876 while ((numbytes = recv_buffer(fd, buf, sizeof(buf))) > 0) {
877 // PARA_INFO_LOG("recvd: %s (%d)\n", buf, numbytes);
878 ret = -E_COMMAND_SYNTAX;
879 if (command && numbytes + strlen(command) > STRINGSIZE) /* DOS */
880 goto err_out;
881 command = para_strcat(command, buf);
882 if ((p = strstr(command, EOC_MSG))) {
883 *p = '\0';
884 break;
885 }
886 }
887 ret = numbytes;
888 if (ret < 0)
889 goto err_out;
890 ret = -E_BAD_CMD;
891 /* parse command */
892 if (!(cmd = parse_cmd(command)))
893 goto err_out;
894 /* valid command, check permissions */
895 ret = check_perms(u.perms, cmd);
896 if (ret < 0)
897 goto err_out;
898 /* valid command and sufficient perms */
899 alarm(0);
900 argc = split_args(command, &argv, "\n");
901 mmd_lock();
902 mmd->num_commands++;
903 mmd_unlock();
904 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cmd->name, u.name,
905 inet_ntoa(addr->sin_addr));
906 ret = cmd->handler(fd, argc, argv);
907 if (ret >= 0) {
908 ret = EXIT_SUCCESS;
909 goto out;
910 }
911 err_out:
912 if (ret != -E_SEND && ret != -E_RECV) {
913 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-ret));
914 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
915 }
916 ret = EXIT_FAILURE;
917 out:
918 free(command);
919 free(argv);
920 mmd_lock();
921 if (cmd && (cmd->perms & DB_WRITE) && ret >= 0)
922 mmd->events++;
923 mmd->active_connections--;
924 mmd_unlock();
925 return ret;
926 }