chiark / gitweb /
disable LC_COLLATE for shell globbing
[disorder] / lib / eclient.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 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 /** @file lib/eclient.c
21  * @brief Client code for event-driven programs
22  */
23
24 #include <config.h>
25 #include "types.h"
26
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <sys/un.h>
31 #include <string.h>
32 #include <stdio.h>
33 #include <unistd.h>
34 #include <errno.h>
35 #include <netdb.h>
36 #include <stdlib.h>
37 #include <assert.h>
38 #include <inttypes.h>
39 #include <stddef.h>
40 #include <time.h>
41
42 #include "log.h"
43 #include "mem.h"
44 #include "configuration.h"
45 #include "queue.h"
46 #include "eclient.h"
47 #include "charset.h"
48 #include "hex.h"
49 #include "split.h"
50 #include "vector.h"
51 #include "inputline.h"
52 #include "kvp.h"
53 #include "syscalls.h"
54 #include "printf.h"
55 #include "addr.h"
56 #include "authhash.h"
57 #include "table.h"
58 #include "client-common.h"
59
60 /* TODO: more commands */
61
62 /** @brief How often to send data to the server when receiving logs */
63 #define LOG_PROD_INTERVAL 10
64
65 /* Types *********************************************************************/
66
67 /** @brief Client state */
68 enum client_state {
69   state_disconnected,          /**< @brief not connected */
70   state_connecting,            /**< @brief waiting for connect() */
71   state_connected,             /**< @brief connected but not authenticated */
72   state_idle,                  /**< @brief not doing anything */
73   state_cmdresponse,           /**< @brief waiting for command resonse */
74   state_body,                  /**< @brief accumulating body */
75   state_log,                   /**< @brief monitoring log */
76 };
77
78 /** @brief Names for @ref client_state */
79 static const char *const states[] = {
80   "disconnected",
81   "connecting",
82   "connected",
83   "idle",
84   "cmdresponse",
85   "body",
86   "log"
87 };
88
89 struct operation;                       /* forward decl */
90
91 /** @brief Type of an operation callback */
92 typedef void operation_callback(disorder_eclient *c, struct operation *op);
93
94 /** @brief A pending operation.
95  *
96  * This can be either a command or part of the authentication protocol.  In the
97  * former case new commands are appended to the list, in the latter case they
98  * are inserted at the front. */
99 struct operation {
100   struct operation *next;          /**< @brief next operation */
101   char *cmd;                       /**< @brief command to send or 0 */
102   operation_callback *opcallback;  /**< @brief internal completion callback */
103   void (*completed)();             /**< @brief user completion callback or 0 */
104   void *v;                         /**< @brief data for COMPLETED */
105   disorder_eclient *client;        /**< @brief owning client */
106
107   /** @brief true if sent to server
108    *
109    * This is cleared by disorder_eclient_close(), forcing all queued
110    * commands to be transparently resent.
111    */
112   int sent;
113 };
114
115 /** @brief Client structure */
116 struct disorder_eclient {
117   const char *ident;
118   int fd;                               /**< @brief connection to server */
119   enum client_state state;              /**< @brief current state */
120   int authenticated;                    /**< @brief true when authenicated */
121   struct dynstr output;                 /**< @brief output buffer */
122   struct dynstr input;                  /**< @brief input buffer */
123   int eof;                              /**< @brief input buffer is at EOF */
124   const disorder_eclient_callbacks *callbacks; /**< @brief error callbacks */
125   void *u;                              /**< @brief user data */
126   struct operation *ops;                /**< @brief queue of operations */
127   struct operation **opstail;           /**< @brief queue tail */
128   /* accumulated response */
129   int rc;                               /**< @brief response code */
130   char *line;                           /**< @brief complete line */
131   struct vector vec;                    /**< @brief body */
132
133   const disorder_eclient_log_callbacks *log_callbacks;
134   /**< @brief log callbacks
135    *
136    * Once disorder_eclient_log() has been issued this is always set.  When we
137    * re-connect it is checked to re-issue the log command.
138    */
139   void *log_v;                          /**< @brief user data */
140   unsigned long statebits;              /**< @brief latest state */
141
142   time_t last_prod;
143   /**< @brief last time we sent a prod
144    *
145    * When we are receiving log data we send a "prod" byte to the server from
146    * time to time so that we detect broken connections reasonably quickly.  The
147    * server just ignores these bytes.
148    */
149 };
150
151 /* Forward declarations ******************************************************/
152
153 static int start_connect(void *cc,
154                          const struct sockaddr *sa,
155                          socklen_t len,
156                          const char *ident);
157 static void process_line(disorder_eclient *c, char *line);
158 static int start_connect(void *cc,
159                          const struct sockaddr *sa,
160                          socklen_t len,
161                          const char *ident);
162 static void maybe_connected(disorder_eclient *c);
163 static void authbanner_opcallback(disorder_eclient *c,
164                                   struct operation *op);
165 static void authuser_opcallback(disorder_eclient *c,
166                                 struct operation *op);
167 static void complete(disorder_eclient *c);
168 static void send_output(disorder_eclient *c);
169 static void put(disorder_eclient *c, const char *s, size_t n);
170 static void read_input(disorder_eclient *c);
171 static void stash_command(disorder_eclient *c,
172                           int queuejump,
173                           operation_callback *opcallback,
174                           void (*completed)(),
175                           void *v,
176                           const char *cmd,
177                           ...);
178 static void log_opcallback(disorder_eclient *c, struct operation *op);
179 static void logline(disorder_eclient *c, const char *line);
180 static void logentry_completed(disorder_eclient *c, int nvec, char **vec);
181 static void logentry_failed(disorder_eclient *c, int nvec, char **vec);
182 static void logentry_moved(disorder_eclient *c, int nvec, char **vec);
183 static void logentry_playing(disorder_eclient *c, int nvec, char **vec);
184 static void logentry_queue(disorder_eclient *c, int nvec, char **vec);
185 static void logentry_recent_added(disorder_eclient *c, int nvec, char **vec);
186 static void logentry_recent_removed(disorder_eclient *c, int nvec, char **vec);
187 static void logentry_removed(disorder_eclient *c, int nvec, char **vec);
188 static void logentry_scratched(disorder_eclient *c, int nvec, char **vec);
189 static void logentry_state(disorder_eclient *c, int nvec, char **vec);
190 static void logentry_volume(disorder_eclient *c, int nvec, char **vec);
191 static void logentry_rescanned(disorder_eclient *c, int nvec, char **vec);
192
193 /* Tables ********************************************************************/
194
195 /** @brief One possible log entry */
196 struct logentry_handler {
197   const char *name;                     /**< @brief Entry name */
198   int min;                              /**< @brief Minimum arguments */
199   int max;                              /**< @brief Maximum arguments */
200   void (*handler)(disorder_eclient *c,
201                   int nvec,
202                   char **vec);          /**< @brief Handler function */
203 };
204
205 /** @brief Table for parsing log entries */
206 static const struct logentry_handler logentry_handlers[] = {
207 #define LE(X, MIN, MAX) { #X, MIN, MAX, logentry_##X }
208   LE(completed, 1, 1),
209   LE(failed, 2, 2),
210   LE(moved, 1, 1),
211   LE(playing, 1, 2),
212   LE(queue, 2, INT_MAX),
213   LE(recent_added, 2, INT_MAX),
214   LE(recent_removed, 1, 1),
215   LE(removed, 1, 2),
216   LE(rescanned, 0, 0),
217   LE(scratched, 2, 2),
218   LE(state, 1, 1),
219   LE(volume, 2, 2)
220 };
221
222 /* Setup and teardown ********************************************************/
223
224 /** @brief Create a new client
225  *
226  * Does NOT connect the client - connections are made (and re-made) on demand.
227  */
228 disorder_eclient *disorder_eclient_new(const disorder_eclient_callbacks *cb,
229                                        void *u) {
230   disorder_eclient *c = xmalloc(sizeof *c);
231   D(("disorder_eclient_new"));
232   c->fd = -1;
233   c->callbacks = cb;
234   c->u = u;
235   c->opstail = &c->ops;
236   vector_init(&c->vec);
237   dynstr_init(&c->input);
238   dynstr_init(&c->output);
239   if(!config->password) {
240     error(0, "no password set");
241     return 0;
242   }
243   return c;
244 }
245
246 /** @brief Disconnect a client
247  * @param c Client to disconnect
248  *
249  * NB that this routine just disconnnects the TCP connection.  It does not
250  * destroy the client!  If you continue to use it then it will attempt to
251  * reconnect.
252  */
253 void disorder_eclient_close(disorder_eclient *c) {
254   struct operation *op;
255
256   D(("disorder_eclient_close"));
257   if(c->fd != -1) {
258     D(("disorder_eclient_close closing fd %d", c->fd));
259     c->callbacks->poll(c->u, c, c->fd, 0);
260     xclose(c->fd);
261     c->fd = -1;
262     c->state = state_disconnected;
263     c->statebits = 0;
264   }
265   c->output.nvec = 0;
266   c->input.nvec = 0;
267   c->eof = 0;
268   c->authenticated = 0;
269   /* We'll need to resend all operations */
270   for(op = c->ops; op; op = op->next)
271     op->sent = 0;
272   /* Drop our use a hint that we're disconnected */
273   if(c->log_callbacks && c->log_callbacks->state)
274     c->log_callbacks->state(c->log_v, c->statebits);
275 }
276
277 /** @brief Return current state */
278 unsigned long disorder_eclient_state(const disorder_eclient *c) {
279   return c->statebits | (c->state > state_connected ? DISORDER_CONNECTED : 0);
280 }
281
282 /* Error reporting ***********************************************************/
283
284 /** @brief called when a connection error occurs
285  *
286  * After this called we will be disconnected (by disorder_eclient_close()),
287  * so there will be a reconnection before any commands can be sent.
288  */
289 static int comms_error(disorder_eclient *c, const char *fmt, ...) {
290   va_list ap;
291   char *s;
292
293   D(("comms_error"));
294   va_start(ap, fmt);
295   byte_xvasprintf(&s, fmt, ap);
296   va_end(ap);
297   disorder_eclient_close(c);
298   c->callbacks->comms_error(c->u, s);
299   return -1;
300 }
301
302 /** @brief called when the server reports an error */
303 static int protocol_error(disorder_eclient *c, struct operation *op,
304                           int code, const char *fmt, ...) {
305   va_list ap;
306   char *s;
307
308   D(("protocol_error"));
309   va_start(ap, fmt);
310   byte_xvasprintf(&s, fmt, ap);
311   va_end(ap);
312   c->callbacks->protocol_error(c->u, op->v, code, s);
313   return -1;
314 }
315
316 /* State machine *************************************************************/
317
318 /** @brief Called when there's something to do
319  * @param c Client
320  * @param mode bitmap of @ref DISORDER_POLL_READ and/or @ref DISORDER_POLL_WRITE.
321  *
322  * This should be called from by your code when the file descriptor is readable
323  * or writable (as requested by the @c poll callback, see @ref
324  * disorder_eclient_callbacks) and in any case from time to time (with @p mode
325  * = 0) to allow for retries to work.
326  */
327 void disorder_eclient_polled(disorder_eclient *c, unsigned mode) {
328   struct operation *op;
329   time_t now;
330   
331   D(("disorder_eclient_polled fd=%d state=%s mode=[%s %s]",
332      c->fd, states[c->state],
333      mode & DISORDER_POLL_READ ? "READ" : "",
334      mode & DISORDER_POLL_WRITE ? "WRITE" : ""));
335   /* The pattern here is to check each possible state in turn and try to
336    * advance (though on error we might go back).  If we advance we leave open
337    * the possibility of falling through to the next state, but we set the mode
338    * bits to 0, to avoid false positives (which matter more in some cases than
339    * others). */
340
341   if(c->state == state_disconnected) {
342     D(("state_disconnected"));
343     with_sockaddr(c, start_connect);
344     /* might now be state_disconnected (on error), state_connecting (slow
345      * connect) or state_connected (fast connect).  If state_disconnected then
346      * we just rely on a periodic callback from the event loop sometime. */
347     mode = 0;
348   }
349
350   if(c->state == state_connecting && mode) {
351     D(("state_connecting"));
352     maybe_connected(c);
353     /* Might be state_disconnected (on error) or state_connected (on success).
354      * In the former case we rely on the event loop for a periodic callback to
355      * retry. */
356     mode = 0;
357   }
358
359   if(c->state == state_connected) {
360     D(("state_connected"));
361     /* We just connected.  Initiate the authentication protocol. */
362     stash_command(c, 1/*queuejump*/, authbanner_opcallback,
363                   0/*completed*/, 0/*v*/, 0/*cmd*/);
364     /* We never stay is state_connected very long.  We could in principle jump
365      * straight to state_cmdresponse since there's actually no command to
366      * send, but that would arguably be cheating. */
367     c->state = state_idle;
368   }
369
370   if(c->state == state_idle) {
371     D(("state_idle"));
372     /* We are connected, and have finished any command we set off, look for
373      * some work to do */
374     if(c->ops) {
375       D(("have ops"));
376       if(c->authenticated) {
377         /* Transmit all unsent operations */
378         for(op = c->ops; op; op = op->next) {
379           if(!op->sent) {
380             put(c, op->cmd, strlen(op->cmd));
381             op->sent = 1;
382           }
383         }
384       } else {
385         /* Just send the head operation */
386         if(c->ops->cmd && !c->ops->sent) {
387           put(c, c->ops->cmd, strlen(c->ops->cmd));
388           c->ops->sent = 1;
389         }
390       }
391       /* Awaiting response for the operation at the head of the list */
392       c->state = state_cmdresponse;
393     } else
394       /* genuinely idle */
395       c->callbacks->report(c->u, 0);
396   }
397
398   /* Queue up a byte to send */
399   if(c->state == state_log
400      && c->output.nvec == 0
401      && time(&now) - c->last_prod > LOG_PROD_INTERVAL) {
402     put(c, "x", 1);
403     c->last_prod = now;
404   }
405   
406   if(c->state == state_cmdresponse
407      || c->state == state_body
408      || c->state == state_log) {
409     D(("state_%s", states[c->state]));
410     /* We are awaiting a response */
411     if(mode & DISORDER_POLL_WRITE) send_output(c);
412     if(mode & DISORDER_POLL_READ) read_input(c);
413     /* There are a couple of reasons we might want to re-enter the state
414      * machine from the top.  state_idle is obvious: there may be further
415      * commands to process.  Re-entering on state_disconnected means that we
416      * immediately retry connection if a comms error occurs during a command.
417      * This is different to the case where a connection fails, where we await a
418      * spontaneous call to initiate the retry. */
419     switch(c->state) {
420     case state_disconnected:            /* lost connection */
421     case state_idle:                    /* completed a command */
422       D(("retrying"));
423       disorder_eclient_polled(c, 0);
424       return;
425     default:
426       break;
427     }
428   }
429   
430   /* Figure out what to set the mode to */
431   switch(c->state) {
432   case state_disconnected:
433     D(("state_disconnected (2)"));
434     /* Probably an error occurred.  Await a retry. */
435     mode = 0;
436     break;
437   case state_connecting:
438     D(("state_connecting (2)"));
439     /* Waiting for connect to complete */
440     mode = DISORDER_POLL_READ|DISORDER_POLL_WRITE;
441     break;
442   case state_connected:
443     D(("state_connected (2)"));
444     assert(!"should never be in state_connected here");
445     break;
446   case state_idle:
447     D(("state_idle (2)"));
448     /* Connected but nothing to do. */
449     mode = 0;
450     break;
451   case state_cmdresponse:
452   case state_body:
453   case state_log:
454     D(("state_%s (2)", states[c->state]));
455     /* Gathering a response.  Wait for input. */
456     mode = DISORDER_POLL_READ;
457     /* Flush any pending output. */
458     if(c->output.nvec) mode |= DISORDER_POLL_WRITE;
459     break;
460   }
461   D(("fd=%d new mode [%s %s]",
462      c->fd,
463      mode & DISORDER_POLL_READ ? "READ" : "",
464      mode & DISORDER_POLL_WRITE ? "WRITE" : ""));
465   if(c->fd != -1) c->callbacks->poll(c->u, c, c->fd, mode);
466 }
467
468 /** @brief Called to start connecting */
469 static int start_connect(void *cc,
470                          const struct sockaddr *sa,
471                          socklen_t len,
472                          const char *ident) {
473   disorder_eclient *c = cc;
474
475   D(("start_connect"));
476   c->ident = xstrdup(ident);
477   if(c->fd != -1) {
478     xclose(c->fd);
479     c->fd = -1;
480   }
481   if((c->fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
482     return comms_error(c, "socket: %s", strerror(errno));
483   c->eof = 0;
484   nonblock(c->fd);
485   cloexec(c->fd);
486   if(connect(c->fd, sa, len) < 0) {
487     switch(errno) {
488     case EINTR:
489     case EINPROGRESS:
490       c->state = state_connecting;
491       /* We are called from _polled so the state machine will get to do its
492        * thing */
493       return 0;
494     default:
495       /* Signal the error to the caller. */
496       return comms_error(c, "connecting to %s: %s", ident, strerror(errno));
497     }
498   } else
499     c->state = state_connected;
500   return 0;
501 }
502
503 /** @brief Called when poll triggers while waiting for a connection */
504 static void maybe_connected(disorder_eclient *c) {
505   /* We either connected, or got an error. */
506   int err;
507   socklen_t len = sizeof err;
508   
509   D(("maybe_connected"));
510   /* Work around over-enthusiastic error slippage */
511   if(getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0)
512     err = errno;
513   if(err) {
514     /* The connection failed */
515     comms_error(c, "connecting to %s: %s", c->ident, strerror(err));
516     /* sets state_disconnected */
517   } else {
518     char *r;
519     
520     /* The connection succeeded */
521     c->state = state_connected;
522     byte_xasprintf(&r, "connected to %s", c->ident);
523     c->callbacks->report(c->u, r);
524     /* If this is a log client we expect to get a bunch of updates from the
525      * server straight away */
526   }
527 }
528
529 /* Authentication ************************************************************/
530
531 static void authbanner_opcallback(disorder_eclient *c,
532                                   struct operation *op) {
533   size_t nonce_len;
534   const unsigned char *nonce;
535   const char *res;
536   char **rvec;
537   int nrvec;
538   const char *algo = "SHA1";
539   
540   D(("authbanner_opcallback"));
541   if(c->rc / 100 != 2
542      || !(rvec = split(c->line + 4, &nrvec, SPLIT_QUOTES, 0, 0))
543      || nrvec < 1) {
544     /* Banner told us to go away, or was malformed.  We cannot proceed. */
545     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
546     disorder_eclient_close(c);
547     return;
548   }
549   if(nrvec > 1) {
550     algo = *rvec++;
551     --nrvec;
552   }
553   nonce = unhex(rvec[0], &nonce_len);
554   res = authhash(nonce, nonce_len, config->password, algo);
555   if(!res) {
556     protocol_error(c, op, c->rc, "%s: unknown authentication algorithm '%s'",
557                    c->ident, algo);
558     disorder_eclient_close(c);
559     return;
560   }
561   stash_command(c, 1/*queuejump*/, authuser_opcallback, 0/*completed*/, 0/*v*/,
562                 "user", quoteutf8(config->username), quoteutf8(res),
563                 (char *)0);
564 }
565
566 static void authuser_opcallback(disorder_eclient *c,
567                                 struct operation *op) {
568   char *r;
569
570   D(("authuser_opcallback"));
571   if(c->rc / 100 != 2) {
572     /* Wrong password or something.  We cannot proceed. */
573     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
574     disorder_eclient_close(c);
575     return;
576   }
577   /* OK, we're authenticated now. */
578   c->authenticated = 1;
579   byte_xasprintf(&r, "authenticated with %s", c->ident);
580   c->callbacks->report(c->u, r);
581   if(c->log_callbacks && !(c->ops && c->ops->opcallback == log_opcallback))
582     /* We are a log client, switch to logging mode */
583     stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, c->log_v,
584                   "log", (char *)0);
585 }
586
587 /* Output ********************************************************************/
588
589 /* Chop N bytes off the front of a dynstr */
590 static void consume(struct dynstr *d, int n) {
591   D(("consume %d", n));
592   assert(d->nvec >= n);
593   memmove(d->vec, d->vec + n, d->nvec - n);
594   d->nvec -= n;
595 }
596
597 /* Write some bytes */
598 static void put(disorder_eclient *c, const char *s, size_t n) {
599   D(("put %d %.*s", c->fd, (int)n, s));
600   dynstr_append_bytes(&c->output, s, n);
601 }
602
603 /* Called when we can write to our FD, or at any other time */
604 static void send_output(disorder_eclient *c) {
605   int n;
606
607   D(("send_output %d bytes pending", c->output.nvec));
608   if(c->state > state_connecting && c->output.nvec) {
609     n = write(c->fd, c->output.vec, c->output.nvec);
610     if(n < 0) {
611       switch(errno) {
612       case EINTR:
613       case EAGAIN:
614         break;
615       default:
616         comms_error(c, "writing to %s: %s", c->ident, strerror(errno));
617         break;
618       }
619     } else
620       consume(&c->output, n);
621   }
622 }
623
624 /* Input *********************************************************************/
625
626 /* Called when c->fd might be readable, or at any other time */
627 static void read_input(disorder_eclient *c) {
628   char *nl;
629   int n;
630   char buffer[512];
631
632   D(("read_input in state %s", states[c->state]));
633   if(c->state <= state_connected) return; /* ignore bogus calls */
634   /* read some more input */
635   n = read(c->fd, buffer, sizeof buffer);
636   if(n < 0) {
637     switch(errno) {
638     case EINTR:
639     case EAGAIN:
640       break;
641     default:
642       comms_error(c, "reading from %s: %s", c->ident, strerror(errno));
643       break;
644     }
645     return;                             /* no new input to process */
646   } else if(n) {
647     D(("read %d bytes: [%.*s]", n, n, buffer));
648     dynstr_append_bytes(&c->input, buffer, n);
649   } else
650     c->eof = 1;
651   /* might have more than one line to process */
652   while(c->state > state_connecting
653         && (nl = memchr(c->input.vec, '\n', c->input.nvec))) {
654     process_line(c, xstrndup(c->input.vec, nl - c->input.vec));
655     /* we might have disconnected along the way, which zogs the input buffer */
656     if(c->state > state_connecting)
657       consume(&c->input, (nl - c->input.vec) + 1);
658   }
659   if(c->eof) {
660     comms_error(c, "reading from %s: server disconnected", c->ident);
661     c->authenticated = 0;
662   }
663 }
664
665 /* called with a line that has just been read */
666 static void process_line(disorder_eclient *c, char *line) {
667   D(("process_line %d [%s]", c->fd, line));
668   switch(c->state) {
669   case state_cmdresponse:
670     /* This is the first line of a response */
671     if(!(line[0] >= '0' && line[0] <= '9'
672          && line[1] >= '0' && line[1] <= '9'
673          && line[2] >= '0' && line[2] <= '9'
674          && line[3] == ' '))
675       fatal(0, "invalid response from server: %s", line);
676     c->rc = (line[0] * 10 + line[1]) * 10 + line[2] - 111 * '0';
677     c->line = line;
678     switch(c->rc % 10) {
679     case 3:
680       /* We need to collect the body. */
681       c->state = state_body;
682       vector_init(&c->vec);
683       break;
684     case 4:
685       assert(c->log_callbacks != 0);
686       if(c->log_callbacks->connected)
687         c->log_callbacks->connected(c->log_v);
688       c->state = state_log;
689       break;
690     default:
691       /* We've got the whole response.  Go into the idle state so the state
692        * machine knows we're done and then call the operation callback. */
693       complete(c);
694       break;
695     }
696     break;
697   case state_body:
698     if(strcmp(line, ".")) {
699       /* A line from the body */
700       vector_append(&c->vec, line + (line[0] == '.'));
701     } else {
702       /* End of the body. */
703       vector_terminate(&c->vec);
704       complete(c);
705     }
706     break;
707   case state_log:
708     if(strcmp(line, ".")) {
709       logline(c, line + (line[0] == '.'));
710     } else 
711       complete(c);
712     break;
713   default:
714     assert(!"wrong state for location");
715     break;
716   }
717 }
718
719 /* Called when an operation completes */
720 static void complete(disorder_eclient *c) {
721   struct operation *op;
722
723   D(("complete"));
724   /* Pop the operation off the queue */
725   op = c->ops;
726   c->ops = op->next;
727   if(c->opstail == &op->next)
728     c->opstail = &c->ops;
729   /* If we've pipelined a command ahead then we go straight to cmdresponser.
730    * Otherwise we go to idle, which will arrange further sends. */
731   c->state = c->ops && c->ops->sent ? state_cmdresponse : state_idle;
732   op->opcallback(c, op);
733   /* Note that we always call the opcallback even on error, though command
734    * opcallbacks generally always do the same error handling, i.e. just call
735    * protocol_error().  It's the auth* opcallbacks that have different
736    * behaviour. */
737 }
738
739 /* Operation setup ***********************************************************/
740
741 static void stash_command_vector(disorder_eclient *c,
742                                  int queuejump,
743                                  operation_callback *opcallback,
744                                  void (*completed)(),
745                                  void *v,
746                                  int ncmd,
747                                  char **cmd) {
748   struct operation *op = xmalloc(sizeof *op);
749   struct dynstr d;
750   int n;
751
752   if(cmd) {
753     dynstr_init(&d);
754     for(n = 0; n < ncmd; ++n) {
755       if(n)
756         dynstr_append(&d, ' ');
757       dynstr_append_string(&d, quoteutf8(cmd[n]));
758     }
759     dynstr_append(&d, '\n');
760     dynstr_terminate(&d);
761     op->cmd = d.vec;
762   } else
763     op->cmd = 0;                        /* usually, awaiting challenge */
764   op->opcallback = opcallback;
765   op->completed = completed;
766   op->v = v;
767   op->next = 0;
768   op->client = c;
769   assert(op->sent == 0);
770   if(queuejump) {
771     /* Authentication operations jump the queue of useful commands */
772     op->next = c->ops;
773     c->ops = op;
774     if(c->opstail == &c->ops)
775       c->opstail = &op->next;
776     for(op = c->ops; op; op = op->next)
777       assert(!op->sent);
778   } else {
779     *c->opstail = op;
780     c->opstail = &op->next;
781   }
782 }
783
784 static void vstash_command(disorder_eclient *c,
785                            int queuejump,
786                            operation_callback *opcallback,
787                            void (*completed)(),
788                            void *v,
789                            const char *cmd, va_list ap) {
790   char *arg;
791   struct vector vec;
792
793   D(("vstash_command %s", cmd ? cmd : "NULL"));
794   if(cmd) {
795     vector_init(&vec);
796     vector_append(&vec, (char *)cmd);
797     while((arg = va_arg(ap, char *)))
798       vector_append(&vec, arg);
799     stash_command_vector(c, queuejump, opcallback, completed, v, 
800                          vec.nvec, vec.vec);
801   } else
802     stash_command_vector(c, queuejump, opcallback, completed, v, 0, 0);
803 }
804
805 static void stash_command(disorder_eclient *c,
806                           int queuejump,
807                           operation_callback *opcallback,
808                           void (*completed)(),
809                           void *v,
810                           const char *cmd,
811                           ...) {
812   va_list ap;
813
814   va_start(ap, cmd);
815   vstash_command(c, queuejump, opcallback, completed, v, cmd, ap);
816   va_end(ap);
817 }
818
819 /* Command support ***********************************************************/
820
821 /* for commands with a simple string response */ 
822 static void string_response_opcallback(disorder_eclient *c,
823                                        struct operation *op) {
824   D(("string_response_callback"));
825   if(c->rc / 100 == 2) {
826     if(op->completed)
827       ((disorder_eclient_string_response *)op->completed)(op->v, c->line + 4);
828   } else
829     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
830 }
831
832 /* for commands with a simple integer response */ 
833 static void integer_response_opcallback(disorder_eclient *c,
834                                         struct operation *op) {
835   D(("string_response_callback"));
836   if(c->rc / 100 == 2) {
837     if(op->completed)
838       ((disorder_eclient_integer_response *)op->completed)
839         (op->v, strtol(c->line + 4, 0, 10));
840   } else
841     protocol_error(c, op,  c->rc, "%s: %s", c->ident, c->line);
842 }
843
844 /* for commands with no response */
845 static void no_response_opcallback(disorder_eclient *c,
846                                    struct operation *op) {
847   D(("no_response_callback"));
848   if(c->rc / 100 == 2) {
849     if(op->completed)
850       ((disorder_eclient_no_response *)op->completed)(op->v);
851   } else
852     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
853 }
854
855 /* error callback for queue_unmarshall */
856 static void eclient_queue_error(const char *msg,
857                                 void *u) {
858   struct operation *op = u;
859
860   protocol_error(op->client, op, -1, "error parsing queue entry: %s", msg);
861 }
862
863 /* for commands that expect a queue dump */
864 static void queue_response_opcallback(disorder_eclient *c,
865                                       struct operation *op) {
866   int n;
867   struct queue_entry *q, *qh = 0, **qtail = &qh, *qlast = 0;
868   
869   D(("queue_response_callback"));
870   if(c->rc / 100 == 2) {
871     /* parse the queue */
872     for(n = 0; n < c->vec.nvec; ++n) {
873       q = xmalloc(sizeof *q);
874       D(("queue_unmarshall %s", c->vec.vec[n]));
875       if(!queue_unmarshall(q, c->vec.vec[n], eclient_queue_error, op)) {
876         q->prev = qlast;
877         *qtail = q;
878         qtail = &q->next;
879         qlast = q;
880       }
881     }
882     if(op->completed)
883       ((disorder_eclient_queue_response *)op->completed)(op->v, qh);
884   } else
885     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
886
887
888 /* for 'playing' */
889 static void playing_response_opcallback(disorder_eclient *c,
890                                         struct operation *op) {
891   struct queue_entry *q;
892
893   D(("playing_response_callback"));
894   if(c->rc / 100 == 2) {
895     switch(c->rc % 10) {
896     case 2:
897       if(queue_unmarshall(q = xmalloc(sizeof *q), c->line + 4,
898                           eclient_queue_error, c))
899         return;
900       break;
901     case 9:
902       q = 0;
903       break;
904     default:
905       protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
906       return;
907     }
908     if(op->completed)
909       ((disorder_eclient_queue_response *)op->completed)(op->v, q);
910   } else
911     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
912 }
913
914 /* for commands that expect a list of some sort */
915 static void list_response_opcallback(disorder_eclient *c,
916                                      struct operation *op) {
917   D(("list_response_callback"));
918   if(c->rc / 100 == 2) {
919     if(op->completed)
920       ((disorder_eclient_list_response *)op->completed)(op->v,
921                                                         c->vec.nvec,
922                                                         c->vec.vec);
923   } else
924     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
925 }
926
927 /* for volume */
928 static void volume_response_opcallback(disorder_eclient *c,
929                                        struct operation *op) {
930   int l, r;
931
932   D(("volume_response_callback"));
933   if(c->rc / 100 == 2) {
934     if(op->completed) {
935       if(sscanf(c->line + 4, "%d %d", &l, &r) != 2 || l < 0 || r < 0)
936         protocol_error(c, op, -1, "%s: invalid volume response: %s",
937                        c->ident, c->line);
938       else
939         ((disorder_eclient_volume_response *)op->completed)(op->v, l, r);
940     }
941   } else
942     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
943 }
944
945 static int simple(disorder_eclient *c,
946                   operation_callback *opcallback,
947                   void (*completed)(),
948                   void *v,
949                   const char *cmd, ...) {
950   va_list ap;
951
952   va_start(ap, cmd);
953   vstash_command(c, 0/*queuejump*/, opcallback, completed, v, cmd, ap);
954   va_end(ap);
955   /* Give the state machine a kick, since we might be in state_idle */
956   disorder_eclient_polled(c, 0);
957   return 0;
958 }
959
960 /* Commands ******************************************************************/
961  
962 int disorder_eclient_version(disorder_eclient *c,
963                              disorder_eclient_string_response *completed,
964                              void *v) {
965   return simple(c, string_response_opcallback, (void (*)())completed, v,
966                 "version", (char *)0);
967 }
968
969 int disorder_eclient_namepart(disorder_eclient *c,
970                               disorder_eclient_string_response *completed,
971                               const char *track,
972                               const char *context,
973                               const char *part,
974                               void *v) {
975   return simple(c, string_response_opcallback, (void (*)())completed, v,
976                 "part", track, context, part, (char *)0);
977 }
978
979 int disorder_eclient_play(disorder_eclient *c,
980                           const char *track,
981                           disorder_eclient_no_response *completed,
982                           void *v) {
983   return simple(c, no_response_opcallback, (void (*)())completed, v,
984                 "play", track, (char *)0);
985 }
986
987 int disorder_eclient_pause(disorder_eclient *c,
988                            disorder_eclient_no_response *completed,
989                            void *v) {
990   return simple(c, no_response_opcallback, (void (*)())completed, v,
991                 "pause", (char *)0);
992 }
993
994 int disorder_eclient_resume(disorder_eclient *c,
995                             disorder_eclient_no_response *completed,
996                             void *v) {
997   return simple(c, no_response_opcallback, (void (*)())completed, v,
998                 "resume", (char *)0);
999 }
1000
1001 int disorder_eclient_scratch(disorder_eclient *c,
1002                              const char *id,
1003                              disorder_eclient_no_response *completed,
1004                              void *v) {
1005   return simple(c, no_response_opcallback, (void (*)())completed, v,
1006                 "scratch", id, (char *)0);
1007 }
1008
1009 int disorder_eclient_scratch_playing(disorder_eclient *c,
1010                                      disorder_eclient_no_response *completed,
1011                                      void *v) {
1012   return disorder_eclient_scratch(c, 0, completed, v);
1013 }
1014
1015 int disorder_eclient_remove(disorder_eclient *c,
1016                             const char *id,
1017                             disorder_eclient_no_response *completed,
1018                             void *v) {
1019   return simple(c, no_response_opcallback, (void (*)())completed, v,
1020                 "remove", id, (char *)0);
1021 }
1022
1023 int disorder_eclient_moveafter(disorder_eclient *c,
1024                                const char *target,
1025                                int nids,
1026                                const char **ids,
1027                                disorder_eclient_no_response *completed,
1028                                void *v) {
1029   struct vector vec;
1030   int n;
1031
1032   vector_init(&vec);
1033   vector_append(&vec, (char *)"moveafter");
1034   vector_append(&vec, (char *)target);
1035   for(n = 0; n < nids; ++n)
1036     vector_append(&vec, (char *)ids[n]);
1037   stash_command_vector(c, 0/*queuejump*/, no_response_opcallback, completed, v,
1038                        vec.nvec, vec.vec);
1039   disorder_eclient_polled(c, 0);
1040   return 0;
1041 }
1042
1043 int disorder_eclient_recent(disorder_eclient *c,
1044                             disorder_eclient_queue_response *completed,
1045                             void *v) {
1046   return simple(c, queue_response_opcallback, (void (*)())completed, v,
1047                 "recent", (char *)0);
1048 }
1049
1050 int disorder_eclient_queue(disorder_eclient *c,
1051                             disorder_eclient_queue_response *completed,
1052                             void *v) {
1053   return simple(c, queue_response_opcallback, (void (*)())completed, v,
1054                 "queue", (char *)0);
1055 }
1056
1057 int disorder_eclient_files(disorder_eclient *c,
1058                            disorder_eclient_list_response *completed,
1059                            const char *dir,
1060                            const char *re,
1061                            void *v) {
1062   return simple(c, list_response_opcallback, (void (*)())completed, v,
1063                 "files", dir, re, (char *)0);
1064 }
1065
1066 int disorder_eclient_dirs(disorder_eclient *c,
1067                           disorder_eclient_list_response *completed,
1068                           const char *dir,
1069                           const char *re,
1070                           void *v) {
1071   return simple(c, list_response_opcallback, (void (*)())completed, v,
1072                 "dirs", dir, re, (char *)0);
1073 }
1074
1075 int disorder_eclient_playing(disorder_eclient *c,
1076                              disorder_eclient_queue_response *completed,
1077                              void *v) {
1078   return simple(c, playing_response_opcallback, (void (*)())completed, v,
1079                 "playing", (char *)0);
1080 }
1081
1082 int disorder_eclient_length(disorder_eclient *c,
1083                             disorder_eclient_integer_response *completed,
1084                             const char *track,
1085                             void *v) {
1086   return simple(c, integer_response_opcallback, (void (*)())completed, v,
1087                 "length", track, (char *)0);
1088 }
1089
1090 int disorder_eclient_volume(disorder_eclient *c,
1091                             disorder_eclient_volume_response *completed,
1092                             int l, int r,
1093                             void *v) {
1094   char sl[64], sr[64];
1095
1096   if(l < 0 && r < 0) {
1097     return simple(c, volume_response_opcallback, (void (*)())completed, v,
1098                   "volume", (char *)0);
1099   } else if(l >= 0 && r >= 0) {
1100     assert(l <= 100);
1101     assert(r <= 100);
1102     byte_snprintf(sl, sizeof sl, "%d", l);
1103     byte_snprintf(sr, sizeof sr, "%d", r);
1104     return simple(c, volume_response_opcallback, (void (*)())completed, v,
1105                   "volume", sl, sr, (char *)0);
1106   } else {
1107     assert(!"invalid arguments to disorder_eclient_volume");
1108     return -1;                          /* gcc is being dim */
1109   }
1110 }
1111
1112 int disorder_eclient_enable(disorder_eclient *c,
1113                             disorder_eclient_no_response *completed,
1114                             void *v) {
1115   return simple(c, no_response_opcallback, (void (*)())completed, v,
1116                 "enable", (char *)0);
1117 }
1118
1119 int disorder_eclient_disable(disorder_eclient *c,
1120                              disorder_eclient_no_response *completed,
1121                              void *v){
1122   return simple(c, no_response_opcallback, (void (*)())completed, v,
1123                 "disable", (char *)0);
1124 }
1125
1126 int disorder_eclient_random_enable(disorder_eclient *c,
1127                                    disorder_eclient_no_response *completed,
1128                                    void *v){
1129   return simple(c, no_response_opcallback, (void (*)())completed, v,
1130                 "random-enable", (char *)0);
1131 }
1132
1133 int disorder_eclient_random_disable(disorder_eclient *c,
1134                                     disorder_eclient_no_response *completed,
1135                                     void *v){
1136   return simple(c, no_response_opcallback, (void (*)())completed, v,
1137                 "random-disable", (char *)0);
1138 }
1139
1140 int disorder_eclient_get(disorder_eclient *c,
1141                          disorder_eclient_string_response *completed,
1142                          const char *track, const char *pref,
1143                          void *v) {
1144   return simple(c, string_response_opcallback, (void (*)())completed, v, 
1145                 "get", track, pref, (char *)0);
1146 }
1147
1148 int disorder_eclient_set(disorder_eclient *c,
1149                          disorder_eclient_no_response *completed,
1150                          const char *track, const char *pref, 
1151                          const char *value,
1152                          void *v) {
1153   return simple(c, no_response_opcallback, (void (*)())completed, v, 
1154                 "set", track, pref, value, (char *)0);
1155 }
1156
1157 int disorder_eclient_unset(disorder_eclient *c,
1158                            disorder_eclient_no_response *completed,
1159                            const char *track, const char *pref, 
1160                            void *v) {
1161   return simple(c, no_response_opcallback, (void (*)())completed, v, 
1162                 "unset", track, pref, (char *)0);
1163 }
1164
1165 int disorder_eclient_resolve(disorder_eclient *c,
1166                              disorder_eclient_string_response *completed,
1167                              const char *track,
1168                              void *v) {
1169   return simple(c, string_response_opcallback,  (void (*)())completed, v, 
1170                 "resolve", track, (char *)0);
1171 }
1172
1173 int disorder_eclient_search(disorder_eclient *c,
1174                             disorder_eclient_list_response *completed,
1175                             const char *terms,
1176                             void *v) {
1177   if(!split(terms, 0, SPLIT_QUOTES, 0, 0)) return -1;
1178   return simple(c, list_response_opcallback, (void (*)())completed, v,
1179                 "search", terms, (char *)0);
1180 }
1181
1182 int disorder_eclient_nop(disorder_eclient *c,
1183                          disorder_eclient_no_response *completed,
1184                          void *v) {
1185   return simple(c, no_response_opcallback, (void (*)())completed, v, 
1186                 "nop", (char *)0);
1187 }
1188
1189 /** @brief Get the last @p max added tracks
1190  * @param c Client
1191  * @param completed Called with list
1192  * @param max Number of tracks to get, 0 for all
1193  * @param v Passed to @p completed
1194  *
1195  * The first track in the list is the most recently added.
1196  */
1197 int disorder_eclient_new_tracks(disorder_eclient *c,
1198                                 disorder_eclient_list_response *completed,
1199                                 int max,
1200                                 void *v) {
1201   char limit[32];
1202
1203   sprintf(limit, "%d", max);
1204   return simple(c, list_response_opcallback, (void (*)())completed, v,
1205                 "new", limit, (char *)0);
1206 }
1207
1208 static void rtp_response_opcallback(disorder_eclient *c,
1209                                     struct operation *op) {
1210   D(("rtp_response_opcallback"));
1211   if(c->rc / 100 == 2) {
1212     if(op->completed) {
1213       int nvec;
1214       char **vec = split(c->line + 4, &nvec, SPLIT_QUOTES, 0, 0);
1215
1216       ((disorder_eclient_list_response *)op->completed)(op->v, nvec, vec);
1217     }
1218   } else
1219     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
1220 }
1221
1222 /** @brief Determine the RTP target address
1223  * @param c Client
1224  * @param completed Called with address details
1225  * @param v Passed to @p completed
1226  *
1227  * The address details will be two elements, the first being the hostname and
1228  * the second the service (port).
1229  */
1230 int disorder_eclient_rtp_address(disorder_eclient *c,
1231                                  disorder_eclient_list_response *completed,
1232                                  void *v) {
1233   return simple(c, rtp_response_opcallback, (void (*)())completed, v,
1234                 "rtp-address", (char *)0);
1235 }
1236
1237 /* Log clients ***************************************************************/
1238
1239 /** @brief Monitor the server log
1240  * @param c Client
1241  * @param callbacks Functions to call when anything happens
1242  * @param v Passed to @p callbacks functions
1243  *
1244  * Once a client is being used for logging it cannot be used for anything else.
1245  * There is magic in authuser_opcallback() to re-submit the @c log command
1246  * after reconnection.
1247  *
1248  * NB that the @c state callback may be called from within this function,
1249  * i.e. not solely later on from the event loop callback.
1250  */
1251 int disorder_eclient_log(disorder_eclient *c,
1252                          const disorder_eclient_log_callbacks *callbacks,
1253                          void *v) {
1254   if(c->log_callbacks) return -1;
1255   c->log_callbacks = callbacks;
1256   c->log_v = v;
1257   /* Repoort initial state */
1258   if(c->log_callbacks->state)
1259     c->log_callbacks->state(c->log_v, c->statebits);
1260   stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, v,
1261                 "log", (char *)0);
1262   return 0;
1263 }
1264
1265 /* If we get here we've stopped being a log client */
1266 static void log_opcallback(disorder_eclient *c,
1267                            struct operation attribute((unused)) *op) {
1268   D(("log_opcallback"));
1269   c->log_callbacks = 0;
1270   c->log_v = 0;
1271 }
1272
1273 /* error callback for log line parsing */
1274 static void logline_error(const char *msg, void *u) {
1275   disorder_eclient *c = u;
1276   protocol_error(c, c->ops, -1, "error parsing log line: %s", msg);
1277 }
1278
1279 /* process a single log line */
1280 static void logline(disorder_eclient *c, const char *line) {
1281   int nvec, n;
1282   char **vec;
1283   uintmax_t when;
1284
1285   D(("logline [%s]", line));
1286   vec = split(line, &nvec, SPLIT_QUOTES, logline_error, c);
1287   if(nvec < 2) return;                  /* probably an error, already
1288                                          * reported */
1289   if(sscanf(vec[0], "%"SCNxMAX, &when) != 1) {
1290     /* probably the wrong side of a format change */
1291     protocol_error(c, c->ops, -1, "invalid log timestamp '%s'", vec[0]);
1292     return;
1293   }
1294   /* TODO: do something with the time */
1295   n = TABLE_FIND(logentry_handlers, struct logentry_handler, name, vec[1]);
1296   if(n < 0) return;                     /* probably a future command */
1297   vec += 2;
1298   nvec -= 2;
1299   if(nvec < logentry_handlers[n].min || nvec > logentry_handlers[n].max)
1300     return;
1301   logentry_handlers[n].handler(c, nvec, vec);
1302 }
1303
1304 static void logentry_completed(disorder_eclient *c,
1305                                int attribute((unused)) nvec, char **vec) {
1306   if(!c->log_callbacks->completed) return;
1307   c->statebits &= ~DISORDER_PLAYING;
1308   c->log_callbacks->completed(c->log_v, vec[0]);
1309   if(c->log_callbacks->state)
1310     c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1311 }
1312
1313 static void logentry_failed(disorder_eclient *c,
1314                             int attribute((unused)) nvec, char **vec) {
1315   if(!c->log_callbacks->failed)return;
1316   c->statebits &= ~DISORDER_PLAYING;
1317   c->log_callbacks->failed(c->log_v, vec[0], vec[1]);
1318   if(c->log_callbacks->state)
1319     c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1320 }
1321
1322 static void logentry_moved(disorder_eclient *c,
1323                            int attribute((unused)) nvec, char **vec) {
1324   if(!c->log_callbacks->moved) return;
1325   c->log_callbacks->moved(c->log_v, vec[0]);
1326 }
1327
1328 static void logentry_playing(disorder_eclient *c,
1329                              int attribute((unused)) nvec, char **vec) {
1330   if(!c->log_callbacks->playing) return;
1331   c->statebits |= DISORDER_PLAYING;
1332   c->log_callbacks->playing(c->log_v, vec[0], vec[1]);
1333   if(c->log_callbacks->state)
1334     c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1335 }
1336
1337 static void logentry_queue(disorder_eclient *c,
1338                            int attribute((unused)) nvec, char **vec) {
1339   struct queue_entry *q;
1340
1341   if(!c->log_callbacks->completed) return;
1342   q = xmalloc(sizeof *q);
1343   if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1344     return;                             /* bogus */
1345   c->log_callbacks->queue(c->log_v, q);
1346 }
1347
1348 static void logentry_recent_added(disorder_eclient *c,
1349                                   int attribute((unused)) nvec, char **vec) {
1350   struct queue_entry *q;
1351
1352   if(!c->log_callbacks->recent_added) return;
1353   q = xmalloc(sizeof *q);
1354   if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1355     return;                           /* bogus */
1356   c->log_callbacks->recent_added(c->log_v, q);
1357 }
1358
1359 static void logentry_recent_removed(disorder_eclient *c,
1360                                     int attribute((unused)) nvec, char **vec) {
1361   if(!c->log_callbacks->recent_removed) return;
1362   c->log_callbacks->recent_removed(c->log_v, vec[0]);
1363 }
1364
1365 static void logentry_removed(disorder_eclient *c,
1366                              int attribute((unused)) nvec, char **vec) {
1367   if(!c->log_callbacks->removed) return;
1368   c->log_callbacks->removed(c->log_v, vec[0], vec[1]);
1369 }
1370
1371 static void logentry_rescanned(disorder_eclient *c,
1372                                int attribute((unused)) nvec,
1373                                char attribute((unused)) **vec) {
1374   if(!c->log_callbacks->rescanned) return;
1375   c->log_callbacks->rescanned(c->log_v);
1376 }
1377
1378 static void logentry_scratched(disorder_eclient *c,
1379                                int attribute((unused)) nvec, char **vec) {
1380   if(!c->log_callbacks->scratched) return;
1381   c->statebits &= ~DISORDER_PLAYING;
1382   c->log_callbacks->scratched(c->log_v, vec[0], vec[1]);
1383   if(c->log_callbacks->state)
1384     c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1385 }
1386
1387 static const struct {
1388   unsigned long bit;
1389   const char *enable;
1390   const char *disable;
1391 } statestrings[] = {
1392   { DISORDER_PLAYING_ENABLED, "enable_play", "disable_play" },
1393   { DISORDER_RANDOM_ENABLED, "enable_random", "disable_random" },
1394   { DISORDER_TRACK_PAUSED, "pause", "resume" },
1395   { DISORDER_PLAYING, "playing", "completed" },
1396   { DISORDER_PLAYING, 0, "scratched" },
1397   { DISORDER_PLAYING, 0, "failed" },
1398 };
1399 #define NSTATES (int)(sizeof statestrings / sizeof *statestrings)
1400
1401 static void logentry_state(disorder_eclient *c,
1402                            int attribute((unused)) nvec, char **vec) {
1403   int n;
1404
1405   for(n = 0; n < NSTATES; ++n)
1406     if(statestrings[n].enable && !strcmp(vec[0], statestrings[n].enable)) {
1407       c->statebits |= statestrings[n].bit;
1408       break;
1409     } else if(statestrings[n].disable && !strcmp(vec[0], statestrings[n].disable)) {
1410       c->statebits &= ~statestrings[n].bit;
1411       break;
1412     }
1413   if(!c->log_callbacks->state) return;
1414   c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1415 }
1416
1417 static void logentry_volume(disorder_eclient *c,
1418                             int attribute((unused)) nvec, char **vec) {
1419   long l, r;
1420
1421   if(!c->log_callbacks->volume) return;
1422   if(xstrtol(&l, vec[0], 0, 10)
1423      || xstrtol(&r, vec[1], 0, 10)
1424      || l < 0 || l > INT_MAX
1425      || r < 0 || r > INT_MAX)
1426     return;                             /* bogus */
1427   c->log_callbacks->volume(c->log_v, (int)l, (int)r);
1428 }
1429
1430 /** @brief Convert @p statebits to a string */
1431 char *disorder_eclient_interpret_state(unsigned long statebits) {
1432   struct dynstr d[1];
1433   size_t n;
1434
1435   static const struct {
1436     unsigned long bit;
1437     const char *name;
1438   } bits[] = {
1439     { DISORDER_PLAYING_ENABLED, "playing_enabled" },
1440     { DISORDER_RANDOM_ENABLED, "random_enabled" },
1441     { DISORDER_TRACK_PAUSED, "track_paused" },
1442     { DISORDER_PLAYING, "playing" },
1443     { DISORDER_CONNECTED, "connected" },
1444   };
1445 #define NBITS (sizeof bits / sizeof *bits)
1446
1447   dynstr_init(d);
1448   if(!statebits)
1449     dynstr_append(d, '0');
1450   for(n = 0; n < NBITS; ++n)
1451     if(statebits & bits[n].bit) {
1452       if(d->nvec)
1453         dynstr_append(d, '|');
1454       dynstr_append_string(d, bits[n].name);
1455       statebits ^= bits[n].bit;
1456     }
1457   if(statebits) {
1458     char s[20];
1459
1460     if(d->nvec)
1461       dynstr_append(d, '|');
1462     sprintf(s, "%#lx", statebits);
1463     dynstr_append_string(d, s);
1464   }
1465   dynstr_terminate(d);
1466   return d->vec;
1467 }
1468
1469 /*
1470 Local Variables:
1471 c-basic-offset:2
1472 comment-column:40
1473 fill-column:79
1474 indent-tabs-mode:nil
1475 End:
1476 */