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