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