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