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