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