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