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