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