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