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