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