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