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