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