chiark / gitweb /
2d85fb92233696dcb3122f72e9d169670b3a9c3e
[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 *algo = "SHA1";
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 > 1) {
551     algo = *rvec++;
552     --nrvec;
553   }
554   nonce = unhex(rvec[0], &nonce_len);
555   res = authhash(nonce, nonce_len, config->password, algo);
556   if(!res) {
557     protocol_error(c, op, c->rc, "%s: unknown authentication algorithm '%s'",
558                    c->ident, algo);
559     disorder_eclient_close(c);
560     return;
561   }
562   stash_command(c, 1/*queuejump*/, authuser_opcallback, 0/*completed*/, 0/*v*/,
563                 "user", quoteutf8(config->username), quoteutf8(res),
564                 (char *)0);
565 }
566
567 static void authuser_opcallback(disorder_eclient *c,
568                                 struct operation *op) {
569   char *r;
570
571   D(("authuser_opcallback"));
572   if(c->rc / 100 != 2) {
573     /* Wrong password or something.  We cannot proceed. */
574     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
575     disorder_eclient_close(c);
576     return;
577   }
578   /* OK, we're authenticated now. */
579   c->authenticated = 1;
580   byte_xasprintf(&r, "authenticated with %s", c->ident);
581   c->callbacks->report(c->u, r);
582   if(c->log_callbacks && !(c->ops && c->ops->opcallback == log_opcallback))
583     /* We are a log client, switch to logging mode */
584     stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, c->log_v,
585                   "log", (char *)0);
586 }
587
588 /* Output ********************************************************************/
589
590 /* Chop N bytes off the front of a dynstr */
591 static void consume(struct dynstr *d, int n) {
592   D(("consume %d", n));
593   assert(d->nvec >= n);
594   memmove(d->vec, d->vec + n, d->nvec - n);
595   d->nvec -= n;
596 }
597
598 /* Write some bytes */
599 static void put(disorder_eclient *c, const char *s, size_t n) {
600   D(("put %d %.*s", c->fd, (int)n, s));
601   dynstr_append_bytes(&c->output, s, n);
602 }
603
604 /* Called when we can write to our FD, or at any other time */
605 static void send_output(disorder_eclient *c) {
606   int n;
607
608   D(("send_output %d bytes pending", c->output.nvec));
609   if(c->state > state_connecting && c->output.nvec) {
610     n = write(c->fd, c->output.vec, c->output.nvec);
611     if(n < 0) {
612       switch(errno) {
613       case EINTR:
614       case EAGAIN:
615         break;
616       default:
617         comms_error(c, "writing to %s: %s", c->ident, strerror(errno));
618         break;
619       }
620     } else
621       consume(&c->output, n);
622   }
623 }
624
625 /* Input *********************************************************************/
626
627 /* Called when c->fd might be readable, or at any other time */
628 static void read_input(disorder_eclient *c) {
629   char *nl;
630   int n;
631   char buffer[512];
632
633   D(("read_input in state %s", states[c->state]));
634   if(c->state <= state_connected) return; /* ignore bogus calls */
635   /* read some more input */
636   n = read(c->fd, buffer, sizeof buffer);
637   if(n < 0) {
638     switch(errno) {
639     case EINTR:
640     case EAGAIN:
641       break;
642     default:
643       comms_error(c, "reading from %s: %s", c->ident, strerror(errno));
644       break;
645     }
646     return;                             /* no new input to process */
647   } else if(n) {
648     D(("read %d bytes: [%.*s]", n, n, buffer));
649     dynstr_append_bytes(&c->input, buffer, n);
650   } else
651     c->eof = 1;
652   /* might have more than one line to process */
653   while(c->state > state_connecting
654         && (nl = memchr(c->input.vec, '\n', c->input.nvec))) {
655     process_line(c, xstrndup(c->input.vec, nl - c->input.vec));
656     /* we might have disconnected along the way, which zogs the input buffer */
657     if(c->state > state_connecting)
658       consume(&c->input, (nl - c->input.vec) + 1);
659   }
660   if(c->eof) {
661     comms_error(c, "reading from %s: server disconnected", c->ident);
662     c->authenticated = 0;
663   }
664 }
665
666 /* called with a line that has just been read */
667 static void process_line(disorder_eclient *c, char *line) {
668   D(("process_line %d [%s]", c->fd, line));
669   switch(c->state) {
670   case state_cmdresponse:
671     /* This is the first line of a response */
672     if(!(line[0] >= '0' && line[0] <= '9'
673          && line[1] >= '0' && line[1] <= '9'
674          && line[2] >= '0' && line[2] <= '9'
675          && line[3] == ' '))
676       fatal(0, "invalid response from server: %s", line);
677     c->rc = (line[0] * 10 + line[1]) * 10 + line[2] - 111 * '0';
678     c->line = line;
679     switch(c->rc % 10) {
680     case 3:
681       /* We need to collect the body. */
682       c->state = state_body;
683       vector_init(&c->vec);
684       break;
685     case 4:
686       assert(c->log_callbacks != 0);
687       if(c->log_callbacks->connected)
688         c->log_callbacks->connected(c->log_v);
689       c->state = state_log;
690       break;
691     default:
692       /* We've got the whole response.  Go into the idle state so the state
693        * machine knows we're done and then call the operation callback. */
694       complete(c);
695       break;
696     }
697     break;
698   case state_body:
699     if(strcmp(line, ".")) {
700       /* A line from the body */
701       vector_append(&c->vec, line + (line[0] == '.'));
702     } else {
703       /* End of the body. */
704       vector_terminate(&c->vec);
705       complete(c);
706     }
707     break;
708   case state_log:
709     if(strcmp(line, ".")) {
710       logline(c, line + (line[0] == '.'));
711     } else 
712       complete(c);
713     break;
714   default:
715     assert(!"wrong state for location");
716     break;
717   }
718 }
719
720 /* Called when an operation completes */
721 static void complete(disorder_eclient *c) {
722   struct operation *op;
723
724   D(("complete"));
725   /* Pop the operation off the queue */
726   op = c->ops;
727   c->ops = op->next;
728   if(c->opstail == &op->next)
729     c->opstail = &c->ops;
730   /* If we've pipelined a command ahead then we go straight to cmdresponser.
731    * Otherwise we go to idle, which will arrange further sends. */
732   c->state = c->ops && c->ops->sent ? state_cmdresponse : state_idle;
733   op->opcallback(c, op);
734   /* Note that we always call the opcallback even on error, though command
735    * opcallbacks generally always do the same error handling, i.e. just call
736    * protocol_error().  It's the auth* opcallbacks that have different
737    * behaviour. */
738 }
739
740 /* Operation setup ***********************************************************/
741
742 static void stash_command_vector(disorder_eclient *c,
743                                  int queuejump,
744                                  operation_callback *opcallback,
745                                  void (*completed)(),
746                                  void *v,
747                                  int ncmd,
748                                  char **cmd) {
749   struct operation *op = xmalloc(sizeof *op);
750   struct dynstr d;
751   int n;
752
753   if(cmd) {
754     dynstr_init(&d);
755     for(n = 0; n < ncmd; ++n) {
756       if(n)
757         dynstr_append(&d, ' ');
758       dynstr_append_string(&d, quoteutf8(cmd[n]));
759     }
760     dynstr_append(&d, '\n');
761     dynstr_terminate(&d);
762     op->cmd = d.vec;
763   } else
764     op->cmd = 0;                        /* usually, awaiting challenge */
765   op->opcallback = opcallback;
766   op->completed = completed;
767   op->v = v;
768   op->next = 0;
769   op->client = c;
770   assert(op->sent == 0);
771   if(queuejump) {
772     /* Authentication operations jump the queue of useful commands */
773     op->next = c->ops;
774     c->ops = op;
775     if(c->opstail == &c->ops)
776       c->opstail = &op->next;
777     for(op = c->ops; op; op = op->next)
778       assert(!op->sent);
779   } else {
780     *c->opstail = op;
781     c->opstail = &op->next;
782   }
783 }
784
785 static void vstash_command(disorder_eclient *c,
786                            int queuejump,
787                            operation_callback *opcallback,
788                            void (*completed)(),
789                            void *v,
790                            const char *cmd, va_list ap) {
791   char *arg;
792   struct vector vec;
793
794   D(("vstash_command %s", cmd ? cmd : "NULL"));
795   if(cmd) {
796     vector_init(&vec);
797     vector_append(&vec, (char *)cmd);
798     while((arg = va_arg(ap, char *)))
799       vector_append(&vec, arg);
800     stash_command_vector(c, queuejump, opcallback, completed, v, 
801                          vec.nvec, vec.vec);
802   } else
803     stash_command_vector(c, queuejump, opcallback, completed, v, 0, 0);
804 }
805
806 static void stash_command(disorder_eclient *c,
807                           int queuejump,
808                           operation_callback *opcallback,
809                           void (*completed)(),
810                           void *v,
811                           const char *cmd,
812                           ...) {
813   va_list ap;
814
815   va_start(ap, cmd);
816   vstash_command(c, queuejump, opcallback, completed, v, cmd, ap);
817   va_end(ap);
818 }
819
820 /* Command support ***********************************************************/
821
822 /* for commands with a quoted string response */ 
823 static void string_response_opcallback(disorder_eclient *c,
824                                        struct operation *op) {
825   D(("string_response_callback"));
826   if(c->rc / 100 == 2) {
827     if(op->completed) {
828       char **rr = split(c->line + 4, 0, SPLIT_QUOTES, 0, 0);
829
830       if(rr && *rr)
831         ((disorder_eclient_string_response *)op->completed)(op->v, *rr);
832       else
833         protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
834     }
835   } else
836     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
837 }
838
839 /* for commands with a simple integer response */ 
840 static void integer_response_opcallback(disorder_eclient *c,
841                                         struct operation *op) {
842   D(("string_response_callback"));
843   if(c->rc / 100 == 2) {
844     if(op->completed)
845       ((disorder_eclient_integer_response *)op->completed)
846         (op->v, strtol(c->line + 4, 0, 10));
847   } else
848     protocol_error(c, op,  c->rc, "%s: %s", c->ident, c->line);
849 }
850
851 /* for commands with no response */
852 static void no_response_opcallback(disorder_eclient *c,
853                                    struct operation *op) {
854   D(("no_response_callback"));
855   if(c->rc / 100 == 2) {
856     if(op->completed)
857       ((disorder_eclient_no_response *)op->completed)(op->v);
858   } else
859     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
860 }
861
862 /* error callback for queue_unmarshall */
863 static void eclient_queue_error(const char *msg,
864                                 void *u) {
865   struct operation *op = u;
866
867   protocol_error(op->client, op, -1, "error parsing queue entry: %s", msg);
868 }
869
870 /* for commands that expect a queue dump */
871 static void queue_response_opcallback(disorder_eclient *c,
872                                       struct operation *op) {
873   int n;
874   struct queue_entry *q, *qh = 0, **qtail = &qh, *qlast = 0;
875   
876   D(("queue_response_callback"));
877   if(c->rc / 100 == 2) {
878     /* parse the queue */
879     for(n = 0; n < c->vec.nvec; ++n) {
880       q = xmalloc(sizeof *q);
881       D(("queue_unmarshall %s", c->vec.vec[n]));
882       if(!queue_unmarshall(q, c->vec.vec[n], eclient_queue_error, op)) {
883         q->prev = qlast;
884         *qtail = q;
885         qtail = &q->next;
886         qlast = q;
887       }
888     }
889     if(op->completed)
890       ((disorder_eclient_queue_response *)op->completed)(op->v, qh);
891   } else
892     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
893
894
895 /* for 'playing' */
896 static void playing_response_opcallback(disorder_eclient *c,
897                                         struct operation *op) {
898   struct queue_entry *q;
899
900   D(("playing_response_callback"));
901   if(c->rc / 100 == 2) {
902     switch(c->rc % 10) {
903     case 2:
904       if(queue_unmarshall(q = xmalloc(sizeof *q), c->line + 4,
905                           eclient_queue_error, c))
906         return;
907       break;
908     case 9:
909       q = 0;
910       break;
911     default:
912       protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
913       return;
914     }
915     if(op->completed)
916       ((disorder_eclient_queue_response *)op->completed)(op->v, q);
917   } else
918     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
919 }
920
921 /* for commands that expect a list of some sort */
922 static void list_response_opcallback(disorder_eclient *c,
923                                      struct operation *op) {
924   D(("list_response_callback"));
925   if(c->rc / 100 == 2) {
926     if(op->completed)
927       ((disorder_eclient_list_response *)op->completed)(op->v,
928                                                         c->vec.nvec,
929                                                         c->vec.vec);
930   } else
931     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
932 }
933
934 /* for volume */
935 static void volume_response_opcallback(disorder_eclient *c,
936                                        struct operation *op) {
937   int l, r;
938
939   D(("volume_response_callback"));
940   if(c->rc / 100 == 2) {
941     if(op->completed) {
942       if(sscanf(c->line + 4, "%d %d", &l, &r) != 2 || l < 0 || r < 0)
943         protocol_error(c, op, -1, "%s: invalid volume response: %s",
944                        c->ident, c->line);
945       else
946         ((disorder_eclient_volume_response *)op->completed)(op->v, l, r);
947     }
948   } else
949     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
950 }
951
952 static int simple(disorder_eclient *c,
953                   operation_callback *opcallback,
954                   void (*completed)(),
955                   void *v,
956                   const char *cmd, ...) {
957   va_list ap;
958
959   va_start(ap, cmd);
960   vstash_command(c, 0/*queuejump*/, opcallback, completed, v, cmd, ap);
961   va_end(ap);
962   /* Give the state machine a kick, since we might be in state_idle */
963   disorder_eclient_polled(c, 0);
964   return 0;
965 }
966
967 /* Commands ******************************************************************/
968  
969 int disorder_eclient_version(disorder_eclient *c,
970                              disorder_eclient_string_response *completed,
971                              void *v) {
972   return simple(c, string_response_opcallback, (void (*)())completed, v,
973                 "version", (char *)0);
974 }
975
976 int disorder_eclient_namepart(disorder_eclient *c,
977                               disorder_eclient_string_response *completed,
978                               const char *track,
979                               const char *context,
980                               const char *part,
981                               void *v) {
982   return simple(c, string_response_opcallback, (void (*)())completed, v,
983                 "part", track, context, part, (char *)0);
984 }
985
986 int disorder_eclient_play(disorder_eclient *c,
987                           const char *track,
988                           disorder_eclient_no_response *completed,
989                           void *v) {
990   return simple(c, no_response_opcallback, (void (*)())completed, v,
991                 "play", track, (char *)0);
992 }
993
994 int disorder_eclient_pause(disorder_eclient *c,
995                            disorder_eclient_no_response *completed,
996                            void *v) {
997   return simple(c, no_response_opcallback, (void (*)())completed, v,
998                 "pause", (char *)0);
999 }
1000
1001 int disorder_eclient_resume(disorder_eclient *c,
1002                             disorder_eclient_no_response *completed,
1003                             void *v) {
1004   return simple(c, no_response_opcallback, (void (*)())completed, v,
1005                 "resume", (char *)0);
1006 }
1007
1008 int disorder_eclient_scratch(disorder_eclient *c,
1009                              const char *id,
1010                              disorder_eclient_no_response *completed,
1011                              void *v) {
1012   return simple(c, no_response_opcallback, (void (*)())completed, v,
1013                 "scratch", id, (char *)0);
1014 }
1015
1016 int disorder_eclient_scratch_playing(disorder_eclient *c,
1017                                      disorder_eclient_no_response *completed,
1018                                      void *v) {
1019   return disorder_eclient_scratch(c, 0, completed, v);
1020 }
1021
1022 int disorder_eclient_remove(disorder_eclient *c,
1023                             const char *id,
1024                             disorder_eclient_no_response *completed,
1025                             void *v) {
1026   return simple(c, no_response_opcallback, (void (*)())completed, v,
1027                 "remove", id, (char *)0);
1028 }
1029
1030 int disorder_eclient_moveafter(disorder_eclient *c,
1031                                const char *target,
1032                                int nids,
1033                                const char **ids,
1034                                disorder_eclient_no_response *completed,
1035                                void *v) {
1036   struct vector vec;
1037   int n;
1038
1039   vector_init(&vec);
1040   vector_append(&vec, (char *)"moveafter");
1041   vector_append(&vec, (char *)target);
1042   for(n = 0; n < nids; ++n)
1043     vector_append(&vec, (char *)ids[n]);
1044   stash_command_vector(c, 0/*queuejump*/, no_response_opcallback, completed, v,
1045                        vec.nvec, vec.vec);
1046   disorder_eclient_polled(c, 0);
1047   return 0;
1048 }
1049
1050 int disorder_eclient_recent(disorder_eclient *c,
1051                             disorder_eclient_queue_response *completed,
1052                             void *v) {
1053   return simple(c, queue_response_opcallback, (void (*)())completed, v,
1054                 "recent", (char *)0);
1055 }
1056
1057 int disorder_eclient_queue(disorder_eclient *c,
1058                             disorder_eclient_queue_response *completed,
1059                             void *v) {
1060   return simple(c, queue_response_opcallback, (void (*)())completed, v,
1061                 "queue", (char *)0);
1062 }
1063
1064 int disorder_eclient_files(disorder_eclient *c,
1065                            disorder_eclient_list_response *completed,
1066                            const char *dir,
1067                            const char *re,
1068                            void *v) {
1069   return simple(c, list_response_opcallback, (void (*)())completed, v,
1070                 "files", dir, re, (char *)0);
1071 }
1072
1073 int disorder_eclient_dirs(disorder_eclient *c,
1074                           disorder_eclient_list_response *completed,
1075                           const char *dir,
1076                           const char *re,
1077                           void *v) {
1078   return simple(c, list_response_opcallback, (void (*)())completed, v,
1079                 "dirs", dir, re, (char *)0);
1080 }
1081
1082 int disorder_eclient_playing(disorder_eclient *c,
1083                              disorder_eclient_queue_response *completed,
1084                              void *v) {
1085   return simple(c, playing_response_opcallback, (void (*)())completed, v,
1086                 "playing", (char *)0);
1087 }
1088
1089 int disorder_eclient_length(disorder_eclient *c,
1090                             disorder_eclient_integer_response *completed,
1091                             const char *track,
1092                             void *v) {
1093   return simple(c, integer_response_opcallback, (void (*)())completed, v,
1094                 "length", track, (char *)0);
1095 }
1096
1097 int disorder_eclient_volume(disorder_eclient *c,
1098                             disorder_eclient_volume_response *completed,
1099                             int l, int r,
1100                             void *v) {
1101   char sl[64], sr[64];
1102
1103   if(l < 0 && r < 0) {
1104     return simple(c, volume_response_opcallback, (void (*)())completed, v,
1105                   "volume", (char *)0);
1106   } else if(l >= 0 && r >= 0) {
1107     assert(l <= 100);
1108     assert(r <= 100);
1109     byte_snprintf(sl, sizeof sl, "%d", l);
1110     byte_snprintf(sr, sizeof sr, "%d", r);
1111     return simple(c, volume_response_opcallback, (void (*)())completed, v,
1112                   "volume", sl, sr, (char *)0);
1113   } else {
1114     assert(!"invalid arguments to disorder_eclient_volume");
1115     return -1;                          /* gcc is being dim */
1116   }
1117 }
1118
1119 int disorder_eclient_enable(disorder_eclient *c,
1120                             disorder_eclient_no_response *completed,
1121                             void *v) {
1122   return simple(c, no_response_opcallback, (void (*)())completed, v,
1123                 "enable", (char *)0);
1124 }
1125
1126 int disorder_eclient_disable(disorder_eclient *c,
1127                              disorder_eclient_no_response *completed,
1128                              void *v){
1129   return simple(c, no_response_opcallback, (void (*)())completed, v,
1130                 "disable", (char *)0);
1131 }
1132
1133 int disorder_eclient_random_enable(disorder_eclient *c,
1134                                    disorder_eclient_no_response *completed,
1135                                    void *v){
1136   return simple(c, no_response_opcallback, (void (*)())completed, v,
1137                 "random-enable", (char *)0);
1138 }
1139
1140 int disorder_eclient_random_disable(disorder_eclient *c,
1141                                     disorder_eclient_no_response *completed,
1142                                     void *v){
1143   return simple(c, no_response_opcallback, (void (*)())completed, v,
1144                 "random-disable", (char *)0);
1145 }
1146
1147 int disorder_eclient_get(disorder_eclient *c,
1148                          disorder_eclient_string_response *completed,
1149                          const char *track, const char *pref,
1150                          void *v) {
1151   return simple(c, string_response_opcallback, (void (*)())completed, v, 
1152                 "get", track, pref, (char *)0);
1153 }
1154
1155 int disorder_eclient_set(disorder_eclient *c,
1156                          disorder_eclient_no_response *completed,
1157                          const char *track, const char *pref, 
1158                          const char *value,
1159                          void *v) {
1160   return simple(c, no_response_opcallback, (void (*)())completed, v, 
1161                 "set", track, pref, value, (char *)0);
1162 }
1163
1164 int disorder_eclient_unset(disorder_eclient *c,
1165                            disorder_eclient_no_response *completed,
1166                            const char *track, const char *pref, 
1167                            void *v) {
1168   return simple(c, no_response_opcallback, (void (*)())completed, v, 
1169                 "unset", track, pref, (char *)0);
1170 }
1171
1172 int disorder_eclient_resolve(disorder_eclient *c,
1173                              disorder_eclient_string_response *completed,
1174                              const char *track,
1175                              void *v) {
1176   return simple(c, string_response_opcallback,  (void (*)())completed, v, 
1177                 "resolve", track, (char *)0);
1178 }
1179
1180 int disorder_eclient_search(disorder_eclient *c,
1181                             disorder_eclient_list_response *completed,
1182                             const char *terms,
1183                             void *v) {
1184   if(!split(terms, 0, SPLIT_QUOTES, 0, 0)) return -1;
1185   return simple(c, list_response_opcallback, (void (*)())completed, v,
1186                 "search", terms, (char *)0);
1187 }
1188
1189 int disorder_eclient_nop(disorder_eclient *c,
1190                          disorder_eclient_no_response *completed,
1191                          void *v) {
1192   return simple(c, no_response_opcallback, (void (*)())completed, v, 
1193                 "nop", (char *)0);
1194 }
1195
1196 /** @brief Get the last @p max added tracks
1197  * @param c Client
1198  * @param completed Called with list
1199  * @param max Number of tracks to get, 0 for all
1200  * @param v Passed to @p completed
1201  *
1202  * The first track in the list is the most recently added.
1203  */
1204 int disorder_eclient_new_tracks(disorder_eclient *c,
1205                                 disorder_eclient_list_response *completed,
1206                                 int max,
1207                                 void *v) {
1208   char limit[32];
1209
1210   sprintf(limit, "%d", max);
1211   return simple(c, list_response_opcallback, (void (*)())completed, v,
1212                 "new", limit, (char *)0);
1213 }
1214
1215 static void rtp_response_opcallback(disorder_eclient *c,
1216                                     struct operation *op) {
1217   D(("rtp_response_opcallback"));
1218   if(c->rc / 100 == 2) {
1219     if(op->completed) {
1220       int nvec;
1221       char **vec = split(c->line + 4, &nvec, SPLIT_QUOTES, 0, 0);
1222
1223       ((disorder_eclient_list_response *)op->completed)(op->v, nvec, vec);
1224     }
1225   } else
1226     protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
1227 }
1228
1229 /** @brief Determine the RTP target address
1230  * @param c Client
1231  * @param completed Called with address details
1232  * @param v Passed to @p completed
1233  *
1234  * The address details will be two elements, the first being the hostname and
1235  * the second the service (port).
1236  */
1237 int disorder_eclient_rtp_address(disorder_eclient *c,
1238                                  disorder_eclient_list_response *completed,
1239                                  void *v) {
1240   return simple(c, rtp_response_opcallback, (void (*)())completed, v,
1241                 "rtp-address", (char *)0);
1242 }
1243
1244 /* Log clients ***************************************************************/
1245
1246 /** @brief Monitor the server log
1247  * @param c Client
1248  * @param callbacks Functions to call when anything happens
1249  * @param v Passed to @p callbacks functions
1250  *
1251  * Once a client is being used for logging it cannot be used for anything else.
1252  * There is magic in authuser_opcallback() to re-submit the @c log command
1253  * after reconnection.
1254  *
1255  * NB that the @c state callback may be called from within this function,
1256  * i.e. not solely later on from the event loop callback.
1257  */
1258 int disorder_eclient_log(disorder_eclient *c,
1259                          const disorder_eclient_log_callbacks *callbacks,
1260                          void *v) {
1261   if(c->log_callbacks) return -1;
1262   c->log_callbacks = callbacks;
1263   c->log_v = v;
1264   /* Repoort initial state */
1265   if(c->log_callbacks->state)
1266     c->log_callbacks->state(c->log_v, c->statebits);
1267   stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, v,
1268                 "log", (char *)0);
1269   return 0;
1270 }
1271
1272 /* If we get here we've stopped being a log client */
1273 static void log_opcallback(disorder_eclient *c,
1274                            struct operation attribute((unused)) *op) {
1275   D(("log_opcallback"));
1276   c->log_callbacks = 0;
1277   c->log_v = 0;
1278 }
1279
1280 /* error callback for log line parsing */
1281 static void logline_error(const char *msg, void *u) {
1282   disorder_eclient *c = u;
1283   protocol_error(c, c->ops, -1, "error parsing log line: %s", msg);
1284 }
1285
1286 /* process a single log line */
1287 static void logline(disorder_eclient *c, const char *line) {
1288   int nvec, n;
1289   char **vec;
1290   uintmax_t when;
1291
1292   D(("logline [%s]", line));
1293   vec = split(line, &nvec, SPLIT_QUOTES, logline_error, c);
1294   if(nvec < 2) return;                  /* probably an error, already
1295                                          * reported */
1296   if(sscanf(vec[0], "%"SCNxMAX, &when) != 1) {
1297     /* probably the wrong side of a format change */
1298     protocol_error(c, c->ops, -1, "invalid log timestamp '%s'", vec[0]);
1299     return;
1300   }
1301   /* TODO: do something with the time */
1302   n = TABLE_FIND(logentry_handlers, struct logentry_handler, name, vec[1]);
1303   if(n < 0) return;                     /* probably a future command */
1304   vec += 2;
1305   nvec -= 2;
1306   if(nvec < logentry_handlers[n].min || nvec > logentry_handlers[n].max)
1307     return;
1308   logentry_handlers[n].handler(c, nvec, vec);
1309 }
1310
1311 static void logentry_completed(disorder_eclient *c,
1312                                int attribute((unused)) nvec, char **vec) {
1313   if(!c->log_callbacks->completed) return;
1314   c->statebits &= ~DISORDER_PLAYING;
1315   c->log_callbacks->completed(c->log_v, vec[0]);
1316   if(c->log_callbacks->state)
1317     c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1318 }
1319
1320 static void logentry_failed(disorder_eclient *c,
1321                             int attribute((unused)) nvec, char **vec) {
1322   if(!c->log_callbacks->failed)return;
1323   c->statebits &= ~DISORDER_PLAYING;
1324   c->log_callbacks->failed(c->log_v, vec[0], vec[1]);
1325   if(c->log_callbacks->state)
1326     c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1327 }
1328
1329 static void logentry_moved(disorder_eclient *c,
1330                            int attribute((unused)) nvec, char **vec) {
1331   if(!c->log_callbacks->moved) return;
1332   c->log_callbacks->moved(c->log_v, vec[0]);
1333 }
1334
1335 static void logentry_playing(disorder_eclient *c,
1336                              int attribute((unused)) nvec, char **vec) {
1337   if(!c->log_callbacks->playing) return;
1338   c->statebits |= DISORDER_PLAYING;
1339   c->log_callbacks->playing(c->log_v, vec[0], vec[1]);
1340   if(c->log_callbacks->state)
1341     c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1342 }
1343
1344 static void logentry_queue(disorder_eclient *c,
1345                            int attribute((unused)) nvec, char **vec) {
1346   struct queue_entry *q;
1347
1348   if(!c->log_callbacks->completed) return;
1349   q = xmalloc(sizeof *q);
1350   if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1351     return;                             /* bogus */
1352   c->log_callbacks->queue(c->log_v, q);
1353 }
1354
1355 static void logentry_recent_added(disorder_eclient *c,
1356                                   int attribute((unused)) nvec, char **vec) {
1357   struct queue_entry *q;
1358
1359   if(!c->log_callbacks->recent_added) return;
1360   q = xmalloc(sizeof *q);
1361   if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1362     return;                           /* bogus */
1363   c->log_callbacks->recent_added(c->log_v, q);
1364 }
1365
1366 static void logentry_recent_removed(disorder_eclient *c,
1367                                     int attribute((unused)) nvec, char **vec) {
1368   if(!c->log_callbacks->recent_removed) return;
1369   c->log_callbacks->recent_removed(c->log_v, vec[0]);
1370 }
1371
1372 static void logentry_removed(disorder_eclient *c,
1373                              int attribute((unused)) nvec, char **vec) {
1374   if(!c->log_callbacks->removed) return;
1375   c->log_callbacks->removed(c->log_v, vec[0], vec[1]);
1376 }
1377
1378 static void logentry_rescanned(disorder_eclient *c,
1379                                int attribute((unused)) nvec,
1380                                char attribute((unused)) **vec) {
1381   if(!c->log_callbacks->rescanned) return;
1382   c->log_callbacks->rescanned(c->log_v);
1383 }
1384
1385 static void logentry_scratched(disorder_eclient *c,
1386                                int attribute((unused)) nvec, char **vec) {
1387   if(!c->log_callbacks->scratched) return;
1388   c->statebits &= ~DISORDER_PLAYING;
1389   c->log_callbacks->scratched(c->log_v, vec[0], vec[1]);
1390   if(c->log_callbacks->state)
1391     c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1392 }
1393
1394 static const struct {
1395   unsigned long bit;
1396   const char *enable;
1397   const char *disable;
1398 } statestrings[] = {
1399   { DISORDER_PLAYING_ENABLED, "enable_play", "disable_play" },
1400   { DISORDER_RANDOM_ENABLED, "enable_random", "disable_random" },
1401   { DISORDER_TRACK_PAUSED, "pause", "resume" },
1402   { DISORDER_PLAYING, "playing", "completed" },
1403   { DISORDER_PLAYING, 0, "scratched" },
1404   { DISORDER_PLAYING, 0, "failed" },
1405 };
1406 #define NSTATES (int)(sizeof statestrings / sizeof *statestrings)
1407
1408 static void logentry_state(disorder_eclient *c,
1409                            int attribute((unused)) nvec, char **vec) {
1410   int n;
1411
1412   for(n = 0; n < NSTATES; ++n)
1413     if(statestrings[n].enable && !strcmp(vec[0], statestrings[n].enable)) {
1414       c->statebits |= statestrings[n].bit;
1415       break;
1416     } else if(statestrings[n].disable && !strcmp(vec[0], statestrings[n].disable)) {
1417       c->statebits &= ~statestrings[n].bit;
1418       break;
1419     }
1420   if(!c->log_callbacks->state) return;
1421   c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1422 }
1423
1424 static void logentry_volume(disorder_eclient *c,
1425                             int attribute((unused)) nvec, char **vec) {
1426   long l, r;
1427
1428   if(!c->log_callbacks->volume) return;
1429   if(xstrtol(&l, vec[0], 0, 10)
1430      || xstrtol(&r, vec[1], 0, 10)
1431      || l < 0 || l > INT_MAX
1432      || r < 0 || r > INT_MAX)
1433     return;                             /* bogus */
1434   c->log_callbacks->volume(c->log_v, (int)l, (int)r);
1435 }
1436
1437 /** @brief Convert @p statebits to a string */
1438 char *disorder_eclient_interpret_state(unsigned long statebits) {
1439   struct dynstr d[1];
1440   size_t n;
1441
1442   static const struct {
1443     unsigned long bit;
1444     const char *name;
1445   } bits[] = {
1446     { DISORDER_PLAYING_ENABLED, "playing_enabled" },
1447     { DISORDER_RANDOM_ENABLED, "random_enabled" },
1448     { DISORDER_TRACK_PAUSED, "track_paused" },
1449     { DISORDER_PLAYING, "playing" },
1450     { DISORDER_CONNECTED, "connected" },
1451   };
1452 #define NBITS (sizeof bits / sizeof *bits)
1453
1454   dynstr_init(d);
1455   if(!statebits)
1456     dynstr_append(d, '0');
1457   for(n = 0; n < NBITS; ++n)
1458     if(statebits & bits[n].bit) {
1459       if(d->nvec)
1460         dynstr_append(d, '|');
1461       dynstr_append_string(d, bits[n].name);
1462       statebits ^= bits[n].bit;
1463     }
1464   if(statebits) {
1465     char s[20];
1466
1467     if(d->nvec)
1468       dynstr_append(d, '|');
1469     sprintf(s, "%#lx", statebits);
1470     dynstr_append_string(d, s);
1471   }
1472   dynstr_terminate(d);
1473   return d->vec;
1474 }
1475
1476 /*
1477 Local Variables:
1478 c-basic-offset:2
1479 comment-column:40
1480 fill-column:79
1481 indent-tabs-mode:nil
1482 End:
1483 */