gui: Make some functions return void.
[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 command_context *cc, 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 clang.
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 command_context *cc)
197 {
198 int i, ret;
199 char *msg = NULL;
200 struct sender_command_data scd;
201
202 if (cc->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(&cc->scc, msg);
210 free(msg);
211 return ret;
212 }
213 ret = check_sender_args(cc->argc, cc->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(&cc->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(cc->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 command_context *cc)
248 {
249 int i, ret;
250 char *ut;
251 char *sender_info = NULL;
252
253 if (cc->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(&cc->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 command_context *cc)
288 {
289 if (cc->argc != 1)
290 return -E_COMMAND_SYNTAX;
291 return sc_send_buffer(&cc->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 command_context *cc)
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 < cc->argc; i++) {
364 const char *arg = cc->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 != cc->argc)
384 return -E_COMMAND_SYNTAX;
385 for (;;) {
386 mmd_dup(nmmd);
387 s = get_status(nmmd, parser_friendly);
388 ret = sc_send_buffer(&cc->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(&cc->scc, esi);
397 if (ret < 0)
398 goto out;
399 } else
400 send_afs_status(cc, 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 command_context *cc)
453 {
454 struct server_command *cmd;
455 char *perms, *handler;
456 int ret;
457
458 if (cc->argc < 2) {
459 /* no argument given, print list of commands */
460 if ((ret = send_list_of_commands(&cc->scc, server_cmds, "server")) < 0)
461 return ret;
462 return send_list_of_commands(&cc->scc, afs_cmds, "afs");
463 }
464 /* argument given for help */
465 cmd = get_cmd_ptr(cc->argv[1], &handler);
466 if (!cmd)
467 return -E_BAD_CMD;
468 perms = cmd_perms_itohuman(cmd->perms);
469 ret = sc_send_va_buffer(&cc->scc,
470 "%s - %s\n\n"
471 "handler: %s\n"
472 "permissions: %s\n"
473 "usage: %s\n\n"
474 "%s\n",
475 cc->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(struct command_context *cc)
489 {
490 if (cc->argc != 1)
491 return -E_COMMAND_SYNTAX;
492 kill(getppid(), SIGHUP);
493 return 1;
494 }
495
496 /* term */
497 int com_term(struct command_context *cc)
498 {
499 if (cc->argc != 1)
500 return -E_COMMAND_SYNTAX;
501 kill(getppid(), SIGTERM);
502 return 1;
503 }
504
505 int com_play(struct command_context *cc)
506 {
507 if (cc->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 /* stop */
517 int com_stop(struct command_context *cc)
518 {
519 if (cc->argc != 1)
520 return -E_COMMAND_SYNTAX;
521 mutex_lock(mmd_mutex);
522 mmd->new_vss_status_flags &= ~VSS_PLAYING;
523 mmd->new_vss_status_flags &= ~VSS_REPOS;
524 mmd->new_vss_status_flags |= VSS_NEXT;
525 mutex_unlock(mmd_mutex);
526 return 1;
527 }
528
529 /* pause */
530 int com_pause(struct command_context *cc)
531 {
532 if (cc->argc != 1)
533 return -E_COMMAND_SYNTAX;
534 mutex_lock(mmd_mutex);
535 if (!vss_paused() && !vss_stopped()) {
536 mmd->events++;
537 mmd->new_vss_status_flags &= ~VSS_PLAYING;
538 mmd->new_vss_status_flags &= ~VSS_NEXT;
539 }
540 mutex_unlock(mmd_mutex);
541 return 1;
542 }
543
544 /* next */
545 int com_next(struct command_context *cc)
546 {
547 if (cc->argc != 1)
548 return -E_COMMAND_SYNTAX;
549 mutex_lock(mmd_mutex);
550 mmd->events++;
551 mmd->new_vss_status_flags |= VSS_NEXT;
552 mutex_unlock(mmd_mutex);
553 return 1;
554 }
555
556 /* nomore */
557 int com_nomore(struct command_context *cc)
558 {
559 if (cc->argc != 1)
560 return -E_COMMAND_SYNTAX;
561 mutex_lock(mmd_mutex);
562 if (vss_playing() || vss_paused())
563 mmd->new_vss_status_flags |= VSS_NOMORE;
564 mutex_unlock(mmd_mutex);
565 return 1;
566 }
567
568 /* ff */
569 int com_ff(struct command_context *cc)
570 {
571 long promille;
572 int ret, backwards = 0;
573 unsigned i;
574 char c;
575
576 if (cc->argc != 2)
577 return -E_COMMAND_SYNTAX;
578 if (!(ret = sscanf(cc->argv[1], "%u%c", &i, &c)))
579 return -E_COMMAND_SYNTAX;
580 if (ret > 1 && c == '-')
581 backwards = 1; /* jmp backwards */
582 mutex_lock(mmd_mutex);
583 ret = -E_NO_AUDIO_FILE;
584 if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
585 goto out;
586 promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
587 if (backwards)
588 promille -= 1000 * i / mmd->afd.afhi.seconds_total;
589 else
590 promille += 1000 * i / mmd->afd.afhi.seconds_total;
591 if (promille < 0)
592 promille = 0;
593 if (promille > 1000) {
594 mmd->new_vss_status_flags |= VSS_NEXT;
595 goto out;
596 }
597 mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
598 mmd->new_vss_status_flags |= VSS_REPOS;
599 mmd->new_vss_status_flags &= ~VSS_NEXT;
600 mmd->events++;
601 ret = 1;
602 out:
603 mutex_unlock(mmd_mutex);
604 return ret;
605 }
606
607 /* jmp */
608 int com_jmp(struct command_context *cc)
609 {
610 long unsigned int i;
611 int ret;
612
613 if (cc->argc != 2)
614 return -E_COMMAND_SYNTAX;
615 if (sscanf(cc->argv[1], "%lu", &i) <= 0)
616 return -E_COMMAND_SYNTAX;
617 mutex_lock(mmd_mutex);
618 ret = -E_NO_AUDIO_FILE;
619 if (!mmd->afd.afhi.chunks_total)
620 goto out;
621 if (i > 100)
622 i = 100;
623 PARA_INFO_LOG("jumping to %lu%%\n", i);
624 mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50)/ 100;
625 PARA_INFO_LOG("sent: %lu, offset before jmp: %lu\n",
626 mmd->chunks_sent, mmd->offset);
627 mmd->new_vss_status_flags |= VSS_REPOS;
628 mmd->new_vss_status_flags &= ~VSS_NEXT;
629 ret = 1;
630 mmd->events++;
631 out:
632 mutex_unlock(mmd_mutex);
633 return ret;
634 }
635
636 /*
637 * check if perms are sufficient to exec a command having perms cmd_perms.
638 * Returns 0 if perms are sufficient, -E_PERM otherwise.
639 */
640 static int check_perms(unsigned int perms, struct server_command *cmd_ptr)
641 {
642 PARA_DEBUG_LOG("checking permissions\n");
643 return (cmd_ptr->perms & perms) < cmd_ptr->perms ? -E_PERM : 0;
644 }
645
646 /*
647 * Parse first string from *cmd and lookup in table of valid commands.
648 * On error, NULL is returned.
649 */
650 static struct server_command *parse_cmd(const char *cmdstr)
651 {
652 char buf[255];
653 int n = 0;
654
655 sscanf(cmdstr, "%200s%n", buf, &n);
656 if (!n)
657 return NULL;
658 buf[n] = '\0';
659 return get_cmd_ptr(buf, NULL);
660 }
661
662 static int read_command(struct stream_cipher_context *scc, char **result)
663 {
664 int ret;
665 char buf[4096];
666 char *command = NULL;
667
668 for (;;) {
669 size_t numbytes;
670 char *p;
671
672 ret = sc_recv_buffer(scc, buf, sizeof(buf));
673 if (ret < 0)
674 goto out;
675 if (!ret)
676 break;
677 numbytes = ret;
678 ret = -E_COMMAND_SYNTAX;
679 if (command && numbytes + strlen(command) > MAX_COMMAND_LEN) /* DOS */
680 goto out;
681 command = para_strcat(command, buf);
682 p = strstr(command, EOC_MSG);
683 if (p) {
684 *p = '\0';
685 break;
686 }
687 }
688 ret = command? 1 : -E_COMMAND_SYNTAX;
689 out:
690 if (ret < 0)
691 free(command);
692 else
693 *result = command;
694 return ret;
695
696 }
697
698 static void reset_signals(void)
699 {
700 para_sigaction(SIGCHLD, SIG_IGN);
701 para_sigaction(SIGINT, SIG_DFL);
702 para_sigaction(SIGTERM, SIG_DFL);
703 para_sigaction(SIGHUP, SIG_DFL);
704 }
705
706 /**
707 * Perform user authentication and execute a command.
708 *
709 * \param fd The file descriptor to send output to.
710 * \param peername Identifies the connecting peer.
711 *
712 * Whenever para_server accepts an incoming tcp connection on
713 * the port it listens on, it forks and the resulting child
714 * calls this function.
715 *
716 * An RSA-based challenge/response is used to authenticate
717 * the peer. It that authentication succeeds, a random
718 * session key is generated and sent back to the peer,
719 * encrypted with its RSA public key. From this point on,
720 * all transfers are crypted with this session key.
721 *
722 * Next it is checked if the peer supplied a valid server command or a command
723 * for the audio file selector. If yes, and if the user has sufficient
724 * permissions to execute that command, the function calls the corresponding
725 * command handler which does argument checking and further processing.
726 *
727 * In order to cope with a DOS attacks, a timeout is set up
728 * which terminates the function if the connection was not
729 * authenticated when the timeout expires.
730 *
731 * \sa alarm(2), crypt.c, crypt.h
732 */
733 __noreturn void handle_connect(int fd, const char *peername)
734 {
735 int ret;
736 char buf[4096];
737 unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
738 unsigned char challenge_hash[HASH_SIZE];
739 char *p, *command = NULL;
740 size_t numbytes;
741 struct command_context cc_struct = {.peer = peername}, *cc = &cc_struct;
742
743 cc->scc.fd = fd;
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 net_err;
749 /* send Welcome message */
750 ret = write_va_buffer(fd, "This is para_server, version "
751 PACKAGE_VERSION ".\n" );
752 if (ret < 0)
753 goto net_err;
754 /* recv auth request line */
755 ret = recv_buffer(fd, buf, sizeof(buf));
756 if (ret < 0)
757 goto net_err;
758 if (ret < 10) {
759 ret = -E_AUTH_REQUEST;
760 goto net_err;
761 }
762 ret = -E_AUTH_REQUEST;
763 if (strncmp(buf, AUTH_REQUEST_MSG, strlen(AUTH_REQUEST_MSG)))
764 goto net_err;
765 p = buf + strlen(AUTH_REQUEST_MSG);
766 PARA_DEBUG_LOG("received auth request for user %s\n", p);
767 cc->u = lookup_user(p);
768 if (cc->u) {
769 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
770 ret = pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
771 (unsigned char *)buf);
772 if (ret < 0)
773 goto net_err;
774 numbytes = ret;
775 } else {
776 /*
777 * We don't want to reveal our user names, so we send a
778 * challenge to the client even if the user does not exist, and
779 * fail the authentication later.
780 */
781 numbytes = 256;
782 get_random_bytes_or_die((unsigned char *)buf, numbytes);
783 }
784 PARA_DEBUG_LOG("sending %u byte challenge + rc4 keys (%zu bytes)\n",
785 CHALLENGE_SIZE, numbytes);
786 ret = write_all(fd, buf, numbytes);
787 if (ret < 0)
788 goto net_err;
789 /* recv challenge response */
790 ret = recv_bin_buffer(fd, buf, HASH_SIZE);
791 if (ret < 0)
792 goto net_err;
793 numbytes = ret;
794 PARA_DEBUG_LOG("received %d bytes challenge response\n", ret);
795 ret = -E_BAD_USER;
796 if (!cc->u)
797 goto net_err;
798 /*
799 * The correct response is the hash of the first CHALLENGE_SIZE bytes
800 * of the random data.
801 */
802 ret = -E_BAD_AUTH;
803 if (numbytes != HASH_SIZE)
804 goto net_err;
805 hash_function((char *)rand_buf, CHALLENGE_SIZE, challenge_hash);
806 if (memcmp(challenge_hash, buf, HASH_SIZE))
807 goto net_err;
808 /* auth successful */
809 alarm(0);
810 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
811 /* init stream cipher keys with the second part of the random buffer */
812 cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
813 cc->scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN, SESSION_KEY_LEN);
814 ret = sc_send_buffer(&cc->scc, PROCEED_MSG);
815 if (ret < 0)
816 goto net_err;
817 ret = read_command(&cc->scc, &command);
818 if (ret == -E_COMMAND_SYNTAX)
819 goto err_out;
820 if (ret < 0)
821 goto net_err;
822 ret = -E_BAD_CMD;
823 cc->cmd = parse_cmd(command);
824 if (!cc->cmd)
825 goto err_out;
826 /* valid command, check permissions */
827 ret = check_perms(cc->u->perms, cc->cmd);
828 if (ret < 0)
829 goto err_out;
830 /* valid command and sufficient perms */
831 ret = create_argv(command, "\n", &cc->argv);
832 if (ret < 0)
833 goto err_out;
834 cc->argc = ret;
835 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", cc->cmd->name,
836 cc->u->name, peername);
837 ret = cc->cmd->handler(cc);
838 free_argv(cc->argv);
839 mutex_lock(mmd_mutex);
840 mmd->num_commands++;
841 mutex_unlock(mmd_mutex);
842 if (ret >= 0)
843 goto out;
844 err_out:
845 sc_send_va_buffer(&cc->scc, "%s\n", para_strerror(-ret));
846 net_err:
847 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
848 out:
849 free(command);
850 sc_free(cc->scc.recv);
851 sc_free(cc->scc.send);
852 mutex_lock(mmd_mutex);
853 if (cc->cmd && (cc->cmd->perms & AFS_WRITE) && ret >= 0)
854 mmd->events++;
855 mmd->active_connections--;
856 mutex_unlock(mmd_mutex);
857 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
858 }