chiark / gitweb /
fix server crash if log connection fails
[disorder] / server / server.c
CommitLineData
460b9539 1/*
2 * This file is part of DisOrder.
768d7355 3 * Copyright (C) 2004, 2005, 2006, 2007 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"
54#include "trackdb.h"
55#include "table.h"
56#include "kvp.h"
57#include "mixer.h"
58#include "sink.h"
59#include "authhash.h"
60#include "plugin.h"
61#include "printf.h"
62#include "trackname.h"
63#include "eventlog.h"
64#include "defs.h"
65#include "cache.h"
66
67#ifndef NONCE_SIZE
68# define NONCE_SIZE 16
69#endif
70
71int volume_left, volume_right; /* last known volume */
72
18e6d6e6 73/** @brief Accept all well-formed login attempts
74 *
75 * Used in debugging.
76 */
77int wideopen;
78
460b9539 79struct listener {
80 const char *name;
81 int pf;
82};
83
84struct conn {
85 ev_reader *r;
86 ev_writer *w;
87 int fd;
88 unsigned tag;
89 char *who;
90 ev_source *ev;
91 unsigned char nonce[NONCE_SIZE];
92 ev_reader_callback *reader;
93 struct eventlog_output *lo;
94 const struct listener *l;
95};
96
97static int reader_callback(ev_source *ev,
98 ev_reader *reader,
460b9539 99 void *ptr,
100 size_t bytes,
101 int eof,
102 void *u);
103
104static const char *noyes[] = { "no", "yes" };
105
106static int writer_error(ev_source attribute((unused)) *ev,
460b9539 107 int errno_value,
108 void *u) {
109 struct conn *c = u;
110
75d64210 111 D(("server writer_error %d", errno_value));
1563f6f6 112 info("writer_error S%x %d", c->tag, errno_value);
460b9539 113 if(errno_value == 0) {
114 /* writer is done */
75d64210 115 error(errno_value, "S%x writer completed", c->tag); /* TODO */
460b9539 116 } else {
117 if(errno_value != EPIPE)
118 error(errno_value, "S%x write error on socket", c->tag);
38b8221f
RK
119 if(c->r) {
120 info("cancel reader");
121 ev_reader_cancel(c->r);
122 c->r = 0;
123 }
1563f6f6 124 info("done cancel reader");
460b9539 125 }
38b8221f 126 c->w = 0;
75d64210 127 ev_report(ev);
460b9539 128 return 0;
129}
130
131static int reader_error(ev_source attribute((unused)) *ev,
460b9539 132 int errno_value,
133 void *u) {
134 struct conn *c = u;
135
75d64210 136 D(("server reader_error %d", errno_value));
1563f6f6
RK
137 info("reader_error S%x %d", c->tag, errno_value);
138 error(errno_value, "S%x read error on socket", c->tag);
38b8221f
RK
139 if(c->w)
140 ev_writer_close(c->w);
141 c->w = 0;
142 c->r = 0;
768d7355 143 ev_report(ev);
460b9539 144 return 0;
145}
146
147/* return true if we are talking to a trusted user */
148static int trusted(struct conn *c) {
149 int n;
150
151 for(n = 0; (n < config->trust.n
152 && strcmp(config->trust.s[n], c->who)); ++n)
153 ;
154 return n < config->trust.n;
155}
156
157static int c_disable(struct conn *c, char **vec, int nvec) {
158 if(nvec == 0)
159 disable_playing(c->who);
160 else if(nvec == 1 && !strcmp(vec[0], "now"))
161 disable_playing(c->who);
162 else {
163 sink_writes(ev_writer_sink(c->w), "550 invalid argument\n");
164 return 1; /* completed */
165 }
166 sink_writes(ev_writer_sink(c->w), "250 OK\n");
167 return 1; /* completed */
168}
169
170static int c_enable(struct conn *c,
171 char attribute((unused)) **vec,
172 int attribute((unused)) nvec) {
173 enable_playing(c->who, c->ev);
174 /* Enable implicitly unpauses if there is nothing playing */
175 if(paused && !playing) resume_playing(c->who);
176 sink_writes(ev_writer_sink(c->w), "250 OK\n");
177 return 1; /* completed */
178}
179
180static int c_enabled(struct conn *c,
181 char attribute((unused)) **vec,
182 int attribute((unused)) nvec) {
183 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[playing_is_enabled()]);
184 return 1; /* completed */
185}
186
187static int c_play(struct conn *c, char **vec,
188 int attribute((unused)) nvec) {
189 const char *track;
190 struct queue_entry *q;
191
192 if(!trackdb_exists(vec[0])) {
193 sink_writes(ev_writer_sink(c->w), "550 track is not in database\n");
194 return 1;
195 }
196 if(!(track = trackdb_resolve(vec[0]))) {
197 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
198 return 1;
199 }
200 q = queue_add(track, c->who, WHERE_BEFORE_RANDOM);
201 queue_write();
202 /* If we added the first track, and something is playing, then prepare the
203 * new track. If nothing is playing then we don't bother as it wouldn't gain
204 * anything. */
205 if(q == qhead.next && playing)
206 prepare(c->ev, q);
207 sink_writes(ev_writer_sink(c->w), "250 queued\n");
208 /* If the queue was empty but we are for some reason paused then
209 * unpause. */
210 if(!playing) resume_playing(0);
211 play(c->ev);
212 return 1; /* completed */
213}
214
215static int c_remove(struct conn *c, char **vec,
216 int attribute((unused)) nvec) {
217 struct queue_entry *q;
218
219 if(!(q = queue_find(vec[0]))) {
220 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
221 return 1;
222 }
223 if(config->restrictions & RESTRICT_REMOVE) {
224 /* can only remove tracks that you submitted */
225 if(!q->submitter || strcmp(q->submitter, c->who)) {
226 sink_writes(ev_writer_sink(c->w), "550 you didn't submit that track!\n");
227 return 1;
228 }
229 }
230 queue_remove(q, c->who);
231 /* De-prepare the track. */
232 abandon(c->ev, q);
233 /* If we removed the random track then add another one. */
234 if(q->state == playing_random)
235 add_random_track();
236 /* Prepare whatever the next head track is. */
237 if(qhead.next != &qhead)
238 prepare(c->ev, qhead.next);
239 queue_write();
240 sink_writes(ev_writer_sink(c->w), "250 removed\n");
241 return 1; /* completed */
242}
243
244static int c_scratch(struct conn *c,
245 char **vec,
246 int nvec) {
247 if(!playing) {
248 sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
249 return 1; /* completed */
250 }
251 if(config->restrictions & RESTRICT_SCRATCH) {
252 /* can only scratch tracks you submitted and randomly selected ones */
253 if(playing->submitter && strcmp(playing->submitter, c->who)) {
254 sink_writes(ev_writer_sink(c->w), "550 you didn't submit that track!\n");
255 return 1;
256 }
257 }
258 scratch(c->who, nvec == 1 ? vec[0] : 0);
259 /* If you scratch an unpaused track then it is automatically unpaused */
260 resume_playing(0);
261 sink_writes(ev_writer_sink(c->w), "250 scratched\n");
262 return 1; /* completed */
263}
264
265static int c_pause(struct conn *c,
266 char attribute((unused)) **vec,
267 int attribute((unused)) nvec) {
268 if(!playing) {
269 sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
270 return 1; /* completed */
271 }
272 if(paused) {
273 sink_writes(ev_writer_sink(c->w), "250 already paused\n");
274 return 1; /* completed */
275 }
276 if(pause_playing(c->who) < 0)
277 sink_writes(ev_writer_sink(c->w), "550 cannot pause this track\n");
278 else
279 sink_writes(ev_writer_sink(c->w), "250 paused\n");
280 return 1;
281}
282
283static int c_resume(struct conn *c,
284 char attribute((unused)) **vec,
285 int attribute((unused)) nvec) {
286 if(!paused) {
287 sink_writes(ev_writer_sink(c->w), "250 not paused\n");
288 return 1; /* completed */
289 }
290 resume_playing(c->who);
291 sink_writes(ev_writer_sink(c->w), "250 paused\n");
292 return 1;
293}
294
295static int c_shutdown(struct conn *c,
296 char attribute((unused)) **vec,
297 int attribute((unused)) nvec) {
298 info("S%x shut down by %s", c->tag, c->who);
299 sink_writes(ev_writer_sink(c->w), "250 shutting down\n");
300 ev_writer_flush(c->w);
301 quit(c->ev);
302}
303
304static int c_reconfigure(struct conn *c,
305 char attribute((unused)) **vec,
306 int attribute((unused)) nvec) {
307 info("S%x reconfigure by %s", c->tag, c->who);
308 if(reconfigure(c->ev, 1))
309 sink_writes(ev_writer_sink(c->w), "550 error reading new config\n");
310 else
311 sink_writes(ev_writer_sink(c->w), "250 installed new config\n");
312 return 1; /* completed */
313}
314
315static int c_rescan(struct conn *c,
316 char attribute((unused)) **vec,
317 int attribute((unused)) nvec) {
318 info("S%x rescan by %s", c->tag, c->who);
319 trackdb_rescan(c->ev);
320 sink_writes(ev_writer_sink(c->w), "250 initiated rescan\n");
321 return 1; /* completed */
322}
323
324static int c_version(struct conn *c,
325 char attribute((unused)) **vec,
326 int attribute((unused)) nvec) {
327 /* VERSION had better only use the basic character set */
328 sink_printf(ev_writer_sink(c->w), "251 %s\n", disorder_version_string);
329 return 1; /* completed */
330}
331
332static int c_playing(struct conn *c,
333 char attribute((unused)) **vec,
334 int attribute((unused)) nvec) {
335 if(playing) {
336 queue_fix_sofar(playing);
337 playing->expected = 0;
338 sink_printf(ev_writer_sink(c->w), "252 %s\n", queue_marshall(playing));
339 } else
340 sink_printf(ev_writer_sink(c->w), "259 nothing playing\n");
341 return 1; /* completed */
342}
343
344static int c_become(struct conn *c,
345 char **vec,
346 int attribute((unused)) nvec) {
347 c->who = vec[0];
348 sink_writes(ev_writer_sink(c->w), "230 OK\n");
349 return 1;
350}
351
352static int c_user(struct conn *c,
353 char **vec,
354 int attribute((unused)) nvec) {
355 int n;
356 const char *res;
357 union {
358 struct sockaddr sa;
359 struct sockaddr_in in;
360 struct sockaddr_in6 in6;
361 } u;
362 socklen_t l;
363 char host[1024];
364
365 if(c->who) {
366 sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
367 return 1;
368 }
369 /* get connection data */
370 l = sizeof u;
371 if(getpeername(c->fd, &u.sa, &l) < 0) {
372 error(errno, "S%x error calling getpeername", c->tag);
373 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
374 return 1;
375 }
376 if(c->l->pf != PF_UNIX) {
377 if((n = getnameinfo(&u.sa, l,
378 host, sizeof host, 0, 0, NI_NUMERICHOST))) {
379 error(0, "S%x error calling getnameinfo: %s", c->tag, gai_strerror(n));
380 sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
381 return 1;
382 }
18e6d6e6 383 } else
384 strcpy(host, "local");
460b9539 385 /* find the user */
386 for(n = 0; n < config->allow.n
387 && strcmp(config->allow.s[n].s[0], vec[0]); ++n)
388 ;
389 /* if it's a real user check whether the response is right */
18e6d6e6 390 if(n >= config->allow.n) {
391 info("S%x unknown user '%s' from %s", c->tag, vec[0], host);
392 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
393 return 1;
394 }
637fdea3
RK
395 res = authhash(c->nonce, sizeof c->nonce, config->allow.s[n].s[1],
396 config->authorization_algorithm);
18e6d6e6 397 if(wideopen || (res && !strcmp(res, vec[1]))) {
398 c->who = vec[0];
399 /* currently we only bother logging remote connections */
400 if(c->l->pf != PF_UNIX)
401 info("S%x %s connected from %s", c->tag, vec[0], host);
402 sink_writes(ev_writer_sink(c->w), "230 OK\n");
403 return 1;
460b9539 404 }
405 /* oops, response was wrong */
18e6d6e6 406 info("S%x authentication failure for %s from %s", c->tag, vec[0], host);
460b9539 407 sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
408 return 1;
409}
410
411static int c_recent(struct conn *c,
412 char attribute((unused)) **vec,
413 int attribute((unused)) nvec) {
414 const struct queue_entry *q;
415
416 sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
417 for(q = phead.next; q != &phead; q = q->next)
418 sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
419 sink_writes(ev_writer_sink(c->w), ".\n");
420 return 1; /* completed */
421}
422
423static int c_queue(struct conn *c,
424 char attribute((unused)) **vec,
425 int attribute((unused)) nvec) {
426 struct queue_entry *q;
427 time_t when = 0;
428 const char *l;
429 long length;
430
431 sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
432 if(playing_is_enabled() && !paused) {
433 if(playing) {
434 queue_fix_sofar(playing);
435 if((l = trackdb_get(playing->track, "_length"))
436 && (length = atol(l))) {
437 time(&when);
438 when += length - playing->sofar + config->gap;
439 }
440 } else
441 /* Nothing is playing but playing is enabled, so whatever is
442 * first in the queue can be expected to start immediately. */
443 time(&when);
444 }
445 for(q = qhead.next; q != &qhead; q = q->next) {
446 /* fill in estimated start time */
447 q->expected = when;
448 sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
449 /* update for next track */
450 if(when) {
451 if((l = trackdb_get(q->track, "_length"))
452 && (length = atol(l)))
453 when += length + config->gap;
454 else
455 when = 0;
456 }
457 }
458 sink_writes(ev_writer_sink(c->w), ".\n");
459 return 1; /* completed */
460}
461
462static int output_list(struct conn *c, char **vec) {
463 while(*vec)
464 sink_printf(ev_writer_sink(c->w), "%s\n", *vec++);
465 sink_writes(ev_writer_sink(c->w), ".\n");
466 return 1;
467}
468
469static int files_dirs(struct conn *c,
470 char **vec,
471 int nvec,
472 enum trackdb_listable what) {
473 const char *dir, *re, *errstr;
474 int erroffset;
475 pcre *rec;
476 char **fvec, *key;
477
478 switch(nvec) {
479 case 0: dir = 0; re = 0; break;
480 case 1: dir = vec[0]; re = 0; break;
481 case 2: dir = vec[0]; re = vec[1]; break;
482 default: abort();
483 }
484 /* A bit of a bodge to make sure the args don't trample on cache keys */
485 if(dir && strchr(dir, '\n')) {
486 sink_writes(ev_writer_sink(c->w), "550 invalid directory name\n");
487 return 1;
488 }
489 if(re && strchr(re, '\n')) {
490 sink_writes(ev_writer_sink(c->w), "550 invalid regexp\n");
491 return 1;
492 }
493 /* We bother eliminating "" because the web interface is relatively
494 * likely to send it */
495 if(re && *re) {
496 byte_xasprintf(&key, "%d\n%s\n%s", (int)what, dir ? dir : "", re);
497 fvec = (char **)cache_get(&cache_files_type, key);
498 if(fvec) {
499 /* Got a cache hit, don't store the answer in the cache */
500 key = 0;
501 ++cache_files_hits;
502 rec = 0; /* quieten compiler */
503 } else {
504 /* Cache miss, we'll do the lookup and key != 0 so we'll store the answer
505 * in the cache. */
506 if(!(rec = pcre_compile(re, PCRE_CASELESS|PCRE_UTF8,
507 &errstr, &erroffset, 0))) {
508 sink_printf(ev_writer_sink(c->w), "550 Error compiling regexp: %s\n",
509 errstr);
510 return 1;
511 }
512 /* It only counts as a miss if the regexp was valid. */
513 ++cache_files_misses;
514 }
515 } else {
516 /* No regexp, don't bother caching the result */
517 rec = 0;
518 key = 0;
519 fvec = 0;
520 }
521 if(!fvec) {
522 /* No cache hit (either because a miss, or because we did not look) so do
523 * the lookup */
524 if(dir && *dir)
525 fvec = trackdb_list(dir, 0, what, rec);
526 else
527 fvec = trackdb_list(0, 0, what, rec);
528 }
529 if(key)
530 /* Put the answer in the cache */
531 cache_put(&cache_files_type, key, fvec);
532 sink_writes(ev_writer_sink(c->w), "253 Listing follow\n");
533 return output_list(c, fvec);
534}
535
536static int c_files(struct conn *c,
537 char **vec,
538 int nvec) {
539 return files_dirs(c, vec, nvec, trackdb_files);
540}
541
542static int c_dirs(struct conn *c,
543 char **vec,
544 int nvec) {
545 return files_dirs(c, vec, nvec, trackdb_directories);
546}
547
548static int c_allfiles(struct conn *c,
549 char **vec,
550 int nvec) {
551 return files_dirs(c, vec, nvec, trackdb_directories|trackdb_files);
552}
553
554static int c_get(struct conn *c,
555 char **vec,
556 int attribute((unused)) nvec) {
557 const char *v;
558
559 if(vec[1][0] != '_' && (v = trackdb_get(vec[0], vec[1])))
560 sink_printf(ev_writer_sink(c->w), "252 %s\n", v);
561 else
562 sink_writes(ev_writer_sink(c->w), "550 not found\n");
563 return 1;
564}
565
566static int c_length(struct conn *c,
567 char **vec,
568 int attribute((unused)) nvec) {
569 const char *track, *v;
570
571 if(!(track = trackdb_resolve(vec[0]))) {
572 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
573 return 1;
574 }
575 if((v = trackdb_get(track, "_length")))
576 sink_printf(ev_writer_sink(c->w), "252 %s\n", v);
577 else
578 sink_writes(ev_writer_sink(c->w), "550 not found\n");
579 return 1;
580}
581
582static int c_set(struct conn *c,
583 char **vec,
584 int attribute((unused)) nvec) {
585 if(vec[1][0] != '_' && !trackdb_set(vec[0], vec[1], vec[2]))
586 sink_writes(ev_writer_sink(c->w), "250 OK\n");
587 else
588 sink_writes(ev_writer_sink(c->w), "550 not found\n");
589 return 1;
590}
591
592static int c_prefs(struct conn *c,
593 char **vec,
594 int attribute((unused)) nvec) {
595 struct kvp *k;
596
597 k = trackdb_get_all(vec[0]);
598 sink_writes(ev_writer_sink(c->w), "253 prefs follow\n");
599 for(; k; k = k->next)
600 if(k->name[0] != '_') /* omit internal values */
601 sink_printf(ev_writer_sink(c->w),
602 " %s %s\n", quoteutf8(k->name), quoteutf8(k->value));
603 sink_writes(ev_writer_sink(c->w), ".\n");
604 return 1;
605}
606
607static int c_exists(struct conn *c,
608 char **vec,
609 int attribute((unused)) nvec) {
610 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[trackdb_exists(vec[0])]);
611 return 1;
612}
613
614static void search_parse_error(const char *msg, void *u) {
615 *(const char **)u = msg;
616}
617
618static int c_search(struct conn *c,
619 char **vec,
620 int attribute((unused)) nvec) {
621 char **terms, **results;
622 int nterms, nresults, n;
623 const char *e = "unknown error";
624
625 /* This is a bit of a bodge. Initially it's there to make the eclient
626 * interface a bit more convenient to add searching to, but it has the more
627 * compelling advantage that if everything uses it, then interpretation of
628 * user-supplied search strings will be the same everywhere. */
629 if(!(terms = split(vec[0], &nterms, SPLIT_QUOTES, search_parse_error, &e))) {
630 sink_printf(ev_writer_sink(c->w), "550 %s\n", e);
631 } else {
632 results = trackdb_search(terms, nterms, &nresults);
633 sink_printf(ev_writer_sink(c->w), "253 %d matches\n", nresults);
634 for(n = 0; n < nresults; ++n)
635 sink_printf(ev_writer_sink(c->w), "%s\n", results[n]);
636 sink_writes(ev_writer_sink(c->w), ".\n");
637 }
638 return 1;
639}
640
641static int c_random_enable(struct conn *c,
642 char attribute((unused)) **vec,
643 int attribute((unused)) nvec) {
644 enable_random(c->who, c->ev);
645 /* Enable implicitly unpauses if there is nothing playing */
646 if(paused && !playing) resume_playing(c->who);
647 sink_writes(ev_writer_sink(c->w), "250 OK\n");
648 return 1; /* completed */
649}
650
651static int c_random_disable(struct conn *c,
652 char attribute((unused)) **vec,
653 int attribute((unused)) nvec) {
654 disable_random(c->who);
655 sink_writes(ev_writer_sink(c->w), "250 OK\n");
656 return 1; /* completed */
657}
658
659static int c_random_enabled(struct conn *c,
660 char attribute((unused)) **vec,
661 int attribute((unused)) nvec) {
662 sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[random_is_enabled()]);
663 return 1; /* completed */
664}
665
d6dde5a3
RK
666static void got_stats(char *stats, void *u) {
667 struct conn *const c = u;
668
669 sink_printf(ev_writer_sink(c->w), "253 stats\n%s\n.\n", stats);
670 /* Now we can start processing commands again */
671 ev_reader_enable(c->r);
672}
673
460b9539 674static int c_stats(struct conn *c,
675 char attribute((unused)) **vec,
676 int attribute((unused)) nvec) {
d6dde5a3
RK
677 trackdb_stats_subprocess(c->ev, got_stats, c);
678 return 0; /* not yet complete */
460b9539 679}
680
681static int c_volume(struct conn *c,
682 char **vec,
683 int nvec) {
684 int l, r, set;
685 char lb[32], rb[32];
686
687 switch(nvec) {
688 case 0:
689 set = 0;
690 break;
691 case 1:
692 l = r = atoi(vec[0]);
693 set = 1;
694 break;
695 case 2:
696 l = atoi(vec[0]);
697 r = atoi(vec[1]);
698 set = 1;
699 break;
700 default:
701 abort();
702 }
703 if(mixer_control(&l, &r, set))
704 sink_writes(ev_writer_sink(c->w), "550 error accessing mixer\n");
705 else {
706 sink_printf(ev_writer_sink(c->w), "252 %d %d\n", l, r);
707 if(l != volume_left || r != volume_right) {
708 volume_left = l;
709 volume_right = r;
710 snprintf(lb, sizeof lb, "%d", l);
711 snprintf(rb, sizeof rb, "%d", r);
712 eventlog("volume", lb, rb, (char *)0);
713 }
714 }
715 return 1;
716}
717
718/* we are logging, and some data is available to read */
719static int logging_reader_callback(ev_source *ev,
720 ev_reader *reader,
460b9539 721 void *ptr,
722 size_t bytes,
723 int eof,
724 void *u) {
725 struct conn *c = u;
726
727 /* don't log to this conn any more */
728 eventlog_remove(c->lo);
f6033c46
RK
729 if(c->w) {
730 /* Terminate the log output, but only if the writer hasn't been killed off
731 * from a failure on some earlier write */
732 sink_writes(ev_writer_sink(c->w), ".\n");
733 }
460b9539 734 /* restore the reader callback */
735 c->reader = reader_callback;
736 /* ...and exit via it */
75d64210 737 return c->reader(ev, reader, ptr, bytes, eof, u);
460b9539 738}
739
740static void logclient(const char *msg, void *user) {
741 struct conn *c = user;
742
f6033c46
RK
743 if(!c->w || !c->r) {
744 /* This connection has gone up in smoke for some reason */
745 eventlog_remove(c->lo);
746 return;
747 }
460b9539 748 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" %s\n",
749 (uintmax_t)time(0), msg);
750}
751
752static int c_log(struct conn *c,
753 char attribute((unused)) **vec,
754 int attribute((unused)) nvec) {
755 time_t now;
756
757 sink_writes(ev_writer_sink(c->w), "254 OK\n");
758 /* pump out initial state */
759 time(&now);
760 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
761 (uintmax_t)now,
762 playing_is_enabled() ? "enable_play" : "disable_play");
763 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
764 (uintmax_t)now,
765 random_is_enabled() ? "enable_random" : "disable_random");
766 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
767 (uintmax_t)now,
768 paused ? "pause" : "resume");
5abe307a
RK
769 if(playing)
770 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state playing\n",
771 (uintmax_t)now);
df44d69b
RK
772 /* Initial volume */
773 sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" volume %d %d\n",
774 (uintmax_t)now, volume_left, volume_right);
460b9539 775 c->lo = xmalloc(sizeof *c->lo);
776 c->lo->fn = logclient;
777 c->lo->user = c;
778 eventlog_add(c->lo);
779 c->reader = logging_reader_callback;
780 return 0;
781}
782
783static void post_move_cleanup(void) {
784 struct queue_entry *q;
785
138baa2d
RK
786 /* If we have caused any random tracks to not be at the end then we make them
787 * no longer be random. */
460b9539 788 for(q = qhead.next; q != &qhead; q = q->next)
789 if(q->state == playing_random && q->next != &qhead)
790 q->state = playing_unplayed;
791 /* That might mean we need to add a new random track. */
792 add_random_track();
793 queue_write();
794}
795
796static int c_move(struct conn *c,
797 char **vec,
798 int attribute((unused)) nvec) {
799 struct queue_entry *q;
800 int n;
801
802 if(config->restrictions & RESTRICT_MOVE) {
803 if(!trusted(c)) {
804 sink_writes(ev_writer_sink(c->w),
805 "550 only trusted users can move tracks\n");
806 return 1;
807 }
808 }
809 if(!(q = queue_find(vec[0]))) {
810 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
811 return 1;
812 }
813 n = queue_move(q, atoi(vec[1]), c->who);
814 post_move_cleanup();
815 sink_printf(ev_writer_sink(c->w), "252 %d\n", n);
816 /* If we've moved to the head of the queue then prepare the track. */
817 if(q == qhead.next)
818 prepare(c->ev, q);
819 return 1;
820}
821
822static int c_moveafter(struct conn *c,
823 char **vec,
824 int attribute((unused)) nvec) {
825 struct queue_entry *q, **qs;
826 int n;
827
828 if(config->restrictions & RESTRICT_MOVE) {
829 if(!trusted(c)) {
830 sink_writes(ev_writer_sink(c->w),
831 "550 only trusted users can move tracks\n");
832 return 1;
833 }
834 }
835 if(vec[0][0]) {
836 if(!(q = queue_find(vec[0]))) {
837 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
838 return 1;
839 }
840 } else
841 q = 0;
842 ++vec;
843 --nvec;
844 qs = xcalloc(nvec, sizeof *qs);
845 for(n = 0; n < nvec; ++n)
846 if(!(qs[n] = queue_find(vec[n]))) {
847 sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
848 return 1;
849 }
850 queue_moveafter(q, nvec, qs, c->who);
851 post_move_cleanup();
852 sink_printf(ev_writer_sink(c->w), "250 Moved tracks\n");
853 /* If we've moved to the head of the queue then prepare the track. */
854 if(q == qhead.next)
855 prepare(c->ev, q);
856 return 1;
857}
858
859static int c_part(struct conn *c,
860 char **vec,
861 int attribute((unused)) nvec) {
862 sink_printf(ev_writer_sink(c->w), "252 %s\n",
863 trackdb_getpart(vec[0], vec[1], vec[2]));
864 return 1;
865}
866
867static int c_resolve(struct conn *c,
868 char **vec,
869 int attribute((unused)) nvec) {
870 const char *track;
871
872 if(!(track = trackdb_resolve(vec[0]))) {
873 sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
874 return 1;
875 }
876 sink_printf(ev_writer_sink(c->w), "252 %s\n", track);
877 return 1;
878}
879
880static int c_tags(struct conn *c,
881 char attribute((unused)) **vec,
882 int attribute((unused)) nvec) {
883 char **tags = trackdb_alltags();
884
885 sink_printf(ev_writer_sink(c->w), "253 Tag list follows\n");
886 while(*tags) {
887 sink_printf(ev_writer_sink(c->w), "%s%s\n",
888 **tags == '.' ? "." : "", *tags);
889 ++tags;
890 }
891 sink_writes(ev_writer_sink(c->w), ".\n");
892 return 1; /* completed */
893
894}
895
896static int c_set_global(struct conn *c,
897 char **vec,
898 int attribute((unused)) nvec) {
899 trackdb_set_global(vec[0], vec[1], c->who);
900 sink_printf(ev_writer_sink(c->w), "250 OK\n");
901 return 1;
902}
903
904static int c_get_global(struct conn *c,
905 char **vec,
906 int attribute((unused)) nvec) {
907 const char *s = trackdb_get_global(vec[0]);
908
909 if(s)
910 sink_printf(ev_writer_sink(c->w), "252 %s\n", s);
911 else
912 sink_writes(ev_writer_sink(c->w), "550 not found\n");
913 return 1;
914}
915
7858930d 916static int c_nop(struct conn *c,
917 char attribute((unused)) **vec,
918 int attribute((unused)) nvec) {
919 sink_printf(ev_writer_sink(c->w), "250 Quack\n");
920 return 1;
921}
922
2a10b70b
RK
923static int c_new(struct conn *c,
924 char **vec,
925 int nvec) {
926 char **tracks = trackdb_new(0, nvec > 0 ? atoi(vec[0]) : INT_MAX);
927
928 sink_printf(ev_writer_sink(c->w), "253 New track list follows\n");
929 while(*tracks) {
930 sink_printf(ev_writer_sink(c->w), "%s%s\n",
931 **tracks == '.' ? "." : "", *tracks);
932 ++tracks;
933 }
934 sink_writes(ev_writer_sink(c->w), ".\n");
935 return 1; /* completed */
936
937}
938
ca831831
RK
939static int c_rtp_address(struct conn *c,
940 char attribute((unused)) **vec,
941 int attribute((unused)) nvec) {
942 if(config->speaker_backend == BACKEND_NETWORK) {
943 sink_printf(ev_writer_sink(c->w), "252 %s %s\n",
944 quoteutf8(config->broadcast.s[0]),
945 quoteutf8(config->broadcast.s[1]));
946 } else
947 sink_writes(ev_writer_sink(c->w), "550 No RTP\n");
948 return 1;
949}
950
460b9539 951#define C_AUTH 0001 /* must be authenticated */
952#define C_TRUSTED 0002 /* must be trusted user */
953
954static const struct command {
955 const char *name;
956 int minargs, maxargs;
957 int (*fn)(struct conn *, char **, int);
958 unsigned flags;
959} commands[] = {
960 { "allfiles", 0, 2, c_allfiles, C_AUTH },
961 { "become", 1, 1, c_become, C_AUTH|C_TRUSTED },
962 { "dirs", 0, 2, c_dirs, C_AUTH },
963 { "disable", 0, 1, c_disable, C_AUTH },
964 { "enable", 0, 0, c_enable, C_AUTH },
965 { "enabled", 0, 0, c_enabled, C_AUTH },
966 { "exists", 1, 1, c_exists, C_AUTH },
967 { "files", 0, 2, c_files, C_AUTH },
968 { "get", 2, 2, c_get, C_AUTH },
969 { "get-global", 1, 1, c_get_global, C_AUTH },
970 { "length", 1, 1, c_length, C_AUTH },
971 { "log", 0, 0, c_log, C_AUTH },
972 { "move", 2, 2, c_move, C_AUTH },
973 { "moveafter", 1, INT_MAX, c_moveafter, C_AUTH },
2a10b70b 974 { "new", 0, 1, c_new, C_AUTH },
7858930d 975 { "nop", 0, 0, c_nop, C_AUTH },
460b9539 976 { "part", 3, 3, c_part, C_AUTH },
977 { "pause", 0, 0, c_pause, C_AUTH },
978 { "play", 1, 1, c_play, C_AUTH },
979 { "playing", 0, 0, c_playing, C_AUTH },
980 { "prefs", 1, 1, c_prefs, C_AUTH },
981 { "queue", 0, 0, c_queue, C_AUTH },
982 { "random-disable", 0, 0, c_random_disable, C_AUTH },
983 { "random-enable", 0, 0, c_random_enable, C_AUTH },
984 { "random-enabled", 0, 0, c_random_enabled, C_AUTH },
985 { "recent", 0, 0, c_recent, C_AUTH },
986 { "reconfigure", 0, 0, c_reconfigure, C_AUTH|C_TRUSTED },
987 { "remove", 1, 1, c_remove, C_AUTH },
988 { "rescan", 0, 0, c_rescan, C_AUTH|C_TRUSTED },
989 { "resolve", 1, 1, c_resolve, C_AUTH },
990 { "resume", 0, 0, c_resume, C_AUTH },
ca831831 991 { "rtp-address", 0, 0, c_rtp_address, C_AUTH },
460b9539 992 { "scratch", 0, 1, c_scratch, C_AUTH },
993 { "search", 1, 1, c_search, C_AUTH },
994 { "set", 3, 3, c_set, C_AUTH, },
995 { "set-global", 2, 2, c_set_global, C_AUTH },
996 { "shutdown", 0, 0, c_shutdown, C_AUTH|C_TRUSTED },
997 { "stats", 0, 0, c_stats, C_AUTH },
998 { "tags", 0, 0, c_tags, C_AUTH },
999 { "unset", 2, 2, c_set, C_AUTH },
1000 { "unset-global", 1, 1, c_set_global, C_AUTH },
1001 { "user", 2, 2, c_user, 0 },
1002 { "version", 0, 0, c_version, C_AUTH },
1003 { "volume", 0, 2, c_volume, C_AUTH }
1004};
1005
1006static void command_error(const char *msg, void *u) {
1007 struct conn *c = u;
1008
1009 sink_printf(ev_writer_sink(c->w), "500 parse error: %s\n", msg);
1010}
1011
1012/* process a command. Return 1 if complete, 0 if incomplete. */
1013static int command(struct conn *c, char *line) {
1014 char **vec;
1015 int nvec, n;
1016
1017 D(("server command %s", line));
1018 if(!(vec = split(line, &nvec, SPLIT_QUOTES, command_error, c))) {
1019 sink_writes(ev_writer_sink(c->w), "500 cannot parse command\n");
1020 return 1;
1021 }
1022 if(nvec == 0) {
1023 sink_writes(ev_writer_sink(c->w), "500 do what?\n");
1024 return 1;
1025 }
1026 if((n = TABLE_FIND(commands, struct command, name, vec[0])) < 0)
1027 sink_writes(ev_writer_sink(c->w), "500 unknown command\n");
1028 else {
1029 if((commands[n].flags & C_AUTH) && !c->who) {
1030 sink_writes(ev_writer_sink(c->w), "530 not authenticated\n");
1031 return 1;
1032 }
1033 if((commands[n].flags & C_TRUSTED) && !trusted(c)) {
1034 sink_writes(ev_writer_sink(c->w), "530 insufficient privilege\n");
1035 return 1;
1036 }
1037 ++vec;
1038 --nvec;
1039 if(nvec < commands[n].minargs) {
1040 sink_writes(ev_writer_sink(c->w), "500 missing argument(s)\n");
1041 return 1;
1042 }
1043 if(nvec > commands[n].maxargs) {
1044 sink_writes(ev_writer_sink(c->w), "500 too many arguments\n");
1045 return 1;
1046 }
1047 return commands[n].fn(c, vec, nvec);
1048 }
1049 return 1; /* completed */
1050}
1051
1052/* redirect to the right reader callback for our current state */
1053static int redirect_reader_callback(ev_source *ev,
1054 ev_reader *reader,
460b9539 1055 void *ptr,
1056 size_t bytes,
1057 int eof,
1058 void *u) {
1059 struct conn *c = u;
1060
75d64210 1061 return c->reader(ev, reader, ptr, bytes, eof, u);
460b9539 1062}
1063
1064/* the main command reader */
1065static int reader_callback(ev_source attribute((unused)) *ev,
1066 ev_reader *reader,
460b9539 1067 void *ptr,
1068 size_t bytes,
1069 int eof,
1070 void *u) {
1071 struct conn *c = u;
1072 char *eol;
1073 int complete;
1074
1075 D(("server reader_callback"));
1076 while((eol = memchr(ptr, '\n', bytes))) {
1077 *eol++ = 0;
1078 ev_reader_consume(reader, eol - (char *)ptr);
1079 complete = command(c, ptr);
1080 bytes -= (eol - (char *)ptr);
1081 ptr = eol;
1082 if(!complete) {
1083 /* the command had better have set a new reader callback */
1084 if(bytes || eof)
1085 /* there are further bytes to read, or we are at eof; arrange for the
1086 * command's reader callback to handle them */
1087 return ev_reader_incomplete(reader);
1088 /* nothing's going on right now */
1089 return 0;
1090 }
1091 /* command completed, we can go around and handle the next one */
1092 }
1093 if(eof) {
1094 if(bytes)
1095 error(0, "S%x unterminated line", c->tag);
460b9539 1096 return ev_writer_close(c->w);
1097 }
1098 return 0;
1099}
1100
1101static int listen_callback(ev_source *ev,
1102 int fd,
1103 const struct sockaddr attribute((unused)) *remote,
1104 socklen_t attribute((unused)) rlen,
1105 void *u) {
1106 const struct listener *l = u;
1107 struct conn *c = xmalloc(sizeof *c);
1108 static unsigned tags;
1109
1110 D(("server listen_callback fd %d (%s)", fd, l->name));
1111 nonblock(fd);
1112 cloexec(fd);
1113 c->tag = tags++;
1114 c->ev = ev;
e8c92ba7
RK
1115 c->w = ev_writer_new(ev, fd, writer_error, c,
1116 "client writer");
1117 c->r = ev_reader_new(ev, fd, redirect_reader_callback, reader_error, c,
1118 "client reader");
75d64210 1119 ev_tie(c->r, c->w);
460b9539 1120 c->fd = fd;
1121 c->reader = reader_callback;
1122 c->l = l;
1123 gcry_randomize(c->nonce, sizeof c->nonce, GCRY_STRONG_RANDOM);
637fdea3
RK
1124 if(!strcmp(config->authorization_algorithm, "sha1")
1125 || !strcmp(config->authorization_algorithm, "SHA1")) {
1126 sink_printf(ev_writer_sink(c->w), "231 %s\n",
1127 hex(c->nonce, sizeof c->nonce));
1128 } else {
1129 sink_printf(ev_writer_sink(c->w), "231 %s %s\n",
1130 config->authorization_algorithm,
1131 hex(c->nonce, sizeof c->nonce));
1132 }
460b9539 1133 return 0;
1134}
1135
1136int server_start(ev_source *ev, int pf,
1137 size_t socklen, const struct sockaddr *sa,
1138 const char *name) {
1139 int fd;
1140 struct listener *l = xmalloc(sizeof *l);
1141 static const int one = 1;
1142
1143 D(("server_init socket %s", name));
1144 fd = xsocket(pf, SOCK_STREAM, 0);
1145 xsetsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
1146 if(bind(fd, sa, socklen) < 0) {
1147 error(errno, "error binding to %s", name);
1148 return -1;
1149 }
1150 xlisten(fd, 128);
1151 nonblock(fd);
1152 cloexec(fd);
1153 l->name = name;
1154 l->pf = pf;
e8c92ba7
RK
1155 if(ev_listen(ev, fd, listen_callback, l, "server listener"))
1156 exit(EXIT_FAILURE);
460b9539 1157 return fd;
1158}
1159
1160int server_stop(ev_source *ev, int fd) {
1161 xclose(fd);
1162 return ev_listen_cancel(ev, fd);
1163}
1164
1165/*
1166Local Variables:
1167c-basic-offset:2
1168comment-column:40
1169fill-column:79
1170End:
1171*/