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