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