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