chiark / gitweb /
server side support for cookies, basic tests
[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   int n;
407   const char *res, *host;
408
409   if(c->who) {
410     sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
411     return 1;
412   }
413   /* get connection data */
414   if(!(host = connection_host(c))) {
415     sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
416     return 1;
417   }
418   /* find the user */
419   for(n = 0; n < config->allow.n
420         && strcmp(config->allow.s[n].s[0], vec[0]); ++n)
421     ;
422   /* if it's a real user check whether the response is right */
423   if(n >= config->allow.n) {
424     info("S%x unknown user '%s' from %s", c->tag, vec[0], host);
425     sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
426     return 1;
427   }
428   res = authhash(c->nonce, sizeof c->nonce, config->allow.s[n].s[1],
429                  config->authorization_algorithm);
430   if(wideopen || (res && !strcmp(res, vec[1]))) {
431     c->who = vec[0];
432     /* currently we only bother logging remote connections */
433     if(strcmp(host, "local"))
434       info("S%x %s connected from %s", c->tag, vec[0], host);
435     sink_writes(ev_writer_sink(c->w), "230 OK\n");
436     return 1;
437   }
438   /* oops, response was wrong */
439   info("S%x authentication failure for %s from %s", c->tag, vec[0], host);
440   sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
441   return 1;
442 }
443
444 static int c_recent(struct conn *c,
445                     char attribute((unused)) **vec,
446                     int attribute((unused)) nvec) {
447   const struct queue_entry *q;
448
449   sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
450   for(q = phead.next; q != &phead; q = q->next)
451     sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
452   sink_writes(ev_writer_sink(c->w), ".\n");
453   return 1;                             /* completed */
454 }
455
456 static int c_queue(struct conn *c,
457                    char attribute((unused)) **vec,
458                    int attribute((unused)) nvec) {
459   struct queue_entry *q;
460   time_t when = 0;
461   const char *l;
462   long length;
463
464   sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
465   if(playing_is_enabled() && !paused) {
466     if(playing) {
467       queue_fix_sofar(playing);
468       if((l = trackdb_get(playing->track, "_length"))
469          && (length = atol(l))) {
470         time(&when);
471         when += length - playing->sofar + config->gap;
472       }
473     } else
474       /* Nothing is playing but playing is enabled, so whatever is
475        * first in the queue can be expected to start immediately. */
476       time(&when);
477   }
478   for(q = qhead.next; q != &qhead; q = q->next) {
479     /* fill in estimated start time */
480     q->expected = when;
481     sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
482     /* update for next track */
483     if(when) {
484       if((l = trackdb_get(q->track, "_length"))
485          && (length = atol(l)))
486         when += length + config->gap;
487       else
488         when = 0;
489     }
490   }
491   sink_writes(ev_writer_sink(c->w), ".\n");
492   return 1;                             /* completed */
493 }
494
495 static int output_list(struct conn *c, char **vec) {
496   while(*vec)
497     sink_printf(ev_writer_sink(c->w), "%s\n", *vec++);
498   sink_writes(ev_writer_sink(c->w), ".\n");
499   return 1;
500 }
501
502 static int files_dirs(struct conn *c,
503                       char **vec,
504                       int nvec,
505                       enum trackdb_listable what) {
506   const char *dir, *re, *errstr;
507   int erroffset;
508   pcre *rec;
509   char **fvec, *key;
510   
511   switch(nvec) {
512   case 0: dir = 0; re = 0; break;
513   case 1: dir = vec[0]; re = 0; break;
514   case 2: dir = vec[0]; re = vec[1]; break;
515   default: abort();
516   }
517   /* A bit of a bodge to make sure the args don't trample on cache keys */
518   if(dir && strchr(dir, '\n')) {
519     sink_writes(ev_writer_sink(c->w), "550 invalid directory name\n");
520     return 1;
521   }
522   if(re && strchr(re, '\n')) {
523     sink_writes(ev_writer_sink(c->w), "550 invalid regexp\n");
524     return 1;
525   }
526   /* We bother eliminating "" because the web interface is relatively
527    * likely to send it */
528   if(re && *re) {
529     byte_xasprintf(&key, "%d\n%s\n%s", (int)what, dir ? dir : "", re);
530     fvec = (char **)cache_get(&cache_files_type, key);
531     if(fvec) {
532       /* Got a cache hit, don't store the answer in the cache */
533       key = 0;
534       ++cache_files_hits;
535       rec = 0;                          /* quieten compiler */
536     } else {
537       /* Cache miss, we'll do the lookup and key != 0 so we'll store the answer
538        * in the cache. */
539       if(!(rec = pcre_compile(re, PCRE_CASELESS|PCRE_UTF8,
540                               &errstr, &erroffset, 0))) {
541         sink_printf(ev_writer_sink(c->w), "550 Error compiling regexp: %s\n",
542                     errstr);
543         return 1;
544       }
545       /* It only counts as a miss if the regexp was valid. */
546       ++cache_files_misses;
547     }
548   } else {
549     /* No regexp, don't bother caching the result */
550     rec = 0;
551     key = 0;
552     fvec = 0;
553   }
554   if(!fvec) {
555     /* No cache hit (either because a miss, or because we did not look) so do
556      * the lookup */
557     if(dir && *dir)
558       fvec = trackdb_list(dir, 0, what, rec);
559     else
560       fvec = trackdb_list(0, 0, what, rec);
561   }
562   if(key)
563     /* Put the answer in the cache */
564     cache_put(&cache_files_type, key, fvec);
565   sink_writes(ev_writer_sink(c->w), "253 Listing follow\n");
566   return output_list(c, fvec);
567 }
568
569 static int c_files(struct conn *c,
570                   char **vec,
571                   int nvec) {
572   return files_dirs(c, vec, nvec, trackdb_files);
573 }
574
575 static int c_dirs(struct conn *c,
576                   char **vec,
577                   int nvec) {
578   return files_dirs(c, vec, nvec, trackdb_directories);
579 }
580
581 static int c_allfiles(struct conn *c,
582                       char **vec,
583                       int nvec) {
584   return files_dirs(c, vec, nvec, trackdb_directories|trackdb_files);
585 }
586
587 static int c_get(struct conn *c,
588                  char **vec,
589                  int attribute((unused)) nvec) {
590   const char *v;
591
592   if(vec[1][0] != '_' && (v = trackdb_get(vec[0], vec[1])))
593     sink_printf(ev_writer_sink(c->w), "252 %s\n", v);
594   else
595     sink_writes(ev_writer_sink(c->w), "555 not found\n");
596   return 1;
597 }
598
599 static int c_length(struct conn *c,
600                  char **vec,
601                  int attribute((unused)) nvec) {
602   const char *track, *v;
603
604   if(!(track = trackdb_resolve(vec[0]))) {
605     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
606     return 1;
607   }
608   if((v = trackdb_get(track, "_length")))
609     sink_printf(ev_writer_sink(c->w), "252 %s\n", v);
610   else
611     sink_writes(ev_writer_sink(c->w), "550 not found\n");
612   return 1;
613 }
614
615 static int c_set(struct conn *c,
616                  char **vec,
617                  int attribute((unused)) nvec) {
618   if(vec[1][0] != '_' && !trackdb_set(vec[0], vec[1], vec[2]))
619     sink_writes(ev_writer_sink(c->w), "250 OK\n");
620   else
621     sink_writes(ev_writer_sink(c->w), "550 not found\n");
622   return 1;
623 }
624
625 static int c_prefs(struct conn *c,
626                    char **vec,
627                    int attribute((unused)) nvec) {
628   struct kvp *k;
629
630   k = trackdb_get_all(vec[0]);
631   sink_writes(ev_writer_sink(c->w), "253 prefs follow\n");
632   for(; k; k = k->next)
633     if(k->name[0] != '_')               /* omit internal values */
634       sink_printf(ev_writer_sink(c->w),
635                   " %s %s\n", quoteutf8(k->name), quoteutf8(k->value));
636   sink_writes(ev_writer_sink(c->w), ".\n");
637   return 1;
638 }
639
640 static int c_exists(struct conn *c,
641                     char **vec,
642                     int attribute((unused)) nvec) {
643   sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[trackdb_exists(vec[0])]);
644   return 1;
645 }
646
647 static void search_parse_error(const char *msg, void *u) {
648   *(const char **)u = msg;
649 }
650
651 static int c_search(struct conn *c,
652                           char **vec,
653                           int attribute((unused)) nvec) {
654   char **terms, **results;
655   int nterms, nresults, n;
656   const char *e = "unknown error";
657
658   /* This is a bit of a bodge.  Initially it's there to make the eclient
659    * interface a bit more convenient to add searching to, but it has the more
660    * compelling advantage that if everything uses it, then interpretation of
661    * user-supplied search strings will be the same everywhere. */
662   if(!(terms = split(vec[0], &nterms, SPLIT_QUOTES, search_parse_error, &e))) {
663     sink_printf(ev_writer_sink(c->w), "550 %s\n", e);
664   } else {
665     results = trackdb_search(terms, nterms, &nresults);
666     sink_printf(ev_writer_sink(c->w), "253 %d matches\n", nresults);
667     for(n = 0; n < nresults; ++n)
668       sink_printf(ev_writer_sink(c->w), "%s\n", results[n]);
669     sink_writes(ev_writer_sink(c->w), ".\n");
670   }
671   return 1;
672 }
673
674 static int c_random_enable(struct conn *c,
675                            char attribute((unused)) **vec,
676                            int attribute((unused)) nvec) {
677   enable_random(c->who, c->ev);
678   /* Enable implicitly unpauses if there is nothing playing */
679   if(paused && !playing) resume_playing(c->who);
680   sink_writes(ev_writer_sink(c->w), "250 OK\n");
681   return 1;                     /* completed */
682 }
683
684 static int c_random_disable(struct conn *c,
685                             char attribute((unused)) **vec,
686                             int attribute((unused)) nvec) {
687   disable_random(c->who);
688   sink_writes(ev_writer_sink(c->w), "250 OK\n");
689   return 1;                     /* completed */
690 }
691
692 static int c_random_enabled(struct conn *c,
693                             char attribute((unused)) **vec,
694                             int attribute((unused)) nvec) {
695   sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[random_is_enabled()]);
696   return 1;                     /* completed */
697 }
698
699 static void got_stats(char *stats, void *u) {
700   struct conn *const c = u;
701
702   sink_printf(ev_writer_sink(c->w), "253 stats\n%s\n.\n", stats);
703   /* Now we can start processing commands again */
704   ev_reader_enable(c->r);
705 }
706
707 static int c_stats(struct conn *c,
708                    char attribute((unused)) **vec,
709                    int attribute((unused)) nvec) {
710   trackdb_stats_subprocess(c->ev, got_stats, c);
711   return 0;                             /* not yet complete */
712 }
713
714 static int c_volume(struct conn *c,
715                     char **vec,
716                     int nvec) {
717   int l, r, set;
718   char lb[32], rb[32];
719
720   switch(nvec) {
721   case 0:
722     set = 0;
723     break;
724   case 1:
725     l = r = atoi(vec[0]);
726     set = 1;
727     break;
728   case 2:
729     l = atoi(vec[0]);
730     r = atoi(vec[1]);
731     set = 1;
732     break;
733   default:
734     abort();
735   }
736   if(mixer_control(&l, &r, set))
737     sink_writes(ev_writer_sink(c->w), "550 error accessing mixer\n");
738   else {
739     sink_printf(ev_writer_sink(c->w), "252 %d %d\n", l, r);
740     if(l != volume_left || r != volume_right) {
741       volume_left = l;
742       volume_right = r;
743       snprintf(lb, sizeof lb, "%d", l);
744       snprintf(rb, sizeof rb, "%d", r);
745       eventlog("volume", lb, rb, (char *)0);
746     }
747   }
748   return 1;
749 }
750
751 /** @brief Called when data arrives on a log connection
752  *
753  * We just discard all such data.  The client may occasionally send data as a
754  * keepalive.
755  */
756 static int logging_reader_callback(ev_source attribute((unused)) *ev,
757                                    ev_reader *reader,
758                                    void attribute((unused)) *ptr,
759                                    size_t bytes,
760                                    int attribute((unused)) eof,
761                                    void attribute((unused)) *u) {
762   struct conn *c = u;
763
764   ev_reader_consume(reader, bytes);
765   if(eof) {
766     /* Oops, that's all for now */
767     D(("logging reader eof"));
768     if(c->w) {
769       D(("close writer"));
770       ev_writer_close(c->w);
771       c->w = 0;
772     }
773     c->r = 0;
774   }
775   return 0;
776 }
777
778 static void logclient(const char *msg, void *user) {
779   struct conn *c = user;
780
781   if(!c->w || !c->r) {
782     /* This connection has gone up in smoke for some reason */
783     eventlog_remove(c->lo);
784     return;
785   }
786   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" %s\n",
787               (uintmax_t)time(0), msg);
788 }
789
790 static int c_log(struct conn *c,
791                  char attribute((unused)) **vec,
792                  int attribute((unused)) nvec) {
793   time_t now;
794
795   sink_writes(ev_writer_sink(c->w), "254 OK\n");
796   /* pump out initial state */
797   time(&now);
798   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
799               (uintmax_t)now, 
800               playing_is_enabled() ? "enable_play" : "disable_play");
801   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
802               (uintmax_t)now, 
803               random_is_enabled() ? "enable_random" : "disable_random");
804   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
805               (uintmax_t)now, 
806               paused ? "pause" : "resume");
807   if(playing)
808     sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state playing\n",
809                 (uintmax_t)now);
810   /* Initial volume */
811   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" volume %d %d\n",
812               (uintmax_t)now, volume_left, volume_right);
813   c->lo = xmalloc(sizeof *c->lo);
814   c->lo->fn = logclient;
815   c->lo->user = c;
816   eventlog_add(c->lo);
817   c->reader = logging_reader_callback;
818   return 0;
819 }
820
821 static int c_move(struct conn *c,
822                   char **vec,
823                   int attribute((unused)) nvec) {
824   struct queue_entry *q;
825   int n;
826
827   if(config->restrictions & RESTRICT_MOVE) {
828     if(!trusted(c)) {
829       sink_writes(ev_writer_sink(c->w),
830                   "550 only trusted users can move tracks\n");
831       return 1;
832     }
833   }
834   if(!(q = queue_find(vec[0]))) {
835     sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
836     return 1;
837   }
838   n = queue_move(q, atoi(vec[1]), c->who);
839   sink_printf(ev_writer_sink(c->w), "252 %d\n", n);
840   /* If we've moved to the head of the queue then prepare the track. */
841   if(q == qhead.next)
842     prepare(c->ev, q);
843   return 1;
844 }
845
846 static int c_moveafter(struct conn *c,
847                        char **vec,
848                        int attribute((unused)) nvec) {
849   struct queue_entry *q, **qs;
850   int n;
851
852   if(config->restrictions & RESTRICT_MOVE) {
853     if(!trusted(c)) {
854       sink_writes(ev_writer_sink(c->w),
855                   "550 only trusted users can move tracks\n");
856       return 1;
857     }
858   }
859   if(vec[0][0]) {
860     if(!(q = queue_find(vec[0]))) {
861       sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
862       return 1;
863     }
864   } else
865     q = 0;
866   ++vec;
867   --nvec;
868   qs = xcalloc(nvec, sizeof *qs);
869   for(n = 0; n < nvec; ++n)
870     if(!(qs[n] = queue_find(vec[n]))) {
871       sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
872       return 1;
873     }
874   queue_moveafter(q, nvec, qs, c->who);
875   sink_printf(ev_writer_sink(c->w), "250 Moved tracks\n");
876   /* If we've moved to the head of the queue then prepare the track. */
877   if(q == qhead.next)
878     prepare(c->ev, q);
879   return 1;
880 }
881
882 static int c_part(struct conn *c,
883                   char **vec,
884                   int attribute((unused)) nvec) {
885   sink_printf(ev_writer_sink(c->w), "252 %s\n",
886               trackdb_getpart(vec[0], vec[1], vec[2]));
887   return 1;
888 }
889
890 static int c_resolve(struct conn *c,
891                      char **vec,
892                      int attribute((unused)) nvec) {
893   const char *track;
894
895   if(!(track = trackdb_resolve(vec[0]))) {
896     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
897     return 1;
898   }
899   sink_printf(ev_writer_sink(c->w), "252 %s\n", track);
900   return 1;
901 }
902
903 static int c_tags(struct conn *c,
904                   char attribute((unused)) **vec,
905                   int attribute((unused)) nvec) {
906   char **tags = trackdb_alltags();
907   
908   sink_printf(ev_writer_sink(c->w), "253 Tag list follows\n");
909   while(*tags) {
910     sink_printf(ev_writer_sink(c->w), "%s%s\n",
911                 **tags == '.' ? "." : "", *tags);
912     ++tags;
913   }
914   sink_writes(ev_writer_sink(c->w), ".\n");
915   return 1;                             /* completed */
916
917 }
918
919 static int c_set_global(struct conn *c,
920                         char **vec,
921                         int attribute((unused)) nvec) {
922   if(vec[0][0] == '_') {
923     sink_writes(ev_writer_sink(c->w), "550 cannot set internal global preferences\n");
924     return 1;
925   }
926   trackdb_set_global(vec[0], vec[1], c->who);
927   sink_printf(ev_writer_sink(c->w), "250 OK\n");
928   return 1;
929 }
930
931 static int c_get_global(struct conn *c,
932                         char **vec,
933                         int attribute((unused)) nvec) {
934   const char *s = trackdb_get_global(vec[0]);
935
936   if(s)
937     sink_printf(ev_writer_sink(c->w), "252 %s\n", s);
938   else
939     sink_writes(ev_writer_sink(c->w), "555 not found\n");
940   return 1;
941 }
942
943 static int c_nop(struct conn *c,
944                  char attribute((unused)) **vec,
945                  int attribute((unused)) nvec) {
946   sink_printf(ev_writer_sink(c->w), "250 Quack\n");
947   return 1;
948 }
949
950 static int c_new(struct conn *c,
951                  char **vec,
952                  int nvec) {
953   char **tracks = trackdb_new(0, nvec > 0 ? atoi(vec[0]) : INT_MAX);
954
955   sink_printf(ev_writer_sink(c->w), "253 New track list follows\n");
956   while(*tracks) {
957     sink_printf(ev_writer_sink(c->w), "%s%s\n",
958                 **tracks == '.' ? "." : "", *tracks);
959     ++tracks;
960   }
961   sink_writes(ev_writer_sink(c->w), ".\n");
962   return 1;                             /* completed */
963
964 }
965
966 static int c_rtp_address(struct conn *c,
967                          char attribute((unused)) **vec,
968                          int attribute((unused)) nvec) {
969   if(config->speaker_backend == BACKEND_NETWORK) {
970     sink_printf(ev_writer_sink(c->w), "252 %s %s\n",
971                 quoteutf8(config->broadcast.s[0]),
972                 quoteutf8(config->broadcast.s[1]));
973   } else
974     sink_writes(ev_writer_sink(c->w), "550 No RTP\n");
975   return 1;
976 }
977
978 static int c_cookie(struct conn *c,
979                     char **vec,
980                     int attribute((unused)) nvec) {
981   const char *host;
982   char *user;
983
984   /* Can't log in twice on the same connection */
985   if(c->who) {
986     sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
987     return 1;
988   }
989   /* Get some kind of peer identifcation */
990   if(!(host = connection_host(c))) {
991     sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
992     return 1;
993   }
994   /* Check the cookie */
995   user = verify_cookie(vec[0]);
996   if(!user) {
997     sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
998     return 1;
999   }
1000   /* Log in */
1001   c->who = user;
1002   c->cookie = vec[0];
1003   if(strcmp(host, "local"))
1004     info("S%x %s connected with cookie from %s", c->tag, user, host);
1005   sink_writes(ev_writer_sink(c->w), "230 OK\n");
1006   return 1;
1007 }
1008
1009 static int c_make_cookie(struct conn *c,
1010                          char attribute((unused)) **vec,
1011                          int attribute((unused)) nvec) {
1012   const char *cookie = make_cookie(c->who);
1013
1014   if(cookie)
1015     sink_printf(ev_writer_sink(c->w), "252 %s\n", cookie);
1016   else
1017     sink_writes(ev_writer_sink(c->w), "550 Cannot create cookie\n");
1018   return 1;
1019 }
1020
1021 static int c_revoke(struct conn *c,
1022                     char attribute((unused)) **vec,
1023                     int attribute((unused)) nvec) {
1024   if(c->cookie) {
1025     revoke_cookie(c->cookie);
1026     sink_writes(ev_writer_sink(c->w), "250 OK\n");
1027   } else
1028     sink_writes(ev_writer_sink(c->w), "550 Did not log in with cookie\n");
1029   return 1;
1030 }
1031
1032 #define C_AUTH          0001            /* must be authenticated */
1033 #define C_TRUSTED       0002            /* must be trusted user */
1034
1035 static const struct command {
1036   const char *name;
1037   int minargs, maxargs;
1038   int (*fn)(struct conn *, char **, int);
1039   unsigned flags;
1040 } commands[] = {
1041   { "allfiles",       0, 2,       c_allfiles,       C_AUTH },
1042   { "become",         1, 1,       c_become,         C_AUTH|C_TRUSTED },
1043   { "cookie",         1, 1,       c_cookie,         0 },
1044   { "dirs",           0, 2,       c_dirs,           C_AUTH },
1045   { "disable",        0, 1,       c_disable,        C_AUTH },
1046   { "enable",         0, 0,       c_enable,         C_AUTH },
1047   { "enabled",        0, 0,       c_enabled,        C_AUTH },
1048   { "exists",         1, 1,       c_exists,         C_AUTH },
1049   { "files",          0, 2,       c_files,          C_AUTH },
1050   { "get",            2, 2,       c_get,            C_AUTH },
1051   { "get-global",     1, 1,       c_get_global,     C_AUTH },
1052   { "length",         1, 1,       c_length,         C_AUTH },
1053   { "log",            0, 0,       c_log,            C_AUTH },
1054   { "make-cookie",    0, 0,       c_make_cookie,    C_AUTH },
1055   { "move",           2, 2,       c_move,           C_AUTH },
1056   { "moveafter",      1, INT_MAX, c_moveafter,      C_AUTH },
1057   { "new",            0, 1,       c_new,            C_AUTH },
1058   { "nop",            0, 0,       c_nop,            C_AUTH },
1059   { "part",           3, 3,       c_part,           C_AUTH },
1060   { "pause",          0, 0,       c_pause,          C_AUTH },
1061   { "play",           1, 1,       c_play,           C_AUTH },
1062   { "playing",        0, 0,       c_playing,        C_AUTH },
1063   { "prefs",          1, 1,       c_prefs,          C_AUTH },
1064   { "queue",          0, 0,       c_queue,          C_AUTH },
1065   { "random-disable", 0, 0,       c_random_disable, C_AUTH },
1066   { "random-enable",  0, 0,       c_random_enable,  C_AUTH },
1067   { "random-enabled", 0, 0,       c_random_enabled, C_AUTH },
1068   { "recent",         0, 0,       c_recent,         C_AUTH },
1069   { "reconfigure",    0, 0,       c_reconfigure,    C_AUTH|C_TRUSTED },
1070   { "remove",         1, 1,       c_remove,         C_AUTH },
1071   { "rescan",         0, 0,       c_rescan,         C_AUTH|C_TRUSTED },
1072   { "resolve",        1, 1,       c_resolve,        C_AUTH },
1073   { "resume",         0, 0,       c_resume,         C_AUTH },
1074   { "revoke",         0, 0,       c_revoke,         C_AUTH },
1075   { "rtp-address",    0, 0,       c_rtp_address,    C_AUTH },
1076   { "scratch",        0, 1,       c_scratch,        C_AUTH },
1077   { "search",         1, 1,       c_search,         C_AUTH },
1078   { "set",            3, 3,       c_set,            C_AUTH, },
1079   { "set-global",     2, 2,       c_set_global,     C_AUTH },
1080   { "shutdown",       0, 0,       c_shutdown,       C_AUTH|C_TRUSTED },
1081   { "stats",          0, 0,       c_stats,          C_AUTH },
1082   { "tags",           0, 0,       c_tags,           C_AUTH },
1083   { "unset",          2, 2,       c_set,            C_AUTH },
1084   { "unset-global",   1, 1,       c_set_global,      C_AUTH },
1085   { "user",           2, 2,       c_user,           0 },
1086   { "version",        0, 0,       c_version,        C_AUTH },
1087   { "volume",         0, 2,       c_volume,         C_AUTH }
1088 };
1089
1090 static void command_error(const char *msg, void *u) {
1091   struct conn *c = u;
1092
1093   sink_printf(ev_writer_sink(c->w), "500 parse error: %s\n", msg);
1094 }
1095
1096 /* process a command.  Return 1 if complete, 0 if incomplete. */
1097 static int command(struct conn *c, char *line) {
1098   char **vec;
1099   int nvec, n;
1100
1101   D(("server command %s", line));
1102   /* We force everything into NFC as early as possible */
1103   if(!(line = utf8_compose_canon(line, strlen(line), 0))) {
1104     sink_writes(ev_writer_sink(c->w), "500 cannot normalize command\n");
1105     return 1;
1106   }
1107   if(!(vec = split(line, &nvec, SPLIT_QUOTES, command_error, c))) {
1108     sink_writes(ev_writer_sink(c->w), "500 cannot parse command\n");
1109     return 1;
1110   }
1111   if(nvec == 0) {
1112     sink_writes(ev_writer_sink(c->w), "500 do what?\n");
1113     return 1;
1114   }
1115   if((n = TABLE_FIND(commands, struct command, name, vec[0])) < 0)
1116     sink_writes(ev_writer_sink(c->w), "500 unknown command\n");
1117   else {
1118     if((commands[n].flags & C_AUTH) && !c->who) {
1119       sink_writes(ev_writer_sink(c->w), "530 not authenticated\n");
1120       return 1;
1121     }
1122     if((commands[n].flags & C_TRUSTED) && !trusted(c)) {
1123       sink_writes(ev_writer_sink(c->w), "530 insufficient privilege\n");
1124       return 1;
1125     }
1126     ++vec;
1127     --nvec;
1128     if(nvec < commands[n].minargs) {
1129       sink_writes(ev_writer_sink(c->w), "500 missing argument(s)\n");
1130       return 1;
1131     }
1132     if(nvec > commands[n].maxargs) {
1133       sink_writes(ev_writer_sink(c->w), "500 too many arguments\n");
1134       return 1;
1135     }
1136     return commands[n].fn(c, vec, nvec);
1137   }
1138   return 1;                     /* completed */
1139 }
1140
1141 /* redirect to the right reader callback for our current state */
1142 static int redirect_reader_callback(ev_source *ev,
1143                                     ev_reader *reader,
1144                                     void *ptr,
1145                                     size_t bytes,
1146                                     int eof,
1147                                     void *u) {
1148   struct conn *c = u;
1149
1150   return c->reader(ev, reader, ptr, bytes, eof, u);
1151 }
1152
1153 /* the main command reader */
1154 static int reader_callback(ev_source attribute((unused)) *ev,
1155                            ev_reader *reader,
1156                            void *ptr,
1157                            size_t bytes,
1158                            int eof,
1159                            void *u) {
1160   struct conn *c = u;
1161   char *eol;
1162   int complete;
1163
1164   D(("server reader_callback"));
1165   while((eol = memchr(ptr, '\n', bytes))) {
1166     *eol++ = 0;
1167     ev_reader_consume(reader, eol - (char *)ptr);
1168     complete = command(c, ptr);
1169     bytes -= (eol - (char *)ptr);
1170     ptr = eol;
1171     if(!complete) {
1172       /* the command had better have set a new reader callback */
1173       if(bytes || eof)
1174         /* there are further bytes to read, or we are at eof; arrange for the
1175          * command's reader callback to handle them */
1176         return ev_reader_incomplete(reader);
1177       /* nothing's going on right now */
1178       return 0;
1179     }
1180     /* command completed, we can go around and handle the next one */
1181   }
1182   if(eof) {
1183     if(bytes)
1184       error(0, "S%x unterminated line", c->tag);
1185     D(("normal reader close"));
1186     c->r = 0;
1187     if(c->w) {
1188       D(("close associated writer"));
1189       ev_writer_close(c->w);
1190       c->w = 0;
1191     }
1192   }
1193   return 0;
1194 }
1195
1196 static int listen_callback(ev_source *ev,
1197                            int fd,
1198                            const struct sockaddr attribute((unused)) *remote,
1199                            socklen_t attribute((unused)) rlen,
1200                            void *u) {
1201   const struct listener *l = u;
1202   struct conn *c = xmalloc(sizeof *c);
1203   static unsigned tags;
1204
1205   D(("server listen_callback fd %d (%s)", fd, l->name));
1206   nonblock(fd);
1207   cloexec(fd);
1208   c->tag = tags++;
1209   c->ev = ev;
1210   c->w = ev_writer_new(ev, fd, writer_error, c,
1211                        "client writer");
1212   c->r = ev_reader_new(ev, fd, redirect_reader_callback, reader_error, c,
1213                        "client reader");
1214   ev_tie(c->r, c->w);
1215   c->fd = fd;
1216   c->reader = reader_callback;
1217   c->l = l;
1218   gcry_randomize(c->nonce, sizeof c->nonce, GCRY_STRONG_RANDOM);
1219   if(!strcmp(config->authorization_algorithm, "sha1")
1220      || !strcmp(config->authorization_algorithm, "SHA1")) {
1221     sink_printf(ev_writer_sink(c->w), "231 %s\n",
1222                 hex(c->nonce, sizeof c->nonce));
1223   } else {
1224     sink_printf(ev_writer_sink(c->w), "231 %s %s\n",
1225                 config->authorization_algorithm,
1226                 hex(c->nonce, sizeof c->nonce));
1227   }
1228   return 0;
1229 }
1230
1231 int server_start(ev_source *ev, int pf,
1232                  size_t socklen, const struct sockaddr *sa,
1233                  const char *name) {
1234   int fd;
1235   struct listener *l = xmalloc(sizeof *l);
1236   static const int one = 1;
1237
1238   D(("server_init socket %s", name));
1239   fd = xsocket(pf, SOCK_STREAM, 0);
1240   xsetsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
1241   if(bind(fd, sa, socklen) < 0) {
1242     error(errno, "error binding to %s", name);
1243     return -1;
1244   }
1245   xlisten(fd, 128);
1246   nonblock(fd);
1247   cloexec(fd);
1248   l->name = name;
1249   l->pf = pf;
1250   if(ev_listen(ev, fd, listen_callback, l, "server listener"))
1251     exit(EXIT_FAILURE);
1252   return fd;
1253 }
1254
1255 int server_stop(ev_source *ev, int fd) {
1256   xclose(fd);
1257   return ev_listen_cancel(ev, fd);
1258 }
1259
1260 /*
1261 Local Variables:
1262 c-basic-offset:2
1263 comment-column:40
1264 fill-column:79
1265 End:
1266 */