chiark / gitweb /
5df2d330a611c1b42e8f2c756177cad9fd10624a
[disorder] / server / server.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004-2008 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 #include "base64.h"
70 #include "hash.h"
71 #include "mime.h"
72 #include "sendmail.h"
73 #include "wstat.h"
74 #include "schedule.h"
75
76 #ifndef NONCE_SIZE
77 # define NONCE_SIZE 16
78 #endif
79
80 #ifndef CONFIRM_SIZE
81 # define CONFIRM_SIZE 10
82 #endif
83
84 int volume_left, volume_right;          /* last known volume */
85
86 /** @brief Accept all well-formed login attempts
87  *
88  * Used in debugging.
89  */
90 int wideopen;
91
92 struct listener {
93   const char *name;
94   int pf;
95 };
96
97 /** @brief One client connection */
98 struct conn {
99   /** @brief Read commands from here */
100   ev_reader *r;
101   /** @brief Send responses to here */
102   ev_writer *w;
103   /** @brief Underlying file descriptor */
104   int fd;
105   /** @brief Unique identifier for connection used in log messages */
106   unsigned tag;
107   /** @brief Login name or NULL */
108   char *who;
109   /** @brief Event loop */
110   ev_source *ev;
111   /** @brief Nonce chosen for this connection */
112   unsigned char nonce[NONCE_SIZE];
113   /** @brief Current reader callback
114    *
115    * We change this depending on whether we're servicing the @b log command
116    */
117   ev_reader_callback *reader;
118   /** @brief Event log output sending to this connection */
119   struct eventlog_output *lo;
120   /** @brief Parent listener */
121   const struct listener *l;
122   /** @brief Login cookie or NULL */
123   char *cookie;
124   /** @brief Connection rights */
125   rights_type rights;
126   /** @brief Next connection */
127   struct conn *next;
128   /** @brief True if pending rescan had 'wait' set */
129   int rescan_wait;
130 };
131
132 /** @brief Linked list of connections */
133 static struct conn *connections;
134
135 static int reader_callback(ev_source *ev,
136                            ev_reader *reader,
137                            void *ptr,
138                            size_t bytes,
139                            int eof,
140                            void *u);
141
142 static const char *noyes[] = { "no", "yes" };
143
144 /** @brief Remove a connection from the connection list */
145 static void remove_connection(struct conn *c) {
146   struct conn **cc;
147
148   for(cc = &connections; *cc && *cc != c; cc = &(*cc)->next)
149     ;
150   if(*cc)
151     *cc = c->next;
152 }
153
154 /** @brief Called when a connection's writer fails or is shut down
155  *
156  * If the connection still has a raeder that is cancelled.
157  */
158 static int writer_error(ev_source attribute((unused)) *ev,
159                         int errno_value,
160                         void *u) {
161   struct conn *c = u;
162
163   D(("server writer_error S%x %d", c->tag, errno_value));
164   if(errno_value == 0) {
165     /* writer is done */
166     D(("S%x writer completed", c->tag));
167   } else {
168     if(errno_value != EPIPE)
169       error(errno_value, "S%x write error on socket", c->tag);
170     if(c->r) {
171       D(("cancel reader"));
172       ev_reader_cancel(c->r);
173       c->r = 0;
174     }
175     D(("done cancel reader"));
176   }
177   c->w = 0;
178   ev_report(ev);
179   remove_connection(c);
180   return 0;
181 }
182
183 /** @brief Called when a conncetion's reader fails or is shut down
184  *
185  * If connection still has a writer then it is closed.
186  */
187 static int reader_error(ev_source attribute((unused)) *ev,
188                         int errno_value,
189                         void *u) {
190   struct conn *c = u;
191
192   D(("server reader_error S%x %d", c->tag, errno_value));
193   error(errno_value, "S%x read error on socket", c->tag);
194   if(c->w)
195     ev_writer_close(c->w);
196   c->w = 0;
197   c->r = 0;
198   ev_report(ev);
199   remove_connection(c);
200   return 0;
201 }
202
203 static int c_disable(struct conn *c, char **vec, int nvec) {
204   if(nvec == 0)
205     disable_playing(c->who);
206   else if(nvec == 1 && !strcmp(vec[0], "now"))
207     disable_playing(c->who);
208   else {
209     sink_writes(ev_writer_sink(c->w), "550 invalid argument\n");
210     return 1;                   /* completed */
211   }
212   sink_writes(ev_writer_sink(c->w), "250 OK\n");
213   return 1;                     /* completed */
214 }
215
216 static int c_enable(struct conn *c,
217                     char attribute((unused)) **vec,
218                     int attribute((unused)) nvec) {
219   enable_playing(c->who, c->ev);
220   /* Enable implicitly unpauses if there is nothing playing */
221   if(paused && !playing) resume_playing(c->who);
222   sink_writes(ev_writer_sink(c->w), "250 OK\n");
223   return 1;                     /* completed */
224 }
225
226 static int c_enabled(struct conn *c,
227                      char attribute((unused)) **vec,
228                      int attribute((unused)) nvec) {
229   sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[playing_is_enabled()]);
230   return 1;                     /* completed */
231 }
232
233 static int c_play(struct conn *c, char **vec,
234                   int attribute((unused)) nvec) {
235   const char *track;
236   struct queue_entry *q;
237   
238   if(!trackdb_exists(vec[0])) {
239     sink_writes(ev_writer_sink(c->w), "550 track is not in database\n");
240     return 1;
241   }
242   if(!(track = trackdb_resolve(vec[0]))) {
243     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
244     return 1;
245   }
246   q = queue_add(track, c->who, WHERE_BEFORE_RANDOM);
247   queue_write();
248   /* If we added the first track, and something is playing, then prepare the
249    * new track.  If nothing is playing then we don't bother as it wouldn't gain
250    * anything. */
251   if(q == qhead.next && playing)
252     prepare(c->ev, q);
253   sink_printf(ev_writer_sink(c->w), "252 %s\n", q->id);
254   /* If the queue was empty but we are for some reason paused then
255    * unpause. */
256   if(!playing) resume_playing(0);
257   play(c->ev);
258   return 1;                     /* completed */
259 }
260
261 static int c_remove(struct conn *c, char **vec,
262                     int attribute((unused)) nvec) {
263   struct queue_entry *q;
264
265   if(!(q = queue_find(vec[0]))) {
266     sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
267     return 1;
268   }
269   if(!right_removable(c->rights, c->who, q)) {
270     error(0, "%s attempted remove but lacks required rights", c->who);
271     sink_writes(ev_writer_sink(c->w),
272                 "510 Not authorized to remove that track\n");
273     return 1;
274   }
275   queue_remove(q, c->who);
276   /* De-prepare the track. */
277   abandon(c->ev, q);
278   /* See about adding a new random track */
279   add_random_track(c->ev);
280   /* Prepare whatever the next head track is. */
281   if(qhead.next != &qhead)
282     prepare(c->ev, qhead.next);
283   queue_write();
284   sink_writes(ev_writer_sink(c->w), "250 removed\n");
285   return 1;                     /* completed */
286 }
287
288 static int c_scratch(struct conn *c,
289                      char **vec,
290                      int nvec) {
291   if(!playing) {
292     sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
293     return 1;                   /* completed */
294   }
295   /* TODO there is a bug here: if we specify an ID but it's not the currently
296    * playing track then you will get 550 if you weren't authorized to scratch
297    * the currently playing track. */
298   if(!right_scratchable(c->rights, c->who, playing)) {
299     error(0, "%s attempted scratch but lacks required rights", c->who);
300     sink_writes(ev_writer_sink(c->w),
301                 "510 Not authorized to scratch that track\n");
302     return 1;
303   }
304   scratch(c->who, nvec == 1 ? vec[0] : 0);
305   /* If you scratch an unpaused track then it is automatically unpaused */
306   resume_playing(0);
307   sink_writes(ev_writer_sink(c->w), "250 scratched\n");
308   return 1;                     /* completed */
309 }
310
311 static int c_pause(struct conn *c,
312                    char attribute((unused)) **vec,
313                    int attribute((unused)) nvec) {
314   if(!playing) {
315     sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
316     return 1;                   /* completed */
317   }
318   if(paused) {
319     sink_writes(ev_writer_sink(c->w), "250 already paused\n");
320     return 1;                   /* completed */
321   }
322   if(pause_playing(c->who) < 0)
323     sink_writes(ev_writer_sink(c->w), "550 cannot pause this track\n");
324   else
325     sink_writes(ev_writer_sink(c->w), "250 paused\n");
326   return 1;
327 }
328
329 static int c_resume(struct conn *c,
330                    char attribute((unused)) **vec,
331                    int attribute((unused)) nvec) {
332   if(!paused) {
333     sink_writes(ev_writer_sink(c->w), "250 not paused\n");
334     return 1;                   /* completed */
335   }
336   resume_playing(c->who);
337   sink_writes(ev_writer_sink(c->w), "250 paused\n");
338   return 1;
339 }
340
341 static int c_shutdown(struct conn *c,
342                       char attribute((unused)) **vec,
343                       int attribute((unused)) nvec) {
344   info("S%x shut down by %s", c->tag, c->who);
345   sink_writes(ev_writer_sink(c->w), "250 shutting down\n");
346   ev_writer_flush(c->w);
347   quit(c->ev);
348 }
349
350 static int c_reconfigure(struct conn *c,
351                          char attribute((unused)) **vec,
352                          int attribute((unused)) nvec) {
353   info("S%x reconfigure by %s", c->tag, c->who);
354   if(reconfigure(c->ev, 1))
355     sink_writes(ev_writer_sink(c->w), "550 error reading new config\n");
356   else
357     sink_writes(ev_writer_sink(c->w), "250 installed new config\n");
358   return 1;                             /* completed */
359 }
360
361 static void finished_rescan(void *ru) {
362   struct conn *const c = ru;
363
364   sink_writes(ev_writer_sink(c->w), "250 rescan completed\n");
365   /* Turn this connection back on */
366   ev_reader_enable(c->r);
367 }
368
369 static void start_fresh_rescan(void *ru) {
370   struct conn *const c = ru;
371
372   if(trackdb_rescan_underway()) {
373     /* Some other waiter beat us to it.  However in this case we're happy to
374      * piggyback; the requirement is that a new rescan be started, not that it
375      * was _our_ rescan. */
376     if(c->rescan_wait) {
377       /* We block until the rescan completes */
378       trackdb_add_rescanned(finished_rescan, c);
379     } else {
380       /* We report that the new rescan has started */
381       sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
382       /* Turn this connection back on */
383       ev_reader_enable(c->r);
384     }
385   } else {
386     /* We are the first connection to get a callback so we must start a
387      * rescan. */
388     if(c->rescan_wait) {
389       /* We want to block until the new rescan completes */
390       trackdb_rescan(c->ev, 1/*check*/, finished_rescan, c);
391     } else {
392       /* We can report back immediately */
393       trackdb_rescan(c->ev, 1/*check*/, 0, 0);
394       sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
395       /* Turn this connection back on */
396       ev_reader_enable(c->r);
397     }
398   }
399 }
400
401 static int c_rescan(struct conn *c,
402                     char **vec,
403                     int nvec) {
404   int wait = 0, fresh = 0, n;
405
406   /* Parse flags */
407   for(n = 0; n < nvec; ++n) {
408     if(!strcmp(vec[n], "wait"))
409       wait = 1;                         /* wait for rescan to complete */
410 #if 0
411     /* Currently disabled because untested (and hard to test). */
412     else if(!strcmp(vec[n], "fresh"))
413       fresh = 1;                        /* don't piggyback underway rescan */
414 #endif
415     else {
416       sink_writes(ev_writer_sink(c->w), "550 unknown flag\n");
417       return 1;                         /* completed */
418     }
419   }
420   /* Report what was requested */
421   info("S%x rescan by %s (%s %s)", c->tag, c->who,
422        wait ? "wait" : "",
423        fresh ? "fresh" : "");
424   if(trackdb_rescan_underway()) {
425     if(fresh) {
426       /* We want a fresh rescan but there is already one underway.  Arrange a
427        * callback when it completes and then set off a new one. */
428       c->rescan_wait = wait;
429       trackdb_add_rescanned(start_fresh_rescan, c);
430       if(wait)
431         return 0;
432       else {
433         sink_writes(ev_writer_sink(c->w), "250 rescan queued\n");
434         return 1;
435       }
436     } else {
437       /* There's a rescan underway, and it's acceptable to piggyback on it */
438       if(wait) {
439         /* We want to block until completion. */
440         trackdb_add_rescanned(finished_rescan, c);
441         return 0;
442       } else {
443         /* We don't want to block.  So we just report that things are in
444          * hand. */
445         sink_writes(ev_writer_sink(c->w), "250 rescan already underway\n");
446         return 1;
447       }
448     }
449   } else {
450     /* No rescan is underway.  fresh is therefore irrelevant. */
451     if(wait) {
452       /* We want to block until completion */
453       trackdb_rescan(c->ev, 1/*check*/, finished_rescan, c);
454       return 0;
455     } else {
456       /* We don't want to block. */
457       trackdb_rescan(c->ev, 1/*check*/, 0, 0);
458       sink_writes(ev_writer_sink(c->w), "250 rescan initiated\n");
459       return 1;                         /* completed */
460     }
461   }
462 }
463
464 static int c_version(struct conn *c,
465                      char attribute((unused)) **vec,
466                      int attribute((unused)) nvec) {
467   /* VERSION had better only use the basic character set */
468   sink_printf(ev_writer_sink(c->w), "251 %s\n", disorder_short_version_string);
469   return 1;                     /* completed */
470 }
471
472 static int c_playing(struct conn *c,
473                      char attribute((unused)) **vec,
474                      int attribute((unused)) nvec) {
475   if(playing) {
476     queue_fix_sofar(playing);
477     playing->expected = 0;
478     sink_printf(ev_writer_sink(c->w), "252 %s\n", queue_marshall(playing));
479   } else
480     sink_printf(ev_writer_sink(c->w), "259 nothing playing\n");
481   return 1;                             /* completed */
482 }
483
484 static const char *connection_host(struct conn *c) {
485   union {
486     struct sockaddr sa;
487     struct sockaddr_in in;
488     struct sockaddr_in6 in6;
489   } u;
490   socklen_t l;
491   int n;
492   char host[1024];
493
494   /* get connection data */
495   l = sizeof u;
496   if(getpeername(c->fd, &u.sa, &l) < 0) {
497     error(errno, "S%x error calling getpeername", c->tag);
498     return 0;
499   }
500   if(c->l->pf != PF_UNIX) {
501     if((n = getnameinfo(&u.sa, l,
502                         host, sizeof host, 0, 0, NI_NUMERICHOST))) {
503       error(0, "S%x error calling getnameinfo: %s", c->tag, gai_strerror(n));
504       return 0;
505     }
506     return xstrdup(host);
507   } else
508     return "local";
509 }
510
511 static int c_user(struct conn *c,
512                   char **vec,
513                   int attribute((unused)) nvec) {
514   struct kvp *k;
515   const char *res, *host, *password;
516   rights_type rights;
517
518   if(c->who) {
519     sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
520     return 1;
521   }
522   /* get connection data */
523   if(!(host = connection_host(c))) {
524     sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
525     return 1;
526   }
527   /* find the user */
528   k = trackdb_getuserinfo(vec[0]);
529   /* reject nonexistent users */
530   if(!k) {
531     error(0, "S%x unknown user '%s' from %s", c->tag, vec[0], host);
532     sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
533     return 1;
534   }
535   /* reject unconfirmed users */
536   if(kvp_get(k, "confirmation")) {
537     error(0, "S%x unconfirmed user '%s' from %s", c->tag, vec[0], host);
538     sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
539     return 1;
540   }
541   password = kvp_get(k, "password");
542   if(!password) password = "";
543   if(parse_rights(kvp_get(k, "rights"), &rights, 1)) {
544     error(0, "error parsing rights for %s", vec[0]);
545     sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
546     return 1;
547   }
548   /* check whether the response is right */
549   res = authhash(c->nonce, sizeof c->nonce, password,
550                  config->authorization_algorithm);
551   if(wideopen || (res && !strcmp(res, vec[1]))) {
552     c->who = vec[0];
553     c->rights = rights;
554     /* currently we only bother logging remote connections */
555     if(strcmp(host, "local"))
556       info("S%x %s connected from %s", c->tag, vec[0], host);
557     else
558       c->rights |= RIGHT__LOCAL;
559     sink_writes(ev_writer_sink(c->w), "230 OK\n");
560     return 1;
561   }
562   /* oops, response was wrong */
563   info("S%x authentication failure for %s from %s", c->tag, vec[0], host);
564   sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
565   return 1;
566 }
567
568 static int c_recent(struct conn *c,
569                     char attribute((unused)) **vec,
570                     int attribute((unused)) nvec) {
571   const struct queue_entry *q;
572
573   sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
574   for(q = phead.next; q != &phead; q = q->next)
575     sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
576   sink_writes(ev_writer_sink(c->w), ".\n");
577   return 1;                             /* completed */
578 }
579
580 static int c_queue(struct conn *c,
581                    char attribute((unused)) **vec,
582                    int attribute((unused)) nvec) {
583   struct queue_entry *q;
584   time_t when = 0;
585   const char *l;
586   long length;
587
588   sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
589   if(playing_is_enabled() && !paused) {
590     if(playing) {
591       queue_fix_sofar(playing);
592       if((l = trackdb_get(playing->track, "_length"))
593          && (length = atol(l))) {
594         time(&when);
595         when += length - playing->sofar + config->gap;
596       }
597     } else
598       /* Nothing is playing but playing is enabled, so whatever is
599        * first in the queue can be expected to start immediately. */
600       time(&when);
601   }
602   for(q = qhead.next; q != &qhead; q = q->next) {
603     /* fill in estimated start time */
604     q->expected = when;
605     sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
606     /* update for next track */
607     if(when) {
608       if((l = trackdb_get(q->track, "_length"))
609          && (length = atol(l)))
610         when += length + config->gap;
611       else
612         when = 0;
613     }
614   }
615   sink_writes(ev_writer_sink(c->w), ".\n");
616   return 1;                             /* completed */
617 }
618
619 static int output_list(struct conn *c, char **vec) {
620   while(*vec)
621     sink_printf(ev_writer_sink(c->w), "%s\n", *vec++);
622   sink_writes(ev_writer_sink(c->w), ".\n");
623   return 1;
624 }
625
626 static int files_dirs(struct conn *c,
627                       char **vec,
628                       int nvec,
629                       enum trackdb_listable what) {
630   const char *dir, *re, *errstr;
631   int erroffset;
632   pcre *rec;
633   char **fvec, *key;
634   
635   switch(nvec) {
636   case 0: dir = 0; re = 0; break;
637   case 1: dir = vec[0]; re = 0; break;
638   case 2: dir = vec[0]; re = vec[1]; break;
639   default: abort();
640   }
641   /* A bit of a bodge to make sure the args don't trample on cache keys */
642   if(dir && strchr(dir, '\n')) {
643     sink_writes(ev_writer_sink(c->w), "550 invalid directory name\n");
644     return 1;
645   }
646   if(re && strchr(re, '\n')) {
647     sink_writes(ev_writer_sink(c->w), "550 invalid regexp\n");
648     return 1;
649   }
650   /* We bother eliminating "" because the web interface is relatively
651    * likely to send it */
652   if(re && *re) {
653     byte_xasprintf(&key, "%d\n%s\n%s", (int)what, dir ? dir : "", re);
654     fvec = (char **)cache_get(&cache_files_type, key);
655     if(fvec) {
656       /* Got a cache hit, don't store the answer in the cache */
657       key = 0;
658       ++cache_files_hits;
659       rec = 0;                          /* quieten compiler */
660     } else {
661       /* Cache miss, we'll do the lookup and key != 0 so we'll store the answer
662        * in the cache. */
663       if(!(rec = pcre_compile(re, PCRE_CASELESS|PCRE_UTF8,
664                               &errstr, &erroffset, 0))) {
665         sink_printf(ev_writer_sink(c->w), "550 Error compiling regexp: %s\n",
666                     errstr);
667         return 1;
668       }
669       /* It only counts as a miss if the regexp was valid. */
670       ++cache_files_misses;
671     }
672   } else {
673     /* No regexp, don't bother caching the result */
674     rec = 0;
675     key = 0;
676     fvec = 0;
677   }
678   if(!fvec) {
679     /* No cache hit (either because a miss, or because we did not look) so do
680      * the lookup */
681     if(dir && *dir)
682       fvec = trackdb_list(dir, 0, what, rec);
683     else
684       fvec = trackdb_list(0, 0, what, rec);
685   }
686   if(key)
687     /* Put the answer in the cache */
688     cache_put(&cache_files_type, key, fvec);
689   sink_writes(ev_writer_sink(c->w), "253 Listing follow\n");
690   return output_list(c, fvec);
691 }
692
693 static int c_files(struct conn *c,
694                   char **vec,
695                   int nvec) {
696   return files_dirs(c, vec, nvec, trackdb_files);
697 }
698
699 static int c_dirs(struct conn *c,
700                   char **vec,
701                   int nvec) {
702   return files_dirs(c, vec, nvec, trackdb_directories);
703 }
704
705 static int c_allfiles(struct conn *c,
706                       char **vec,
707                       int nvec) {
708   return files_dirs(c, vec, nvec, trackdb_directories|trackdb_files);
709 }
710
711 static int c_get(struct conn *c,
712                  char **vec,
713                  int attribute((unused)) nvec) {
714   const char *v, *track;
715
716   if(!(track = trackdb_resolve(vec[0]))) {
717     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
718     return 1;
719   }
720   if(vec[1][0] != '_' && (v = trackdb_get(track, vec[1])))
721     sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
722   else
723     sink_writes(ev_writer_sink(c->w), "555 not found\n");
724   return 1;
725 }
726
727 static int c_length(struct conn *c,
728                  char **vec,
729                  int attribute((unused)) nvec) {
730   const char *track, *v;
731
732   if(!(track = trackdb_resolve(vec[0]))) {
733     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
734     return 1;
735   }
736   if((v = trackdb_get(track, "_length")))
737     sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
738   else
739     sink_writes(ev_writer_sink(c->w), "550 not found\n");
740   return 1;
741 }
742
743 static int c_set(struct conn *c,
744                  char **vec,
745                  int attribute((unused)) nvec) {
746   const char *track;
747
748   if(!(track = trackdb_resolve(vec[0]))) {
749     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
750     return 1;
751   }
752   if(vec[1][0] != '_' && !trackdb_set(track, vec[1], vec[2]))
753     sink_writes(ev_writer_sink(c->w), "250 OK\n");
754   else
755     sink_writes(ev_writer_sink(c->w), "550 not found\n");
756   return 1;
757 }
758
759 static int c_prefs(struct conn *c,
760                    char **vec,
761                    int attribute((unused)) nvec) {
762   struct kvp *k;
763   const char *track;
764
765   if(!(track = trackdb_resolve(vec[0]))) {
766     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
767     return 1;
768   }
769   k = trackdb_get_all(track);
770   sink_writes(ev_writer_sink(c->w), "253 prefs follow\n");
771   for(; k; k = k->next)
772     if(k->name[0] != '_')               /* omit internal values */
773       sink_printf(ev_writer_sink(c->w),
774                   " %s %s\n", quoteutf8(k->name), quoteutf8(k->value));
775   sink_writes(ev_writer_sink(c->w), ".\n");
776   return 1;
777 }
778
779 static int c_exists(struct conn *c,
780                     char **vec,
781                     int attribute((unused)) nvec) {
782   /* trackdb_exists() does its own alias checking */
783   sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[trackdb_exists(vec[0])]);
784   return 1;
785 }
786
787 static void search_parse_error(const char *msg, void *u) {
788   *(const char **)u = msg;
789 }
790
791 static int c_search(struct conn *c,
792                           char **vec,
793                           int attribute((unused)) nvec) {
794   char **terms, **results;
795   int nterms, nresults, n;
796   const char *e = "unknown error";
797
798   /* This is a bit of a bodge.  Initially it's there to make the eclient
799    * interface a bit more convenient to add searching to, but it has the more
800    * compelling advantage that if everything uses it, then interpretation of
801    * user-supplied search strings will be the same everywhere. */
802   if(!(terms = split(vec[0], &nterms, SPLIT_QUOTES, search_parse_error, &e))) {
803     sink_printf(ev_writer_sink(c->w), "550 %s\n", e);
804   } else {
805     results = trackdb_search(terms, nterms, &nresults);
806     sink_printf(ev_writer_sink(c->w), "253 %d matches\n", nresults);
807     for(n = 0; n < nresults; ++n)
808       sink_printf(ev_writer_sink(c->w), "%s\n", results[n]);
809     sink_writes(ev_writer_sink(c->w), ".\n");
810   }
811   return 1;
812 }
813
814 static int c_random_enable(struct conn *c,
815                            char attribute((unused)) **vec,
816                            int attribute((unused)) nvec) {
817   enable_random(c->who, c->ev);
818   /* Enable implicitly unpauses if there is nothing playing */
819   if(paused && !playing) resume_playing(c->who);
820   sink_writes(ev_writer_sink(c->w), "250 OK\n");
821   return 1;                     /* completed */
822 }
823
824 static int c_random_disable(struct conn *c,
825                             char attribute((unused)) **vec,
826                             int attribute((unused)) nvec) {
827   disable_random(c->who);
828   sink_writes(ev_writer_sink(c->w), "250 OK\n");
829   return 1;                     /* completed */
830 }
831
832 static int c_random_enabled(struct conn *c,
833                             char attribute((unused)) **vec,
834                             int attribute((unused)) nvec) {
835   sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[random_is_enabled()]);
836   return 1;                     /* completed */
837 }
838
839 static void got_stats(char *stats, void *u) {
840   struct conn *const c = u;
841
842   sink_printf(ev_writer_sink(c->w), "253 stats\n%s\n.\n", stats);
843   /* Now we can start processing commands again */
844   ev_reader_enable(c->r);
845 }
846
847 static int c_stats(struct conn *c,
848                    char attribute((unused)) **vec,
849                    int attribute((unused)) nvec) {
850   trackdb_stats_subprocess(c->ev, got_stats, c);
851   return 0;                             /* not yet complete */
852 }
853
854 static int c_volume(struct conn *c,
855                     char **vec,
856                     int nvec) {
857   int l, r, set;
858   char lb[32], rb[32];
859   rights_type rights;
860
861   switch(nvec) {
862   case 0:
863     set = 0;
864     break;
865   case 1:
866     l = r = atoi(vec[0]);
867     set = 1;
868     break;
869   case 2:
870     l = atoi(vec[0]);
871     r = atoi(vec[1]);
872     set = 1;
873     break;
874   default:
875     abort();
876   }
877   rights = set ? RIGHT_VOLUME : RIGHT_READ;
878   if(!(c->rights & rights)) {
879     error(0, "%s attempted to set volume but lacks required rights", c->who);
880     sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
881     return 1;
882   }
883   if(mixer_control(-1/*as configured*/, &l, &r, set))
884     sink_writes(ev_writer_sink(c->w), "550 error accessing mixer\n");
885   else {
886     sink_printf(ev_writer_sink(c->w), "252 %d %d\n", l, r);
887     if(l != volume_left || r != volume_right) {
888       volume_left = l;
889       volume_right = r;
890       snprintf(lb, sizeof lb, "%d", l);
891       snprintf(rb, sizeof rb, "%d", r);
892       eventlog("volume", lb, rb, (char *)0);
893     }
894   }
895   return 1;
896 }
897
898 /** @brief Called when data arrives on a log connection
899  *
900  * We just discard all such data.  The client may occasionally send data as a
901  * keepalive.
902  */
903 static int logging_reader_callback(ev_source attribute((unused)) *ev,
904                                    ev_reader *reader,
905                                    void attribute((unused)) *ptr,
906                                    size_t bytes,
907                                    int attribute((unused)) eof,
908                                    void attribute((unused)) *u) {
909   struct conn *c = u;
910
911   ev_reader_consume(reader, bytes);
912   if(eof) {
913     /* Oops, that's all for now */
914     D(("logging reader eof"));
915     if(c->w) {
916       D(("close writer"));
917       ev_writer_close(c->w);
918       c->w = 0;
919     }
920     c->r = 0;
921     remove_connection(c);
922   }
923   return 0;
924 }
925
926 static void logclient(const char *msg, void *user) {
927   struct conn *c = user;
928
929   if(!c->w || !c->r) {
930     /* This connection has gone up in smoke for some reason */
931     eventlog_remove(c->lo);
932     return;
933   }
934   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" %s\n",
935               (uintmax_t)time(0), msg);
936 }
937
938 static int c_log(struct conn *c,
939                  char attribute((unused)) **vec,
940                  int attribute((unused)) nvec) {
941   time_t now;
942
943   sink_writes(ev_writer_sink(c->w), "254 OK\n");
944   /* pump out initial state */
945   time(&now);
946   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
947               (uintmax_t)now, 
948               playing_is_enabled() ? "enable_play" : "disable_play");
949   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
950               (uintmax_t)now, 
951               random_is_enabled() ? "enable_random" : "disable_random");
952   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
953               (uintmax_t)now, 
954               paused ? "pause" : "resume");
955   if(playing)
956     sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state playing\n",
957                 (uintmax_t)now);
958   /* Initial volume */
959   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" volume %d %d\n",
960               (uintmax_t)now, volume_left, volume_right);
961   c->lo = xmalloc(sizeof *c->lo);
962   c->lo->fn = logclient;
963   c->lo->user = c;
964   eventlog_add(c->lo);
965   c->reader = logging_reader_callback;
966   return 0;
967 }
968
969 /** @brief Test whether a move is allowed
970  * @param c Connection
971  * @param qs List of IDs on queue
972  * @param nqs Number of IDs
973  * @return 0 if move is prohibited, non-0 if it is allowed
974  */
975 static int has_move_rights(struct conn *c, struct queue_entry **qs, int nqs) {
976   for(; nqs > 0; ++qs, --nqs) {
977     struct queue_entry *const q = *qs;
978
979     if(!right_movable(c->rights, c->who, q))
980       return 0;
981   }
982   return 1;
983 }
984
985 static int c_move(struct conn *c,
986                   char **vec,
987                   int attribute((unused)) nvec) {
988   struct queue_entry *q;
989   int n;
990
991   if(!(q = queue_find(vec[0]))) {
992     sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
993     return 1;
994   }
995   if(!has_move_rights(c, &q, 1)) {
996     error(0, "%s attempted move but lacks required rights", c->who);
997     sink_writes(ev_writer_sink(c->w),
998                 "510 Not authorized to move that track\n");
999     return 1;
1000   }
1001   n = queue_move(q, atoi(vec[1]), c->who);
1002   sink_printf(ev_writer_sink(c->w), "252 %d\n", n);
1003   /* If we've moved to the head of the queue then prepare the track. */
1004   if(q == qhead.next)
1005     prepare(c->ev, q);
1006   return 1;
1007 }
1008
1009 static int c_moveafter(struct conn *c,
1010                        char **vec,
1011                        int attribute((unused)) nvec) {
1012   struct queue_entry *q, **qs;
1013   int n;
1014
1015   if(vec[0][0]) {
1016     if(!(q = queue_find(vec[0]))) {
1017       sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1018       return 1;
1019     }
1020   } else
1021     q = 0;
1022   ++vec;
1023   --nvec;
1024   qs = xcalloc(nvec, sizeof *qs);
1025   for(n = 0; n < nvec; ++n)
1026     if(!(qs[n] = queue_find(vec[n]))) {
1027       sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1028       return 1;
1029     }
1030   if(!has_move_rights(c, qs, nvec)) {
1031     error(0, "%s attempted moveafter but lacks required rights", c->who);
1032     sink_writes(ev_writer_sink(c->w),
1033                 "510 Not authorized to move those tracks\n");
1034     return 1;
1035   }
1036   queue_moveafter(q, nvec, qs, c->who);
1037   sink_printf(ev_writer_sink(c->w), "250 Moved tracks\n");
1038   /* If we've moved to the head of the queue then prepare the track. */
1039   if(q == qhead.next)
1040     prepare(c->ev, q);
1041   return 1;
1042 }
1043
1044 static int c_part(struct conn *c,
1045                   char **vec,
1046                   int attribute((unused)) nvec) {
1047   const char *track;
1048
1049   if(!(track = trackdb_resolve(vec[0]))) {
1050     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1051     return 1;
1052   }
1053   sink_printf(ev_writer_sink(c->w), "252 %s\n",
1054               quoteutf8(trackdb_getpart(track, vec[1], vec[2])));
1055   return 1;
1056 }
1057
1058 static int c_resolve(struct conn *c,
1059                      char **vec,
1060                      int attribute((unused)) nvec) {
1061   const char *track;
1062
1063   if(!(track = trackdb_resolve(vec[0]))) {
1064     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1065     return 1;
1066   }
1067   sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(track));
1068   return 1;
1069 }
1070
1071 static int c_tags(struct conn *c,
1072                   char attribute((unused)) **vec,
1073                   int attribute((unused)) nvec) {
1074   char **tags = trackdb_alltags();
1075   
1076   sink_printf(ev_writer_sink(c->w), "253 Tag list follows\n");
1077   while(*tags) {
1078     sink_printf(ev_writer_sink(c->w), "%s%s\n",
1079                 **tags == '.' ? "." : "", *tags);
1080     ++tags;
1081   }
1082   sink_writes(ev_writer_sink(c->w), ".\n");
1083   return 1;                             /* completed */
1084 }
1085
1086 static int c_set_global(struct conn *c,
1087                         char **vec,
1088                         int attribute((unused)) nvec) {
1089   if(vec[0][0] == '_') {
1090     sink_writes(ev_writer_sink(c->w), "550 cannot set internal global preferences\n");
1091     return 1;
1092   }
1093   trackdb_set_global(vec[0], vec[1], c->who);
1094   sink_printf(ev_writer_sink(c->w), "250 OK\n");
1095   return 1;
1096 }
1097
1098 static int c_get_global(struct conn *c,
1099                         char **vec,
1100                         int attribute((unused)) nvec) {
1101   const char *s = trackdb_get_global(vec[0]);
1102
1103   if(s)
1104     sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(s));
1105   else
1106     sink_writes(ev_writer_sink(c->w), "555 not found\n");
1107   return 1;
1108 }
1109
1110 static int c_nop(struct conn *c,
1111                  char attribute((unused)) **vec,
1112                  int attribute((unused)) nvec) {
1113   sink_printf(ev_writer_sink(c->w), "250 Quack\n");
1114   return 1;
1115 }
1116
1117 static int c_new(struct conn *c,
1118                  char **vec,
1119                  int nvec) {
1120   int max, n;
1121   char **tracks;
1122
1123   if(nvec > 0)
1124     max = atoi(vec[0]);
1125   else
1126     max = INT_MAX;
1127   if(max <= 0 || max > config->new_max)
1128     max = config->new_max;
1129   tracks = trackdb_new(0, max);
1130   sink_printf(ev_writer_sink(c->w), "253 New track list follows\n");
1131   n = 0;
1132   while(*tracks) {
1133     sink_printf(ev_writer_sink(c->w), "%s%s\n",
1134                 **tracks == '.' ? "." : "", *tracks);
1135     ++tracks;
1136   }
1137   sink_writes(ev_writer_sink(c->w), ".\n");
1138   return 1;                             /* completed */
1139
1140 }
1141
1142 static int c_rtp_address(struct conn *c,
1143                          char attribute((unused)) **vec,
1144                          int attribute((unused)) nvec) {
1145   if(config->api == BACKEND_NETWORK) {
1146     sink_printf(ev_writer_sink(c->w), "252 %s %s\n",
1147                 quoteutf8(config->broadcast.s[0]),
1148                 quoteutf8(config->broadcast.s[1]));
1149   } else
1150     sink_writes(ev_writer_sink(c->w), "550 No RTP\n");
1151   return 1;
1152 }
1153
1154 static int c_cookie(struct conn *c,
1155                     char **vec,
1156                     int attribute((unused)) nvec) {
1157   const char *host;
1158   char *user;
1159   rights_type rights;
1160
1161   /* Can't log in twice on the same connection */
1162   if(c->who) {
1163     sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
1164     return 1;
1165   }
1166   /* Get some kind of peer identifcation */
1167   if(!(host = connection_host(c))) {
1168     sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1169     return 1;
1170   }
1171   /* Check the cookie */
1172   user = verify_cookie(vec[0], &rights);
1173   if(!user) {
1174     sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1175     return 1;
1176   }
1177   /* Log in */
1178   c->who = user;
1179   c->cookie = vec[0];
1180   c->rights = rights;
1181   if(strcmp(host, "local"))
1182     info("S%x %s connected with cookie from %s", c->tag, user, host);
1183   else
1184     c->rights |= RIGHT__LOCAL;
1185   /* Response contains username so client knows who they are acting as */
1186   sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
1187   return 1;
1188 }
1189
1190 static int c_make_cookie(struct conn *c,
1191                          char attribute((unused)) **vec,
1192                          int attribute((unused)) nvec) {
1193   const char *cookie = make_cookie(c->who);
1194
1195   if(cookie)
1196     sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cookie));
1197   else
1198     sink_writes(ev_writer_sink(c->w), "550 Cannot create cookie\n");
1199   return 1;
1200 }
1201
1202 static int c_revoke(struct conn *c,
1203                     char attribute((unused)) **vec,
1204                     int attribute((unused)) nvec) {
1205   if(c->cookie) {
1206     revoke_cookie(c->cookie);
1207     sink_writes(ev_writer_sink(c->w), "250 OK\n");
1208   } else
1209     sink_writes(ev_writer_sink(c->w), "550 Did not log in with cookie\n");
1210   return 1;
1211 }
1212
1213 static int c_adduser(struct conn *c,
1214                      char **vec,
1215                      int nvec) {
1216   const char *rights;
1217
1218   if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1219     error(0, "S%x: remote adduser", c->tag);
1220     sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1221     return 1;
1222   }
1223   if(nvec > 2) {
1224     rights = vec[2];
1225     if(parse_rights(vec[2], 0, 1)) {
1226       sink_writes(ev_writer_sink(c->w), "550 Invalid rights list\n");
1227       return -1;
1228     }
1229   } else
1230     rights = config->default_rights;
1231   if(trackdb_adduser(vec[0], vec[1], rights,
1232                      0/*email*/, 0/*confirmation*/))
1233     sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1234   else
1235     sink_writes(ev_writer_sink(c->w), "250 User created\n");
1236   return 1;
1237 }
1238
1239 static int c_deluser(struct conn *c,
1240                      char **vec,
1241                      int attribute((unused)) nvec) {
1242   struct conn *d;
1243
1244   if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1245     error(0, "S%x: remote deluser", c->tag);
1246     sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1247     return 1;
1248   }
1249   if(trackdb_deluser(vec[0])) {
1250     sink_writes(ev_writer_sink(c->w), "550 Cannot delete user\n");
1251     return 1;
1252   }
1253   /* Zap connections belonging to deleted user */
1254   for(d = connections; d; d = d->next)
1255     if(!strcmp(d->who, vec[0]))
1256       d->rights = 0;
1257   sink_writes(ev_writer_sink(c->w), "250 User deleted\n");
1258   return 1;
1259 }
1260
1261 static int c_edituser(struct conn *c,
1262                       char **vec,
1263                       int attribute((unused)) nvec) {
1264   struct conn *d;
1265
1266   if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1267     error(0, "S%x: remote edituser", c->tag);
1268     sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1269     return 1;
1270   }
1271   /* RIGHT_ADMIN can do anything; otherwise you can only set your own email
1272    * address and password. */
1273   if((c->rights & RIGHT_ADMIN)
1274      || (!strcmp(c->who, vec[0])
1275          && (!strcmp(vec[1], "email")
1276              || !strcmp(vec[1], "password")))) {
1277     if(trackdb_edituserinfo(vec[0], vec[1], vec[2])) {
1278       sink_writes(ev_writer_sink(c->w), "550 Failed to change setting\n");
1279       return 1;
1280     }
1281     if(!strcmp(vec[1], "password")) {
1282       /* Zap all connections for this user after a password change */
1283       for(d = connections; d; d = d->next)
1284         if(!strcmp(d->who, vec[0]))
1285           d->rights = 0;
1286     } else if(!strcmp(vec[1], "rights")) {
1287       /* Update rights for this user */
1288       rights_type r;
1289
1290       if(parse_rights(vec[2], &r, 1))
1291         for(d = connections; d; d = d->next)
1292           if(!strcmp(d->who, vec[0]))
1293             d->rights = r;
1294     }
1295     sink_writes(ev_writer_sink(c->w), "250 OK\n");
1296   } else {
1297     error(0, "%s attempted edituser but lacks required rights", c->who);
1298     sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
1299   }
1300   return 1;
1301 }
1302
1303 static int c_userinfo(struct conn *c,
1304                       char attribute((unused)) **vec,
1305                       int attribute((unused)) nvec) {
1306   struct kvp *k;
1307   const char *value;
1308
1309   /* We allow remote querying of rights so that clients can figure out what
1310    * they're allowed to do */
1311   if(!config->remote_userman
1312      && !(c->rights & RIGHT__LOCAL)
1313      && strcmp(vec[1], "rights")) {
1314     error(0, "S%x: remote userinfo %s %s", c->tag, vec[0], vec[1]);
1315     sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1316     return 1;
1317   }
1318   /* RIGHT_ADMIN allows anything; otherwise you can only get your own email
1319    * address and rights list. */
1320   if((c->rights & RIGHT_ADMIN)
1321      || (!strcmp(c->who, vec[0])
1322          && (!strcmp(vec[1], "email")
1323              || !strcmp(vec[1], "rights")))) {
1324     if((k = trackdb_getuserinfo(vec[0])))
1325       if((value = kvp_get(k, vec[1])))
1326         sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(value));
1327       else
1328         sink_writes(ev_writer_sink(c->w), "555 Not set\n");
1329     else
1330       sink_writes(ev_writer_sink(c->w), "550 No such user\n");
1331   } else {
1332     error(0, "%s attempted userinfo but lacks required rights", c->who);
1333     sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
1334   }
1335   return 1;
1336 }
1337
1338 static int c_users(struct conn *c,
1339                    char attribute((unused)) **vec,
1340                    int attribute((unused)) nvec) {
1341   /* TODO de-dupe with c_tags */
1342   char **users = trackdb_listusers();
1343
1344   sink_writes(ev_writer_sink(c->w), "253 User list follows\n");
1345   while(*users) {
1346     sink_printf(ev_writer_sink(c->w), "%s%s\n",
1347                 **users == '.' ? "." : "", *users);
1348     ++users;
1349   }
1350   sink_writes(ev_writer_sink(c->w), ".\n");
1351   return 1;                             /* completed */
1352 }
1353
1354 /** @brief Base64 mapping table for confirmation strings
1355  *
1356  * This is used with generic_to_base64() and generic_base64().  We cannot use
1357  * the MIME table as that contains '+' and '=' which get quoted when
1358  * URL-encoding.  (The CGI still does the URL encoding but it is desirable to
1359  * avoid it being necessary.)
1360  */
1361 static const char confirm_base64_table[] =
1362   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/.*";
1363
1364 static int c_register(struct conn *c,
1365                       char **vec,
1366                       int attribute((unused)) nvec) {
1367   char *buf, *cs;
1368   size_t bufsize;
1369   int offset;
1370
1371   /* The confirmation string is base64(username;nonce) */
1372   bufsize = strlen(vec[0]) + CONFIRM_SIZE + 2;
1373   buf = xmalloc_noptr(bufsize);
1374   offset = byte_snprintf(buf, bufsize, "%s;", vec[0]);
1375   gcry_randomize(buf + offset, CONFIRM_SIZE, GCRY_STRONG_RANDOM);
1376   cs = generic_to_base64((uint8_t *)buf, offset + CONFIRM_SIZE,
1377                          confirm_base64_table);
1378   if(trackdb_adduser(vec[0], vec[1], config->default_rights, vec[2], cs))
1379     sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1380   else
1381     sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cs));
1382   return 1;
1383 }
1384
1385 static int c_confirm(struct conn *c,
1386                      char **vec,
1387                      int attribute((unused)) nvec) {
1388   size_t nuser;
1389   char *user, *sep;
1390   rights_type rights;
1391   const char *host;
1392
1393   /* Get some kind of peer identifcation */
1394   if(!(host = connection_host(c))) {
1395     sink_writes(ev_writer_sink(c->w), "530 Authentication failure\n");
1396     return 1;
1397   }
1398   if(!(user = generic_base64(vec[0], &nuser, confirm_base64_table))
1399      || !(sep = memchr(user, ';', nuser))) {
1400     sink_writes(ev_writer_sink(c->w), "550 Malformed confirmation string\n");
1401     return 1;
1402   }
1403   *sep = 0;
1404   if(trackdb_confirm(user, vec[0], &rights))
1405     sink_writes(ev_writer_sink(c->w), "550 Incorrect confirmation string\n");
1406   else {
1407     c->who = user;
1408     c->cookie = 0;
1409     c->rights = rights;
1410     if(strcmp(host, "local"))
1411       info("S%x %s confirmed from %s", c->tag, user, host);
1412     else
1413       c->rights |= RIGHT__LOCAL;
1414     /* Response contains username so client knows who they are acting as */
1415     sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
1416   }
1417   return 1;
1418 }
1419
1420 static int sent_reminder(ev_source attribute((unused)) *ev,
1421                          pid_t attribute((unused)) pid,
1422                          int status,
1423                          const struct rusage attribute((unused)) *rusage,
1424                          void *u) {
1425   struct conn *const c = u;
1426
1427   /* Tell the client what went down */ 
1428   if(!status) {
1429     sink_writes(ev_writer_sink(c->w), "250 OK\n");
1430   } else {
1431     error(0, "reminder subprocess %s", wstat(status));
1432     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1433   }
1434   /* Re-enable this connection */
1435   ev_reader_enable(c->r);
1436   return 0;
1437 }
1438
1439 static int c_reminder(struct conn *c,
1440                       char **vec,
1441                       int attribute((unused)) nvec) {
1442   struct kvp *k;
1443   const char *password, *email, *text, *encoding, *charset, *content_type;
1444   const time_t *last;
1445   time_t now;
1446   pid_t pid;
1447   
1448   static hash *last_reminder;
1449
1450   if(!config->mail_sender) {
1451     error(0, "cannot send password reminders because mail_sender not set");
1452     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1453     return 1;
1454   }
1455   if(!(k = trackdb_getuserinfo(vec[0]))) {
1456     error(0, "reminder for user '%s' who does not exist", vec[0]);
1457     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1458     return 1;
1459   }
1460   if(!(email = kvp_get(k, "email"))
1461      || !strchr(email, '@')) {
1462     error(0, "user '%s' has no valid email address", vec[0]);
1463     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1464     return 1;
1465   }
1466   if(!(password = kvp_get(k, "password"))
1467      || !*password) {
1468     error(0, "user '%s' has no password", vec[0]);
1469     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1470     return 1;
1471   }
1472   /* Rate-limit reminders.  This hash is bounded in size by the number of
1473    * users.  If this is actually a problem for anyone then we can periodically
1474    * clean it. */
1475   if(!last_reminder)
1476     last_reminder = hash_new(sizeof (time_t));
1477   last = hash_find(last_reminder, vec[0]);
1478   time(&now);
1479   if(last && now < *last + config->reminder_interval) {
1480     error(0, "sent a password reminder to '%s' too recently", vec[0]);
1481     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1482     return 1;
1483   }
1484   /* Send the reminder */
1485   /* TODO this should be templatized and to some extent merged with
1486    * the code in act_register() */
1487   byte_xasprintf((char **)&text,
1488 "Someone requested that you be sent a reminder of your DisOrder password.\n"
1489 "Your password is:\n"
1490 "\n"
1491 "  %s\n", password);
1492   if(!(text = mime_encode_text(text, &charset, &encoding)))
1493     fatal(0, "cannot encode email");
1494   byte_xasprintf((char **)&content_type, "text/plain;charset=%s",
1495                  quote822(charset, 0));
1496   pid = sendmail_subprocess("", config->mail_sender, email,
1497                             "DisOrder password reminder",
1498                             encoding, content_type, text);
1499   if(pid < 0) {
1500     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1501     return 1;
1502   }
1503   hash_add(last_reminder, vec[0], &now, HASH_INSERT_OR_REPLACE);
1504   info("sending a passsword reminder to user '%s'", vec[0]);
1505   /* We can only continue when the subprocess finishes */
1506   ev_child(c->ev, pid, 0, sent_reminder, c);
1507   return 0;
1508 }
1509
1510 static int c_schedule_list(struct conn *c,
1511                            char attribute((unused)) **vec,
1512                            int attribute((unused)) nvec) {
1513   char **ids = schedule_list(0);
1514   sink_writes(ev_writer_sink(c->w), "253 ID list follows\n");
1515   while(*ids)
1516     sink_printf(ev_writer_sink(c->w), "%s\n", *ids++);
1517   sink_writes(ev_writer_sink(c->w), ".\n");
1518   return 1;                             /* completed */
1519 }
1520
1521 static int c_schedule_get(struct conn *c,
1522                           char **vec,
1523                           int attribute((unused)) nvec) {
1524   struct kvp *actiondata = schedule_get(vec[0]), *k;
1525
1526   if(!actiondata) {
1527     sink_writes(ev_writer_sink(c->w), "555 No such event\n");
1528     return 1;                           /* completed */
1529   }
1530   /* Scheduled events are public information.  Anyone with RIGHT_READ can see
1531    * them. */
1532   sink_writes(ev_writer_sink(c->w), "253 Event information follows\n");
1533   for(k = actiondata; k; k = k->next)
1534     sink_printf(ev_writer_sink(c->w), " %s %s\n",
1535                 quoteutf8(k->name),  quoteutf8(k->value));
1536   sink_writes(ev_writer_sink(c->w), ".\n");
1537   return 1;                             /* completed */
1538 }
1539
1540 static int c_schedule_del(struct conn *c,
1541                           char **vec,
1542                           int attribute((unused)) nvec) {
1543   struct kvp *actiondata = schedule_get(vec[0]);
1544
1545   if(!actiondata) {
1546     sink_writes(ev_writer_sink(c->w), "555 No such event\n");
1547     return 1;                           /* completed */
1548   }
1549   /* If you have admin rights you can delete anything.  If you don't then you
1550    * can only delete your own scheduled events. */
1551   if(!(c->rights & RIGHT_ADMIN)) {
1552     const char *who = kvp_get(actiondata, "who");
1553
1554     if(!who || !c->who || strcmp(who, c->who)) {
1555       sink_writes(ev_writer_sink(c->w), "551 Not authorized\n");
1556       return 1;                         /* completed */
1557     }
1558   }
1559   if(schedule_del(vec[0]))
1560     sink_writes(ev_writer_sink(c->w), "550 Could not delete scheduled event\n");
1561   else
1562     sink_writes(ev_writer_sink(c->w), "250 Deleted\n");
1563   return 1;                             /* completed */
1564 }
1565
1566 static int c_schedule_add(struct conn *c,
1567                           char **vec,
1568                           int nvec) {
1569   struct kvp *actiondata = 0;
1570   const char *id;
1571
1572   /* Standard fields */
1573   kvp_set(&actiondata, "who", c->who);
1574   kvp_set(&actiondata, "when", vec[0]);
1575   kvp_set(&actiondata, "priority", vec[1]);
1576   kvp_set(&actiondata, "action", vec[2]);
1577   /* Action-dependent fields */
1578   if(!strcmp(vec[2], "play")) {
1579     if(nvec != 4) {
1580       sink_writes(ev_writer_sink(c->w), "550 Wrong number of arguments\n");
1581       return 1;
1582     }
1583     if(!trackdb_exists(vec[3])) {
1584       sink_writes(ev_writer_sink(c->w), "550 Track is not in database\n");
1585       return 1;
1586     }
1587     kvp_set(&actiondata, "track", vec[3]);
1588   } else if(!strcmp(vec[2], "set-global")) {
1589     if(nvec < 4 || nvec > 5) {
1590       sink_writes(ev_writer_sink(c->w), "550 Wrong number of arguments\n");
1591       return 1;
1592     }
1593     kvp_set(&actiondata, "key", vec[3]);
1594     if(nvec > 4)
1595       kvp_set(&actiondata, "value", vec[4]);
1596   } else {
1597     sink_writes(ev_writer_sink(c->w), "550 Unknown action\n");
1598     return 1;
1599   }
1600   /* schedule_add() checks user rights */
1601   id = schedule_add(c->ev, actiondata);
1602   if(!id)
1603     sink_writes(ev_writer_sink(c->w), "550 Cannot add scheduled event\n");
1604   else
1605     sink_printf(ev_writer_sink(c->w), "252 %s\n", id);
1606   return 1;
1607 }
1608
1609 static const struct command {
1610   /** @brief Command name */
1611   const char *name;
1612
1613   /** @brief Minimum number of arguments */
1614   int minargs;
1615
1616   /** @brief Maximum number of arguments */
1617   int maxargs;
1618
1619   /** @brief Function to process command */
1620   int (*fn)(struct conn *, char **, int);
1621
1622   /** @brief Rights required to execute command
1623    *
1624    * 0 means that the command can be issued without logging in.  If multiple
1625    * bits are listed here any of those rights will do.
1626    */
1627   rights_type rights;
1628 } commands[] = {
1629   { "adduser",        2, 3,       c_adduser,        RIGHT_ADMIN|RIGHT__LOCAL },
1630   { "allfiles",       0, 2,       c_allfiles,       RIGHT_READ },
1631   { "confirm",        1, 1,       c_confirm,        0 },
1632   { "cookie",         1, 1,       c_cookie,         0 },
1633   { "deluser",        1, 1,       c_deluser,        RIGHT_ADMIN|RIGHT__LOCAL },
1634   { "dirs",           0, 2,       c_dirs,           RIGHT_READ },
1635   { "disable",        0, 1,       c_disable,        RIGHT_GLOBAL_PREFS },
1636   { "edituser",       3, 3,       c_edituser,       RIGHT_ADMIN|RIGHT_USERINFO },
1637   { "enable",         0, 0,       c_enable,         RIGHT_GLOBAL_PREFS },
1638   { "enabled",        0, 0,       c_enabled,        RIGHT_READ },
1639   { "exists",         1, 1,       c_exists,         RIGHT_READ },
1640   { "files",          0, 2,       c_files,          RIGHT_READ },
1641   { "get",            2, 2,       c_get,            RIGHT_READ },
1642   { "get-global",     1, 1,       c_get_global,     RIGHT_READ },
1643   { "length",         1, 1,       c_length,         RIGHT_READ },
1644   { "log",            0, 0,       c_log,            RIGHT_READ },
1645   { "make-cookie",    0, 0,       c_make_cookie,    RIGHT_READ },
1646   { "move",           2, 2,       c_move,           RIGHT_MOVE__MASK },
1647   { "moveafter",      1, INT_MAX, c_moveafter,      RIGHT_MOVE__MASK },
1648   { "new",            0, 1,       c_new,            RIGHT_READ },
1649   { "nop",            0, 0,       c_nop,            0 },
1650   { "part",           3, 3,       c_part,           RIGHT_READ },
1651   { "pause",          0, 0,       c_pause,          RIGHT_PAUSE },
1652   { "play",           1, 1,       c_play,           RIGHT_PLAY },
1653   { "playing",        0, 0,       c_playing,        RIGHT_READ },
1654   { "prefs",          1, 1,       c_prefs,          RIGHT_READ },
1655   { "queue",          0, 0,       c_queue,          RIGHT_READ },
1656   { "random-disable", 0, 0,       c_random_disable, RIGHT_GLOBAL_PREFS },
1657   { "random-enable",  0, 0,       c_random_enable,  RIGHT_GLOBAL_PREFS },
1658   { "random-enabled", 0, 0,       c_random_enabled, RIGHT_READ },
1659   { "recent",         0, 0,       c_recent,         RIGHT_READ },
1660   { "reconfigure",    0, 0,       c_reconfigure,    RIGHT_ADMIN },
1661   { "register",       3, 3,       c_register,       RIGHT_REGISTER|RIGHT__LOCAL },
1662   { "reminder",       1, 1,       c_reminder,       RIGHT__LOCAL },
1663   { "remove",         1, 1,       c_remove,         RIGHT_REMOVE__MASK },
1664   { "rescan",         0, INT_MAX, c_rescan,         RIGHT_RESCAN },
1665   { "resolve",        1, 1,       c_resolve,        RIGHT_READ },
1666   { "resume",         0, 0,       c_resume,         RIGHT_PAUSE },
1667   { "revoke",         0, 0,       c_revoke,         RIGHT_READ },
1668   { "rtp-address",    0, 0,       c_rtp_address,    0 },
1669   { "schedule-add",   3, INT_MAX, c_schedule_add,   RIGHT_READ },
1670   { "schedule-del",   1, 1,       c_schedule_del,   RIGHT_READ },
1671   { "schedule-get",   1, 1,       c_schedule_get,   RIGHT_READ },
1672   { "schedule-list",  0, 0,       c_schedule_list,  RIGHT_READ },
1673   { "scratch",        0, 1,       c_scratch,        RIGHT_SCRATCH__MASK },
1674   { "search",         1, 1,       c_search,         RIGHT_READ },
1675   { "set",            3, 3,       c_set,            RIGHT_PREFS, },
1676   { "set-global",     2, 2,       c_set_global,     RIGHT_GLOBAL_PREFS },
1677   { "shutdown",       0, 0,       c_shutdown,       RIGHT_ADMIN },
1678   { "stats",          0, 0,       c_stats,          RIGHT_READ },
1679   { "tags",           0, 0,       c_tags,           RIGHT_READ },
1680   { "unset",          2, 2,       c_set,            RIGHT_PREFS },
1681   { "unset-global",   1, 1,       c_set_global,     RIGHT_GLOBAL_PREFS },
1682   { "user",           2, 2,       c_user,           0 },
1683   { "userinfo",       2, 2,       c_userinfo,       RIGHT_READ },
1684   { "users",          0, 0,       c_users,          RIGHT_READ },
1685   { "version",        0, 0,       c_version,        RIGHT_READ },
1686   { "volume",         0, 2,       c_volume,         RIGHT_READ|RIGHT_VOLUME }
1687 };
1688
1689 static void command_error(const char *msg, void *u) {
1690   struct conn *c = u;
1691
1692   sink_printf(ev_writer_sink(c->w), "500 parse error: %s\n", msg);
1693 }
1694
1695 /* process a command.  Return 1 if complete, 0 if incomplete. */
1696 static int command(struct conn *c, char *line) {
1697   char **vec;
1698   int nvec, n;
1699
1700   D(("server command %s", line));
1701   /* We force everything into NFC as early as possible */
1702   if(!(line = utf8_compose_canon(line, strlen(line), 0))) {
1703     sink_writes(ev_writer_sink(c->w), "500 cannot normalize command\n");
1704     return 1;
1705   }
1706   if(!(vec = split(line, &nvec, SPLIT_QUOTES, command_error, c))) {
1707     sink_writes(ev_writer_sink(c->w), "500 cannot parse command\n");
1708     return 1;
1709   }
1710   if(nvec == 0) {
1711     sink_writes(ev_writer_sink(c->w), "500 do what?\n");
1712     return 1;
1713   }
1714   if((n = TABLE_FIND(commands, struct command, name, vec[0])) < 0)
1715     sink_writes(ev_writer_sink(c->w), "500 unknown command\n");
1716   else {
1717     if(commands[n].rights
1718        && !(c->rights & commands[n].rights)) {
1719       error(0, "%s attempted %s but lacks required rights", c->who ? c->who : "NULL",
1720             commands[n].name);
1721       sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
1722       return 1;
1723     }
1724     ++vec;
1725     --nvec;
1726     if(nvec < commands[n].minargs) {
1727       sink_writes(ev_writer_sink(c->w), "500 missing argument(s)\n");
1728       return 1;
1729     }
1730     if(nvec > commands[n].maxargs) {
1731       sink_writes(ev_writer_sink(c->w), "500 too many arguments\n");
1732       return 1;
1733     }
1734     return commands[n].fn(c, vec, nvec);
1735   }
1736   return 1;                     /* completed */
1737 }
1738
1739 /* redirect to the right reader callback for our current state */
1740 static int redirect_reader_callback(ev_source *ev,
1741                                     ev_reader *reader,
1742                                     void *ptr,
1743                                     size_t bytes,
1744                                     int eof,
1745                                     void *u) {
1746   struct conn *c = u;
1747
1748   return c->reader(ev, reader, ptr, bytes, eof, u);
1749 }
1750
1751 /* the main command reader */
1752 static int reader_callback(ev_source attribute((unused)) *ev,
1753                            ev_reader *reader,
1754                            void *ptr,
1755                            size_t bytes,
1756                            int eof,
1757                            void *u) {
1758   struct conn *c = u;
1759   char *eol;
1760   int complete;
1761
1762   D(("server reader_callback"));
1763   while((eol = memchr(ptr, '\n', bytes))) {
1764     *eol++ = 0;
1765     ev_reader_consume(reader, eol - (char *)ptr);
1766     complete = command(c, ptr);
1767     bytes -= (eol - (char *)ptr);
1768     ptr = eol;
1769     if(!complete) {
1770       /* the command had better have set a new reader callback */
1771       if(bytes || eof)
1772         /* there are further bytes to read, or we are at eof; arrange for the
1773          * command's reader callback to handle them */
1774         return ev_reader_incomplete(reader);
1775       /* nothing's going on right now */
1776       return 0;
1777     }
1778     /* command completed, we can go around and handle the next one */
1779   }
1780   if(eof) {
1781     if(bytes)
1782       error(0, "S%x unterminated line", c->tag);
1783     D(("normal reader close"));
1784     c->r = 0;
1785     if(c->w) {
1786       D(("close associated writer"));
1787       ev_writer_close(c->w);
1788       c->w = 0;
1789     }
1790     remove_connection(c);
1791   }
1792   return 0;
1793 }
1794
1795 static int listen_callback(ev_source *ev,
1796                            int fd,
1797                            const struct sockaddr attribute((unused)) *remote,
1798                            socklen_t attribute((unused)) rlen,
1799                            void *u) {
1800   const struct listener *l = u;
1801   struct conn *c = xmalloc(sizeof *c);
1802   static unsigned tags;
1803
1804   D(("server listen_callback fd %d (%s)", fd, l->name));
1805   nonblock(fd);
1806   cloexec(fd);
1807   c->tag = tags++;
1808   c->ev = ev;
1809   c->w = ev_writer_new(ev, fd, writer_error, c,
1810                        "client writer");
1811   c->r = ev_reader_new(ev, fd, redirect_reader_callback, reader_error, c,
1812                        "client reader");
1813   ev_tie(c->r, c->w);
1814   c->fd = fd;
1815   c->reader = reader_callback;
1816   c->l = l;
1817   c->rights = 0;
1818   gcry_randomize(c->nonce, sizeof c->nonce, GCRY_STRONG_RANDOM);
1819   sink_printf(ev_writer_sink(c->w), "231 %d %s %s\n",
1820               2,
1821               config->authorization_algorithm,
1822               hex(c->nonce, sizeof c->nonce));
1823   return 0;
1824 }
1825
1826 int server_start(ev_source *ev, int pf,
1827                  size_t socklen, const struct sockaddr *sa,
1828                  const char *name) {
1829   int fd;
1830   struct listener *l = xmalloc(sizeof *l);
1831   static const int one = 1;
1832
1833   D(("server_init socket %s", name));
1834   fd = xsocket(pf, SOCK_STREAM, 0);
1835   xsetsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
1836   if(bind(fd, sa, socklen) < 0) {
1837     error(errno, "error binding to %s", name);
1838     return -1;
1839   }
1840   xlisten(fd, 128);
1841   nonblock(fd);
1842   cloexec(fd);
1843   l->name = name;
1844   l->pf = pf;
1845   if(ev_listen(ev, fd, listen_callback, l, "server listener"))
1846     exit(EXIT_FAILURE);
1847   return fd;
1848 }
1849
1850 int server_stop(ev_source *ev, int fd) {
1851   xclose(fd);
1852   return ev_listen_cancel(ev, fd);
1853 }
1854
1855 /*
1856 Local Variables:
1857 c-basic-offset:2
1858 comment-column:40
1859 fill-column:79
1860 End:
1861 */