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