2 * This file is part of DisOrder.
3 * Copyright (C) 2004-2008 Richard Kettlewell
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #include "disorder-server.h"
22 # define NONCE_SIZE 16
26 # define CONFIRM_SIZE 10
29 int volume_left, volume_right; /* last known volume */
31 /** @brief Accept all well-formed login attempts
44 /** @brief Signature for line reader callback
47 * @return 0 if incomplete, 1 if complete
49 * @p line is 0-terminated and excludes the newline. It points into the
50 * input buffer so will become invalid shortly.
52 typedef int line_reader_type(struct conn *c,
55 /** @brief Signature for with-body command callbacks
57 * @param body List of body lines
58 * @param nbody Number of body lines
59 * @param u As passed to fetch_body()
60 * @return 0 to suspend input, 1 if complete
62 * The body strings are allocated (so survive indefinitely) and don't include
65 typedef int body_callback_type(struct conn *c,
70 /** @brief One client connection */
72 /** @brief Read commands from here */
74 /** @brief Send responses to here */
76 /** @brief Underlying file descriptor */
78 /** @brief Unique identifier for connection used in log messages */
80 /** @brief Login name or NULL */
82 /** @brief Event loop */
84 /** @brief Nonce chosen for this connection */
85 unsigned char nonce[NONCE_SIZE];
86 /** @brief Current reader callback
88 * We change this depending on whether we're servicing the @b log command
90 ev_reader_callback *reader;
91 /** @brief Event log output sending to this connection */
92 struct eventlog_output *lo;
93 /** @brief Parent listener */
94 const struct listener *l;
95 /** @brief Login cookie or NULL */
97 /** @brief Connection rights */
99 /** @brief Next connection */
101 /** @brief True if pending rescan had 'wait' set */
103 /** @brief Playlist that this connection locks */
104 const char *locked_playlist;
105 /** @brief When that playlist was locked */
107 /** @brief Line reader function */
108 line_reader_type *line_reader;
109 /** @brief Called when command body has been read */
110 body_callback_type *body_callback;
111 /** @brief Passed to @c body_callback */
113 /** @brief Accumulating body */
114 struct vector body[1];
117 /** @brief Linked list of connections */
118 static struct conn *connections;
120 static int reader_callback(ev_source *ev,
126 static int c_playlist_set_body(struct conn *c,
130 static int fetch_body(struct conn *c,
131 body_callback_type body_callback,
133 static int body_line(struct conn *c, char *line);
134 static int command(struct conn *c, char *line);
136 static const char *noyes[] = { "no", "yes" };
138 /** @brief Remove a connection from the connection list */
139 static void remove_connection(struct conn *c) {
142 for(cc = &connections; *cc && *cc != c; cc = &(*cc)->next)
148 /** @brief Called when a connection's writer fails or is shut down
150 * If the connection still has a raeder that is cancelled.
152 static int writer_error(ev_source attribute((unused)) *ev,
157 D(("server writer_error S%x %d", c->tag, errno_value));
158 if(errno_value == 0) {
160 D(("S%x writer completed", c->tag));
162 if(errno_value != EPIPE)
163 error(errno_value, "S%x write error on socket", c->tag);
165 D(("cancel reader"));
166 ev_reader_cancel(c->r);
169 D(("done cancel reader"));
173 remove_connection(c);
177 /** @brief Called when a conncetion's reader fails or is shut down
179 * If connection still has a writer then it is closed.
181 static int reader_error(ev_source attribute((unused)) *ev,
186 D(("server reader_error S%x %d", c->tag, errno_value));
187 error(errno_value, "S%x read error on socket", c->tag);
189 ev_writer_close(c->w);
193 remove_connection(c);
197 static int c_disable(struct conn *c, char **vec, int nvec) {
199 disable_playing(c->who);
200 else if(nvec == 1 && !strcmp(vec[0], "now"))
201 disable_playing(c->who);
203 sink_writes(ev_writer_sink(c->w), "550 invalid argument\n");
204 return 1; /* completed */
206 sink_writes(ev_writer_sink(c->w), "250 OK\n");
207 return 1; /* completed */
210 static int c_enable(struct conn *c,
211 char attribute((unused)) **vec,
212 int attribute((unused)) nvec) {
213 enable_playing(c->who, c->ev);
214 /* Enable implicitly unpauses if there is nothing playing */
215 if(paused && !playing) resume_playing(c->who);
216 sink_writes(ev_writer_sink(c->w), "250 OK\n");
217 return 1; /* completed */
220 static int c_enabled(struct conn *c,
221 char attribute((unused)) **vec,
222 int attribute((unused)) nvec) {
223 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[playing_is_enabled()]);
224 return 1; /* completed */
227 static int c_play(struct conn *c, char **vec,
228 int attribute((unused)) nvec) {
230 struct queue_entry *q;
232 if(!trackdb_exists(vec[0])) {
233 sink_writes(ev_writer_sink(c->w), "550 track is not in database\n");
236 if(!(track = trackdb_resolve(vec[0]))) {
237 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
240 q = queue_add(track, c->who, WHERE_BEFORE_RANDOM, origin_picked);
242 /* If we added the first track, and something is playing, then prepare the
243 * new track. If nothing is playing then we don't bother as it wouldn't gain
245 if(q == qhead.next && playing)
247 sink_printf(ev_writer_sink(c->w), "252 %s\n", q->id);
248 /* If the queue was empty but we are for some reason paused then
250 if(!playing) resume_playing(0);
252 return 1; /* completed */
255 static int c_remove(struct conn *c, char **vec,
256 int attribute((unused)) nvec) {
257 struct queue_entry *q;
259 if(!(q = queue_find(vec[0]))) {
260 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
263 if(!right_removable(c->rights, c->who, q)) {
264 error(0, "%s attempted remove but lacks required rights", c->who);
265 sink_writes(ev_writer_sink(c->w),
266 "510 Not authorized to remove that track\n");
269 queue_remove(q, c->who);
270 /* De-prepare the track. */
272 /* See about adding a new random track */
273 add_random_track(c->ev);
274 /* Prepare whatever the next head track is. */
275 if(qhead.next != &qhead)
276 prepare(c->ev, qhead.next);
278 sink_writes(ev_writer_sink(c->w), "250 removed\n");
279 return 1; /* completed */
282 static int c_scratch(struct conn *c,
286 sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
287 return 1; /* completed */
289 /* TODO there is a bug here: if we specify an ID but it's not the currently
290 * playing track then you will get 550 if you weren't authorized to scratch
291 * the currently playing track. */
292 if(!right_scratchable(c->rights, c->who, playing)) {
293 error(0, "%s attempted scratch but lacks required rights", c->who);
294 sink_writes(ev_writer_sink(c->w),
295 "510 Not authorized to scratch that track\n");
298 scratch(c->who, nvec == 1 ? vec[0] : 0);
299 /* If you scratch an unpaused track then it is automatically unpaused */
301 sink_writes(ev_writer_sink(c->w), "250 scratched\n");
302 return 1; /* completed */
305 static int c_pause(struct conn *c,
306 char attribute((unused)) **vec,
307 int attribute((unused)) nvec) {
309 sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
310 return 1; /* completed */
313 sink_writes(ev_writer_sink(c->w), "250 already paused\n");
314 return 1; /* completed */
316 if(pause_playing(c->who) < 0)
317 sink_writes(ev_writer_sink(c->w), "550 cannot pause this track\n");
319 sink_writes(ev_writer_sink(c->w), "250 paused\n");
323 static int c_resume(struct conn *c,
324 char attribute((unused)) **vec,
325 int attribute((unused)) nvec) {
327 sink_writes(ev_writer_sink(c->w), "250 not paused\n");
328 return 1; /* completed */
330 resume_playing(c->who);
331 sink_writes(ev_writer_sink(c->w), "250 paused\n");
335 static int c_shutdown(struct conn *c,
336 char attribute((unused)) **vec,
337 int attribute((unused)) nvec) {
338 info("S%x shut down by %s", c->tag, c->who);
339 sink_writes(ev_writer_sink(c->w), "250 shutting down\n");
340 ev_writer_flush(c->w);
344 static int c_reconfigure(struct conn *c,
345 char attribute((unused)) **vec,
346 int attribute((unused)) nvec) {
347 info("S%x reconfigure by %s", c->tag, c->who);
348 if(reconfigure(c->ev, 1))
349 sink_writes(ev_writer_sink(c->w), "550 error reading new config\n");
351 sink_writes(ev_writer_sink(c->w), "250 installed new config\n");
352 return 1; /* completed */
355 static void finished_rescan(void *ru) {
356 struct conn *const c = ru;
358 sink_writes(ev_writer_sink(c->w), "250 rescan completed\n");
359 /* Turn this connection back on */
360 ev_reader_enable(c->r);
363 static void start_fresh_rescan(void *ru) {
364 struct conn *const c = ru;
366 if(trackdb_rescan_underway()) {
367 /* Some other waiter beat us to it. However in this case we're happy to
368 * piggyback; the requirement is that a new rescan be started, not that it
369 * was _our_ rescan. */
371 /* We block until the rescan completes */
372 trackdb_add_rescanned(finished_rescan, c);
374 /* We report that the new rescan has started */
375 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
376 /* Turn this connection back on */
377 ev_reader_enable(c->r);
380 /* We are the first connection to get a callback so we must start a
383 /* We want to block until the new rescan completes */
384 trackdb_rescan(c->ev, 1/*check*/, finished_rescan, c);
386 /* We can report back immediately */
387 trackdb_rescan(c->ev, 1/*check*/, 0, 0);
388 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
389 /* Turn this connection back on */
390 ev_reader_enable(c->r);
395 static int c_rescan(struct conn *c,
398 int flag_wait = 0, flag_fresh = 0, n;
401 for(n = 0; n < nvec; ++n) {
402 if(!strcmp(vec[n], "wait"))
403 flag_wait = 1; /* wait for rescan to complete */
405 /* Currently disabled because untested (and hard to test). */
406 else if(!strcmp(vec[n], "fresh"))
407 flag_fresh = 1; /* don't piggyback underway rescan */
410 sink_writes(ev_writer_sink(c->w), "550 unknown flag\n");
411 return 1; /* completed */
414 /* Report what was requested */
415 info("S%x rescan by %s (%s %s)", c->tag, c->who,
416 flag_wait ? "wait" : "",
417 flag_fresh ? "fresh" : "");
418 if(trackdb_rescan_underway()) {
420 /* We want a fresh rescan but there is already one underway. Arrange a
421 * callback when it completes and then set off a new one. */
422 c->rescan_wait = flag_wait;
423 trackdb_add_rescanned(start_fresh_rescan, c);
427 sink_writes(ev_writer_sink(c->w), "250 rescan queued\n");
431 /* There's a rescan underway, and it's acceptable to piggyback on it */
433 /* We want to block until completion. */
434 trackdb_add_rescanned(finished_rescan, c);
437 /* We don't want to block. So we just report that things are in
439 sink_writes(ev_writer_sink(c->w), "250 rescan already underway\n");
444 /* No rescan is underway. fresh is therefore irrelevant. */
446 /* We want to block until completion */
447 trackdb_rescan(c->ev, 1/*check*/, finished_rescan, c);
450 /* We don't want to block. */
451 trackdb_rescan(c->ev, 1/*check*/, 0, 0);
452 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
453 return 1; /* completed */
458 static int c_version(struct conn *c,
459 char attribute((unused)) **vec,
460 int attribute((unused)) nvec) {
461 /* VERSION had better only use the basic character set */
462 sink_printf(ev_writer_sink(c->w), "251 %s\n", disorder_short_version_string);
463 return 1; /* completed */
466 static int c_playing(struct conn *c,
467 char attribute((unused)) **vec,
468 int attribute((unused)) nvec) {
470 queue_fix_sofar(playing);
471 playing->expected = 0;
472 sink_printf(ev_writer_sink(c->w), "252 %s\n", queue_marshall(playing));
474 sink_printf(ev_writer_sink(c->w), "259 nothing playing\n");
475 return 1; /* completed */
478 static const char *connection_host(struct conn *c) {
481 struct sockaddr_in in;
482 struct sockaddr_in6 in6;
488 /* get connection data */
490 if(getpeername(c->fd, &u.sa, &l) < 0) {
491 error(errno, "S%x error calling getpeername", c->tag);
494 if(c->l->pf != PF_UNIX) {
495 if((n = getnameinfo(&u.sa, l,
496 host, sizeof host, 0, 0, NI_NUMERICHOST))) {
497 error(0, "S%x error calling getnameinfo: %s", c->tag, gai_strerror(n));
500 return xstrdup(host);
505 static int c_user(struct conn *c,
507 int attribute((unused)) nvec) {
509 const char *res, *host, *password;
513 sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
516 /* get connection data */
517 if(!(host = connection_host(c))) {
518 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
522 k = trackdb_getuserinfo(vec[0]);
523 /* reject nonexistent users */
525 error(0, "S%x unknown user '%s' from %s", c->tag, vec[0], host);
526 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
529 /* reject unconfirmed users */
530 if(kvp_get(k, "confirmation")) {
531 error(0, "S%x unconfirmed user '%s' from %s", c->tag, vec[0], host);
532 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
535 password = kvp_get(k, "password");
536 if(!password) password = "";
537 if(parse_rights(kvp_get(k, "rights"), &rights, 1)) {
538 error(0, "error parsing rights for %s", vec[0]);
539 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
542 /* check whether the response is right */
543 res = authhash(c->nonce, sizeof c->nonce, password,
544 config->authorization_algorithm);
545 if(wideopen || (res && !strcmp(res, vec[1]))) {
548 /* currently we only bother logging remote connections */
549 if(strcmp(host, "local"))
550 info("S%x %s connected from %s", c->tag, vec[0], host);
552 c->rights |= RIGHT__LOCAL;
553 sink_writes(ev_writer_sink(c->w), "230 OK\n");
556 /* oops, response was wrong */
557 info("S%x authentication failure for %s from %s", c->tag, vec[0], host);
558 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
562 static int c_recent(struct conn *c,
563 char attribute((unused)) **vec,
564 int attribute((unused)) nvec) {
565 const struct queue_entry *q;
567 sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
568 for(q = phead.next; q != &phead; q = q->next)
569 sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
570 sink_writes(ev_writer_sink(c->w), ".\n");
571 return 1; /* completed */
574 static int c_queue(struct conn *c,
575 char attribute((unused)) **vec,
576 int attribute((unused)) nvec) {
577 struct queue_entry *q;
582 sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
583 if(playing_is_enabled() && !paused) {
585 queue_fix_sofar(playing);
586 if((l = trackdb_get(playing->track, "_length"))
587 && (length = atol(l))) {
589 when += length - playing->sofar + config->gap;
592 /* Nothing is playing but playing is enabled, so whatever is
593 * first in the queue can be expected to start immediately. */
596 for(q = qhead.next; q != &qhead; q = q->next) {
597 /* fill in estimated start time */
599 sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
600 /* update for next track */
602 if((l = trackdb_get(q->track, "_length"))
603 && (length = atol(l)))
604 when += length + config->gap;
609 sink_writes(ev_writer_sink(c->w), ".\n");
610 return 1; /* completed */
613 static int output_list(struct conn *c, char **vec) {
615 sink_printf(ev_writer_sink(c->w), "%s\n", *vec++);
616 sink_writes(ev_writer_sink(c->w), ".\n");
620 static int files_dirs(struct conn *c,
623 enum trackdb_listable what) {
624 const char *dir, *re, *errstr;
630 case 0: dir = 0; re = 0; break;
631 case 1: dir = vec[0]; re = 0; break;
632 case 2: dir = vec[0]; re = vec[1]; break;
635 /* A bit of a bodge to make sure the args don't trample on cache keys */
636 if(dir && strchr(dir, '\n')) {
637 sink_writes(ev_writer_sink(c->w), "550 invalid directory name\n");
640 if(re && strchr(re, '\n')) {
641 sink_writes(ev_writer_sink(c->w), "550 invalid regexp\n");
644 /* We bother eliminating "" because the web interface is relatively
645 * likely to send it */
647 byte_xasprintf(&key, "%d\n%s\n%s", (int)what, dir ? dir : "", re);
648 fvec = (char **)cache_get(&cache_files_type, key);
650 /* Got a cache hit, don't store the answer in the cache */
653 rec = 0; /* quieten compiler */
655 /* Cache miss, we'll do the lookup and key != 0 so we'll store the answer
657 if(!(rec = pcre_compile(re, PCRE_CASELESS|PCRE_UTF8,
658 &errstr, &erroffset, 0))) {
659 sink_printf(ev_writer_sink(c->w), "550 Error compiling regexp: %s\n",
663 /* It only counts as a miss if the regexp was valid. */
664 ++cache_files_misses;
667 /* No regexp, don't bother caching the result */
673 /* No cache hit (either because a miss, or because we did not look) so do
676 fvec = trackdb_list(dir, 0, what, rec);
678 fvec = trackdb_list(0, 0, what, rec);
681 /* Put the answer in the cache */
682 cache_put(&cache_files_type, key, fvec);
683 sink_writes(ev_writer_sink(c->w), "253 Listing follow\n");
684 return output_list(c, fvec);
687 static int c_files(struct conn *c,
690 return files_dirs(c, vec, nvec, trackdb_files);
693 static int c_dirs(struct conn *c,
696 return files_dirs(c, vec, nvec, trackdb_directories);
699 static int c_allfiles(struct conn *c,
702 return files_dirs(c, vec, nvec, trackdb_directories|trackdb_files);
705 static int c_get(struct conn *c,
707 int attribute((unused)) nvec) {
708 const char *v, *track;
710 if(!(track = trackdb_resolve(vec[0]))) {
711 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
714 if(vec[1][0] != '_' && (v = trackdb_get(track, vec[1])))
715 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
717 sink_writes(ev_writer_sink(c->w), "555 not found\n");
721 static int c_length(struct conn *c,
723 int attribute((unused)) nvec) {
724 const char *track, *v;
726 if(!(track = trackdb_resolve(vec[0]))) {
727 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
730 if((v = trackdb_get(track, "_length")))
731 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
733 sink_writes(ev_writer_sink(c->w), "550 not found\n");
737 static int c_set(struct conn *c,
739 int attribute((unused)) nvec) {
742 if(!(track = trackdb_resolve(vec[0]))) {
743 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
746 if(vec[1][0] != '_' && !trackdb_set(track, vec[1], vec[2]))
747 sink_writes(ev_writer_sink(c->w), "250 OK\n");
749 sink_writes(ev_writer_sink(c->w), "550 not found\n");
753 static int c_prefs(struct conn *c,
755 int attribute((unused)) nvec) {
759 if(!(track = trackdb_resolve(vec[0]))) {
760 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
763 k = trackdb_get_all(track);
764 sink_writes(ev_writer_sink(c->w), "253 prefs follow\n");
765 for(; k; k = k->next)
766 if(k->name[0] != '_') /* omit internal values */
767 sink_printf(ev_writer_sink(c->w),
768 " %s %s\n", quoteutf8(k->name), quoteutf8(k->value));
769 sink_writes(ev_writer_sink(c->w), ".\n");
773 static int c_exists(struct conn *c,
775 int attribute((unused)) nvec) {
776 /* trackdb_exists() does its own alias checking */
777 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[trackdb_exists(vec[0])]);
781 static void search_parse_error(const char *msg, void *u) {
782 *(const char **)u = msg;
785 static int c_search(struct conn *c,
787 int attribute((unused)) nvec) {
788 char **terms, **results;
789 int nterms, nresults, n;
790 const char *e = "unknown error";
792 /* This is a bit of a bodge. Initially it's there to make the eclient
793 * interface a bit more convenient to add searching to, but it has the more
794 * compelling advantage that if everything uses it, then interpretation of
795 * user-supplied search strings will be the same everywhere. */
796 if(!(terms = split(vec[0], &nterms, SPLIT_QUOTES, search_parse_error, &e))) {
797 sink_printf(ev_writer_sink(c->w), "550 %s\n", e);
799 results = trackdb_search(terms, nterms, &nresults);
800 sink_printf(ev_writer_sink(c->w), "253 %d matches\n", nresults);
801 for(n = 0; n < nresults; ++n)
802 sink_printf(ev_writer_sink(c->w), "%s\n", results[n]);
803 sink_writes(ev_writer_sink(c->w), ".\n");
808 static int c_random_enable(struct conn *c,
809 char attribute((unused)) **vec,
810 int attribute((unused)) nvec) {
811 enable_random(c->who, c->ev);
812 /* Enable implicitly unpauses if there is nothing playing */
813 if(paused && !playing) resume_playing(c->who);
814 sink_writes(ev_writer_sink(c->w), "250 OK\n");
815 return 1; /* completed */
818 static int c_random_disable(struct conn *c,
819 char attribute((unused)) **vec,
820 int attribute((unused)) nvec) {
821 disable_random(c->who);
822 sink_writes(ev_writer_sink(c->w), "250 OK\n");
823 return 1; /* completed */
826 static int c_random_enabled(struct conn *c,
827 char attribute((unused)) **vec,
828 int attribute((unused)) nvec) {
829 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[random_is_enabled()]);
830 return 1; /* completed */
833 static void got_stats(char *stats, void *u) {
834 struct conn *const c = u;
836 sink_printf(ev_writer_sink(c->w), "253 stats\n%s\n.\n", stats);
837 /* Now we can start processing commands again */
838 ev_reader_enable(c->r);
841 static int c_stats(struct conn *c,
842 char attribute((unused)) **vec,
843 int attribute((unused)) nvec) {
844 trackdb_stats_subprocess(c->ev, got_stats, c);
845 return 0; /* not yet complete */
848 static int c_volume(struct conn *c,
860 l = r = atoi(vec[0]);
871 rights = set ? RIGHT_VOLUME : RIGHT_READ;
872 if(!(c->rights & rights)) {
873 error(0, "%s attempted to set volume but lacks required rights", c->who);
874 sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
877 if(mixer_control(-1/*as configured*/, &l, &r, set))
878 sink_writes(ev_writer_sink(c->w), "550 error accessing mixer\n");
880 sink_printf(ev_writer_sink(c->w), "252 %d %d\n", l, r);
881 if(l != volume_left || r != volume_right) {
884 snprintf(lb, sizeof lb, "%d", l);
885 snprintf(rb, sizeof rb, "%d", r);
886 eventlog("volume", lb, rb, (char *)0);
892 /** @brief Called when data arrives on a log connection
894 * We just discard all such data. The client may occasionally send data as a
897 static int logging_reader_callback(ev_source attribute((unused)) *ev,
899 void attribute((unused)) *ptr,
901 int attribute((unused)) eof,
902 void attribute((unused)) *u) {
905 ev_reader_consume(reader, bytes);
907 /* Oops, that's all for now */
908 D(("logging reader eof"));
911 ev_writer_close(c->w);
915 remove_connection(c);
920 static void logclient(const char *msg, void *user) {
921 struct conn *c = user;
924 /* This connection has gone up in smoke for some reason */
925 eventlog_remove(c->lo);
929 /* user_* messages are restricted */
930 if(!strncmp(msg, "user_", 5)) {
931 /* They are only sent to admin users */
932 if(!(c->rights & RIGHT_ADMIN))
934 /* They are not sent over TCP connections unless remote user-management is
936 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL))
939 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" %s\n",
940 (uintmax_t)time(0), msg);
943 static int c_log(struct conn *c,
944 char attribute((unused)) **vec,
945 int attribute((unused)) nvec) {
948 sink_writes(ev_writer_sink(c->w), "254 OK\n");
949 /* pump out initial state */
951 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
953 playing_is_enabled() ? "enable_play" : "disable_play");
954 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
956 random_is_enabled() ? "enable_random" : "disable_random");
957 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
959 paused ? "pause" : "resume");
961 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state playing\n",
964 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" volume %d %d\n",
965 (uintmax_t)now, volume_left, volume_right);
966 c->lo = xmalloc(sizeof *c->lo);
967 c->lo->fn = logclient;
970 c->reader = logging_reader_callback;
974 /** @brief Test whether a move is allowed
975 * @param c Connection
976 * @param qs List of IDs on queue
977 * @param nqs Number of IDs
978 * @return 0 if move is prohibited, non-0 if it is allowed
980 static int has_move_rights(struct conn *c, struct queue_entry **qs, int nqs) {
981 for(; nqs > 0; ++qs, --nqs) {
982 struct queue_entry *const q = *qs;
984 if(!right_movable(c->rights, c->who, q))
990 static int c_move(struct conn *c,
992 int attribute((unused)) nvec) {
993 struct queue_entry *q;
996 if(!(q = queue_find(vec[0]))) {
997 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1000 if(!has_move_rights(c, &q, 1)) {
1001 error(0, "%s attempted move but lacks required rights", c->who);
1002 sink_writes(ev_writer_sink(c->w),
1003 "510 Not authorized to move that track\n");
1006 n = queue_move(q, atoi(vec[1]), c->who);
1007 sink_printf(ev_writer_sink(c->w), "252 %d\n", n);
1008 /* If we've moved to the head of the queue then prepare the track. */
1014 static int c_moveafter(struct conn *c,
1016 int attribute((unused)) nvec) {
1017 struct queue_entry *q, **qs;
1021 if(!(q = queue_find(vec[0]))) {
1022 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1029 qs = xcalloc(nvec, sizeof *qs);
1030 for(n = 0; n < nvec; ++n)
1031 if(!(qs[n] = queue_find(vec[n]))) {
1032 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1035 if(!has_move_rights(c, qs, nvec)) {
1036 error(0, "%s attempted moveafter but lacks required rights", c->who);
1037 sink_writes(ev_writer_sink(c->w),
1038 "510 Not authorized to move those tracks\n");
1041 queue_moveafter(q, nvec, qs, c->who);
1042 sink_printf(ev_writer_sink(c->w), "250 Moved tracks\n");
1043 /* If we've moved to the head of the queue then prepare the track. */
1049 static int c_part(struct conn *c,
1051 int attribute((unused)) nvec) {
1054 if(!(track = trackdb_resolve(vec[0]))) {
1055 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1058 sink_printf(ev_writer_sink(c->w), "252 %s\n",
1059 quoteutf8(trackdb_getpart(track, vec[1], vec[2])));
1063 static int c_resolve(struct conn *c,
1065 int attribute((unused)) nvec) {
1068 if(!(track = trackdb_resolve(vec[0]))) {
1069 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1072 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(track));
1076 static int list_response(struct conn *c,
1079 sink_printf(ev_writer_sink(c->w), "253 %s\n", reply);
1081 sink_printf(ev_writer_sink(c->w), "%s%s\n",
1082 **list == '.' ? "." : "", *list);
1085 sink_writes(ev_writer_sink(c->w), ".\n");
1086 return 1; /* completed */
1089 static int c_tags(struct conn *c,
1090 char attribute((unused)) **vec,
1091 int attribute((unused)) nvec) {
1092 return list_response(c, "Tag list follows", trackdb_alltags());
1095 static int c_set_global(struct conn *c,
1097 int attribute((unused)) nvec) {
1098 if(vec[0][0] == '_') {
1099 sink_writes(ev_writer_sink(c->w), "550 cannot set internal global preferences\n");
1102 trackdb_set_global(vec[0], vec[1], c->who);
1103 sink_printf(ev_writer_sink(c->w), "250 OK\n");
1107 static int c_get_global(struct conn *c,
1109 int attribute((unused)) nvec) {
1110 const char *s = trackdb_get_global(vec[0]);
1113 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(s));
1115 sink_writes(ev_writer_sink(c->w), "555 not found\n");
1119 static int c_nop(struct conn *c,
1120 char attribute((unused)) **vec,
1121 int attribute((unused)) nvec) {
1122 sink_printf(ev_writer_sink(c->w), "250 Quack\n");
1126 static int c_new(struct conn *c,
1136 if(max <= 0 || max > config->new_max)
1137 max = config->new_max;
1138 tracks = trackdb_new(0, max);
1139 sink_printf(ev_writer_sink(c->w), "253 New track list follows\n");
1142 sink_printf(ev_writer_sink(c->w), "%s%s\n",
1143 **tracks == '.' ? "." : "", *tracks);
1146 sink_writes(ev_writer_sink(c->w), ".\n");
1147 return 1; /* completed */
1151 static int c_rtp_address(struct conn *c,
1152 char attribute((unused)) **vec,
1153 int attribute((unused)) nvec) {
1154 if(config->api == BACKEND_NETWORK) {
1155 sink_printf(ev_writer_sink(c->w), "252 %s %s\n",
1156 quoteutf8(config->broadcast.s[0]),
1157 quoteutf8(config->broadcast.s[1]));
1159 sink_writes(ev_writer_sink(c->w), "550 No RTP\n");
1163 static int c_cookie(struct conn *c,
1165 int attribute((unused)) nvec) {
1170 /* Can't log in twice on the same connection */
1172 sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
1175 /* Get some kind of peer identifcation */
1176 if(!(host = connection_host(c))) {
1177 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1180 /* Check the cookie */
1181 user = verify_cookie(vec[0], &rights);
1183 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1190 if(strcmp(host, "local"))
1191 info("S%x %s connected with cookie from %s", c->tag, user, host);
1193 c->rights |= RIGHT__LOCAL;
1194 /* Response contains username so client knows who they are acting as */
1195 sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
1199 static int c_make_cookie(struct conn *c,
1200 char attribute((unused)) **vec,
1201 int attribute((unused)) nvec) {
1202 const char *cookie = make_cookie(c->who);
1205 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cookie));
1207 sink_writes(ev_writer_sink(c->w), "550 Cannot create cookie\n");
1211 static int c_revoke(struct conn *c,
1212 char attribute((unused)) **vec,
1213 int attribute((unused)) nvec) {
1215 revoke_cookie(c->cookie);
1216 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1218 sink_writes(ev_writer_sink(c->w), "550 Did not log in with cookie\n");
1222 static int c_adduser(struct conn *c,
1227 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1228 error(0, "S%x: remote adduser", c->tag);
1229 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1234 if(parse_rights(vec[2], 0, 1)) {
1235 sink_writes(ev_writer_sink(c->w), "550 Invalid rights list\n");
1239 rights = config->default_rights;
1240 if(trackdb_adduser(vec[0], vec[1], rights,
1241 0/*email*/, 0/*confirmation*/))
1242 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1244 sink_writes(ev_writer_sink(c->w), "250 User created\n");
1248 static int c_deluser(struct conn *c,
1250 int attribute((unused)) nvec) {
1253 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1254 error(0, "S%x: remote deluser", c->tag);
1255 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1258 if(trackdb_deluser(vec[0])) {
1259 sink_writes(ev_writer_sink(c->w), "550 Cannot delete user\n");
1262 /* Zap connections belonging to deleted user */
1263 for(d = connections; d; d = d->next)
1264 if(!strcmp(d->who, vec[0]))
1266 sink_writes(ev_writer_sink(c->w), "250 User deleted\n");
1270 static int c_edituser(struct conn *c,
1272 int attribute((unused)) nvec) {
1275 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1276 error(0, "S%x: remote edituser", c->tag);
1277 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1280 /* RIGHT_ADMIN can do anything; otherwise you can only set your own email
1281 * address and password. */
1282 if((c->rights & RIGHT_ADMIN)
1283 || (!strcmp(c->who, vec[0])
1284 && (!strcmp(vec[1], "email")
1285 || !strcmp(vec[1], "password")))) {
1286 if(trackdb_edituserinfo(vec[0], vec[1], vec[2])) {
1287 sink_writes(ev_writer_sink(c->w), "550 Failed to change setting\n");
1290 if(!strcmp(vec[1], "password")) {
1291 /* Zap all connections for this user after a password change */
1292 for(d = connections; d; d = d->next)
1293 if(!strcmp(d->who, vec[0]))
1295 } else if(!strcmp(vec[1], "rights")) {
1296 /* Update rights for this user */
1299 if(!parse_rights(vec[2], &r, 1)) {
1300 const char *new_rights = rights_string(r);
1301 for(d = connections; d; d = d->next) {
1302 if(!strcmp(d->who, vec[0])) {
1305 /* Notify any log connections */
1307 sink_printf(ev_writer_sink(d->w),
1308 "%"PRIxMAX" rights_changed %s\n",
1310 quoteutf8(new_rights));
1315 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1317 error(0, "%s attempted edituser but lacks required rights", c->who);
1318 sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
1323 static int c_userinfo(struct conn *c,
1324 char attribute((unused)) **vec,
1325 int attribute((unused)) nvec) {
1329 /* We allow remote querying of rights so that clients can figure out what
1330 * they're allowed to do */
1331 if(!config->remote_userman
1332 && !(c->rights & RIGHT__LOCAL)
1333 && strcmp(vec[1], "rights")) {
1334 error(0, "S%x: remote userinfo %s %s", c->tag, vec[0], vec[1]);
1335 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1338 /* RIGHT_ADMIN allows anything; otherwise you can only get your own email
1339 * address and rights list. */
1340 if((c->rights & RIGHT_ADMIN)
1341 || (!strcmp(c->who, vec[0])
1342 && (!strcmp(vec[1], "email")
1343 || !strcmp(vec[1], "rights")))) {
1344 if((k = trackdb_getuserinfo(vec[0])))
1345 if((value = kvp_get(k, vec[1])))
1346 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(value));
1348 sink_writes(ev_writer_sink(c->w), "555 Not set\n");
1350 sink_writes(ev_writer_sink(c->w), "550 No such user\n");
1352 error(0, "%s attempted userinfo but lacks required rights", c->who);
1353 sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
1358 static int c_users(struct conn *c,
1359 char attribute((unused)) **vec,
1360 int attribute((unused)) nvec) {
1361 return list_response(c, "User list follows", trackdb_listusers());
1364 /** @brief Base64 mapping table for confirmation strings
1366 * This is used with generic_to_base64() and generic_base64(). We cannot use
1367 * the MIME table as that contains '+' and '=' which get quoted when
1368 * URL-encoding. (The CGI still does the URL encoding but it is desirable to
1369 * avoid it being necessary.)
1371 static const char confirm_base64_table[] =
1372 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/.*";
1374 static int c_register(struct conn *c,
1376 int attribute((unused)) nvec) {
1381 /* The confirmation string is base64(username;nonce) */
1382 bufsize = strlen(vec[0]) + CONFIRM_SIZE + 2;
1383 buf = xmalloc_noptr(bufsize);
1384 offset = byte_snprintf(buf, bufsize, "%s;", vec[0]);
1385 gcry_randomize(buf + offset, CONFIRM_SIZE, GCRY_STRONG_RANDOM);
1386 cs = generic_to_base64((uint8_t *)buf, offset + CONFIRM_SIZE,
1387 confirm_base64_table);
1388 if(trackdb_adduser(vec[0], vec[1], config->default_rights, vec[2], cs))
1389 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1391 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cs));
1395 static int c_confirm(struct conn *c,
1397 int attribute((unused)) nvec) {
1403 /* Get some kind of peer identifcation */
1404 if(!(host = connection_host(c))) {
1405 sink_writes(ev_writer_sink(c->w), "530 Authentication failure\n");
1408 if(!(user = generic_base64(vec[0], &nuser, confirm_base64_table))
1409 || !(sep = memchr(user, ';', nuser))) {
1410 sink_writes(ev_writer_sink(c->w), "550 Malformed confirmation string\n");
1414 if(trackdb_confirm(user, vec[0], &rights))
1415 sink_writes(ev_writer_sink(c->w), "550 Incorrect confirmation string\n");
1420 if(strcmp(host, "local"))
1421 info("S%x %s confirmed from %s", c->tag, user, host);
1423 c->rights |= RIGHT__LOCAL;
1424 /* Response contains username so client knows who they are acting as */
1425 sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
1430 static int sent_reminder(ev_source attribute((unused)) *ev,
1431 pid_t attribute((unused)) pid,
1433 const struct rusage attribute((unused)) *rusage,
1435 struct conn *const c = u;
1437 /* Tell the client what went down */
1439 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1441 error(0, "reminder subprocess %s", wstat(status));
1442 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1444 /* Re-enable this connection */
1445 ev_reader_enable(c->r);
1449 static int c_reminder(struct conn *c,
1451 int attribute((unused)) nvec) {
1453 const char *password, *email, *text, *encoding, *charset, *content_type;
1458 static hash *last_reminder;
1460 if(!config->mail_sender) {
1461 error(0, "cannot send password reminders because mail_sender not set");
1462 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1465 if(!(k = trackdb_getuserinfo(vec[0]))) {
1466 error(0, "reminder for user '%s' who does not exist", vec[0]);
1467 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1470 if(!(email = kvp_get(k, "email"))
1471 || !email_valid(email)) {
1472 error(0, "user '%s' has no valid email address", vec[0]);
1473 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1476 if(!(password = kvp_get(k, "password"))
1478 error(0, "user '%s' has no password", vec[0]);
1479 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1482 /* Rate-limit reminders. This hash is bounded in size by the number of
1483 * users. If this is actually a problem for anyone then we can periodically
1486 last_reminder = hash_new(sizeof (time_t));
1487 last = hash_find(last_reminder, vec[0]);
1489 if(last && now < *last + config->reminder_interval) {
1490 error(0, "sent a password reminder to '%s' too recently", vec[0]);
1491 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1494 /* Send the reminder */
1495 /* TODO this should be templatized and to some extent merged with
1496 * the code in act_register() */
1497 byte_xasprintf((char **)&text,
1498 "Someone requested that you be sent a reminder of your DisOrder password.\n"
1499 "Your password is:\n"
1502 if(!(text = mime_encode_text(text, &charset, &encoding)))
1503 fatal(0, "cannot encode email");
1504 byte_xasprintf((char **)&content_type, "text/plain;charset=%s",
1505 quote822(charset, 0));
1506 pid = sendmail_subprocess("", config->mail_sender, email,
1507 "DisOrder password reminder",
1508 encoding, content_type, text);
1510 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1513 hash_add(last_reminder, vec[0], &now, HASH_INSERT_OR_REPLACE);
1514 info("sending a passsword reminder to user '%s'", vec[0]);
1515 /* We can only continue when the subprocess finishes */
1516 ev_child(c->ev, pid, 0, sent_reminder, c);
1520 static int c_schedule_list(struct conn *c,
1521 char attribute((unused)) **vec,
1522 int attribute((unused)) nvec) {
1523 char **ids = schedule_list(0);
1524 sink_writes(ev_writer_sink(c->w), "253 ID list follows\n");
1526 sink_printf(ev_writer_sink(c->w), "%s\n", *ids++);
1527 sink_writes(ev_writer_sink(c->w), ".\n");
1528 return 1; /* completed */
1531 static int c_schedule_get(struct conn *c,
1533 int attribute((unused)) nvec) {
1534 struct kvp *actiondata = schedule_get(vec[0]), *k;
1537 sink_writes(ev_writer_sink(c->w), "555 No such event\n");
1538 return 1; /* completed */
1540 /* Scheduled events are public information. Anyone with RIGHT_READ can see
1542 sink_writes(ev_writer_sink(c->w), "253 Event information follows\n");
1543 for(k = actiondata; k; k = k->next)
1544 sink_printf(ev_writer_sink(c->w), " %s %s\n",
1545 quoteutf8(k->name), quoteutf8(k->value));
1546 sink_writes(ev_writer_sink(c->w), ".\n");
1547 return 1; /* completed */
1550 static int c_schedule_del(struct conn *c,
1552 int attribute((unused)) nvec) {
1553 struct kvp *actiondata = schedule_get(vec[0]);
1556 sink_writes(ev_writer_sink(c->w), "555 No such event\n");
1557 return 1; /* completed */
1559 /* If you have admin rights you can delete anything. If you don't then you
1560 * can only delete your own scheduled events. */
1561 if(!(c->rights & RIGHT_ADMIN)) {
1562 const char *who = kvp_get(actiondata, "who");
1564 if(!who || !c->who || strcmp(who, c->who)) {
1565 sink_writes(ev_writer_sink(c->w), "551 Not authorized\n");
1566 return 1; /* completed */
1569 if(schedule_del(vec[0]))
1570 sink_writes(ev_writer_sink(c->w), "550 Could not delete scheduled event\n");
1572 sink_writes(ev_writer_sink(c->w), "250 Deleted\n");
1573 return 1; /* completed */
1576 static int c_schedule_add(struct conn *c,
1579 struct kvp *actiondata = 0;
1582 /* Standard fields */
1583 kvp_set(&actiondata, "who", c->who);
1584 kvp_set(&actiondata, "when", vec[0]);
1585 kvp_set(&actiondata, "priority", vec[1]);
1586 kvp_set(&actiondata, "action", vec[2]);
1587 /* Action-dependent fields */
1588 if(!strcmp(vec[2], "play")) {
1590 sink_writes(ev_writer_sink(c->w), "550 Wrong number of arguments\n");
1593 if(!trackdb_exists(vec[3])) {
1594 sink_writes(ev_writer_sink(c->w), "550 Track is not in database\n");
1597 kvp_set(&actiondata, "track", vec[3]);
1598 } else if(!strcmp(vec[2], "set-global")) {
1599 if(nvec < 4 || nvec > 5) {
1600 sink_writes(ev_writer_sink(c->w), "550 Wrong number of arguments\n");
1603 kvp_set(&actiondata, "key", vec[3]);
1605 kvp_set(&actiondata, "value", vec[4]);
1607 sink_writes(ev_writer_sink(c->w), "550 Unknown action\n");
1610 /* schedule_add() checks user rights */
1611 id = schedule_add(c->ev, actiondata);
1613 sink_writes(ev_writer_sink(c->w), "550 Cannot add scheduled event\n");
1615 sink_printf(ev_writer_sink(c->w), "252 %s\n", id);
1619 static int c_adopt(struct conn *c,
1621 int attribute((unused)) nvec) {
1622 struct queue_entry *q;
1625 sink_writes(ev_writer_sink(c->w), "550 no identity\n");
1628 if(!(q = queue_find(vec[0]))) {
1629 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1632 if(q->origin != origin_random) {
1633 sink_writes(ev_writer_sink(c->w), "550 not a random track\n");
1636 q->origin = origin_adopted;
1637 q->submitter = xstrdup(c->who);
1638 eventlog("adopted", q->id, q->submitter, (char *)0);
1640 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1644 static int playlist_response(struct conn *c,
1648 assert(!"cannot cope with success");
1650 sink_writes(ev_writer_sink(c->w), "550 Access denied\n");
1653 sink_writes(ev_writer_sink(c->w), "550 Invalid playlist name\n");
1656 sink_writes(ev_writer_sink(c->w), "555 No such playlist\n");
1659 sink_writes(ev_writer_sink(c->w), "550 Error accessing playlist\n");
1665 static int c_playlist_get(struct conn *c,
1667 int attribute((unused)) nvec) {
1671 if(!(err = trackdb_playlist_get(vec[0], c->who, &tracks, 0, 0)))
1672 return list_response(c, "Playlist contents follows", tracks);
1674 return playlist_response(c, err);
1677 static int c_playlist_set(struct conn *c,
1679 int attribute((unused)) nvec) {
1680 return fetch_body(c, c_playlist_set_body, vec[0]);
1683 static int c_playlist_set_body(struct conn *c,
1687 const char *playlist = u;
1690 if(!c->locked_playlist
1691 || strcmp(playlist, c->locked_playlist)) {
1692 sink_writes(ev_writer_sink(c->w), "550 Playlist is not locked\n");
1695 if(!(err = trackdb_playlist_set(playlist, c->who,
1697 sink_printf(ev_writer_sink(c->w), "250 OK\n");
1700 return playlist_response(c, err);
1703 static int c_playlist_get_share(struct conn *c,
1705 int attribute((unused)) nvec) {
1709 if(!(err = trackdb_playlist_get(vec[0], c->who, 0, 0, &share))) {
1710 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(share));
1713 return playlist_response(c, err);
1716 static int c_playlist_set_share(struct conn *c,
1718 int attribute((unused)) nvec) {
1721 if(!(err = trackdb_playlist_set(vec[0], c->who, 0, 0, vec[1]))) {
1722 sink_printf(ev_writer_sink(c->w), "250 OK\n");
1725 return playlist_response(c, err);
1728 static int c_playlists(struct conn *c,
1729 char attribute((unused)) **vec,
1730 int attribute((unused)) nvec) {
1733 trackdb_playlist_list(c->who, &p, 0);
1734 return list_response(c, "List of playlists follows", p);
1737 static int c_playlist_delete(struct conn *c,
1739 int attribute((unused)) nvec) {
1742 if(!(err = trackdb_playlist_delete(vec[0], c->who))) {
1743 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1746 return playlist_response(c, err);
1749 static int c_playlist_lock(struct conn *c,
1751 int attribute((unused)) nvec) {
1755 /* Check we're allowed to modify this playlist */
1756 if((err = trackdb_playlist_set(vec[0], c->who, 0, 0, 0)))
1757 return playlist_response(c, err);
1758 /* If we hold a lock don't allow a new one */
1759 if(c->locked_playlist) {
1760 sink_writes(ev_writer_sink(c->w), "550 Already holding a lock\n");
1763 /* See if some other connection locks the same playlist */
1764 for(cc = connections; cc; cc = cc->next)
1765 if(cc->locked_playlist && !strcmp(cc->locked_playlist, vec[0]))
1768 /* TODO: implement config->playlist_lock_timeout */
1769 sink_writes(ev_writer_sink(c->w), "550 Already locked\n");
1772 c->locked_playlist = xstrdup(vec[0]);
1773 time(&c->locked_when);
1774 sink_writes(ev_writer_sink(c->w), "250 Acquired lock\n");
1778 static int c_playlist_unlock(struct conn *c,
1779 char attribute((unused)) **vec,
1780 int attribute((unused)) nvec) {
1781 if(!c->locked_playlist) {
1782 sink_writes(ev_writer_sink(c->w), "550 Not holding a lock\n");
1785 c->locked_playlist = 0;
1786 sink_writes(ev_writer_sink(c->w), "250 Released lock\n");
1790 static const struct command {
1791 /** @brief Command name */
1794 /** @brief Minimum number of arguments */
1797 /** @brief Maximum number of arguments */
1800 /** @brief Function to process command */
1801 int (*fn)(struct conn *, char **, int);
1803 /** @brief Rights required to execute command
1805 * 0 means that the command can be issued without logging in. If multiple
1806 * bits are listed here any of those rights will do.
1810 { "adduser", 2, 3, c_adduser, RIGHT_ADMIN|RIGHT__LOCAL },
1811 { "adopt", 1, 1, c_adopt, RIGHT_PLAY },
1812 { "allfiles", 0, 2, c_allfiles, RIGHT_READ },
1813 { "confirm", 1, 1, c_confirm, 0 },
1814 { "cookie", 1, 1, c_cookie, 0 },
1815 { "deluser", 1, 1, c_deluser, RIGHT_ADMIN|RIGHT__LOCAL },
1816 { "dirs", 0, 2, c_dirs, RIGHT_READ },
1817 { "disable", 0, 1, c_disable, RIGHT_GLOBAL_PREFS },
1818 { "edituser", 3, 3, c_edituser, RIGHT_ADMIN|RIGHT_USERINFO },
1819 { "enable", 0, 0, c_enable, RIGHT_GLOBAL_PREFS },
1820 { "enabled", 0, 0, c_enabled, RIGHT_READ },
1821 { "exists", 1, 1, c_exists, RIGHT_READ },
1822 { "files", 0, 2, c_files, RIGHT_READ },
1823 { "get", 2, 2, c_get, RIGHT_READ },
1824 { "get-global", 1, 1, c_get_global, RIGHT_READ },
1825 { "length", 1, 1, c_length, RIGHT_READ },
1826 { "log", 0, 0, c_log, RIGHT_READ },
1827 { "make-cookie", 0, 0, c_make_cookie, RIGHT_READ },
1828 { "move", 2, 2, c_move, RIGHT_MOVE__MASK },
1829 { "moveafter", 1, INT_MAX, c_moveafter, RIGHT_MOVE__MASK },
1830 { "new", 0, 1, c_new, RIGHT_READ },
1831 { "nop", 0, 0, c_nop, 0 },
1832 { "part", 3, 3, c_part, RIGHT_READ },
1833 { "pause", 0, 0, c_pause, RIGHT_PAUSE },
1834 { "play", 1, 1, c_play, RIGHT_PLAY },
1835 { "playing", 0, 0, c_playing, RIGHT_READ },
1836 { "playlist-delete", 1, 1, c_playlist_delete, RIGHT_PLAY },
1837 { "playlist-get", 1, 1, c_playlist_get, RIGHT_READ },
1838 { "playlist-get-share", 1, 1, c_playlist_get_share, RIGHT_READ },
1839 { "playlist-lock", 1, 1, c_playlist_lock, RIGHT_PLAY },
1840 { "playlist-set", 1, 1, c_playlist_set, RIGHT_PLAY },
1841 { "playlist-set-share", 2, 2, c_playlist_set_share, RIGHT_PLAY },
1842 { "playlist-unlock", 0, 0, c_playlist_unlock, RIGHT_PLAY },
1843 { "playlists", 0, 0, c_playlists, RIGHT_READ },
1844 { "prefs", 1, 1, c_prefs, RIGHT_READ },
1845 { "queue", 0, 0, c_queue, RIGHT_READ },
1846 { "random-disable", 0, 0, c_random_disable, RIGHT_GLOBAL_PREFS },
1847 { "random-enable", 0, 0, c_random_enable, RIGHT_GLOBAL_PREFS },
1848 { "random-enabled", 0, 0, c_random_enabled, RIGHT_READ },
1849 { "recent", 0, 0, c_recent, RIGHT_READ },
1850 { "reconfigure", 0, 0, c_reconfigure, RIGHT_ADMIN },
1851 { "register", 3, 3, c_register, RIGHT_REGISTER|RIGHT__LOCAL },
1852 { "reminder", 1, 1, c_reminder, RIGHT__LOCAL },
1853 { "remove", 1, 1, c_remove, RIGHT_REMOVE__MASK },
1854 { "rescan", 0, INT_MAX, c_rescan, RIGHT_RESCAN },
1855 { "resolve", 1, 1, c_resolve, RIGHT_READ },
1856 { "resume", 0, 0, c_resume, RIGHT_PAUSE },
1857 { "revoke", 0, 0, c_revoke, RIGHT_READ },
1858 { "rtp-address", 0, 0, c_rtp_address, 0 },
1859 { "schedule-add", 3, INT_MAX, c_schedule_add, RIGHT_READ },
1860 { "schedule-del", 1, 1, c_schedule_del, RIGHT_READ },
1861 { "schedule-get", 1, 1, c_schedule_get, RIGHT_READ },
1862 { "schedule-list", 0, 0, c_schedule_list, RIGHT_READ },
1863 { "scratch", 0, 1, c_scratch, RIGHT_SCRATCH__MASK },
1864 { "search", 1, 1, c_search, RIGHT_READ },
1865 { "set", 3, 3, c_set, RIGHT_PREFS, },
1866 { "set-global", 2, 2, c_set_global, RIGHT_GLOBAL_PREFS },
1867 { "shutdown", 0, 0, c_shutdown, RIGHT_ADMIN },
1868 { "stats", 0, 0, c_stats, RIGHT_READ },
1869 { "tags", 0, 0, c_tags, RIGHT_READ },
1870 { "unset", 2, 2, c_set, RIGHT_PREFS },
1871 { "unset-global", 1, 1, c_set_global, RIGHT_GLOBAL_PREFS },
1872 { "user", 2, 2, c_user, 0 },
1873 { "userinfo", 2, 2, c_userinfo, RIGHT_READ },
1874 { "users", 0, 0, c_users, RIGHT_READ },
1875 { "version", 0, 0, c_version, RIGHT_READ },
1876 { "volume", 0, 2, c_volume, RIGHT_READ|RIGHT_VOLUME }
1879 /** @brief Fetch a command body
1880 * @param c Connection
1881 * @param body_callback Called with body
1882 * @param u Passed to body_callback
1885 static int fetch_body(struct conn *c,
1886 body_callback_type body_callback,
1888 assert(c->line_reader == command);
1889 c->line_reader = body_line;
1890 c->body_callback = body_callback;
1892 vector_init(c->body);
1896 /** @brief @ref line_reader_type callback for command body lines
1897 * @param c Connection
1899 * @return 1 if complete, 0 if incomplete
1901 * Called from reader_callback().
1903 static int body_line(struct conn *c,
1908 /* That's the lot */
1909 c->line_reader = command;
1910 vector_terminate(c->body);
1911 return c->body_callback(c, c->body->vec, c->body->nvec, c->body_u);
1914 vector_append(c->body, xstrdup(line));
1915 return 1; /* completed */
1918 static void command_error(const char *msg, void *u) {
1921 sink_printf(ev_writer_sink(c->w), "500 parse error: %s\n", msg);
1924 /** @brief @ref line_reader_type callback for commands
1925 * @param c Connection
1927 * @return 1 if complete, 0 if incomplete
1929 * Called from reader_callback().
1931 static int command(struct conn *c, char *line) {
1935 D(("server command %s", line));
1936 /* We force everything into NFC as early as possible */
1937 if(!(line = utf8_compose_canon(line, strlen(line), 0))) {
1938 sink_writes(ev_writer_sink(c->w), "500 cannot normalize command\n");
1941 if(!(vec = split(line, &nvec, SPLIT_QUOTES, command_error, c))) {
1942 sink_writes(ev_writer_sink(c->w), "500 cannot parse command\n");
1946 sink_writes(ev_writer_sink(c->w), "500 do what?\n");
1949 if((n = TABLE_FIND(commands, name, vec[0])) < 0)
1950 sink_writes(ev_writer_sink(c->w), "500 unknown command\n");
1952 if(commands[n].rights
1953 && !(c->rights & commands[n].rights)) {
1954 error(0, "%s attempted %s but lacks required rights", c->who ? c->who : "NULL",
1956 sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
1961 if(nvec < commands[n].minargs) {
1962 sink_writes(ev_writer_sink(c->w), "500 missing argument(s)\n");
1965 if(nvec > commands[n].maxargs) {
1966 sink_writes(ev_writer_sink(c->w), "500 too many arguments\n");
1969 return commands[n].fn(c, vec, nvec);
1971 return 1; /* completed */
1974 /* redirect to the right reader callback for our current state */
1975 static int redirect_reader_callback(ev_source *ev,
1983 return c->reader(ev, reader, ptr, bytes, eof, u);
1986 /* the main command reader */
1987 static int reader_callback(ev_source attribute((unused)) *ev,
1997 D(("server reader_callback"));
1998 while((eol = memchr(ptr, '\n', bytes))) {
2000 ev_reader_consume(reader, eol - (char *)ptr);
2001 complete = c->line_reader(c, ptr); /* usually command() */
2002 bytes -= (eol - (char *)ptr);
2005 /* the command had better have set a new reader callback */
2007 /* there are further bytes to read, or we are at eof; arrange for the
2008 * command's reader callback to handle them */
2009 return ev_reader_incomplete(reader);
2010 /* nothing's going on right now */
2013 /* command completed, we can go around and handle the next one */
2017 error(0, "S%x unterminated line", c->tag);
2018 D(("normal reader close"));
2021 D(("close associated writer"));
2022 ev_writer_close(c->w);
2025 remove_connection(c);
2030 static int listen_callback(ev_source *ev,
2032 const struct sockaddr attribute((unused)) *remote,
2033 socklen_t attribute((unused)) rlen,
2035 const struct listener *l = u;
2036 struct conn *c = xmalloc(sizeof *c);
2037 static unsigned tags;
2039 D(("server listen_callback fd %d (%s)", fd, l->name));
2042 c->next = connections;
2045 c->w = ev_writer_new(ev, fd, writer_error, c,
2048 error(0, "ev_writer_new for file inbound connection (fd=%d) failed",
2053 c->r = ev_reader_new(ev, fd, redirect_reader_callback, reader_error, c,
2056 /* Main reason for failure is the FD is too big and that will already have
2058 fatal(0, "ev_reader_new for file inbound connection (fd=%d) failed", fd);
2061 c->reader = reader_callback;
2064 c->line_reader = command;
2066 gcry_randomize(c->nonce, sizeof c->nonce, GCRY_STRONG_RANDOM);
2067 sink_printf(ev_writer_sink(c->w), "231 %d %s %s\n",
2069 config->authorization_algorithm,
2070 hex(c->nonce, sizeof c->nonce));
2074 int server_start(ev_source *ev, int pf,
2075 size_t socklen, const struct sockaddr *sa,
2078 struct listener *l = xmalloc(sizeof *l);
2079 static const int one = 1;
2081 D(("server_init socket %s", name));
2082 fd = xsocket(pf, SOCK_STREAM, 0);
2083 xsetsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
2084 if(bind(fd, sa, socklen) < 0) {
2085 error(errno, "error binding to %s", name);
2093 if(ev_listen(ev, fd, listen_callback, l, "server listener"))
2098 int server_stop(ev_source *ev, int fd) {
2100 return ev_listen_cancel(ev, fd);