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