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