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