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