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