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