server: Convert com_mvatt() to lopsub.
[paraslash.git] / command.c
1 /*
2 * Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>
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 <netinet/in.h>
10 #include <sys/socket.h>
11 #include <regex.h>
12 #include <signal.h>
13 #include <sys/types.h>
14 #include <osl.h>
15 #include <arpa/inet.h>
16 #include <sys/un.h>
17 #include <netdb.h>
18 #include <lopsub.h>
19
20 #include "para.h"
21 #include "error.h"
22 #include "crypt.h"
23 #include "sideband.h"
24 #include "command.h"
25 #include "server.cmdline.h"
26 #include "string.h"
27 #include "afh.h"
28 #include "afs.h"
29 #include "server.h"
30 #include "list.h"
31 #include "send.h"
32 #include "sched.h"
33 #include "vss.h"
34 #include "net.h"
35 #include "daemon.h"
36 #include "fd.h"
37 #include "ipc.h"
38 #include "server_cmd.lsg.h"
39 #include "user_list.h"
40 #include "afs.command_list.h"
41 #include "signal.h"
42 #include "version.h"
43
44 #define SERVER_CMD_AUX_INFO(_arg) _arg,
45 static const unsigned server_command_perms[] = {LSG_SERVER_CMD_AUX_INFOS};
46 #undef SERVER_CMD_AUX_INFO
47 #define SERVER_CMD_AUX_INFO(_arg) #_arg,
48 static const char * const server_command_perms_txt[] = {LSG_SERVER_CMD_AUX_INFOS};
49 #undef SERVER_CMD_AUX_INFO
50
51 typedef int server_command_handler_t(struct command_context *);
52 server_command_handler_t AFS_COMMAND_HANDLERS;
53
54 /* Defines one command of para_server. */
55 struct server_command {
56 /* The name of the command. */
57 const char *name;
58 /* Pointer to the function that handles the command. */
59 server_command_handler_t *handler;
60 /* The privileges a user must have to execute this command. */
61 unsigned int perms;
62 /* One-line description of the command. */
63 const char *description;
64 /* Summary of the command line options. */
65 const char *usage;
66 /* The long help text. */
67 const char *help;
68 };
69
70 static struct server_command afs_cmds[] = {DEFINE_AFS_CMD_ARRAY};
71
72 /** Commands including options must be shorter than this. */
73 #define MAX_COMMAND_LEN 32768
74
75 extern int mmd_mutex;
76 extern struct misc_meta_data *mmd;
77 extern struct sender senders[];
78 int send_afs_status(struct command_context *cc, int parser_friendly);
79
80 static void dummy(__a_unused int s)
81 {
82 }
83
84 /*
85 * Compute human readable vss status text.
86 *
87 * We can't call vss_playing() and friends here because those functions read
88 * the flags from the primary mmd structure, so calling them from command
89 * handler context would require to take the mmd lock. At the time the function
90 * is called we already took a copy of the mmd structure and want to use the
91 * flags value of the copy for computing the vss status text.
92 */
93 static char *vss_status_tohuman(unsigned int flags)
94 {
95 if (flags & VSS_PLAYING)
96 return para_strdup("playing");
97 if (flags & VSS_NEXT)
98 return para_strdup("stopped");
99 return para_strdup("paused");
100 }
101
102 /*
103 * Never returns NULL.
104 */
105 static char *vss_get_status_flags(unsigned int flags)
106 {
107 char *msg = para_malloc(5 * sizeof(char));
108
109 msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
110 msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
111 msg[2] = (flags & VSS_NEXT)? 'N' : '_';
112 msg[3] = (flags & VSS_REPOS)? 'R' : '_';
113 msg[4] = '\0';
114 return msg;
115 }
116
117 static unsigned get_status(struct misc_meta_data *nmmd, bool parser_friendly,
118 char **result)
119 {
120 char *status, *flags; /* vss status info */
121 /* nobody updates our version of "now" */
122 long offset = (nmmd->offset + 500) / 1000;
123 struct timeval current_time;
124 struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
125
126 /* report real status */
127 status = vss_status_tohuman(nmmd->vss_status_flags);
128 flags = vss_get_status_flags(nmmd->vss_status_flags);
129 clock_get_realtime(&current_time);
130 /*
131 * The calls to WRITE_STATUS_ITEM() below never fail because
132 * b->max_size is zero (unlimited), see para_printf(). However, clang
133 * is not smart enough to prove this and complains nevertheless.
134 * Casting the return value to void silences clang.
135 */
136 (void)WRITE_STATUS_ITEM(&b, SI_STATUS, "%s\n", status);
137 (void)WRITE_STATUS_ITEM(&b, SI_STATUS_FLAGS, "%s\n", flags);
138 (void)WRITE_STATUS_ITEM(&b, SI_OFFSET, "%li\n", offset);
139 (void)WRITE_STATUS_ITEM(&b, SI_AFS_MODE, "%s\n", mmd->afs_mode_string);
140 (void)WRITE_STATUS_ITEM(&b, SI_STREAM_START, "%lu.%lu\n",
141 (long unsigned)nmmd->stream_start.tv_sec,
142 (long unsigned)nmmd->stream_start.tv_usec);
143 (void)WRITE_STATUS_ITEM(&b, SI_CURRENT_TIME, "%lu.%lu\n",
144 (long unsigned)current_time.tv_sec,
145 (long unsigned)current_time.tv_usec);
146 free(flags);
147 free(status);
148 *result = b.buf;
149 return b.offset;
150 }
151
152 /**
153 * Send a sideband packet through a blocking file descriptor.
154 *
155 * \param scc fd and crypto keys.
156 * \param buf The buffer to send.
157 * \param numbytes The size of \a buf.
158 * \param band The sideband designator of this packet.
159 * \param dont_free If true, never deallocate \a buf.
160 *
161 * The nonblock flag must be disabled for the file descriptor given by \a scc.
162 *
163 * Stream cipher encryption is automatically activated if necessary via the
164 * sideband transformation, depending on the value of \a band.
165 *
166 * \return Standard.
167 *
168 * \sa \ref send_sb_va().
169 */
170 int send_sb(struct stream_cipher_context *scc, void *buf, size_t numbytes,
171 int band, bool dont_free)
172 {
173 int ret;
174 struct sb_context *sbc;
175 struct iovec iov[2];
176 sb_transformation trafo = band < SBD_PROCEED? NULL : sc_trafo;
177 struct sb_buffer sbb = SBB_INIT(band, buf, numbytes);
178
179 sbc = sb_new_send(&sbb, dont_free, trafo, scc->send);
180 do {
181 ret = sb_get_send_buffers(sbc, iov);
182 ret = xwritev(scc->fd, iov, ret);
183 if (ret < 0)
184 goto fail;
185 } while (sb_sent(sbc, ret) == false);
186 return 1;
187 fail:
188 sb_free(sbc);
189 return ret;
190 }
191
192 /**
193 * Create a variable sized buffer and send it as a sideband packet.
194 *
195 * \param scc Passed to \ref send_sb.
196 * \param band See \ref send_sb.
197 * \param fmt The format string.
198 *
199 * \return The return value of the underlying call to \ref send_sb.
200 */
201 __printf_3_4 int send_sb_va(struct stream_cipher_context *scc, int band,
202 const char *fmt, ...)
203 {
204 va_list ap;
205 char *msg;
206 int ret;
207
208 va_start(ap, fmt);
209 ret = xvasprintf(&msg, fmt, ap);
210 va_end(ap);
211 return send_sb(scc, msg, ret, band, false);
212 }
213
214 /**
215 * Send an error message to a client.
216 *
217 * \param cc Client info.
218 * \param err The (positive) error code.
219 *
220 * \return The return value of the underlying call to send_sb_va().
221 */
222 int send_strerror(struct command_context *cc, int err)
223 {
224 return send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", para_strerror(err));
225 }
226
227 /**
228 * Send an error context to a client,
229 *
230 * \param cc Client info.
231 * \param errctx The error context string.
232 *
233 * \return The return value of the underlying call to send_sb_va().
234 *
235 * This function frees the error context string after it was sent.
236 */
237 int send_errctx(struct command_context *cc, char *errctx)
238 {
239 int ret;
240
241 if (!errctx)
242 return 0;
243 ret = send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", errctx);
244 free(errctx);
245 return ret;
246 }
247
248 static int check_sender_args(struct command_context *cc,
249 struct lls_parse_result *lpr, struct sender_command_data *scd)
250 {
251 int i, ret;
252 const char *subcmds[] = {SENDER_SUBCOMMANDS};
253 const char *arg;
254 char *errctx;
255 unsigned num_inputs = lls_num_inputs(lpr);
256
257 scd->sender_num = -1;
258 ret = lls(lls_check_arg_count(lpr, 2, INT_MAX, &errctx));
259 if (ret < 0) {
260 send_errctx(cc, errctx);
261 return ret;
262 }
263 arg = lls_input(0, lpr);
264 for (i = 0; senders[i].name; i++)
265 if (!strcmp(senders[i].name, arg))
266 break;
267 if (!senders[i].name)
268 return -E_COMMAND_SYNTAX;
269 scd->sender_num = i;
270 arg = lls_input(1, lpr);
271 for (i = 0; subcmds[i]; i++)
272 if (!strcmp(subcmds[i], arg))
273 break;
274 if (!subcmds[i])
275 return -E_COMMAND_SYNTAX;
276 scd->cmd_num = i;
277 if (!senders[scd->sender_num].client_cmds[scd->cmd_num])
278 return -E_SENDER_CMD;
279 switch (scd->cmd_num) {
280 case SENDER_on:
281 case SENDER_off:
282 if (num_inputs != 2)
283 return -E_COMMAND_SYNTAX;
284 break;
285 case SENDER_deny:
286 case SENDER_allow:
287 if (num_inputs != 3 || parse_cidr(lls_input(2, lpr), scd->host,
288 sizeof(scd->host), &scd->netmask) == NULL)
289 return -E_COMMAND_SYNTAX;
290 break;
291 case SENDER_add:
292 case SENDER_delete:
293 if (num_inputs != 3)
294 return -E_COMMAND_SYNTAX;
295 return parse_fec_url(lls_input(2, lpr), scd);
296 default:
297 return -E_COMMAND_SYNTAX;
298 }
299 return 1;
300 }
301
302 /**
303 * Send a sideband packet through a blocking file descriptor.
304 *
305 * \param scc fd and crypto keys.
306 * \param expected_band The expected band designator.
307 * \param max_size Passed to \ref sb_new_recv().
308 * \param result Body of the sideband packet is returned here.
309 *
310 * If \a expected_band is not \p SBD_ANY, the band designator of the received
311 * sideband packet is compared to \a expected_band and a mismatch is considered
312 * an error.
313 *
314 * \return Standard.
315 */
316 int recv_sb(struct stream_cipher_context *scc,
317 enum sb_designator expected_band,
318 size_t max_size, struct iovec *result)
319 {
320 int ret;
321 struct sb_context *sbc;
322 struct iovec iov;
323 struct sb_buffer sbb;
324 sb_transformation trafo;
325
326 trafo = expected_band != SBD_ANY && expected_band < SBD_PROCEED?
327 NULL : sc_trafo;
328 sbc = sb_new_recv(max_size, trafo, scc->recv);
329 for (;;) {
330 sb_get_recv_buffer(sbc, &iov);
331 ret = recv_bin_buffer(scc->fd, iov.iov_base, iov.iov_len);
332 if (ret == 0)
333 ret = -E_EOF;
334 if (ret < 0)
335 goto fail;
336 ret = sb_received(sbc, ret, &sbb);
337 if (ret < 0)
338 goto fail;
339 if (ret > 0)
340 break;
341 }
342 ret = -E_BAD_BAND;
343 if (expected_band != SBD_ANY && sbb.band != expected_band)
344 goto fail;
345 *result = sbb.iov;
346 return 1;
347 fail:
348 sb_free(sbc);
349 return ret;
350 }
351
352 static int com_sender(struct command_context *cc, struct lls_parse_result *lpr)
353 {
354 int i, ret = 0;
355 char *msg = NULL;
356 struct sender_command_data scd;
357
358 if (lls_num_inputs(lpr) == 0) {
359 for (i = 0; senders[i].name; i++) {
360 char *tmp;
361 ret = xasprintf(&tmp, "%s%s\n", msg? msg : "",
362 senders[i].name);
363 free(msg);
364 msg = tmp;
365 }
366 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
367 }
368 ret = check_sender_args(cc, lpr, &scd);
369 if (ret < 0) {
370 if (scd.sender_num < 0)
371 return ret;
372 if (strcmp(lls_input(1, lpr), "status") == 0)
373 msg = senders[scd.sender_num].status();
374 else
375 msg = senders[scd.sender_num].help();
376 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
377 }
378
379 switch (scd.cmd_num) {
380 case SENDER_add:
381 case SENDER_delete:
382 assert(senders[scd.sender_num].resolve_target);
383 ret = senders[scd.sender_num].resolve_target(lls_input(2, lpr),
384 &scd);
385 if (ret < 0)
386 return ret;
387 }
388
389 for (i = 0; i < 10; i++) {
390 mutex_lock(mmd_mutex);
391 if (mmd->sender_cmd_data.cmd_num >= 0) {
392 /* another sender command is active, retry in 100ms */
393 struct timespec ts = {.tv_nsec = 100 * 1000 * 1000};
394 mutex_unlock(mmd_mutex);
395 nanosleep(&ts, NULL);
396 continue;
397 }
398 mmd->sender_cmd_data = scd;
399 mutex_unlock(mmd_mutex);
400 break;
401 }
402 return (i < 10)? 1 : -E_LOCK;
403 }
404 EXPORT_SERVER_CMD_HANDLER(sender);
405
406 static int com_si(struct command_context *cc,
407 __a_unused struct lls_parse_result *lpr)
408 {
409 char *msg, *ut;
410 int ret;
411
412 ut = daemon_get_uptime_str(now);
413 mutex_lock(mmd_mutex);
414 ret = xasprintf(&msg,
415 "up: %s\nplayed: %u\n"
416 "server_pid: %d\n"
417 "afs_pid: %d\n"
418 "connections (active/accepted/total): %u/%u/%u\n"
419 "current loglevel: %s\n"
420 "supported audio formats: %s\n",
421 ut, mmd->num_played,
422 (int)getppid(),
423 (int)mmd->afs_pid,
424 mmd->active_connections,
425 mmd->num_commands,
426 mmd->num_connects,
427 conf.loglevel_arg,
428 AUDIO_FORMAT_HANDLERS
429 );
430 mutex_unlock(mmd_mutex);
431 free(ut);
432 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
433 }
434 EXPORT_SERVER_CMD_HANDLER(si);
435
436 static int com_version(struct command_context *cc, struct lls_parse_result *lpr)
437 {
438 char *msg;
439 size_t len;
440
441 if (SERVER_CMD_OPT_GIVEN(VERSION, VERBOSE, lpr))
442 len = xasprintf(&msg, "%s", version_text("server"));
443 else
444 len = xasprintf(&msg, "%s\n", version_single_line("server"));
445 return send_sb(&cc->scc, msg, len, SBD_OUTPUT, false);
446 }
447 EXPORT_SERVER_CMD_HANDLER(version);
448
449 /** These status items are cleared if no audio file is currently open. */
450 #define EMPTY_STATUS_ITEMS \
451 ITEM(PATH) \
452 ITEM(DIRECTORY) \
453 ITEM(BASENAME) \
454 ITEM(SCORE) \
455 ITEM(ATTRIBUTES_BITMAP) \
456 ITEM(ATTRIBUTES_TXT) \
457 ITEM(HASH) \
458 ITEM(IMAGE_ID) \
459 ITEM(IMAGE_NAME) \
460 ITEM(LYRICS_ID) \
461 ITEM(LYRICS_NAME) \
462 ITEM(BITRATE) \
463 ITEM(FORMAT) \
464 ITEM(FREQUENCY) \
465 ITEM(CHANNELS) \
466 ITEM(DURATION) \
467 ITEM(SECONDS_TOTAL) \
468 ITEM(NUM_PLAYED) \
469 ITEM(LAST_PLAYED) \
470 ITEM(TECHINFO) \
471 ITEM(ARTIST) \
472 ITEM(TITLE) \
473 ITEM(YEAR) \
474 ITEM(ALBUM) \
475 ITEM(COMMENT) \
476 ITEM(MTIME) \
477 ITEM(FILE_SIZE) \
478 ITEM(CHUNK_TIME) \
479 ITEM(NUM_CHUNKS) \
480 ITEM(AMPLIFICATION) \
481
482 /**
483 * Write a list of audio-file related status items with empty values.
484 *
485 * This is used by vss when currently no audio file is open.
486 */
487 static unsigned empty_status_items(bool parser_friendly, char **result)
488 {
489 char *esi;
490 unsigned len;
491
492 if (parser_friendly)
493 len = xasprintf(&esi,
494 #define ITEM(x) "0004 %02x:\n"
495 EMPTY_STATUS_ITEMS
496 #undef ITEM
497 #define ITEM(x) , (unsigned) SI_ ## x
498 EMPTY_STATUS_ITEMS
499 #undef ITEM
500 );
501 else
502 len = xasprintf(&esi,
503 #define ITEM(x) "%s:\n"
504 EMPTY_STATUS_ITEMS
505 #undef ITEM
506 #define ITEM(x) ,status_item_list[SI_ ## x]
507 EMPTY_STATUS_ITEMS
508 #undef ITEM
509 );
510 *result = esi;
511 return len;
512 }
513 #undef EMPTY_STATUS_ITEMS
514
515 static int com_stat(struct command_context *cc, struct lls_parse_result *lpr)
516 {
517 int ret;
518 struct misc_meta_data tmp, *nmmd = &tmp;
519 char *s;
520 bool parser_friendly = SERVER_CMD_OPT_GIVEN(STAT, PARSER_FRIENDLY,
521 lpr) > 0;
522 uint32_t num = SERVER_CMD_UINT32_VAL(STAT, NUM, lpr);
523
524 para_sigaction(SIGUSR1, dummy);
525 for (;;) {
526 /*
527 * Copy the mmd structure to minimize the time we hold the mmd
528 * lock.
529 */
530 mutex_lock(mmd_mutex);
531 *nmmd = *mmd;
532 mutex_unlock(mmd_mutex);
533 ret = get_status(nmmd, parser_friendly, &s);
534 ret = send_sb(&cc->scc, s, ret, SBD_OUTPUT, false);
535 if (ret < 0)
536 goto out;
537 if (nmmd->vss_status_flags & VSS_NEXT) {
538 char *esi;
539 ret = empty_status_items(parser_friendly, &esi);
540 ret = send_sb(&cc->scc, esi, ret, SBD_OUTPUT, false);
541 if (ret < 0)
542 goto out;
543 } else
544 send_afs_status(cc, parser_friendly);
545 ret = 1;
546 if (num > 0 && !--num)
547 goto out;
548 sleep(50);
549 ret = -E_SERVER_CRASH;
550 if (getppid() == 1)
551 goto out;
552 }
553 out:
554 return ret;
555 }
556 EXPORT_SERVER_CMD_HANDLER(stat);
557
558 /* fixed-length, human readable permission string */
559 const char *server_cmd_perms_str(unsigned int perms)
560 {
561 static char result[5];
562
563 result[0] = perms & AFS_READ? 'a' : '-';
564 result[1] = perms & AFS_WRITE? 'A' : '-';
565 result[2] = perms & VSS_READ? 'v' : '-';
566 result[3] = perms & VSS_WRITE? 'V' : '-';
567 result[4] = '\0';
568 return result;
569 }
570
571 static int send_list_of_commands(struct command_context *cc)
572 {
573 int i;
574 const struct lls_command *cmd;
575 char *msg = para_strdup("");
576
577 for (i = 1; (cmd = lls_cmd(i, server_cmd_suite)); i++) {
578 const char *perms = server_cmd_perms_str(server_command_perms[i]);
579 char *tmp = make_message("%s%s\t%s\t%s\n", msg,
580 lls_command_name(cmd), perms, lls_purpose(cmd));
581 free(msg);
582 msg = tmp;
583 }
584 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
585 }
586
587 /* returns string that must be freed by the caller */
588 static struct server_command *get_cmd_ptr(const char *name, char **handler)
589 {
590 struct server_command *cmd;
591
592 /* not found, look for commands supported by afs */
593 for (cmd = afs_cmds; cmd->name; cmd++)
594 if (!strcmp(cmd->name, name)) {
595 if (handler)
596 *handler = para_strdup("afs");
597 return cmd;
598 }
599 return NULL;
600 }
601
602 static int com_help(struct command_context *cc, struct lls_parse_result *lpr)
603 {
604 const char *perms;
605 char *long_help, *buf, *errctx;
606 int ret;
607 const struct lls_command *cmd;
608
609 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
610 if (ret < 0) {
611 send_errctx(cc, errctx);
612 return ret;
613 }
614 if (lls_num_inputs(lpr) == 0)
615 return send_list_of_commands(cc);
616 /* argument given for help */
617 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), server_cmd_suite,
618 &errctx));
619 if (ret < 0) {
620 send_errctx(cc, errctx);
621 return ret;
622 }
623 cmd = lls_cmd(ret, server_cmd_suite);
624 perms = server_command_perms_txt[ret];
625 long_help = lls_long_help(cmd);
626 assert(long_help);
627 ret = xasprintf(&buf, "%spermissions: %s\n", long_help, perms);
628 free(long_help);
629 return send_sb(&cc->scc, buf, ret, SBD_OUTPUT, false);
630 }
631 EXPORT_SERVER_CMD_HANDLER(help);
632
633 static int com_hup(__a_unused struct command_context *cc,
634 __a_unused struct lls_parse_result *lpr)
635 {
636 kill(getppid(), SIGHUP);
637 return 1;
638 }
639 EXPORT_SERVER_CMD_HANDLER(hup);
640
641 static int com_term(__a_unused struct command_context *cc,
642 __a_unused struct lls_parse_result *lpr)
643 {
644 kill(getppid(), SIGTERM);
645 return 1;
646 }
647 EXPORT_SERVER_CMD_HANDLER(term);
648
649 static int com_play(__a_unused struct command_context *cc,
650 __a_unused struct lls_parse_result *lpr)
651 {
652 mutex_lock(mmd_mutex);
653 mmd->new_vss_status_flags |= VSS_PLAYING;
654 mmd->new_vss_status_flags &= ~VSS_NOMORE;
655 mutex_unlock(mmd_mutex);
656 return 1;
657 }
658 EXPORT_SERVER_CMD_HANDLER(play);
659
660 static int com_stop(__a_unused struct command_context *cc,
661 __a_unused struct lls_parse_result *lpr)
662 {
663 mutex_lock(mmd_mutex);
664 mmd->new_vss_status_flags &= ~VSS_PLAYING;
665 mmd->new_vss_status_flags &= ~VSS_REPOS;
666 mmd->new_vss_status_flags |= VSS_NEXT;
667 mutex_unlock(mmd_mutex);
668 return 1;
669 }
670 EXPORT_SERVER_CMD_HANDLER(stop);
671
672 static int com_pause(__a_unused struct command_context *cc,
673 __a_unused struct lls_parse_result *lpr)
674 {
675 mutex_lock(mmd_mutex);
676 if (!vss_paused() && !vss_stopped()) {
677 mmd->events++;
678 mmd->new_vss_status_flags &= ~VSS_PLAYING;
679 mmd->new_vss_status_flags &= ~VSS_NEXT;
680 }
681 mutex_unlock(mmd_mutex);
682 return 1;
683 }
684 EXPORT_SERVER_CMD_HANDLER(pause);
685
686 static int com_next(__a_unused struct command_context *cc,
687 __a_unused struct lls_parse_result *lpr)
688 {
689 mutex_lock(mmd_mutex);
690 mmd->events++;
691 mmd->new_vss_status_flags |= VSS_NEXT;
692 mutex_unlock(mmd_mutex);
693 return 1;
694 }
695 EXPORT_SERVER_CMD_HANDLER(next);
696
697 static int com_nomore(__a_unused struct command_context *cc,
698 __a_unused struct lls_parse_result *lpr)
699 {
700 mutex_lock(mmd_mutex);
701 if (vss_playing() || vss_paused())
702 mmd->new_vss_status_flags |= VSS_NOMORE;
703 mutex_unlock(mmd_mutex);
704 return 1;
705 }
706 EXPORT_SERVER_CMD_HANDLER(nomore);
707
708 static int com_ff(__a_unused struct command_context *cc,
709 struct lls_parse_result *lpr)
710 {
711 long promille;
712 int ret, backwards = 0;
713 unsigned i;
714 char c, *errctx;
715
716 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
717 if (ret < 0) {
718 send_errctx(cc, errctx);
719 return ret;
720 }
721 if (!(ret = sscanf(lls_input(0, lpr), "%u%c", &i, &c)))
722 return -E_COMMAND_SYNTAX;
723 if (ret > 1 && c == '-')
724 backwards = 1; /* jmp backwards */
725 mutex_lock(mmd_mutex);
726 ret = -E_NO_AUDIO_FILE;
727 if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
728 goto out;
729 promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
730 if (backwards)
731 promille -= 1000 * i / mmd->afd.afhi.seconds_total;
732 else
733 promille += 1000 * i / mmd->afd.afhi.seconds_total;
734 if (promille < 0)
735 promille = 0;
736 if (promille > 1000) {
737 mmd->new_vss_status_flags |= VSS_NEXT;
738 goto out;
739 }
740 mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
741 mmd->new_vss_status_flags |= VSS_REPOS;
742 mmd->new_vss_status_flags &= ~VSS_NEXT;
743 mmd->events++;
744 ret = 1;
745 out:
746 mutex_unlock(mmd_mutex);
747 return ret;
748 }
749 EXPORT_SERVER_CMD_HANDLER(ff);
750
751 static int com_jmp(__a_unused struct command_context *cc,
752 struct lls_parse_result *lpr)
753 {
754 long unsigned int i;
755 int ret;
756 char *errctx;
757
758 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
759 if (ret < 0) {
760 send_errctx(cc, errctx);
761 return ret;
762 }
763 if (sscanf(lls_input(0, lpr), "%lu", &i) <= 0)
764 return -ERRNO_TO_PARA_ERROR(EINVAL);
765 mutex_lock(mmd_mutex);
766 ret = -E_NO_AUDIO_FILE;
767 if (!mmd->afd.afhi.chunks_total)
768 goto out;
769 if (i > 100)
770 i = 100;
771 PARA_INFO_LOG("jumping to %lu%%\n", i);
772 mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50) / 100;
773 PARA_INFO_LOG("sent: %lu, offset before jmp: %li\n",
774 mmd->chunks_sent, mmd->offset);
775 mmd->new_vss_status_flags |= VSS_REPOS;
776 mmd->new_vss_status_flags &= ~VSS_NEXT;
777 ret = 1;
778 mmd->events++;
779 out:
780 mutex_unlock(mmd_mutex);
781 return ret;
782 }
783 EXPORT_SERVER_CMD_HANDLER(jmp);
784
785 static int com_tasks(struct command_context *cc,
786 __a_unused struct lls_parse_result *lpr)
787 {
788 char *tl = server_get_tasks();
789 assert(tl);
790 return send_sb(&cc->scc, tl, strlen(tl), SBD_OUTPUT, false);
791 }
792 EXPORT_SERVER_CMD_HANDLER(tasks);
793
794 /*
795 * check if perms are sufficient to exec a command having perms cmd_perms.
796 * Returns 0 if perms are sufficient, -E_PERM otherwise.
797 */
798 static int check_perms(unsigned int perms, const struct server_command *cmd_ptr)
799 {
800 PARA_DEBUG_LOG("checking permissions\n");
801 return (cmd_ptr->perms & perms) < cmd_ptr->perms ? -E_PERM : 0;
802 }
803
804 static void reset_signals(void)
805 {
806 para_sigaction(SIGCHLD, SIG_IGN);
807 para_sigaction(SIGINT, SIG_DFL);
808 para_sigaction(SIGTERM, SIG_DFL);
809 para_sigaction(SIGHUP, SIG_DFL);
810 }
811
812 struct connection_features {
813 bool aes_ctr128_requested;
814 };
815
816 static int parse_auth_request(char *buf, int len, struct user **u,
817 struct connection_features *cf)
818 {
819 int ret;
820 char *p, *username, **features = NULL;
821 size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
822
823 *u = NULL;
824 memset(cf, 0, sizeof(*cf));
825 if (len < auth_rq_len + 2)
826 return -E_AUTH_REQUEST;
827 if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
828 return -E_AUTH_REQUEST;
829 username = buf + auth_rq_len;
830 p = strchr(username, ' ');
831 if (p) {
832 int i;
833 if (p == username)
834 return -E_AUTH_REQUEST;
835 *p = '\0';
836 p++;
837 create_argv(p, ",", &features);
838 for (i = 0; features[i]; i++) {
839 if (strcmp(features[i], "sideband") == 0)
840 continue;
841 if (strcmp(features[i], "aes_ctr128") == 0)
842 cf->aes_ctr128_requested = true;
843 else {
844 ret = -E_BAD_FEATURE;
845 goto out;
846 }
847 }
848 }
849 PARA_DEBUG_LOG("received auth request for user %s\n", username);
850 *u = lookup_user(username);
851 ret = 1;
852 out:
853 free_argv(features);
854 return ret;
855 }
856
857 #define HANDSHAKE_BUFSIZE 4096
858
859 static int run_command(struct command_context *cc, struct iovec *iov,
860 const char *peername)
861 {
862 int ret, i;
863 char *p, *end;
864 struct server_command *cmd = NULL;
865 const struct lls_command *lcmd = NULL;
866 unsigned perms;
867 struct lls_parse_result *lpr;
868 char *errctx;
869
870 if (iov->iov_base == NULL || iov->iov_len == 0)
871 return -ERRNO_TO_PARA_ERROR(EINVAL);
872 p = iov->iov_base;
873 p[iov->iov_len - 1] = '\0'; /* just to be sure */
874
875 ret = lls(lls_lookup_subcmd(p, server_cmd_suite, &errctx));
876 if (ret >= 0 && !strcmp(p, lls_command_name(lls_cmd(ret,
877 server_cmd_suite)))) {
878 perms = server_command_perms[ret];
879 if ((perms & cc->u->perms) != perms)
880 return -E_PERM;
881 lcmd = lls_cmd(ret, server_cmd_suite);
882 } else {
883 cmd = get_cmd_ptr(p, NULL);
884 if (!cmd) {
885 send_errctx(cc, errctx);
886 return ret;
887 }
888 perms = cmd->perms;
889 ret = check_perms(cc->u->perms, cmd);
890 if (ret < 0)
891 return ret;
892 }
893 end = iov->iov_base + iov->iov_len;
894 for (i = 0; p < end; i++)
895 p += strlen(p) + 1;
896 cc->argc = i;
897 cc->argv = para_malloc((cc->argc + 1) * sizeof(char *));
898 for (i = 0, p = iov->iov_base; p < end; i++) {
899 cc->argv[i] = para_strdup(p);
900 p += strlen(p) + 1;
901 }
902 cc->argv[cc->argc] = NULL;
903 PARA_NOTICE_LOG("calling com_%s() for %s@%s\n", lcmd?
904 lls_command_name(lcmd) : cmd->name, cc->u->name, peername);
905 if (lcmd) {
906 ret = lls(lls_parse(cc->argc, cc->argv, lcmd, &lpr, &errctx));
907 if (ret >= 0) {
908 const struct server_cmd_user_data *ud = lls_user_data(lcmd);
909 ret = ud->handler(cc, lpr);
910 lls_free_parse_result(lpr, lcmd);
911 } else
912 send_errctx(cc, errctx);
913 } else {
914 ret = cmd->handler(cc);
915 }
916 free_argv(cc->argv);
917 mutex_lock(mmd_mutex);
918 mmd->num_commands++;
919 if (ret >= 0 && (perms & AFS_WRITE))
920 mmd->events++;
921 mutex_unlock(mmd_mutex);
922 return ret;
923 }
924
925 /**
926 * Perform user authentication and execute a command.
927 *
928 * \param fd The file descriptor to send output to.
929 * \param peername Identifies the connecting peer.
930 *
931 * Whenever para_server accepts an incoming tcp connection on the port it
932 * listens on, it forks and the resulting child calls this function.
933 *
934 * An RSA-based challenge/response is used to authenticate the peer. It that
935 * authentication succeeds, a random session key is generated and sent back to
936 * the peer, encrypted with its RSA public key. From this point on, all
937 * transfers are crypted with this session key.
938 *
939 * Next it is checked if the peer supplied a valid server command or a command
940 * for the audio file selector. If yes, and if the user has sufficient
941 * permissions to execute that command, the function calls the corresponding
942 * command handler which does argument checking and further processing.
943 *
944 * In order to cope with a DOS attacks, a timeout is set up which terminates
945 * the function if the connection was not authenticated when the timeout
946 * expires.
947 *
948 * \sa alarm(2), crypt.c, crypt.h
949 */
950 __noreturn void handle_connect(int fd, const char *peername)
951 {
952 int ret;
953 unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
954 unsigned char challenge_hash[HASH_SIZE];
955 char *command = NULL, *buf = para_malloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
956 size_t numbytes;
957 struct command_context cc_struct = {.peer = peername}, *cc = &cc_struct;
958 struct iovec iov;
959 struct connection_features cf;
960
961 cc->scc.fd = fd;
962 reset_signals();
963 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
964 ret = mark_fd_blocking(fd);
965 if (ret < 0)
966 goto net_err;
967 /* send Welcome message */
968 ret = write_va_buffer(fd, "This is para_server, version "
969 PACKAGE_VERSION ".\n"
970 "Features: sideband,aes_ctr128\n"
971 );
972 if (ret < 0)
973 goto net_err;
974 /* recv auth request line */
975 ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
976 if (ret < 0)
977 goto net_err;
978 ret = parse_auth_request(buf, ret, &cc->u, &cf);
979 if (ret < 0)
980 goto net_err;
981 if (cc->u) {
982 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
983 ret = pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
984 (unsigned char *)buf);
985 if (ret < 0)
986 goto net_err;
987 numbytes = ret;
988 } else {
989 /*
990 * We don't want to reveal our user names, so we send a
991 * challenge to the client even if the user does not exist, and
992 * fail the authentication later.
993 */
994 numbytes = 256;
995 get_random_bytes_or_die((unsigned char *)buf, numbytes);
996 }
997 PARA_DEBUG_LOG("sending %d byte challenge + session key (%zu bytes)\n",
998 CHALLENGE_SIZE, numbytes);
999 ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
1000 buf = NULL;
1001 if (ret < 0)
1002 goto net_err;
1003 ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
1004 HANDSHAKE_BUFSIZE, &iov);
1005 if (ret < 0)
1006 goto net_err;
1007 buf = iov.iov_base;
1008 numbytes = iov.iov_len;
1009 PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
1010 ret = -E_BAD_USER;
1011 if (!cc->u)
1012 goto net_err;
1013 /*
1014 * The correct response is the hash of the first CHALLENGE_SIZE bytes
1015 * of the random data.
1016 */
1017 ret = -E_BAD_AUTH;
1018 if (numbytes != HASH_SIZE)
1019 goto net_err;
1020 hash_function((char *)rand_buf, CHALLENGE_SIZE, challenge_hash);
1021 if (memcmp(challenge_hash, buf, HASH_SIZE))
1022 goto net_err;
1023 /* auth successful */
1024 alarm(0);
1025 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
1026 /* init stream cipher keys with the second part of the random buffer */
1027 cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN,
1028 cf.aes_ctr128_requested);
1029 cc->scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN,
1030 SESSION_KEY_LEN, cf.aes_ctr128_requested);
1031 ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
1032 if (ret < 0)
1033 goto net_err;
1034 ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
1035 if (ret < 0)
1036 goto net_err;
1037 ret = run_command(cc, &iov, peername);
1038 free(iov.iov_base);
1039 if (ret < 0)
1040 goto err_out;
1041 if (ret >= 0)
1042 goto out;
1043 err_out:
1044 if (send_strerror(cc, -ret) >= 0)
1045 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
1046 net_err:
1047 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1048 out:
1049 free(buf);
1050 free(command);
1051 mutex_lock(mmd_mutex);
1052 mmd->active_connections--;
1053 mutex_unlock(mmd_mutex);
1054 if (ret >= 0) {
1055 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1056 if (ret < 0)
1057 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1058 }
1059 sc_free(cc->scc.recv);
1060 sc_free(cc->scc.send);
1061 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
1062 }