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