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