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