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