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