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