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