chiark / gitweb /
ev_reader and ev_writer now own the FDs you give them. This is
[disorder] / server / server.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004, 2005, 2006, 2007 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 2 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, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * 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, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20
21 #include <config.h>
22 #include "types.h"
23
24 #include <pwd.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/time.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <gcrypt.h>
34 #include <stddef.h>
35 #include <time.h>
36 #include <limits.h>
37 #include <pcre.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40
41 #include "event.h"
42 #include "server.h"
43 #include "syscalls.h"
44 #include "queue.h"
45 #include "server-queue.h"
46 #include "play.h"
47 #include "log.h"
48 #include "mem.h"
49 #include "state.h"
50 #include "charset.h"
51 #include "split.h"
52 #include "configuration.h"
53 #include "hex.h"
54 #include "trackdb.h"
55 #include "table.h"
56 #include "kvp.h"
57 #include "mixer.h"
58 #include "sink.h"
59 #include "authhash.h"
60 #include "plugin.h"
61 #include "printf.h"
62 #include "trackname.h"
63 #include "eventlog.h"
64 #include "defs.h"
65 #include "cache.h"
66
67 #ifndef NONCE_SIZE
68 # define NONCE_SIZE 16
69 #endif
70
71 int volume_left, volume_right;          /* last known volume */
72
73 /** @brief Accept all well-formed login attempts
74  *
75  * Used in debugging.
76  */
77 int wideopen;
78
79 struct listener {
80   const char *name;
81   int pf;
82 };
83
84 struct conn {
85   ev_reader *r;
86   ev_writer *w;
87   int fd;
88   unsigned tag;
89   char *who;
90   ev_source *ev;
91   unsigned char nonce[NONCE_SIZE];
92   ev_reader_callback *reader;
93   struct eventlog_output *lo;
94   const struct listener *l;
95 };
96
97 static int reader_callback(ev_source *ev,
98                            ev_reader *reader,
99                            void *ptr,
100                            size_t bytes,
101                            int eof,
102                            void *u);
103
104 static const char *noyes[] = { "no", "yes" };
105
106 static int writer_error(ev_source attribute((unused)) *ev,
107                         int errno_value,
108                         void *u) {
109   struct conn *c = u;
110
111   D(("server writer_error %d", errno_value));
112   if(errno_value == 0) {
113     /* writer is done */
114     error(errno_value, "S%x writer completed", c->tag); /* TODO */
115   } else {
116     if(errno_value != EPIPE)
117       error(errno_value, "S%x write error on socket", c->tag);
118     ev_reader_cancel(c->r);
119   }
120   ev_report(ev);
121   return 0;
122 }
123
124 static int reader_error(ev_source attribute((unused)) *ev,
125                         int errno_value,
126                         void *u) {
127   struct conn *c = u;
128
129   D(("server reader_error %d", errno_value));
130   error(errno, "S%x read error on socket", c->tag);
131   ev_writer_close(c->w);
132   ev_report(ev);
133   return 0;
134 }
135
136 /* return true if we are talking to a trusted user */
137 static int trusted(struct conn *c) {
138   int n;
139   
140   for(n = 0; (n < config->trust.n
141               && strcmp(config->trust.s[n], c->who)); ++n)
142     ;
143   return n < config->trust.n;
144 }
145
146 static int c_disable(struct conn *c, char **vec, int nvec) {
147   if(nvec == 0)
148     disable_playing(c->who);
149   else if(nvec == 1 && !strcmp(vec[0], "now"))
150     disable_playing(c->who);
151   else {
152     sink_writes(ev_writer_sink(c->w), "550 invalid argument\n");
153     return 1;                   /* completed */
154   }
155   sink_writes(ev_writer_sink(c->w), "250 OK\n");
156   return 1;                     /* completed */
157 }
158
159 static int c_enable(struct conn *c,
160                     char attribute((unused)) **vec,
161                     int attribute((unused)) nvec) {
162   enable_playing(c->who, c->ev);
163   /* Enable implicitly unpauses if there is nothing playing */
164   if(paused && !playing) resume_playing(c->who);
165   sink_writes(ev_writer_sink(c->w), "250 OK\n");
166   return 1;                     /* completed */
167 }
168
169 static int c_enabled(struct conn *c,
170                      char attribute((unused)) **vec,
171                      int attribute((unused)) nvec) {
172   sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[playing_is_enabled()]);
173   return 1;                     /* completed */
174 }
175
176 static int c_play(struct conn *c, char **vec,
177                   int attribute((unused)) nvec) {
178   const char *track;
179   struct queue_entry *q;
180   
181   if(!trackdb_exists(vec[0])) {
182     sink_writes(ev_writer_sink(c->w), "550 track is not in database\n");
183     return 1;
184   }
185   if(!(track = trackdb_resolve(vec[0]))) {
186     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
187     return 1;
188   }
189   q = queue_add(track, c->who, WHERE_BEFORE_RANDOM);
190   queue_write();
191   /* If we added the first track, and something is playing, then prepare the
192    * new track.  If nothing is playing then we don't bother as it wouldn't gain
193    * anything. */
194   if(q == qhead.next && playing)
195     prepare(c->ev, q);
196   sink_writes(ev_writer_sink(c->w), "250 queued\n");
197   /* If the queue was empty but we are for some reason paused then
198    * unpause. */
199   if(!playing) resume_playing(0);
200   play(c->ev);
201   return 1;                     /* completed */
202 }
203
204 static int c_remove(struct conn *c, char **vec,
205                     int attribute((unused)) nvec) {
206   struct queue_entry *q;
207
208   if(!(q = queue_find(vec[0]))) {
209     sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
210     return 1;
211   }
212   if(config->restrictions & RESTRICT_REMOVE) {
213     /* can only remove tracks that you submitted */
214     if(!q->submitter || strcmp(q->submitter, c->who)) {
215       sink_writes(ev_writer_sink(c->w), "550 you didn't submit that track!\n");
216       return 1;
217     }
218   }
219   queue_remove(q, c->who);
220   /* De-prepare the track. */
221   abandon(c->ev, q);
222   /* If we removed the random track then add another one. */
223   if(q->state == playing_random)
224     add_random_track();
225   /* Prepare whatever the next head track is. */
226   if(qhead.next != &qhead)
227     prepare(c->ev, qhead.next);
228   queue_write();
229   sink_writes(ev_writer_sink(c->w), "250 removed\n");
230   return 1;                     /* completed */
231 }
232
233 static int c_scratch(struct conn *c,
234                      char **vec,
235                      int nvec) {
236   if(!playing) {
237     sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
238     return 1;                   /* completed */
239   }
240   if(config->restrictions & RESTRICT_SCRATCH) {
241     /* can only scratch tracks you submitted and randomly selected ones */
242     if(playing->submitter && strcmp(playing->submitter, c->who)) {
243       sink_writes(ev_writer_sink(c->w), "550 you didn't submit that track!\n");
244       return 1;
245     }
246   }
247   scratch(c->who, nvec == 1 ? vec[0] : 0);
248   /* If you scratch an unpaused track then it is automatically unpaused */
249   resume_playing(0);
250   sink_writes(ev_writer_sink(c->w), "250 scratched\n");
251   return 1;                     /* completed */
252 }
253
254 static int c_pause(struct conn *c,
255                    char attribute((unused)) **vec,
256                    int attribute((unused)) nvec) {
257   if(!playing) {
258     sink_writes(ev_writer_sink(c->w), "250 nothing is playing\n");
259     return 1;                   /* completed */
260   }
261   if(paused) {
262     sink_writes(ev_writer_sink(c->w), "250 already paused\n");
263     return 1;                   /* completed */
264   }
265   if(pause_playing(c->who) < 0)
266     sink_writes(ev_writer_sink(c->w), "550 cannot pause this track\n");
267   else
268     sink_writes(ev_writer_sink(c->w), "250 paused\n");
269   return 1;
270 }
271
272 static int c_resume(struct conn *c,
273                    char attribute((unused)) **vec,
274                    int attribute((unused)) nvec) {
275   if(!paused) {
276     sink_writes(ev_writer_sink(c->w), "250 not paused\n");
277     return 1;                   /* completed */
278   }
279   resume_playing(c->who);
280   sink_writes(ev_writer_sink(c->w), "250 paused\n");
281   return 1;
282 }
283
284 static int c_shutdown(struct conn *c,
285                       char attribute((unused)) **vec,
286                       int attribute((unused)) nvec) {
287   info("S%x shut down by %s", c->tag, c->who);
288   sink_writes(ev_writer_sink(c->w), "250 shutting down\n");
289   ev_writer_flush(c->w);
290   quit(c->ev);
291 }
292
293 static int c_reconfigure(struct conn *c,
294                          char attribute((unused)) **vec,
295                          int attribute((unused)) nvec) {
296   info("S%x reconfigure by %s", c->tag, c->who);
297   if(reconfigure(c->ev, 1))
298     sink_writes(ev_writer_sink(c->w), "550 error reading new config\n");
299   else
300     sink_writes(ev_writer_sink(c->w), "250 installed new config\n");
301   return 1;                             /* completed */
302 }
303
304 static int c_rescan(struct conn *c,
305                     char attribute((unused)) **vec,
306                     int attribute((unused)) nvec) {
307   info("S%x rescan by %s", c->tag, c->who);
308   trackdb_rescan(c->ev);
309   sink_writes(ev_writer_sink(c->w), "250 initiated rescan\n");
310   return 1;                             /* completed */
311 }
312
313 static int c_version(struct conn *c,
314                      char attribute((unused)) **vec,
315                      int attribute((unused)) nvec) {
316   /* VERSION had better only use the basic character set */
317   sink_printf(ev_writer_sink(c->w), "251 %s\n", disorder_version_string);
318   return 1;                     /* completed */
319 }
320
321 static int c_playing(struct conn *c,
322                      char attribute((unused)) **vec,
323                      int attribute((unused)) nvec) {
324   if(playing) {
325     queue_fix_sofar(playing);
326     playing->expected = 0;
327     sink_printf(ev_writer_sink(c->w), "252 %s\n", queue_marshall(playing));
328   } else
329     sink_printf(ev_writer_sink(c->w), "259 nothing playing\n");
330   return 1;                             /* completed */
331 }
332
333 static int c_become(struct conn *c,
334                   char **vec,
335                   int attribute((unused)) nvec) {
336   c->who = vec[0];
337   sink_writes(ev_writer_sink(c->w), "230 OK\n");
338   return 1;
339 }
340
341 static int c_user(struct conn *c,
342                   char **vec,
343                   int attribute((unused)) nvec) {
344   int n;
345   const char *res;
346   union {
347     struct sockaddr sa;
348     struct sockaddr_in in;
349     struct sockaddr_in6 in6;
350   } u;
351   socklen_t l;
352   char host[1024];
353
354   if(c->who) {
355     sink_writes(ev_writer_sink(c->w), "530 already authenticated\n");
356     return 1;
357   }
358   /* get connection data */
359   l = sizeof u;
360   if(getpeername(c->fd, &u.sa, &l) < 0) {
361     error(errno, "S%x error calling getpeername", c->tag);
362     sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
363     return 1;
364   }
365   if(c->l->pf != PF_UNIX) {
366     if((n = getnameinfo(&u.sa, l,
367                         host, sizeof host, 0, 0, NI_NUMERICHOST))) {
368       error(0, "S%x error calling getnameinfo: %s", c->tag, gai_strerror(n));
369       sink_writes(ev_writer_sink(c->w), "530 authentication failure\n");
370       return 1;
371     }
372   } else
373     strcpy(host, "local");
374   /* find the user */
375   for(n = 0; n < config->allow.n
376         && strcmp(config->allow.s[n].s[0], vec[0]); ++n)
377     ;
378   /* if it's a real user check whether the response is right */
379   if(n >= config->allow.n) {
380     info("S%x unknown user '%s' from %s", c->tag, vec[0], host);
381     sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
382     return 1;
383   }
384   res = authhash(c->nonce, sizeof c->nonce, config->allow.s[n].s[1],
385                  config->authorization_algorithm);
386   if(wideopen || (res && !strcmp(res, vec[1]))) {
387     c->who = vec[0];
388     /* currently we only bother logging remote connections */
389     if(c->l->pf != PF_UNIX)
390       info("S%x %s connected from %s", c->tag, vec[0], host);
391     sink_writes(ev_writer_sink(c->w), "230 OK\n");
392     return 1;
393   }
394   /* oops, response was wrong */
395   info("S%x authentication failure for %s from %s", c->tag, vec[0], host);
396   sink_writes(ev_writer_sink(c->w), "530 authentication failed\n");
397   return 1;
398 }
399
400 static int c_recent(struct conn *c,
401                     char attribute((unused)) **vec,
402                     int attribute((unused)) nvec) {
403   const struct queue_entry *q;
404
405   sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
406   for(q = phead.next; q != &phead; q = q->next)
407     sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
408   sink_writes(ev_writer_sink(c->w), ".\n");
409   return 1;                             /* completed */
410 }
411
412 static int c_queue(struct conn *c,
413                    char attribute((unused)) **vec,
414                    int attribute((unused)) nvec) {
415   struct queue_entry *q;
416   time_t when = 0;
417   const char *l;
418   long length;
419
420   sink_writes(ev_writer_sink(c->w), "253 Tracks follow\n");
421   if(playing_is_enabled() && !paused) {
422     if(playing) {
423       queue_fix_sofar(playing);
424       if((l = trackdb_get(playing->track, "_length"))
425          && (length = atol(l))) {
426         time(&when);
427         when += length - playing->sofar + config->gap;
428       }
429     } else
430       /* Nothing is playing but playing is enabled, so whatever is
431        * first in the queue can be expected to start immediately. */
432       time(&when);
433   }
434   for(q = qhead.next; q != &qhead; q = q->next) {
435     /* fill in estimated start time */
436     q->expected = when;
437     sink_printf(ev_writer_sink(c->w), " %s\n", queue_marshall(q));
438     /* update for next track */
439     if(when) {
440       if((l = trackdb_get(q->track, "_length"))
441          && (length = atol(l)))
442         when += length + config->gap;
443       else
444         when = 0;
445     }
446   }
447   sink_writes(ev_writer_sink(c->w), ".\n");
448   return 1;                             /* completed */
449 }
450
451 static int output_list(struct conn *c, char **vec) {
452   while(*vec)
453     sink_printf(ev_writer_sink(c->w), "%s\n", *vec++);
454   sink_writes(ev_writer_sink(c->w), ".\n");
455   return 1;
456 }
457
458 static int files_dirs(struct conn *c,
459                       char **vec,
460                       int nvec,
461                       enum trackdb_listable what) {
462   const char *dir, *re, *errstr;
463   int erroffset;
464   pcre *rec;
465   char **fvec, *key;
466   
467   switch(nvec) {
468   case 0: dir = 0; re = 0; break;
469   case 1: dir = vec[0]; re = 0; break;
470   case 2: dir = vec[0]; re = vec[1]; break;
471   default: abort();
472   }
473   /* A bit of a bodge to make sure the args don't trample on cache keys */
474   if(dir && strchr(dir, '\n')) {
475     sink_writes(ev_writer_sink(c->w), "550 invalid directory name\n");
476     return 1;
477   }
478   if(re && strchr(re, '\n')) {
479     sink_writes(ev_writer_sink(c->w), "550 invalid regexp\n");
480     return 1;
481   }
482   /* We bother eliminating "" because the web interface is relatively
483    * likely to send it */
484   if(re && *re) {
485     byte_xasprintf(&key, "%d\n%s\n%s", (int)what, dir ? dir : "", re);
486     fvec = (char **)cache_get(&cache_files_type, key);
487     if(fvec) {
488       /* Got a cache hit, don't store the answer in the cache */
489       key = 0;
490       ++cache_files_hits;
491       rec = 0;                          /* quieten compiler */
492     } else {
493       /* Cache miss, we'll do the lookup and key != 0 so we'll store the answer
494        * in the cache. */
495       if(!(rec = pcre_compile(re, PCRE_CASELESS|PCRE_UTF8,
496                               &errstr, &erroffset, 0))) {
497         sink_printf(ev_writer_sink(c->w), "550 Error compiling regexp: %s\n",
498                     errstr);
499         return 1;
500       }
501       /* It only counts as a miss if the regexp was valid. */
502       ++cache_files_misses;
503     }
504   } else {
505     /* No regexp, don't bother caching the result */
506     rec = 0;
507     key = 0;
508     fvec = 0;
509   }
510   if(!fvec) {
511     /* No cache hit (either because a miss, or because we did not look) so do
512      * the lookup */
513     if(dir && *dir)
514       fvec = trackdb_list(dir, 0, what, rec);
515     else
516       fvec = trackdb_list(0, 0, what, rec);
517   }
518   if(key)
519     /* Put the answer in the cache */
520     cache_put(&cache_files_type, key, fvec);
521   sink_writes(ev_writer_sink(c->w), "253 Listing follow\n");
522   return output_list(c, fvec);
523 }
524
525 static int c_files(struct conn *c,
526                   char **vec,
527                   int nvec) {
528   return files_dirs(c, vec, nvec, trackdb_files);
529 }
530
531 static int c_dirs(struct conn *c,
532                   char **vec,
533                   int nvec) {
534   return files_dirs(c, vec, nvec, trackdb_directories);
535 }
536
537 static int c_allfiles(struct conn *c,
538                       char **vec,
539                       int nvec) {
540   return files_dirs(c, vec, nvec, trackdb_directories|trackdb_files);
541 }
542
543 static int c_get(struct conn *c,
544                  char **vec,
545                  int attribute((unused)) nvec) {
546   const char *v;
547
548   if(vec[1][0] != '_' && (v = trackdb_get(vec[0], vec[1])))
549     sink_printf(ev_writer_sink(c->w), "252 %s\n", v);
550   else
551     sink_writes(ev_writer_sink(c->w), "550 not found\n");
552   return 1;
553 }
554
555 static int c_length(struct conn *c,
556                  char **vec,
557                  int attribute((unused)) nvec) {
558   const char *track, *v;
559
560   if(!(track = trackdb_resolve(vec[0]))) {
561     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
562     return 1;
563   }
564   if((v = trackdb_get(track, "_length")))
565     sink_printf(ev_writer_sink(c->w), "252 %s\n", v);
566   else
567     sink_writes(ev_writer_sink(c->w), "550 not found\n");
568   return 1;
569 }
570
571 static int c_set(struct conn *c,
572                  char **vec,
573                  int attribute((unused)) nvec) {
574   if(vec[1][0] != '_' && !trackdb_set(vec[0], vec[1], vec[2]))
575     sink_writes(ev_writer_sink(c->w), "250 OK\n");
576   else
577     sink_writes(ev_writer_sink(c->w), "550 not found\n");
578   return 1;
579 }
580
581 static int c_prefs(struct conn *c,
582                    char **vec,
583                    int attribute((unused)) nvec) {
584   struct kvp *k;
585
586   k = trackdb_get_all(vec[0]);
587   sink_writes(ev_writer_sink(c->w), "253 prefs follow\n");
588   for(; k; k = k->next)
589     if(k->name[0] != '_')               /* omit internal values */
590       sink_printf(ev_writer_sink(c->w),
591                   " %s %s\n", quoteutf8(k->name), quoteutf8(k->value));
592   sink_writes(ev_writer_sink(c->w), ".\n");
593   return 1;
594 }
595
596 static int c_exists(struct conn *c,
597                     char **vec,
598                     int attribute((unused)) nvec) {
599   sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[trackdb_exists(vec[0])]);
600   return 1;
601 }
602
603 static void search_parse_error(const char *msg, void *u) {
604   *(const char **)u = msg;
605 }
606
607 static int c_search(struct conn *c,
608                           char **vec,
609                           int attribute((unused)) nvec) {
610   char **terms, **results;
611   int nterms, nresults, n;
612   const char *e = "unknown error";
613
614   /* This is a bit of a bodge.  Initially it's there to make the eclient
615    * interface a bit more convenient to add searching to, but it has the more
616    * compelling advantage that if everything uses it, then interpretation of
617    * user-supplied search strings will be the same everywhere. */
618   if(!(terms = split(vec[0], &nterms, SPLIT_QUOTES, search_parse_error, &e))) {
619     sink_printf(ev_writer_sink(c->w), "550 %s\n", e);
620   } else {
621     results = trackdb_search(terms, nterms, &nresults);
622     sink_printf(ev_writer_sink(c->w), "253 %d matches\n", nresults);
623     for(n = 0; n < nresults; ++n)
624       sink_printf(ev_writer_sink(c->w), "%s\n", results[n]);
625     sink_writes(ev_writer_sink(c->w), ".\n");
626   }
627   return 1;
628 }
629
630 static int c_random_enable(struct conn *c,
631                            char attribute((unused)) **vec,
632                            int attribute((unused)) nvec) {
633   enable_random(c->who, c->ev);
634   /* Enable implicitly unpauses if there is nothing playing */
635   if(paused && !playing) resume_playing(c->who);
636   sink_writes(ev_writer_sink(c->w), "250 OK\n");
637   return 1;                     /* completed */
638 }
639
640 static int c_random_disable(struct conn *c,
641                             char attribute((unused)) **vec,
642                             int attribute((unused)) nvec) {
643   disable_random(c->who);
644   sink_writes(ev_writer_sink(c->w), "250 OK\n");
645   return 1;                     /* completed */
646 }
647
648 static int c_random_enabled(struct conn *c,
649                             char attribute((unused)) **vec,
650                             int attribute((unused)) nvec) {
651   sink_printf(ev_writer_sink(c->w), "252 %s\n", noyes[random_is_enabled()]);
652   return 1;                     /* completed */
653 }
654
655 static void got_stats(char *stats, void *u) {
656   struct conn *const c = u;
657
658   sink_printf(ev_writer_sink(c->w), "253 stats\n%s\n.\n", stats);
659   /* Now we can start processing commands again */
660   ev_reader_enable(c->r);
661 }
662
663 static int c_stats(struct conn *c,
664                    char attribute((unused)) **vec,
665                    int attribute((unused)) nvec) {
666   trackdb_stats_subprocess(c->ev, got_stats, c);
667   return 0;                             /* not yet complete */
668 }
669
670 static int c_volume(struct conn *c,
671                     char **vec,
672                     int nvec) {
673   int l, r, set;
674   char lb[32], rb[32];
675
676   switch(nvec) {
677   case 0:
678     set = 0;
679     break;
680   case 1:
681     l = r = atoi(vec[0]);
682     set = 1;
683     break;
684   case 2:
685     l = atoi(vec[0]);
686     r = atoi(vec[1]);
687     set = 1;
688     break;
689   default:
690     abort();
691   }
692   if(mixer_control(&l, &r, set))
693     sink_writes(ev_writer_sink(c->w), "550 error accessing mixer\n");
694   else {
695     sink_printf(ev_writer_sink(c->w), "252 %d %d\n", l, r);
696     if(l != volume_left || r != volume_right) {
697       volume_left = l;
698       volume_right = r;
699       snprintf(lb, sizeof lb, "%d", l);
700       snprintf(rb, sizeof rb, "%d", r);
701       eventlog("volume", lb, rb, (char *)0);
702     }
703   }
704   return 1;
705 }
706
707 /* we are logging, and some data is available to read */
708 static int logging_reader_callback(ev_source *ev,
709                                    ev_reader *reader,
710                                    void *ptr,
711                                    size_t bytes,
712                                    int eof,
713                                    void *u) {
714   struct conn *c = u;
715
716   /* don't log to this conn any more */
717   eventlog_remove(c->lo);
718   if(c->w) {
719     /* Terminate the log output, but only if the writer hasn't been killed off
720      * from a failure on some earlier write */
721     sink_writes(ev_writer_sink(c->w), ".\n");
722   }
723   /* restore the reader callback */
724   c->reader = reader_callback;
725   /* ...and exit via it */
726   return c->reader(ev, reader, ptr, bytes, eof, u);
727 }
728
729 static void logclient(const char *msg, void *user) {
730   struct conn *c = user;
731
732   if(!c->w || !c->r) {
733     /* This connection has gone up in smoke for some reason */
734     eventlog_remove(c->lo);
735     return;
736   }
737   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" %s\n",
738               (uintmax_t)time(0), msg);
739 }
740
741 static int c_log(struct conn *c,
742                  char attribute((unused)) **vec,
743                  int attribute((unused)) nvec) {
744   time_t now;
745
746   sink_writes(ev_writer_sink(c->w), "254 OK\n");
747   /* pump out initial state */
748   time(&now);
749   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
750               (uintmax_t)now, 
751               playing_is_enabled() ? "enable_play" : "disable_play");
752   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
753               (uintmax_t)now, 
754               random_is_enabled() ? "enable_random" : "disable_random");
755   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state %s\n",
756               (uintmax_t)now, 
757               paused ? "pause" : "resume");
758   if(playing)
759     sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" state playing\n",
760                 (uintmax_t)now);
761   /* Initial volume */
762   sink_printf(ev_writer_sink(c->w), "%"PRIxMAX" volume %d %d\n",
763               (uintmax_t)now, volume_left, volume_right);
764   c->lo = xmalloc(sizeof *c->lo);
765   c->lo->fn = logclient;
766   c->lo->user = c;
767   eventlog_add(c->lo);
768   c->reader = logging_reader_callback;
769   return 0;
770 }
771
772 static void post_move_cleanup(void) {
773   struct queue_entry *q;
774
775   /* If we have caused any random tracks to not be at the end then we make them
776    * no longer be random. */
777   for(q = qhead.next; q != &qhead; q = q->next)
778     if(q->state == playing_random && q->next != &qhead)
779       q->state = playing_unplayed;
780   /* That might mean we need to add a new random track. */
781   add_random_track();
782   queue_write();
783 }
784
785 static int c_move(struct conn *c,
786                   char **vec,
787                   int attribute((unused)) nvec) {
788   struct queue_entry *q;
789   int n;
790
791   if(config->restrictions & RESTRICT_MOVE) {
792     if(!trusted(c)) {
793       sink_writes(ev_writer_sink(c->w),
794                   "550 only trusted users can move tracks\n");
795       return 1;
796     }
797   }
798   if(!(q = queue_find(vec[0]))) {
799     sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
800     return 1;
801   }
802   n = queue_move(q, atoi(vec[1]), c->who);
803   post_move_cleanup();
804   sink_printf(ev_writer_sink(c->w), "252 %d\n", n);
805   /* If we've moved to the head of the queue then prepare the track. */
806   if(q == qhead.next)
807     prepare(c->ev, q);
808   return 1;
809 }
810
811 static int c_moveafter(struct conn *c,
812                        char **vec,
813                        int attribute((unused)) nvec) {
814   struct queue_entry *q, **qs;
815   int n;
816
817   if(config->restrictions & RESTRICT_MOVE) {
818     if(!trusted(c)) {
819       sink_writes(ev_writer_sink(c->w),
820                   "550 only trusted users can move tracks\n");
821       return 1;
822     }
823   }
824   if(vec[0][0]) {
825     if(!(q = queue_find(vec[0]))) {
826       sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
827       return 1;
828     }
829   } else
830     q = 0;
831   ++vec;
832   --nvec;
833   qs = xcalloc(nvec, sizeof *qs);
834   for(n = 0; n < nvec; ++n)
835     if(!(qs[n] = queue_find(vec[n]))) {
836       sink_writes(ev_writer_sink(c->w), "550 no such track on the queue\n");
837       return 1;
838     }
839   queue_moveafter(q, nvec, qs, c->who);
840   post_move_cleanup();
841   sink_printf(ev_writer_sink(c->w), "250 Moved tracks\n");
842   /* If we've moved to the head of the queue then prepare the track. */
843   if(q == qhead.next)
844     prepare(c->ev, q);
845   return 1;
846 }
847
848 static int c_part(struct conn *c,
849                   char **vec,
850                   int attribute((unused)) nvec) {
851   sink_printf(ev_writer_sink(c->w), "252 %s\n",
852               trackdb_getpart(vec[0], vec[1], vec[2]));
853   return 1;
854 }
855
856 static int c_resolve(struct conn *c,
857                      char **vec,
858                      int attribute((unused)) nvec) {
859   const char *track;
860
861   if(!(track = trackdb_resolve(vec[0]))) {
862     sink_writes(ev_writer_sink(c->w), "550 cannot resolve track\n");
863     return 1;
864   }
865   sink_printf(ev_writer_sink(c->w), "252 %s\n", track);
866   return 1;
867 }
868
869 static int c_tags(struct conn *c,
870                   char attribute((unused)) **vec,
871                   int attribute((unused)) nvec) {
872   char **tags = trackdb_alltags();
873   
874   sink_printf(ev_writer_sink(c->w), "253 Tag list follows\n");
875   while(*tags) {
876     sink_printf(ev_writer_sink(c->w), "%s%s\n",
877                 **tags == '.' ? "." : "", *tags);
878     ++tags;
879   }
880   sink_writes(ev_writer_sink(c->w), ".\n");
881   return 1;                             /* completed */
882
883 }
884
885 static int c_set_global(struct conn *c,
886                         char **vec,
887                         int attribute((unused)) nvec) {
888   trackdb_set_global(vec[0], vec[1], c->who);
889   sink_printf(ev_writer_sink(c->w), "250 OK\n");
890   return 1;
891 }
892
893 static int c_get_global(struct conn *c,
894                         char **vec,
895                         int attribute((unused)) nvec) {
896   const char *s = trackdb_get_global(vec[0]);
897
898   if(s)
899     sink_printf(ev_writer_sink(c->w), "252 %s\n", s);
900   else
901     sink_writes(ev_writer_sink(c->w), "550 not found\n");
902   return 1;
903 }
904
905 static int c_nop(struct conn *c,
906                  char attribute((unused)) **vec,
907                  int attribute((unused)) nvec) {
908   sink_printf(ev_writer_sink(c->w), "250 Quack\n");
909   return 1;
910 }
911
912 static int c_new(struct conn *c,
913                  char **vec,
914                  int nvec) {
915   char **tracks = trackdb_new(0, nvec > 0 ? atoi(vec[0]) : INT_MAX);
916
917   sink_printf(ev_writer_sink(c->w), "253 New track list follows\n");
918   while(*tracks) {
919     sink_printf(ev_writer_sink(c->w), "%s%s\n",
920                 **tracks == '.' ? "." : "", *tracks);
921     ++tracks;
922   }
923   sink_writes(ev_writer_sink(c->w), ".\n");
924   return 1;                             /* completed */
925
926 }
927
928 static int c_rtp_address(struct conn *c,
929                          char attribute((unused)) **vec,
930                          int attribute((unused)) nvec) {
931   if(config->speaker_backend == BACKEND_NETWORK) {
932     sink_printf(ev_writer_sink(c->w), "252 %s %s\n",
933                 quoteutf8(config->broadcast.s[0]),
934                 quoteutf8(config->broadcast.s[1]));
935   } else
936     sink_writes(ev_writer_sink(c->w), "550 No RTP\n");
937   return 1;
938 }
939  
940 #define C_AUTH          0001            /* must be authenticated */
941 #define C_TRUSTED       0002            /* must be trusted user */
942
943 static const struct command {
944   const char *name;
945   int minargs, maxargs;
946   int (*fn)(struct conn *, char **, int);
947   unsigned flags;
948 } commands[] = {
949   { "allfiles",       0, 2,       c_allfiles,       C_AUTH },
950   { "become",         1, 1,       c_become,         C_AUTH|C_TRUSTED },
951   { "dirs",           0, 2,       c_dirs,           C_AUTH },
952   { "disable",        0, 1,       c_disable,        C_AUTH },
953   { "enable",         0, 0,       c_enable,         C_AUTH },
954   { "enabled",        0, 0,       c_enabled,        C_AUTH },
955   { "exists",         1, 1,       c_exists,         C_AUTH },
956   { "files",          0, 2,       c_files,          C_AUTH },
957   { "get",            2, 2,       c_get,            C_AUTH },
958   { "get-global",     1, 1,       c_get_global,     C_AUTH },
959   { "length",         1, 1,       c_length,         C_AUTH },
960   { "log",            0, 0,       c_log,            C_AUTH },
961   { "move",           2, 2,       c_move,           C_AUTH },
962   { "moveafter",      1, INT_MAX, c_moveafter,      C_AUTH },
963   { "new",            0, 1,       c_new,            C_AUTH },
964   { "nop",            0, 0,       c_nop,            C_AUTH },
965   { "part",           3, 3,       c_part,           C_AUTH },
966   { "pause",          0, 0,       c_pause,          C_AUTH },
967   { "play",           1, 1,       c_play,           C_AUTH },
968   { "playing",        0, 0,       c_playing,        C_AUTH },
969   { "prefs",          1, 1,       c_prefs,          C_AUTH },
970   { "queue",          0, 0,       c_queue,          C_AUTH },
971   { "random-disable", 0, 0,       c_random_disable, C_AUTH },
972   { "random-enable",  0, 0,       c_random_enable,  C_AUTH },
973   { "random-enabled", 0, 0,       c_random_enabled, C_AUTH },
974   { "recent",         0, 0,       c_recent,         C_AUTH },
975   { "reconfigure",    0, 0,       c_reconfigure,    C_AUTH|C_TRUSTED },
976   { "remove",         1, 1,       c_remove,         C_AUTH },
977   { "rescan",         0, 0,       c_rescan,         C_AUTH|C_TRUSTED },
978   { "resolve",        1, 1,       c_resolve,        C_AUTH },
979   { "resume",         0, 0,       c_resume,         C_AUTH },
980   { "rtp-address",    0, 0,       c_rtp_address,    C_AUTH },
981   { "scratch",        0, 1,       c_scratch,        C_AUTH },
982   { "search",         1, 1,       c_search,         C_AUTH },
983   { "set",            3, 3,       c_set,            C_AUTH, },
984   { "set-global",     2, 2,       c_set_global,     C_AUTH },
985   { "shutdown",       0, 0,       c_shutdown,       C_AUTH|C_TRUSTED },
986   { "stats",          0, 0,       c_stats,          C_AUTH },
987   { "tags",           0, 0,       c_tags,           C_AUTH },
988   { "unset",          2, 2,       c_set,            C_AUTH },
989   { "unset-global",   1, 1,       c_set_global,      C_AUTH },
990   { "user",           2, 2,       c_user,           0 },
991   { "version",        0, 0,       c_version,        C_AUTH },
992   { "volume",         0, 2,       c_volume,         C_AUTH }
993 };
994
995 static void command_error(const char *msg, void *u) {
996   struct conn *c = u;
997
998   sink_printf(ev_writer_sink(c->w), "500 parse error: %s\n", msg);
999 }
1000
1001 /* process a command.  Return 1 if complete, 0 if incomplete. */
1002 static int command(struct conn *c, char *line) {
1003   char **vec;
1004   int nvec, n;
1005
1006   D(("server command %s", line));
1007   if(!(vec = split(line, &nvec, SPLIT_QUOTES, command_error, c))) {
1008     sink_writes(ev_writer_sink(c->w), "500 cannot parse command\n");
1009     return 1;
1010   }
1011   if(nvec == 0) {
1012     sink_writes(ev_writer_sink(c->w), "500 do what?\n");
1013     return 1;
1014   }
1015   if((n = TABLE_FIND(commands, struct command, name, vec[0])) < 0)
1016     sink_writes(ev_writer_sink(c->w), "500 unknown command\n");
1017   else {
1018     if((commands[n].flags & C_AUTH) && !c->who) {
1019       sink_writes(ev_writer_sink(c->w), "530 not authenticated\n");
1020       return 1;
1021     }
1022     if((commands[n].flags & C_TRUSTED) && !trusted(c)) {
1023       sink_writes(ev_writer_sink(c->w), "530 insufficient privilege\n");
1024       return 1;
1025     }
1026     ++vec;
1027     --nvec;
1028     if(nvec < commands[n].minargs) {
1029       sink_writes(ev_writer_sink(c->w), "500 missing argument(s)\n");
1030       return 1;
1031     }
1032     if(nvec > commands[n].maxargs) {
1033       sink_writes(ev_writer_sink(c->w), "500 too many arguments\n");
1034       return 1;
1035     }
1036     return commands[n].fn(c, vec, nvec);
1037   }
1038   return 1;                     /* completed */
1039 }
1040
1041 /* redirect to the right reader callback for our current state */
1042 static int redirect_reader_callback(ev_source *ev,
1043                                     ev_reader *reader,
1044                                     void *ptr,
1045                                     size_t bytes,
1046                                     int eof,
1047                                     void *u) {
1048   struct conn *c = u;
1049
1050   return c->reader(ev, reader, ptr, bytes, eof, u);
1051 }
1052
1053 /* the main command reader */
1054 static int reader_callback(ev_source attribute((unused)) *ev,
1055                            ev_reader *reader,
1056                            void *ptr,
1057                            size_t bytes,
1058                            int eof,
1059                            void *u) {
1060   struct conn *c = u;
1061   char *eol;
1062   int complete;
1063
1064   D(("server reader_callback"));
1065   while((eol = memchr(ptr, '\n', bytes))) {
1066     *eol++ = 0;
1067     ev_reader_consume(reader, eol - (char *)ptr);
1068     complete = command(c, ptr);
1069     bytes -= (eol - (char *)ptr);
1070     ptr = eol;
1071     if(!complete) {
1072       /* the command had better have set a new reader callback */
1073       if(bytes || eof)
1074         /* there are further bytes to read, or we are at eof; arrange for the
1075          * command's reader callback to handle them */
1076         return ev_reader_incomplete(reader);
1077       /* nothing's going on right now */
1078       return 0;
1079     }
1080     /* command completed, we can go around and handle the next one */
1081   }
1082   if(eof) {
1083     if(bytes)
1084       error(0, "S%x unterminated line", c->tag);
1085     c->r = 0;
1086     return ev_writer_close(c->w);
1087   }
1088   return 0;
1089 }
1090
1091 static int listen_callback(ev_source *ev,
1092                            int fd,
1093                            const struct sockaddr attribute((unused)) *remote,
1094                            socklen_t attribute((unused)) rlen,
1095                            void *u) {
1096   const struct listener *l = u;
1097   struct conn *c = xmalloc(sizeof *c);
1098   static unsigned tags;
1099
1100   D(("server listen_callback fd %d (%s)", fd, l->name));
1101   nonblock(fd);
1102   cloexec(fd);
1103   c->tag = tags++;
1104   c->ev = ev;
1105   c->w = ev_writer_new(ev, fd, writer_error, c,
1106                        "client writer");
1107   c->r = ev_reader_new(ev, fd, redirect_reader_callback, reader_error, c,
1108                        "client reader");
1109   ev_tie(c->r, c->w);
1110   c->fd = fd;
1111   c->reader = reader_callback;
1112   c->l = l;
1113   gcry_randomize(c->nonce, sizeof c->nonce, GCRY_STRONG_RANDOM);
1114   if(!strcmp(config->authorization_algorithm, "sha1")
1115      || !strcmp(config->authorization_algorithm, "SHA1")) {
1116     sink_printf(ev_writer_sink(c->w), "231 %s\n",
1117                 hex(c->nonce, sizeof c->nonce));
1118   } else {
1119     sink_printf(ev_writer_sink(c->w), "231 %s %s\n",
1120                 config->authorization_algorithm,
1121                 hex(c->nonce, sizeof c->nonce));
1122   }
1123   return 0;
1124 }
1125
1126 int server_start(ev_source *ev, int pf,
1127                  size_t socklen, const struct sockaddr *sa,
1128                  const char *name) {
1129   int fd;
1130   struct listener *l = xmalloc(sizeof *l);
1131   static const int one = 1;
1132
1133   D(("server_init socket %s", name));
1134   fd = xsocket(pf, SOCK_STREAM, 0);
1135   xsetsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
1136   if(bind(fd, sa, socklen) < 0) {
1137     error(errno, "error binding to %s", name);
1138     return -1;
1139   }
1140   xlisten(fd, 128);
1141   nonblock(fd);
1142   cloexec(fd);
1143   l->name = name;
1144   l->pf = pf;
1145   if(ev_listen(ev, fd, listen_callback, l, "server listener"))
1146     exit(EXIT_FAILURE);
1147   return fd;
1148 }
1149
1150 int server_stop(ev_source *ev, int fd) {
1151   xclose(fd);
1152   return ev_listen_cancel(ev, fd);
1153 }
1154
1155 /*
1156 Local Variables:
1157 c-basic-offset:2
1158 comment-column:40
1159 fill-column:79
1160 End:
1161 */