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