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
47 /** @brief One client connection */
49 /** @brief Read commands from here */
51 /** @brief Send responses to here */
53 /** @brief Underlying file descriptor */
55 /** @brief Unique identifier for connection used in log messages */
57 /** @brief Login name or NULL */
59 /** @brief Event loop */
61 /** @brief Nonce chosen for this connection */
62 unsigned char nonce[NONCE_SIZE];
63 /** @brief Current reader callback
65 * We change this depending on whether we're servicing the @b log command
67 ev_reader_callback *reader;
68 /** @brief Event log output sending to this connection */
69 struct eventlog_output *lo;
70 /** @brief Parent listener */
71 const struct listener *l;
72 /** @brief Login cookie or NULL */
74 /** @brief Connection rights */
76 /** @brief Next connection */
78 /** @brief True if pending rescan had 'wait' set */
82 /** @brief Linked list of connections */
83 static struct conn *connections;
85 static int reader_callback(ev_source *ev,
92 static const char *noyes[] = { "no", "yes" };
94 /** @brief Remove a connection from the connection list */
95 static void remove_connection(struct conn *c) {
98 for(cc = &connections; *cc && *cc != c; cc = &(*cc)->next)
104 /** @brief Called when a connection's writer fails or is shut down
106 * If the connection still has a raeder that is cancelled.
108 static int writer_error(ev_source attribute((unused)) *ev,
113 D(("server writer_error S%x %d", c->tag, errno_value));
114 if(errno_value == 0) {
116 D(("S%x writer completed", c->tag));
118 if(errno_value != EPIPE)
119 error(errno_value, "S%x write error on socket", c->tag);
121 D(("cancel reader"));
122 ev_reader_cancel(c->r);
125 D(("done cancel reader"));
129 remove_connection(c);
133 /** @brief Called when a conncetion's reader fails or is shut down
135 * If connection still has a writer then it is closed.
137 static int reader_error(ev_source attribute((unused)) *ev,
142 D(("server reader_error S%x %d", c->tag, errno_value));
143 error(errno_value, "S%x read error on socket", c->tag);
145 ev_writer_close(c->w);
149 remove_connection(c);
153 static int c_disable(struct conn *c, char **vec, int nvec) {
155 disable_playing(c->who);
156 else if(nvec == 1 && !strcmp(vec[0], "now"))
157 disable_playing(c->who);
159 sink_writes(ev_writer_sink(c->w), "550 invalid argument\n");
160 return 1; /* completed */
162 sink_writes(ev_writer_sink(c->w), "250 OK\n");
163 return 1; /* completed */
166 static int c_enable(struct conn *c,
167 char attribute((unused)) **vec,
168 int attribute((unused)) nvec) {
169 enable_playing(c->who, c->ev);
170 /* Enable implicitly unpauses if there is nothing playing */
171 if(paused && !playing) resume_playing(c->who);
172 sink_writes(ev_writer_sink(c->w), "250 OK\n");
173 return 1; /* completed */
176 static int c_enabled(struct conn *c,
177 char attribute((unused)) **vec,
178 int attribute((unused)) nvec) {
179 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[playing_is_enabled()]);
180 return 1; /* completed */
183 static int c_play(struct conn *c, char **vec,
184 int attribute((unused)) nvec) {
186 struct queue_entry *q;
188 if(!trackdb_exists(vec[0])) {
189 sink_writes(ev_writer_sink(c->w), "550 track is not in database\n");
192 if(!(track = trackdb_resolve(vec[0]))) {
193 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
196 q = queue_add(track, c->who, WHERE_BEFORE_RANDOM, origin_picked);
198 /* If we added the first track, and something is playing, then prepare the
199 * new track. If nothing is playing then we don't bother as it wouldn't gain
201 if(q == qhead.next && playing)
203 sink_printf(ev_writer_sink(c->w), "252 %s\n", q->id);
204 /* If the queue was empty but we are for some reason paused then
206 if(!playing) resume_playing(0);
208 return 1; /* completed */
211 static int c_remove(struct conn *c, char **vec,
212 int attribute((unused)) nvec) {
213 struct queue_entry *q;
215 if(!(q = queue_find(vec[0]))) {
216 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
219 if(!right_removable(c->rights, c->who, q)) {
220 error(0, "%s attempted remove but lacks required rights", c->who);
221 sink_writes(ev_writer_sink(c->w),
222 "510 Not authorized to remove that track\n");
225 queue_remove(q, c->who);
226 /* De-prepare the track. */
228 /* See about adding a new random track */
229 add_random_track(c->ev);
230 /* Prepare whatever the next head track is. */
231 if(qhead.next != &qhead)
232 prepare(c->ev, qhead.next);
234 sink_writes(ev_writer_sink(c->w), "250 removed\n");
235 return 1; /* completed */
238 static int c_scratch(struct conn *c,
242 sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
243 return 1; /* completed */
245 /* TODO there is a bug here: if we specify an ID but it's not the currently
246 * playing track then you will get 550 if you weren't authorized to scratch
247 * the currently playing track. */
248 if(!right_scratchable(c->rights, c->who, playing)) {
249 error(0, "%s attempted scratch but lacks required rights", c->who);
250 sink_writes(ev_writer_sink(c->w),
251 "510 Not authorized to scratch that track\n");
254 scratch(c->who, nvec == 1 ? vec[0] : 0);
255 /* If you scratch an unpaused track then it is automatically unpaused */
257 sink_writes(ev_writer_sink(c->w), "250 scratched\n");
258 return 1; /* completed */
261 static int c_pause(struct conn *c,
262 char attribute((unused)) **vec,
263 int attribute((unused)) nvec) {
265 sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
266 return 1; /* completed */
269 sink_writes(ev_writer_sink(c->w), "250 already paused\n");
270 return 1; /* completed */
272 if(pause_playing(c->who) < 0)
273 sink_writes(ev_writer_sink(c->w), "550 cannot pause this track\n");
275 sink_writes(ev_writer_sink(c->w), "250 paused\n");
279 static int c_resume(struct conn *c,
280 char attribute((unused)) **vec,
281 int attribute((unused)) nvec) {
283 sink_writes(ev_writer_sink(c->w), "250 not paused\n");
284 return 1; /* completed */
286 resume_playing(c->who);
287 sink_writes(ev_writer_sink(c->w), "250 paused\n");
291 static int c_shutdown(struct conn *c,
292 char attribute((unused)) **vec,
293 int attribute((unused)) nvec) {
294 info("S%x shut down by %s", c->tag, c->who);
295 sink_writes(ev_writer_sink(c->w), "250 shutting down\n");
296 ev_writer_flush(c->w);
300 static int c_reconfigure(struct conn *c,
301 char attribute((unused)) **vec,
302 int attribute((unused)) nvec) {
303 info("S%x reconfigure by %s", c->tag, c->who);
304 if(reconfigure(c->ev, 1))
305 sink_writes(ev_writer_sink(c->w), "550 error reading new config\n");
307 sink_writes(ev_writer_sink(c->w), "250 installed new config\n");
308 return 1; /* completed */
311 static void finished_rescan(void *ru) {
312 struct conn *const c = ru;
314 sink_writes(ev_writer_sink(c->w), "250 rescan completed\n");
315 /* Turn this connection back on */
316 ev_reader_enable(c->r);
319 static void start_fresh_rescan(void *ru) {
320 struct conn *const c = ru;
322 if(trackdb_rescan_underway()) {
323 /* Some other waiter beat us to it. However in this case we're happy to
324 * piggyback; the requirement is that a new rescan be started, not that it
325 * was _our_ rescan. */
327 /* We block until the rescan completes */
328 trackdb_add_rescanned(finished_rescan, c);
330 /* We report that the new rescan has started */
331 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
332 /* Turn this connection back on */
333 ev_reader_enable(c->r);
336 /* We are the first connection to get a callback so we must start a
339 /* We want to block until the new rescan completes */
340 trackdb_rescan(c->ev, 1/*check*/, finished_rescan, c);
342 /* We can report back immediately */
343 trackdb_rescan(c->ev, 1/*check*/, 0, 0);
344 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
345 /* Turn this connection back on */
346 ev_reader_enable(c->r);
351 static int c_rescan(struct conn *c,
354 int flag_wait = 0, flag_fresh = 0, n;
357 for(n = 0; n < nvec; ++n) {
358 if(!strcmp(vec[n], "wait"))
359 flag_wait = 1; /* wait for rescan to complete */
361 /* Currently disabled because untested (and hard to test). */
362 else if(!strcmp(vec[n], "fresh"))
363 flag_fresh = 1; /* don't piggyback underway rescan */
366 sink_writes(ev_writer_sink(c->w), "550 unknown flag\n");
367 return 1; /* completed */
370 /* Report what was requested */
371 info("S%x rescan by %s (%s %s)", c->tag, c->who,
372 flag_wait ? "wait" : "",
373 flag_fresh ? "fresh" : "");
374 if(trackdb_rescan_underway()) {
376 /* We want a fresh rescan but there is already one underway. Arrange a
377 * callback when it completes and then set off a new one. */
378 c->rescan_wait = flag_wait;
379 trackdb_add_rescanned(start_fresh_rescan, c);
383 sink_writes(ev_writer_sink(c->w), "250 rescan queued\n");
387 /* There's a rescan underway, and it's acceptable to piggyback on it */
389 /* We want to block until completion. */
390 trackdb_add_rescanned(finished_rescan, c);
393 /* We don't want to block. So we just report that things are in
395 sink_writes(ev_writer_sink(c->w), "250 rescan already underway\n");
400 /* No rescan is underway. fresh is therefore irrelevant. */
402 /* We want to block until completion */
403 trackdb_rescan(c->ev, 1/*check*/, finished_rescan, c);
406 /* We don't want to block. */
407 trackdb_rescan(c->ev, 1/*check*/, 0, 0);
408 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
409 return 1; /* completed */
414 static int c_version(struct conn *c,
415 char attribute((unused)) **vec,
416 int attribute((unused)) nvec) {
417 /* VERSION had better only use the basic character set */
418 sink_printf(ev_writer_sink(c->w), "251 %s\n", disorder_short_version_string);
419 return 1; /* completed */
422 static int c_playing(struct conn *c,
423 char attribute((unused)) **vec,
424 int attribute((unused)) nvec) {
426 queue_fix_sofar(playing);
427 playing->expected = 0;
428 sink_printf(ev_writer_sink(c->w), "252 %s\n", queue_marshall(playing));
430 sink_printf(ev_writer_sink(c->w), "259 nothing playing\n");
431 return 1; /* completed */
434 static const char *connection_host(struct conn *c) {
437 struct sockaddr_in in;
438 struct sockaddr_in6 in6;
444 /* get connection data */
446 if(getpeername(c->fd, &u.sa, &l) < 0) {
447 error(errno, "S%x error calling getpeername", c->tag);
450 if(c->l->pf != PF_UNIX) {
451 if((n = getnameinfo(&u.sa, l,
452 host, sizeof host, 0, 0, NI_NUMERICHOST))) {
453 error(0, "S%x error calling getnameinfo: %s", c->tag, gai_strerror(n));
456 return xstrdup(host);
461 static int c_user(struct conn *c,
463 int attribute((unused)) nvec) {
465 const char *res, *host, *password;
469 sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
472 /* get connection data */
473 if(!(host = connection_host(c))) {
474 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
478 k = trackdb_getuserinfo(vec[0]);
479 /* reject nonexistent users */
481 error(0, "S%x unknown user '%s' from %s", c->tag, vec[0], host);
482 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
485 /* reject unconfirmed users */
486 if(kvp_get(k, "confirmation")) {
487 error(0, "S%x unconfirmed user '%s' from %s", c->tag, vec[0], host);
488 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
491 password = kvp_get(k, "password");
492 if(!password) password = "";
493 if(parse_rights(kvp_get(k, "rights"), &rights, 1)) {
494 error(0, "error parsing rights for %s", vec[0]);
495 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
498 /* check whether the response is right */
499 res = authhash(c->nonce, sizeof c->nonce, password,
500 config->authorization_algorithm);
501 if(wideopen || (res && !strcmp(res, vec[1]))) {
504 /* currently we only bother logging remote connections */
505 if(strcmp(host, "local"))
506 info("S%x %s connected from %s", c->tag, vec[0], host);
508 c->rights |= RIGHT__LOCAL;
509 sink_writes(ev_writer_sink(c->w), "230 OK\n");
512 /* oops, response was wrong */
513 info("S%x authentication failure for %s from %s", c->tag, vec[0], host);
514 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
518 static int c_recent(struct conn *c,
519 char attribute((unused)) **vec,
520 int attribute((unused)) nvec) {
521 const struct queue_entry *q;
523 sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
524 for(q = phead.next; q != &phead; q = q->next)
525 sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
526 sink_writes(ev_writer_sink(c->w), ".\n");
527 return 1; /* completed */
530 static int c_queue(struct conn *c,
531 char attribute((unused)) **vec,
532 int attribute((unused)) nvec) {
533 struct queue_entry *q;
538 sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
539 if(playing_is_enabled() && !paused) {
541 queue_fix_sofar(playing);
542 if((l = trackdb_get(playing->track, "_length"))
543 && (length = atol(l))) {
545 when += length - playing->sofar + config->gap;
548 /* Nothing is playing but playing is enabled, so whatever is
549 * first in the queue can be expected to start immediately. */
552 for(q = qhead.next; q != &qhead; q = q->next) {
553 /* fill in estimated start time */
555 sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
556 /* update for next track */
558 if((l = trackdb_get(q->track, "_length"))
559 && (length = atol(l)))
560 when += length + config->gap;
565 sink_writes(ev_writer_sink(c->w), ".\n");
566 return 1; /* completed */
569 static int output_list(struct conn *c, char **vec) {
571 sink_printf(ev_writer_sink(c->w), "%s\n", *vec++);
572 sink_writes(ev_writer_sink(c->w), ".\n");
576 static int files_dirs(struct conn *c,
579 enum trackdb_listable what) {
580 const char *dir, *re, *errstr;
586 case 0: dir = 0; re = 0; break;
587 case 1: dir = vec[0]; re = 0; break;
588 case 2: dir = vec[0]; re = vec[1]; break;
591 /* A bit of a bodge to make sure the args don't trample on cache keys */
592 if(dir && strchr(dir, '\n')) {
593 sink_writes(ev_writer_sink(c->w), "550 invalid directory name\n");
596 if(re && strchr(re, '\n')) {
597 sink_writes(ev_writer_sink(c->w), "550 invalid regexp\n");
600 /* We bother eliminating "" because the web interface is relatively
601 * likely to send it */
603 byte_xasprintf(&key, "%d\n%s\n%s", (int)what, dir ? dir : "", re);
604 fvec = (char **)cache_get(&cache_files_type, key);
606 /* Got a cache hit, don't store the answer in the cache */
609 rec = 0; /* quieten compiler */
611 /* Cache miss, we'll do the lookup and key != 0 so we'll store the answer
613 if(!(rec = pcre_compile(re, PCRE_CASELESS|PCRE_UTF8,
614 &errstr, &erroffset, 0))) {
615 sink_printf(ev_writer_sink(c->w), "550 Error compiling regexp: %s\n",
619 /* It only counts as a miss if the regexp was valid. */
620 ++cache_files_misses;
623 /* No regexp, don't bother caching the result */
629 /* No cache hit (either because a miss, or because we did not look) so do
632 fvec = trackdb_list(dir, 0, what, rec);
634 fvec = trackdb_list(0, 0, what, rec);
637 /* Put the answer in the cache */
638 cache_put(&cache_files_type, key, fvec);
639 sink_writes(ev_writer_sink(c->w), "253 Listing follow\n");
640 return output_list(c, fvec);
643 static int c_files(struct conn *c,
646 return files_dirs(c, vec, nvec, trackdb_files);
649 static int c_dirs(struct conn *c,
652 return files_dirs(c, vec, nvec, trackdb_directories);
655 static int c_allfiles(struct conn *c,
658 return files_dirs(c, vec, nvec, trackdb_directories|trackdb_files);
661 static int c_get(struct conn *c,
663 int attribute((unused)) nvec) {
664 const char *v, *track;
666 if(!(track = trackdb_resolve(vec[0]))) {
667 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
670 if(vec[1][0] != '_' && (v = trackdb_get(track, vec[1])))
671 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
673 sink_writes(ev_writer_sink(c->w), "555 not found\n");
677 static int c_length(struct conn *c,
679 int attribute((unused)) nvec) {
680 const char *track, *v;
682 if(!(track = trackdb_resolve(vec[0]))) {
683 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
686 if((v = trackdb_get(track, "_length")))
687 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
689 sink_writes(ev_writer_sink(c->w), "550 not found\n");
693 static int c_set(struct conn *c,
695 int attribute((unused)) nvec) {
698 if(!(track = trackdb_resolve(vec[0]))) {
699 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
702 if(vec[1][0] != '_' && !trackdb_set(track, vec[1], vec[2]))
703 sink_writes(ev_writer_sink(c->w), "250 OK\n");
705 sink_writes(ev_writer_sink(c->w), "550 not found\n");
709 static int c_prefs(struct conn *c,
711 int attribute((unused)) nvec) {
715 if(!(track = trackdb_resolve(vec[0]))) {
716 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
719 k = trackdb_get_all(track);
720 sink_writes(ev_writer_sink(c->w), "253 prefs follow\n");
721 for(; k; k = k->next)
722 if(k->name[0] != '_') /* omit internal values */
723 sink_printf(ev_writer_sink(c->w),
724 " %s %s\n", quoteutf8(k->name), quoteutf8(k->value));
725 sink_writes(ev_writer_sink(c->w), ".\n");
729 static int c_exists(struct conn *c,
731 int attribute((unused)) nvec) {
732 /* trackdb_exists() does its own alias checking */
733 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[trackdb_exists(vec[0])]);
737 static void search_parse_error(const char *msg, void *u) {
738 *(const char **)u = msg;
741 static int c_search(struct conn *c,
743 int attribute((unused)) nvec) {
744 char **terms, **results;
745 int nterms, nresults, n;
746 const char *e = "unknown error";
748 /* This is a bit of a bodge. Initially it's there to make the eclient
749 * interface a bit more convenient to add searching to, but it has the more
750 * compelling advantage that if everything uses it, then interpretation of
751 * user-supplied search strings will be the same everywhere. */
752 if(!(terms = split(vec[0], &nterms, SPLIT_QUOTES, search_parse_error, &e))) {
753 sink_printf(ev_writer_sink(c->w), "550 %s\n", e);
755 results = trackdb_search(terms, nterms, &nresults);
756 sink_printf(ev_writer_sink(c->w), "253 %d matches\n", nresults);
757 for(n = 0; n < nresults; ++n)
758 sink_printf(ev_writer_sink(c->w), "%s\n", results[n]);
759 sink_writes(ev_writer_sink(c->w), ".\n");
764 static int c_random_enable(struct conn *c,
765 char attribute((unused)) **vec,
766 int attribute((unused)) nvec) {
767 enable_random(c->who, c->ev);
768 /* Enable implicitly unpauses if there is nothing playing */
769 if(paused && !playing) resume_playing(c->who);
770 sink_writes(ev_writer_sink(c->w), "250 OK\n");
771 return 1; /* completed */
774 static int c_random_disable(struct conn *c,
775 char attribute((unused)) **vec,
776 int attribute((unused)) nvec) {
777 disable_random(c->who);
778 sink_writes(ev_writer_sink(c->w), "250 OK\n");
779 return 1; /* completed */
782 static int c_random_enabled(struct conn *c,
783 char attribute((unused)) **vec,
784 int attribute((unused)) nvec) {
785 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[random_is_enabled()]);
786 return 1; /* completed */
789 static void got_stats(char *stats, void *u) {
790 struct conn *const c = u;
792 sink_printf(ev_writer_sink(c->w), "253 stats\n%s\n.\n", stats);
793 /* Now we can start processing commands again */
794 ev_reader_enable(c->r);
797 static int c_stats(struct conn *c,
798 char attribute((unused)) **vec,
799 int attribute((unused)) nvec) {
800 trackdb_stats_subprocess(c->ev, got_stats, c);
801 return 0; /* not yet complete */
804 static int c_volume(struct conn *c,
816 l = r = atoi(vec[0]);
827 rights = set ? RIGHT_VOLUME : RIGHT_READ;
828 if(!(c->rights & rights)) {
829 error(0, "%s attempted to set volume but lacks required rights", c->who);
830 sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
833 if(!api || !api->set_volume) {
834 sink_writes(ev_writer_sink(c->w), "550 error accessing mixer\n");
837 (set ? api->set_volume : api->get_volume)(&l, &r);
838 sink_printf(ev_writer_sink(c->w), "252 %d %d\n", l, r);
839 if(l != volume_left || r != volume_right) {
842 snprintf(lb, sizeof lb, "%d", l);
843 snprintf(rb, sizeof rb, "%d", r);
844 eventlog("volume", lb, rb, (char *)0);
849 /** @brief Called when data arrives on a log connection
851 * We just discard all such data. The client may occasionally send data as a
854 static int logging_reader_callback(ev_source attribute((unused)) *ev,
856 void attribute((unused)) *ptr,
858 int attribute((unused)) eof,
859 void attribute((unused)) *u) {
862 ev_reader_consume(reader, bytes);
864 /* Oops, that's all for now */
865 D(("logging reader eof"));
868 ev_writer_close(c->w);
872 remove_connection(c);
877 static void logclient(const char *msg, void *user) {
878 struct conn *c = user;
881 /* This connection has gone up in smoke for some reason */
882 eventlog_remove(c->lo);
886 /* user_* messages are restricted */
887 if(!strncmp(msg, "user_", 5)) {
888 /* They are only sent to admin users */
889 if(!(c->rights & RIGHT_ADMIN))
891 /* They are not sent over TCP connections unless remote user-management is
893 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL))
896 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" %s\n",
897 (uintmax_t)time(0), msg);
900 static int c_log(struct conn *c,
901 char attribute((unused)) **vec,
902 int attribute((unused)) nvec) {
905 sink_writes(ev_writer_sink(c->w), "254 OK\n");
906 /* pump out initial state */
908 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
910 playing_is_enabled() ? "enable_play" : "disable_play");
911 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
913 random_is_enabled() ? "enable_random" : "disable_random");
914 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
916 paused ? "pause" : "resume");
918 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state playing\n",
921 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" volume %d %d\n",
922 (uintmax_t)now, volume_left, volume_right);
923 c->lo = xmalloc(sizeof *c->lo);
924 c->lo->fn = logclient;
927 c->reader = logging_reader_callback;
931 /** @brief Test whether a move is allowed
932 * @param c Connection
933 * @param qs List of IDs on queue
934 * @param nqs Number of IDs
935 * @return 0 if move is prohibited, non-0 if it is allowed
937 static int has_move_rights(struct conn *c, struct queue_entry **qs, int nqs) {
938 for(; nqs > 0; ++qs, --nqs) {
939 struct queue_entry *const q = *qs;
941 if(!right_movable(c->rights, c->who, q))
947 static int c_move(struct conn *c,
949 int attribute((unused)) nvec) {
950 struct queue_entry *q;
953 if(!(q = queue_find(vec[0]))) {
954 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
957 if(!has_move_rights(c, &q, 1)) {
958 error(0, "%s attempted move but lacks required rights", c->who);
959 sink_writes(ev_writer_sink(c->w),
960 "510 Not authorized to move that track\n");
963 n = queue_move(q, atoi(vec[1]), c->who);
964 sink_printf(ev_writer_sink(c->w), "252 %d\n", n);
965 /* If we've moved to the head of the queue then prepare the track. */
971 static int c_moveafter(struct conn *c,
973 int attribute((unused)) nvec) {
974 struct queue_entry *q, **qs;
978 if(!(q = queue_find(vec[0]))) {
979 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
986 qs = xcalloc(nvec, sizeof *qs);
987 for(n = 0; n < nvec; ++n)
988 if(!(qs[n] = queue_find(vec[n]))) {
989 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
992 if(!has_move_rights(c, qs, nvec)) {
993 error(0, "%s attempted moveafter but lacks required rights", c->who);
994 sink_writes(ev_writer_sink(c->w),
995 "510 Not authorized to move those tracks\n");
998 queue_moveafter(q, nvec, qs, c->who);
999 sink_printf(ev_writer_sink(c->w), "250 Moved tracks\n");
1000 /* If we've moved to the head of the queue then prepare the track. */
1006 static int c_part(struct conn *c,
1008 int attribute((unused)) nvec) {
1011 if(!(track = trackdb_resolve(vec[0]))) {
1012 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1015 sink_printf(ev_writer_sink(c->w), "252 %s\n",
1016 quoteutf8(trackdb_getpart(track, vec[1], vec[2])));
1020 static int c_resolve(struct conn *c,
1022 int attribute((unused)) nvec) {
1025 if(!(track = trackdb_resolve(vec[0]))) {
1026 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1029 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(track));
1033 static int c_tags(struct conn *c,
1034 char attribute((unused)) **vec,
1035 int attribute((unused)) nvec) {
1036 char **tags = trackdb_alltags();
1038 sink_printf(ev_writer_sink(c->w), "253 Tag list follows\n");
1040 sink_printf(ev_writer_sink(c->w), "%s%s\n",
1041 **tags == '.' ? "." : "", *tags);
1044 sink_writes(ev_writer_sink(c->w), ".\n");
1045 return 1; /* completed */
1048 static int c_set_global(struct conn *c,
1050 int attribute((unused)) nvec) {
1051 if(vec[0][0] == '_') {
1052 sink_writes(ev_writer_sink(c->w), "550 cannot set internal global preferences\n");
1055 trackdb_set_global(vec[0], vec[1], c->who);
1056 sink_printf(ev_writer_sink(c->w), "250 OK\n");
1060 static int c_get_global(struct conn *c,
1062 int attribute((unused)) nvec) {
1063 const char *s = trackdb_get_global(vec[0]);
1066 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(s));
1068 sink_writes(ev_writer_sink(c->w), "555 not found\n");
1072 static int c_nop(struct conn *c,
1073 char attribute((unused)) **vec,
1074 int attribute((unused)) nvec) {
1075 sink_printf(ev_writer_sink(c->w), "250 Quack\n");
1079 static int c_new(struct conn *c,
1089 if(max <= 0 || max > config->new_max)
1090 max = config->new_max;
1091 tracks = trackdb_new(0, max);
1092 sink_printf(ev_writer_sink(c->w), "253 New track list follows\n");
1095 sink_printf(ev_writer_sink(c->w), "%s%s\n",
1096 **tracks == '.' ? "." : "", *tracks);
1099 sink_writes(ev_writer_sink(c->w), ".\n");
1100 return 1; /* completed */
1104 static int c_rtp_address(struct conn *c,
1105 char attribute((unused)) **vec,
1106 int attribute((unused)) nvec) {
1107 if(api == &uaudio_rtp) {
1108 sink_printf(ev_writer_sink(c->w), "252 %s %s\n",
1109 quoteutf8(config->broadcast.s[0]),
1110 quoteutf8(config->broadcast.s[1]));
1112 sink_writes(ev_writer_sink(c->w), "550 No RTP\n");
1116 static int c_cookie(struct conn *c,
1118 int attribute((unused)) nvec) {
1123 /* Can't log in twice on the same connection */
1125 sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
1128 /* Get some kind of peer identifcation */
1129 if(!(host = connection_host(c))) {
1130 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1133 /* Check the cookie */
1134 user = verify_cookie(vec[0], &rights);
1136 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1143 if(strcmp(host, "local"))
1144 info("S%x %s connected with cookie from %s", c->tag, user, host);
1146 c->rights |= RIGHT__LOCAL;
1147 /* Response contains username so client knows who they are acting as */
1148 sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
1152 static int c_make_cookie(struct conn *c,
1153 char attribute((unused)) **vec,
1154 int attribute((unused)) nvec) {
1155 const char *cookie = make_cookie(c->who);
1158 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cookie));
1160 sink_writes(ev_writer_sink(c->w), "550 Cannot create cookie\n");
1164 static int c_revoke(struct conn *c,
1165 char attribute((unused)) **vec,
1166 int attribute((unused)) nvec) {
1168 revoke_cookie(c->cookie);
1169 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1171 sink_writes(ev_writer_sink(c->w), "550 Did not log in with cookie\n");
1175 static int c_adduser(struct conn *c,
1180 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1181 error(0, "S%x: remote adduser", c->tag);
1182 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1187 if(parse_rights(vec[2], 0, 1)) {
1188 sink_writes(ev_writer_sink(c->w), "550 Invalid rights list\n");
1192 rights = config->default_rights;
1193 if(trackdb_adduser(vec[0], vec[1], rights,
1194 0/*email*/, 0/*confirmation*/))
1195 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1197 sink_writes(ev_writer_sink(c->w), "250 User created\n");
1201 static int c_deluser(struct conn *c,
1203 int attribute((unused)) nvec) {
1206 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1207 error(0, "S%x: remote deluser", c->tag);
1208 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1211 if(trackdb_deluser(vec[0])) {
1212 sink_writes(ev_writer_sink(c->w), "550 Cannot delete user\n");
1215 /* Zap connections belonging to deleted user */
1216 for(d = connections; d; d = d->next)
1217 if(!strcmp(d->who, vec[0]))
1219 sink_writes(ev_writer_sink(c->w), "250 User deleted\n");
1223 static int c_edituser(struct conn *c,
1225 int attribute((unused)) nvec) {
1228 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1229 error(0, "S%x: remote edituser", c->tag);
1230 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1233 /* RIGHT_ADMIN can do anything; otherwise you can only set your own email
1234 * address and password. */
1235 if((c->rights & RIGHT_ADMIN)
1236 || (!strcmp(c->who, vec[0])
1237 && (!strcmp(vec[1], "email")
1238 || !strcmp(vec[1], "password")))) {
1239 if(trackdb_edituserinfo(vec[0], vec[1], vec[2])) {
1240 sink_writes(ev_writer_sink(c->w), "550 Failed to change setting\n");
1243 if(!strcmp(vec[1], "password")) {
1244 /* Zap all connections for this user after a password change */
1245 for(d = connections; d; d = d->next)
1246 if(!strcmp(d->who, vec[0]))
1248 } else if(!strcmp(vec[1], "rights")) {
1249 /* Update rights for this user */
1252 if(!parse_rights(vec[2], &r, 1)) {
1253 const char *new_rights = rights_string(r);
1254 for(d = connections; d; d = d->next) {
1255 if(!strcmp(d->who, vec[0])) {
1258 /* Notify any log connections */
1260 sink_printf(ev_writer_sink(d->w),
1261 "%"PRIxMAX" rights_changed %s\n",
1263 quoteutf8(new_rights));
1268 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1270 error(0, "%s attempted edituser but lacks required rights", c->who);
1271 sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
1276 static int c_userinfo(struct conn *c,
1277 char attribute((unused)) **vec,
1278 int attribute((unused)) nvec) {
1282 /* We allow remote querying of rights so that clients can figure out what
1283 * they're allowed to do */
1284 if(!config->remote_userman
1285 && !(c->rights & RIGHT__LOCAL)
1286 && strcmp(vec[1], "rights")) {
1287 error(0, "S%x: remote userinfo %s %s", c->tag, vec[0], vec[1]);
1288 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1291 /* RIGHT_ADMIN allows anything; otherwise you can only get your own email
1292 * address and rights list. */
1293 if((c->rights & RIGHT_ADMIN)
1294 || (!strcmp(c->who, vec[0])
1295 && (!strcmp(vec[1], "email")
1296 || !strcmp(vec[1], "rights")))) {
1297 if((k = trackdb_getuserinfo(vec[0])))
1298 if((value = kvp_get(k, vec[1])))
1299 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(value));
1301 sink_writes(ev_writer_sink(c->w), "555 Not set\n");
1303 sink_writes(ev_writer_sink(c->w), "550 No such user\n");
1305 error(0, "%s attempted userinfo but lacks required rights", c->who);
1306 sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
1311 static int c_users(struct conn *c,
1312 char attribute((unused)) **vec,
1313 int attribute((unused)) nvec) {
1314 /* TODO de-dupe with c_tags */
1315 char **users = trackdb_listusers();
1317 sink_writes(ev_writer_sink(c->w), "253 User list follows\n");
1319 sink_printf(ev_writer_sink(c->w), "%s%s\n",
1320 **users == '.' ? "." : "", *users);
1323 sink_writes(ev_writer_sink(c->w), ".\n");
1324 return 1; /* completed */
1327 static int c_register(struct conn *c,
1329 int attribute((unused)) nvec) {
1331 uint32_t nonce[CONFIRM_SIZE];
1332 char nonce_str[(32 * CONFIRM_SIZE) / 5 + 1];
1334 /* The confirmation string is username/base62(nonce). The confirmation
1335 * process will pick the username back out to identify them but the _whole_
1336 * string is used as the confirmation string. Base 62 means we used only
1337 * letters and digits, minimizing the chance of the URL being mispasted. */
1338 gcry_randomize(nonce, sizeof nonce, GCRY_STRONG_RANDOM);
1339 if(basen(nonce, CONFIRM_SIZE, nonce_str, sizeof nonce_str, 62)) {
1340 error(0, "buffer too small encoding confirmation string");
1341 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1343 byte_xasprintf(&cs, "%s/%s", vec[0], nonce_str);
1344 if(trackdb_adduser(vec[0], vec[1], config->default_rights, vec[2], cs))
1345 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1347 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cs));
1351 static int c_confirm(struct conn *c,
1353 int attribute((unused)) nvec) {
1358 /* Get some kind of peer identifcation */
1359 if(!(host = connection_host(c))) {
1360 sink_writes(ev_writer_sink(c->w), "530 Authentication failure\n");
1363 /* Picking the LAST / means we don't (here) rule out slashes in usernames. */
1364 if(!(sep = strrchr(vec[0], '/'))) {
1365 sink_writes(ev_writer_sink(c->w), "550 Malformed confirmation string\n");
1368 user = xstrndup(vec[0], sep - vec[0]);
1369 if(trackdb_confirm(user, vec[0], &rights))
1370 sink_writes(ev_writer_sink(c->w), "550 Incorrect confirmation string\n");
1375 if(strcmp(host, "local"))
1376 info("S%x %s confirmed from %s", c->tag, user, host);
1378 c->rights |= RIGHT__LOCAL;
1379 /* Response contains username so client knows who they are acting as */
1380 sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
1385 static int sent_reminder(ev_source attribute((unused)) *ev,
1386 pid_t attribute((unused)) pid,
1388 const struct rusage attribute((unused)) *rusage,
1390 struct conn *const c = u;
1392 /* Tell the client what went down */
1394 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1396 error(0, "reminder subprocess %s", wstat(status));
1397 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1399 /* Re-enable this connection */
1400 ev_reader_enable(c->r);
1404 static int c_reminder(struct conn *c,
1406 int attribute((unused)) nvec) {
1408 const char *password, *email, *text, *encoding, *charset, *content_type;
1413 static hash *last_reminder;
1415 if(!config->mail_sender) {
1416 error(0, "cannot send password reminders because mail_sender not set");
1417 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1420 if(!(k = trackdb_getuserinfo(vec[0]))) {
1421 error(0, "reminder for user '%s' who does not exist", vec[0]);
1422 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1425 if(!(email = kvp_get(k, "email"))
1426 || !email_valid(email)) {
1427 error(0, "user '%s' has no valid email address", vec[0]);
1428 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1431 if(!(password = kvp_get(k, "password"))
1433 error(0, "user '%s' has no password", vec[0]);
1434 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1437 /* Rate-limit reminders. This hash is bounded in size by the number of
1438 * users. If this is actually a problem for anyone then we can periodically
1441 last_reminder = hash_new(sizeof (time_t));
1442 last = hash_find(last_reminder, vec[0]);
1444 if(last && now < *last + config->reminder_interval) {
1445 error(0, "sent a password reminder to '%s' too recently", vec[0]);
1446 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1449 /* Send the reminder */
1450 /* TODO this should be templatized and to some extent merged with
1451 * the code in act_register() */
1452 byte_xasprintf((char **)&text,
1453 "Someone requested that you be sent a reminder of your DisOrder password.\n"
1454 "Your password is:\n"
1457 if(!(text = mime_encode_text(text, &charset, &encoding)))
1458 fatal(0, "cannot encode email");
1459 byte_xasprintf((char **)&content_type, "text/plain;charset=%s",
1460 quote822(charset, 0));
1461 pid = sendmail_subprocess("", config->mail_sender, email,
1462 "DisOrder password reminder",
1463 encoding, content_type, text);
1465 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1468 hash_add(last_reminder, vec[0], &now, HASH_INSERT_OR_REPLACE);
1469 info("sending a passsword reminder to user '%s'", vec[0]);
1470 /* We can only continue when the subprocess finishes */
1471 ev_child(c->ev, pid, 0, sent_reminder, c);
1475 static int c_schedule_list(struct conn *c,
1476 char attribute((unused)) **vec,
1477 int attribute((unused)) nvec) {
1478 char **ids = schedule_list(0);
1479 sink_writes(ev_writer_sink(c->w), "253 ID list follows\n");
1481 sink_printf(ev_writer_sink(c->w), "%s\n", *ids++);
1482 sink_writes(ev_writer_sink(c->w), ".\n");
1483 return 1; /* completed */
1486 static int c_schedule_get(struct conn *c,
1488 int attribute((unused)) nvec) {
1489 struct kvp *actiondata = schedule_get(vec[0]), *k;
1492 sink_writes(ev_writer_sink(c->w), "555 No such event\n");
1493 return 1; /* completed */
1495 /* Scheduled events are public information. Anyone with RIGHT_READ can see
1497 sink_writes(ev_writer_sink(c->w), "253 Event information follows\n");
1498 for(k = actiondata; k; k = k->next)
1499 sink_printf(ev_writer_sink(c->w), " %s %s\n",
1500 quoteutf8(k->name), quoteutf8(k->value));
1501 sink_writes(ev_writer_sink(c->w), ".\n");
1502 return 1; /* completed */
1505 static int c_schedule_del(struct conn *c,
1507 int attribute((unused)) nvec) {
1508 struct kvp *actiondata = schedule_get(vec[0]);
1511 sink_writes(ev_writer_sink(c->w), "555 No such event\n");
1512 return 1; /* completed */
1514 /* If you have admin rights you can delete anything. If you don't then you
1515 * can only delete your own scheduled events. */
1516 if(!(c->rights & RIGHT_ADMIN)) {
1517 const char *who = kvp_get(actiondata, "who");
1519 if(!who || !c->who || strcmp(who, c->who)) {
1520 sink_writes(ev_writer_sink(c->w), "551 Not authorized\n");
1521 return 1; /* completed */
1524 if(schedule_del(vec[0]))
1525 sink_writes(ev_writer_sink(c->w), "550 Could not delete scheduled event\n");
1527 sink_writes(ev_writer_sink(c->w), "250 Deleted\n");
1528 return 1; /* completed */
1531 static int c_schedule_add(struct conn *c,
1534 struct kvp *actiondata = 0;
1537 /* Standard fields */
1538 kvp_set(&actiondata, "who", c->who);
1539 kvp_set(&actiondata, "when", vec[0]);
1540 kvp_set(&actiondata, "priority", vec[1]);
1541 kvp_set(&actiondata, "action", vec[2]);
1542 /* Action-dependent fields */
1543 if(!strcmp(vec[2], "play")) {
1545 sink_writes(ev_writer_sink(c->w), "550 Wrong number of arguments\n");
1548 if(!trackdb_exists(vec[3])) {
1549 sink_writes(ev_writer_sink(c->w), "550 Track is not in database\n");
1552 kvp_set(&actiondata, "track", vec[3]);
1553 } else if(!strcmp(vec[2], "set-global")) {
1554 if(nvec < 4 || nvec > 5) {
1555 sink_writes(ev_writer_sink(c->w), "550 Wrong number of arguments\n");
1558 kvp_set(&actiondata, "key", vec[3]);
1560 kvp_set(&actiondata, "value", vec[4]);
1562 sink_writes(ev_writer_sink(c->w), "550 Unknown action\n");
1565 /* schedule_add() checks user rights */
1566 id = schedule_add(c->ev, actiondata);
1568 sink_writes(ev_writer_sink(c->w), "550 Cannot add scheduled event\n");
1570 sink_printf(ev_writer_sink(c->w), "252 %s\n", id);
1574 static int c_adopt(struct conn *c,
1576 int attribute((unused)) nvec) {
1577 struct queue_entry *q;
1580 sink_writes(ev_writer_sink(c->w), "550 no identity\n");
1583 if(!(q = queue_find(vec[0]))) {
1584 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1587 if(q->origin != origin_random) {
1588 sink_writes(ev_writer_sink(c->w), "550 not a random track\n");
1591 q->origin = origin_adopted;
1592 q->submitter = xstrdup(c->who);
1593 eventlog("adopted", q->id, q->submitter, (char *)0);
1595 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1599 static const struct command {
1600 /** @brief Command name */
1603 /** @brief Minimum number of arguments */
1606 /** @brief Maximum number of arguments */
1609 /** @brief Function to process command */
1610 int (*fn)(struct conn *, char **, int);
1612 /** @brief Rights required to execute command
1614 * 0 means that the command can be issued without logging in. If multiple
1615 * bits are listed here any of those rights will do.
1619 { "adduser", 2, 3, c_adduser, RIGHT_ADMIN|RIGHT__LOCAL },
1620 { "adopt", 1, 1, c_adopt, RIGHT_PLAY },
1621 { "allfiles", 0, 2, c_allfiles, RIGHT_READ },
1622 { "confirm", 1, 1, c_confirm, 0 },
1623 { "cookie", 1, 1, c_cookie, 0 },
1624 { "deluser", 1, 1, c_deluser, RIGHT_ADMIN|RIGHT__LOCAL },
1625 { "dirs", 0, 2, c_dirs, RIGHT_READ },
1626 { "disable", 0, 1, c_disable, RIGHT_GLOBAL_PREFS },
1627 { "edituser", 3, 3, c_edituser, RIGHT_ADMIN|RIGHT_USERINFO },
1628 { "enable", 0, 0, c_enable, RIGHT_GLOBAL_PREFS },
1629 { "enabled", 0, 0, c_enabled, RIGHT_READ },
1630 { "exists", 1, 1, c_exists, RIGHT_READ },
1631 { "files", 0, 2, c_files, RIGHT_READ },
1632 { "get", 2, 2, c_get, RIGHT_READ },
1633 { "get-global", 1, 1, c_get_global, RIGHT_READ },
1634 { "length", 1, 1, c_length, RIGHT_READ },
1635 { "log", 0, 0, c_log, RIGHT_READ },
1636 { "make-cookie", 0, 0, c_make_cookie, RIGHT_READ },
1637 { "move", 2, 2, c_move, RIGHT_MOVE__MASK },
1638 { "moveafter", 1, INT_MAX, c_moveafter, RIGHT_MOVE__MASK },
1639 { "new", 0, 1, c_new, RIGHT_READ },
1640 { "nop", 0, 0, c_nop, 0 },
1641 { "part", 3, 3, c_part, RIGHT_READ },
1642 { "pause", 0, 0, c_pause, RIGHT_PAUSE },
1643 { "play", 1, 1, c_play, RIGHT_PLAY },
1644 { "playing", 0, 0, c_playing, RIGHT_READ },
1645 { "prefs", 1, 1, c_prefs, RIGHT_READ },
1646 { "queue", 0, 0, c_queue, RIGHT_READ },
1647 { "random-disable", 0, 0, c_random_disable, RIGHT_GLOBAL_PREFS },
1648 { "random-enable", 0, 0, c_random_enable, RIGHT_GLOBAL_PREFS },
1649 { "random-enabled", 0, 0, c_random_enabled, RIGHT_READ },
1650 { "recent", 0, 0, c_recent, RIGHT_READ },
1651 { "reconfigure", 0, 0, c_reconfigure, RIGHT_ADMIN },
1652 { "register", 3, 3, c_register, RIGHT_REGISTER|RIGHT__LOCAL },
1653 { "reminder", 1, 1, c_reminder, RIGHT__LOCAL },
1654 { "remove", 1, 1, c_remove, RIGHT_REMOVE__MASK },
1655 { "rescan", 0, INT_MAX, c_rescan, RIGHT_RESCAN },
1656 { "resolve", 1, 1, c_resolve, RIGHT_READ },
1657 { "resume", 0, 0, c_resume, RIGHT_PAUSE },
1658 { "revoke", 0, 0, c_revoke, RIGHT_READ },
1659 { "rtp-address", 0, 0, c_rtp_address, 0 },
1660 { "schedule-add", 3, INT_MAX, c_schedule_add, RIGHT_READ },
1661 { "schedule-del", 1, 1, c_schedule_del, RIGHT_READ },
1662 { "schedule-get", 1, 1, c_schedule_get, RIGHT_READ },
1663 { "schedule-list", 0, 0, c_schedule_list, RIGHT_READ },
1664 { "scratch", 0, 1, c_scratch, RIGHT_SCRATCH__MASK },
1665 { "search", 1, 1, c_search, RIGHT_READ },
1666 { "set", 3, 3, c_set, RIGHT_PREFS, },
1667 { "set-global", 2, 2, c_set_global, RIGHT_GLOBAL_PREFS },
1668 { "shutdown", 0, 0, c_shutdown, RIGHT_ADMIN },
1669 { "stats", 0, 0, c_stats, RIGHT_READ },
1670 { "tags", 0, 0, c_tags, RIGHT_READ },
1671 { "unset", 2, 2, c_set, RIGHT_PREFS },
1672 { "unset-global", 1, 1, c_set_global, RIGHT_GLOBAL_PREFS },
1673 { "user", 2, 2, c_user, 0 },
1674 { "userinfo", 2, 2, c_userinfo, RIGHT_READ },
1675 { "users", 0, 0, c_users, RIGHT_READ },
1676 { "version", 0, 0, c_version, RIGHT_READ },
1677 { "volume", 0, 2, c_volume, RIGHT_READ|RIGHT_VOLUME }
1680 static void command_error(const char *msg, void *u) {
1683 sink_printf(ev_writer_sink(c->w), "500 parse error: %s\n", msg);
1686 /* process a command. Return 1 if complete, 0 if incomplete. */
1687 static int command(struct conn *c, char *line) {
1691 D(("server command %s", line));
1692 /* We force everything into NFC as early as possible */
1693 if(!(line = utf8_compose_canon(line, strlen(line), 0))) {
1694 sink_writes(ev_writer_sink(c->w), "500 cannot normalize command\n");
1697 if(!(vec = split(line, &nvec, SPLIT_QUOTES, command_error, c))) {
1698 sink_writes(ev_writer_sink(c->w), "500 cannot parse command\n");
1702 sink_writes(ev_writer_sink(c->w), "500 do what?\n");
1705 if((n = TABLE_FIND(commands, name, vec[0])) < 0)
1706 sink_writes(ev_writer_sink(c->w), "500 unknown command\n");
1708 if(commands[n].rights
1709 && !(c->rights & commands[n].rights)) {
1710 error(0, "%s attempted %s but lacks required rights", c->who ? c->who : "NULL",
1712 sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
1717 if(nvec < commands[n].minargs) {
1718 sink_writes(ev_writer_sink(c->w), "500 missing argument(s)\n");
1721 if(nvec > commands[n].maxargs) {
1722 sink_writes(ev_writer_sink(c->w), "500 too many arguments\n");
1725 return commands[n].fn(c, vec, nvec);
1727 return 1; /* completed */
1730 /* redirect to the right reader callback for our current state */
1731 static int redirect_reader_callback(ev_source *ev,
1739 return c->reader(ev, reader, ptr, bytes, eof, u);
1742 /* the main command reader */
1743 static int reader_callback(ev_source attribute((unused)) *ev,
1753 D(("server reader_callback"));
1754 while((eol = memchr(ptr, '\n', bytes))) {
1756 ev_reader_consume(reader, eol - (char *)ptr);
1757 complete = command(c, ptr);
1758 bytes -= (eol - (char *)ptr);
1761 /* the command had better have set a new reader callback */
1763 /* there are further bytes to read, or we are at eof; arrange for the
1764 * command's reader callback to handle them */
1765 return ev_reader_incomplete(reader);
1766 /* nothing's going on right now */
1769 /* command completed, we can go around and handle the next one */
1773 error(0, "S%x unterminated line", c->tag);
1774 D(("normal reader close"));
1777 D(("close associated writer"));
1778 ev_writer_close(c->w);
1781 remove_connection(c);
1786 static int listen_callback(ev_source *ev,
1788 const struct sockaddr attribute((unused)) *remote,
1789 socklen_t attribute((unused)) rlen,
1791 const struct listener *l = u;
1792 struct conn *c = xmalloc(sizeof *c);
1793 static unsigned tags;
1795 D(("server listen_callback fd %d (%s)", fd, l->name));
1798 c->next = connections;
1801 c->w = ev_writer_new(ev, fd, writer_error, c,
1804 error(0, "ev_writer_new for file inbound connection (fd=%d) failed",
1809 c->r = ev_reader_new(ev, fd, redirect_reader_callback, reader_error, c,
1812 /* Main reason for failure is the FD is too big and that will already have
1814 fatal(0, "ev_reader_new for file inbound connection (fd=%d) failed", fd);
1817 c->reader = reader_callback;
1821 gcry_randomize(c->nonce, sizeof c->nonce, GCRY_STRONG_RANDOM);
1822 sink_printf(ev_writer_sink(c->w), "231 %d %s %s\n",
1824 config->authorization_algorithm,
1825 hex(c->nonce, sizeof c->nonce));
1829 int server_start(ev_source *ev, int pf,
1830 size_t socklen, const struct sockaddr *sa,
1833 struct listener *l = xmalloc(sizeof *l);
1834 static const int one = 1;
1836 D(("server_init socket %s", name));
1837 fd = xsocket(pf, SOCK_STREAM, 0);
1838 xsetsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
1839 if(bind(fd, sa, socklen) < 0) {
1840 error(errno, "error binding to %s", name);
1848 if(ev_listen(ev, fd, listen_callback, l, "server listener"))
1853 int server_stop(ev_source *ev, int fd) {
1855 return ev_listen_cancel(ev, fd);