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