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