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