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