chiark / gitweb /
More conditional header inclusion.
[disorder] / server / server.c
CommitLineData
460b9539 1/*
2 * This file is part of DisOrder.
8a886602 3 * Copyright (C) 2004-2012 Richard Kettlewell
460b9539 4 *
e7eb3a27 5 * This program is free software: you can redistribute it and/or modify
460b9539 6 * it under the terms of the GNU General Public License as published by
e7eb3a27 7 * the Free Software Foundation, either version 3 of the License, or
460b9539 8 * (at your option) any later version.
9 *
e7eb3a27
RK
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.
14 *
460b9539 15 * You should have received a copy of the GNU General Public License
e7eb3a27 16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
460b9539 17 */
18
05b75f8d 19#include "disorder-server.h"
53710d44 20#include "basen.h"
460b9539 21
22#ifndef NONCE_SIZE
23# define NONCE_SIZE 16
24#endif
25
10114017 26#ifndef CONFIRM_SIZE
53710d44
RK
27/** @brief Size of nonce in confirmation string in 32-bit words
28 *
29 * 64 bits gives 11 digits (in base 62).
30 */
31# define CONFIRM_SIZE 2
10114017 32#endif
33
460b9539 34int volume_left, volume_right; /* last known volume */
35
18e6d6e6 36/** @brief Accept all well-formed login attempts
37 *
38 * Used in debugging.
39 */
40int wideopen;
41
460b9539 42struct listener {
43 const char *name;
44 int pf;
de37b640 45 int privileged;
460b9539 46};
47
f65f5aff
RK
48struct conn;
49
50/** @brief Signature for line reader callback
51 * @param c Connection
52 * @param line Line
53 * @return 0 if incomplete, 1 if complete
54 *
55 * @p line is 0-terminated and excludes the newline. It points into the
56 * input buffer so will become invalid shortly.
57 */
58typedef int line_reader_type(struct conn *c,
59 char *line);
60
61/** @brief Signature for with-body command callbacks
62 * @param c Connection
63 * @param body List of body lines
64 * @param nbody Number of body lines
65 * @param u As passed to fetch_body()
66 * @return 0 to suspend input, 1 if complete
67 *
68 * The body strings are allocated (so survive indefinitely) and don't include
69 * newlines.
70 */
71typedef int body_callback_type(struct conn *c,
72 char **body,
73 int nbody,
74 void *u);
75
397ef7bb 76/** @brief One client connection */
460b9539 77struct conn {
397ef7bb 78 /** @brief Read commands from here */
460b9539 79 ev_reader *r;
397ef7bb 80 /** @brief Send responses to here */
460b9539 81 ev_writer *w;
397ef7bb 82 /** @brief Underlying file descriptor */
460b9539 83 int fd;
397ef7bb 84 /** @brief Unique identifier for connection used in log messages */
460b9539 85 unsigned tag;
397ef7bb 86 /** @brief Login name or NULL */
460b9539 87 char *who;
397ef7bb 88 /** @brief Event loop */
460b9539 89 ev_source *ev;
397ef7bb 90 /** @brief Nonce chosen for this connection */
460b9539 91 unsigned char nonce[NONCE_SIZE];
397ef7bb
RK
92 /** @brief Current reader callback
93 *
94 * We change this depending on whether we're servicing the @b log command
95 */
460b9539 96 ev_reader_callback *reader;
397ef7bb 97 /** @brief Event log output sending to this connection */
460b9539 98 struct eventlog_output *lo;
397ef7bb 99 /** @brief Parent listener */
460b9539 100 const struct listener *l;
b12be54a
RK
101 /** @brief Login cookie or NULL */
102 char *cookie;
eb5dc014
RK
103 /** @brief Connection rights */
104 rights_type rights;
0126692c 105 /** @brief Next connection */
106 struct conn *next;
dd9af5cb
RK
107 /** @brief True if pending rescan had 'wait' set */
108 int rescan_wait;
ddbf05c8
RK
109 /** @brief Playlist that this connection locks */
110 const char *locked_playlist;
111 /** @brief When that playlist was locked */
112 time_t locked_when;
f65f5aff
RK
113 /** @brief Line reader function */
114 line_reader_type *line_reader;
115 /** @brief Called when command body has been read */
116 body_callback_type *body_callback;
117 /** @brief Passed to @c body_callback */
118 void *body_u;
119 /** @brief Accumulating body */
120 struct vector body[1];
b0116b5c
RK
121
122 /** @brief Nonzero if an active RTP request exists */
123 int rtp_requested;
124
125 /** @brief RTP destination (if @ref rtp_requested is nonzero) */
126 struct sockaddr_storage rtp_destination;
460b9539 127};
128
0126692c 129/** @brief Linked list of connections */
130static struct conn *connections;
131
460b9539 132static int reader_callback(ev_source *ev,
133 ev_reader *reader,
460b9539 134 void *ptr,
135 size_t bytes,
136 int eof,
137 void *u);
f65f5aff
RK
138static int c_playlist_set_body(struct conn *c,
139 char **body,
140 int nbody,
141 void *u);
142static int fetch_body(struct conn *c,
143 body_callback_type body_callback,
144 void *u);
145static int body_line(struct conn *c, char *line);
146static int command(struct conn *c, char *line);
460b9539 147
148static const char *noyes[] = { "no", "yes" };
149
b0116b5c
RK
150/** @brief Remove a connection from the connection list
151 *
152 * This is a good place for cleaning things up when connections are closed for
153 * any reason.
154 */
0126692c 155static void remove_connection(struct conn *c) {
156 struct conn **cc;
157
b0116b5c
RK
158 if(c->rtp_requested) {
159 rtp_request_cancel(&c->rtp_destination);
160 c->rtp_requested = 0;
161 }
0126692c 162 for(cc = &connections; *cc && *cc != c; cc = &(*cc)->next)
163 ;
164 if(*cc)
165 *cc = c->next;
166}
167
397ef7bb
RK
168/** @brief Called when a connection's writer fails or is shut down
169 *
170 * If the connection still has a raeder that is cancelled.
171 */
460b9539 172static int writer_error(ev_source attribute((unused)) *ev,
460b9539 173 int errno_value,
174 void *u) {
175 struct conn *c = u;
176
8d8b8c1f 177 D(("server writer_error S%x %d", c->tag, errno_value));
460b9539 178 if(errno_value == 0) {
179 /* writer is done */
8d8b8c1f 180 D(("S%x writer completed", c->tag));
460b9539 181 } else {
182 if(errno_value != EPIPE)
2e9ba080 183 disorder_error(errno_value, "S%x write error on socket", c->tag);
38b8221f 184 if(c->r) {
8d8b8c1f 185 D(("cancel reader"));
38b8221f
RK
186 ev_reader_cancel(c->r);
187 c->r = 0;
188 }
8d8b8c1f 189 D(("done cancel reader"));
460b9539 190 }
38b8221f 191 c->w = 0;
75d64210 192 ev_report(ev);
0126692c 193 remove_connection(c);
460b9539 194 return 0;
195}
196
397ef7bb
RK
197/** @brief Called when a conncetion's reader fails or is shut down
198 *
199 * If connection still has a writer then it is closed.
200 */
460b9539 201static int reader_error(ev_source attribute((unused)) *ev,
460b9539 202 int errno_value,
203 void *u) {
204 struct conn *c = u;
205
8d8b8c1f 206 D(("server reader_error S%x %d", c->tag, errno_value));
2e9ba080 207 disorder_error(errno_value, "S%x read error on socket", c->tag);
38b8221f
RK
208 if(c->w)
209 ev_writer_close(c->w);
210 c->w = 0;
211 c->r = 0;
768d7355 212 ev_report(ev);
0126692c 213 remove_connection(c);
460b9539 214 return 0;
215}
216
460b9539 217static int c_disable(struct conn *c, char **vec, int nvec) {
218 if(nvec == 0)
9439cdab 219 disable_playing(c->who, c->ev);
460b9539 220 else if(nvec == 1 && !strcmp(vec[0], "now"))
9439cdab 221 disable_playing(c->who, c->ev);
460b9539 222 else {
223 sink_writes(ev_writer_sink(c->w), "550 invalid argument\n");
224 return 1; /* completed */
225 }
226 sink_writes(ev_writer_sink(c->w), "250 OK\n");
227 return 1; /* completed */
228}
229
230static int c_enable(struct conn *c,
231 char attribute((unused)) **vec,
232 int attribute((unused)) nvec) {
233 enable_playing(c->who, c->ev);
234 /* Enable implicitly unpauses if there is nothing playing */
235 if(paused && !playing) resume_playing(c->who);
236 sink_writes(ev_writer_sink(c->w), "250 OK\n");
237 return 1; /* completed */
238}
239
240static int c_enabled(struct conn *c,
241 char attribute((unused)) **vec,
242 int attribute((unused)) nvec) {
243 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[playing_is_enabled()]);
244 return 1; /* completed */
245}
246
247static int c_play(struct conn *c, char **vec,
248 int attribute((unused)) nvec) {
249 const char *track;
250 struct queue_entry *q;
251
252 if(!trackdb_exists(vec[0])) {
253 sink_writes(ev_writer_sink(c->w), "550 track is not in database\n");
254 return 1;
255 }
256 if(!(track = trackdb_resolve(vec[0]))) {
257 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
258 return 1;
259 }
7a853280 260 q = queue_add(track, c->who, WHERE_BEFORE_RANDOM, NULL, origin_picked);
460b9539 261 queue_write();
81e440ce 262 sink_printf(ev_writer_sink(c->w), "252 %s\n", q->id);
7a853280
RK
263 /* We make sure the track at the head of the queue is prepared, just in case
264 * we added it. We could be more subtle but prepare() will ensure we don't
265 * prepare the same track twice so there's no point. */
266 if(qhead.next != &qhead)
267 prepare(c->ev, qhead.next);
460b9539 268 /* If the queue was empty but we are for some reason paused then
269 * unpause. */
270 if(!playing) resume_playing(0);
271 play(c->ev);
272 return 1; /* completed */
273}
274
7a853280
RK
275static int c_playafter(struct conn *c, char **vec,
276 int attribute((unused)) nvec) {
277 const char *track;
278 struct queue_entry *q;
279 const char *afterme = vec[0];
280
281 for(int n = 1; n < nvec; ++n) {
282 if(!trackdb_exists(vec[n])) {
283 sink_writes(ev_writer_sink(c->w), "550 track is not in database\n");
284 return 1;
285 }
286 if(!(track = trackdb_resolve(vec[n]))) {
287 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
288 return 1;
289 }
290 q = queue_add(track, c->who, WHERE_AFTER, afterme, origin_picked);
291 if(!q) {
292 sink_printf(ev_writer_sink(c->w), "550 No such ID\n");
293 return 1;
294 }
2e9ba080 295 disorder_info("added %s as %s after %s", track, q->id, afterme);
7a853280
RK
296 afterme = q->id;
297 }
298 queue_write();
299 sink_printf(ev_writer_sink(c->w), "252 OK\n");
300 /* We make sure the track at the head of the queue is prepared, just in case
301 * we added it. We could be more subtle but prepare() will ensure we don't
302 * prepare the same track twice so there's no point. */
303 if(qhead.next != &qhead) {
304 prepare(c->ev, qhead.next);
2e9ba080 305 disorder_info("prepared %s", qhead.next->id);
7a853280
RK
306 }
307 /* If the queue was empty but we are for some reason paused then
308 * unpause. */
309 if(!playing)
310 resume_playing(0);
311 play(c->ev);
312 return 1; /* completed */
313}
314
460b9539 315static int c_remove(struct conn *c, char **vec,
316 int attribute((unused)) nvec) {
317 struct queue_entry *q;
318
319 if(!(q = queue_find(vec[0]))) {
320 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
321 return 1;
322 }
938d8157 323 if(!right_removable(c->rights, c->who, q)) {
2e9ba080 324 disorder_error(0, "%s attempted remove but lacks required rights", c->who);
eb5dc014 325 sink_writes(ev_writer_sink(c->w),
b4a80f69 326 "510 Not authorized to remove that track\n");
eb5dc014 327 return 1;
460b9539 328 }
329 queue_remove(q, c->who);
330 /* De-prepare the track. */
331 abandon(c->ev, q);
49a773eb
RK
332 /* See about adding a new random track */
333 add_random_track(c->ev);
460b9539 334 /* Prepare whatever the next head track is. */
335 if(qhead.next != &qhead)
336 prepare(c->ev, qhead.next);
337 queue_write();
338 sink_writes(ev_writer_sink(c->w), "250 removed\n");
339 return 1; /* completed */
340}
341
342static int c_scratch(struct conn *c,
343 char **vec,
344 int nvec) {
345 if(!playing) {
346 sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
347 return 1; /* completed */
348 }
eb5dc014
RK
349 /* TODO there is a bug here: if we specify an ID but it's not the currently
350 * playing track then you will get 550 if you weren't authorized to scratch
351 * the currently playing track. */
938d8157 352 if(!right_scratchable(c->rights, c->who, playing)) {
2e9ba080 353 disorder_error(0, "%s attempted scratch but lacks required rights", c->who);
eb5dc014 354 sink_writes(ev_writer_sink(c->w),
b4a80f69 355 "510 Not authorized to scratch that track\n");
eb5dc014 356 return 1;
460b9539 357 }
358 scratch(c->who, nvec == 1 ? vec[0] : 0);
359 /* If you scratch an unpaused track then it is automatically unpaused */
360 resume_playing(0);
361 sink_writes(ev_writer_sink(c->w), "250 scratched\n");
362 return 1; /* completed */
363}
364
365static int c_pause(struct conn *c,
366 char attribute((unused)) **vec,
367 int attribute((unused)) nvec) {
368 if(!playing) {
369 sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
370 return 1; /* completed */
371 }
372 if(paused) {
373 sink_writes(ev_writer_sink(c->w), "250 already paused\n");
374 return 1; /* completed */
375 }
376 if(pause_playing(c->who) < 0)
377 sink_writes(ev_writer_sink(c->w), "550 cannot pause this track\n");
378 else
379 sink_writes(ev_writer_sink(c->w), "250 paused\n");
380 return 1;
381}
382
383static int c_resume(struct conn *c,
384 char attribute((unused)) **vec,
385 int attribute((unused)) nvec) {
386 if(!paused) {
387 sink_writes(ev_writer_sink(c->w), "250 not paused\n");
388 return 1; /* completed */
389 }
390 resume_playing(c->who);
391 sink_writes(ev_writer_sink(c->w), "250 paused\n");
392 return 1;
393}
394
395static int c_shutdown(struct conn *c,
396 char attribute((unused)) **vec,
397 int attribute((unused)) nvec) {
2e9ba080 398 disorder_info("S%x shut down by %s", c->tag, c->who);
460b9539 399 sink_writes(ev_writer_sink(c->w), "250 shutting down\n");
400 ev_writer_flush(c->w);
401 quit(c->ev);
402}
403
404static int c_reconfigure(struct conn *c,
405 char attribute((unused)) **vec,
406 int attribute((unused)) nvec) {
2e9ba080 407 disorder_info("S%x reconfigure by %s", c->tag, c->who);
460b9539 408 if(reconfigure(c->ev, 1))
409 sink_writes(ev_writer_sink(c->w), "550 error reading new config\n");
410 else
411 sink_writes(ev_writer_sink(c->w), "250 installed new config\n");
412 return 1; /* completed */
413}
414
dd9af5cb
RK
415static void finished_rescan(void *ru) {
416 struct conn *const c = ru;
417
418 sink_writes(ev_writer_sink(c->w), "250 rescan completed\n");
419 /* Turn this connection back on */
420 ev_reader_enable(c->r);
421}
422
423static void start_fresh_rescan(void *ru) {
424 struct conn *const c = ru;
425
426 if(trackdb_rescan_underway()) {
427 /* Some other waiter beat us to it. However in this case we're happy to
428 * piggyback; the requirement is that a new rescan be started, not that it
429 * was _our_ rescan. */
430 if(c->rescan_wait) {
431 /* We block until the rescan completes */
432 trackdb_add_rescanned(finished_rescan, c);
433 } else {
434 /* We report that the new rescan has started */
435 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
436 /* Turn this connection back on */
437 ev_reader_enable(c->r);
438 }
439 } else {
440 /* We are the first connection to get a callback so we must start a
441 * rescan. */
442 if(c->rescan_wait) {
443 /* We want to block until the new rescan completes */
444 trackdb_rescan(c->ev, 1/*check*/, finished_rescan, c);
445 } else {
446 /* We can report back immediately */
447 trackdb_rescan(c->ev, 1/*check*/, 0, 0);
448 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
449 /* Turn this connection back on */
450 ev_reader_enable(c->r);
451 }
452 }
453}
454
460b9539 455static int c_rescan(struct conn *c,
dd9af5cb
RK
456 char **vec,
457 int nvec) {
d867af10 458 int flag_wait = 0, flag_fresh = 0, n;
dd9af5cb
RK
459
460 /* Parse flags */
461 for(n = 0; n < nvec; ++n) {
462 if(!strcmp(vec[n], "wait"))
d867af10 463 flag_wait = 1; /* wait for rescan to complete */
dd9af5cb
RK
464#if 0
465 /* Currently disabled because untested (and hard to test). */
466 else if(!strcmp(vec[n], "fresh"))
d867af10 467 flag_fresh = 1; /* don't piggyback underway rescan */
dd9af5cb
RK
468#endif
469 else {
470 sink_writes(ev_writer_sink(c->w), "550 unknown flag\n");
471 return 1; /* completed */
472 }
473 }
474 /* Report what was requested */
2e9ba080
RK
475 disorder_info("S%x rescan by %s (%s %s)", c->tag, c->who,
476 flag_wait ? "wait" : "",
477 flag_fresh ? "fresh" : "");
dd9af5cb 478 if(trackdb_rescan_underway()) {
d867af10 479 if(flag_fresh) {
dd9af5cb
RK
480 /* We want a fresh rescan but there is already one underway. Arrange a
481 * callback when it completes and then set off a new one. */
d867af10 482 c->rescan_wait = flag_wait;
dd9af5cb 483 trackdb_add_rescanned(start_fresh_rescan, c);
d867af10 484 if(flag_wait)
dd9af5cb
RK
485 return 0;
486 else {
487 sink_writes(ev_writer_sink(c->w), "250 rescan queued\n");
488 return 1;
489 }
490 } else {
491 /* There's a rescan underway, and it's acceptable to piggyback on it */
d867af10 492 if(flag_wait) {
dd9af5cb
RK
493 /* We want to block until completion. */
494 trackdb_add_rescanned(finished_rescan, c);
495 return 0;
496 } else {
497 /* We don't want to block. So we just report that things are in
498 * hand. */
499 sink_writes(ev_writer_sink(c->w), "250 rescan already underway\n");
500 return 1;
501 }
502 }
503 } else {
504 /* No rescan is underway. fresh is therefore irrelevant. */
d867af10 505 if(flag_wait) {
dd9af5cb
RK
506 /* We want to block until completion */
507 trackdb_rescan(c->ev, 1/*check*/, finished_rescan, c);
508 return 0;
509 } else {
510 /* We don't want to block. */
511 trackdb_rescan(c->ev, 1/*check*/, 0, 0);
512 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
513 return 1; /* completed */
514 }
515 }
460b9539 516}
517
518static int c_version(struct conn *c,
519 char attribute((unused)) **vec,
520 int attribute((unused)) nvec) {
521 /* VERSION had better only use the basic character set */
a05e4467 522 sink_printf(ev_writer_sink(c->w), "251 %s\n", disorder_short_version_string);
460b9539 523 return 1; /* completed */
524}
525
526static int c_playing(struct conn *c,
527 char attribute((unused)) **vec,
528 int attribute((unused)) nvec) {
529 if(playing) {
530 queue_fix_sofar(playing);
531 playing->expected = 0;
532 sink_printf(ev_writer_sink(c->w), "252 %s\n", queue_marshall(playing));
533 } else
534 sink_printf(ev_writer_sink(c->w), "259 nothing playing\n");
535 return 1; /* completed */
536}
537
b12be54a 538static const char *connection_host(struct conn *c) {
460b9539 539 union {
540 struct sockaddr sa;
541 struct sockaddr_in in;
542 struct sockaddr_in6 in6;
543 } u;
544 socklen_t l;
b12be54a 545 int n;
460b9539 546 char host[1024];
547
460b9539 548 /* get connection data */
549 l = sizeof u;
550 if(getpeername(c->fd, &u.sa, &l) < 0) {
2e9ba080 551 disorder_error(errno, "S%x error calling getpeername", c->tag);
b12be54a 552 return 0;
460b9539 553 }
554 if(c->l->pf != PF_UNIX) {
555 if((n = getnameinfo(&u.sa, l,
556 host, sizeof host, 0, 0, NI_NUMERICHOST))) {
2e9ba080
RK
557 disorder_error(0, "S%x error calling getnameinfo: %s",
558 c->tag, gai_strerror(n));
b12be54a 559 return 0;
460b9539 560 }
b12be54a 561 return xstrdup(host);
18e6d6e6 562 } else
b12be54a
RK
563 return "local";
564}
565
566static int c_user(struct conn *c,
567 char **vec,
568 int attribute((unused)) nvec) {
eb5dc014 569 struct kvp *k;
f0feb22e 570 const char *res, *host, *password;
eb5dc014 571 rights_type rights;
b12be54a
RK
572
573 if(c->who) {
574 sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
575 return 1;
576 }
577 /* get connection data */
578 if(!(host = connection_host(c))) {
579 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
580 return 1;
581 }
460b9539 582 /* find the user */
eb5dc014 583 k = trackdb_getuserinfo(vec[0]);
f0feb22e 584 /* reject nonexistent users */
eb5dc014 585 if(!k) {
2e9ba080 586 disorder_error(0, "S%x unknown user '%s' from %s", c->tag, vec[0], host);
eb5dc014
RK
587 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
588 return 1;
589 }
590 /* reject unconfirmed users */
591 if(kvp_get(k, "confirmation")) {
2e9ba080
RK
592 disorder_error(0, "S%x unconfirmed user '%s' from %s",
593 c->tag, vec[0], host);
eb5dc014
RK
594 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
595 return 1;
596 }
597 password = kvp_get(k, "password");
598 if(!password) password = "";
0f55e905 599 if(parse_rights(kvp_get(k, "rights"), &rights, 1)) {
2e9ba080 600 disorder_error(0, "error parsing rights for %s", vec[0]);
18e6d6e6 601 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
602 return 1;
603 }
f0feb22e
RK
604 /* check whether the response is right */
605 res = authhash(c->nonce, sizeof c->nonce, password,
637fdea3 606 config->authorization_algorithm);
de37b640 607 if(wideopen || c->l->privileged || (res && !strcmp(res, vec[1]))) {
18e6d6e6 608 c->who = vec[0];
eb5dc014 609 c->rights = rights;
18e6d6e6 610 /* currently we only bother logging remote connections */
30365519 611 if(strcmp(host, "local"))
2e9ba080 612 disorder_info("S%x %s connected from %s", c->tag, vec[0], host);
30365519 613 else
eb5dc014 614 c->rights |= RIGHT__LOCAL;
18e6d6e6 615 sink_writes(ev_writer_sink(c->w), "230 OK\n");
616 return 1;
460b9539 617 }
618 /* oops, response was wrong */
2e9ba080
RK
619 disorder_info("S%x authentication failure for %s from %s",
620 c->tag, vec[0], host);
460b9539 621 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
622 return 1;
623}
624
625static int c_recent(struct conn *c,
626 char attribute((unused)) **vec,
627 int attribute((unused)) nvec) {
628 const struct queue_entry *q;
629
630 sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
631 for(q = phead.next; q != &phead; q = q->next)
632 sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
633 sink_writes(ev_writer_sink(c->w), ".\n");
634 return 1; /* completed */
635}
636
637static int c_queue(struct conn *c,
638 char attribute((unused)) **vec,
639 int attribute((unused)) nvec) {
640 struct queue_entry *q;
641 time_t when = 0;
642 const char *l;
643 long length;
644
645 sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
646 if(playing_is_enabled() && !paused) {
647 if(playing) {
648 queue_fix_sofar(playing);
649 if((l = trackdb_get(playing->track, "_length"))
650 && (length = atol(l))) {
4265e5d3 651 xtime(&when);
657fdb79 652 when += length - playing->sofar;
460b9539 653 }
654 } else
655 /* Nothing is playing but playing is enabled, so whatever is
656 * first in the queue can be expected to start immediately. */
4265e5d3 657 xtime(&when);
460b9539 658 }
659 for(q = qhead.next; q != &qhead; q = q->next) {
660 /* fill in estimated start time */
661 q->expected = when;
662 sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
663 /* update for next track */
664 if(when) {
665 if((l = trackdb_get(q->track, "_length"))
666 && (length = atol(l)))
657fdb79 667 when += length;
460b9539 668 else
669 when = 0;
670 }
671 }
672 sink_writes(ev_writer_sink(c->w), ".\n");
673 return 1; /* completed */
674}
675
676static int output_list(struct conn *c, char **vec) {
677 while(*vec)
678 sink_printf(ev_writer_sink(c->w), "%s\n", *vec++);
679 sink_writes(ev_writer_sink(c->w), ".\n");
680 return 1;
681}
682
683static int files_dirs(struct conn *c,
684 char **vec,
685 int nvec,
686 enum trackdb_listable what) {
687 const char *dir, *re, *errstr;
688 int erroffset;
689 pcre *rec;
690 char **fvec, *key;
691
692 switch(nvec) {
693 case 0: dir = 0; re = 0; break;
694 case 1: dir = vec[0]; re = 0; break;
695 case 2: dir = vec[0]; re = vec[1]; break;
696 default: abort();
697 }
698 /* A bit of a bodge to make sure the args don't trample on cache keys */
699 if(dir && strchr(dir, '\n')) {
700 sink_writes(ev_writer_sink(c->w), "550 invalid directory name\n");
701 return 1;
702 }
703 if(re && strchr(re, '\n')) {
704 sink_writes(ev_writer_sink(c->w), "550 invalid regexp\n");
705 return 1;
706 }
707 /* We bother eliminating "" because the web interface is relatively
708 * likely to send it */
709 if(re && *re) {
710 byte_xasprintf(&key, "%d\n%s\n%s", (int)what, dir ? dir : "", re);
711 fvec = (char **)cache_get(&cache_files_type, key);
712 if(fvec) {
713 /* Got a cache hit, don't store the answer in the cache */
714 key = 0;
715 ++cache_files_hits;
716 rec = 0; /* quieten compiler */
717 } else {
718 /* Cache miss, we'll do the lookup and key != 0 so we'll store the answer
719 * in the cache. */
720 if(!(rec = pcre_compile(re, PCRE_CASELESS|PCRE_UTF8,
721 &errstr, &erroffset, 0))) {
722 sink_printf(ev_writer_sink(c->w), "550 Error compiling regexp: %s\n",
723 errstr);
724 return 1;
725 }
726 /* It only counts as a miss if the regexp was valid. */
727 ++cache_files_misses;
728 }
729 } else {
730 /* No regexp, don't bother caching the result */
731 rec = 0;
732 key = 0;
733 fvec = 0;
734 }
735 if(!fvec) {
736 /* No cache hit (either because a miss, or because we did not look) so do
737 * the lookup */
738 if(dir && *dir)
739 fvec = trackdb_list(dir, 0, what, rec);
740 else
741 fvec = trackdb_list(0, 0, what, rec);
742 }
743 if(key)
744 /* Put the answer in the cache */
745 cache_put(&cache_files_type, key, fvec);
746 sink_writes(ev_writer_sink(c->w), "253 Listing follow\n");
747 return output_list(c, fvec);
748}
749
750static int c_files(struct conn *c,
751 char **vec,
752 int nvec) {
753 return files_dirs(c, vec, nvec, trackdb_files);
754}
755
756static int c_dirs(struct conn *c,
757 char **vec,
758 int nvec) {
759 return files_dirs(c, vec, nvec, trackdb_directories);
760}
761
762static int c_allfiles(struct conn *c,
763 char **vec,
764 int nvec) {
765 return files_dirs(c, vec, nvec, trackdb_directories|trackdb_files);
766}
767
768static int c_get(struct conn *c,
769 char **vec,
770 int attribute((unused)) nvec) {
27ed5a69 771 const char *v, *track;
460b9539 772
27ed5a69
RK
773 if(!(track = trackdb_resolve(vec[0]))) {
774 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
775 return 1;
776 }
777 if(vec[1][0] != '_' && (v = trackdb_get(track, vec[1])))
7b32e917 778 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
460b9539 779 else
fb1bc1f5 780 sink_writes(ev_writer_sink(c->w), "555 not found\n");
460b9539 781 return 1;
782}
783
784static int c_length(struct conn *c,
785 char **vec,
786 int attribute((unused)) nvec) {
787 const char *track, *v;
788
789 if(!(track = trackdb_resolve(vec[0]))) {
790 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
791 return 1;
792 }
793 if((v = trackdb_get(track, "_length")))
7b32e917 794 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
460b9539 795 else
796 sink_writes(ev_writer_sink(c->w), "550 not found\n");
797 return 1;
798}
799
800static int c_set(struct conn *c,
801 char **vec,
802 int attribute((unused)) nvec) {
27ed5a69
RK
803 const char *track;
804
805 if(!(track = trackdb_resolve(vec[0]))) {
806 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
807 return 1;
808 }
809 if(vec[1][0] != '_' && !trackdb_set(track, vec[1], vec[2]))
460b9539 810 sink_writes(ev_writer_sink(c->w), "250 OK\n");
811 else
812 sink_writes(ev_writer_sink(c->w), "550 not found\n");
813 return 1;
814}
815
816static int c_prefs(struct conn *c,
817 char **vec,
818 int attribute((unused)) nvec) {
819 struct kvp *k;
27ed5a69 820 const char *track;
460b9539 821
27ed5a69
RK
822 if(!(track = trackdb_resolve(vec[0]))) {
823 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
824 return 1;
825 }
826 k = trackdb_get_all(track);
460b9539 827 sink_writes(ev_writer_sink(c->w), "253 prefs follow\n");
828 for(; k; k = k->next)
829 if(k->name[0] != '_') /* omit internal values */
830 sink_printf(ev_writer_sink(c->w),
831 " %s %s\n", quoteutf8(k->name), quoteutf8(k->value));
832 sink_writes(ev_writer_sink(c->w), ".\n");
833 return 1;
834}
835
836static int c_exists(struct conn *c,
837 char **vec,
838 int attribute((unused)) nvec) {
27ed5a69 839 /* trackdb_exists() does its own alias checking */
460b9539 840 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[trackdb_exists(vec[0])]);
841 return 1;
842}
843
844static void search_parse_error(const char *msg, void *u) {
845 *(const char **)u = msg;
846}
847
848static int c_search(struct conn *c,
849 char **vec,
850 int attribute((unused)) nvec) {
851 char **terms, **results;
852 int nterms, nresults, n;
853 const char *e = "unknown error";
854
855 /* This is a bit of a bodge. Initially it's there to make the eclient
856 * interface a bit more convenient to add searching to, but it has the more
857 * compelling advantage that if everything uses it, then interpretation of
858 * user-supplied search strings will be the same everywhere. */
859 if(!(terms = split(vec[0], &nterms, SPLIT_QUOTES, search_parse_error, &e))) {
860 sink_printf(ev_writer_sink(c->w), "550 %s\n", e);
861 } else {
862 results = trackdb_search(terms, nterms, &nresults);
863 sink_printf(ev_writer_sink(c->w), "253 %d matches\n", nresults);
864 for(n = 0; n < nresults; ++n)
865 sink_printf(ev_writer_sink(c->w), "%s\n", results[n]);
866 sink_writes(ev_writer_sink(c->w), ".\n");
867 }
868 return 1;
869}
870
871static int c_random_enable(struct conn *c,
872 char attribute((unused)) **vec,
873 int attribute((unused)) nvec) {
874 enable_random(c->who, c->ev);
875 /* Enable implicitly unpauses if there is nothing playing */
876 if(paused && !playing) resume_playing(c->who);
877 sink_writes(ev_writer_sink(c->w), "250 OK\n");
878 return 1; /* completed */
879}
880
881static int c_random_disable(struct conn *c,
882 char attribute((unused)) **vec,
883 int attribute((unused)) nvec) {
9439cdab 884 disable_random(c->who, c->ev);
460b9539 885 sink_writes(ev_writer_sink(c->w), "250 OK\n");
886 return 1; /* completed */
887}
888
889static int c_random_enabled(struct conn *c,
890 char attribute((unused)) **vec,
891 int attribute((unused)) nvec) {
892 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[random_is_enabled()]);
893 return 1; /* completed */
894}
895
d6dde5a3
RK
896static void got_stats(char *stats, void *u) {
897 struct conn *const c = u;
898
899 sink_printf(ev_writer_sink(c->w), "253 stats\n%s\n.\n", stats);
900 /* Now we can start processing commands again */
901 ev_reader_enable(c->r);
902}
903
460b9539 904static int c_stats(struct conn *c,
905 char attribute((unused)) **vec,
906 int attribute((unused)) nvec) {
d6dde5a3
RK
907 trackdb_stats_subprocess(c->ev, got_stats, c);
908 return 0; /* not yet complete */
460b9539 909}
910
911static int c_volume(struct conn *c,
912 char **vec,
913 int nvec) {
914 int l, r, set;
915 char lb[32], rb[32];
eb5dc014 916 rights_type rights;
460b9539 917
918 switch(nvec) {
919 case 0:
920 set = 0;
921 break;
922 case 1:
923 l = r = atoi(vec[0]);
924 set = 1;
925 break;
926 case 2:
927 l = atoi(vec[0]);
928 r = atoi(vec[1]);
929 set = 1;
930 break;
931 default:
932 abort();
933 }
eb5dc014
RK
934 rights = set ? RIGHT_VOLUME : RIGHT_READ;
935 if(!(c->rights & rights)) {
2e9ba080
RK
936 disorder_error(0, "%s attempted to set volume but lacks required rights",
937 c->who);
b4a80f69 938 sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
eb5dc014
RK
939 return 1;
940 }
b50cfb8a 941 if(!api || !api->set_volume) {
460b9539 942 sink_writes(ev_writer_sink(c->w), "550 error accessing mixer\n");
b50cfb8a
RK
943 return 1;
944 }
e4d0463f 945 (set ? api->set_volume : api->get_volume)(&l, &r);
b50cfb8a
RK
946 sink_printf(ev_writer_sink(c->w), "252 %d %d\n", l, r);
947 if(l != volume_left || r != volume_right) {
948 volume_left = l;
949 volume_right = r;
950 snprintf(lb, sizeof lb, "%d", l);
951 snprintf(rb, sizeof rb, "%d", r);
952 eventlog("volume", lb, rb, (char *)0);
460b9539 953 }
954 return 1;
955}
956
397ef7bb
RK
957/** @brief Called when data arrives on a log connection
958 *
959 * We just discard all such data. The client may occasionally send data as a
960 * keepalive.
961 */
962static int logging_reader_callback(ev_source attribute((unused)) *ev,
460b9539 963 ev_reader *reader,
397ef7bb 964 void attribute((unused)) *ptr,
460b9539 965 size_t bytes,
397ef7bb
RK
966 int attribute((unused)) eof,
967 void attribute((unused)) *u) {
460b9539 968 struct conn *c = u;
969
397ef7bb
RK
970 ev_reader_consume(reader, bytes);
971 if(eof) {
972 /* Oops, that's all for now */
8d8b8c1f 973 D(("logging reader eof"));
397ef7bb 974 if(c->w) {
8d8b8c1f 975 D(("close writer"));
397ef7bb
RK
976 ev_writer_close(c->w);
977 c->w = 0;
978 }
979 c->r = 0;
0126692c 980 remove_connection(c);
f6033c46 981 }
397ef7bb 982 return 0;
460b9539 983}
984
985static void logclient(const char *msg, void *user) {
986 struct conn *c = user;
987
f6033c46
RK
988 if(!c->w || !c->r) {
989 /* This connection has gone up in smoke for some reason */
990 eventlog_remove(c->lo);
ad492e00 991 c->lo = 0;
f6033c46
RK
992 return;
993 }
75e7b7c3
RK
994 /* user_* messages are restricted */
995 if(!strncmp(msg, "user_", 5)) {
58d2aad2
RK
996 /* They are only sent to admin users */
997 if(!(c->rights & RIGHT_ADMIN))
998 return;
999 /* They are not sent over TCP connections unless remote user-management is
1000 * enabled */
1001 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL))
1002 return;
1003 }
460b9539 1004 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" %s\n",
4265e5d3 1005 (uintmax_t)xtime(0), msg);
460b9539 1006}
1007
1008static int c_log(struct conn *c,
1009 char attribute((unused)) **vec,
1010 int attribute((unused)) nvec) {
1011 time_t now;
1012
1013 sink_writes(ev_writer_sink(c->w), "254 OK\n");
1014 /* pump out initial state */
4265e5d3 1015 xtime(&now);
460b9539 1016 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
1017 (uintmax_t)now,
1018 playing_is_enabled() ? "enable_play" : "disable_play");
1019 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
1020 (uintmax_t)now,
1021 random_is_enabled() ? "enable_random" : "disable_random");
1022 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
1023 (uintmax_t)now,
1024 paused ? "pause" : "resume");
5abe307a
RK
1025 if(playing)
1026 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state playing\n",
1027 (uintmax_t)now);
df44d69b
RK
1028 /* Initial volume */
1029 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" volume %d %d\n",
1030 (uintmax_t)now, volume_left, volume_right);
460b9539 1031 c->lo = xmalloc(sizeof *c->lo);
1032 c->lo->fn = logclient;
1033 c->lo->user = c;
1034 eventlog_add(c->lo);
1035 c->reader = logging_reader_callback;
1036 return 0;
1037}
1038
eb5dc014
RK
1039/** @brief Test whether a move is allowed
1040 * @param c Connection
1041 * @param qs List of IDs on queue
1042 * @param nqs Number of IDs
1043 * @return 0 if move is prohibited, non-0 if it is allowed
1044 */
1045static int has_move_rights(struct conn *c, struct queue_entry **qs, int nqs) {
eb5dc014
RK
1046 for(; nqs > 0; ++qs, --nqs) {
1047 struct queue_entry *const q = *qs;
1048
938d8157 1049 if(!right_movable(c->rights, c->who, q))
1050 return 0;
eb5dc014 1051 }
938d8157 1052 return 1;
eb5dc014
RK
1053}
1054
460b9539 1055static int c_move(struct conn *c,
1056 char **vec,
1057 int attribute((unused)) nvec) {
1058 struct queue_entry *q;
1059 int n;
1060
460b9539 1061 if(!(q = queue_find(vec[0]))) {
1062 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1063 return 1;
1064 }
eb5dc014 1065 if(!has_move_rights(c, &q, 1)) {
2e9ba080 1066 disorder_error(0, "%s attempted move but lacks required rights", c->who);
eb5dc014 1067 sink_writes(ev_writer_sink(c->w),
b4a80f69 1068 "510 Not authorized to move that track\n");
eb5dc014
RK
1069 return 1;
1070 }
460b9539 1071 n = queue_move(q, atoi(vec[1]), c->who);
460b9539 1072 sink_printf(ev_writer_sink(c->w), "252 %d\n", n);
1073 /* If we've moved to the head of the queue then prepare the track. */
1074 if(q == qhead.next)
1075 prepare(c->ev, q);
1076 return 1;
1077}
1078
1079static int c_moveafter(struct conn *c,
1080 char **vec,
1081 int attribute((unused)) nvec) {
1082 struct queue_entry *q, **qs;
1083 int n;
1084
460b9539 1085 if(vec[0][0]) {
1086 if(!(q = queue_find(vec[0]))) {
1087 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1088 return 1;
1089 }
1090 } else
1091 q = 0;
1092 ++vec;
1093 --nvec;
1094 qs = xcalloc(nvec, sizeof *qs);
1095 for(n = 0; n < nvec; ++n)
1096 if(!(qs[n] = queue_find(vec[n]))) {
1097 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1098 return 1;
1099 }
eb5dc014 1100 if(!has_move_rights(c, qs, nvec)) {
2e9ba080
RK
1101 disorder_error(0, "%s attempted moveafter but lacks required rights",
1102 c->who);
eb5dc014 1103 sink_writes(ev_writer_sink(c->w),
b4a80f69 1104 "510 Not authorized to move those tracks\n");
eb5dc014
RK
1105 return 1;
1106 }
460b9539 1107 queue_moveafter(q, nvec, qs, c->who);
460b9539 1108 sink_printf(ev_writer_sink(c->w), "250 Moved tracks\n");
1109 /* If we've moved to the head of the queue then prepare the track. */
1110 if(q == qhead.next)
1111 prepare(c->ev, q);
1112 return 1;
1113}
1114
1115static int c_part(struct conn *c,
1116 char **vec,
1117 int attribute((unused)) nvec) {
27ed5a69
RK
1118 const char *track;
1119
1120 if(!(track = trackdb_resolve(vec[0]))) {
1121 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1122 return 1;
1123 }
460b9539 1124 sink_printf(ev_writer_sink(c->w), "252 %s\n",
27ed5a69 1125 quoteutf8(trackdb_getpart(track, vec[1], vec[2])));
460b9539 1126 return 1;
1127}
1128
1129static int c_resolve(struct conn *c,
1130 char **vec,
1131 int attribute((unused)) nvec) {
1132 const char *track;
1133
1134 if(!(track = trackdb_resolve(vec[0]))) {
1135 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1136 return 1;
1137 }
7b32e917 1138 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(track));
460b9539 1139 return 1;
1140}
1141
ddbf05c8
RK
1142static int list_response(struct conn *c,
1143 const char *reply,
1144 char **list) {
1145 sink_printf(ev_writer_sink(c->w), "253 %s\n", reply);
1146 while(*list) {
460b9539 1147 sink_printf(ev_writer_sink(c->w), "%s%s\n",
ddbf05c8
RK
1148 **list == '.' ? "." : "", *list);
1149 ++list;
460b9539 1150 }
1151 sink_writes(ev_writer_sink(c->w), ".\n");
1152 return 1; /* completed */
460b9539 1153}
1154
ddbf05c8
RK
1155static int c_tags(struct conn *c,
1156 char attribute((unused)) **vec,
1157 int attribute((unused)) nvec) {
1158 return list_response(c, "Tag list follows", trackdb_alltags());
1159}
1160
460b9539 1161static int c_set_global(struct conn *c,
1162 char **vec,
1163 int attribute((unused)) nvec) {
f9635e06
RK
1164 if(vec[0][0] == '_') {
1165 sink_writes(ev_writer_sink(c->w), "550 cannot set internal global preferences\n");
1166 return 1;
1167 }
9439cdab
RK
1168 /* We special-case the 'magic' preferences here. */
1169 if(!strcmp(vec[0], "playing")) {
1170 (flag_enabled(vec[1]) ? enable_playing : disable_playing)(c->who, c->ev);
43386708 1171 sink_printf(ev_writer_sink(c->w), "250 OK\n");
9439cdab
RK
1172 } else if(!strcmp(vec[0], "random-play")) {
1173 (flag_enabled(vec[1]) ? enable_random : disable_random)(c->who, c->ev);
43386708 1174 sink_printf(ev_writer_sink(c->w), "250 OK\n");
9439cdab 1175 } else {
2fbc0bd2 1176 if(!trackdb_set_global(vec[0], vec[1], c->who))
9439cdab
RK
1177 sink_printf(ev_writer_sink(c->w), "250 OK\n");
1178 else
1179 sink_writes(ev_writer_sink(c->w), "550 not found\n");
1180 }
460b9539 1181 return 1;
1182}
1183
1184static int c_get_global(struct conn *c,
1185 char **vec,
1186 int attribute((unused)) nvec) {
1187 const char *s = trackdb_get_global(vec[0]);
1188
1189 if(s)
7b32e917 1190 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(s));
460b9539 1191 else
fb1bc1f5 1192 sink_writes(ev_writer_sink(c->w), "555 not found\n");
460b9539 1193 return 1;
1194}
1195
7858930d 1196static int c_nop(struct conn *c,
1197 char attribute((unused)) **vec,
1198 int attribute((unused)) nvec) {
1199 sink_printf(ev_writer_sink(c->w), "250 Quack\n");
1200 return 1;
1201}
1202
2a10b70b
RK
1203static int c_new(struct conn *c,
1204 char **vec,
1205 int nvec) {
375d9478 1206 int max;
d742bb47 1207 char **tracks;
2a10b70b 1208
d742bb47
RK
1209 if(nvec > 0)
1210 max = atoi(vec[0]);
1211 else
1212 max = INT_MAX;
1213 if(max <= 0 || max > config->new_max)
1214 max = config->new_max;
1215 tracks = trackdb_new(0, max);
2a10b70b
RK
1216 sink_printf(ev_writer_sink(c->w), "253 New track list follows\n");
1217 while(*tracks) {
1218 sink_printf(ev_writer_sink(c->w), "%s%s\n",
1219 **tracks == '.' ? "." : "", *tracks);
1220 ++tracks;
1221 }
1222 sink_writes(ev_writer_sink(c->w), ".\n");
1223 return 1; /* completed */
1224
1225}
1226
ca831831
RK
1227static int c_rtp_address(struct conn *c,
1228 char attribute((unused)) **vec,
1229 int attribute((unused)) nvec) {
b50cfb8a 1230 if(api == &uaudio_rtp) {
76e72f65
RK
1231 char **addr;
1232
b0116b5c
RK
1233 if(!strcmp(config->rtp_mode, "request"))
1234 sink_printf(ev_writer_sink(c->w), "252 - -\n");
1235 else {
1236 netaddress_format(&config->broadcast, NULL, &addr);
1237 sink_printf(ev_writer_sink(c->w), "252 %s %s\n",
1238 quoteutf8(addr[1]),
1239 quoteutf8(addr[2]));
1240 }
ca831831
RK
1241 } else
1242 sink_writes(ev_writer_sink(c->w), "550 No RTP\n");
1243 return 1;
1244}
b12be54a 1245
b0116b5c
RK
1246static int c_rtp_cancel(struct conn *c,
1247 char attribute((unused)) **vec,
1248 int attribute((unused)) nvec) {
1249 if(!c->rtp_requested) {
1250 sink_writes(ev_writer_sink(c->w), "550 No active RTP stream\n");
1251 return 1;
1252 }
1253 rtp_request_cancel(&c->rtp_destination);
1254 c->rtp_requested = 0;
1255 sink_writes(ev_writer_sink(c->w), "250 Cancelled RTP stream\n");
1256 return 1;
1257}
1258
1259static int c_rtp_request(struct conn *c,
1260 char **vec,
1261 int attribute((unused)) nvec) {
1262 static const struct addrinfo hints = {
1263 .ai_family = AF_UNSPEC,
1264 .ai_socktype = SOCK_DGRAM,
1265 .ai_protocol = IPPROTO_UDP,
1266 .ai_flags = AI_NUMERICHOST|AI_NUMERICSERV,
1267 };
1268 struct addrinfo *res;
1269 int rc = getaddrinfo(vec[0], vec[1], &hints, &res);
1270 if(rc) {
1271 disorder_error(0, "%s port %s: %s",
1272 vec[0], vec[1], gai_strerror(rc));
1273 sink_writes(ev_writer_sink(c->w), "550 Invalid address\n");
1274 return 1;
1275 }
1276 disorder_info("%s requested RTP stream to %s %s", c->who, vec[0], vec[1]);
1277 /* TODO might be useful to tighten this up to restrict clients to targetting
1278 * themselves only */
1279 if(c->rtp_requested) {
1280 rtp_request_cancel(&c->rtp_destination);
1281 c->rtp_requested = 0;
1282 }
1283 memcpy(&c->rtp_destination, res->ai_addr, res->ai_addrlen);
1284 freeaddrinfo(res);
1285 rtp_request(&c->rtp_destination);
1286 c->rtp_requested = 1;
1287 sink_writes(ev_writer_sink(c->w), "250 Initiated RTP stream\n");
1288 // TODO teardown on connection close
1289 return 1;
1290}
1291
b12be54a
RK
1292static int c_cookie(struct conn *c,
1293 char **vec,
1294 int attribute((unused)) nvec) {
1295 const char *host;
1296 char *user;
eb5dc014 1297 rights_type rights;
b12be54a
RK
1298
1299 /* Can't log in twice on the same connection */
1300 if(c->who) {
1301 sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
1302 return 1;
1303 }
1304 /* Get some kind of peer identifcation */
1305 if(!(host = connection_host(c))) {
1306 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1307 return 1;
1308 }
1309 /* Check the cookie */
eb5dc014 1310 user = verify_cookie(vec[0], &rights);
b12be54a
RK
1311 if(!user) {
1312 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1313 return 1;
1314 }
1315 /* Log in */
e48c28bb 1316 c->who = user;
b12be54a 1317 c->cookie = vec[0];
eb5dc014 1318 c->rights = rights;
30365519 1319 if(strcmp(host, "local"))
2e9ba080 1320 disorder_info("S%x %s connected with cookie from %s", c->tag, user, host);
30365519 1321 else
eb5dc014 1322 c->rights |= RIGHT__LOCAL;
0227f67d
RK
1323 /* Response contains username so client knows who they are acting as */
1324 sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
b12be54a
RK
1325 return 1;
1326}
1327
1328static int c_make_cookie(struct conn *c,
1329 char attribute((unused)) **vec,
1330 int attribute((unused)) nvec) {
1331 const char *cookie = make_cookie(c->who);
1332
1333 if(cookie)
eb5dc014 1334 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cookie));
b12be54a
RK
1335 else
1336 sink_writes(ev_writer_sink(c->w), "550 Cannot create cookie\n");
1337 return 1;
1338}
1339
1340static int c_revoke(struct conn *c,
1341 char attribute((unused)) **vec,
1342 int attribute((unused)) nvec) {
1343 if(c->cookie) {
1344 revoke_cookie(c->cookie);
1345 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1346 } else
b60ceb3c 1347 sink_writes(ev_writer_sink(c->w), "510 Did not log in with cookie\n");
b12be54a
RK
1348 return 1;
1349}
1350
f0feb22e
RK
1351static int c_adduser(struct conn *c,
1352 char **vec,
0f55e905
RK
1353 int nvec) {
1354 const char *rights;
1355
810b8083 1356 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
2e9ba080 1357 disorder_error(0, "S%x: remote adduser", c->tag);
b60ceb3c 1358 sink_writes(ev_writer_sink(c->w), "510 Remote user management is disabled\n");
810b8083
RK
1359 return 1;
1360 }
0f55e905
RK
1361 if(nvec > 2) {
1362 rights = vec[2];
1363 if(parse_rights(vec[2], 0, 1)) {
1364 sink_writes(ev_writer_sink(c->w), "550 Invalid rights list\n");
1365 return -1;
1366 }
1367 } else
1368 rights = config->default_rights;
1369 if(trackdb_adduser(vec[0], vec[1], rights,
ba39faf6 1370 0/*email*/, 0/*confirmation*/))
f0feb22e
RK
1371 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1372 else
1373 sink_writes(ev_writer_sink(c->w), "250 User created\n");
1374 return 1;
1375}
1376
1377static int c_deluser(struct conn *c,
1378 char **vec,
1379 int attribute((unused)) nvec) {
0126692c 1380 struct conn *d;
1381
810b8083 1382 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
2e9ba080 1383 disorder_error(0, "S%x: remote deluser", c->tag);
b60ceb3c 1384 sink_writes(ev_writer_sink(c->w), "510 Remote user management is disabled\n");
810b8083
RK
1385 return 1;
1386 }
0126692c 1387 if(trackdb_deluser(vec[0])) {
ba39faf6 1388 sink_writes(ev_writer_sink(c->w), "550 Cannot delete user\n");
0126692c 1389 return 1;
1390 }
1391 /* Zap connections belonging to deleted user */
1392 for(d = connections; d; d = d->next)
1393 if(!strcmp(d->who, vec[0]))
1394 d->rights = 0;
1395 sink_writes(ev_writer_sink(c->w), "250 User deleted\n");
f0feb22e
RK
1396 return 1;
1397}
1398
1399static int c_edituser(struct conn *c,
5df73aeb 1400 char **vec,
f0feb22e 1401 int attribute((unused)) nvec) {
0126692c 1402 struct conn *d;
1403
810b8083 1404 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
2e9ba080 1405 disorder_error(0, "S%x: remote edituser", c->tag);
b60ceb3c 1406 sink_writes(ev_writer_sink(c->w), "510 Remote user management is disabled\n");
810b8083
RK
1407 return 1;
1408 }
eb5dc014
RK
1409 /* RIGHT_ADMIN can do anything; otherwise you can only set your own email
1410 * address and password. */
1411 if((c->rights & RIGHT_ADMIN)
5df73aeb
RK
1412 || (!strcmp(c->who, vec[0])
1413 && (!strcmp(vec[1], "email")
1414 || !strcmp(vec[1], "password")))) {
0126692c 1415 if(trackdb_edituserinfo(vec[0], vec[1], vec[2])) {
5df73aeb 1416 sink_writes(ev_writer_sink(c->w), "550 Failed to change setting\n");
0126692c 1417 return 1;
1418 }
1419 if(!strcmp(vec[1], "password")) {
1420 /* Zap all connections for this user after a password change */
1421 for(d = connections; d; d = d->next)
1422 if(!strcmp(d->who, vec[0]))
1423 d->rights = 0;
1424 } else if(!strcmp(vec[1], "rights")) {
1425 /* Update rights for this user */
1426 rights_type r;
1427
ad492e00
RK
1428 if(!parse_rights(vec[2], &r, 1)) {
1429 const char *new_rights = rights_string(r);
1430 for(d = connections; d; d = d->next) {
1431 if(!strcmp(d->who, vec[0])) {
1432 /* Update rights */
0126692c 1433 d->rights = r;
ad492e00
RK
1434 /* Notify any log connections */
1435 if(d->lo)
1436 sink_printf(ev_writer_sink(d->w),
75e7b7c3 1437 "%"PRIxMAX" rights_changed %s\n",
4265e5d3 1438 (uintmax_t)xtime(0),
75e7b7c3 1439 quoteutf8(new_rights));
ad492e00
RK
1440 }
1441 }
1442 }
0126692c 1443 }
1444 sink_writes(ev_writer_sink(c->w), "250 OK\n");
834e7c4a 1445 } else {
2e9ba080
RK
1446 disorder_error(0, "%s attempted edituser but lacks required rights",
1447 c->who);
b4a80f69 1448 sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
834e7c4a 1449 }
f0feb22e
RK
1450 return 1;
1451}
1452
1453static int c_userinfo(struct conn *c,
1454 char attribute((unused)) **vec,
1455 int attribute((unused)) nvec) {
5df73aeb
RK
1456 struct kvp *k;
1457 const char *value;
eb5dc014 1458
39e7dcfb
RK
1459 /* We allow remote querying of rights so that clients can figure out what
1460 * they're allowed to do */
1461 if(!config->remote_userman
1462 && !(c->rights & RIGHT__LOCAL)
1463 && strcmp(vec[1], "rights")) {
2e9ba080 1464 disorder_error(0, "S%x: remote userinfo %s %s", c->tag, vec[0], vec[1]);
b60ceb3c 1465 sink_writes(ev_writer_sink(c->w), "510 Remote user management is disabled\n");
810b8083
RK
1466 return 1;
1467 }
eb5dc014 1468 /* RIGHT_ADMIN allows anything; otherwise you can only get your own email
29f5fbd2 1469 * address and rights list. */
eb5dc014 1470 if((c->rights & RIGHT_ADMIN)
5df73aeb
RK
1471 || (!strcmp(c->who, vec[0])
1472 && (!strcmp(vec[1], "email")
1473 || !strcmp(vec[1], "rights")))) {
1474 if((k = trackdb_getuserinfo(vec[0])))
1475 if((value = kvp_get(k, vec[1])))
1476 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(value));
1477 else
1478 sink_writes(ev_writer_sink(c->w), "555 Not set\n");
1479 else
1480 sink_writes(ev_writer_sink(c->w), "550 No such user\n");
834e7c4a 1481 } else {
2e9ba080
RK
1482 disorder_error(0, "%s attempted userinfo but lacks required rights",
1483 c->who);
b4a80f69 1484 sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
834e7c4a 1485 }
f0feb22e
RK
1486 return 1;
1487}
1488
c3be4f19
RK
1489static int c_users(struct conn *c,
1490 char attribute((unused)) **vec,
1491 int attribute((unused)) nvec) {
ddbf05c8 1492 return list_response(c, "User list follows", trackdb_listusers());
c3be4f19
RK
1493}
1494
ba39faf6
RK
1495static int c_register(struct conn *c,
1496 char **vec,
1497 int attribute((unused)) nvec) {
53710d44
RK
1498 char *cs;
1499 uint32_t nonce[CONFIRM_SIZE];
1500 char nonce_str[(32 * CONFIRM_SIZE) / 5 + 1];
1501
1502 /* The confirmation string is username/base62(nonce). The confirmation
1503 * process will pick the username back out to identify them but the _whole_
1504 * string is used as the confirmation string. Base 62 means we used only
1505 * letters and digits, minimizing the chance of the URL being mispasted. */
1506 gcry_randomize(nonce, sizeof nonce, GCRY_STRONG_RANDOM);
1507 if(basen(nonce, CONFIRM_SIZE, nonce_str, sizeof nonce_str, 62)) {
2e9ba080 1508 disorder_error(0, "buffer too small encoding confirmation string");
53710d44
RK
1509 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1510 }
1511 byte_xasprintf(&cs, "%s/%s", vec[0], nonce_str);
ba39faf6
RK
1512 if(trackdb_adduser(vec[0], vec[1], config->default_rights, vec[2], cs))
1513 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1514 else
1515 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cs));
1516 return 1;
1517}
1518
1519static int c_confirm(struct conn *c,
1520 char **vec,
1521 int attribute((unused)) nvec) {
ba39faf6 1522 char *user, *sep;
30365519 1523 rights_type rights;
1524 const char *host;
ba39faf6 1525
30365519 1526 /* Get some kind of peer identifcation */
1527 if(!(host = connection_host(c))) {
1528 sink_writes(ev_writer_sink(c->w), "530 Authentication failure\n");
1529 return 1;
1530 }
53710d44
RK
1531 /* Picking the LAST / means we don't (here) rule out slashes in usernames. */
1532 if(!(sep = strrchr(vec[0], '/'))) {
ba39faf6
RK
1533 sink_writes(ev_writer_sink(c->w), "550 Malformed confirmation string\n");
1534 return 1;
1535 }
53710d44 1536 user = xstrndup(vec[0], sep - vec[0]);
30365519 1537 if(trackdb_confirm(user, vec[0], &rights))
b60ceb3c 1538 sink_writes(ev_writer_sink(c->w), "510 Incorrect confirmation string\n");
30365519 1539 else {
1540 c->who = user;
1541 c->cookie = 0;
1542 c->rights = rights;
1543 if(strcmp(host, "local"))
2e9ba080 1544 disorder_info("S%x %s confirmed from %s", c->tag, user, host);
30365519 1545 else
1546 c->rights |= RIGHT__LOCAL;
1547 /* Response contains username so client knows who they are acting as */
1548 sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
1549 }
ba39faf6
RK
1550 return 1;
1551}
6207d2f3 1552
1553static int sent_reminder(ev_source attribute((unused)) *ev,
1554 pid_t attribute((unused)) pid,
1555 int status,
1556 const struct rusage attribute((unused)) *rusage,
1557 void *u) {
1558 struct conn *const c = u;
1559
1560 /* Tell the client what went down */
1561 if(!status) {
1562 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1563 } else {
2e9ba080 1564 disorder_error(0, "reminder subprocess %s", wstat(status));
6207d2f3 1565 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1566 }
1567 /* Re-enable this connection */
1568 ev_reader_enable(c->r);
1569 return 0;
1570}
1571
1572static int c_reminder(struct conn *c,
1573 char **vec,
1574 int attribute((unused)) nvec) {
1575 struct kvp *k;
1576 const char *password, *email, *text, *encoding, *charset, *content_type;
1577 const time_t *last;
1578 time_t now;
1579 pid_t pid;
1580
1581 static hash *last_reminder;
1582
1583 if(!config->mail_sender) {
2e9ba080 1584 disorder_error(0, "cannot send password reminders because mail_sender not set");
6207d2f3 1585 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1586 return 1;
1587 }
1588 if(!(k = trackdb_getuserinfo(vec[0]))) {
2e9ba080 1589 disorder_error(0, "reminder for user '%s' who does not exist", vec[0]);
6207d2f3 1590 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1591 return 1;
1592 }
1593 if(!(email = kvp_get(k, "email"))
33e95f03 1594 || !email_valid(email)) {
2e9ba080 1595 disorder_error(0, "user '%s' has no valid email address", vec[0]);
6207d2f3 1596 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1597 return 1;
1598 }
1599 if(!(password = kvp_get(k, "password"))
1600 || !*password) {
2e9ba080 1601 disorder_error(0, "user '%s' has no password", vec[0]);
6207d2f3 1602 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1603 return 1;
1604 }
1605 /* Rate-limit reminders. This hash is bounded in size by the number of
1606 * users. If this is actually a problem for anyone then we can periodically
1607 * clean it. */
1608 if(!last_reminder)
1609 last_reminder = hash_new(sizeof (time_t));
1610 last = hash_find(last_reminder, vec[0]);
4265e5d3 1611 xtime(&now);
6207d2f3 1612 if(last && now < *last + config->reminder_interval) {
2e9ba080 1613 disorder_error(0, "sent a password reminder to '%s' too recently", vec[0]);
6207d2f3 1614 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1615 return 1;
1616 }
1617 /* Send the reminder */
1618 /* TODO this should be templatized and to some extent merged with
1619 * the code in act_register() */
1620 byte_xasprintf((char **)&text,
1621"Someone requested that you be sent a reminder of your DisOrder password.\n"
1622"Your password is:\n"
1623"\n"
1624" %s\n", password);
1625 if(!(text = mime_encode_text(text, &charset, &encoding)))
2e9ba080 1626 disorder_fatal(0, "cannot encode email");
6207d2f3 1627 byte_xasprintf((char **)&content_type, "text/plain;charset=%s",
1628 quote822(charset, 0));
1629 pid = sendmail_subprocess("", config->mail_sender, email,
1630 "DisOrder password reminder",
1631 encoding, content_type, text);
1632 if(pid < 0) {
1633 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1634 return 1;
1635 }
1636 hash_add(last_reminder, vec[0], &now, HASH_INSERT_OR_REPLACE);
2e9ba080 1637 disorder_info("sending a passsword reminder to user '%s'", vec[0]);
6207d2f3 1638 /* We can only continue when the subprocess finishes */
1639 ev_child(c->ev, pid, 0, sent_reminder, c);
1640 return 0;
1641}
1642
2b33c4cf
RK
1643static int c_schedule_list(struct conn *c,
1644 char attribute((unused)) **vec,
1645 int attribute((unused)) nvec) {
1646 char **ids = schedule_list(0);
1647 sink_writes(ev_writer_sink(c->w), "253 ID list follows\n");
1648 while(*ids)
1649 sink_printf(ev_writer_sink(c->w), "%s\n", *ids++);
1650 sink_writes(ev_writer_sink(c->w), ".\n");
1651 return 1; /* completed */
1652}
1653
1654static int c_schedule_get(struct conn *c,
1655 char **vec,
1656 int attribute((unused)) nvec) {
1657 struct kvp *actiondata = schedule_get(vec[0]), *k;
1658
1659 if(!actiondata) {
1660 sink_writes(ev_writer_sink(c->w), "555 No such event\n");
1661 return 1; /* completed */
1662 }
1663 /* Scheduled events are public information. Anyone with RIGHT_READ can see
1664 * them. */
1665 sink_writes(ev_writer_sink(c->w), "253 Event information follows\n");
1666 for(k = actiondata; k; k = k->next)
1667 sink_printf(ev_writer_sink(c->w), " %s %s\n",
1668 quoteutf8(k->name), quoteutf8(k->value));
1669 sink_writes(ev_writer_sink(c->w), ".\n");
1670 return 1; /* completed */
1671}
1672
1673static int c_schedule_del(struct conn *c,
1674 char **vec,
1675 int attribute((unused)) nvec) {
1676 struct kvp *actiondata = schedule_get(vec[0]);
1677
1678 if(!actiondata) {
1679 sink_writes(ev_writer_sink(c->w), "555 No such event\n");
1680 return 1; /* completed */
1681 }
1682 /* If you have admin rights you can delete anything. If you don't then you
1683 * can only delete your own scheduled events. */
1684 if(!(c->rights & RIGHT_ADMIN)) {
1685 const char *who = kvp_get(actiondata, "who");
1686
1687 if(!who || !c->who || strcmp(who, c->who)) {
b60ceb3c 1688 sink_writes(ev_writer_sink(c->w), "510 Not authorized\n");
2b33c4cf
RK
1689 return 1; /* completed */
1690 }
1691 }
1692 if(schedule_del(vec[0]))
1693 sink_writes(ev_writer_sink(c->w), "550 Could not delete scheduled event\n");
1694 else
1695 sink_writes(ev_writer_sink(c->w), "250 Deleted\n");
1696 return 1; /* completed */
1697}
1698
1699static int c_schedule_add(struct conn *c,
1700 char **vec,
1701 int nvec) {
1702 struct kvp *actiondata = 0;
067eeb5f 1703 const char *id;
2b33c4cf
RK
1704
1705 /* Standard fields */
1706 kvp_set(&actiondata, "who", c->who);
1707 kvp_set(&actiondata, "when", vec[0]);
1708 kvp_set(&actiondata, "priority", vec[1]);
1709 kvp_set(&actiondata, "action", vec[2]);
1710 /* Action-dependent fields */
1711 if(!strcmp(vec[2], "play")) {
1712 if(nvec != 4) {
1713 sink_writes(ev_writer_sink(c->w), "550 Wrong number of arguments\n");
1714 return 1;
1715 }
1716 if(!trackdb_exists(vec[3])) {
1717 sink_writes(ev_writer_sink(c->w), "550 Track is not in database\n");
1718 return 1;
1719 }
1720 kvp_set(&actiondata, "track", vec[3]);
1721 } else if(!strcmp(vec[2], "set-global")) {
1722 if(nvec < 4 || nvec > 5) {
1723 sink_writes(ev_writer_sink(c->w), "550 Wrong number of arguments\n");
1724 return 1;
1725 }
1726 kvp_set(&actiondata, "key", vec[3]);
1727 if(nvec > 4)
1728 kvp_set(&actiondata, "value", vec[4]);
1729 } else {
1730 sink_writes(ev_writer_sink(c->w), "550 Unknown action\n");
1731 return 1;
1732 }
1733 /* schedule_add() checks user rights */
1734 id = schedule_add(c->ev, actiondata);
1735 if(!id)
1736 sink_writes(ev_writer_sink(c->w), "550 Cannot add scheduled event\n");
1737 else
1738 sink_printf(ev_writer_sink(c->w), "252 %s\n", id);
1739 return 1;
1740}
1741
d42e98ca
RK
1742static int c_adopt(struct conn *c,
1743 char **vec,
1744 int attribute((unused)) nvec) {
1745 struct queue_entry *q;
1746
1747 if(!c->who) {
1748 sink_writes(ev_writer_sink(c->w), "550 no identity\n");
1749 return 1;
1750 }
1751 if(!(q = queue_find(vec[0]))) {
1752 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1753 return 1;
1754 }
1755 if(q->origin != origin_random) {
1756 sink_writes(ev_writer_sink(c->w), "550 not a random track\n");
1757 return 1;
1758 }
1759 q->origin = origin_adopted;
1760 q->submitter = xstrdup(c->who);
1761 eventlog("adopted", q->id, q->submitter, (char *)0);
1762 queue_write();
1763 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1764 return 1;
1765}
1766
ddbf05c8
RK
1767static int playlist_response(struct conn *c,
1768 int err) {
1769 switch(err) {
1770 case 0:
1771 assert(!"cannot cope with success");
1772 case EACCES:
b60ceb3c 1773 sink_writes(ev_writer_sink(c->w), "510 Access denied\n");
ddbf05c8
RK
1774 break;
1775 case EINVAL:
1776 sink_writes(ev_writer_sink(c->w), "550 Invalid playlist name\n");
1777 break;
1778 case ENOENT:
1779 sink_writes(ev_writer_sink(c->w), "555 No such playlist\n");
1780 break;
1781 default:
1782 sink_writes(ev_writer_sink(c->w), "550 Error accessing playlist\n");
1783 break;
1784 }
1785 return 1;
1786}
1787
1788static int c_playlist_get(struct conn *c,
1789 char **vec,
1790 int attribute((unused)) nvec) {
1791 char **tracks;
1792 int err;
1793
1794 if(!(err = trackdb_playlist_get(vec[0], c->who, &tracks, 0, 0)))
1795 return list_response(c, "Playlist contents follows", tracks);
1796 else
1797 return playlist_response(c, err);
1798}
1799
1800static int c_playlist_set(struct conn *c,
1801 char **vec,
1802 int attribute((unused)) nvec) {
f65f5aff
RK
1803 return fetch_body(c, c_playlist_set_body, vec[0]);
1804}
1805
1806static int c_playlist_set_body(struct conn *c,
1807 char **body,
1808 int nbody,
1809 void *u) {
1810 const char *playlist = u;
1811 int err;
1812
440af55d
RK
1813 if(!c->locked_playlist
1814 || strcmp(playlist, c->locked_playlist)) {
1815 sink_writes(ev_writer_sink(c->w), "550 Playlist is not locked\n");
1816 return 1;
1817 }
f65f5aff
RK
1818 if(!(err = trackdb_playlist_set(playlist, c->who,
1819 body, nbody, 0))) {
1820 sink_printf(ev_writer_sink(c->w), "250 OK\n");
1821 return 1;
1822 } else
1823 return playlist_response(c, err);
ddbf05c8
RK
1824}
1825
1826static int c_playlist_get_share(struct conn *c,
1827 char **vec,
1828 int attribute((unused)) nvec) {
1829 char *share;
1830 int err;
1831
1832 if(!(err = trackdb_playlist_get(vec[0], c->who, 0, 0, &share))) {
f65f5aff 1833 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(share));
ddbf05c8
RK
1834 return 1;
1835 } else
1836 return playlist_response(c, err);
1837}
1838
1839static int c_playlist_set_share(struct conn *c,
1840 char **vec,
1841 int attribute((unused)) nvec) {
1842 int err;
1843
1844 if(!(err = trackdb_playlist_set(vec[0], c->who, 0, 0, vec[1]))) {
f65f5aff 1845 sink_printf(ev_writer_sink(c->w), "250 OK\n");
ddbf05c8
RK
1846 return 1;
1847 } else
1848 return playlist_response(c, err);
1849}
1850
1851static int c_playlists(struct conn *c,
1852 char attribute((unused)) **vec,
1853 int attribute((unused)) nvec) {
1854 char **p;
1855
1856 trackdb_playlist_list(c->who, &p, 0);
1857 return list_response(c, "List of playlists follows", p);
1858}
1859
1860static int c_playlist_delete(struct conn *c,
1861 char **vec,
1862 int attribute((unused)) nvec) {
1863 int err;
1864
1865 if(!(err = trackdb_playlist_delete(vec[0], c->who))) {
f65f5aff 1866 sink_writes(ev_writer_sink(c->w), "250 OK\n");
ddbf05c8
RK
1867 return 1;
1868 } else
1869 return playlist_response(c, err);
1870}
1871
1872static int c_playlist_lock(struct conn *c,
1873 char **vec,
1874 int attribute((unused)) nvec) {
1875 int err;
1876 struct conn *cc;
1877
1878 /* Check we're allowed to modify this playlist */
1879 if((err = trackdb_playlist_set(vec[0], c->who, 0, 0, 0)))
1880 return playlist_response(c, err);
1881 /* If we hold a lock don't allow a new one */
1882 if(c->locked_playlist) {
1883 sink_writes(ev_writer_sink(c->w), "550 Already holding a lock\n");
1884 return 1;
1885 }
1886 /* See if some other connection locks the same playlist */
1887 for(cc = connections; cc; cc = cc->next)
1888 if(cc->locked_playlist && !strcmp(cc->locked_playlist, vec[0]))
1889 break;
1890 if(cc) {
1891 /* TODO: implement config->playlist_lock_timeout */
1892 sink_writes(ev_writer_sink(c->w), "550 Already locked\n");
1893 return 1;
1894 }
1895 c->locked_playlist = xstrdup(vec[0]);
1896 time(&c->locked_when);
1897 sink_writes(ev_writer_sink(c->w), "250 Acquired lock\n");
1898 return 1;
1899}
1900
1901static int c_playlist_unlock(struct conn *c,
f65f5aff 1902 char attribute((unused)) **vec,
ddbf05c8
RK
1903 int attribute((unused)) nvec) {
1904 if(!c->locked_playlist) {
1905 sink_writes(ev_writer_sink(c->w), "550 Not holding a lock\n");
1906 return 1;
1907 }
1908 c->locked_playlist = 0;
1909 sink_writes(ev_writer_sink(c->w), "250 Released lock\n");
1910 return 1;
1911}
1912
598b07b7
RK
1913/** @brief Server's definition of a command */
1914static const struct server_command {
eb5dc014 1915 /** @brief Command name */
460b9539 1916 const char *name;
eb5dc014
RK
1917
1918 /** @brief Minimum number of arguments */
1919 int minargs;
1920
1921 /** @brief Maximum number of arguments */
1922 int maxargs;
1923
1924 /** @brief Function to process command */
460b9539 1925 int (*fn)(struct conn *, char **, int);
eb5dc014
RK
1926
1927 /** @brief Rights required to execute command
1928 *
1929 * 0 means that the command can be issued without logging in. If multiple
1930 * bits are listed here any of those rights will do.
1931 */
1932 rights_type rights;
460b9539 1933} commands[] = {
a6e44aa2 1934 { "adduser", 2, 3, c_adduser, RIGHT_ADMIN },
d42e98ca 1935 { "adopt", 1, 1, c_adopt, RIGHT_PLAY },
eb5dc014 1936 { "allfiles", 0, 2, c_allfiles, RIGHT_READ },
ba39faf6 1937 { "confirm", 1, 1, c_confirm, 0 },
b12be54a 1938 { "cookie", 1, 1, c_cookie, 0 },
a6e44aa2 1939 { "deluser", 1, 1, c_deluser, RIGHT_ADMIN },
eb5dc014
RK
1940 { "dirs", 0, 2, c_dirs, RIGHT_READ },
1941 { "disable", 0, 1, c_disable, RIGHT_GLOBAL_PREFS },
1942 { "edituser", 3, 3, c_edituser, RIGHT_ADMIN|RIGHT_USERINFO },
1943 { "enable", 0, 0, c_enable, RIGHT_GLOBAL_PREFS },
1944 { "enabled", 0, 0, c_enabled, RIGHT_READ },
1945 { "exists", 1, 1, c_exists, RIGHT_READ },
1946 { "files", 0, 2, c_files, RIGHT_READ },
1947 { "get", 2, 2, c_get, RIGHT_READ },
1948 { "get-global", 1, 1, c_get_global, RIGHT_READ },
1949 { "length", 1, 1, c_length, RIGHT_READ },
1950 { "log", 0, 0, c_log, RIGHT_READ },
1951 { "make-cookie", 0, 0, c_make_cookie, RIGHT_READ },
1952 { "move", 2, 2, c_move, RIGHT_MOVE__MASK },
1953 { "moveafter", 1, INT_MAX, c_moveafter, RIGHT_MOVE__MASK },
1954 { "new", 0, 1, c_new, RIGHT_READ },
1955 { "nop", 0, 0, c_nop, 0 },
1956 { "part", 3, 3, c_part, RIGHT_READ },
1957 { "pause", 0, 0, c_pause, RIGHT_PAUSE },
1958 { "play", 1, 1, c_play, RIGHT_PLAY },
7a853280 1959 { "playafter", 2, INT_MAX, c_playafter, RIGHT_PLAY },
eb5dc014 1960 { "playing", 0, 0, c_playing, RIGHT_READ },
ddbf05c8 1961 { "playlist-delete", 1, 1, c_playlist_delete, RIGHT_PLAY },
fc80bbcd
RK
1962 { "playlist-get", 1, 1, c_playlist_get, RIGHT_READ },
1963 { "playlist-get-share", 1, 1, c_playlist_get_share, RIGHT_READ },
ddbf05c8
RK
1964 { "playlist-lock", 1, 1, c_playlist_lock, RIGHT_PLAY },
1965 { "playlist-set", 1, 1, c_playlist_set, RIGHT_PLAY },
1966 { "playlist-set-share", 2, 2, c_playlist_set_share, RIGHT_PLAY },
1967 { "playlist-unlock", 0, 0, c_playlist_unlock, RIGHT_PLAY },
fc80bbcd 1968 { "playlists", 0, 0, c_playlists, RIGHT_READ },
eb5dc014
RK
1969 { "prefs", 1, 1, c_prefs, RIGHT_READ },
1970 { "queue", 0, 0, c_queue, RIGHT_READ },
1971 { "random-disable", 0, 0, c_random_disable, RIGHT_GLOBAL_PREFS },
1972 { "random-enable", 0, 0, c_random_enable, RIGHT_GLOBAL_PREFS },
1973 { "random-enabled", 0, 0, c_random_enabled, RIGHT_READ },
1974 { "recent", 0, 0, c_recent, RIGHT_READ },
1975 { "reconfigure", 0, 0, c_reconfigure, RIGHT_ADMIN },
a6e44aa2 1976 { "register", 3, 3, c_register, RIGHT_REGISTER },
6207d2f3 1977 { "reminder", 1, 1, c_reminder, RIGHT__LOCAL },
eb5dc014 1978 { "remove", 1, 1, c_remove, RIGHT_REMOVE__MASK },
dd9af5cb 1979 { "rescan", 0, INT_MAX, c_rescan, RIGHT_RESCAN },
eb5dc014
RK
1980 { "resolve", 1, 1, c_resolve, RIGHT_READ },
1981 { "resume", 0, 0, c_resume, RIGHT_PAUSE },
1982 { "revoke", 0, 0, c_revoke, RIGHT_READ },
1983 { "rtp-address", 0, 0, c_rtp_address, 0 },
b0116b5c
RK
1984 { "rtp-cancel", 0, 0, c_rtp_cancel, 0 },
1985 { "rtp-request", 2, 2, c_rtp_request, RIGHT_READ },
2b33c4cf
RK
1986 { "schedule-add", 3, INT_MAX, c_schedule_add, RIGHT_READ },
1987 { "schedule-del", 1, 1, c_schedule_del, RIGHT_READ },
1988 { "schedule-get", 1, 1, c_schedule_get, RIGHT_READ },
1989 { "schedule-list", 0, 0, c_schedule_list, RIGHT_READ },
eb5dc014
RK
1990 { "scratch", 0, 1, c_scratch, RIGHT_SCRATCH__MASK },
1991 { "search", 1, 1, c_search, RIGHT_READ },
1992 { "set", 3, 3, c_set, RIGHT_PREFS, },
1993 { "set-global", 2, 2, c_set_global, RIGHT_GLOBAL_PREFS },
1994 { "shutdown", 0, 0, c_shutdown, RIGHT_ADMIN },
1995 { "stats", 0, 0, c_stats, RIGHT_READ },
1996 { "tags", 0, 0, c_tags, RIGHT_READ },
1997 { "unset", 2, 2, c_set, RIGHT_PREFS },
1998 { "unset-global", 1, 1, c_set_global, RIGHT_GLOBAL_PREFS },
460b9539 1999 { "user", 2, 2, c_user, 0 },
eb5dc014
RK
2000 { "userinfo", 2, 2, c_userinfo, RIGHT_READ },
2001 { "users", 0, 0, c_users, RIGHT_READ },
2002 { "version", 0, 0, c_version, RIGHT_READ },
2003 { "volume", 0, 2, c_volume, RIGHT_READ|RIGHT_VOLUME }
460b9539 2004};
2005
f65f5aff
RK
2006/** @brief Fetch a command body
2007 * @param c Connection
2008 * @param body_callback Called with body
2009 * @param u Passed to body_callback
2010 * @return 1
2011 */
2012static int fetch_body(struct conn *c,
2013 body_callback_type body_callback,
2014 void *u) {
2015 assert(c->line_reader == command);
2016 c->line_reader = body_line;
2017 c->body_callback = body_callback;
2018 c->body_u = u;
2019 vector_init(c->body);
2020 return 1;
2021}
2022
2023/** @brief @ref line_reader_type callback for command body lines
2024 * @param c Connection
2025 * @param line Line
2026 * @return 1 if complete, 0 if incomplete
2027 *
2028 * Called from reader_callback().
2029 */
2030static int body_line(struct conn *c,
2031 char *line) {
2032 if(*line == '.') {
2033 ++line;
2034 if(!*line) {
2035 /* That's the lot */
2036 c->line_reader = command;
2037 vector_terminate(c->body);
2038 return c->body_callback(c, c->body->vec, c->body->nvec, c->body_u);
2039 }
2040 }
2041 vector_append(c->body, xstrdup(line));
2042 return 1; /* completed */
2043}
2044
460b9539 2045static void command_error(const char *msg, void *u) {
2046 struct conn *c = u;
2047
2048 sink_printf(ev_writer_sink(c->w), "500 parse error: %s\n", msg);
2049}
2050
f65f5aff
RK
2051/** @brief @ref line_reader_type callback for commands
2052 * @param c Connection
2053 * @param line Line
2054 * @return 1 if complete, 0 if incomplete
2055 *
2056 * Called from reader_callback().
2057 */
460b9539 2058static int command(struct conn *c, char *line) {
2059 char **vec;
2060 int nvec, n;
2061
2062 D(("server command %s", line));
f9635e06
RK
2063 /* We force everything into NFC as early as possible */
2064 if(!(line = utf8_compose_canon(line, strlen(line), 0))) {
2065 sink_writes(ev_writer_sink(c->w), "500 cannot normalize command\n");
2066 return 1;
2067 }
460b9539 2068 if(!(vec = split(line, &nvec, SPLIT_QUOTES, command_error, c))) {
2069 sink_writes(ev_writer_sink(c->w), "500 cannot parse command\n");
2070 return 1;
2071 }
2072 if(nvec == 0) {
2073 sink_writes(ev_writer_sink(c->w), "500 do what?\n");
2074 return 1;
2075 }
ba937f01 2076 if((n = TABLE_FIND(commands, name, vec[0])) < 0)
460b9539 2077 sink_writes(ev_writer_sink(c->w), "500 unknown command\n");
2078 else {
eb5dc014
RK
2079 if(commands[n].rights
2080 && !(c->rights & commands[n].rights)) {
2e9ba080
RK
2081 disorder_error(0, "%s attempted %s but lacks required rights",
2082 c->who ? c->who : "NULL",
834e7c4a 2083 commands[n].name);
b4a80f69 2084 sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
460b9539 2085 return 1;
2086 }
2087 ++vec;
2088 --nvec;
2089 if(nvec < commands[n].minargs) {
2090 sink_writes(ev_writer_sink(c->w), "500 missing argument(s)\n");
2091 return 1;
2092 }
2093 if(nvec > commands[n].maxargs) {
2094 sink_writes(ev_writer_sink(c->w), "500 too many arguments\n");
2095 return 1;
2096 }
2097 return commands[n].fn(c, vec, nvec);
2098 }
2099 return 1; /* completed */
2100}
2101
2102/* redirect to the right reader callback for our current state */
2103static int redirect_reader_callback(ev_source *ev,
2104 ev_reader *reader,
460b9539 2105 void *ptr,
2106 size_t bytes,
2107 int eof,
2108 void *u) {
2109 struct conn *c = u;
2110
75d64210 2111 return c->reader(ev, reader, ptr, bytes, eof, u);
460b9539 2112}
2113
2114/* the main command reader */
2115static int reader_callback(ev_source attribute((unused)) *ev,
2116 ev_reader *reader,
460b9539 2117 void *ptr,
2118 size_t bytes,
2119 int eof,
2120 void *u) {
2121 struct conn *c = u;
2122 char *eol;
2123 int complete;
2124
2125 D(("server reader_callback"));
2126 while((eol = memchr(ptr, '\n', bytes))) {
2127 *eol++ = 0;
2128 ev_reader_consume(reader, eol - (char *)ptr);
f65f5aff 2129 complete = c->line_reader(c, ptr); /* usually command() */
460b9539 2130 bytes -= (eol - (char *)ptr);
2131 ptr = eol;
2132 if(!complete) {
2133 /* the command had better have set a new reader callback */
2134 if(bytes || eof)
2135 /* there are further bytes to read, or we are at eof; arrange for the
2136 * command's reader callback to handle them */
2137 return ev_reader_incomplete(reader);
2138 /* nothing's going on right now */
2139 return 0;
2140 }
2141 /* command completed, we can go around and handle the next one */
2142 }
2143 if(eof) {
2144 if(bytes)
2e9ba080 2145 disorder_error(0, "S%x unterminated line", c->tag);
8d8b8c1f 2146 D(("normal reader close"));
397ef7bb
RK
2147 c->r = 0;
2148 if(c->w) {
8d8b8c1f 2149 D(("close associated writer"));
397ef7bb
RK
2150 ev_writer_close(c->w);
2151 c->w = 0;
2152 }
0126692c 2153 remove_connection(c);
460b9539 2154 }
2155 return 0;
2156}
2157
2158static int listen_callback(ev_source *ev,
2159 int fd,
2160 const struct sockaddr attribute((unused)) *remote,
2161 socklen_t attribute((unused)) rlen,
2162 void *u) {
2163 const struct listener *l = u;
2164 struct conn *c = xmalloc(sizeof *c);
2165 static unsigned tags;
2166
2167 D(("server listen_callback fd %d (%s)", fd, l->name));
2168 nonblock(fd);
2169 cloexec(fd);
ad492e00 2170 c->next = connections;
460b9539 2171 c->tag = tags++;
2172 c->ev = ev;
e8c92ba7
RK
2173 c->w = ev_writer_new(ev, fd, writer_error, c,
2174 "client writer");
31e2a93e 2175 if(!c->w) {
2e9ba080 2176 disorder_error(0, "ev_writer_new for file inbound connection (fd=%d) failed",
31e2a93e
RK
2177 fd);
2178 close(fd);
2179 return 0;
2180 }
e8c92ba7
RK
2181 c->r = ev_reader_new(ev, fd, redirect_reader_callback, reader_error, c,
2182 "client reader");
31e2a93e
RK
2183 if(!c->r)
2184 /* Main reason for failure is the FD is too big and that will already have
2185 * been handled */
2e9ba080
RK
2186 disorder_fatal(0,
2187 "ev_reader_new for file inbound connection (fd=%d) failed",
2188 fd);
75d64210 2189 ev_tie(c->r, c->w);
460b9539 2190 c->fd = fd;
2191 c->reader = reader_callback;
2192 c->l = l;
eb5dc014 2193 c->rights = 0;
f65f5aff 2194 c->line_reader = command;
ad492e00 2195 connections = c;
460b9539 2196 gcry_randomize(c->nonce, sizeof c->nonce, GCRY_STRONG_RANDOM);
7b32e917
RK
2197 sink_printf(ev_writer_sink(c->w), "231 %d %s %s\n",
2198 2,
b3141726
RK
2199 config->authorization_algorithm,
2200 hex(c->nonce, sizeof c->nonce));
460b9539 2201 return 0;
2202}
2203
2204int server_start(ev_source *ev, int pf,
2205 size_t socklen, const struct sockaddr *sa,
de37b640
RK
2206 const char *name,
2207 int privileged) {
460b9539 2208 int fd;
2209 struct listener *l = xmalloc(sizeof *l);
2210 static const int one = 1;
2211
de37b640
RK
2212 D(("server_init socket %s privileged=%d", name, privileged));
2213 /* Sanity check */
2214 if(privileged && pf != AF_UNIX)
2215 disorder_fatal(0, "cannot create a privileged listener on a non-local port");
460b9539 2216 fd = xsocket(pf, SOCK_STREAM, 0);
2217 xsetsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
2218 if(bind(fd, sa, socklen) < 0) {
2e9ba080 2219 disorder_error(errno, "error binding to %s", name);
460b9539 2220 return -1;
2221 }
2222 xlisten(fd, 128);
2223 nonblock(fd);
2224 cloexec(fd);
2225 l->name = name;
2226 l->pf = pf;
de37b640 2227 l->privileged = privileged;
e8c92ba7
RK
2228 if(ev_listen(ev, fd, listen_callback, l, "server listener"))
2229 exit(EXIT_FAILURE);
2e9ba080 2230 disorder_info("listening on %s", name);
460b9539 2231 return fd;
2232}
2233
2234int server_stop(ev_source *ev, int fd) {
2235 xclose(fd);
2236 return ev_listen_cancel(ev, fd);
2237}
2238
2239/*
2240Local Variables:
2241c-basic-offset:2
2242comment-column:40
2243fill-column:79
2244End:
2245*/