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