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