2 * This file is part of DisOrder.
3 * Copyright (C) 2004-2009 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"
23 # define NONCE_SIZE 16
27 /** @brief Size of nonce in confirmation string in 32-bit words
29 * 64 bits gives 11 digits (in base 62).
31 # define CONFIRM_SIZE 2
34 int volume_left, volume_right; /* last known volume */
36 /** @brief Accept all well-formed login attempts
49 /** @brief Signature for line reader callback
52 * @return 0 if incomplete, 1 if complete
54 * @p line is 0-terminated and excludes the newline. It points into the
55 * input buffer so will become invalid shortly.
57 typedef int line_reader_type(struct conn *c,
60 /** @brief Signature for with-body command callbacks
62 * @param body List of body lines
63 * @param nbody Number of body lines
64 * @param u As passed to fetch_body()
65 * @return 0 to suspend input, 1 if complete
67 * The body strings are allocated (so survive indefinitely) and don't include
70 typedef int body_callback_type(struct conn *c,
75 /** @brief One client connection */
77 /** @brief Read commands from here */
79 /** @brief Send responses to here */
81 /** @brief Underlying file descriptor */
83 /** @brief Unique identifier for connection used in log messages */
85 /** @brief Login name or NULL */
87 /** @brief Event loop */
89 /** @brief Nonce chosen for this connection */
90 unsigned char nonce[NONCE_SIZE];
91 /** @brief Current reader callback
93 * We change this depending on whether we're servicing the @b log command
95 ev_reader_callback *reader;
96 /** @brief Event log output sending to this connection */
97 struct eventlog_output *lo;
98 /** @brief Parent listener */
99 const struct listener *l;
100 /** @brief Login cookie or NULL */
102 /** @brief Connection rights */
104 /** @brief Next connection */
106 /** @brief True if pending rescan had 'wait' set */
108 /** @brief Playlist that this connection locks */
109 const char *locked_playlist;
110 /** @brief When that playlist was locked */
112 /** @brief Line reader function */
113 line_reader_type *line_reader;
114 /** @brief Called when command body has been read */
115 body_callback_type *body_callback;
116 /** @brief Passed to @c body_callback */
118 /** @brief Accumulating body */
119 struct vector body[1];
122 /** @brief Linked list of connections */
123 static struct conn *connections;
125 static int reader_callback(ev_source *ev,
131 static int c_playlist_set_body(struct conn *c,
135 static int fetch_body(struct conn *c,
136 body_callback_type body_callback,
138 static int body_line(struct conn *c, char *line);
139 static int command(struct conn *c, char *line);
141 static const char *noyes[] = { "no", "yes" };
143 /** @brief Remove a connection from the connection list */
144 static void remove_connection(struct conn *c) {
147 for(cc = &connections; *cc && *cc != c; cc = &(*cc)->next)
153 /** @brief Called when a connection's writer fails or is shut down
155 * If the connection still has a raeder that is cancelled.
157 static int writer_error(ev_source attribute((unused)) *ev,
162 D(("server writer_error S%x %d", c->tag, errno_value));
163 if(errno_value == 0) {
165 D(("S%x writer completed", c->tag));
167 if(errno_value != EPIPE)
168 disorder_error(errno_value, "S%x write error on socket", c->tag);
170 D(("cancel reader"));
171 ev_reader_cancel(c->r);
174 D(("done cancel reader"));
178 remove_connection(c);
182 /** @brief Called when a conncetion's reader fails or is shut down
184 * If connection still has a writer then it is closed.
186 static int reader_error(ev_source attribute((unused)) *ev,
191 D(("server reader_error S%x %d", c->tag, errno_value));
192 disorder_error(errno_value, "S%x read error on socket", c->tag);
194 ev_writer_close(c->w);
198 remove_connection(c);
202 static int c_disable(struct conn *c, char **vec, int nvec) {
204 disable_playing(c->who);
205 else if(nvec == 1 && !strcmp(vec[0], "now"))
206 disable_playing(c->who);
208 sink_writes(ev_writer_sink(c->w), "550 invalid argument\n");
209 return 1; /* completed */
211 sink_writes(ev_writer_sink(c->w), "250 OK\n");
212 return 1; /* completed */
215 static int c_enable(struct conn *c,
216 char attribute((unused)) **vec,
217 int attribute((unused)) nvec) {
218 enable_playing(c->who, c->ev);
219 /* Enable implicitly unpauses if there is nothing playing */
220 if(paused && !playing) resume_playing(c->who);
221 sink_writes(ev_writer_sink(c->w), "250 OK\n");
222 return 1; /* completed */
225 static int c_enabled(struct conn *c,
226 char attribute((unused)) **vec,
227 int attribute((unused)) nvec) {
228 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[playing_is_enabled()]);
229 return 1; /* completed */
232 static int c_play(struct conn *c, char **vec,
233 int attribute((unused)) nvec) {
235 struct queue_entry *q;
237 if(!trackdb_exists(vec[0])) {
238 sink_writes(ev_writer_sink(c->w), "550 track is not in database\n");
241 if(!(track = trackdb_resolve(vec[0]))) {
242 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
245 q = queue_add(track, c->who, WHERE_BEFORE_RANDOM, NULL, origin_picked);
247 sink_printf(ev_writer_sink(c->w), "252 %s\n", q->id);
248 /* We make sure the track at the head of the queue is prepared, just in case
249 * we added it. We could be more subtle but prepare() will ensure we don't
250 * prepare the same track twice so there's no point. */
251 if(qhead.next != &qhead)
252 prepare(c->ev, qhead.next);
253 /* If the queue was empty but we are for some reason paused then
255 if(!playing) resume_playing(0);
257 return 1; /* completed */
260 static int c_playafter(struct conn *c, char **vec,
261 int attribute((unused)) nvec) {
263 struct queue_entry *q;
264 const char *afterme = vec[0];
266 for(int n = 1; n < nvec; ++n) {
267 if(!trackdb_exists(vec[n])) {
268 sink_writes(ev_writer_sink(c->w), "550 track is not in database\n");
271 if(!(track = trackdb_resolve(vec[n]))) {
272 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
275 q = queue_add(track, c->who, WHERE_AFTER, afterme, origin_picked);
277 sink_printf(ev_writer_sink(c->w), "550 No such ID\n");
280 disorder_info("added %s as %s after %s", track, q->id, afterme);
284 sink_printf(ev_writer_sink(c->w), "252 OK\n");
285 /* We make sure the track at the head of the queue is prepared, just in case
286 * we added it. We could be more subtle but prepare() will ensure we don't
287 * prepare the same track twice so there's no point. */
288 if(qhead.next != &qhead) {
289 prepare(c->ev, qhead.next);
290 disorder_info("prepared %s", qhead.next->id);
292 /* If the queue was empty but we are for some reason paused then
297 return 1; /* completed */
300 static int c_remove(struct conn *c, char **vec,
301 int attribute((unused)) nvec) {
302 struct queue_entry *q;
304 if(!(q = queue_find(vec[0]))) {
305 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
308 if(!right_removable(c->rights, c->who, q)) {
309 disorder_error(0, "%s attempted remove but lacks required rights", c->who);
310 sink_writes(ev_writer_sink(c->w),
311 "510 Not authorized to remove that track\n");
314 queue_remove(q, c->who);
315 /* De-prepare the track. */
317 /* See about adding a new random track */
318 add_random_track(c->ev);
319 /* Prepare whatever the next head track is. */
320 if(qhead.next != &qhead)
321 prepare(c->ev, qhead.next);
323 sink_writes(ev_writer_sink(c->w), "250 removed\n");
324 return 1; /* completed */
327 static int c_scratch(struct conn *c,
331 sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
332 return 1; /* completed */
334 /* TODO there is a bug here: if we specify an ID but it's not the currently
335 * playing track then you will get 550 if you weren't authorized to scratch
336 * the currently playing track. */
337 if(!right_scratchable(c->rights, c->who, playing)) {
338 disorder_error(0, "%s attempted scratch but lacks required rights", c->who);
339 sink_writes(ev_writer_sink(c->w),
340 "510 Not authorized to scratch that track\n");
343 scratch(c->who, nvec == 1 ? vec[0] : 0);
344 /* If you scratch an unpaused track then it is automatically unpaused */
346 sink_writes(ev_writer_sink(c->w), "250 scratched\n");
347 return 1; /* completed */
350 static int c_pause(struct conn *c,
351 char attribute((unused)) **vec,
352 int attribute((unused)) nvec) {
354 sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
355 return 1; /* completed */
358 sink_writes(ev_writer_sink(c->w), "250 already paused\n");
359 return 1; /* completed */
361 if(pause_playing(c->who) < 0)
362 sink_writes(ev_writer_sink(c->w), "550 cannot pause this track\n");
364 sink_writes(ev_writer_sink(c->w), "250 paused\n");
368 static int c_resume(struct conn *c,
369 char attribute((unused)) **vec,
370 int attribute((unused)) nvec) {
372 sink_writes(ev_writer_sink(c->w), "250 not paused\n");
373 return 1; /* completed */
375 resume_playing(c->who);
376 sink_writes(ev_writer_sink(c->w), "250 paused\n");
380 static int c_shutdown(struct conn *c,
381 char attribute((unused)) **vec,
382 int attribute((unused)) nvec) {
383 disorder_info("S%x shut down by %s", c->tag, c->who);
384 sink_writes(ev_writer_sink(c->w), "250 shutting down\n");
385 ev_writer_flush(c->w);
389 static int c_reconfigure(struct conn *c,
390 char attribute((unused)) **vec,
391 int attribute((unused)) nvec) {
392 disorder_info("S%x reconfigure by %s", c->tag, c->who);
393 if(reconfigure(c->ev, 1))
394 sink_writes(ev_writer_sink(c->w), "550 error reading new config\n");
396 sink_writes(ev_writer_sink(c->w), "250 installed new config\n");
397 return 1; /* completed */
400 static void finished_rescan(void *ru) {
401 struct conn *const c = ru;
403 sink_writes(ev_writer_sink(c->w), "250 rescan completed\n");
404 /* Turn this connection back on */
405 ev_reader_enable(c->r);
408 static void start_fresh_rescan(void *ru) {
409 struct conn *const c = ru;
411 if(trackdb_rescan_underway()) {
412 /* Some other waiter beat us to it. However in this case we're happy to
413 * piggyback; the requirement is that a new rescan be started, not that it
414 * was _our_ rescan. */
416 /* We block until the rescan completes */
417 trackdb_add_rescanned(finished_rescan, c);
419 /* We report that the new rescan has started */
420 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
421 /* Turn this connection back on */
422 ev_reader_enable(c->r);
425 /* We are the first connection to get a callback so we must start a
428 /* We want to block until the new rescan completes */
429 trackdb_rescan(c->ev, 1/*check*/, finished_rescan, c);
431 /* We can report back immediately */
432 trackdb_rescan(c->ev, 1/*check*/, 0, 0);
433 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
434 /* Turn this connection back on */
435 ev_reader_enable(c->r);
440 static int c_rescan(struct conn *c,
443 int flag_wait = 0, flag_fresh = 0, n;
446 for(n = 0; n < nvec; ++n) {
447 if(!strcmp(vec[n], "wait"))
448 flag_wait = 1; /* wait for rescan to complete */
450 /* Currently disabled because untested (and hard to test). */
451 else if(!strcmp(vec[n], "fresh"))
452 flag_fresh = 1; /* don't piggyback underway rescan */
455 sink_writes(ev_writer_sink(c->w), "550 unknown flag\n");
456 return 1; /* completed */
459 /* Report what was requested */
460 disorder_info("S%x rescan by %s (%s %s)", c->tag, c->who,
461 flag_wait ? "wait" : "",
462 flag_fresh ? "fresh" : "");
463 if(trackdb_rescan_underway()) {
465 /* We want a fresh rescan but there is already one underway. Arrange a
466 * callback when it completes and then set off a new one. */
467 c->rescan_wait = flag_wait;
468 trackdb_add_rescanned(start_fresh_rescan, c);
472 sink_writes(ev_writer_sink(c->w), "250 rescan queued\n");
476 /* There's a rescan underway, and it's acceptable to piggyback on it */
478 /* We want to block until completion. */
479 trackdb_add_rescanned(finished_rescan, c);
482 /* We don't want to block. So we just report that things are in
484 sink_writes(ev_writer_sink(c->w), "250 rescan already underway\n");
489 /* No rescan is underway. fresh is therefore irrelevant. */
491 /* We want to block until completion */
492 trackdb_rescan(c->ev, 1/*check*/, finished_rescan, c);
495 /* We don't want to block. */
496 trackdb_rescan(c->ev, 1/*check*/, 0, 0);
497 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
498 return 1; /* completed */
503 static int c_version(struct conn *c,
504 char attribute((unused)) **vec,
505 int attribute((unused)) nvec) {
506 /* VERSION had better only use the basic character set */
507 sink_printf(ev_writer_sink(c->w), "251 %s\n", disorder_short_version_string);
508 return 1; /* completed */
511 static int c_playing(struct conn *c,
512 char attribute((unused)) **vec,
513 int attribute((unused)) nvec) {
515 queue_fix_sofar(playing);
516 playing->expected = 0;
517 sink_printf(ev_writer_sink(c->w), "252 %s\n", queue_marshall(playing));
519 sink_printf(ev_writer_sink(c->w), "259 nothing playing\n");
520 return 1; /* completed */
523 static const char *connection_host(struct conn *c) {
526 struct sockaddr_in in;
527 struct sockaddr_in6 in6;
533 /* get connection data */
535 if(getpeername(c->fd, &u.sa, &l) < 0) {
536 disorder_error(errno, "S%x error calling getpeername", c->tag);
539 if(c->l->pf != PF_UNIX) {
540 if((n = getnameinfo(&u.sa, l,
541 host, sizeof host, 0, 0, NI_NUMERICHOST))) {
542 disorder_error(0, "S%x error calling getnameinfo: %s",
543 c->tag, gai_strerror(n));
546 return xstrdup(host);
551 static int c_user(struct conn *c,
553 int attribute((unused)) nvec) {
555 const char *res, *host, *password;
559 sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
562 /* get connection data */
563 if(!(host = connection_host(c))) {
564 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
568 k = trackdb_getuserinfo(vec[0]);
569 /* reject nonexistent users */
571 disorder_error(0, "S%x unknown user '%s' from %s", c->tag, vec[0], host);
572 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
575 /* reject unconfirmed users */
576 if(kvp_get(k, "confirmation")) {
577 disorder_error(0, "S%x unconfirmed user '%s' from %s",
578 c->tag, vec[0], host);
579 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
582 password = kvp_get(k, "password");
583 if(!password) password = "";
584 if(parse_rights(kvp_get(k, "rights"), &rights, 1)) {
585 disorder_error(0, "error parsing rights for %s", vec[0]);
586 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
589 /* check whether the response is right */
590 res = authhash(c->nonce, sizeof c->nonce, password,
591 config->authorization_algorithm);
592 if(wideopen || (res && !strcmp(res, vec[1]))) {
595 /* currently we only bother logging remote connections */
596 if(strcmp(host, "local"))
597 disorder_info("S%x %s connected from %s", c->tag, vec[0], host);
599 c->rights |= RIGHT__LOCAL;
600 sink_writes(ev_writer_sink(c->w), "230 OK\n");
603 /* oops, response was wrong */
604 disorder_info("S%x authentication failure for %s from %s",
605 c->tag, vec[0], host);
606 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
610 static int c_recent(struct conn *c,
611 char attribute((unused)) **vec,
612 int attribute((unused)) nvec) {
613 const struct queue_entry *q;
615 sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
616 for(q = phead.next; q != &phead; q = q->next)
617 sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
618 sink_writes(ev_writer_sink(c->w), ".\n");
619 return 1; /* completed */
622 static int c_queue(struct conn *c,
623 char attribute((unused)) **vec,
624 int attribute((unused)) nvec) {
625 struct queue_entry *q;
630 sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
631 if(playing_is_enabled() && !paused) {
633 queue_fix_sofar(playing);
634 if((l = trackdb_get(playing->track, "_length"))
635 && (length = atol(l))) {
637 when += length - playing->sofar + config->gap;
640 /* Nothing is playing but playing is enabled, so whatever is
641 * first in the queue can be expected to start immediately. */
644 for(q = qhead.next; q != &qhead; q = q->next) {
645 /* fill in estimated start time */
647 sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
648 /* update for next track */
650 if((l = trackdb_get(q->track, "_length"))
651 && (length = atol(l)))
652 when += length + config->gap;
657 sink_writes(ev_writer_sink(c->w), ".\n");
658 return 1; /* completed */
661 static int output_list(struct conn *c, char **vec) {
663 sink_printf(ev_writer_sink(c->w), "%s\n", *vec++);
664 sink_writes(ev_writer_sink(c->w), ".\n");
668 static int files_dirs(struct conn *c,
671 enum trackdb_listable what) {
672 const char *dir, *re, *errstr;
678 case 0: dir = 0; re = 0; break;
679 case 1: dir = vec[0]; re = 0; break;
680 case 2: dir = vec[0]; re = vec[1]; break;
683 /* A bit of a bodge to make sure the args don't trample on cache keys */
684 if(dir && strchr(dir, '\n')) {
685 sink_writes(ev_writer_sink(c->w), "550 invalid directory name\n");
688 if(re && strchr(re, '\n')) {
689 sink_writes(ev_writer_sink(c->w), "550 invalid regexp\n");
692 /* We bother eliminating "" because the web interface is relatively
693 * likely to send it */
695 byte_xasprintf(&key, "%d\n%s\n%s", (int)what, dir ? dir : "", re);
696 fvec = (char **)cache_get(&cache_files_type, key);
698 /* Got a cache hit, don't store the answer in the cache */
701 rec = 0; /* quieten compiler */
703 /* Cache miss, we'll do the lookup and key != 0 so we'll store the answer
705 if(!(rec = pcre_compile(re, PCRE_CASELESS|PCRE_UTF8,
706 &errstr, &erroffset, 0))) {
707 sink_printf(ev_writer_sink(c->w), "550 Error compiling regexp: %s\n",
711 /* It only counts as a miss if the regexp was valid. */
712 ++cache_files_misses;
715 /* No regexp, don't bother caching the result */
721 /* No cache hit (either because a miss, or because we did not look) so do
724 fvec = trackdb_list(dir, 0, what, rec);
726 fvec = trackdb_list(0, 0, what, rec);
729 /* Put the answer in the cache */
730 cache_put(&cache_files_type, key, fvec);
731 sink_writes(ev_writer_sink(c->w), "253 Listing follow\n");
732 return output_list(c, fvec);
735 static int c_files(struct conn *c,
738 return files_dirs(c, vec, nvec, trackdb_files);
741 static int c_dirs(struct conn *c,
744 return files_dirs(c, vec, nvec, trackdb_directories);
747 static int c_allfiles(struct conn *c,
750 return files_dirs(c, vec, nvec, trackdb_directories|trackdb_files);
753 static int c_get(struct conn *c,
755 int attribute((unused)) nvec) {
756 const char *v, *track;
758 if(!(track = trackdb_resolve(vec[0]))) {
759 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
762 if(vec[1][0] != '_' && (v = trackdb_get(track, vec[1])))
763 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
765 sink_writes(ev_writer_sink(c->w), "555 not found\n");
769 static int c_length(struct conn *c,
771 int attribute((unused)) nvec) {
772 const char *track, *v;
774 if(!(track = trackdb_resolve(vec[0]))) {
775 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
778 if((v = trackdb_get(track, "_length")))
779 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
781 sink_writes(ev_writer_sink(c->w), "550 not found\n");
785 static int c_set(struct conn *c,
787 int attribute((unused)) nvec) {
790 if(!(track = trackdb_resolve(vec[0]))) {
791 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
794 if(vec[1][0] != '_' && !trackdb_set(track, vec[1], vec[2]))
795 sink_writes(ev_writer_sink(c->w), "250 OK\n");
797 sink_writes(ev_writer_sink(c->w), "550 not found\n");
801 static int c_prefs(struct conn *c,
803 int attribute((unused)) nvec) {
807 if(!(track = trackdb_resolve(vec[0]))) {
808 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
811 k = trackdb_get_all(track);
812 sink_writes(ev_writer_sink(c->w), "253 prefs follow\n");
813 for(; k; k = k->next)
814 if(k->name[0] != '_') /* omit internal values */
815 sink_printf(ev_writer_sink(c->w),
816 " %s %s\n", quoteutf8(k->name), quoteutf8(k->value));
817 sink_writes(ev_writer_sink(c->w), ".\n");
821 static int c_exists(struct conn *c,
823 int attribute((unused)) nvec) {
824 /* trackdb_exists() does its own alias checking */
825 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[trackdb_exists(vec[0])]);
829 static void search_parse_error(const char *msg, void *u) {
830 *(const char **)u = msg;
833 static int c_search(struct conn *c,
835 int attribute((unused)) nvec) {
836 char **terms, **results;
837 int nterms, nresults, n;
838 const char *e = "unknown error";
840 /* This is a bit of a bodge. Initially it's there to make the eclient
841 * interface a bit more convenient to add searching to, but it has the more
842 * compelling advantage that if everything uses it, then interpretation of
843 * user-supplied search strings will be the same everywhere. */
844 if(!(terms = split(vec[0], &nterms, SPLIT_QUOTES, search_parse_error, &e))) {
845 sink_printf(ev_writer_sink(c->w), "550 %s\n", e);
847 results = trackdb_search(terms, nterms, &nresults);
848 sink_printf(ev_writer_sink(c->w), "253 %d matches\n", nresults);
849 for(n = 0; n < nresults; ++n)
850 sink_printf(ev_writer_sink(c->w), "%s\n", results[n]);
851 sink_writes(ev_writer_sink(c->w), ".\n");
856 static int c_random_enable(struct conn *c,
857 char attribute((unused)) **vec,
858 int attribute((unused)) nvec) {
859 enable_random(c->who, c->ev);
860 /* Enable implicitly unpauses if there is nothing playing */
861 if(paused && !playing) resume_playing(c->who);
862 sink_writes(ev_writer_sink(c->w), "250 OK\n");
863 return 1; /* completed */
866 static int c_random_disable(struct conn *c,
867 char attribute((unused)) **vec,
868 int attribute((unused)) nvec) {
869 disable_random(c->who);
870 sink_writes(ev_writer_sink(c->w), "250 OK\n");
871 return 1; /* completed */
874 static int c_random_enabled(struct conn *c,
875 char attribute((unused)) **vec,
876 int attribute((unused)) nvec) {
877 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[random_is_enabled()]);
878 return 1; /* completed */
881 static void got_stats(char *stats, void *u) {
882 struct conn *const c = u;
884 sink_printf(ev_writer_sink(c->w), "253 stats\n%s\n.\n", stats);
885 /* Now we can start processing commands again */
886 ev_reader_enable(c->r);
889 static int c_stats(struct conn *c,
890 char attribute((unused)) **vec,
891 int attribute((unused)) nvec) {
892 trackdb_stats_subprocess(c->ev, got_stats, c);
893 return 0; /* not yet complete */
896 static int c_volume(struct conn *c,
908 l = r = atoi(vec[0]);
919 rights = set ? RIGHT_VOLUME : RIGHT_READ;
920 if(!(c->rights & rights)) {
921 disorder_error(0, "%s attempted to set volume but lacks required rights",
923 sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
926 if(!api || !api->set_volume) {
927 sink_writes(ev_writer_sink(c->w), "550 error accessing mixer\n");
930 (set ? api->set_volume : api->get_volume)(&l, &r);
931 sink_printf(ev_writer_sink(c->w), "252 %d %d\n", l, r);
932 if(l != volume_left || r != volume_right) {
935 snprintf(lb, sizeof lb, "%d", l);
936 snprintf(rb, sizeof rb, "%d", r);
937 eventlog("volume", lb, rb, (char *)0);
942 /** @brief Called when data arrives on a log connection
944 * We just discard all such data. The client may occasionally send data as a
947 static int logging_reader_callback(ev_source attribute((unused)) *ev,
949 void attribute((unused)) *ptr,
951 int attribute((unused)) eof,
952 void attribute((unused)) *u) {
955 ev_reader_consume(reader, bytes);
957 /* Oops, that's all for now */
958 D(("logging reader eof"));
961 ev_writer_close(c->w);
965 remove_connection(c);
970 static void logclient(const char *msg, void *user) {
971 struct conn *c = user;
974 /* This connection has gone up in smoke for some reason */
975 eventlog_remove(c->lo);
979 /* user_* messages are restricted */
980 if(!strncmp(msg, "user_", 5)) {
981 /* They are only sent to admin users */
982 if(!(c->rights & RIGHT_ADMIN))
984 /* They are not sent over TCP connections unless remote user-management is
986 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL))
989 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" %s\n",
990 (uintmax_t)xtime(0), msg);
993 static int c_log(struct conn *c,
994 char attribute((unused)) **vec,
995 int attribute((unused)) nvec) {
998 sink_writes(ev_writer_sink(c->w), "254 OK\n");
999 /* pump out initial state */
1001 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
1003 playing_is_enabled() ? "enable_play" : "disable_play");
1004 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
1006 random_is_enabled() ? "enable_random" : "disable_random");
1007 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
1009 paused ? "pause" : "resume");
1011 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state playing\n",
1013 /* Initial volume */
1014 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" volume %d %d\n",
1015 (uintmax_t)now, volume_left, volume_right);
1016 c->lo = xmalloc(sizeof *c->lo);
1017 c->lo->fn = logclient;
1019 eventlog_add(c->lo);
1020 c->reader = logging_reader_callback;
1024 /** @brief Test whether a move is allowed
1025 * @param c Connection
1026 * @param qs List of IDs on queue
1027 * @param nqs Number of IDs
1028 * @return 0 if move is prohibited, non-0 if it is allowed
1030 static int has_move_rights(struct conn *c, struct queue_entry **qs, int nqs) {
1031 for(; nqs > 0; ++qs, --nqs) {
1032 struct queue_entry *const q = *qs;
1034 if(!right_movable(c->rights, c->who, q))
1040 static int c_move(struct conn *c,
1042 int attribute((unused)) nvec) {
1043 struct queue_entry *q;
1046 if(!(q = queue_find(vec[0]))) {
1047 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1050 if(!has_move_rights(c, &q, 1)) {
1051 disorder_error(0, "%s attempted move but lacks required rights", c->who);
1052 sink_writes(ev_writer_sink(c->w),
1053 "510 Not authorized to move that track\n");
1056 n = queue_move(q, atoi(vec[1]), c->who);
1057 sink_printf(ev_writer_sink(c->w), "252 %d\n", n);
1058 /* If we've moved to the head of the queue then prepare the track. */
1064 static int c_moveafter(struct conn *c,
1066 int attribute((unused)) nvec) {
1067 struct queue_entry *q, **qs;
1071 if(!(q = queue_find(vec[0]))) {
1072 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1079 qs = xcalloc(nvec, sizeof *qs);
1080 for(n = 0; n < nvec; ++n)
1081 if(!(qs[n] = queue_find(vec[n]))) {
1082 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1085 if(!has_move_rights(c, qs, nvec)) {
1086 disorder_error(0, "%s attempted moveafter but lacks required rights",
1088 sink_writes(ev_writer_sink(c->w),
1089 "510 Not authorized to move those tracks\n");
1092 queue_moveafter(q, nvec, qs, c->who);
1093 sink_printf(ev_writer_sink(c->w), "250 Moved tracks\n");
1094 /* If we've moved to the head of the queue then prepare the track. */
1100 static int c_part(struct conn *c,
1102 int attribute((unused)) nvec) {
1105 if(!(track = trackdb_resolve(vec[0]))) {
1106 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1109 sink_printf(ev_writer_sink(c->w), "252 %s\n",
1110 quoteutf8(trackdb_getpart(track, vec[1], vec[2])));
1114 static int c_resolve(struct conn *c,
1116 int attribute((unused)) nvec) {
1119 if(!(track = trackdb_resolve(vec[0]))) {
1120 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1123 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(track));
1127 static int list_response(struct conn *c,
1130 sink_printf(ev_writer_sink(c->w), "253 %s\n", reply);
1132 sink_printf(ev_writer_sink(c->w), "%s%s\n",
1133 **list == '.' ? "." : "", *list);
1136 sink_writes(ev_writer_sink(c->w), ".\n");
1137 return 1; /* completed */
1140 static int c_tags(struct conn *c,
1141 char attribute((unused)) **vec,
1142 int attribute((unused)) nvec) {
1143 return list_response(c, "Tag list follows", trackdb_alltags());
1146 static int c_set_global(struct conn *c,
1148 int attribute((unused)) nvec) {
1149 if(vec[0][0] == '_') {
1150 sink_writes(ev_writer_sink(c->w), "550 cannot set internal global preferences\n");
1153 trackdb_set_global(vec[0], vec[1], c->who);
1154 sink_printf(ev_writer_sink(c->w), "250 OK\n");
1158 static int c_get_global(struct conn *c,
1160 int attribute((unused)) nvec) {
1161 const char *s = trackdb_get_global(vec[0]);
1164 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(s));
1166 sink_writes(ev_writer_sink(c->w), "555 not found\n");
1170 static int c_nop(struct conn *c,
1171 char attribute((unused)) **vec,
1172 int attribute((unused)) nvec) {
1173 sink_printf(ev_writer_sink(c->w), "250 Quack\n");
1177 static int c_new(struct conn *c,
1187 if(max <= 0 || max > config->new_max)
1188 max = config->new_max;
1189 tracks = trackdb_new(0, max);
1190 sink_printf(ev_writer_sink(c->w), "253 New track list follows\n");
1193 sink_printf(ev_writer_sink(c->w), "%s%s\n",
1194 **tracks == '.' ? "." : "", *tracks);
1197 sink_writes(ev_writer_sink(c->w), ".\n");
1198 return 1; /* completed */
1202 static int c_rtp_address(struct conn *c,
1203 char attribute((unused)) **vec,
1204 int attribute((unused)) nvec) {
1205 if(api == &uaudio_rtp) {
1208 netaddress_format(&config->broadcast, NULL, &addr);
1209 sink_printf(ev_writer_sink(c->w), "252 %s %s\n",
1211 quoteutf8(addr[2]));
1213 sink_writes(ev_writer_sink(c->w), "550 No RTP\n");
1217 static int c_cookie(struct conn *c,
1219 int attribute((unused)) nvec) {
1224 /* Can't log in twice on the same connection */
1226 sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
1229 /* Get some kind of peer identifcation */
1230 if(!(host = connection_host(c))) {
1231 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1234 /* Check the cookie */
1235 user = verify_cookie(vec[0], &rights);
1237 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1244 if(strcmp(host, "local"))
1245 disorder_info("S%x %s connected with cookie from %s", c->tag, user, host);
1247 c->rights |= RIGHT__LOCAL;
1248 /* Response contains username so client knows who they are acting as */
1249 sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
1253 static int c_make_cookie(struct conn *c,
1254 char attribute((unused)) **vec,
1255 int attribute((unused)) nvec) {
1256 const char *cookie = make_cookie(c->who);
1259 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cookie));
1261 sink_writes(ev_writer_sink(c->w), "550 Cannot create cookie\n");
1265 static int c_revoke(struct conn *c,
1266 char attribute((unused)) **vec,
1267 int attribute((unused)) nvec) {
1269 revoke_cookie(c->cookie);
1270 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1272 sink_writes(ev_writer_sink(c->w), "550 Did not log in with cookie\n");
1276 static int c_adduser(struct conn *c,
1281 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1282 disorder_error(0, "S%x: remote adduser", c->tag);
1283 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1288 if(parse_rights(vec[2], 0, 1)) {
1289 sink_writes(ev_writer_sink(c->w), "550 Invalid rights list\n");
1293 rights = config->default_rights;
1294 if(trackdb_adduser(vec[0], vec[1], rights,
1295 0/*email*/, 0/*confirmation*/))
1296 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1298 sink_writes(ev_writer_sink(c->w), "250 User created\n");
1302 static int c_deluser(struct conn *c,
1304 int attribute((unused)) nvec) {
1307 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1308 disorder_error(0, "S%x: remote deluser", c->tag);
1309 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1312 if(trackdb_deluser(vec[0])) {
1313 sink_writes(ev_writer_sink(c->w), "550 Cannot delete user\n");
1316 /* Zap connections belonging to deleted user */
1317 for(d = connections; d; d = d->next)
1318 if(!strcmp(d->who, vec[0]))
1320 sink_writes(ev_writer_sink(c->w), "250 User deleted\n");
1324 static int c_edituser(struct conn *c,
1326 int attribute((unused)) nvec) {
1329 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1330 disorder_error(0, "S%x: remote edituser", c->tag);
1331 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1334 /* RIGHT_ADMIN can do anything; otherwise you can only set your own email
1335 * address and password. */
1336 if((c->rights & RIGHT_ADMIN)
1337 || (!strcmp(c->who, vec[0])
1338 && (!strcmp(vec[1], "email")
1339 || !strcmp(vec[1], "password")))) {
1340 if(trackdb_edituserinfo(vec[0], vec[1], vec[2])) {
1341 sink_writes(ev_writer_sink(c->w), "550 Failed to change setting\n");
1344 if(!strcmp(vec[1], "password")) {
1345 /* Zap all connections for this user after a password change */
1346 for(d = connections; d; d = d->next)
1347 if(!strcmp(d->who, vec[0]))
1349 } else if(!strcmp(vec[1], "rights")) {
1350 /* Update rights for this user */
1353 if(!parse_rights(vec[2], &r, 1)) {
1354 const char *new_rights = rights_string(r);
1355 for(d = connections; d; d = d->next) {
1356 if(!strcmp(d->who, vec[0])) {
1359 /* Notify any log connections */
1361 sink_printf(ev_writer_sink(d->w),
1362 "%"PRIxMAX" rights_changed %s\n",
1363 (uintmax_t)xtime(0),
1364 quoteutf8(new_rights));
1369 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1371 disorder_error(0, "%s attempted edituser but lacks required rights",
1373 sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
1378 static int c_userinfo(struct conn *c,
1379 char attribute((unused)) **vec,
1380 int attribute((unused)) nvec) {
1384 /* We allow remote querying of rights so that clients can figure out what
1385 * they're allowed to do */
1386 if(!config->remote_userman
1387 && !(c->rights & RIGHT__LOCAL)
1388 && strcmp(vec[1], "rights")) {
1389 disorder_error(0, "S%x: remote userinfo %s %s", c->tag, vec[0], vec[1]);
1390 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1393 /* RIGHT_ADMIN allows anything; otherwise you can only get your own email
1394 * address and rights list. */
1395 if((c->rights & RIGHT_ADMIN)
1396 || (!strcmp(c->who, vec[0])
1397 && (!strcmp(vec[1], "email")
1398 || !strcmp(vec[1], "rights")))) {
1399 if((k = trackdb_getuserinfo(vec[0])))
1400 if((value = kvp_get(k, vec[1])))
1401 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(value));
1403 sink_writes(ev_writer_sink(c->w), "555 Not set\n");
1405 sink_writes(ev_writer_sink(c->w), "550 No such user\n");
1407 disorder_error(0, "%s attempted userinfo but lacks required rights",
1409 sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
1414 static int c_users(struct conn *c,
1415 char attribute((unused)) **vec,
1416 int attribute((unused)) nvec) {
1417 return list_response(c, "User list follows", trackdb_listusers());
1420 static int c_register(struct conn *c,
1422 int attribute((unused)) nvec) {
1424 uint32_t nonce[CONFIRM_SIZE];
1425 char nonce_str[(32 * CONFIRM_SIZE) / 5 + 1];
1427 /* The confirmation string is username/base62(nonce). The confirmation
1428 * process will pick the username back out to identify them but the _whole_
1429 * string is used as the confirmation string. Base 62 means we used only
1430 * letters and digits, minimizing the chance of the URL being mispasted. */
1431 gcry_randomize(nonce, sizeof nonce, GCRY_STRONG_RANDOM);
1432 if(basen(nonce, CONFIRM_SIZE, nonce_str, sizeof nonce_str, 62)) {
1433 disorder_error(0, "buffer too small encoding confirmation string");
1434 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1436 byte_xasprintf(&cs, "%s/%s", vec[0], nonce_str);
1437 if(trackdb_adduser(vec[0], vec[1], config->default_rights, vec[2], cs))
1438 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1440 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cs));
1444 static int c_confirm(struct conn *c,
1446 int attribute((unused)) nvec) {
1451 /* Get some kind of peer identifcation */
1452 if(!(host = connection_host(c))) {
1453 sink_writes(ev_writer_sink(c->w), "530 Authentication failure\n");
1456 /* Picking the LAST / means we don't (here) rule out slashes in usernames. */
1457 if(!(sep = strrchr(vec[0], '/'))) {
1458 sink_writes(ev_writer_sink(c->w), "550 Malformed confirmation string\n");
1461 user = xstrndup(vec[0], sep - vec[0]);
1462 if(trackdb_confirm(user, vec[0], &rights))
1463 sink_writes(ev_writer_sink(c->w), "550 Incorrect confirmation string\n");
1468 if(strcmp(host, "local"))
1469 disorder_info("S%x %s confirmed from %s", c->tag, user, host);
1471 c->rights |= RIGHT__LOCAL;
1472 /* Response contains username so client knows who they are acting as */
1473 sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
1478 static int sent_reminder(ev_source attribute((unused)) *ev,
1479 pid_t attribute((unused)) pid,
1481 const struct rusage attribute((unused)) *rusage,
1483 struct conn *const c = u;
1485 /* Tell the client what went down */
1487 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1489 disorder_error(0, "reminder subprocess %s", wstat(status));
1490 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1492 /* Re-enable this connection */
1493 ev_reader_enable(c->r);
1497 static int c_reminder(struct conn *c,
1499 int attribute((unused)) nvec) {
1501 const char *password, *email, *text, *encoding, *charset, *content_type;
1506 static hash *last_reminder;
1508 if(!config->mail_sender) {
1509 disorder_error(0, "cannot send password reminders because mail_sender not set");
1510 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1513 if(!(k = trackdb_getuserinfo(vec[0]))) {
1514 disorder_error(0, "reminder for user '%s' who does not exist", vec[0]);
1515 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1518 if(!(email = kvp_get(k, "email"))
1519 || !email_valid(email)) {
1520 disorder_error(0, "user '%s' has no valid email address", vec[0]);
1521 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1524 if(!(password = kvp_get(k, "password"))
1526 disorder_error(0, "user '%s' has no password", vec[0]);
1527 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1530 /* Rate-limit reminders. This hash is bounded in size by the number of
1531 * users. If this is actually a problem for anyone then we can periodically
1534 last_reminder = hash_new(sizeof (time_t));
1535 last = hash_find(last_reminder, vec[0]);
1537 if(last && now < *last + config->reminder_interval) {
1538 disorder_error(0, "sent a password reminder to '%s' too recently", vec[0]);
1539 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1542 /* Send the reminder */
1543 /* TODO this should be templatized and to some extent merged with
1544 * the code in act_register() */
1545 byte_xasprintf((char **)&text,
1546 "Someone requested that you be sent a reminder of your DisOrder password.\n"
1547 "Your password is:\n"
1550 if(!(text = mime_encode_text(text, &charset, &encoding)))
1551 disorder_fatal(0, "cannot encode email");
1552 byte_xasprintf((char **)&content_type, "text/plain;charset=%s",
1553 quote822(charset, 0));
1554 pid = sendmail_subprocess("", config->mail_sender, email,
1555 "DisOrder password reminder",
1556 encoding, content_type, text);
1558 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1561 hash_add(last_reminder, vec[0], &now, HASH_INSERT_OR_REPLACE);
1562 disorder_info("sending a passsword reminder to user '%s'", vec[0]);
1563 /* We can only continue when the subprocess finishes */
1564 ev_child(c->ev, pid, 0, sent_reminder, c);
1568 static int c_schedule_list(struct conn *c,
1569 char attribute((unused)) **vec,
1570 int attribute((unused)) nvec) {
1571 char **ids = schedule_list(0);
1572 sink_writes(ev_writer_sink(c->w), "253 ID list follows\n");
1574 sink_printf(ev_writer_sink(c->w), "%s\n", *ids++);
1575 sink_writes(ev_writer_sink(c->w), ".\n");
1576 return 1; /* completed */
1579 static int c_schedule_get(struct conn *c,
1581 int attribute((unused)) nvec) {
1582 struct kvp *actiondata = schedule_get(vec[0]), *k;
1585 sink_writes(ev_writer_sink(c->w), "555 No such event\n");
1586 return 1; /* completed */
1588 /* Scheduled events are public information. Anyone with RIGHT_READ can see
1590 sink_writes(ev_writer_sink(c->w), "253 Event information follows\n");
1591 for(k = actiondata; k; k = k->next)
1592 sink_printf(ev_writer_sink(c->w), " %s %s\n",
1593 quoteutf8(k->name), quoteutf8(k->value));
1594 sink_writes(ev_writer_sink(c->w), ".\n");
1595 return 1; /* completed */
1598 static int c_schedule_del(struct conn *c,
1600 int attribute((unused)) nvec) {
1601 struct kvp *actiondata = schedule_get(vec[0]);
1604 sink_writes(ev_writer_sink(c->w), "555 No such event\n");
1605 return 1; /* completed */
1607 /* If you have admin rights you can delete anything. If you don't then you
1608 * can only delete your own scheduled events. */
1609 if(!(c->rights & RIGHT_ADMIN)) {
1610 const char *who = kvp_get(actiondata, "who");
1612 if(!who || !c->who || strcmp(who, c->who)) {
1613 sink_writes(ev_writer_sink(c->w), "551 Not authorized\n");
1614 return 1; /* completed */
1617 if(schedule_del(vec[0]))
1618 sink_writes(ev_writer_sink(c->w), "550 Could not delete scheduled event\n");
1620 sink_writes(ev_writer_sink(c->w), "250 Deleted\n");
1621 return 1; /* completed */
1624 static int c_schedule_add(struct conn *c,
1627 struct kvp *actiondata = 0;
1630 /* Standard fields */
1631 kvp_set(&actiondata, "who", c->who);
1632 kvp_set(&actiondata, "when", vec[0]);
1633 kvp_set(&actiondata, "priority", vec[1]);
1634 kvp_set(&actiondata, "action", vec[2]);
1635 /* Action-dependent fields */
1636 if(!strcmp(vec[2], "play")) {
1638 sink_writes(ev_writer_sink(c->w), "550 Wrong number of arguments\n");
1641 if(!trackdb_exists(vec[3])) {
1642 sink_writes(ev_writer_sink(c->w), "550 Track is not in database\n");
1645 kvp_set(&actiondata, "track", vec[3]);
1646 } else if(!strcmp(vec[2], "set-global")) {
1647 if(nvec < 4 || nvec > 5) {
1648 sink_writes(ev_writer_sink(c->w), "550 Wrong number of arguments\n");
1651 kvp_set(&actiondata, "key", vec[3]);
1653 kvp_set(&actiondata, "value", vec[4]);
1655 sink_writes(ev_writer_sink(c->w), "550 Unknown action\n");
1658 /* schedule_add() checks user rights */
1659 id = schedule_add(c->ev, actiondata);
1661 sink_writes(ev_writer_sink(c->w), "550 Cannot add scheduled event\n");
1663 sink_printf(ev_writer_sink(c->w), "252 %s\n", id);
1667 static int c_adopt(struct conn *c,
1669 int attribute((unused)) nvec) {
1670 struct queue_entry *q;
1673 sink_writes(ev_writer_sink(c->w), "550 no identity\n");
1676 if(!(q = queue_find(vec[0]))) {
1677 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1680 if(q->origin != origin_random) {
1681 sink_writes(ev_writer_sink(c->w), "550 not a random track\n");
1684 q->origin = origin_adopted;
1685 q->submitter = xstrdup(c->who);
1686 eventlog("adopted", q->id, q->submitter, (char *)0);
1688 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1692 static int playlist_response(struct conn *c,
1696 assert(!"cannot cope with success");
1698 sink_writes(ev_writer_sink(c->w), "550 Access denied\n");
1701 sink_writes(ev_writer_sink(c->w), "550 Invalid playlist name\n");
1704 sink_writes(ev_writer_sink(c->w), "555 No such playlist\n");
1707 sink_writes(ev_writer_sink(c->w), "550 Error accessing playlist\n");
1713 static int c_playlist_get(struct conn *c,
1715 int attribute((unused)) nvec) {
1719 if(!(err = trackdb_playlist_get(vec[0], c->who, &tracks, 0, 0)))
1720 return list_response(c, "Playlist contents follows", tracks);
1722 return playlist_response(c, err);
1725 static int c_playlist_set(struct conn *c,
1727 int attribute((unused)) nvec) {
1728 return fetch_body(c, c_playlist_set_body, vec[0]);
1731 static int c_playlist_set_body(struct conn *c,
1735 const char *playlist = u;
1738 if(!c->locked_playlist
1739 || strcmp(playlist, c->locked_playlist)) {
1740 sink_writes(ev_writer_sink(c->w), "550 Playlist is not locked\n");
1743 if(!(err = trackdb_playlist_set(playlist, c->who,
1745 sink_printf(ev_writer_sink(c->w), "250 OK\n");
1748 return playlist_response(c, err);
1751 static int c_playlist_get_share(struct conn *c,
1753 int attribute((unused)) nvec) {
1757 if(!(err = trackdb_playlist_get(vec[0], c->who, 0, 0, &share))) {
1758 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(share));
1761 return playlist_response(c, err);
1764 static int c_playlist_set_share(struct conn *c,
1766 int attribute((unused)) nvec) {
1769 if(!(err = trackdb_playlist_set(vec[0], c->who, 0, 0, vec[1]))) {
1770 sink_printf(ev_writer_sink(c->w), "250 OK\n");
1773 return playlist_response(c, err);
1776 static int c_playlists(struct conn *c,
1777 char attribute((unused)) **vec,
1778 int attribute((unused)) nvec) {
1781 trackdb_playlist_list(c->who, &p, 0);
1782 return list_response(c, "List of playlists follows", p);
1785 static int c_playlist_delete(struct conn *c,
1787 int attribute((unused)) nvec) {
1790 if(!(err = trackdb_playlist_delete(vec[0], c->who))) {
1791 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1794 return playlist_response(c, err);
1797 static int c_playlist_lock(struct conn *c,
1799 int attribute((unused)) nvec) {
1803 /* Check we're allowed to modify this playlist */
1804 if((err = trackdb_playlist_set(vec[0], c->who, 0, 0, 0)))
1805 return playlist_response(c, err);
1806 /* If we hold a lock don't allow a new one */
1807 if(c->locked_playlist) {
1808 sink_writes(ev_writer_sink(c->w), "550 Already holding a lock\n");
1811 /* See if some other connection locks the same playlist */
1812 for(cc = connections; cc; cc = cc->next)
1813 if(cc->locked_playlist && !strcmp(cc->locked_playlist, vec[0]))
1816 /* TODO: implement config->playlist_lock_timeout */
1817 sink_writes(ev_writer_sink(c->w), "550 Already locked\n");
1820 c->locked_playlist = xstrdup(vec[0]);
1821 time(&c->locked_when);
1822 sink_writes(ev_writer_sink(c->w), "250 Acquired lock\n");
1826 static int c_playlist_unlock(struct conn *c,
1827 char attribute((unused)) **vec,
1828 int attribute((unused)) nvec) {
1829 if(!c->locked_playlist) {
1830 sink_writes(ev_writer_sink(c->w), "550 Not holding a lock\n");
1833 c->locked_playlist = 0;
1834 sink_writes(ev_writer_sink(c->w), "250 Released lock\n");
1838 static const struct command {
1839 /** @brief Command name */
1842 /** @brief Minimum number of arguments */
1845 /** @brief Maximum number of arguments */
1848 /** @brief Function to process command */
1849 int (*fn)(struct conn *, char **, int);
1851 /** @brief Rights required to execute command
1853 * 0 means that the command can be issued without logging in. If multiple
1854 * bits are listed here any of those rights will do.
1858 { "adduser", 2, 3, c_adduser, RIGHT_ADMIN|RIGHT__LOCAL },
1859 { "adopt", 1, 1, c_adopt, RIGHT_PLAY },
1860 { "allfiles", 0, 2, c_allfiles, RIGHT_READ },
1861 { "confirm", 1, 1, c_confirm, 0 },
1862 { "cookie", 1, 1, c_cookie, 0 },
1863 { "deluser", 1, 1, c_deluser, RIGHT_ADMIN|RIGHT__LOCAL },
1864 { "dirs", 0, 2, c_dirs, RIGHT_READ },
1865 { "disable", 0, 1, c_disable, RIGHT_GLOBAL_PREFS },
1866 { "edituser", 3, 3, c_edituser, RIGHT_ADMIN|RIGHT_USERINFO },
1867 { "enable", 0, 0, c_enable, RIGHT_GLOBAL_PREFS },
1868 { "enabled", 0, 0, c_enabled, RIGHT_READ },
1869 { "exists", 1, 1, c_exists, RIGHT_READ },
1870 { "files", 0, 2, c_files, RIGHT_READ },
1871 { "get", 2, 2, c_get, RIGHT_READ },
1872 { "get-global", 1, 1, c_get_global, RIGHT_READ },
1873 { "length", 1, 1, c_length, RIGHT_READ },
1874 { "log", 0, 0, c_log, RIGHT_READ },
1875 { "make-cookie", 0, 0, c_make_cookie, RIGHT_READ },
1876 { "move", 2, 2, c_move, RIGHT_MOVE__MASK },
1877 { "moveafter", 1, INT_MAX, c_moveafter, RIGHT_MOVE__MASK },
1878 { "new", 0, 1, c_new, RIGHT_READ },
1879 { "nop", 0, 0, c_nop, 0 },
1880 { "part", 3, 3, c_part, RIGHT_READ },
1881 { "pause", 0, 0, c_pause, RIGHT_PAUSE },
1882 { "play", 1, 1, c_play, RIGHT_PLAY },
1883 { "playafter", 2, INT_MAX, c_playafter, RIGHT_PLAY },
1884 { "playing", 0, 0, c_playing, RIGHT_READ },
1885 { "playlist-delete", 1, 1, c_playlist_delete, RIGHT_PLAY },
1886 { "playlist-get", 1, 1, c_playlist_get, RIGHT_READ },
1887 { "playlist-get-share", 1, 1, c_playlist_get_share, RIGHT_READ },
1888 { "playlist-lock", 1, 1, c_playlist_lock, RIGHT_PLAY },
1889 { "playlist-set", 1, 1, c_playlist_set, RIGHT_PLAY },
1890 { "playlist-set-share", 2, 2, c_playlist_set_share, RIGHT_PLAY },
1891 { "playlist-unlock", 0, 0, c_playlist_unlock, RIGHT_PLAY },
1892 { "playlists", 0, 0, c_playlists, RIGHT_READ },
1893 { "prefs", 1, 1, c_prefs, RIGHT_READ },
1894 { "queue", 0, 0, c_queue, RIGHT_READ },
1895 { "random-disable", 0, 0, c_random_disable, RIGHT_GLOBAL_PREFS },
1896 { "random-enable", 0, 0, c_random_enable, RIGHT_GLOBAL_PREFS },
1897 { "random-enabled", 0, 0, c_random_enabled, RIGHT_READ },
1898 { "recent", 0, 0, c_recent, RIGHT_READ },
1899 { "reconfigure", 0, 0, c_reconfigure, RIGHT_ADMIN },
1900 { "register", 3, 3, c_register, RIGHT_REGISTER|RIGHT__LOCAL },
1901 { "reminder", 1, 1, c_reminder, RIGHT__LOCAL },
1902 { "remove", 1, 1, c_remove, RIGHT_REMOVE__MASK },
1903 { "rescan", 0, INT_MAX, c_rescan, RIGHT_RESCAN },
1904 { "resolve", 1, 1, c_resolve, RIGHT_READ },
1905 { "resume", 0, 0, c_resume, RIGHT_PAUSE },
1906 { "revoke", 0, 0, c_revoke, RIGHT_READ },
1907 { "rtp-address", 0, 0, c_rtp_address, 0 },
1908 { "schedule-add", 3, INT_MAX, c_schedule_add, RIGHT_READ },
1909 { "schedule-del", 1, 1, c_schedule_del, RIGHT_READ },
1910 { "schedule-get", 1, 1, c_schedule_get, RIGHT_READ },
1911 { "schedule-list", 0, 0, c_schedule_list, RIGHT_READ },
1912 { "scratch", 0, 1, c_scratch, RIGHT_SCRATCH__MASK },
1913 { "search", 1, 1, c_search, RIGHT_READ },
1914 { "set", 3, 3, c_set, RIGHT_PREFS, },
1915 { "set-global", 2, 2, c_set_global, RIGHT_GLOBAL_PREFS },
1916 { "shutdown", 0, 0, c_shutdown, RIGHT_ADMIN },
1917 { "stats", 0, 0, c_stats, RIGHT_READ },
1918 { "tags", 0, 0, c_tags, RIGHT_READ },
1919 { "unset", 2, 2, c_set, RIGHT_PREFS },
1920 { "unset-global", 1, 1, c_set_global, RIGHT_GLOBAL_PREFS },
1921 { "user", 2, 2, c_user, 0 },
1922 { "userinfo", 2, 2, c_userinfo, RIGHT_READ },
1923 { "users", 0, 0, c_users, RIGHT_READ },
1924 { "version", 0, 0, c_version, RIGHT_READ },
1925 { "volume", 0, 2, c_volume, RIGHT_READ|RIGHT_VOLUME }
1928 /** @brief Fetch a command body
1929 * @param c Connection
1930 * @param body_callback Called with body
1931 * @param u Passed to body_callback
1934 static int fetch_body(struct conn *c,
1935 body_callback_type body_callback,
1937 assert(c->line_reader == command);
1938 c->line_reader = body_line;
1939 c->body_callback = body_callback;
1941 vector_init(c->body);
1945 /** @brief @ref line_reader_type callback for command body lines
1946 * @param c Connection
1948 * @return 1 if complete, 0 if incomplete
1950 * Called from reader_callback().
1952 static int body_line(struct conn *c,
1957 /* That's the lot */
1958 c->line_reader = command;
1959 vector_terminate(c->body);
1960 return c->body_callback(c, c->body->vec, c->body->nvec, c->body_u);
1963 vector_append(c->body, xstrdup(line));
1964 return 1; /* completed */
1967 static void command_error(const char *msg, void *u) {
1970 sink_printf(ev_writer_sink(c->w), "500 parse error: %s\n", msg);
1973 /** @brief @ref line_reader_type callback for commands
1974 * @param c Connection
1976 * @return 1 if complete, 0 if incomplete
1978 * Called from reader_callback().
1980 static int command(struct conn *c, char *line) {
1984 D(("server command %s", line));
1985 /* We force everything into NFC as early as possible */
1986 if(!(line = utf8_compose_canon(line, strlen(line), 0))) {
1987 sink_writes(ev_writer_sink(c->w), "500 cannot normalize command\n");
1990 if(!(vec = split(line, &nvec, SPLIT_QUOTES, command_error, c))) {
1991 sink_writes(ev_writer_sink(c->w), "500 cannot parse command\n");
1995 sink_writes(ev_writer_sink(c->w), "500 do what?\n");
1998 if((n = TABLE_FIND(commands, name, vec[0])) < 0)
1999 sink_writes(ev_writer_sink(c->w), "500 unknown command\n");
2001 if(commands[n].rights
2002 && !(c->rights & commands[n].rights)) {
2003 disorder_error(0, "%s attempted %s but lacks required rights",
2004 c->who ? c->who : "NULL",
2006 sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
2011 if(nvec < commands[n].minargs) {
2012 sink_writes(ev_writer_sink(c->w), "500 missing argument(s)\n");
2015 if(nvec > commands[n].maxargs) {
2016 sink_writes(ev_writer_sink(c->w), "500 too many arguments\n");
2019 return commands[n].fn(c, vec, nvec);
2021 return 1; /* completed */
2024 /* redirect to the right reader callback for our current state */
2025 static int redirect_reader_callback(ev_source *ev,
2033 return c->reader(ev, reader, ptr, bytes, eof, u);
2036 /* the main command reader */
2037 static int reader_callback(ev_source attribute((unused)) *ev,
2047 D(("server reader_callback"));
2048 while((eol = memchr(ptr, '\n', bytes))) {
2050 ev_reader_consume(reader, eol - (char *)ptr);
2051 complete = c->line_reader(c, ptr); /* usually command() */
2052 bytes -= (eol - (char *)ptr);
2055 /* the command had better have set a new reader callback */
2057 /* there are further bytes to read, or we are at eof; arrange for the
2058 * command's reader callback to handle them */
2059 return ev_reader_incomplete(reader);
2060 /* nothing's going on right now */
2063 /* command completed, we can go around and handle the next one */
2067 disorder_error(0, "S%x unterminated line", c->tag);
2068 D(("normal reader close"));
2071 D(("close associated writer"));
2072 ev_writer_close(c->w);
2075 remove_connection(c);
2080 static int listen_callback(ev_source *ev,
2082 const struct sockaddr attribute((unused)) *remote,
2083 socklen_t attribute((unused)) rlen,
2085 const struct listener *l = u;
2086 struct conn *c = xmalloc(sizeof *c);
2087 static unsigned tags;
2089 D(("server listen_callback fd %d (%s)", fd, l->name));
2092 c->next = connections;
2095 c->w = ev_writer_new(ev, fd, writer_error, c,
2098 disorder_error(0, "ev_writer_new for file inbound connection (fd=%d) failed",
2103 c->r = ev_reader_new(ev, fd, redirect_reader_callback, reader_error, c,
2106 /* Main reason for failure is the FD is too big and that will already have
2109 "ev_reader_new for file inbound connection (fd=%d) failed",
2113 c->reader = reader_callback;
2116 c->line_reader = command;
2118 gcry_randomize(c->nonce, sizeof c->nonce, GCRY_STRONG_RANDOM);
2119 sink_printf(ev_writer_sink(c->w), "231 %d %s %s\n",
2121 config->authorization_algorithm,
2122 hex(c->nonce, sizeof c->nonce));
2126 int server_start(ev_source *ev, int pf,
2127 size_t socklen, const struct sockaddr *sa,
2130 struct listener *l = xmalloc(sizeof *l);
2131 static const int one = 1;
2133 D(("server_init socket %s", name));
2134 fd = xsocket(pf, SOCK_STREAM, 0);
2135 xsetsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
2136 if(bind(fd, sa, socklen) < 0) {
2137 disorder_error(errno, "error binding to %s", name);
2145 if(ev_listen(ev, fd, listen_callback, l, "server listener"))
2147 disorder_info("listening on %s", name);
2151 int server_stop(ev_source *ev, int fd) {
2153 return ev_listen_cancel(ev, fd);