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