chiark / gitweb /
6866764419cee840879da5ef3766a7dd64a484f0
[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       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   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     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     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     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     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   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   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   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     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       error(0, "S%x error calling getnameinfo: %s", c->tag, gai_strerror(n));
543       return 0;
544     }
545     return xstrdup(host);
546   } else
547     return "local";
548 }
549
550 static int c_user(struct conn *c,
551                   char **vec,
552                   int attribute((unused)) nvec) {
553   struct kvp *k;
554   const char *res, *host, *password;
555   rights_type rights;
556
557   if(c->who) {
558     sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
559     return 1;
560   }
561   /* get connection data */
562   if(!(host = connection_host(c))) {
563     sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
564     return 1;
565   }
566   /* find the user */
567   k = trackdb_getuserinfo(vec[0]);
568   /* reject nonexistent users */
569   if(!k) {
570     error(0, "S%x unknown user '%s' from %s", c->tag, vec[0], host);
571     sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
572     return 1;
573   }
574   /* reject unconfirmed users */
575   if(kvp_get(k, "confirmation")) {
576     error(0, "S%x unconfirmed user '%s' from %s", c->tag, vec[0], host);
577     sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
578     return 1;
579   }
580   password = kvp_get(k, "password");
581   if(!password) password = "";
582   if(parse_rights(kvp_get(k, "rights"), &rights, 1)) {
583     error(0, "error parsing rights for %s", vec[0]);
584     sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
585     return 1;
586   }
587   /* check whether the response is right */
588   res = authhash(c->nonce, sizeof c->nonce, password,
589                  config->authorization_algorithm);
590   if(wideopen || (res && !strcmp(res, vec[1]))) {
591     c->who = vec[0];
592     c->rights = rights;
593     /* currently we only bother logging remote connections */
594     if(strcmp(host, "local"))
595       info("S%x %s connected from %s", c->tag, vec[0], host);
596     else
597       c->rights |= RIGHT__LOCAL;
598     sink_writes(ev_writer_sink(c->w), "230 OK\n");
599     return 1;
600   }
601   /* oops, response was wrong */
602   info("S%x authentication failure for %s from %s", c->tag, vec[0], host);
603   sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
604   return 1;
605 }
606
607 static int c_recent(struct conn *c,
608                     char attribute((unused)) **vec,
609                     int attribute((unused)) nvec) {
610   const struct queue_entry *q;
611
612   sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
613   for(q = phead.next; q != &phead; q = q->next)
614     sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
615   sink_writes(ev_writer_sink(c->w), ".\n");
616   return 1;                             /* completed */
617 }
618
619 static int c_queue(struct conn *c,
620                    char attribute((unused)) **vec,
621                    int attribute((unused)) nvec) {
622   struct queue_entry *q;
623   time_t when = 0;
624   const char *l;
625   long length;
626
627   sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
628   if(playing_is_enabled() && !paused) {
629     if(playing) {
630       queue_fix_sofar(playing);
631       if((l = trackdb_get(playing->track, "_length"))
632          && (length = atol(l))) {
633         xtime(&when);
634         when += length - playing->sofar + config->gap;
635       }
636     } else
637       /* Nothing is playing but playing is enabled, so whatever is
638        * first in the queue can be expected to start immediately. */
639       xtime(&when);
640   }
641   for(q = qhead.next; q != &qhead; q = q->next) {
642     /* fill in estimated start time */
643     q->expected = when;
644     sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
645     /* update for next track */
646     if(when) {
647       if((l = trackdb_get(q->track, "_length"))
648          && (length = atol(l)))
649         when += length + config->gap;
650       else
651         when = 0;
652     }
653   }
654   sink_writes(ev_writer_sink(c->w), ".\n");
655   return 1;                             /* completed */
656 }
657
658 static int output_list(struct conn *c, char **vec) {
659   while(*vec)
660     sink_printf(ev_writer_sink(c->w), "%s\n", *vec++);
661   sink_writes(ev_writer_sink(c->w), ".\n");
662   return 1;
663 }
664
665 static int files_dirs(struct conn *c,
666                       char **vec,
667                       int nvec,
668                       enum trackdb_listable what) {
669   const char *dir, *re, *errstr;
670   int erroffset;
671   pcre *rec;
672   char **fvec, *key;
673   
674   switch(nvec) {
675   case 0: dir = 0; re = 0; break;
676   case 1: dir = vec[0]; re = 0; break;
677   case 2: dir = vec[0]; re = vec[1]; break;
678   default: abort();
679   }
680   /* A bit of a bodge to make sure the args don't trample on cache keys */
681   if(dir && strchr(dir, '\n')) {
682     sink_writes(ev_writer_sink(c->w), "550 invalid directory name\n");
683     return 1;
684   }
685   if(re && strchr(re, '\n')) {
686     sink_writes(ev_writer_sink(c->w), "550 invalid regexp\n");
687     return 1;
688   }
689   /* We bother eliminating "" because the web interface is relatively
690    * likely to send it */
691   if(re && *re) {
692     byte_xasprintf(&key, "%d\n%s\n%s", (int)what, dir ? dir : "", re);
693     fvec = (char **)cache_get(&cache_files_type, key);
694     if(fvec) {
695       /* Got a cache hit, don't store the answer in the cache */
696       key = 0;
697       ++cache_files_hits;
698       rec = 0;                          /* quieten compiler */
699     } else {
700       /* Cache miss, we'll do the lookup and key != 0 so we'll store the answer
701        * in the cache. */
702       if(!(rec = pcre_compile(re, PCRE_CASELESS|PCRE_UTF8,
703                               &errstr, &erroffset, 0))) {
704         sink_printf(ev_writer_sink(c->w), "550 Error compiling regexp: %s\n",
705                     errstr);
706         return 1;
707       }
708       /* It only counts as a miss if the regexp was valid. */
709       ++cache_files_misses;
710     }
711   } else {
712     /* No regexp, don't bother caching the result */
713     rec = 0;
714     key = 0;
715     fvec = 0;
716   }
717   if(!fvec) {
718     /* No cache hit (either because a miss, or because we did not look) so do
719      * the lookup */
720     if(dir && *dir)
721       fvec = trackdb_list(dir, 0, what, rec);
722     else
723       fvec = trackdb_list(0, 0, what, rec);
724   }
725   if(key)
726     /* Put the answer in the cache */
727     cache_put(&cache_files_type, key, fvec);
728   sink_writes(ev_writer_sink(c->w), "253 Listing follow\n");
729   return output_list(c, fvec);
730 }
731
732 static int c_files(struct conn *c,
733                   char **vec,
734                   int nvec) {
735   return files_dirs(c, vec, nvec, trackdb_files);
736 }
737
738 static int c_dirs(struct conn *c,
739                   char **vec,
740                   int nvec) {
741   return files_dirs(c, vec, nvec, trackdb_directories);
742 }
743
744 static int c_allfiles(struct conn *c,
745                       char **vec,
746                       int nvec) {
747   return files_dirs(c, vec, nvec, trackdb_directories|trackdb_files);
748 }
749
750 static int c_get(struct conn *c,
751                  char **vec,
752                  int attribute((unused)) nvec) {
753   const char *v, *track;
754
755   if(!(track = trackdb_resolve(vec[0]))) {
756     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
757     return 1;
758   }
759   if(vec[1][0] != '_' && (v = trackdb_get(track, vec[1])))
760     sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
761   else
762     sink_writes(ev_writer_sink(c->w), "555 not found\n");
763   return 1;
764 }
765
766 static int c_length(struct conn *c,
767                  char **vec,
768                  int attribute((unused)) nvec) {
769   const char *track, *v;
770
771   if(!(track = trackdb_resolve(vec[0]))) {
772     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
773     return 1;
774   }
775   if((v = trackdb_get(track, "_length")))
776     sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(v));
777   else
778     sink_writes(ev_writer_sink(c->w), "550 not found\n");
779   return 1;
780 }
781
782 static int c_set(struct conn *c,
783                  char **vec,
784                  int attribute((unused)) nvec) {
785   const char *track;
786
787   if(!(track = trackdb_resolve(vec[0]))) {
788     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
789     return 1;
790   }
791   if(vec[1][0] != '_' && !trackdb_set(track, vec[1], vec[2]))
792     sink_writes(ev_writer_sink(c->w), "250 OK\n");
793   else
794     sink_writes(ev_writer_sink(c->w), "550 not found\n");
795   return 1;
796 }
797
798 static int c_prefs(struct conn *c,
799                    char **vec,
800                    int attribute((unused)) nvec) {
801   struct kvp *k;
802   const char *track;
803
804   if(!(track = trackdb_resolve(vec[0]))) {
805     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
806     return 1;
807   }
808   k = trackdb_get_all(track);
809   sink_writes(ev_writer_sink(c->w), "253 prefs follow\n");
810   for(; k; k = k->next)
811     if(k->name[0] != '_')               /* omit internal values */
812       sink_printf(ev_writer_sink(c->w),
813                   " %s %s\n", quoteutf8(k->name), quoteutf8(k->value));
814   sink_writes(ev_writer_sink(c->w), ".\n");
815   return 1;
816 }
817
818 static int c_exists(struct conn *c,
819                     char **vec,
820                     int attribute((unused)) nvec) {
821   /* trackdb_exists() does its own alias checking */
822   sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[trackdb_exists(vec[0])]);
823   return 1;
824 }
825
826 static void search_parse_error(const char *msg, void *u) {
827   *(const char **)u = msg;
828 }
829
830 static int c_search(struct conn *c,
831                           char **vec,
832                           int attribute((unused)) nvec) {
833   char **terms, **results;
834   int nterms, nresults, n;
835   const char *e = "unknown error";
836
837   /* This is a bit of a bodge.  Initially it's there to make the eclient
838    * interface a bit more convenient to add searching to, but it has the more
839    * compelling advantage that if everything uses it, then interpretation of
840    * user-supplied search strings will be the same everywhere. */
841   if(!(terms = split(vec[0], &nterms, SPLIT_QUOTES, search_parse_error, &e))) {
842     sink_printf(ev_writer_sink(c->w), "550 %s\n", e);
843   } else {
844     results = trackdb_search(terms, nterms, &nresults);
845     sink_printf(ev_writer_sink(c->w), "253 %d matches\n", nresults);
846     for(n = 0; n < nresults; ++n)
847       sink_printf(ev_writer_sink(c->w), "%s\n", results[n]);
848     sink_writes(ev_writer_sink(c->w), ".\n");
849   }
850   return 1;
851 }
852
853 static int c_random_enable(struct conn *c,
854                            char attribute((unused)) **vec,
855                            int attribute((unused)) nvec) {
856   enable_random(c->who, c->ev);
857   /* Enable implicitly unpauses if there is nothing playing */
858   if(paused && !playing) resume_playing(c->who);
859   sink_writes(ev_writer_sink(c->w), "250 OK\n");
860   return 1;                     /* completed */
861 }
862
863 static int c_random_disable(struct conn *c,
864                             char attribute((unused)) **vec,
865                             int attribute((unused)) nvec) {
866   disable_random(c->who);
867   sink_writes(ev_writer_sink(c->w), "250 OK\n");
868   return 1;                     /* completed */
869 }
870
871 static int c_random_enabled(struct conn *c,
872                             char attribute((unused)) **vec,
873                             int attribute((unused)) nvec) {
874   sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[random_is_enabled()]);
875   return 1;                     /* completed */
876 }
877
878 static void got_stats(char *stats, void *u) {
879   struct conn *const c = u;
880
881   sink_printf(ev_writer_sink(c->w), "253 stats\n%s\n.\n", stats);
882   /* Now we can start processing commands again */
883   ev_reader_enable(c->r);
884 }
885
886 static int c_stats(struct conn *c,
887                    char attribute((unused)) **vec,
888                    int attribute((unused)) nvec) {
889   trackdb_stats_subprocess(c->ev, got_stats, c);
890   return 0;                             /* not yet complete */
891 }
892
893 static int c_volume(struct conn *c,
894                     char **vec,
895                     int nvec) {
896   int l, r, set;
897   char lb[32], rb[32];
898   rights_type rights;
899
900   switch(nvec) {
901   case 0:
902     set = 0;
903     break;
904   case 1:
905     l = r = atoi(vec[0]);
906     set = 1;
907     break;
908   case 2:
909     l = atoi(vec[0]);
910     r = atoi(vec[1]);
911     set = 1;
912     break;
913   default:
914     abort();
915   }
916   rights = set ? RIGHT_VOLUME : RIGHT_READ;
917   if(!(c->rights & rights)) {
918     error(0, "%s attempted to set volume but lacks required rights", c->who);
919     sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
920     return 1;
921   }
922   if(!api || !api->set_volume) {
923     sink_writes(ev_writer_sink(c->w), "550 error accessing mixer\n");
924     return 1;
925   }
926   (set ? api->set_volume : api->get_volume)(&l, &r);
927   sink_printf(ev_writer_sink(c->w), "252 %d %d\n", l, r);
928   if(l != volume_left || r != volume_right) {
929     volume_left = l;
930     volume_right = r;
931     snprintf(lb, sizeof lb, "%d", l);
932     snprintf(rb, sizeof rb, "%d", r);
933     eventlog("volume", lb, rb, (char *)0);
934   }
935   return 1;
936 }
937
938 /** @brief Called when data arrives on a log connection
939  *
940  * We just discard all such data.  The client may occasionally send data as a
941  * keepalive.
942  */
943 static int logging_reader_callback(ev_source attribute((unused)) *ev,
944                                    ev_reader *reader,
945                                    void attribute((unused)) *ptr,
946                                    size_t bytes,
947                                    int attribute((unused)) eof,
948                                    void attribute((unused)) *u) {
949   struct conn *c = u;
950
951   ev_reader_consume(reader, bytes);
952   if(eof) {
953     /* Oops, that's all for now */
954     D(("logging reader eof"));
955     if(c->w) {
956       D(("close writer"));
957       ev_writer_close(c->w);
958       c->w = 0;
959     }
960     c->r = 0;
961     remove_connection(c);
962   }
963   return 0;
964 }
965
966 static void logclient(const char *msg, void *user) {
967   struct conn *c = user;
968
969   if(!c->w || !c->r) {
970     /* This connection has gone up in smoke for some reason */
971     eventlog_remove(c->lo);
972     c->lo = 0;
973     return;
974   }
975   /* user_* messages are restricted */
976   if(!strncmp(msg, "user_", 5)) {
977     /* They are only sent to admin users */
978     if(!(c->rights & RIGHT_ADMIN))
979       return;
980     /* They are not sent over TCP connections unless remote user-management is
981      * enabled */
982     if(!config->remote_userman && !(c->rights & RIGHT__LOCAL))
983       return;
984   }
985   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" %s\n",
986               (uintmax_t)xtime(0), msg);
987 }
988
989 static int c_log(struct conn *c,
990                  char attribute((unused)) **vec,
991                  int attribute((unused)) nvec) {
992   time_t now;
993
994   sink_writes(ev_writer_sink(c->w), "254 OK\n");
995   /* pump out initial state */
996   xtime(&now);
997   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
998               (uintmax_t)now, 
999               playing_is_enabled() ? "enable_play" : "disable_play");
1000   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
1001               (uintmax_t)now, 
1002               random_is_enabled() ? "enable_random" : "disable_random");
1003   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
1004               (uintmax_t)now, 
1005               paused ? "pause" : "resume");
1006   if(playing)
1007     sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state playing\n",
1008                 (uintmax_t)now);
1009   /* Initial volume */
1010   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" volume %d %d\n",
1011               (uintmax_t)now, volume_left, volume_right);
1012   c->lo = xmalloc(sizeof *c->lo);
1013   c->lo->fn = logclient;
1014   c->lo->user = c;
1015   eventlog_add(c->lo);
1016   c->reader = logging_reader_callback;
1017   return 0;
1018 }
1019
1020 /** @brief Test whether a move is allowed
1021  * @param c Connection
1022  * @param qs List of IDs on queue
1023  * @param nqs Number of IDs
1024  * @return 0 if move is prohibited, non-0 if it is allowed
1025  */
1026 static int has_move_rights(struct conn *c, struct queue_entry **qs, int nqs) {
1027   for(; nqs > 0; ++qs, --nqs) {
1028     struct queue_entry *const q = *qs;
1029
1030     if(!right_movable(c->rights, c->who, q))
1031       return 0;
1032   }
1033   return 1;
1034 }
1035
1036 static int c_move(struct conn *c,
1037                   char **vec,
1038                   int attribute((unused)) nvec) {
1039   struct queue_entry *q;
1040   int n;
1041
1042   if(!(q = queue_find(vec[0]))) {
1043     sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1044     return 1;
1045   }
1046   if(!has_move_rights(c, &q, 1)) {
1047     error(0, "%s attempted move but lacks required rights", c->who);
1048     sink_writes(ev_writer_sink(c->w),
1049                 "510 Not authorized to move that track\n");
1050     return 1;
1051   }
1052   n = queue_move(q, atoi(vec[1]), c->who);
1053   sink_printf(ev_writer_sink(c->w), "252 %d\n", n);
1054   /* If we've moved to the head of the queue then prepare the track. */
1055   if(q == qhead.next)
1056     prepare(c->ev, q);
1057   return 1;
1058 }
1059
1060 static int c_moveafter(struct conn *c,
1061                        char **vec,
1062                        int attribute((unused)) nvec) {
1063   struct queue_entry *q, **qs;
1064   int n;
1065
1066   if(vec[0][0]) {
1067     if(!(q = queue_find(vec[0]))) {
1068       sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1069       return 1;
1070     }
1071   } else
1072     q = 0;
1073   ++vec;
1074   --nvec;
1075   qs = xcalloc(nvec, sizeof *qs);
1076   for(n = 0; n < nvec; ++n)
1077     if(!(qs[n] = queue_find(vec[n]))) {
1078       sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1079       return 1;
1080     }
1081   if(!has_move_rights(c, qs, nvec)) {
1082     error(0, "%s attempted moveafter but lacks required rights", c->who);
1083     sink_writes(ev_writer_sink(c->w),
1084                 "510 Not authorized to move those tracks\n");
1085     return 1;
1086   }
1087   queue_moveafter(q, nvec, qs, c->who);
1088   sink_printf(ev_writer_sink(c->w), "250 Moved tracks\n");
1089   /* If we've moved to the head of the queue then prepare the track. */
1090   if(q == qhead.next)
1091     prepare(c->ev, q);
1092   return 1;
1093 }
1094
1095 static int c_part(struct conn *c,
1096                   char **vec,
1097                   int attribute((unused)) nvec) {
1098   const char *track;
1099
1100   if(!(track = trackdb_resolve(vec[0]))) {
1101     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1102     return 1;
1103   }
1104   sink_printf(ev_writer_sink(c->w), "252 %s\n",
1105               quoteutf8(trackdb_getpart(track, vec[1], vec[2])));
1106   return 1;
1107 }
1108
1109 static int c_resolve(struct conn *c,
1110                      char **vec,
1111                      int attribute((unused)) nvec) {
1112   const char *track;
1113
1114   if(!(track = trackdb_resolve(vec[0]))) {
1115     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
1116     return 1;
1117   }
1118   sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(track));
1119   return 1;
1120 }
1121
1122 static int list_response(struct conn *c,
1123                          const char *reply,
1124                          char **list) {
1125   sink_printf(ev_writer_sink(c->w), "253 %s\n", reply);
1126   while(*list) {
1127     sink_printf(ev_writer_sink(c->w), "%s%s\n",
1128                 **list == '.' ? "." : "", *list);
1129     ++list;
1130   }
1131   sink_writes(ev_writer_sink(c->w), ".\n");
1132   return 1;                             /* completed */
1133 }
1134
1135 static int c_tags(struct conn *c,
1136                   char attribute((unused)) **vec,
1137                   int attribute((unused)) nvec) {
1138   return list_response(c, "Tag list follows", trackdb_alltags());
1139 }
1140
1141 static int c_set_global(struct conn *c,
1142                         char **vec,
1143                         int attribute((unused)) nvec) {
1144   if(vec[0][0] == '_') {
1145     sink_writes(ev_writer_sink(c->w), "550 cannot set internal global preferences\n");
1146     return 1;
1147   }
1148   trackdb_set_global(vec[0], vec[1], c->who);
1149   sink_printf(ev_writer_sink(c->w), "250 OK\n");
1150   return 1;
1151 }
1152
1153 static int c_get_global(struct conn *c,
1154                         char **vec,
1155                         int attribute((unused)) nvec) {
1156   const char *s = trackdb_get_global(vec[0]);
1157
1158   if(s)
1159     sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(s));
1160   else
1161     sink_writes(ev_writer_sink(c->w), "555 not found\n");
1162   return 1;
1163 }
1164
1165 static int c_nop(struct conn *c,
1166                  char attribute((unused)) **vec,
1167                  int attribute((unused)) nvec) {
1168   sink_printf(ev_writer_sink(c->w), "250 Quack\n");
1169   return 1;
1170 }
1171
1172 static int c_new(struct conn *c,
1173                  char **vec,
1174                  int nvec) {
1175   int max, n;
1176   char **tracks;
1177
1178   if(nvec > 0)
1179     max = atoi(vec[0]);
1180   else
1181     max = INT_MAX;
1182   if(max <= 0 || max > config->new_max)
1183     max = config->new_max;
1184   tracks = trackdb_new(0, max);
1185   sink_printf(ev_writer_sink(c->w), "253 New track list follows\n");
1186   n = 0;
1187   while(*tracks) {
1188     sink_printf(ev_writer_sink(c->w), "%s%s\n",
1189                 **tracks == '.' ? "." : "", *tracks);
1190     ++tracks;
1191   }
1192   sink_writes(ev_writer_sink(c->w), ".\n");
1193   return 1;                             /* completed */
1194
1195 }
1196
1197 static int c_rtp_address(struct conn *c,
1198                          char attribute((unused)) **vec,
1199                          int attribute((unused)) nvec) {
1200   if(api == &uaudio_rtp) {
1201     char **addr;
1202
1203     netaddress_format(&config->broadcast, NULL, &addr);
1204     sink_printf(ev_writer_sink(c->w), "252 %s %s\n",
1205                 quoteutf8(addr[1]),
1206                 quoteutf8(addr[2]));
1207   } else
1208     sink_writes(ev_writer_sink(c->w), "550 No RTP\n");
1209   return 1;
1210 }
1211
1212 static int c_cookie(struct conn *c,
1213                     char **vec,
1214                     int attribute((unused)) nvec) {
1215   const char *host;
1216   char *user;
1217   rights_type rights;
1218
1219   /* Can't log in twice on the same connection */
1220   if(c->who) {
1221     sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
1222     return 1;
1223   }
1224   /* Get some kind of peer identifcation */
1225   if(!(host = connection_host(c))) {
1226     sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1227     return 1;
1228   }
1229   /* Check the cookie */
1230   user = verify_cookie(vec[0], &rights);
1231   if(!user) {
1232     sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
1233     return 1;
1234   }
1235   /* Log in */
1236   c->who = user;
1237   c->cookie = vec[0];
1238   c->rights = rights;
1239   if(strcmp(host, "local"))
1240     info("S%x %s connected with cookie from %s", c->tag, user, host);
1241   else
1242     c->rights |= RIGHT__LOCAL;
1243   /* Response contains username so client knows who they are acting as */
1244   sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
1245   return 1;
1246 }
1247
1248 static int c_make_cookie(struct conn *c,
1249                          char attribute((unused)) **vec,
1250                          int attribute((unused)) nvec) {
1251   const char *cookie = make_cookie(c->who);
1252
1253   if(cookie)
1254     sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cookie));
1255   else
1256     sink_writes(ev_writer_sink(c->w), "550 Cannot create cookie\n");
1257   return 1;
1258 }
1259
1260 static int c_revoke(struct conn *c,
1261                     char attribute((unused)) **vec,
1262                     int attribute((unused)) nvec) {
1263   if(c->cookie) {
1264     revoke_cookie(c->cookie);
1265     sink_writes(ev_writer_sink(c->w), "250 OK\n");
1266   } else
1267     sink_writes(ev_writer_sink(c->w), "550 Did not log in with cookie\n");
1268   return 1;
1269 }
1270
1271 static int c_adduser(struct conn *c,
1272                      char **vec,
1273                      int nvec) {
1274   const char *rights;
1275
1276   if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1277     error(0, "S%x: remote adduser", c->tag);
1278     sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1279     return 1;
1280   }
1281   if(nvec > 2) {
1282     rights = vec[2];
1283     if(parse_rights(vec[2], 0, 1)) {
1284       sink_writes(ev_writer_sink(c->w), "550 Invalid rights list\n");
1285       return -1;
1286     }
1287   } else
1288     rights = config->default_rights;
1289   if(trackdb_adduser(vec[0], vec[1], rights,
1290                      0/*email*/, 0/*confirmation*/))
1291     sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1292   else
1293     sink_writes(ev_writer_sink(c->w), "250 User created\n");
1294   return 1;
1295 }
1296
1297 static int c_deluser(struct conn *c,
1298                      char **vec,
1299                      int attribute((unused)) nvec) {
1300   struct conn *d;
1301
1302   if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1303     error(0, "S%x: remote deluser", c->tag);
1304     sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1305     return 1;
1306   }
1307   if(trackdb_deluser(vec[0])) {
1308     sink_writes(ev_writer_sink(c->w), "550 Cannot delete user\n");
1309     return 1;
1310   }
1311   /* Zap connections belonging to deleted user */
1312   for(d = connections; d; d = d->next)
1313     if(!strcmp(d->who, vec[0]))
1314       d->rights = 0;
1315   sink_writes(ev_writer_sink(c->w), "250 User deleted\n");
1316   return 1;
1317 }
1318
1319 static int c_edituser(struct conn *c,
1320                       char **vec,
1321                       int attribute((unused)) nvec) {
1322   struct conn *d;
1323
1324   if(!config->remote_userman && !(c->rights & RIGHT__LOCAL)) {
1325     error(0, "S%x: remote edituser", c->tag);
1326     sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1327     return 1;
1328   }
1329   /* RIGHT_ADMIN can do anything; otherwise you can only set your own email
1330    * address and password. */
1331   if((c->rights & RIGHT_ADMIN)
1332      || (!strcmp(c->who, vec[0])
1333          && (!strcmp(vec[1], "email")
1334              || !strcmp(vec[1], "password")))) {
1335     if(trackdb_edituserinfo(vec[0], vec[1], vec[2])) {
1336       sink_writes(ev_writer_sink(c->w), "550 Failed to change setting\n");
1337       return 1;
1338     }
1339     if(!strcmp(vec[1], "password")) {
1340       /* Zap all connections for this user after a password change */
1341       for(d = connections; d; d = d->next)
1342         if(!strcmp(d->who, vec[0]))
1343           d->rights = 0;
1344     } else if(!strcmp(vec[1], "rights")) {
1345       /* Update rights for this user */
1346       rights_type r;
1347
1348       if(!parse_rights(vec[2], &r, 1)) {
1349         const char *new_rights = rights_string(r);
1350         for(d = connections; d; d = d->next) {
1351           if(!strcmp(d->who, vec[0])) {
1352             /* Update rights */
1353             d->rights = r;
1354             /* Notify any log connections */
1355             if(d->lo)
1356               sink_printf(ev_writer_sink(d->w),
1357                           "%"PRIxMAX" rights_changed %s\n",
1358                           (uintmax_t)xtime(0),
1359                           quoteutf8(new_rights));
1360           }
1361         }
1362       }
1363     }
1364     sink_writes(ev_writer_sink(c->w), "250 OK\n");
1365   } else {
1366     error(0, "%s attempted edituser but lacks required rights", c->who);
1367     sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
1368   }
1369   return 1;
1370 }
1371
1372 static int c_userinfo(struct conn *c,
1373                       char attribute((unused)) **vec,
1374                       int attribute((unused)) nvec) {
1375   struct kvp *k;
1376   const char *value;
1377
1378   /* We allow remote querying of rights so that clients can figure out what
1379    * they're allowed to do */
1380   if(!config->remote_userman
1381      && !(c->rights & RIGHT__LOCAL)
1382      && strcmp(vec[1], "rights")) {
1383     error(0, "S%x: remote userinfo %s %s", c->tag, vec[0], vec[1]);
1384     sink_writes(ev_writer_sink(c->w), "550 Remote user management is disabled\n");
1385     return 1;
1386   }
1387   /* RIGHT_ADMIN allows anything; otherwise you can only get your own email
1388    * address and rights list. */
1389   if((c->rights & RIGHT_ADMIN)
1390      || (!strcmp(c->who, vec[0])
1391          && (!strcmp(vec[1], "email")
1392              || !strcmp(vec[1], "rights")))) {
1393     if((k = trackdb_getuserinfo(vec[0])))
1394       if((value = kvp_get(k, vec[1])))
1395         sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(value));
1396       else
1397         sink_writes(ev_writer_sink(c->w), "555 Not set\n");
1398     else
1399       sink_writes(ev_writer_sink(c->w), "550 No such user\n");
1400   } else {
1401     error(0, "%s attempted userinfo but lacks required rights", c->who);
1402     sink_writes(ev_writer_sink(c->w), "510 Restricted to administrators\n");
1403   }
1404   return 1;
1405 }
1406
1407 static int c_users(struct conn *c,
1408                    char attribute((unused)) **vec,
1409                    int attribute((unused)) nvec) {
1410   return list_response(c, "User list follows", trackdb_listusers());
1411 }
1412
1413 static int c_register(struct conn *c,
1414                       char **vec,
1415                       int attribute((unused)) nvec) {
1416   char *cs;
1417   uint32_t nonce[CONFIRM_SIZE];
1418   char nonce_str[(32 * CONFIRM_SIZE) / 5 + 1];
1419
1420   /* The confirmation string is username/base62(nonce).  The confirmation
1421    * process will pick the username back out to identify them but the _whole_
1422    * string is used as the confirmation string.  Base 62 means we used only
1423    * letters and digits, minimizing the chance of the URL being mispasted. */
1424   gcry_randomize(nonce, sizeof nonce, GCRY_STRONG_RANDOM);
1425   if(basen(nonce, CONFIRM_SIZE, nonce_str, sizeof nonce_str, 62)) {
1426     error(0, "buffer too small encoding confirmation string");
1427     sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1428   }
1429   byte_xasprintf(&cs, "%s/%s", vec[0], nonce_str);
1430   if(trackdb_adduser(vec[0], vec[1], config->default_rights, vec[2], cs))
1431     sink_writes(ev_writer_sink(c->w), "550 Cannot create user\n");
1432   else
1433     sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(cs));
1434   return 1;
1435 }
1436
1437 static int c_confirm(struct conn *c,
1438                      char **vec,
1439                      int attribute((unused)) nvec) {
1440   char *user, *sep;
1441   rights_type rights;
1442   const char *host;
1443
1444   /* Get some kind of peer identifcation */
1445   if(!(host = connection_host(c))) {
1446     sink_writes(ev_writer_sink(c->w), "530 Authentication failure\n");
1447     return 1;
1448   }
1449   /* Picking the LAST / means we don't (here) rule out slashes in usernames. */
1450   if(!(sep = strrchr(vec[0], '/'))) {
1451     sink_writes(ev_writer_sink(c->w), "550 Malformed confirmation string\n");
1452     return 1;
1453   }
1454   user = xstrndup(vec[0], sep - vec[0]);
1455   if(trackdb_confirm(user, vec[0], &rights))
1456     sink_writes(ev_writer_sink(c->w), "550 Incorrect confirmation string\n");
1457   else {
1458     c->who = user;
1459     c->cookie = 0;
1460     c->rights = rights;
1461     if(strcmp(host, "local"))
1462       info("S%x %s confirmed from %s", c->tag, user, host);
1463     else
1464       c->rights |= RIGHT__LOCAL;
1465     /* Response contains username so client knows who they are acting as */
1466     sink_printf(ev_writer_sink(c->w), "232 %s\n", quoteutf8(user));
1467   }
1468   return 1;
1469 }
1470
1471 static int sent_reminder(ev_source attribute((unused)) *ev,
1472                          pid_t attribute((unused)) pid,
1473                          int status,
1474                          const struct rusage attribute((unused)) *rusage,
1475                          void *u) {
1476   struct conn *const c = u;
1477
1478   /* Tell the client what went down */ 
1479   if(!status) {
1480     sink_writes(ev_writer_sink(c->w), "250 OK\n");
1481   } else {
1482     error(0, "reminder subprocess %s", wstat(status));
1483     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1484   }
1485   /* Re-enable this connection */
1486   ev_reader_enable(c->r);
1487   return 0;
1488 }
1489
1490 static int c_reminder(struct conn *c,
1491                       char **vec,
1492                       int attribute((unused)) nvec) {
1493   struct kvp *k;
1494   const char *password, *email, *text, *encoding, *charset, *content_type;
1495   const time_t *last;
1496   time_t now;
1497   pid_t pid;
1498   
1499   static hash *last_reminder;
1500
1501   if(!config->mail_sender) {
1502     error(0, "cannot send password reminders because mail_sender not set");
1503     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1504     return 1;
1505   }
1506   if(!(k = trackdb_getuserinfo(vec[0]))) {
1507     error(0, "reminder for user '%s' who does not exist", vec[0]);
1508     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1509     return 1;
1510   }
1511   if(!(email = kvp_get(k, "email"))
1512      || !email_valid(email)) {
1513     error(0, "user '%s' has no valid email address", vec[0]);
1514     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1515     return 1;
1516   }
1517   if(!(password = kvp_get(k, "password"))
1518      || !*password) {
1519     error(0, "user '%s' has no password", vec[0]);
1520     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1521     return 1;
1522   }
1523   /* Rate-limit reminders.  This hash is bounded in size by the number of
1524    * users.  If this is actually a problem for anyone then we can periodically
1525    * clean it. */
1526   if(!last_reminder)
1527     last_reminder = hash_new(sizeof (time_t));
1528   last = hash_find(last_reminder, vec[0]);
1529   xtime(&now);
1530   if(last && now < *last + config->reminder_interval) {
1531     error(0, "sent a password reminder to '%s' too recently", vec[0]);
1532     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1533     return 1;
1534   }
1535   /* Send the reminder */
1536   /* TODO this should be templatized and to some extent merged with
1537    * the code in act_register() */
1538   byte_xasprintf((char **)&text,
1539 "Someone requested that you be sent a reminder of your DisOrder password.\n"
1540 "Your password is:\n"
1541 "\n"
1542 "  %s\n", password);
1543   if(!(text = mime_encode_text(text, &charset, &encoding)))
1544     fatal(0, "cannot encode email");
1545   byte_xasprintf((char **)&content_type, "text/plain;charset=%s",
1546                  quote822(charset, 0));
1547   pid = sendmail_subprocess("", config->mail_sender, email,
1548                             "DisOrder password reminder",
1549                             encoding, content_type, text);
1550   if(pid < 0) {
1551     sink_writes(ev_writer_sink(c->w), "550 Cannot send a reminder email\n");
1552     return 1;
1553   }
1554   hash_add(last_reminder, vec[0], &now, HASH_INSERT_OR_REPLACE);
1555   info("sending a passsword reminder to user '%s'", vec[0]);
1556   /* We can only continue when the subprocess finishes */
1557   ev_child(c->ev, pid, 0, sent_reminder, c);
1558   return 0;
1559 }
1560
1561 static int c_schedule_list(struct conn *c,
1562                            char attribute((unused)) **vec,
1563                            int attribute((unused)) nvec) {
1564   char **ids = schedule_list(0);
1565   sink_writes(ev_writer_sink(c->w), "253 ID list follows\n");
1566   while(*ids)
1567     sink_printf(ev_writer_sink(c->w), "%s\n", *ids++);
1568   sink_writes(ev_writer_sink(c->w), ".\n");
1569   return 1;                             /* completed */
1570 }
1571
1572 static int c_schedule_get(struct conn *c,
1573                           char **vec,
1574                           int attribute((unused)) nvec) {
1575   struct kvp *actiondata = schedule_get(vec[0]), *k;
1576
1577   if(!actiondata) {
1578     sink_writes(ev_writer_sink(c->w), "555 No such event\n");
1579     return 1;                           /* completed */
1580   }
1581   /* Scheduled events are public information.  Anyone with RIGHT_READ can see
1582    * them. */
1583   sink_writes(ev_writer_sink(c->w), "253 Event information follows\n");
1584   for(k = actiondata; k; k = k->next)
1585     sink_printf(ev_writer_sink(c->w), " %s %s\n",
1586                 quoteutf8(k->name),  quoteutf8(k->value));
1587   sink_writes(ev_writer_sink(c->w), ".\n");
1588   return 1;                             /* completed */
1589 }
1590
1591 static int c_schedule_del(struct conn *c,
1592                           char **vec,
1593                           int attribute((unused)) nvec) {
1594   struct kvp *actiondata = schedule_get(vec[0]);
1595
1596   if(!actiondata) {
1597     sink_writes(ev_writer_sink(c->w), "555 No such event\n");
1598     return 1;                           /* completed */
1599   }
1600   /* If you have admin rights you can delete anything.  If you don't then you
1601    * can only delete your own scheduled events. */
1602   if(!(c->rights & RIGHT_ADMIN)) {
1603     const char *who = kvp_get(actiondata, "who");
1604
1605     if(!who || !c->who || strcmp(who, c->who)) {
1606       sink_writes(ev_writer_sink(c->w), "551 Not authorized\n");
1607       return 1;                         /* completed */
1608     }
1609   }
1610   if(schedule_del(vec[0]))
1611     sink_writes(ev_writer_sink(c->w), "550 Could not delete scheduled event\n");
1612   else
1613     sink_writes(ev_writer_sink(c->w), "250 Deleted\n");
1614   return 1;                             /* completed */
1615 }
1616
1617 static int c_schedule_add(struct conn *c,
1618                           char **vec,
1619                           int nvec) {
1620   struct kvp *actiondata = 0;
1621   const char *id;
1622
1623   /* Standard fields */
1624   kvp_set(&actiondata, "who", c->who);
1625   kvp_set(&actiondata, "when", vec[0]);
1626   kvp_set(&actiondata, "priority", vec[1]);
1627   kvp_set(&actiondata, "action", vec[2]);
1628   /* Action-dependent fields */
1629   if(!strcmp(vec[2], "play")) {
1630     if(nvec != 4) {
1631       sink_writes(ev_writer_sink(c->w), "550 Wrong number of arguments\n");
1632       return 1;
1633     }
1634     if(!trackdb_exists(vec[3])) {
1635       sink_writes(ev_writer_sink(c->w), "550 Track is not in database\n");
1636       return 1;
1637     }
1638     kvp_set(&actiondata, "track", vec[3]);
1639   } else if(!strcmp(vec[2], "set-global")) {
1640     if(nvec < 4 || nvec > 5) {
1641       sink_writes(ev_writer_sink(c->w), "550 Wrong number of arguments\n");
1642       return 1;
1643     }
1644     kvp_set(&actiondata, "key", vec[3]);
1645     if(nvec > 4)
1646       kvp_set(&actiondata, "value", vec[4]);
1647   } else {
1648     sink_writes(ev_writer_sink(c->w), "550 Unknown action\n");
1649     return 1;
1650   }
1651   /* schedule_add() checks user rights */
1652   id = schedule_add(c->ev, actiondata);
1653   if(!id)
1654     sink_writes(ev_writer_sink(c->w), "550 Cannot add scheduled event\n");
1655   else
1656     sink_printf(ev_writer_sink(c->w), "252 %s\n", id);
1657   return 1;
1658 }
1659
1660 static int c_adopt(struct conn *c,
1661                    char **vec,
1662                    int attribute((unused)) nvec) {
1663   struct queue_entry *q;
1664
1665   if(!c->who) {
1666     sink_writes(ev_writer_sink(c->w), "550 no identity\n");
1667     return 1;
1668   }
1669   if(!(q = queue_find(vec[0]))) {
1670     sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
1671     return 1;
1672   }
1673   if(q->origin != origin_random) {
1674     sink_writes(ev_writer_sink(c->w), "550 not a random track\n");
1675     return 1;
1676   }
1677   q->origin = origin_adopted;
1678   q->submitter = xstrdup(c->who);
1679   eventlog("adopted", q->id, q->submitter, (char *)0);
1680   queue_write();
1681   sink_writes(ev_writer_sink(c->w), "250 OK\n");
1682   return 1;
1683 }
1684
1685 static int playlist_response(struct conn *c,
1686                              int err) {
1687   switch(err) {
1688   case 0:
1689     assert(!"cannot cope with success");
1690   case EACCES:
1691     sink_writes(ev_writer_sink(c->w), "550 Access denied\n");
1692     break;
1693   case EINVAL:
1694     sink_writes(ev_writer_sink(c->w), "550 Invalid playlist name\n");
1695     break;
1696   case ENOENT:
1697     sink_writes(ev_writer_sink(c->w), "555 No such playlist\n");
1698     break;
1699   default:
1700     sink_writes(ev_writer_sink(c->w), "550 Error accessing playlist\n");
1701     break;
1702   }
1703   return 1;
1704 }
1705
1706 static int c_playlist_get(struct conn *c,
1707                           char **vec,
1708                           int attribute((unused)) nvec) {
1709   char **tracks;
1710   int err;
1711
1712   if(!(err = trackdb_playlist_get(vec[0], c->who, &tracks, 0, 0)))
1713     return list_response(c, "Playlist contents follows", tracks);
1714   else
1715     return playlist_response(c, err);
1716 }
1717
1718 static int c_playlist_set(struct conn *c,
1719                           char **vec,
1720                           int attribute((unused)) nvec) {
1721   return fetch_body(c, c_playlist_set_body, vec[0]);
1722 }
1723
1724 static int c_playlist_set_body(struct conn *c,
1725                                char **body,
1726                                int nbody,
1727                                void *u) {
1728   const char *playlist = u;
1729   int err;
1730
1731   if(!c->locked_playlist
1732      || strcmp(playlist, c->locked_playlist)) {
1733     sink_writes(ev_writer_sink(c->w), "550 Playlist is not locked\n");
1734     return 1;
1735   }
1736   if(!(err = trackdb_playlist_set(playlist, c->who,
1737                                   body, nbody, 0))) {
1738     sink_printf(ev_writer_sink(c->w), "250 OK\n");
1739     return 1;
1740   } else
1741     return playlist_response(c, err);
1742 }
1743
1744 static int c_playlist_get_share(struct conn *c,
1745                                 char **vec,
1746                                 int attribute((unused)) nvec) {
1747   char *share;
1748   int err;
1749
1750   if(!(err = trackdb_playlist_get(vec[0], c->who, 0, 0, &share))) {
1751     sink_printf(ev_writer_sink(c->w), "252 %s\n", quoteutf8(share));
1752     return 1;
1753   } else
1754     return playlist_response(c, err);
1755 }
1756
1757 static int c_playlist_set_share(struct conn *c,
1758                                 char **vec,
1759                                 int attribute((unused)) nvec) {
1760   int err;
1761
1762   if(!(err = trackdb_playlist_set(vec[0], c->who, 0, 0, vec[1]))) {
1763     sink_printf(ev_writer_sink(c->w), "250 OK\n");
1764     return 1;
1765   } else
1766     return playlist_response(c, err);
1767 }
1768
1769 static int c_playlists(struct conn *c,
1770                        char attribute((unused)) **vec,
1771                        int attribute((unused)) nvec) {
1772   char **p;
1773
1774   trackdb_playlist_list(c->who, &p, 0);
1775   return list_response(c, "List of playlists follows", p);
1776 }
1777
1778 static int c_playlist_delete(struct conn *c,
1779                              char **vec,
1780                              int attribute((unused)) nvec) {
1781   int err;
1782   
1783   if(!(err = trackdb_playlist_delete(vec[0], c->who))) {
1784     sink_writes(ev_writer_sink(c->w), "250 OK\n");
1785     return 1;
1786   } else
1787     return playlist_response(c, err);
1788 }
1789
1790 static int c_playlist_lock(struct conn *c,
1791                            char **vec,
1792                            int attribute((unused)) nvec) {
1793   int err;
1794   struct conn *cc;
1795
1796   /* Check we're allowed to modify this playlist */
1797   if((err = trackdb_playlist_set(vec[0], c->who, 0, 0, 0)))
1798     return playlist_response(c, err);
1799   /* If we hold a lock don't allow a new one */
1800   if(c->locked_playlist) {
1801     sink_writes(ev_writer_sink(c->w), "550 Already holding a lock\n");
1802     return 1;
1803   }
1804   /* See if some other connection locks the same playlist */
1805   for(cc = connections; cc; cc = cc->next)
1806     if(cc->locked_playlist && !strcmp(cc->locked_playlist, vec[0]))
1807       break;
1808   if(cc) {
1809     /* TODO: implement config->playlist_lock_timeout */
1810     sink_writes(ev_writer_sink(c->w), "550 Already locked\n");
1811     return 1;
1812   }
1813   c->locked_playlist = xstrdup(vec[0]);
1814   time(&c->locked_when);
1815   sink_writes(ev_writer_sink(c->w), "250 Acquired lock\n");
1816   return 1;
1817 }
1818
1819 static int c_playlist_unlock(struct conn *c,
1820                              char attribute((unused)) **vec,
1821                              int attribute((unused)) nvec) {
1822   if(!c->locked_playlist) {
1823     sink_writes(ev_writer_sink(c->w), "550 Not holding a lock\n");
1824     return 1;
1825   }
1826   c->locked_playlist = 0;
1827   sink_writes(ev_writer_sink(c->w), "250 Released lock\n");
1828   return 1;
1829 }
1830
1831 static const struct command {
1832   /** @brief Command name */
1833   const char *name;
1834
1835   /** @brief Minimum number of arguments */
1836   int minargs;
1837
1838   /** @brief Maximum number of arguments */
1839   int maxargs;
1840
1841   /** @brief Function to process command */
1842   int (*fn)(struct conn *, char **, int);
1843
1844   /** @brief Rights required to execute command
1845    *
1846    * 0 means that the command can be issued without logging in.  If multiple
1847    * bits are listed here any of those rights will do.
1848    */
1849   rights_type rights;
1850 } commands[] = {
1851   { "adduser",        2, 3,       c_adduser,        RIGHT_ADMIN|RIGHT__LOCAL },
1852   { "adopt",          1, 1,       c_adopt,          RIGHT_PLAY },
1853   { "allfiles",       0, 2,       c_allfiles,       RIGHT_READ },
1854   { "confirm",        1, 1,       c_confirm,        0 },
1855   { "cookie",         1, 1,       c_cookie,         0 },
1856   { "deluser",        1, 1,       c_deluser,        RIGHT_ADMIN|RIGHT__LOCAL },
1857   { "dirs",           0, 2,       c_dirs,           RIGHT_READ },
1858   { "disable",        0, 1,       c_disable,        RIGHT_GLOBAL_PREFS },
1859   { "edituser",       3, 3,       c_edituser,       RIGHT_ADMIN|RIGHT_USERINFO },
1860   { "enable",         0, 0,       c_enable,         RIGHT_GLOBAL_PREFS },
1861   { "enabled",        0, 0,       c_enabled,        RIGHT_READ },
1862   { "exists",         1, 1,       c_exists,         RIGHT_READ },
1863   { "files",          0, 2,       c_files,          RIGHT_READ },
1864   { "get",            2, 2,       c_get,            RIGHT_READ },
1865   { "get-global",     1, 1,       c_get_global,     RIGHT_READ },
1866   { "length",         1, 1,       c_length,         RIGHT_READ },
1867   { "log",            0, 0,       c_log,            RIGHT_READ },
1868   { "make-cookie",    0, 0,       c_make_cookie,    RIGHT_READ },
1869   { "move",           2, 2,       c_move,           RIGHT_MOVE__MASK },
1870   { "moveafter",      1, INT_MAX, c_moveafter,      RIGHT_MOVE__MASK },
1871   { "new",            0, 1,       c_new,            RIGHT_READ },
1872   { "nop",            0, 0,       c_nop,            0 },
1873   { "part",           3, 3,       c_part,           RIGHT_READ },
1874   { "pause",          0, 0,       c_pause,          RIGHT_PAUSE },
1875   { "play",           1, 1,       c_play,           RIGHT_PLAY },
1876   { "playafter",      2, INT_MAX, c_playafter,      RIGHT_PLAY },
1877   { "playing",        0, 0,       c_playing,        RIGHT_READ },
1878   { "playlist-delete",    1, 1,   c_playlist_delete,    RIGHT_PLAY },
1879   { "playlist-get",       1, 1,   c_playlist_get,       RIGHT_READ },
1880   { "playlist-get-share", 1, 1,   c_playlist_get_share, RIGHT_READ },
1881   { "playlist-lock",      1, 1,   c_playlist_lock,      RIGHT_PLAY },
1882   { "playlist-set",       1, 1,   c_playlist_set,       RIGHT_PLAY },
1883   { "playlist-set-share", 2, 2,   c_playlist_set_share, RIGHT_PLAY },
1884   { "playlist-unlock",    0, 0,   c_playlist_unlock,    RIGHT_PLAY },
1885   { "playlists",          0, 0,   c_playlists,          RIGHT_READ },
1886   { "prefs",          1, 1,       c_prefs,          RIGHT_READ },
1887   { "queue",          0, 0,       c_queue,          RIGHT_READ },
1888   { "random-disable", 0, 0,       c_random_disable, RIGHT_GLOBAL_PREFS },
1889   { "random-enable",  0, 0,       c_random_enable,  RIGHT_GLOBAL_PREFS },
1890   { "random-enabled", 0, 0,       c_random_enabled, RIGHT_READ },
1891   { "recent",         0, 0,       c_recent,         RIGHT_READ },
1892   { "reconfigure",    0, 0,       c_reconfigure,    RIGHT_ADMIN },
1893   { "register",       3, 3,       c_register,       RIGHT_REGISTER|RIGHT__LOCAL },
1894   { "reminder",       1, 1,       c_reminder,       RIGHT__LOCAL },
1895   { "remove",         1, 1,       c_remove,         RIGHT_REMOVE__MASK },
1896   { "rescan",         0, INT_MAX, c_rescan,         RIGHT_RESCAN },
1897   { "resolve",        1, 1,       c_resolve,        RIGHT_READ },
1898   { "resume",         0, 0,       c_resume,         RIGHT_PAUSE },
1899   { "revoke",         0, 0,       c_revoke,         RIGHT_READ },
1900   { "rtp-address",    0, 0,       c_rtp_address,    0 },
1901   { "schedule-add",   3, INT_MAX, c_schedule_add,   RIGHT_READ },
1902   { "schedule-del",   1, 1,       c_schedule_del,   RIGHT_READ },
1903   { "schedule-get",   1, 1,       c_schedule_get,   RIGHT_READ },
1904   { "schedule-list",  0, 0,       c_schedule_list,  RIGHT_READ },
1905   { "scratch",        0, 1,       c_scratch,        RIGHT_SCRATCH__MASK },
1906   { "search",         1, 1,       c_search,         RIGHT_READ },
1907   { "set",            3, 3,       c_set,            RIGHT_PREFS, },
1908   { "set-global",     2, 2,       c_set_global,     RIGHT_GLOBAL_PREFS },
1909   { "shutdown",       0, 0,       c_shutdown,       RIGHT_ADMIN },
1910   { "stats",          0, 0,       c_stats,          RIGHT_READ },
1911   { "tags",           0, 0,       c_tags,           RIGHT_READ },
1912   { "unset",          2, 2,       c_set,            RIGHT_PREFS },
1913   { "unset-global",   1, 1,       c_set_global,     RIGHT_GLOBAL_PREFS },
1914   { "user",           2, 2,       c_user,           0 },
1915   { "userinfo",       2, 2,       c_userinfo,       RIGHT_READ },
1916   { "users",          0, 0,       c_users,          RIGHT_READ },
1917   { "version",        0, 0,       c_version,        RIGHT_READ },
1918   { "volume",         0, 2,       c_volume,         RIGHT_READ|RIGHT_VOLUME }
1919 };
1920
1921 /** @brief Fetch a command body
1922  * @param c Connection
1923  * @param body_callback Called with body
1924  * @param u Passed to body_callback
1925  * @return 1
1926  */
1927 static int fetch_body(struct conn *c,
1928                       body_callback_type body_callback,
1929                       void *u) {
1930   assert(c->line_reader == command);
1931   c->line_reader = body_line;
1932   c->body_callback = body_callback;
1933   c->body_u = u;
1934   vector_init(c->body);
1935   return 1;
1936 }
1937
1938 /** @brief @ref line_reader_type callback for command body lines
1939  * @param c Connection
1940  * @param line Line
1941  * @return 1 if complete, 0 if incomplete
1942  *
1943  * Called from reader_callback().
1944  */
1945 static int body_line(struct conn *c,
1946                      char *line) {
1947   if(*line == '.') {
1948     ++line;
1949     if(!*line) {
1950       /* That's the lot */
1951       c->line_reader = command;
1952       vector_terminate(c->body);
1953       return c->body_callback(c, c->body->vec, c->body->nvec, c->body_u);
1954     }
1955   }
1956   vector_append(c->body, xstrdup(line));
1957   return 1;                             /* completed */
1958 }
1959
1960 static void command_error(const char *msg, void *u) {
1961   struct conn *c = u;
1962
1963   sink_printf(ev_writer_sink(c->w), "500 parse error: %s\n", msg);
1964 }
1965
1966 /** @brief @ref line_reader_type callback for commands
1967  * @param c Connection
1968  * @param line Line
1969  * @return 1 if complete, 0 if incomplete
1970  *
1971  * Called from reader_callback().
1972  */
1973 static int command(struct conn *c, char *line) {
1974   char **vec;
1975   int nvec, n;
1976
1977   D(("server command %s", line));
1978   /* We force everything into NFC as early as possible */
1979   if(!(line = utf8_compose_canon(line, strlen(line), 0))) {
1980     sink_writes(ev_writer_sink(c->w), "500 cannot normalize command\n");
1981     return 1;
1982   }
1983   if(!(vec = split(line, &nvec, SPLIT_QUOTES, command_error, c))) {
1984     sink_writes(ev_writer_sink(c->w), "500 cannot parse command\n");
1985     return 1;
1986   }
1987   if(nvec == 0) {
1988     sink_writes(ev_writer_sink(c->w), "500 do what?\n");
1989     return 1;
1990   }
1991   if((n = TABLE_FIND(commands, name, vec[0])) < 0)
1992     sink_writes(ev_writer_sink(c->w), "500 unknown command\n");
1993   else {
1994     if(commands[n].rights
1995        && !(c->rights & commands[n].rights)) {
1996       error(0, "%s attempted %s but lacks required rights", c->who ? c->who : "NULL",
1997             commands[n].name);
1998       sink_writes(ev_writer_sink(c->w), "510 Prohibited\n");
1999       return 1;
2000     }
2001     ++vec;
2002     --nvec;
2003     if(nvec < commands[n].minargs) {
2004       sink_writes(ev_writer_sink(c->w), "500 missing argument(s)\n");
2005       return 1;
2006     }
2007     if(nvec > commands[n].maxargs) {
2008       sink_writes(ev_writer_sink(c->w), "500 too many arguments\n");
2009       return 1;
2010     }
2011     return commands[n].fn(c, vec, nvec);
2012   }
2013   return 1;                     /* completed */
2014 }
2015
2016 /* redirect to the right reader callback for our current state */
2017 static int redirect_reader_callback(ev_source *ev,
2018                                     ev_reader *reader,
2019                                     void *ptr,
2020                                     size_t bytes,
2021                                     int eof,
2022                                     void *u) {
2023   struct conn *c = u;
2024
2025   return c->reader(ev, reader, ptr, bytes, eof, u);
2026 }
2027
2028 /* the main command reader */
2029 static int reader_callback(ev_source attribute((unused)) *ev,
2030                            ev_reader *reader,
2031                            void *ptr,
2032                            size_t bytes,
2033                            int eof,
2034                            void *u) {
2035   struct conn *c = u;
2036   char *eol;
2037   int complete;
2038
2039   D(("server reader_callback"));
2040   while((eol = memchr(ptr, '\n', bytes))) {
2041     *eol++ = 0;
2042     ev_reader_consume(reader, eol - (char *)ptr);
2043     complete = c->line_reader(c, ptr);  /* usually command() */
2044     bytes -= (eol - (char *)ptr);
2045     ptr = eol;
2046     if(!complete) {
2047       /* the command had better have set a new reader callback */
2048       if(bytes || eof)
2049         /* there are further bytes to read, or we are at eof; arrange for the
2050          * command's reader callback to handle them */
2051         return ev_reader_incomplete(reader);
2052       /* nothing's going on right now */
2053       return 0;
2054     }
2055     /* command completed, we can go around and handle the next one */
2056   }
2057   if(eof) {
2058     if(bytes)
2059       error(0, "S%x unterminated line", c->tag);
2060     D(("normal reader close"));
2061     c->r = 0;
2062     if(c->w) {
2063       D(("close associated writer"));
2064       ev_writer_close(c->w);
2065       c->w = 0;
2066     }
2067     remove_connection(c);
2068   }
2069   return 0;
2070 }
2071
2072 static int listen_callback(ev_source *ev,
2073                            int fd,
2074                            const struct sockaddr attribute((unused)) *remote,
2075                            socklen_t attribute((unused)) rlen,
2076                            void *u) {
2077   const struct listener *l = u;
2078   struct conn *c = xmalloc(sizeof *c);
2079   static unsigned tags;
2080
2081   D(("server listen_callback fd %d (%s)", fd, l->name));
2082   nonblock(fd);
2083   cloexec(fd);
2084   c->next = connections;
2085   c->tag = tags++;
2086   c->ev = ev;
2087   c->w = ev_writer_new(ev, fd, writer_error, c,
2088                        "client writer");
2089   if(!c->w) {
2090     error(0, "ev_writer_new for file inbound connection (fd=%d) failed",
2091           fd);
2092     close(fd);
2093     return 0;
2094   }
2095   c->r = ev_reader_new(ev, fd, redirect_reader_callback, reader_error, c,
2096                        "client reader");
2097   if(!c->r)
2098     /* Main reason for failure is the FD is too big and that will already have
2099      * been handled */
2100     fatal(0, "ev_reader_new for file inbound connection (fd=%d) failed", fd);
2101   ev_tie(c->r, c->w);
2102   c->fd = fd;
2103   c->reader = reader_callback;
2104   c->l = l;
2105   c->rights = 0;
2106   c->line_reader = command;
2107   connections = c;
2108   gcry_randomize(c->nonce, sizeof c->nonce, GCRY_STRONG_RANDOM);
2109   sink_printf(ev_writer_sink(c->w), "231 %d %s %s\n",
2110               2,
2111               config->authorization_algorithm,
2112               hex(c->nonce, sizeof c->nonce));
2113   return 0;
2114 }
2115
2116 int server_start(ev_source *ev, int pf,
2117                  size_t socklen, const struct sockaddr *sa,
2118                  const char *name) {
2119   int fd;
2120   struct listener *l = xmalloc(sizeof *l);
2121   static const int one = 1;
2122
2123   D(("server_init socket %s", name));
2124   fd = xsocket(pf, SOCK_STREAM, 0);
2125   xsetsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
2126   if(bind(fd, sa, socklen) < 0) {
2127     error(errno, "error binding to %s", name);
2128     return -1;
2129   }
2130   xlisten(fd, 128);
2131   nonblock(fd);
2132   cloexec(fd);
2133   l->name = name;
2134   l->pf = pf;
2135   if(ev_listen(ev, fd, listen_callback, l, "server listener"))
2136     exit(EXIT_FAILURE);
2137   info("listening on %s", name);
2138   return fd;
2139 }
2140
2141 int server_stop(ev_source *ev, int fd) {
2142   xclose(fd);
2143   return ev_listen_cancel(ev, fd);
2144 }
2145
2146 /*
2147 Local Variables:
2148 c-basic-offset:2
2149 comment-column:40
2150 fill-column:79
2151 End:
2152 */