]> git.tuebingen.mpg.de Git - paraslash.git/blob - command.c
openssl: Switch to evp API for sha1 and sha256.
[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 <arpa/inet.h>
10 #include <netdb.h>
11 #include <lopsub.h>
12
13 #include "para.h"
14 #include "error.h"
15 #include "lsu.h"
16 #include "crypt.h"
17 #include "sideband.h"
18 #include "command.h"
19 #include "string.h"
20 #include "afh.h"
21 #include "net.h"
22 #include "server.h"
23 #include "list.h"
24 #include "sched.h"
25 #include "send.h"
26 #include "vss.h"
27 #include "daemon.h"
28 #include "fd.h"
29 #include "ipc.h"
30 #include "server_cmd.lsg.h"
31 #include "user_list.h"
32 #include "signal.h"
33 #include "version.h"
34
35 #define SERVER_CMD_AUX_INFO(_arg) _arg,
36 static const unsigned server_command_perms[] = {LSG_SERVER_CMD_AUX_INFOS};
37 #undef SERVER_CMD_AUX_INFO
38 #define SERVER_CMD_AUX_INFO(_arg) #_arg,
39 static const char * const server_command_perms_txt[] = {LSG_SERVER_CMD_AUX_INFOS};
40 #undef SERVER_CMD_AUX_INFO
41
42 /** Commands including options must be shorter than this. */
43 #define MAX_COMMAND_LEN 32768
44
45 extern int mmd_mutex;
46 extern struct misc_meta_data *mmd;
47 int send_afs_status(struct command_context *cc, int parser_friendly);
48 static bool subcmd_should_die;
49
50 static void command_handler_sighandler(int s)
51 {
52         if (s != SIGTERM)
53                 return;
54         PARA_EMERG_LOG("terminating on signal %d\n", SIGTERM);
55         subcmd_should_die = true;
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 = alloc(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_EACH_SENDER(i)
239                 if (strcmp(senders[i]->name, arg) == 0)
240                         break;
241         if (!senders[i])
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  * Receive a sideband packet from 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_EACH_SENDER(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                 "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                 AUDIO_FORMAT_HANDLERS
401         );
402         mutex_unlock(mmd_mutex);
403         free(ut);
404         return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
405 }
406 EXPORT_SERVER_CMD_HANDLER(si);
407
408 static int com_version(struct command_context *cc, struct lls_parse_result *lpr)
409 {
410         char *msg;
411         size_t len;
412
413         if (SERVER_CMD_OPT_GIVEN(VERSION, VERBOSE, lpr))
414                 len = xasprintf(&msg, "%s", version_text("server"));
415         else
416                 len = xasprintf(&msg, "%s\n", version_single_line("server"));
417         return send_sb(&cc->scc, msg, len, SBD_OUTPUT, false);
418 }
419 EXPORT_SERVER_CMD_HANDLER(version);
420
421 /** These status items are cleared if no audio file is currently open. */
422 #define EMPTY_STATUS_ITEMS \
423         ITEM(path) \
424         ITEM(directory) \
425         ITEM(basename) \
426         ITEM(score) \
427         ITEM(attributes_bitmap) \
428         ITEM(attributes_txt) \
429         ITEM(hash) \
430         ITEM(image_id) \
431         ITEM(image_name) \
432         ITEM(lyrics_id) \
433         ITEM(lyrics_name) \
434         ITEM(bitrate) \
435         ITEM(format) \
436         ITEM(frequency) \
437         ITEM(channels) \
438         ITEM(duration) \
439         ITEM(seconds_total) \
440         ITEM(num_played) \
441         ITEM(last_played) \
442         ITEM(techinfo) \
443         ITEM(artist) \
444         ITEM(title) \
445         ITEM(year) \
446         ITEM(album) \
447         ITEM(comment) \
448         ITEM(mtime) \
449         ITEM(file_size) \
450         ITEM(chunk_time) \
451         ITEM(num_chunks) \
452         ITEM(amplification) \
453         ITEM(play_time) \
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         const struct timespec ts = {.tv_sec = 50, .tv_nsec = 0};
496
497         para_sigaction(SIGINT, SIG_IGN);
498         para_sigaction(SIGUSR1, command_handler_sighandler);
499         para_sigaction(SIGTERM, command_handler_sighandler);
500         /*
501          * Simply checking subcmd_should_die is racy because a signal may
502          * arrive after the check but before the subsequent call to sleep(3).
503          * If this happens, sleep(3) would not be interrupted by the signal.
504          * To avoid this we block SIGTERM here and allow it to arrive only
505          * while we sleep.
506          */
507         para_block_signal(SIGTERM);
508         for (;;) {
509                 sigset_t set;
510                 /*
511                  * Copy the mmd structure to minimize the time we hold the mmd
512                  * lock.
513                  */
514                 mutex_lock(mmd_mutex);
515                 *nmmd = *mmd;
516                 mutex_unlock(mmd_mutex);
517                 ret = get_status(nmmd, parser_friendly, &s);
518                 ret = send_sb(&cc->scc, s, ret, SBD_OUTPUT, false);
519                 if (ret < 0)
520                         goto out;
521                 if (nmmd->vss_status_flags & VSS_NEXT) {
522                         char *esi;
523                         ret = empty_status_items(parser_friendly, &esi);
524                         ret = send_sb(&cc->scc, esi, ret, SBD_OUTPUT, false);
525                         if (ret < 0)
526                                 goto out;
527                 } else
528                         send_afs_status(cc, parser_friendly);
529                 ret = 1;
530                 if (num > 0 && !--num)
531                         goto out;
532                 sigemptyset(&set); /* empty set means: unblock all signals */
533                 /*
534                  * pselect(2) allows to atomically unblock signals, then go to
535                  * sleep. Calling sigprocmask(2) followed by sleep(3) would
536                  * open a race window similar to the one described above.
537                  */
538                 pselect(1, NULL, NULL, NULL, &ts, &set);
539                 if (subcmd_should_die)
540                         goto out;
541                 ret = -E_SERVER_CRASH;
542                 if (getppid() == 1)
543                         goto out;
544         }
545 out:
546         return ret;
547 }
548 EXPORT_SERVER_CMD_HANDLER(stat);
549
550 static const char *aux_info_cb(unsigned cmd_num, bool verbose)
551 {
552         static char result[80];
553         unsigned perms = server_command_perms[cmd_num];
554
555         if (verbose) {
556                 /* permissions: VSS_READ | VSS_WRITE */
557                 sprintf(result, "permissions: %s",
558                         server_command_perms_txt[cmd_num]);
559         } else {
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         }
566         return result;
567 }
568
569 static int com_help(struct command_context *cc, struct lls_parse_result *lpr)
570 {
571         char *buf;
572         int ret;
573         unsigned n;
574         bool long_help = SERVER_CMD_OPT_GIVEN(HELP, LONG, lpr);
575
576         lsu_com_help(long_help, lpr, server_cmd_suite, aux_info_cb, &buf, &n);
577         ret = send_sb(&cc->scc, buf, n, SBD_OUTPUT, false);
578         return ret;
579 }
580 EXPORT_SERVER_CMD_HANDLER(help);
581
582 static int com_hup(__a_unused struct command_context *cc,
583                 __a_unused struct lls_parse_result *lpr)
584 {
585         kill(getppid(), SIGHUP);
586         return 1;
587 }
588 EXPORT_SERVER_CMD_HANDLER(hup);
589
590 static int com_ll(struct command_context *cc, struct lls_parse_result *lpr)
591 {
592         unsigned ll, perms;
593         char *errctx;
594         const char *sev[] = {SEVERITIES}, *arg;
595         int ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
596
597         if (ret < 0) {
598                 send_errctx(cc, errctx);
599                 return ret;
600         }
601         if (lls_num_inputs(lpr) == 0) { /* reporting is an unprivileged op. */
602                 const char *severity;
603                 mutex_lock(mmd_mutex);
604                 severity = sev[mmd->loglevel];
605                 mutex_unlock(mmd_mutex);
606                 return send_sb_va(&cc->scc, SBD_OUTPUT, "%s\n", severity);
607         }
608         /*
609          * Changing the loglevel changes the state of both the afs and the vss,
610          * so we require both AFS_WRITE and VSS_WRITE.
611          */
612         perms = AFS_WRITE | VSS_WRITE;
613         if ((cc->u->perms & perms) != perms)
614                 return -ERRNO_TO_PARA_ERROR(EPERM);
615         arg = lls_input(0, lpr);
616         for (ll = 0; ll < NUM_LOGLEVELS; ll++)
617                 if (!strcmp(arg, sev[ll]))
618                         break;
619         if (ll >= NUM_LOGLEVELS)
620                 return -ERRNO_TO_PARA_ERROR(EINVAL);
621         PARA_INFO_LOG("new log level: %s\n", sev[ll]);
622         /* Ask the server and afs processes to adjust their log level. */
623         mutex_lock(mmd_mutex);
624         mmd->loglevel = ll;
625         mutex_unlock(mmd_mutex);
626         return 1;
627 }
628 EXPORT_SERVER_CMD_HANDLER(ll);
629
630 static int com_term(__a_unused struct command_context *cc,
631                 __a_unused struct lls_parse_result *lpr)
632 {
633         /*
634          * The server catches SIGTERM and propagates this signal to all its
635          * children. We are about to exit anyway, but we'd leak tons of memory
636          * if being terminated by the signal. So we ignore the signal here and
637          * terminate via the normal exit path, deallocating all memory.
638          */
639         para_sigaction(SIGTERM, SIG_IGN);
640         kill(getppid(), SIGTERM);
641         return 1;
642 }
643 EXPORT_SERVER_CMD_HANDLER(term);
644
645 static int com_play(__a_unused struct command_context *cc,
646                 __a_unused struct lls_parse_result *lpr)
647 {
648         mutex_lock(mmd_mutex);
649         mmd->new_vss_status_flags |= VSS_PLAYING;
650         mmd->new_vss_status_flags &= ~VSS_NOMORE;
651         mutex_unlock(mmd_mutex);
652         return 1;
653 }
654 EXPORT_SERVER_CMD_HANDLER(play);
655
656 static int com_stop(__a_unused struct command_context *cc,
657                 __a_unused struct lls_parse_result *lpr)
658 {
659         mutex_lock(mmd_mutex);
660         mmd->new_vss_status_flags &= ~VSS_PLAYING;
661         mmd->new_vss_status_flags &= ~VSS_REPOS;
662         mmd->new_vss_status_flags |= VSS_NEXT;
663         mutex_unlock(mmd_mutex);
664         return 1;
665 }
666 EXPORT_SERVER_CMD_HANDLER(stop);
667
668 static int com_pause(__a_unused struct command_context *cc,
669                 __a_unused struct lls_parse_result *lpr)
670 {
671         mutex_lock(mmd_mutex);
672         if (!vss_paused() && !vss_stopped()) {
673                 mmd->events++;
674                 mmd->new_vss_status_flags &= ~VSS_PLAYING;
675                 mmd->new_vss_status_flags &= ~VSS_NEXT;
676         }
677         mutex_unlock(mmd_mutex);
678         return 1;
679 }
680 EXPORT_SERVER_CMD_HANDLER(pause);
681
682 static int com_next(__a_unused struct command_context *cc,
683                 __a_unused struct lls_parse_result *lpr)
684 {
685         mutex_lock(mmd_mutex);
686         mmd->events++;
687         mmd->new_vss_status_flags |= VSS_NEXT;
688         mutex_unlock(mmd_mutex);
689         return 1;
690 }
691 EXPORT_SERVER_CMD_HANDLER(next);
692
693 static int com_nomore(__a_unused struct command_context *cc,
694                 __a_unused struct lls_parse_result *lpr)
695 {
696         mutex_lock(mmd_mutex);
697         if (vss_playing() || vss_paused())
698                 mmd->new_vss_status_flags |= VSS_NOMORE;
699         mutex_unlock(mmd_mutex);
700         return 1;
701 }
702 EXPORT_SERVER_CMD_HANDLER(nomore);
703
704 static int com_ff(struct command_context *cc, struct lls_parse_result *lpr)
705 {
706         long promille;
707         int i, ret;
708         char c, *errctx;
709
710         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
711         if (ret < 0) {
712                 send_errctx(cc, errctx);
713                 return ret;
714         }
715         ret = para_atoi32(lls_input(0, lpr), &i);
716         if (ret < 0) {
717                 if (ret != -E_ATOI_JUNK_AT_END)
718                         return ret;
719                 /*
720                  * Compatibility code to keep the historic syntax (ff 30-)
721                  * working. This can be removed after 0.7.0.
722                  */
723                 ret = sscanf(lls_input(0, lpr), "%i%c", &i, &c);
724                 if (ret <= 0)
725                         return -E_COMMAND_SYNTAX;
726                 if (ret > 1 && c == '-') {
727                         PARA_WARNING_LOG("use of obsolete syntax\n");
728                         i = -i;
729                 }
730         }
731         mutex_lock(mmd_mutex);
732         ret = -E_NO_AUDIO_FILE;
733         if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
734                 goto out;
735         ret = 1;
736         promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
737         /*
738          * We need this cast because without it the expression on the right
739          * hand side is of unsigned type.
740          */
741         promille += 1000 * i / (int)mmd->afd.afhi.seconds_total;
742         if (promille < 0)
743                 promille = 0;
744         if (promille > 1000) {
745                 mmd->new_vss_status_flags |= VSS_NEXT;
746                 goto out;
747         }
748         mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
749         mmd->new_vss_status_flags |= VSS_REPOS;
750         mmd->new_vss_status_flags &= ~VSS_NEXT;
751         mmd->events++;
752 out:
753         mutex_unlock(mmd_mutex);
754         return ret;
755 }
756 EXPORT_SERVER_CMD_HANDLER(ff);
757
758 static int com_jmp(struct command_context *cc, struct lls_parse_result *lpr)
759 {
760         int i, ret;
761         char *errctx;
762
763         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
764         if (ret < 0) {
765                 send_errctx(cc, errctx);
766                 return ret;
767         }
768         if (sscanf(lls_input(0, lpr), "%d", &i) <= 0)
769                 return -ERRNO_TO_PARA_ERROR(EINVAL);
770         if (i < 0 || i > 100)
771                 return -ERRNO_TO_PARA_ERROR(EINVAL);
772         mutex_lock(mmd_mutex);
773         ret = -E_NO_AUDIO_FILE;
774         if (!mmd->afd.afhi.chunks_total)
775                 goto out;
776         PARA_INFO_LOG("jumping to %d%%\n", i);
777         mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50) / 100;
778         mmd->new_vss_status_flags |= VSS_REPOS;
779         mmd->new_vss_status_flags &= ~VSS_NEXT;
780         ret = 1;
781         mmd->events++;
782 out:
783         mutex_unlock(mmd_mutex);
784         return ret;
785 }
786 EXPORT_SERVER_CMD_HANDLER(jmp);
787
788 static void reset_signals(void)
789 {
790         para_sigaction(SIGCHLD, SIG_IGN);
791         para_sigaction(SIGINT, SIG_DFL);
792         para_sigaction(SIGTERM, SIG_DFL);
793         para_sigaction(SIGHUP, SIG_DFL);
794 }
795
796 struct connection_features {
797         bool sha256_requested; /* can be removed after 0.7.0 */
798 };
799
800 static int parse_auth_request(char *buf, int len, const struct user **u,
801                 struct connection_features *cf)
802 {
803         int ret;
804         char *p, *username, **features = NULL;
805         size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
806
807         *u = NULL;
808         memset(cf, 0, sizeof(*cf));
809         if (len < auth_rq_len + 2)
810                 return -E_AUTH_REQUEST;
811         if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
812                 return -E_AUTH_REQUEST;
813         username = buf + auth_rq_len;
814         p = strchr(username, ' ');
815         if (p) {
816                 int i;
817                 if (p == username)
818                         return -E_AUTH_REQUEST;
819                 *p = '\0';
820                 p++;
821                 create_argv(p, ",", &features);
822                 /*
823                  * Still accept sideband and AES feature requests (as a no-op)
824                  * because some 0.6.x clients request them. The two checks
825                  * below may be removed after 0.7.1.
826                  */
827                 for (i = 0; features[i]; i++) {
828                         if (strcmp(features[i], "sideband") == 0)
829                                 continue;
830                         if (strcmp(features[i], "aes_ctr128") == 0)
831                                 continue;
832                         /*
833                          * ->sha256_requested can go away after 0.7.0 but the
834                          * check has to stay until 0.9.0.
835                          */
836                         if (strcmp(features[i], "sha256") == 0)
837                                 cf->sha256_requested = true;
838                         else {
839                                 ret = -E_BAD_FEATURE;
840                                 goto out;
841                         }
842                 }
843         }
844         PARA_DEBUG_LOG("received auth request for user %s\n", username);
845         *u = user_list_lookup(username);
846         ret = 1;
847 out:
848         free_argv(features);
849         return ret;
850 }
851
852 #define HANDSHAKE_BUFSIZE 4096
853
854 static int run_command(struct command_context *cc, struct iovec *iov)
855 {
856         int ret, i, argc;
857         char *p, *end, **argv;
858         const struct lls_command *lcmd = NULL;
859         unsigned perms;
860         struct lls_parse_result *lpr;
861         char *errctx;
862
863         if (iov->iov_base == NULL || iov->iov_len == 0)
864                 return -ERRNO_TO_PARA_ERROR(EINVAL);
865         p = iov->iov_base;
866         p[iov->iov_len - 1] = '\0'; /* just to be sure */
867
868         ret = lls(lls_lookup_subcmd(p, server_cmd_suite, &errctx));
869         if (ret < 0) {
870                 send_errctx(cc, errctx);
871                 return ret;
872         }
873         perms = server_command_perms[ret];
874         if ((perms & cc->u->perms) != perms)
875                 return -ERRNO_TO_PARA_ERROR(EPERM);
876         lcmd = lls_cmd(ret, server_cmd_suite);
877         end = iov->iov_base + iov->iov_len;
878         for (i = 0; p < end; i++)
879                 p += strlen(p) + 1;
880         argc = i;
881         argv = arr_alloc(argc + 1, sizeof(char *));
882         for (i = 0, p = iov->iov_base; p < end; i++) {
883                 argv[i] = para_strdup(p);
884                 p += strlen(p) + 1;
885         }
886         argv[argc] = NULL;
887         PARA_NOTICE_LOG("calling com_%s() for user %s\n",
888                 lls_command_name(lcmd), cc->u->name);
889         ret = lls(lls_parse(argc, argv, lcmd, &lpr, &errctx));
890         if (ret >= 0) {
891                 const struct server_cmd_user_data *ud = lls_user_data(lcmd);
892                 ret = ud->handler(cc, lpr);
893                 lls_free_parse_result(lpr, lcmd);
894         } else
895                 send_errctx(cc, errctx);
896         free_argv(argv);
897         mutex_lock(mmd_mutex);
898         mmd->num_commands++;
899         if (ret >= 0 && (perms & AFS_WRITE))
900                 mmd->events++;
901         mutex_unlock(mmd_mutex);
902         return ret;
903 }
904
905 /**
906  * Perform user authentication and execute a command.
907  *
908  * \param fd The file descriptor to send output to.
909  *
910  * Whenever para_server accepts an incoming tcp connection on the port it
911  * listens on, it forks and the resulting child calls this function.
912  *
913  * An RSA-based challenge/response is used to authenticate the peer. If the
914  * authentication succeeds, a random session key is generated and sent back to
915  * the peer, encrypted with its RSA public key. From this point on, all
916  * transfers are encrypted with this session key using a stream cipher.
917  *
918  * Next it is checked if the peer supplied a valid server command or a command
919  * for the audio file selector. If yes, and if the user has sufficient
920  * permissions to execute this command, the function calls the corresponding
921  * command handler which performs argument checking and further processing.
922  *
923  * To cope with DOS attacks, a timer is set up right after the fork. If the
924  * connection was still not authenticated when the timeout expires, the child
925  * process is terminated.
926  *
927  * \return Standard.
928  *
929  * \sa alarm(2), \ref openssl.c, \ref crypt.h.
930  */
931 int handle_connect(int fd)
932 {
933         int ret;
934         unsigned char rand_buf[APC_CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
935         unsigned char challenge_hash[HASH2_SIZE];
936         char *command = NULL, *buf = alloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
937         size_t numbytes;
938         struct command_context cc_struct = {.u = NULL}, *cc = &cc_struct;
939         struct iovec iov;
940         struct connection_features cf;
941
942         cc->scc.fd = fd;
943         reset_signals();
944         /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
945         ret = mark_fd_blocking(fd);
946         if (ret < 0)
947                 goto net_err;
948         /* send Welcome message */
949         ret = write_va_buffer(fd, "This is para_server, version "
950                 PACKAGE_VERSION ".\n"
951                 "Features: sha256\n" /* no longer announce this after 0.8.0 */
952         );
953         if (ret < 0)
954                 goto net_err;
955         /* recv auth request line */
956         ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
957         if (ret < 0)
958                 goto net_err;
959         ret = parse_auth_request(buf, ret, &cc->u, &cf);
960         if (ret < 0)
961                 goto net_err;
962         if (cc->u) {
963                 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
964                 ret = apc_pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
965                         (unsigned char *)buf);
966                 if (ret < 0)
967                         goto net_err;
968                 numbytes = ret;
969         } else {
970                 /*
971                  * We don't want to reveal our user names, so we send a
972                  * challenge to the client even if the user does not exist, and
973                  * fail the authentication later.
974                  */
975                 numbytes = 256;
976                 get_random_bytes_or_die((unsigned char *)buf, numbytes);
977         }
978         PARA_DEBUG_LOG("sending %d byte challenge + session key (%zu bytes)\n",
979                 APC_CHALLENGE_SIZE, numbytes);
980         ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
981         buf = NULL;
982         if (ret < 0)
983                 goto net_err;
984         ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
985                 HANDSHAKE_BUFSIZE, &iov);
986         if (ret < 0)
987                 goto net_err;
988         buf = iov.iov_base;
989         numbytes = iov.iov_len;
990         PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
991         ret = -E_BAD_USER;
992         if (!cc->u)
993                 goto net_err;
994         /*
995          * The correct response is the hash of the first APC_CHALLENGE_SIZE bytes
996          * of the random data.
997          */
998         ret = -E_BAD_AUTH;
999         if (cf.sha256_requested) {
1000                 if (numbytes != HASH2_SIZE)
1001                         goto net_err;
1002                 hash2_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
1003                 if (memcmp(challenge_hash, buf, HASH2_SIZE))
1004                         goto net_err;
1005         } else { /* old client. This can be removed after 0.7.0 */
1006                 if (numbytes != HASH_SIZE)
1007                         goto net_err;
1008                 hash_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
1009                 if (memcmp(challenge_hash, buf, HASH_SIZE))
1010                         goto net_err;
1011         }
1012         /* auth successful */
1013         alarm(0);
1014         PARA_INFO_LOG("good auth for %s\n", cc->u->name);
1015         /* init stream cipher keys with the second part of the random buffer */
1016         cc->scc.recv = sc_new(rand_buf + APC_CHALLENGE_SIZE, SESSION_KEY_LEN);
1017         cc->scc.send = sc_new(rand_buf + APC_CHALLENGE_SIZE + SESSION_KEY_LEN,
1018                 SESSION_KEY_LEN);
1019         ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
1020         if (ret < 0)
1021                 goto net_err;
1022         ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
1023         if (ret < 0)
1024                 goto net_err;
1025         ret = run_command(cc, &iov);
1026         free(iov.iov_base);
1027         if (ret < 0)
1028                 goto err_out;
1029         if (ret >= 0)
1030                 goto out;
1031 err_out:
1032         if (send_strerror(cc, -ret) >= 0)
1033                 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
1034 net_err:
1035         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1036 out:
1037         free(buf);
1038         free(command);
1039         mutex_lock(mmd_mutex);
1040         mmd->active_connections--;
1041         mutex_unlock(mmd_mutex);
1042         if (ret >= 0) {
1043                 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1044                 if (ret < 0)
1045                         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1046         }
1047         sc_free(cc->scc.recv);
1048         sc_free(cc->scc.send);
1049         return ret;
1050 }