chiark / gitweb /
Back end for scheduling code (cf defect #6). Currently there's no way
[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
21#include <config.h>
22#include "types.h"
23
24#include <pwd.h>
25#include <sys/types.h>
26#include <sys/socket.h>
27#include <sys/time.h>
28#include <unistd.h>
29#include <stdlib.h>
30#include <string.h>
31#include <errno.h>
32#include <fcntl.h>
33#include <gcrypt.h>
34#include <stddef.h>
35#include <time.h>
36#include <limits.h>
37#include <pcre.h>
38#include <netdb.h>
39#include <netinet/in.h>
40
41#include "event.h"
42#include "server.h"
43#include "syscalls.h"
44#include "queue.h"
f08c0859 45#include "server-queue.h"
460b9539 46#include "play.h"
47#include "log.h"
48#include "mem.h"
49#include "state.h"
50#include "charset.h"
51#include "split.h"
52#include "configuration.h"
53#include "hex.h"
5df73aeb 54#include "rights.h"
460b9539 55#include "trackdb.h"
56#include "table.h"
57#include "kvp.h"
58#include "mixer.h"
59#include "sink.h"
60#include "authhash.h"
61#include "plugin.h"
62#include "printf.h"
63#include "trackname.h"
64#include "eventlog.h"
65#include "defs.h"
66#include "cache.h"
f9635e06 67#include "unicode.h"
b12be54a 68#include "cookies.h"
fce810c2 69#include "base64.h"
6207d2f3 70#include "hash.h"
71#include "mime.h"
72#include "sendmail.h"
73#include "wstat.h"
460b9539 74
75#ifndef NONCE_SIZE
76# define NONCE_SIZE 16
77#endif
78
10114017 79#ifndef CONFIRM_SIZE
80# define CONFIRM_SIZE 10
81#endif
82
460b9539 83int volume_left, volume_right; /* last known volume */
84
18e6d6e6 85/** @brief Accept all well-formed login attempts
86 *
87 * Used in debugging.
88 */
89int wideopen;
90
460b9539 91struct listener {
92 const char *name;
93 int pf;
94};
95
397ef7bb 96/** @brief One client connection */
460b9539 97struct conn {
397ef7bb 98 /** @brief Read commands from here */
460b9539 99 ev_reader *r;
397ef7bb 100 /** @brief Send responses to here */
460b9539 101 ev_writer *w;
397ef7bb 102 /** @brief Underlying file descriptor */
460b9539 103 int fd;
397ef7bb 104 /** @brief Unique identifier for connection used in log messages */
460b9539 105 unsigned tag;
397ef7bb 106 /** @brief Login name or NULL */
460b9539 107 char *who;
397ef7bb 108 /** @brief Event loop */
460b9539 109 ev_source *ev;
397ef7bb 110 /** @brief Nonce chosen for this connection */
460b9539 111 unsigned char nonce[NONCE_SIZE];
397ef7bb
RK
112 /** @brief Current reader callback
113 *
114 * We change this depending on whether we're servicing the @b log command
115 */
460b9539 116 ev_reader_callback *reader;
397ef7bb 117 /** @brief Event log output sending to this connection */
460b9539 118 struct eventlog_output *lo;
397ef7bb 119 /** @brief Parent listener */
460b9539 120 const struct listener *l;
b12be54a
RK
121 /** @brief Login cookie or NULL */
122 char *cookie;
eb5dc014
RK
123 /** @brief Connection rights */
124 rights_type rights;
0126692c 125 /** @brief Next connection */
126 struct conn *next;
dd9af5cb
RK
127 /** @brief True if pending rescan had 'wait' set */
128 int rescan_wait;
460b9539 129};
130
0126692c 131/** @brief Linked list of connections */
132static struct conn *connections;
133
460b9539 134static int reader_callback(ev_source *ev,
135 ev_reader *reader,
460b9539 136 void *ptr,
137 size_t bytes,
138 int eof,
139 void *u);
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)
168 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));
1563f6f6 192 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)
204 disable_playing(c->who);
205 else if(nvec == 1 && !strcmp(vec[0], "now"))
206 disable_playing(c->who);
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 }
245 q = queue_add(track, c->who, WHERE_BEFORE_RANDOM);
246 queue_write();
247 /* If we added the first track, and something is playing, then prepare the
248 * new track. If nothing is playing then we don't bother as it wouldn't gain
249 * anything. */
250 if(q == qhead.next && playing)
251 prepare(c->ev, q);
81e440ce 252 sink_printf(ev_writer_sink(c->w), "252 %s\n", q->id);
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
260static int c_remove(struct conn *c, char **vec,
261 int attribute((unused)) nvec) {
262 struct queue_entry *q;
263
264 if(!(q = queue_find(vec[0]))) {
265 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
266 return 1;
267 }
938d8157 268 if(!right_removable(c->rights, c->who, q)) {
834e7c4a 269 error(0, "%s attempted remove but lacks required rights", c->who);
eb5dc014 270 sink_writes(ev_writer_sink(c->w),
b4a80f69 271 "510 Not authorized to remove that track\n");
eb5dc014 272 return 1;
460b9539 273 }
274 queue_remove(q, c->who);
275 /* De-prepare the track. */
276 abandon(c->ev, q);
49a773eb
RK
277 /* See about adding a new random track */
278 add_random_track(c->ev);
460b9539 279 /* Prepare whatever the next head track is. */
280 if(qhead.next != &qhead)
281 prepare(c->ev, qhead.next);
282 queue_write();
283 sink_writes(ev_writer_sink(c->w), "250 removed\n");
284 return 1; /* completed */
285}
286
287static int c_scratch(struct conn *c,
288 char **vec,
289 int nvec) {
290 if(!playing) {
291 sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
292 return 1; /* completed */
293 }
eb5dc014
RK
294 /* TODO there is a bug here: if we specify an ID but it's not the currently
295 * playing track then you will get 550 if you weren't authorized to scratch
296 * the currently playing track. */
938d8157 297 if(!right_scratchable(c->rights, c->who, playing)) {
834e7c4a 298 error(0, "%s attempted scratch but lacks required rights", c->who);
eb5dc014 299 sink_writes(ev_writer_sink(c->w),
b4a80f69 300 "510 Not authorized to scratch that track\n");
eb5dc014 301 return 1;
460b9539 302 }
303 scratch(c->who, nvec == 1 ? vec[0] : 0);
304 /* If you scratch an unpaused track then it is automatically unpaused */
305 resume_playing(0);
306 sink_writes(ev_writer_sink(c->w), "250 scratched\n");
307 return 1; /* completed */
308}
309
310static int c_pause(struct conn *c,
311 char attribute((unused)) **vec,
312 int attribute((unused)) nvec) {
313 if(!playing) {
314 sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
315 return 1; /* completed */
316 }
317 if(paused) {
318 sink_writes(ev_writer_sink(c->w), "250 already paused\n");
319 return 1; /* completed */
320 }
321 if(pause_playing(c->who) < 0)
322 sink_writes(ev_writer_sink(c->w), "550 cannot pause this track\n");
323 else
324 sink_writes(ev_writer_sink(c->w), "250 paused\n");
325 return 1;
326}
327
328static int c_resume(struct conn *c,
329 char attribute((unused)) **vec,
330 int attribute((unused)) nvec) {
331 if(!paused) {
332 sink_writes(ev_writer_sink(c->w), "250 not paused\n");
333 return 1; /* completed */
334 }
335 resume_playing(c->who);
336 sink_writes(ev_writer_sink(c->w), "250 paused\n");
337 return 1;
338}
339
340static int c_shutdown(struct conn *c,
341 char attribute((unused)) **vec,
342 int attribute((unused)) nvec) {
343 info("S%x shut down by %s", c->tag, c->who);
344 sink_writes(ev_writer_sink(c->w), "250 shutting down\n");
345 ev_writer_flush(c->w);
346 quit(c->ev);
347}
348
349static int c_reconfigure(struct conn *c,
350 char attribute((unused)) **vec,
351 int attribute((unused)) nvec) {
352 info("S%x reconfigure by %s", c->tag, c->who);
353 if(reconfigure(c->ev, 1))
354 sink_writes(ev_writer_sink(c->w), "550 error reading new config\n");
355 else
356 sink_writes(ev_writer_sink(c->w), "250 installed new config\n");
357 return 1; /* completed */
358}
359
dd9af5cb
RK
360static void finished_rescan(void *ru) {
361 struct conn *const c = ru;
362
363 sink_writes(ev_writer_sink(c->w), "250 rescan completed\n");
364 /* Turn this connection back on */
365 ev_reader_enable(c->r);
366}
367
368static void start_fresh_rescan(void *ru) {
369 struct conn *const c = ru;
370
371 if(trackdb_rescan_underway()) {
372 /* Some other waiter beat us to it. However in this case we're happy to
373 * piggyback; the requirement is that a new rescan be started, not that it
374 * was _our_ rescan. */
375 if(c->rescan_wait) {
376 /* We block until the rescan completes */
377 trackdb_add_rescanned(finished_rescan, c);
378 } else {
379 /* We report that the new rescan has started */
380 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
381 /* Turn this connection back on */
382 ev_reader_enable(c->r);
383 }
384 } else {
385 /* We are the first connection to get a callback so we must start a
386 * rescan. */
387 if(c->rescan_wait) {
388 /* We want to block until the new rescan completes */
389 trackdb_rescan(c->ev, 1/*check*/, finished_rescan, c);
390 } else {
391 /* We can report back immediately */
392 trackdb_rescan(c->ev, 1/*check*/, 0, 0);
393 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
394 /* Turn this connection back on */
395 ev_reader_enable(c->r);
396 }
397 }
398}
399
460b9539 400static int c_rescan(struct conn *c,
dd9af5cb
RK
401 char **vec,
402 int nvec) {
403 int wait = 0, fresh = 0, n;
404
405 /* Parse flags */
406 for(n = 0; n < nvec; ++n) {
407 if(!strcmp(vec[n], "wait"))
408 wait = 1; /* wait for rescan to complete */
409#if 0
410 /* Currently disabled because untested (and hard to test). */
411 else if(!strcmp(vec[n], "fresh"))
412 fresh = 1; /* don't piggyback underway rescan */
413#endif
414 else {
415 sink_writes(ev_writer_sink(c->w), "550 unknown flag\n");
416 return 1; /* completed */
417 }
418 }
419 /* Report what was requested */
420 info("S%x rescan by %s (%s %s)", c->tag, c->who,
421 wait ? "wait" : "",
422 fresh ? "fresh" : "");
423 if(trackdb_rescan_underway()) {
424 if(fresh) {
425 /* We want a fresh rescan but there is already one underway. Arrange a
426 * callback when it completes and then set off a new one. */
427 c->rescan_wait = wait;
428 trackdb_add_rescanned(start_fresh_rescan, c);
429 if(wait)
430 return 0;
431 else {
432 sink_writes(ev_writer_sink(c->w), "250 rescan queued\n");
433 return 1;
434 }
435 } else {
436 /* There's a rescan underway, and it's acceptable to piggyback on it */
437 if(wait) {
438 /* We want to block until completion. */
439 trackdb_add_rescanned(finished_rescan, c);
440 return 0;
441 } else {
442 /* We don't want to block. So we just report that things are in
443 * hand. */
444 sink_writes(ev_writer_sink(c->w), "250 rescan already underway\n");
445 return 1;
446 }
447 }
448 } else {
449 /* No rescan is underway. fresh is therefore irrelevant. */
450 if(wait) {
451 /* We want to block until completion */
452 trackdb_rescan(c->ev, 1/*check*/, finished_rescan, c);
453 return 0;
454 } else {
455 /* We don't want to block. */
456 trackdb_rescan(c->ev, 1/*check*/, 0, 0);
457 sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
458 return 1; /* completed */
459 }
460 }
460b9539 461}
462
463static int c_version(struct conn *c,
464 char attribute((unused)) **vec,
465 int attribute((unused)) nvec) {
466 /* VERSION had better only use the basic character set */
a05e4467 467 sink_printf(ev_writer_sink(c->w), "251 %s\n", disorder_short_version_string);
460b9539 468 return 1; /* completed */
469}
470
471static int c_playing(struct conn *c,
472 char attribute((unused)) **vec,
473 int attribute((unused)) nvec) {
474 if(playing) {
475 queue_fix_sofar(playing);
476 playing->expected = 0;
477 sink_printf(ev_writer_sink(c->w), "252 %s\n", queue_marshall(playing));
478 } else
479 sink_printf(ev_writer_sink(c->w), "259 nothing playing\n");
480 return 1; /* completed */
481}
482
b12be54a 483static const char *connection_host(struct conn *c) {
460b9539 484 union {
485 struct sockaddr sa;
486 struct sockaddr_in in;
487 struct sockaddr_in6 in6;
488 } u;
489 socklen_t l;
b12be54a 490 int n;
460b9539 491 char host[1024];
492
460b9539 493 /* get connection data */
494 l = sizeof u;
495 if(getpeername(c->fd, &u.sa, &l) < 0) {
496 error(errno, "S%x error calling getpeername", c->tag);
b12be54a 497 return 0;
460b9539 498 }
499 if(c->l->pf != PF_UNIX) {
500 if((n = getnameinfo(&u.sa, l,
501 host, sizeof host, 0, 0, NI_NUMERICHOST))) {
502 error(0, "S%x error calling getnameinfo: %s", c->tag, gai_strerror(n));
b12be54a 503 return 0;
460b9539 504 }
b12be54a 505 return xstrdup(host);
18e6d6e6 506 } else
b12be54a
RK
507 return "local";
508}
509
510static int c_user(struct conn *c,
511 char **vec,
512 int attribute((unused)) nvec) {
eb5dc014 513 struct kvp *k;
f0feb22e 514 const char *res, *host, *password;
eb5dc014 515 rights_type rights;
b12be54a
RK
516
517 if(c->who) {
518 sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
519 return 1;
520 }
521 /* get connection data */
522 if(!(host = connection_host(c))) {
523 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
524 return 1;
525 }
460b9539 526 /* find the user */
eb5dc014 527 k = trackdb_getuserinfo(vec[0]);
f0feb22e 528 /* reject nonexistent users */
eb5dc014
RK
529 if(!k) {
530 error(0, "S%x unknown user '%s' from %s", c->tag, vec[0], host);
531 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
532 return 1;
533 }
534 /* reject unconfirmed users */
535 if(kvp_get(k, "confirmation")) {
536 error(0, "S%x unconfirmed user '%s' from %s", c->tag, vec[0], host);
537 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
538 return 1;
539 }
540 password = kvp_get(k, "password");
541 if(!password) password = "";
0f55e905 542 if(parse_rights(kvp_get(k, "rights"), &rights, 1)) {
eb5dc014 543 error(0, "error parsing rights for %s", vec[0]);
18e6d6e6 544 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
545 return 1;
546 }
f0feb22e
RK
547 /* check whether the response is right */
548 res = authhash(c->nonce, sizeof c->nonce, password,
637fdea3 549 config->authorization_algorithm);
18e6d6e6 550 if(wideopen || (res && !strcmp(res, vec[1]))) {
551 c->who = vec[0];
eb5dc014 552 c->rights = rights;
18e6d6e6 553 /* currently we only bother logging remote connections */
30365519 554 if(strcmp(host, "local"))
18e6d6e6 555 info("S%x %s connected from %s", c->tag, vec[0], host);
30365519 556 else
eb5dc014 557 c->rights |= RIGHT__LOCAL;
18e6d6e6 558 sink_writes(ev_writer_sink(c->w), "230 OK\n");
559 return 1;
460b9539 560 }
561 /* oops, response was wrong */
18e6d6e6 562 info("S%x authentication failure for %s from %s", c->tag, vec[0], host);
460b9539 563 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
564 return 1;
565}
566
567static int c_recent(struct conn *c,
568 char attribute((unused)) **vec,
569 int attribute((unused)) nvec) {
570 const struct queue_entry *q;
571
572 sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
573 for(q = phead.next; q != &phead; q = q->next)
574 sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
575 sink_writes(ev_writer_sink(c->w), ".\n");
576 return 1; /* completed */
577}
578
579static int c_queue(struct conn *c,
580 char attribute((unused)) **vec,
581 int attribute((unused)) nvec) {
582 struct queue_entry *q;
583 time_t when = 0;
584 const char *l;
585 long length;
586
587 sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
588 if(playing_is_enabled() && !paused) {
589 if(playing) {
590 queue_fix_sofar(playing);
591 if((l = trackdb_get(playing->track, "_length"))
592 && (length = atol(l))) {
593 time(&when);
594 when += length - playing->sofar + config->gap;
595 }
596 } else
597 /* Nothing is playing but playing is enabled, so whatever is
598 * first in the queue can be expected to start immediately. */
599 time(&when);
600 }
601 for(q = qhead.next; q != &qhead; q = q->next) {
602 /* fill in estimated start time */
603 q->expected = when;
604 sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
605 /* update for next track */
606 if(when) {
607 if((l = trackdb_get(q->track, "_length"))
608 && (length = atol(l)))
609 when += length + config->gap;
610 else
611 when = 0;
612 }
613 }
614 sink_writes(ev_writer_sink(c->w), ".\n");
615 return 1; /* completed */
616}
617
618static int output_list(struct conn *c, char **vec) {
619 while(*vec)
620 sink_printf(ev_writer_sink(c->w), "%s\n", *vec++);
621 sink_writes(ev_writer_sink(c->w), ".\n");
622 return 1;
623}
624
625static int files_dirs(struct conn *c,
626 char **vec,
627 int nvec,
628 enum trackdb_listable what) {
629 const char *dir, *re, *errstr;
630 int erroffset;
631 pcre *rec;
632 char **fvec, *key;
633
634 switch(nvec) {
635 case 0: dir = 0; re = 0; break;
636 case 1: dir = vec[0]; re = 0; break;
637 case 2: dir = vec[0]; re = vec[1]; break;
638 default: abort();
639 }
640 /* A bit of a bodge to make sure the args don't trample on cache keys */
641 if(dir && strchr(dir, '\n')) {
642 sink_writes(ev_writer_sink(c->w), "550 invalid directory name\n");
643 return 1;
644 }
645 if(re && strchr(re, '\n')) {
646 sink_writes(ev_writer_sink(c->w), "550 invalid regexp\n");
647 return 1;
648 }
649 /* We bother eliminating "" because the web interface is relatively
650 * likely to send it */
651 if(re && *re) {
652 byte_xasprintf(&key, "%d\n%s\n%s", (int)what, dir ? dir : "", re);
653 fvec = (char **)cache_get(&cache_files_type, key);
654 if(fvec) {
655 /* Got a cache hit, don't store the answer in the cache */
656 key = 0;
657 ++cache_files_hits;
658 rec = 0; /* quieten compiler */
659 } else {
660 /* Cache miss, we'll do the lookup and key != 0 so we'll store the answer
661 * in the cache. */
662 if(!(rec = pcre_compile(re, PCRE_CASELESS|PCRE_UTF8,
663 &errstr, &erroffset, 0))) {
664 sink_printf(ev_writer_sink(c->w), "550 Error compiling regexp: %s\n",
665 errstr);
666 return 1;
667 }
668 /* It only counts as a miss if the regexp was valid. */
669 ++cache_files_misses;
670 }
671 } else {
672 /* No regexp, don't bother caching the result */
673 rec = 0;
674 key = 0;
675 fvec = 0;
676 }
677 if(!fvec) {
678 /* No cache hit (either because a miss, or because we did not look) so do
679 * the lookup */
680 if(dir && *dir)
681 fvec = trackdb_list(dir, 0, what, rec);
682 else
683 fvec = trackdb_list(0, 0, what, rec);
684 }
685 if(key)
686 /* Put the answer in the cache */
687 cache_put(&cache_files_type, key, fvec);
688 sink_writes(ev_writer_sink(c->w), "253 Listing follow\n");
689 return output_list(c, fvec);
690}
691
692static int c_files(struct conn *c,
693 char **vec,
694 int nvec) {
695 return files_dirs(c, vec, nvec, trackdb_files);
696}
697
698static int c_dirs(struct conn *c,
699 char **vec,
700 int nvec) {
701 return files_dirs(c, vec, nvec, trackdb_directories);
702}
703
704static int c_allfiles(struct conn *c,
705 char **vec,
706 int nvec) {
707 return files_dirs(c, vec, nvec, trackdb_directories|trackdb_files);
708}
709
710static int c_get(struct conn *c,
711 char **vec,
712 int attribute((unused)) nvec) {
27ed5a69 713 const char *v, *track;
460b9539 714
27ed5a69
RK
715 if(!(track = trackdb_resolve(vec[0]))) {
716 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
717 return 1;
718 }
719 if(vec[1][0] != '_' && (v = trackdb_get(track, vec[1])))
7b32e917 720 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
460b9539 721 else
fb1bc1f5 722 sink_writes(ev_writer_sink(c->w), "555 not found\n");
460b9539 723 return 1;
724}
725
726static int c_length(struct conn *c,
727 char **vec,
728 int attribute((unused)) nvec) {
729 const char *track, *v;
730
731 if(!(track = trackdb_resolve(vec[0]))) {
732 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
733 return 1;
734 }
735 if((v = trackdb_get(track, "_length")))
7b32e917 736 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
460b9539 737 else
738 sink_writes(ev_writer_sink(c->w), "550 not found\n");
739 return 1;
740}
741
742static int c_set(struct conn *c,
743 char **vec,
744 int attribute((unused)) nvec) {
27ed5a69
RK
745 const char *track;
746
747 if(!(track = trackdb_resolve(vec[0]))) {
748 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
749 return 1;
750 }
751 if(vec[1][0] != '_' && !trackdb_set(track, vec[1], vec[2]))
460b9539 752 sink_writes(ev_writer_sink(c->w), "250 OK\n");
753 else
754 sink_writes(ev_writer_sink(c->w), "550 not found\n");
755 return 1;
756}
757
758static int c_prefs(struct conn *c,
759 char **vec,
760 int attribute((unused)) nvec) {
761 struct kvp *k;
27ed5a69 762 const char *track;
460b9539 763
27ed5a69
RK
764 if(!(track = trackdb_resolve(vec[0]))) {
765 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
766 return 1;
767 }
768 k = trackdb_get_all(track);
460b9539 769 sink_writes(ev_writer_sink(c->w), "253 prefs follow\n");
770 for(; k; k = k->next)
771 if(k->name[0] != '_') /* omit internal values */
772 sink_printf(ev_writer_sink(c->w),
773 " %s %s\n", quoteutf8(k->name), quoteutf8(k->value));
774 sink_writes(ev_writer_sink(c->w), ".\n");
775 return 1;
776}
777
778static int c_exists(struct conn *c,
779 char **vec,
780 int attribute((unused)) nvec) {
27ed5a69 781 /* trackdb_exists() does its own alias checking */
460b9539 782 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[trackdb_exists(vec[0])]);
783 return 1;
784}
785
786static void search_parse_error(const char *msg, void *u) {
787 *(const char **)u = msg;
788}
789
790static int c_search(struct conn *c,
791 char **vec,
792 int attribute((unused)) nvec) {
793 char **terms, **results;
794 int nterms, nresults, n;
795 const char *e = "unknown error";
796
797 /* This is a bit of a bodge. Initially it's there to make the eclient
798 * interface a bit more convenient to add searching to, but it has the more
799 * compelling advantage that if everything uses it, then interpretation of
800 * user-supplied search strings will be the same everywhere. */
801 if(!(terms = split(vec[0], &nterms, SPLIT_QUOTES, search_parse_error, &e))) {
802 sink_printf(ev_writer_sink(c->w), "550 %s\n", e);
803 } else {
804 results = trackdb_search(terms, nterms, &nresults);
805 sink_printf(ev_writer_sink(c->w), "253 %d matches\n", nresults);
806 for(n = 0; n < nresults; ++n)
807 sink_printf(ev_writer_sink(c->w), "%s\n", results[n]);
808 sink_writes(ev_writer_sink(c->w), ".\n");
809 }
810 return 1;
811}
812
813static int c_random_enable(struct conn *c,
814 char attribute((unused)) **vec,
815 int attribute((unused)) nvec) {
816 enable_random(c->who, c->ev);
817 /* Enable implicitly unpauses if there is nothing playing */
818 if(paused && !playing) resume_playing(c->who);
819 sink_writes(ev_writer_sink(c->w), "250 OK\n");
820 return 1; /* completed */
821}
822
823static int c_random_disable(struct conn *c,
824 char attribute((unused)) **vec,
825 int attribute((unused)) nvec) {
826 disable_random(c->who);
827 sink_writes(ev_writer_sink(c->w), "250 OK\n");
828 return 1; /* completed */
829}
830
831static int c_random_enabled(struct conn *c,
832 char attribute((unused)) **vec,
833 int attribute((unused)) nvec) {
834 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[random_is_enabled()]);
835 return 1; /* completed */
836}
837
d6dde5a3
RK
838static void got_stats(char *stats, void *u) {
839 struct conn *const c = u;
840
841 sink_printf(ev_writer_sink(c->w), "253 stats\n%s\n.\n", stats);
842 /* Now we can start processing commands again */
843 ev_reader_enable(c->r);
844}
845
460b9539 846static int c_stats(struct conn *c,
847 char attribute((unused)) **vec,
848 int attribute((unused)) nvec) {
d6dde5a3
RK
849 trackdb_stats_subprocess(c->ev, got_stats, c);
850 return 0; /* not yet complete */
460b9539 851}
852
853static int c_volume(struct conn *c,
854 char **vec,
855 int nvec) {
856 int l, r, set;
857 char lb[32], rb[32];
eb5dc014 858 rights_type rights;
460b9539 859
860 switch(nvec) {
861 case 0:
862 set = 0;
863 break;
864 case 1:
865 l = r = atoi(vec[0]);
866 set = 1;
867 break;
868 case 2:
869 l = atoi(vec[0]);
870 r = atoi(vec[1]);
871 set = 1;
872 break;
873 default:
874 abort();
875 }
eb5dc014
RK
876 rights = set ? RIGHT_VOLUME : RIGHT_READ;
877 if(!(c->rights & rights)) {
834e7c4a 878 error(0, "%s attempted to set volume but lacks required rights", c->who);
b4a80f69 879 sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
eb5dc014
RK
880 return 1;
881 }
3c499fe7 882 if(mixer_control(-1/*as configured*/, &l, &r, set))
460b9539 883 sink_writes(ev_writer_sink(c->w), "550 error accessing mixer\n");
884 else {
885 sink_printf(ev_writer_sink(c->w), "252 %d %d\n", l, r);
886 if(l != volume_left || r != volume_right) {
887 volume_left = l;
888 volume_right = r;
889 snprintf(lb, sizeof lb, "%d", l);
890 snprintf(rb, sizeof rb, "%d", r);
891 eventlog("volume", lb, rb, (char *)0);
892 }
893 }
894 return 1;
895}
896
397ef7bb
RK
897/** @brief Called when data arrives on a log connection
898 *
899 * We just discard all such data. The client may occasionally send data as a
900 * keepalive.
901 */
902static int logging_reader_callback(ev_source attribute((unused)) *ev,
460b9539 903 ev_reader *reader,
397ef7bb 904 void attribute((unused)) *ptr,
460b9539 905 size_t bytes,
397ef7bb
RK
906 int attribute((unused)) eof,
907 void attribute((unused)) *u) {
460b9539 908 struct conn *c = u;
909
397ef7bb
RK
910 ev_reader_consume(reader, bytes);
911 if(eof) {
912 /* Oops, that's all for now */
8d8b8c1f 913 D(("logging reader eof"));
397ef7bb 914 if(c->w) {
8d8b8c1f 915 D(("close writer"));
397ef7bb
RK
916 ev_writer_close(c->w);
917 c->w = 0;
918 }
919 c->r = 0;
0126692c 920 remove_connection(c);
f6033c46 921 }
397ef7bb 922 return 0;
460b9539 923}
924
925static void logclient(const char *msg, void *user) {
926 struct conn *c = user;
927
f6033c46
RK
928 if(!c->w || !c->r) {
929 /* This connection has gone up in smoke for some reason */
930 eventlog_remove(c->lo);
931 return;
932 }
460b9539 933 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" %s\n",
934 (uintmax_t)time(0), msg);
935}
936
937static int c_log(struct conn *c,
938 char attribute((unused)) **vec,
939 int attribute((unused)) nvec) {
940 time_t now;
941
942 sink_writes(ev_writer_sink(c->w), "254 OK\n");
943 /* pump out initial state */
944 time(&now);
945 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
946 (uintmax_t)now,
947 playing_is_enabled() ? "enable_play" : "disable_play");
948 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
949 (uintmax_t)now,
950 random_is_enabled() ? "enable_random" : "disable_random");
951 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
952 (uintmax_t)now,
953 paused ? "pause" : "resume");
5abe307a
RK
954 if(playing)
955 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state playing\n",
956 (uintmax_t)now);
df44d69b
RK
957 /* Initial volume */
958 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" volume %d %d\n",
959 (uintmax_t)now, volume_left, volume_right);
460b9539 960 c->lo = xmalloc(sizeof *c->lo);
961 c->lo->fn = logclient;
962 c->lo->user = c;
963 eventlog_add(c->lo);
964 c->reader = logging_reader_callback;
965 return 0;
966}
967
eb5dc014
RK
968/** @brief Test whether a move is allowed
969 * @param c Connection
970 * @param qs List of IDs on queue
971 * @param nqs Number of IDs
972 * @return 0 if move is prohibited, non-0 if it is allowed
973 */
974static int has_move_rights(struct conn *c, struct queue_entry **qs, int nqs) {
eb5dc014
RK
975 for(; nqs > 0; ++qs, --nqs) {
976 struct queue_entry *const q = *qs;
977
938d8157 978 if(!right_movable(c->rights, c->who, q))
979 return 0;
eb5dc014 980 }
938d8157 981 return 1;
eb5dc014
RK
982}
983
460b9539 984static int c_move(struct conn *c,
985 char **vec,
986 int attribute((unused)) nvec) {
987 struct queue_entry *q;
988 int n;
989
460b9539 990 if(!(q = queue_find(vec[0]))) {
991 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
992 return 1;
993 }
eb5dc014 994 if(!has_move_rights(c, &q, 1)) {
834e7c4a 995 error(0, "%s attempted move but lacks required rights", c->who);
eb5dc014 996 sink_writes(ev_writer_sink(c->w),
b4a80f69 997 "510 Not authorized to move that track\n");
eb5dc014
RK
998 return 1;
999 }
460b9539 1000 n = queue_move(q, atoi(vec[1]), c->who);
460b9539 1001 sink_printf(ev_writer_sink(c->w), "252 %d\n", n);
1002 /* If we've moved to the head of the queue then prepare the track. */
1003 if(q == qhead.next)
1004 prepare(c->ev, q);
1005 return 1;
1006}
1007
1008static int c_moveafter(struct conn *c,
1009 char **vec,
1010 int attribute((unused)) nvec) {
1011 struct queue_entry *q, **qs;
1012 int n;
1013
460b9539 1014 if(vec[0][0]) {
1015 if(!(q = queue_find(vec[0]))) {
1016 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1017 return 1;
1018 }
1019 } else
1020 q = 0;
1021 ++vec;
1022 --nvec;
1023 qs = xcalloc(nvec, sizeof *qs);
1024 for(n = 0; n < nvec; ++n)
1025 if(!(qs[n] = queue_find(vec[n]))) {
1026 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1027 return 1;
1028 }
eb5dc014 1029 if(!has_move_rights(c, qs, nvec)) {
834e7c4a 1030 error(0, "%s attempted moveafter but lacks required rights", c->who);
eb5dc014 1031 sink_writes(ev_writer_sink(c->w),
b4a80f69 1032 "510 Not authorized to move those tracks\n");
eb5dc014
RK
1033 return 1;
1034 }
460b9539 1035 queue_moveafter(q, nvec, qs, c->who);
460b9539 1036 sink_printf(ev_writer_sink(c->w), "250 Moved tracks\n");
1037 /* If we've moved to the head of the queue then prepare the track. */
1038 if(q == qhead.next)
1039 prepare(c->ev, q);
1040 return 1;
1041}
1042
1043static int c_part(struct conn *c,
1044 char **vec,
1045 int attribute((unused)) nvec) {
27ed5a69
RK
1046 const char *track;
1047
1048 if(!(track = trackdb_resolve(vec[0]))) {
1049 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1050 return 1;
1051 }
460b9539 1052 sink_printf(ev_writer_sink(c->w), "252 %s\n",
27ed5a69 1053 quoteutf8(trackdb_getpart(track, vec[1], vec[2])));
460b9539 1054 return 1;
1055}
1056
1057static int c_resolve(struct conn *c,
1058 char **vec,
1059 int attribute((unused)) nvec) {
1060 const char *track;
1061
1062 if(!(track = trackdb_resolve(vec[0]))) {
1063 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1064 return 1;
1065 }
7b32e917 1066 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(track));
460b9539 1067 return 1;
1068}
1069
1070static int c_tags(struct conn *c,
1071 char attribute((unused)) **vec,
1072 int attribute((unused)) nvec) {
1073 char **tags = trackdb_alltags();
1074
1075 sink_printf(ev_writer_sink(c->w), "253 Tag list follows\n");
1076 while(*tags) {
1077 sink_printf(ev_writer_sink(c->w), "%s%s\n",
1078 **tags == '.' ? "." : "", *tags);
1079 ++tags;
1080 }
1081 sink_writes(ev_writer_sink(c->w), ".\n");
1082 return 1; /* completed */
460b9539 1083}
1084
1085static int c_set_global(struct conn *c,
1086 char **vec,
1087 int attribute((unused)) nvec) {
f9635e06
RK
1088 if(vec[0][0] == '_') {
1089 sink_writes(ev_writer_sink(c->w), "550 cannot set internal global preferences\n");
1090 return 1;
1091 }
460b9539 1092 trackdb_set_global(vec[0], vec[1], c->who);
1093 sink_printf(ev_writer_sink(c->w), "250 OK\n");
1094 return 1;
1095}
1096
1097static int c_get_global(struct conn *c,
1098 char **vec,
1099 int attribute((unused)) nvec) {
1100 const char *s = trackdb_get_global(vec[0]);
1101
1102 if(s)
7b32e917 1103 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(s));
460b9539 1104 else
fb1bc1f5 1105 sink_writes(ev_writer_sink(c->w), "555 not found\n");
460b9539 1106 return 1;
1107}
1108
7858930d 1109static int c_nop(struct conn *c,
1110 char attribute((unused)) **vec,
1111 int attribute((unused)) nvec) {
1112 sink_printf(ev_writer_sink(c->w), "250 Quack\n");
1113 return 1;
1114}
1115
2a10b70b
RK
1116static int c_new(struct conn *c,
1117 char **vec,
1118 int nvec) {
d742bb47
RK
1119 int max, n;
1120 char **tracks;
2a10b70b 1121
d742bb47
RK
1122 if(nvec > 0)
1123 max = atoi(vec[0]);
1124 else
1125 max = INT_MAX;
1126 if(max <= 0 || max > config->new_max)
1127 max = config->new_max;
1128 tracks = trackdb_new(0, max);
2a10b70b 1129 sink_printf(ev_writer_sink(c->w), "253 New track list follows\n");
d742bb47 1130 n = 0;
2a10b70b
RK
1131 while(*tracks) {
1132 sink_printf(ev_writer_sink(c->w), "%s%s\n",
1133 **tracks == '.' ? "." : "", *tracks);
1134 ++tracks;
1135 }
1136 sink_writes(ev_writer_sink(c->w), ".\n");
1137 return 1; /* completed */
1138
1139}
1140
ca831831
RK
1141static int c_rtp_address(struct conn *c,
1142 char attribute((unused)) **vec,
1143 int attribute((unused)) nvec) {
bd8895a8 1144 if(config->api == BACKEND_NETWORK) {
ca831831
RK
1145 sink_printf(ev_writer_sink(c->w), "252 %s %s\n",
1146 quoteutf8(config->broadcast.s[0]),
1147 quoteutf8(config->broadcast.s[1]));
1148 } else
1149 sink_writes(ev_writer_sink(c->w), "550 No RTP\n");
1150 return 1;
1151}
b12be54a
RK
1152
1153static int c_cookie(struct conn *c,
1154 char **vec,
1155 int attribute((unused)) nvec) {
1156 const char *host;
1157 char *user;
eb5dc014 1158 rights_type rights;
b12be54a
RK
1159
1160 /* Can't log in twice on the same connection */
1161 if(c->who) {
1162 sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
1163 return 1;
1164 }
1165 /* Get some kind of peer identifcation */
1166 if(!(host = connection_host(c))) {
1167 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1168 return 1;
1169 }
1170 /* Check the cookie */
eb5dc014 1171 user = verify_cookie(vec[0], &rights);
b12be54a
RK
1172 if(!user) {
1173 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1174 return 1;
1175 }
1176 /* Log in */
e48c28bb 1177 c->who = user;
b12be54a 1178 c->cookie = vec[0];
eb5dc014 1179 c->rights = rights;
30365519 1180 if(strcmp(host, "local"))
b12be54a 1181 info("S%x %s connected with cookie from %s", c->tag, user, host);
30365519 1182 else
eb5dc014 1183 c->rights |= RIGHT__LOCAL;
0227f67d
RK
1184 /* Response contains username so client knows who they are acting as */
1185 sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
b12be54a
RK
1186 return 1;
1187}
1188
1189static int c_make_cookie(struct conn *c,
1190 char attribute((unused)) **vec,
1191 int attribute((unused)) nvec) {
1192 const char *cookie = make_cookie(c->who);
1193
1194 if(cookie)
eb5dc014 1195 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cookie));
b12be54a
RK
1196 else
1197 sink_writes(ev_writer_sink(c->w), "550 Cannot create cookie\n");
1198 return 1;
1199}
1200
1201static int c_revoke(struct conn *c,
1202 char attribute((unused)) **vec,
1203 int attribute((unused)) nvec) {
1204 if(c->cookie) {
1205 revoke_cookie(c->cookie);
1206 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1207 } else
1208 sink_writes(ev_writer_sink(c->w), "550 Did not log in with cookie\n");
1209 return 1;
1210}
1211
f0feb22e
RK
1212static int c_adduser(struct conn *c,
1213 char **vec,
0f55e905
RK
1214 int nvec) {
1215 const char *rights;
1216
810b8083 1217 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
39e7dcfb 1218 error(0, "S%x: remote adduser", c->tag);
810b8083
RK
1219 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1220 return 1;
1221 }
0f55e905
RK
1222 if(nvec > 2) {
1223 rights = vec[2];
1224 if(parse_rights(vec[2], 0, 1)) {
1225 sink_writes(ev_writer_sink(c->w), "550 Invalid rights list\n");
1226 return -1;
1227 }
1228 } else
1229 rights = config->default_rights;
1230 if(trackdb_adduser(vec[0], vec[1], rights,
ba39faf6 1231 0/*email*/, 0/*confirmation*/))
f0feb22e
RK
1232 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1233 else
1234 sink_writes(ev_writer_sink(c->w), "250 User created\n");
1235 return 1;
1236}
1237
1238static int c_deluser(struct conn *c,
1239 char **vec,
1240 int attribute((unused)) nvec) {
0126692c 1241 struct conn *d;
1242
810b8083 1243 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
39e7dcfb 1244 error(0, "S%x: remote deluser", c->tag);
810b8083
RK
1245 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1246 return 1;
1247 }
0126692c 1248 if(trackdb_deluser(vec[0])) {
ba39faf6 1249 sink_writes(ev_writer_sink(c->w), "550 Cannot delete user\n");
0126692c 1250 return 1;
1251 }
1252 /* Zap connections belonging to deleted user */
1253 for(d = connections; d; d = d->next)
1254 if(!strcmp(d->who, vec[0]))
1255 d->rights = 0;
1256 sink_writes(ev_writer_sink(c->w), "250 User deleted\n");
f0feb22e
RK
1257 return 1;
1258}
1259
1260static int c_edituser(struct conn *c,
5df73aeb 1261 char **vec,
f0feb22e 1262 int attribute((unused)) nvec) {
0126692c 1263 struct conn *d;
1264
810b8083 1265 if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
39e7dcfb 1266 error(0, "S%x: remote edituser", c->tag);
810b8083
RK
1267 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1268 return 1;
1269 }
eb5dc014
RK
1270 /* RIGHT_ADMIN can do anything; otherwise you can only set your own email
1271 * address and password. */
1272 if((c->rights & RIGHT_ADMIN)
5df73aeb
RK
1273 || (!strcmp(c->who, vec[0])
1274 && (!strcmp(vec[1], "email")
1275 || !strcmp(vec[1], "password")))) {
0126692c 1276 if(trackdb_edituserinfo(vec[0], vec[1], vec[2])) {
5df73aeb 1277 sink_writes(ev_writer_sink(c->w), "550 Failed to change setting\n");
0126692c 1278 return 1;
1279 }
1280 if(!strcmp(vec[1], "password")) {
1281 /* Zap all connections for this user after a password change */
1282 for(d = connections; d; d = d->next)
1283 if(!strcmp(d->who, vec[0]))
1284 d->rights = 0;
1285 } else if(!strcmp(vec[1], "rights")) {
1286 /* Update rights for this user */
1287 rights_type r;
1288
d3369bca 1289 if(parse_rights(vec[2], &r, 1))
0126692c 1290 for(d = connections; d; d = d->next)
1291 if(!strcmp(d->who, vec[0]))
1292 d->rights = r;
1293 }
1294 sink_writes(ev_writer_sink(c->w), "250 OK\n");
834e7c4a 1295 } else {
1296 error(0, "%s attempted edituser but lacks required rights", c->who);
b4a80f69 1297 sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
834e7c4a 1298 }
f0feb22e
RK
1299 return 1;
1300}
1301
1302static int c_userinfo(struct conn *c,
1303 char attribute((unused)) **vec,
1304 int attribute((unused)) nvec) {
5df73aeb
RK
1305 struct kvp *k;
1306 const char *value;
eb5dc014 1307
39e7dcfb
RK
1308 /* We allow remote querying of rights so that clients can figure out what
1309 * they're allowed to do */
1310 if(!config->remote_userman
1311 && !(c->rights & RIGHT__LOCAL)
1312 && strcmp(vec[1], "rights")) {
1313 error(0, "S%x: remote userinfo %s %s", c->tag, vec[0], vec[1]);
810b8083
RK
1314 sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1315 return 1;
1316 }
eb5dc014 1317 /* RIGHT_ADMIN allows anything; otherwise you can only get your own email
29f5fbd2 1318 * address and rights list. */
eb5dc014 1319 if((c->rights & RIGHT_ADMIN)
5df73aeb
RK
1320 || (!strcmp(c->who, vec[0])
1321 && (!strcmp(vec[1], "email")
1322 || !strcmp(vec[1], "rights")))) {
1323 if((k = trackdb_getuserinfo(vec[0])))
1324 if((value = kvp_get(k, vec[1])))
1325 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(value));
1326 else
1327 sink_writes(ev_writer_sink(c->w), "555 Not set\n");
1328 else
1329 sink_writes(ev_writer_sink(c->w), "550 No such user\n");
834e7c4a 1330 } else {
1331 error(0, "%s attempted userinfo but lacks required rights", c->who);
b4a80f69 1332 sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
834e7c4a 1333 }
f0feb22e
RK
1334 return 1;
1335}
1336
c3be4f19
RK
1337static int c_users(struct conn *c,
1338 char attribute((unused)) **vec,
1339 int attribute((unused)) nvec) {
1340 /* TODO de-dupe with c_tags */
1341 char **users = trackdb_listusers();
1342
1343 sink_writes(ev_writer_sink(c->w), "253 User list follows\n");
1344 while(*users) {
1345 sink_printf(ev_writer_sink(c->w), "%s%s\n",
1346 **users == '.' ? "." : "", *users);
1347 ++users;
1348 }
1349 sink_writes(ev_writer_sink(c->w), ".\n");
1350 return 1; /* completed */
1351}
1352
86e3aea7 1353/** @brief Base64 mapping table for confirmation strings
1354 *
1355 * This is used with generic_to_base64() and generic_base64(). We cannot use
1356 * the MIME table as that contains '+' and '=' which get quoted when
1357 * URL-encoding. (The CGI still does the URL encoding but it is desirable to
1358 * avoid it being necessary.)
1359 */
1360static const char confirm_base64_table[] =
1361 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/.*";
1362
ba39faf6
RK
1363static int c_register(struct conn *c,
1364 char **vec,
1365 int attribute((unused)) nvec) {
1366 char *buf, *cs;
1367 size_t bufsize;
1368 int offset;
1369
1370 /* The confirmation string is base64(username;nonce) */
10114017 1371 bufsize = strlen(vec[0]) + CONFIRM_SIZE + 2;
ba39faf6
RK
1372 buf = xmalloc_noptr(bufsize);
1373 offset = byte_snprintf(buf, bufsize, "%s;", vec[0]);
10114017 1374 gcry_randomize(buf + offset, CONFIRM_SIZE, GCRY_STRONG_RANDOM);
86e3aea7 1375 cs = generic_to_base64((uint8_t *)buf, offset + CONFIRM_SIZE,
1376 confirm_base64_table);
ba39faf6
RK
1377 if(trackdb_adduser(vec[0], vec[1], config->default_rights, vec[2], cs))
1378 sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1379 else
1380 sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cs));
1381 return 1;
1382}
1383
1384static int c_confirm(struct conn *c,
1385 char **vec,
1386 int attribute((unused)) nvec) {
1387 size_t nuser;
1388 char *user, *sep;
30365519 1389 rights_type rights;
1390 const char *host;
ba39faf6 1391
30365519 1392 /* Get some kind of peer identifcation */
1393 if(!(host = connection_host(c))) {
1394 sink_writes(ev_writer_sink(c->w), "530 Authentication failure\n");
1395 return 1;
1396 }
86e3aea7 1397 if(!(user = generic_base64(vec[0], &nuser, confirm_base64_table))
ba39faf6
RK
1398 || !(sep = memchr(user, ';', nuser))) {
1399 sink_writes(ev_writer_sink(c->w), "550 Malformed confirmation string\n");
1400 return 1;
1401 }
1402 *sep = 0;
30365519 1403 if(trackdb_confirm(user, vec[0], &rights))
ba39faf6 1404 sink_writes(ev_writer_sink(c->w), "550 Incorrect confirmation string\n");
30365519 1405 else {
1406 c->who = user;
1407 c->cookie = 0;
1408 c->rights = rights;
1409 if(strcmp(host, "local"))
1410 info("S%x %s confirmed from %s", c->tag, user, host);
1411 else
1412 c->rights |= RIGHT__LOCAL;
1413 /* Response contains username so client knows who they are acting as */
1414 sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
1415 }
ba39faf6
RK
1416 return 1;
1417}
6207d2f3 1418
1419static int sent_reminder(ev_source attribute((unused)) *ev,
1420 pid_t attribute((unused)) pid,
1421 int status,
1422 const struct rusage attribute((unused)) *rusage,
1423 void *u) {
1424 struct conn *const c = u;
1425
1426 /* Tell the client what went down */
1427 if(!status) {
1428 sink_writes(ev_writer_sink(c->w), "250 OK\n");
1429 } else {
1430 error(0, "reminder subprocess %s", wstat(status));
1431 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1432 }
1433 /* Re-enable this connection */
1434 ev_reader_enable(c->r);
1435 return 0;
1436}
1437
1438static int c_reminder(struct conn *c,
1439 char **vec,
1440 int attribute((unused)) nvec) {
1441 struct kvp *k;
1442 const char *password, *email, *text, *encoding, *charset, *content_type;
1443 const time_t *last;
1444 time_t now;
1445 pid_t pid;
1446
1447 static hash *last_reminder;
1448
1449 if(!config->mail_sender) {
1450 error(0, "cannot send password reminders because mail_sender not set");
1451 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1452 return 1;
1453 }
1454 if(!(k = trackdb_getuserinfo(vec[0]))) {
1455 error(0, "reminder for user '%s' who does not exist", vec[0]);
1456 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1457 return 1;
1458 }
1459 if(!(email = kvp_get(k, "email"))
1460 || !strchr(email, '@')) {
1461 error(0, "user '%s' has no valid email address", vec[0]);
1462 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1463 return 1;
1464 }
1465 if(!(password = kvp_get(k, "password"))
1466 || !*password) {
1467 error(0, "user '%s' has no password", vec[0]);
1468 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1469 return 1;
1470 }
1471 /* Rate-limit reminders. This hash is bounded in size by the number of
1472 * users. If this is actually a problem for anyone then we can periodically
1473 * clean it. */
1474 if(!last_reminder)
1475 last_reminder = hash_new(sizeof (time_t));
1476 last = hash_find(last_reminder, vec[0]);
1477 time(&now);
1478 if(last && now < *last + config->reminder_interval) {
1479 error(0, "sent a password reminder to '%s' too recently", vec[0]);
1480 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1481 return 1;
1482 }
1483 /* Send the reminder */
1484 /* TODO this should be templatized and to some extent merged with
1485 * the code in act_register() */
1486 byte_xasprintf((char **)&text,
1487"Someone requested that you be sent a reminder of your DisOrder password.\n"
1488"Your password is:\n"
1489"\n"
1490" %s\n", password);
1491 if(!(text = mime_encode_text(text, &charset, &encoding)))
1492 fatal(0, "cannot encode email");
1493 byte_xasprintf((char **)&content_type, "text/plain;charset=%s",
1494 quote822(charset, 0));
1495 pid = sendmail_subprocess("", config->mail_sender, email,
1496 "DisOrder password reminder",
1497 encoding, content_type, text);
1498 if(pid < 0) {
1499 sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1500 return 1;
1501 }
1502 hash_add(last_reminder, vec[0], &now, HASH_INSERT_OR_REPLACE);
1503 info("sending a passsword reminder to user '%s'", vec[0]);
1504 /* We can only continue when the subprocess finishes */
1505 ev_child(c->ev, pid, 0, sent_reminder, c);
1506 return 0;
1507}
1508
460b9539 1509static const struct command {
eb5dc014 1510 /** @brief Command name */
460b9539 1511 const char *name;
eb5dc014
RK
1512
1513 /** @brief Minimum number of arguments */
1514 int minargs;
1515
1516 /** @brief Maximum number of arguments */
1517 int maxargs;
1518
1519 /** @brief Function to process command */
460b9539 1520 int (*fn)(struct conn *, char **, int);
eb5dc014
RK
1521
1522 /** @brief Rights required to execute command
1523 *
1524 * 0 means that the command can be issued without logging in. If multiple
1525 * bits are listed here any of those rights will do.
1526 */
1527 rights_type rights;
460b9539 1528} commands[] = {
0f55e905 1529 { "adduser", 2, 3, c_adduser, RIGHT_ADMIN|RIGHT__LOCAL },
eb5dc014 1530 { "allfiles", 0, 2, c_allfiles, RIGHT_READ },
ba39faf6 1531 { "confirm", 1, 1, c_confirm, 0 },
b12be54a 1532 { "cookie", 1, 1, c_cookie, 0 },
eb5dc014
RK
1533 { "deluser", 1, 1, c_deluser, RIGHT_ADMIN|RIGHT__LOCAL },
1534 { "dirs", 0, 2, c_dirs, RIGHT_READ },
1535 { "disable", 0, 1, c_disable, RIGHT_GLOBAL_PREFS },
1536 { "edituser", 3, 3, c_edituser, RIGHT_ADMIN|RIGHT_USERINFO },
1537 { "enable", 0, 0, c_enable, RIGHT_GLOBAL_PREFS },
1538 { "enabled", 0, 0, c_enabled, RIGHT_READ },
1539 { "exists", 1, 1, c_exists, RIGHT_READ },
1540 { "files", 0, 2, c_files, RIGHT_READ },
1541 { "get", 2, 2, c_get, RIGHT_READ },
1542 { "get-global", 1, 1, c_get_global, RIGHT_READ },
1543 { "length", 1, 1, c_length, RIGHT_READ },
1544 { "log", 0, 0, c_log, RIGHT_READ },
1545 { "make-cookie", 0, 0, c_make_cookie, RIGHT_READ },
1546 { "move", 2, 2, c_move, RIGHT_MOVE__MASK },
1547 { "moveafter", 1, INT_MAX, c_moveafter, RIGHT_MOVE__MASK },
1548 { "new", 0, 1, c_new, RIGHT_READ },
1549 { "nop", 0, 0, c_nop, 0 },
1550 { "part", 3, 3, c_part, RIGHT_READ },
1551 { "pause", 0, 0, c_pause, RIGHT_PAUSE },
1552 { "play", 1, 1, c_play, RIGHT_PLAY },
1553 { "playing", 0, 0, c_playing, RIGHT_READ },
1554 { "prefs", 1, 1, c_prefs, RIGHT_READ },
1555 { "queue", 0, 0, c_queue, RIGHT_READ },
1556 { "random-disable", 0, 0, c_random_disable, RIGHT_GLOBAL_PREFS },
1557 { "random-enable", 0, 0, c_random_enable, RIGHT_GLOBAL_PREFS },
1558 { "random-enabled", 0, 0, c_random_enabled, RIGHT_READ },
1559 { "recent", 0, 0, c_recent, RIGHT_READ },
1560 { "reconfigure", 0, 0, c_reconfigure, RIGHT_ADMIN },
ba39faf6 1561 { "register", 3, 3, c_register, RIGHT_REGISTER|RIGHT__LOCAL },
6207d2f3 1562 { "reminder", 1, 1, c_reminder, RIGHT__LOCAL },
eb5dc014 1563 { "remove", 1, 1, c_remove, RIGHT_REMOVE__MASK },
dd9af5cb 1564 { "rescan", 0, INT_MAX, c_rescan, RIGHT_RESCAN },
eb5dc014
RK
1565 { "resolve", 1, 1, c_resolve, RIGHT_READ },
1566 { "resume", 0, 0, c_resume, RIGHT_PAUSE },
1567 { "revoke", 0, 0, c_revoke, RIGHT_READ },
1568 { "rtp-address", 0, 0, c_rtp_address, 0 },
1569 { "scratch", 0, 1, c_scratch, RIGHT_SCRATCH__MASK },
1570 { "search", 1, 1, c_search, RIGHT_READ },
1571 { "set", 3, 3, c_set, RIGHT_PREFS, },
1572 { "set-global", 2, 2, c_set_global, RIGHT_GLOBAL_PREFS },
1573 { "shutdown", 0, 0, c_shutdown, RIGHT_ADMIN },
1574 { "stats", 0, 0, c_stats, RIGHT_READ },
1575 { "tags", 0, 0, c_tags, RIGHT_READ },
1576 { "unset", 2, 2, c_set, RIGHT_PREFS },
1577 { "unset-global", 1, 1, c_set_global, RIGHT_GLOBAL_PREFS },
460b9539 1578 { "user", 2, 2, c_user, 0 },
eb5dc014
RK
1579 { "userinfo", 2, 2, c_userinfo, RIGHT_READ },
1580 { "users", 0, 0, c_users, RIGHT_READ },
1581 { "version", 0, 0, c_version, RIGHT_READ },
1582 { "volume", 0, 2, c_volume, RIGHT_READ|RIGHT_VOLUME }
460b9539 1583};
1584
1585static void command_error(const char *msg, void *u) {
1586 struct conn *c = u;
1587
1588 sink_printf(ev_writer_sink(c->w), "500 parse error: %s\n", msg);
1589}
1590
1591/* process a command. Return 1 if complete, 0 if incomplete. */
1592static int command(struct conn *c, char *line) {
1593 char **vec;
1594 int nvec, n;
1595
1596 D(("server command %s", line));
f9635e06
RK
1597 /* We force everything into NFC as early as possible */
1598 if(!(line = utf8_compose_canon(line, strlen(line), 0))) {
1599 sink_writes(ev_writer_sink(c->w), "500 cannot normalize command\n");
1600 return 1;
1601 }
460b9539 1602 if(!(vec = split(line, &nvec, SPLIT_QUOTES, command_error, c))) {
1603 sink_writes(ev_writer_sink(c->w), "500 cannot parse command\n");
1604 return 1;
1605 }
1606 if(nvec == 0) {
1607 sink_writes(ev_writer_sink(c->w), "500 do what?\n");
1608 return 1;
1609 }
1610 if((n = TABLE_FIND(commands, struct command, name, vec[0])) < 0)
1611 sink_writes(ev_writer_sink(c->w), "500 unknown command\n");
1612 else {
eb5dc014
RK
1613 if(commands[n].rights
1614 && !(c->rights & commands[n].rights)) {
834e7c4a 1615 error(0, "%s attempted %s but lacks required rights", c->who ? c->who : "NULL",
1616 commands[n].name);
b4a80f69 1617 sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
460b9539 1618 return 1;
1619 }
1620 ++vec;
1621 --nvec;
1622 if(nvec < commands[n].minargs) {
1623 sink_writes(ev_writer_sink(c->w), "500 missing argument(s)\n");
1624 return 1;
1625 }
1626 if(nvec > commands[n].maxargs) {
1627 sink_writes(ev_writer_sink(c->w), "500 too many arguments\n");
1628 return 1;
1629 }
1630 return commands[n].fn(c, vec, nvec);
1631 }
1632 return 1; /* completed */
1633}
1634
1635/* redirect to the right reader callback for our current state */
1636static int redirect_reader_callback(ev_source *ev,
1637 ev_reader *reader,
460b9539 1638 void *ptr,
1639 size_t bytes,
1640 int eof,
1641 void *u) {
1642 struct conn *c = u;
1643
75d64210 1644 return c->reader(ev, reader, ptr, bytes, eof, u);
460b9539 1645}
1646
1647/* the main command reader */
1648static int reader_callback(ev_source attribute((unused)) *ev,
1649 ev_reader *reader,
460b9539 1650 void *ptr,
1651 size_t bytes,
1652 int eof,
1653 void *u) {
1654 struct conn *c = u;
1655 char *eol;
1656 int complete;
1657
1658 D(("server reader_callback"));
1659 while((eol = memchr(ptr, '\n', bytes))) {
1660 *eol++ = 0;
1661 ev_reader_consume(reader, eol - (char *)ptr);
1662 complete = command(c, ptr);
1663 bytes -= (eol - (char *)ptr);
1664 ptr = eol;
1665 if(!complete) {
1666 /* the command had better have set a new reader callback */
1667 if(bytes || eof)
1668 /* there are further bytes to read, or we are at eof; arrange for the
1669 * command's reader callback to handle them */
1670 return ev_reader_incomplete(reader);
1671 /* nothing's going on right now */
1672 return 0;
1673 }
1674 /* command completed, we can go around and handle the next one */
1675 }
1676 if(eof) {
1677 if(bytes)
1678 error(0, "S%x unterminated line", c->tag);
8d8b8c1f 1679 D(("normal reader close"));
397ef7bb
RK
1680 c->r = 0;
1681 if(c->w) {
8d8b8c1f 1682 D(("close associated writer"));
397ef7bb
RK
1683 ev_writer_close(c->w);
1684 c->w = 0;
1685 }
0126692c 1686 remove_connection(c);
460b9539 1687 }
1688 return 0;
1689}
1690
1691static int listen_callback(ev_source *ev,
1692 int fd,
1693 const struct sockaddr attribute((unused)) *remote,
1694 socklen_t attribute((unused)) rlen,
1695 void *u) {
1696 const struct listener *l = u;
1697 struct conn *c = xmalloc(sizeof *c);
1698 static unsigned tags;
1699
1700 D(("server listen_callback fd %d (%s)", fd, l->name));
1701 nonblock(fd);
1702 cloexec(fd);
1703 c->tag = tags++;
1704 c->ev = ev;
e8c92ba7
RK
1705 c->w = ev_writer_new(ev, fd, writer_error, c,
1706 "client writer");
1707 c->r = ev_reader_new(ev, fd, redirect_reader_callback, reader_error, c,
1708 "client reader");
75d64210 1709 ev_tie(c->r, c->w);
460b9539 1710 c->fd = fd;
1711 c->reader = reader_callback;
1712 c->l = l;
eb5dc014 1713 c->rights = 0;
460b9539 1714 gcry_randomize(c->nonce, sizeof c->nonce, GCRY_STRONG_RANDOM);
7b32e917
RK
1715 sink_printf(ev_writer_sink(c->w), "231 %d %s %s\n",
1716 2,
b3141726
RK
1717 config->authorization_algorithm,
1718 hex(c->nonce, sizeof c->nonce));
460b9539 1719 return 0;
1720}
1721
1722int server_start(ev_source *ev, int pf,
1723 size_t socklen, const struct sockaddr *sa,
1724 const char *name) {
1725 int fd;
1726 struct listener *l = xmalloc(sizeof *l);
1727 static const int one = 1;
1728
1729 D(("server_init socket %s", name));
1730 fd = xsocket(pf, SOCK_STREAM, 0);
1731 xsetsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
1732 if(bind(fd, sa, socklen) < 0) {
1733 error(errno, "error binding to %s", name);
1734 return -1;
1735 }
1736 xlisten(fd, 128);
1737 nonblock(fd);
1738 cloexec(fd);
1739 l->name = name;
1740 l->pf = pf;
e8c92ba7
RK
1741 if(ev_listen(ev, fd, listen_callback, l, "server listener"))
1742 exit(EXIT_FAILURE);
460b9539 1743 return fd;
1744}
1745
1746int server_stop(ev_source *ev, int fd) {
1747 xclose(fd);
1748 return ev_listen_cancel(ev, fd);
1749}
1750
1751/*
1752Local Variables:
1753c-basic-offset:2
1754comment-column:40
1755fill-column:79
1756End:
1757*/