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