command.c: Document return value of handle_connect().
[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 static bool subcmd_should_die;
53
54 static void command_handler_sighandler(int s)
55 {
56 if (s != SIGTERM)
57 return;
58 PARA_EMERG_LOG("terminating on signal %d\n", SIGTERM);
59 subcmd_should_die = true;
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_EACH_SENDER(i)
243 if (strcmp(senders[i]->name, arg) == 0)
244 break;
245 if (!senders[i])
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_EACH_SENDER(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)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 const struct timespec ts = {.tv_sec = 50, .tv_nsec = 0};
501
502 para_sigaction(SIGINT, SIG_IGN);
503 para_sigaction(SIGUSR1, command_handler_sighandler);
504 para_sigaction(SIGTERM, command_handler_sighandler);
505 /*
506 * Simply checking subcmd_should_die is racy because a signal may
507 * arrive after the check but before the subsequent call to sleep(3).
508 * If this happens, sleep(3) would not be interrupted by the signal.
509 * To avoid this we block SIGTERM here and allow it to arrive only
510 * while we sleep.
511 */
512 para_block_signal(SIGTERM);
513 for (;;) {
514 sigset_t set;
515 /*
516 * Copy the mmd structure to minimize the time we hold the mmd
517 * lock.
518 */
519 mutex_lock(mmd_mutex);
520 *nmmd = *mmd;
521 mutex_unlock(mmd_mutex);
522 ret = get_status(nmmd, parser_friendly, &s);
523 ret = send_sb(&cc->scc, s, ret, SBD_OUTPUT, false);
524 if (ret < 0)
525 goto out;
526 if (nmmd->vss_status_flags & VSS_NEXT) {
527 char *esi;
528 ret = empty_status_items(parser_friendly, &esi);
529 ret = send_sb(&cc->scc, esi, ret, SBD_OUTPUT, false);
530 if (ret < 0)
531 goto out;
532 } else
533 send_afs_status(cc, parser_friendly);
534 ret = 1;
535 if (num > 0 && !--num)
536 goto out;
537 sigemptyset(&set); /* empty set means: unblock all signals */
538 /*
539 * pselect(2) allows to atomically unblock signals, then go to
540 * sleep. Calling sigprocmask(2) followed by sleep(3) would
541 * open a race window similar to the one described above.
542 */
543 pselect(1, NULL, NULL, NULL, &ts, &set);
544 if (subcmd_should_die)
545 goto out;
546 ret = -E_SERVER_CRASH;
547 if (getppid() == 1)
548 goto out;
549 }
550 out:
551 return ret;
552 }
553 EXPORT_SERVER_CMD_HANDLER(stat);
554
555 /* fixed-length, human readable permission string */
556 const char *server_cmd_perms_str(unsigned int perms)
557 {
558 static char result[5];
559
560 result[0] = perms & AFS_READ? 'a' : '-';
561 result[1] = perms & AFS_WRITE? 'A' : '-';
562 result[2] = perms & VSS_READ? 'v' : '-';
563 result[3] = perms & VSS_WRITE? 'V' : '-';
564 result[4] = '\0';
565 return result;
566 }
567
568 static int send_list_of_commands(struct command_context *cc)
569 {
570 int i;
571 const struct lls_command *cmd;
572 char *msg = para_strdup("");
573
574 for (i = 1; (cmd = lls_cmd(i, server_cmd_suite)); i++) {
575 const char *perms = server_cmd_perms_str(server_command_perms[i]);
576 char *tmp = make_message("%s%s\t%s\t%s\n", msg,
577 lls_command_name(cmd), perms, lls_purpose(cmd));
578 free(msg);
579 msg = tmp;
580 }
581 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
582 }
583
584 static int com_help(struct command_context *cc, struct lls_parse_result *lpr)
585 {
586 const char *perms;
587 char *long_help, *buf, *errctx;
588 int ret;
589 const struct lls_command *cmd;
590
591 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
592 if (ret < 0) {
593 send_errctx(cc, errctx);
594 return ret;
595 }
596 if (lls_num_inputs(lpr) == 0)
597 return send_list_of_commands(cc);
598 /* argument given for help */
599 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), server_cmd_suite,
600 &errctx));
601 if (ret < 0) {
602 send_errctx(cc, errctx);
603 return ret;
604 }
605 cmd = lls_cmd(ret, server_cmd_suite);
606 perms = server_command_perms_txt[ret];
607 long_help = lls_long_help(cmd);
608 assert(long_help);
609 ret = xasprintf(&buf, "%spermissions: %s\n", long_help, perms);
610 free(long_help);
611 return send_sb(&cc->scc, buf, ret, SBD_OUTPUT, false);
612 }
613 EXPORT_SERVER_CMD_HANDLER(help);
614
615 static int com_hup(__a_unused struct command_context *cc,
616 __a_unused struct lls_parse_result *lpr)
617 {
618 kill(getppid(), SIGHUP);
619 return 1;
620 }
621 EXPORT_SERVER_CMD_HANDLER(hup);
622
623 static int com_term(__a_unused struct command_context *cc,
624 __a_unused struct lls_parse_result *lpr)
625 {
626 kill(getppid(), SIGTERM);
627 return 1;
628 }
629 EXPORT_SERVER_CMD_HANDLER(term);
630
631 static int com_play(__a_unused struct command_context *cc,
632 __a_unused struct lls_parse_result *lpr)
633 {
634 mutex_lock(mmd_mutex);
635 mmd->new_vss_status_flags |= VSS_PLAYING;
636 mmd->new_vss_status_flags &= ~VSS_NOMORE;
637 mutex_unlock(mmd_mutex);
638 return 1;
639 }
640 EXPORT_SERVER_CMD_HANDLER(play);
641
642 static int com_stop(__a_unused struct command_context *cc,
643 __a_unused struct lls_parse_result *lpr)
644 {
645 mutex_lock(mmd_mutex);
646 mmd->new_vss_status_flags &= ~VSS_PLAYING;
647 mmd->new_vss_status_flags &= ~VSS_REPOS;
648 mmd->new_vss_status_flags |= VSS_NEXT;
649 mutex_unlock(mmd_mutex);
650 return 1;
651 }
652 EXPORT_SERVER_CMD_HANDLER(stop);
653
654 static int com_pause(__a_unused struct command_context *cc,
655 __a_unused struct lls_parse_result *lpr)
656 {
657 mutex_lock(mmd_mutex);
658 if (!vss_paused() && !vss_stopped()) {
659 mmd->events++;
660 mmd->new_vss_status_flags &= ~VSS_PLAYING;
661 mmd->new_vss_status_flags &= ~VSS_NEXT;
662 }
663 mutex_unlock(mmd_mutex);
664 return 1;
665 }
666 EXPORT_SERVER_CMD_HANDLER(pause);
667
668 static int com_next(__a_unused struct command_context *cc,
669 __a_unused struct lls_parse_result *lpr)
670 {
671 mutex_lock(mmd_mutex);
672 mmd->events++;
673 mmd->new_vss_status_flags |= VSS_NEXT;
674 mutex_unlock(mmd_mutex);
675 return 1;
676 }
677 EXPORT_SERVER_CMD_HANDLER(next);
678
679 static int com_nomore(__a_unused struct command_context *cc,
680 __a_unused struct lls_parse_result *lpr)
681 {
682 mutex_lock(mmd_mutex);
683 if (vss_playing() || vss_paused())
684 mmd->new_vss_status_flags |= VSS_NOMORE;
685 mutex_unlock(mmd_mutex);
686 return 1;
687 }
688 EXPORT_SERVER_CMD_HANDLER(nomore);
689
690 static int com_ff(__a_unused struct command_context *cc,
691 struct lls_parse_result *lpr)
692 {
693 long promille;
694 int ret, backwards = 0;
695 unsigned i;
696 char c, *errctx;
697
698 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
699 if (ret < 0) {
700 send_errctx(cc, errctx);
701 return ret;
702 }
703 if (!(ret = sscanf(lls_input(0, lpr), "%u%c", &i, &c)))
704 return -E_COMMAND_SYNTAX;
705 if (ret > 1 && c == '-')
706 backwards = 1; /* jmp backwards */
707 mutex_lock(mmd_mutex);
708 ret = -E_NO_AUDIO_FILE;
709 if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
710 goto out;
711 promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
712 if (backwards)
713 promille -= 1000 * i / mmd->afd.afhi.seconds_total;
714 else
715 promille += 1000 * i / mmd->afd.afhi.seconds_total;
716 if (promille < 0)
717 promille = 0;
718 if (promille > 1000) {
719 mmd->new_vss_status_flags |= VSS_NEXT;
720 goto out;
721 }
722 mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
723 mmd->new_vss_status_flags |= VSS_REPOS;
724 mmd->new_vss_status_flags &= ~VSS_NEXT;
725 mmd->events++;
726 ret = 1;
727 out:
728 mutex_unlock(mmd_mutex);
729 return ret;
730 }
731 EXPORT_SERVER_CMD_HANDLER(ff);
732
733 static int com_jmp(__a_unused struct command_context *cc,
734 struct lls_parse_result *lpr)
735 {
736 long unsigned int i;
737 int ret;
738 char *errctx;
739
740 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
741 if (ret < 0) {
742 send_errctx(cc, errctx);
743 return ret;
744 }
745 if (sscanf(lls_input(0, lpr), "%lu", &i) <= 0)
746 return -ERRNO_TO_PARA_ERROR(EINVAL);
747 mutex_lock(mmd_mutex);
748 ret = -E_NO_AUDIO_FILE;
749 if (!mmd->afd.afhi.chunks_total)
750 goto out;
751 if (i > 100)
752 i = 100;
753 PARA_INFO_LOG("jumping to %lu%%\n", i);
754 mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50) / 100;
755 PARA_INFO_LOG("sent: %lu, offset before jmp: %li\n",
756 mmd->chunks_sent, mmd->offset);
757 mmd->new_vss_status_flags |= VSS_REPOS;
758 mmd->new_vss_status_flags &= ~VSS_NEXT;
759 ret = 1;
760 mmd->events++;
761 out:
762 mutex_unlock(mmd_mutex);
763 return ret;
764 }
765 EXPORT_SERVER_CMD_HANDLER(jmp);
766
767 /* deprecated, does nothing */
768 static int com_tasks(__a_unused struct command_context *cc,
769 __a_unused struct lls_parse_result *lpr)
770 {
771 return 1;
772 }
773 EXPORT_SERVER_CMD_HANDLER(tasks);
774
775 static void reset_signals(void)
776 {
777 para_sigaction(SIGCHLD, SIG_IGN);
778 para_sigaction(SIGINT, SIG_DFL);
779 para_sigaction(SIGTERM, SIG_DFL);
780 para_sigaction(SIGHUP, SIG_DFL);
781 }
782
783 struct connection_features {
784 int dummy; /* none at the moment */
785 };
786
787 static int parse_auth_request(char *buf, int len, const struct user **u,
788 struct connection_features *cf)
789 {
790 int ret;
791 char *p, *username, **features = NULL;
792 size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
793
794 *u = NULL;
795 memset(cf, 0, sizeof(*cf));
796 if (len < auth_rq_len + 2)
797 return -E_AUTH_REQUEST;
798 if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
799 return -E_AUTH_REQUEST;
800 username = buf + auth_rq_len;
801 p = strchr(username, ' ');
802 if (p) {
803 int i;
804 if (p == username)
805 return -E_AUTH_REQUEST;
806 *p = '\0';
807 p++;
808 create_argv(p, ",", &features);
809 for (i = 0; features[i]; i++) {
810 if (strcmp(features[i], "sideband") == 0)
811 continue;
812 if (strcmp(features[i], "aes_ctr128") == 0)
813 continue;
814 else {
815 ret = -E_BAD_FEATURE;
816 goto out;
817 }
818 }
819 }
820 PARA_DEBUG_LOG("received auth request for user %s\n", username);
821 *u = user_list_lookup(username);
822 ret = 1;
823 out:
824 free_argv(features);
825 return ret;
826 }
827
828 #define HANDSHAKE_BUFSIZE 4096
829
830 static int run_command(struct command_context *cc, struct iovec *iov)
831 {
832 int ret, i, argc;
833 char *p, *end, **argv;
834 const struct lls_command *lcmd = NULL;
835 unsigned perms;
836 struct lls_parse_result *lpr;
837 char *errctx;
838
839 if (iov->iov_base == NULL || iov->iov_len == 0)
840 return -ERRNO_TO_PARA_ERROR(EINVAL);
841 p = iov->iov_base;
842 p[iov->iov_len - 1] = '\0'; /* just to be sure */
843
844 ret = lls(lls_lookup_subcmd(p, server_cmd_suite, &errctx));
845 if (ret < 0) {
846 send_errctx(cc, errctx);
847 return ret;
848 }
849 perms = server_command_perms[ret];
850 if ((perms & cc->u->perms) != perms)
851 return -E_PERM;
852 lcmd = lls_cmd(ret, server_cmd_suite);
853 end = iov->iov_base + iov->iov_len;
854 for (i = 0; p < end; i++)
855 p += strlen(p) + 1;
856 argc = i;
857 argv = para_malloc((argc + 1) * sizeof(char *));
858 for (i = 0, p = iov->iov_base; p < end; i++) {
859 argv[i] = para_strdup(p);
860 p += strlen(p) + 1;
861 }
862 argv[argc] = NULL;
863 PARA_NOTICE_LOG("calling com_%s() for user %s\n",
864 lls_command_name(lcmd), cc->u->name);
865 ret = lls(lls_parse(argc, argv, lcmd, &lpr, &errctx));
866 if (ret >= 0) {
867 const struct server_cmd_user_data *ud = lls_user_data(lcmd);
868 ret = ud->handler(cc, lpr);
869 lls_free_parse_result(lpr, lcmd);
870 } else
871 send_errctx(cc, errctx);
872 free_argv(argv);
873 mutex_lock(mmd_mutex);
874 mmd->num_commands++;
875 if (ret >= 0 && (perms & AFS_WRITE))
876 mmd->events++;
877 mutex_unlock(mmd_mutex);
878 return ret;
879 }
880
881 /**
882 * Perform user authentication and execute a command.
883 *
884 * \param fd The file descriptor to send output to.
885 *
886 * Whenever para_server accepts an incoming tcp connection on the port it
887 * listens on, it forks and the resulting child calls this function.
888 *
889 * An RSA-based challenge/response is used to authenticate the peer. It that
890 * authentication succeeds, a random session key is generated and sent back to
891 * the peer, encrypted with its RSA public key. From this point on, all
892 * transfers are crypted with this session key.
893 *
894 * Next it is checked if the peer supplied a valid server command or a command
895 * for the audio file selector. If yes, and if the user has sufficient
896 * permissions to execute that command, the function calls the corresponding
897 * command handler which does argument checking and further processing.
898 *
899 * In order to cope with DOS attacks, a timeout is set up which terminates
900 * the function if the connection was not authenticated when the timeout
901 * expires.
902 *
903 * \return Standard.
904 *
905 * \sa alarm(2), \ref crypt.c, \ref crypt.h.
906 */
907 int handle_connect(int fd)
908 {
909 int ret;
910 unsigned char rand_buf[CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
911 unsigned char challenge_hash[HASH_SIZE];
912 char *command = NULL, *buf = para_malloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
913 size_t numbytes;
914 struct command_context cc_struct = {.u = NULL}, *cc = &cc_struct;
915 struct iovec iov;
916 struct connection_features cf;
917
918 cc->scc.fd = fd;
919 reset_signals();
920 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
921 ret = mark_fd_blocking(fd);
922 if (ret < 0)
923 goto net_err;
924 /* send Welcome message */
925 ret = write_va_buffer(fd, "This is para_server, version "
926 PACKAGE_VERSION ".\n"
927 "Features: sideband,aes_ctr128\n"
928 );
929 if (ret < 0)
930 goto net_err;
931 /* recv auth request line */
932 ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
933 if (ret < 0)
934 goto net_err;
935 ret = parse_auth_request(buf, ret, &cc->u, &cf);
936 if (ret < 0)
937 goto net_err;
938 if (cc->u) {
939 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
940 ret = pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
941 (unsigned char *)buf);
942 if (ret < 0)
943 goto net_err;
944 numbytes = ret;
945 } else {
946 /*
947 * We don't want to reveal our user names, so we send a
948 * challenge to the client even if the user does not exist, and
949 * fail the authentication later.
950 */
951 numbytes = 256;
952 get_random_bytes_or_die((unsigned char *)buf, numbytes);
953 }
954 PARA_DEBUG_LOG("sending %d byte challenge + session key (%zu bytes)\n",
955 CHALLENGE_SIZE, numbytes);
956 ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
957 buf = NULL;
958 if (ret < 0)
959 goto net_err;
960 ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
961 HANDSHAKE_BUFSIZE, &iov);
962 if (ret < 0)
963 goto net_err;
964 buf = iov.iov_base;
965 numbytes = iov.iov_len;
966 PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
967 ret = -E_BAD_USER;
968 if (!cc->u)
969 goto net_err;
970 /*
971 * The correct response is the hash of the first CHALLENGE_SIZE bytes
972 * of the random data.
973 */
974 ret = -E_BAD_AUTH;
975 if (numbytes != HASH_SIZE)
976 goto net_err;
977 hash_function((char *)rand_buf, CHALLENGE_SIZE, challenge_hash);
978 if (memcmp(challenge_hash, buf, HASH_SIZE))
979 goto net_err;
980 /* auth successful */
981 alarm(0);
982 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
983 /* init stream cipher keys with the second part of the random buffer */
984 cc->scc.recv = sc_new(rand_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
985 cc->scc.send = sc_new(rand_buf + CHALLENGE_SIZE + SESSION_KEY_LEN,
986 SESSION_KEY_LEN);
987 ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
988 if (ret < 0)
989 goto net_err;
990 ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
991 if (ret < 0)
992 goto net_err;
993 ret = run_command(cc, &iov);
994 free(iov.iov_base);
995 if (ret < 0)
996 goto err_out;
997 if (ret >= 0)
998 goto out;
999 err_out:
1000 if (send_strerror(cc, -ret) >= 0)
1001 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
1002 net_err:
1003 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1004 out:
1005 free(buf);
1006 free(command);
1007 mutex_lock(mmd_mutex);
1008 mmd->active_connections--;
1009 mutex_unlock(mmd_mutex);
1010 if (ret >= 0) {
1011 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1012 if (ret < 0)
1013 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1014 }
1015 sc_free(cc->scc.recv);
1016 sc_free(cc->scc.send);
1017 return ret;
1018 }