2 * This file is part of DisOrder.
3 * Copyright (C) 2006, 2007 Richard Kettlewell
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.
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.
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
20 /** @file lib/eclient.c
21 * @brief Client code for event-driven programs
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
44 #include "configuration.h"
51 #include "inputline.h"
58 #include "client-common.h"
60 /* TODO: more commands */
62 /** @brief How often to send data to the server when receiving logs */
63 #define LOG_PROD_INTERVAL 10
65 /* Types *********************************************************************/
67 /** @brief Client state */
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 */
78 /** @brief Names for @ref client_state */
79 static const char *const states[] = {
89 struct operation; /* forward decl */
91 /** @brief Type of an operation callback */
92 typedef void operation_callback(disorder_eclient *c, struct operation *op);
94 /** @brief A pending operation.
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. */
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 */
107 /** @brief true if sent to server
109 * This is cleared by disorder_eclient_close(), forcing all queued
110 * commands to be transparently resent.
115 /** @brief Client structure */
116 struct disorder_eclient {
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 */
128 /* accumulated response */
129 int rc; /**< @brief response code */
130 char *line; /**< @brief complete line */
131 struct vector vec; /**< @brief body */
133 const disorder_eclient_log_callbacks *log_callbacks;
134 /**< @brief log callbacks
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.
139 void *log_v; /**< @brief user data */
140 unsigned long statebits; /**< @brief latest state */
143 /**< @brief last time we sent a prod
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.
151 /* Forward declarations ******************************************************/
153 static int start_connect(void *cc,
154 const struct sockaddr *sa,
157 static void process_line(disorder_eclient *c, char *line);
158 static int start_connect(void *cc,
159 const struct sockaddr *sa,
162 static void maybe_connected(disorder_eclient *c);
163 static void authbanner_opcallback(disorder_eclient *c,
164 struct operation *op);
165 static void authuser_opcallback(disorder_eclient *c,
166 struct operation *op);
167 static void complete(disorder_eclient *c);
168 static void send_output(disorder_eclient *c);
169 static void put(disorder_eclient *c, const char *s, size_t n);
170 static void read_input(disorder_eclient *c);
171 static void stash_command(disorder_eclient *c,
173 operation_callback *opcallback,
178 static void log_opcallback(disorder_eclient *c, struct operation *op);
179 static void logline(disorder_eclient *c, const char *line);
180 static void logentry_completed(disorder_eclient *c, int nvec, char **vec);
181 static void logentry_failed(disorder_eclient *c, int nvec, char **vec);
182 static void logentry_moved(disorder_eclient *c, int nvec, char **vec);
183 static void logentry_playing(disorder_eclient *c, int nvec, char **vec);
184 static void logentry_queue(disorder_eclient *c, int nvec, char **vec);
185 static void logentry_recent_added(disorder_eclient *c, int nvec, char **vec);
186 static void logentry_recent_removed(disorder_eclient *c, int nvec, char **vec);
187 static void logentry_removed(disorder_eclient *c, int nvec, char **vec);
188 static void logentry_scratched(disorder_eclient *c, int nvec, char **vec);
189 static void logentry_state(disorder_eclient *c, int nvec, char **vec);
190 static void logentry_volume(disorder_eclient *c, int nvec, char **vec);
191 static void logentry_rescanned(disorder_eclient *c, int nvec, char **vec);
193 /* Tables ********************************************************************/
195 /** @brief One possible log entry */
196 struct logentry_handler {
197 const char *name; /**< @brief Entry name */
198 int min; /**< @brief Minimum arguments */
199 int max; /**< @brief Maximum arguments */
200 void (*handler)(disorder_eclient *c,
202 char **vec); /**< @brief Handler function */
205 /** @brief Table for parsing log entries */
206 static const struct logentry_handler logentry_handlers[] = {
207 #define LE(X, MIN, MAX) { #X, MIN, MAX, logentry_##X }
212 LE(queue, 2, INT_MAX),
213 LE(recent_added, 2, INT_MAX),
214 LE(recent_removed, 1, 1),
222 /* Setup and teardown ********************************************************/
224 /** @brief Create a new client
226 * Does NOT connect the client - connections are made (and re-made) on demand.
228 disorder_eclient *disorder_eclient_new(const disorder_eclient_callbacks *cb,
230 disorder_eclient *c = xmalloc(sizeof *c);
231 D(("disorder_eclient_new"));
235 c->opstail = &c->ops;
236 vector_init(&c->vec);
237 dynstr_init(&c->input);
238 dynstr_init(&c->output);
242 /** @brief Disconnect a client
243 * @param c Client to disconnect
245 * NB that this routine just disconnnects the TCP connection. It does not
246 * destroy the client! If you continue to use it then it will attempt to
249 void disorder_eclient_close(disorder_eclient *c) {
250 struct operation *op;
252 D(("disorder_eclient_close"));
254 D(("disorder_eclient_close closing fd %d", c->fd));
255 c->callbacks->poll(c->u, c, c->fd, 0);
258 c->state = state_disconnected;
264 c->authenticated = 0;
265 /* We'll need to resend all operations */
266 for(op = c->ops; op; op = op->next)
268 /* Drop our use a hint that we're disconnected */
269 if(c->log_callbacks && c->log_callbacks->state)
270 c->log_callbacks->state(c->log_v, c->statebits);
273 /** @brief Return current state */
274 unsigned long disorder_eclient_state(const disorder_eclient *c) {
275 return c->statebits | (c->state > state_connected ? DISORDER_CONNECTED : 0);
278 /* Error reporting ***********************************************************/
280 /** @brief called when a connection error occurs
282 * After this called we will be disconnected (by disorder_eclient_close()),
283 * so there will be a reconnection before any commands can be sent.
285 static int comms_error(disorder_eclient *c, const char *fmt, ...) {
291 byte_xvasprintf(&s, fmt, ap);
293 disorder_eclient_close(c);
294 c->callbacks->comms_error(c->u, s);
298 /** @brief called when the server reports an error */
299 static int protocol_error(disorder_eclient *c, struct operation *op,
300 int code, const char *fmt, ...) {
304 D(("protocol_error"));
306 byte_xvasprintf(&s, fmt, ap);
308 c->callbacks->protocol_error(c->u, op->v, code, s);
312 /* State machine *************************************************************/
314 /** @brief Called when there's something to do
316 * @param mode bitmap of @ref DISORDER_POLL_READ and/or @ref DISORDER_POLL_WRITE.
318 * This should be called from by your code when the file descriptor is readable
319 * or writable (as requested by the @c poll callback, see @ref
320 * disorder_eclient_callbacks) and in any case from time to time (with @p mode
321 * = 0) to allow for retries to work.
323 void disorder_eclient_polled(disorder_eclient *c, unsigned mode) {
324 struct operation *op;
327 D(("disorder_eclient_polled fd=%d state=%s mode=[%s %s]",
328 c->fd, states[c->state],
329 mode & DISORDER_POLL_READ ? "READ" : "",
330 mode & DISORDER_POLL_WRITE ? "WRITE" : ""));
331 /* The pattern here is to check each possible state in turn and try to
332 * advance (though on error we might go back). If we advance we leave open
333 * the possibility of falling through to the next state, but we set the mode
334 * bits to 0, to avoid false positives (which matter more in some cases than
337 if(c->state == state_disconnected) {
338 D(("state_disconnected"));
339 /* If there is no password yet then we cannot connect */
340 if(!config->password) {
341 comms_error(c, "no password is configured");
344 with_sockaddr(c, start_connect);
345 /* might now be state_disconnected (on error), state_connecting (slow
346 * connect) or state_connected (fast connect). If state_disconnected then
347 * we just rely on a periodic callback from the event loop sometime. */
351 if(c->state == state_connecting && mode) {
352 D(("state_connecting"));
354 /* Might be state_disconnected (on error) or state_connected (on success).
355 * In the former case we rely on the event loop for a periodic callback to
360 if(c->state == state_connected) {
361 D(("state_connected"));
362 /* We just connected. Initiate the authentication protocol. */
363 stash_command(c, 1/*queuejump*/, authbanner_opcallback,
364 0/*completed*/, 0/*v*/, 0/*cmd*/);
365 /* We never stay is state_connected very long. We could in principle jump
366 * straight to state_cmdresponse since there's actually no command to
367 * send, but that would arguably be cheating. */
368 c->state = state_idle;
371 if(c->state == state_idle) {
373 /* We are connected, and have finished any command we set off, look for
377 if(c->authenticated) {
378 /* Transmit all unsent operations */
379 for(op = c->ops; op; op = op->next) {
381 put(c, op->cmd, strlen(op->cmd));
386 /* Just send the head operation */
387 if(c->ops->cmd && !c->ops->sent) {
388 put(c, c->ops->cmd, strlen(c->ops->cmd));
392 /* Awaiting response for the operation at the head of the list */
393 c->state = state_cmdresponse;
396 c->callbacks->report(c->u, 0);
399 /* Queue up a byte to send */
400 if(c->state == state_log
401 && c->output.nvec == 0
402 && time(&now) - c->last_prod > LOG_PROD_INTERVAL) {
407 if(c->state == state_cmdresponse
408 || c->state == state_body
409 || c->state == state_log) {
410 D(("state_%s", states[c->state]));
411 /* We are awaiting a response */
412 if(mode & DISORDER_POLL_WRITE) send_output(c);
413 if(mode & DISORDER_POLL_READ) read_input(c);
414 /* There are a couple of reasons we might want to re-enter the state
415 * machine from the top. state_idle is obvious: there may be further
416 * commands to process. Re-entering on state_disconnected means that we
417 * immediately retry connection if a comms error occurs during a command.
418 * This is different to the case where a connection fails, where we await a
419 * spontaneous call to initiate the retry. */
421 case state_disconnected: /* lost connection */
422 case state_idle: /* completed a command */
424 disorder_eclient_polled(c, 0);
431 /* Figure out what to set the mode to */
433 case state_disconnected:
434 D(("state_disconnected (2)"));
435 /* Probably an error occurred. Await a retry. */
438 case state_connecting:
439 D(("state_connecting (2)"));
440 /* Waiting for connect to complete */
441 mode = DISORDER_POLL_READ|DISORDER_POLL_WRITE;
443 case state_connected:
444 D(("state_connected (2)"));
445 assert(!"should never be in state_connected here");
448 D(("state_idle (2)"));
449 /* Connected but nothing to do. */
452 case state_cmdresponse:
455 D(("state_%s (2)", states[c->state]));
456 /* Gathering a response. Wait for input. */
457 mode = DISORDER_POLL_READ;
458 /* Flush any pending output. */
459 if(c->output.nvec) mode |= DISORDER_POLL_WRITE;
462 D(("fd=%d new mode [%s %s]",
464 mode & DISORDER_POLL_READ ? "READ" : "",
465 mode & DISORDER_POLL_WRITE ? "WRITE" : ""));
466 if(c->fd != -1) c->callbacks->poll(c->u, c, c->fd, mode);
469 /** @brief Called to start connecting */
470 static int start_connect(void *cc,
471 const struct sockaddr *sa,
474 disorder_eclient *c = cc;
476 D(("start_connect"));
477 c->ident = xstrdup(ident);
482 if((c->fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
483 return comms_error(c, "socket: %s", strerror(errno));
487 if(connect(c->fd, sa, len) < 0) {
491 c->state = state_connecting;
492 /* We are called from _polled so the state machine will get to do its
496 /* Signal the error to the caller. */
497 return comms_error(c, "connecting to %s: %s", ident, strerror(errno));
500 c->state = state_connected;
504 /** @brief Called when poll triggers while waiting for a connection */
505 static void maybe_connected(disorder_eclient *c) {
506 /* We either connected, or got an error. */
508 socklen_t len = sizeof err;
510 D(("maybe_connected"));
511 /* Work around over-enthusiastic error slippage */
512 if(getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0)
515 /* The connection failed */
516 comms_error(c, "connecting to %s: %s", c->ident, strerror(err));
517 /* sets state_disconnected */
521 /* The connection succeeded */
522 c->state = state_connected;
523 byte_xasprintf(&r, "connected to %s", c->ident);
524 c->callbacks->report(c->u, r);
525 /* If this is a log client we expect to get a bunch of updates from the
526 * server straight away */
530 /* Authentication ************************************************************/
532 static void authbanner_opcallback(disorder_eclient *c,
533 struct operation *op) {
535 const unsigned char *nonce;
539 const char *algo = "SHA1";
541 D(("authbanner_opcallback"));
543 || !(rvec = split(c->line + 4, &nrvec, SPLIT_QUOTES, 0, 0))
545 /* Banner told us to go away, or was malformed. We cannot proceed. */
546 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
547 disorder_eclient_close(c);
554 nonce = unhex(rvec[0], &nonce_len);
555 res = authhash(nonce, nonce_len, config->password, algo);
557 protocol_error(c, op, c->rc, "%s: unknown authentication algorithm '%s'",
559 disorder_eclient_close(c);
562 stash_command(c, 1/*queuejump*/, authuser_opcallback, 0/*completed*/, 0/*v*/,
563 "user", quoteutf8(config->username), quoteutf8(res),
567 static void authuser_opcallback(disorder_eclient *c,
568 struct operation *op) {
571 D(("authuser_opcallback"));
572 if(c->rc / 100 != 2) {
573 /* Wrong password or something. We cannot proceed. */
574 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
575 disorder_eclient_close(c);
578 /* OK, we're authenticated now. */
579 c->authenticated = 1;
580 byte_xasprintf(&r, "authenticated with %s", c->ident);
581 c->callbacks->report(c->u, r);
582 if(c->log_callbacks && !(c->ops && c->ops->opcallback == log_opcallback))
583 /* We are a log client, switch to logging mode */
584 stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, c->log_v,
588 /* Output ********************************************************************/
590 /* Chop N bytes off the front of a dynstr */
591 static void consume(struct dynstr *d, int n) {
592 D(("consume %d", n));
593 assert(d->nvec >= n);
594 memmove(d->vec, d->vec + n, d->nvec - n);
598 /* Write some bytes */
599 static void put(disorder_eclient *c, const char *s, size_t n) {
600 D(("put %d %.*s", c->fd, (int)n, s));
601 dynstr_append_bytes(&c->output, s, n);
604 /* Called when we can write to our FD, or at any other time */
605 static void send_output(disorder_eclient *c) {
608 D(("send_output %d bytes pending", c->output.nvec));
609 if(c->state > state_connecting && c->output.nvec) {
610 n = write(c->fd, c->output.vec, c->output.nvec);
617 comms_error(c, "writing to %s: %s", c->ident, strerror(errno));
621 consume(&c->output, n);
625 /* Input *********************************************************************/
627 /* Called when c->fd might be readable, or at any other time */
628 static void read_input(disorder_eclient *c) {
633 D(("read_input in state %s", states[c->state]));
634 if(c->state <= state_connected) return; /* ignore bogus calls */
635 /* read some more input */
636 n = read(c->fd, buffer, sizeof buffer);
643 comms_error(c, "reading from %s: %s", c->ident, strerror(errno));
646 return; /* no new input to process */
648 D(("read %d bytes: [%.*s]", n, n, buffer));
649 dynstr_append_bytes(&c->input, buffer, n);
652 /* might have more than one line to process */
653 while(c->state > state_connecting
654 && (nl = memchr(c->input.vec, '\n', c->input.nvec))) {
655 process_line(c, xstrndup(c->input.vec, nl - c->input.vec));
656 /* we might have disconnected along the way, which zogs the input buffer */
657 if(c->state > state_connecting)
658 consume(&c->input, (nl - c->input.vec) + 1);
661 comms_error(c, "reading from %s: server disconnected", c->ident);
662 c->authenticated = 0;
666 /* called with a line that has just been read */
667 static void process_line(disorder_eclient *c, char *line) {
668 D(("process_line %d [%s]", c->fd, line));
670 case state_cmdresponse:
671 /* This is the first line of a response */
672 if(!(line[0] >= '0' && line[0] <= '9'
673 && line[1] >= '0' && line[1] <= '9'
674 && line[2] >= '0' && line[2] <= '9'
676 fatal(0, "invalid response from server: %s", line);
677 c->rc = (line[0] * 10 + line[1]) * 10 + line[2] - 111 * '0';
681 /* We need to collect the body. */
682 c->state = state_body;
683 vector_init(&c->vec);
686 assert(c->log_callbacks != 0);
687 if(c->log_callbacks->connected)
688 c->log_callbacks->connected(c->log_v);
689 c->state = state_log;
692 /* We've got the whole response. Go into the idle state so the state
693 * machine knows we're done and then call the operation callback. */
699 if(strcmp(line, ".")) {
700 /* A line from the body */
701 vector_append(&c->vec, line + (line[0] == '.'));
703 /* End of the body. */
704 vector_terminate(&c->vec);
709 if(strcmp(line, ".")) {
710 logline(c, line + (line[0] == '.'));
715 assert(!"wrong state for location");
720 /* Called when an operation completes */
721 static void complete(disorder_eclient *c) {
722 struct operation *op;
725 /* Pop the operation off the queue */
728 if(c->opstail == &op->next)
729 c->opstail = &c->ops;
730 /* If we've pipelined a command ahead then we go straight to cmdresponser.
731 * Otherwise we go to idle, which will arrange further sends. */
732 c->state = c->ops && c->ops->sent ? state_cmdresponse : state_idle;
733 op->opcallback(c, op);
734 /* Note that we always call the opcallback even on error, though command
735 * opcallbacks generally always do the same error handling, i.e. just call
736 * protocol_error(). It's the auth* opcallbacks that have different
740 /* Operation setup ***********************************************************/
742 static void stash_command_vector(disorder_eclient *c,
744 operation_callback *opcallback,
749 struct operation *op = xmalloc(sizeof *op);
755 for(n = 0; n < ncmd; ++n) {
757 dynstr_append(&d, ' ');
758 dynstr_append_string(&d, quoteutf8(cmd[n]));
760 dynstr_append(&d, '\n');
761 dynstr_terminate(&d);
764 op->cmd = 0; /* usually, awaiting challenge */
765 op->opcallback = opcallback;
766 op->completed = completed;
770 assert(op->sent == 0);
772 /* Authentication operations jump the queue of useful commands */
775 if(c->opstail == &c->ops)
776 c->opstail = &op->next;
777 for(op = c->ops; op; op = op->next)
781 c->opstail = &op->next;
785 static void vstash_command(disorder_eclient *c,
787 operation_callback *opcallback,
790 const char *cmd, va_list ap) {
794 D(("vstash_command %s", cmd ? cmd : "NULL"));
797 vector_append(&vec, (char *)cmd);
798 while((arg = va_arg(ap, char *)))
799 vector_append(&vec, arg);
800 stash_command_vector(c, queuejump, opcallback, completed, v,
803 stash_command_vector(c, queuejump, opcallback, completed, v, 0, 0);
806 static void stash_command(disorder_eclient *c,
808 operation_callback *opcallback,
816 vstash_command(c, queuejump, opcallback, completed, v, cmd, ap);
820 /* Command support ***********************************************************/
822 /* for commands with a simple string response */
823 static void string_response_opcallback(disorder_eclient *c,
824 struct operation *op) {
825 D(("string_response_callback"));
826 if(c->rc / 100 == 2) {
828 ((disorder_eclient_string_response *)op->completed)(op->v, c->line + 4);
830 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
833 /* for commands with a simple integer response */
834 static void integer_response_opcallback(disorder_eclient *c,
835 struct operation *op) {
836 D(("string_response_callback"));
837 if(c->rc / 100 == 2) {
839 ((disorder_eclient_integer_response *)op->completed)
840 (op->v, strtol(c->line + 4, 0, 10));
842 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
845 /* for commands with no response */
846 static void no_response_opcallback(disorder_eclient *c,
847 struct operation *op) {
848 D(("no_response_callback"));
849 if(c->rc / 100 == 2) {
851 ((disorder_eclient_no_response *)op->completed)(op->v);
853 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
856 /* error callback for queue_unmarshall */
857 static void eclient_queue_error(const char *msg,
859 struct operation *op = u;
861 protocol_error(op->client, op, -1, "error parsing queue entry: %s", msg);
864 /* for commands that expect a queue dump */
865 static void queue_response_opcallback(disorder_eclient *c,
866 struct operation *op) {
868 struct queue_entry *q, *qh = 0, **qtail = &qh, *qlast = 0;
870 D(("queue_response_callback"));
871 if(c->rc / 100 == 2) {
872 /* parse the queue */
873 for(n = 0; n < c->vec.nvec; ++n) {
874 q = xmalloc(sizeof *q);
875 D(("queue_unmarshall %s", c->vec.vec[n]));
876 if(!queue_unmarshall(q, c->vec.vec[n], eclient_queue_error, op)) {
884 ((disorder_eclient_queue_response *)op->completed)(op->v, qh);
886 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
890 static void playing_response_opcallback(disorder_eclient *c,
891 struct operation *op) {
892 struct queue_entry *q;
894 D(("playing_response_callback"));
895 if(c->rc / 100 == 2) {
898 if(queue_unmarshall(q = xmalloc(sizeof *q), c->line + 4,
899 eclient_queue_error, c))
906 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
910 ((disorder_eclient_queue_response *)op->completed)(op->v, q);
912 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
915 /* for commands that expect a list of some sort */
916 static void list_response_opcallback(disorder_eclient *c,
917 struct operation *op) {
918 D(("list_response_callback"));
919 if(c->rc / 100 == 2) {
921 ((disorder_eclient_list_response *)op->completed)(op->v,
925 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
929 static void volume_response_opcallback(disorder_eclient *c,
930 struct operation *op) {
933 D(("volume_response_callback"));
934 if(c->rc / 100 == 2) {
936 if(sscanf(c->line + 4, "%d %d", &l, &r) != 2 || l < 0 || r < 0)
937 protocol_error(c, op, -1, "%s: invalid volume response: %s",
940 ((disorder_eclient_volume_response *)op->completed)(op->v, l, r);
943 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
946 static int simple(disorder_eclient *c,
947 operation_callback *opcallback,
950 const char *cmd, ...) {
954 vstash_command(c, 0/*queuejump*/, opcallback, completed, v, cmd, ap);
956 /* Give the state machine a kick, since we might be in state_idle */
957 disorder_eclient_polled(c, 0);
961 /* Commands ******************************************************************/
963 int disorder_eclient_version(disorder_eclient *c,
964 disorder_eclient_string_response *completed,
966 return simple(c, string_response_opcallback, (void (*)())completed, v,
967 "version", (char *)0);
970 int disorder_eclient_namepart(disorder_eclient *c,
971 disorder_eclient_string_response *completed,
976 return simple(c, string_response_opcallback, (void (*)())completed, v,
977 "part", track, context, part, (char *)0);
980 int disorder_eclient_play(disorder_eclient *c,
982 disorder_eclient_no_response *completed,
984 return simple(c, no_response_opcallback, (void (*)())completed, v,
985 "play", track, (char *)0);
988 int disorder_eclient_pause(disorder_eclient *c,
989 disorder_eclient_no_response *completed,
991 return simple(c, no_response_opcallback, (void (*)())completed, v,
995 int disorder_eclient_resume(disorder_eclient *c,
996 disorder_eclient_no_response *completed,
998 return simple(c, no_response_opcallback, (void (*)())completed, v,
999 "resume", (char *)0);
1002 int disorder_eclient_scratch(disorder_eclient *c,
1004 disorder_eclient_no_response *completed,
1006 return simple(c, no_response_opcallback, (void (*)())completed, v,
1007 "scratch", id, (char *)0);
1010 int disorder_eclient_scratch_playing(disorder_eclient *c,
1011 disorder_eclient_no_response *completed,
1013 return disorder_eclient_scratch(c, 0, completed, v);
1016 int disorder_eclient_remove(disorder_eclient *c,
1018 disorder_eclient_no_response *completed,
1020 return simple(c, no_response_opcallback, (void (*)())completed, v,
1021 "remove", id, (char *)0);
1024 int disorder_eclient_moveafter(disorder_eclient *c,
1028 disorder_eclient_no_response *completed,
1034 vector_append(&vec, (char *)"moveafter");
1035 vector_append(&vec, (char *)target);
1036 for(n = 0; n < nids; ++n)
1037 vector_append(&vec, (char *)ids[n]);
1038 stash_command_vector(c, 0/*queuejump*/, no_response_opcallback, completed, v,
1040 disorder_eclient_polled(c, 0);
1044 int disorder_eclient_recent(disorder_eclient *c,
1045 disorder_eclient_queue_response *completed,
1047 return simple(c, queue_response_opcallback, (void (*)())completed, v,
1048 "recent", (char *)0);
1051 int disorder_eclient_queue(disorder_eclient *c,
1052 disorder_eclient_queue_response *completed,
1054 return simple(c, queue_response_opcallback, (void (*)())completed, v,
1055 "queue", (char *)0);
1058 int disorder_eclient_files(disorder_eclient *c,
1059 disorder_eclient_list_response *completed,
1063 return simple(c, list_response_opcallback, (void (*)())completed, v,
1064 "files", dir, re, (char *)0);
1067 int disorder_eclient_dirs(disorder_eclient *c,
1068 disorder_eclient_list_response *completed,
1072 return simple(c, list_response_opcallback, (void (*)())completed, v,
1073 "dirs", dir, re, (char *)0);
1076 int disorder_eclient_playing(disorder_eclient *c,
1077 disorder_eclient_queue_response *completed,
1079 return simple(c, playing_response_opcallback, (void (*)())completed, v,
1080 "playing", (char *)0);
1083 int disorder_eclient_length(disorder_eclient *c,
1084 disorder_eclient_integer_response *completed,
1087 return simple(c, integer_response_opcallback, (void (*)())completed, v,
1088 "length", track, (char *)0);
1091 int disorder_eclient_volume(disorder_eclient *c,
1092 disorder_eclient_volume_response *completed,
1095 char sl[64], sr[64];
1097 if(l < 0 && r < 0) {
1098 return simple(c, volume_response_opcallback, (void (*)())completed, v,
1099 "volume", (char *)0);
1100 } else if(l >= 0 && r >= 0) {
1103 byte_snprintf(sl, sizeof sl, "%d", l);
1104 byte_snprintf(sr, sizeof sr, "%d", r);
1105 return simple(c, volume_response_opcallback, (void (*)())completed, v,
1106 "volume", sl, sr, (char *)0);
1108 assert(!"invalid arguments to disorder_eclient_volume");
1109 return -1; /* gcc is being dim */
1113 int disorder_eclient_enable(disorder_eclient *c,
1114 disorder_eclient_no_response *completed,
1116 return simple(c, no_response_opcallback, (void (*)())completed, v,
1117 "enable", (char *)0);
1120 int disorder_eclient_disable(disorder_eclient *c,
1121 disorder_eclient_no_response *completed,
1123 return simple(c, no_response_opcallback, (void (*)())completed, v,
1124 "disable", (char *)0);
1127 int disorder_eclient_random_enable(disorder_eclient *c,
1128 disorder_eclient_no_response *completed,
1130 return simple(c, no_response_opcallback, (void (*)())completed, v,
1131 "random-enable", (char *)0);
1134 int disorder_eclient_random_disable(disorder_eclient *c,
1135 disorder_eclient_no_response *completed,
1137 return simple(c, no_response_opcallback, (void (*)())completed, v,
1138 "random-disable", (char *)0);
1141 int disorder_eclient_get(disorder_eclient *c,
1142 disorder_eclient_string_response *completed,
1143 const char *track, const char *pref,
1145 return simple(c, string_response_opcallback, (void (*)())completed, v,
1146 "get", track, pref, (char *)0);
1149 int disorder_eclient_set(disorder_eclient *c,
1150 disorder_eclient_no_response *completed,
1151 const char *track, const char *pref,
1154 return simple(c, no_response_opcallback, (void (*)())completed, v,
1155 "set", track, pref, value, (char *)0);
1158 int disorder_eclient_unset(disorder_eclient *c,
1159 disorder_eclient_no_response *completed,
1160 const char *track, const char *pref,
1162 return simple(c, no_response_opcallback, (void (*)())completed, v,
1163 "unset", track, pref, (char *)0);
1166 int disorder_eclient_resolve(disorder_eclient *c,
1167 disorder_eclient_string_response *completed,
1170 return simple(c, string_response_opcallback, (void (*)())completed, v,
1171 "resolve", track, (char *)0);
1174 int disorder_eclient_search(disorder_eclient *c,
1175 disorder_eclient_list_response *completed,
1178 if(!split(terms, 0, SPLIT_QUOTES, 0, 0)) return -1;
1179 return simple(c, list_response_opcallback, (void (*)())completed, v,
1180 "search", terms, (char *)0);
1183 int disorder_eclient_nop(disorder_eclient *c,
1184 disorder_eclient_no_response *completed,
1186 return simple(c, no_response_opcallback, (void (*)())completed, v,
1190 /** @brief Get the last @p max added tracks
1192 * @param completed Called with list
1193 * @param max Number of tracks to get, 0 for all
1194 * @param v Passed to @p completed
1196 * The first track in the list is the most recently added.
1198 int disorder_eclient_new_tracks(disorder_eclient *c,
1199 disorder_eclient_list_response *completed,
1204 sprintf(limit, "%d", max);
1205 return simple(c, list_response_opcallback, (void (*)())completed, v,
1206 "new", limit, (char *)0);
1209 static void rtp_response_opcallback(disorder_eclient *c,
1210 struct operation *op) {
1211 D(("rtp_response_opcallback"));
1212 if(c->rc / 100 == 2) {
1215 char **vec = split(c->line + 4, &nvec, SPLIT_QUOTES, 0, 0);
1217 ((disorder_eclient_list_response *)op->completed)(op->v, nvec, vec);
1220 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
1223 /** @brief Determine the RTP target address
1225 * @param completed Called with address details
1226 * @param v Passed to @p completed
1228 * The address details will be two elements, the first being the hostname and
1229 * the second the service (port).
1231 int disorder_eclient_rtp_address(disorder_eclient *c,
1232 disorder_eclient_list_response *completed,
1234 return simple(c, rtp_response_opcallback, (void (*)())completed, v,
1235 "rtp-address", (char *)0);
1238 /* Log clients ***************************************************************/
1240 /** @brief Monitor the server log
1242 * @param callbacks Functions to call when anything happens
1243 * @param v Passed to @p callbacks functions
1245 * Once a client is being used for logging it cannot be used for anything else.
1246 * There is magic in authuser_opcallback() to re-submit the @c log command
1247 * after reconnection.
1249 * NB that the @c state callback may be called from within this function,
1250 * i.e. not solely later on from the event loop callback.
1252 int disorder_eclient_log(disorder_eclient *c,
1253 const disorder_eclient_log_callbacks *callbacks,
1255 if(c->log_callbacks) return -1;
1256 c->log_callbacks = callbacks;
1258 /* Repoort initial state */
1259 if(c->log_callbacks->state)
1260 c->log_callbacks->state(c->log_v, c->statebits);
1261 stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, v,
1266 /* If we get here we've stopped being a log client */
1267 static void log_opcallback(disorder_eclient *c,
1268 struct operation attribute((unused)) *op) {
1269 D(("log_opcallback"));
1270 c->log_callbacks = 0;
1274 /* error callback for log line parsing */
1275 static void logline_error(const char *msg, void *u) {
1276 disorder_eclient *c = u;
1277 protocol_error(c, c->ops, -1, "error parsing log line: %s", msg);
1280 /* process a single log line */
1281 static void logline(disorder_eclient *c, const char *line) {
1286 D(("logline [%s]", line));
1287 vec = split(line, &nvec, SPLIT_QUOTES, logline_error, c);
1288 if(nvec < 2) return; /* probably an error, already
1290 if(sscanf(vec[0], "%"SCNxMAX, &when) != 1) {
1291 /* probably the wrong side of a format change */
1292 protocol_error(c, c->ops, -1, "invalid log timestamp '%s'", vec[0]);
1295 /* TODO: do something with the time */
1296 n = TABLE_FIND(logentry_handlers, struct logentry_handler, name, vec[1]);
1297 if(n < 0) return; /* probably a future command */
1300 if(nvec < logentry_handlers[n].min || nvec > logentry_handlers[n].max)
1302 logentry_handlers[n].handler(c, nvec, vec);
1305 static void logentry_completed(disorder_eclient *c,
1306 int attribute((unused)) nvec, char **vec) {
1307 if(!c->log_callbacks->completed) return;
1308 c->statebits &= ~DISORDER_PLAYING;
1309 c->log_callbacks->completed(c->log_v, vec[0]);
1310 if(c->log_callbacks->state)
1311 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1314 static void logentry_failed(disorder_eclient *c,
1315 int attribute((unused)) nvec, char **vec) {
1316 if(!c->log_callbacks->failed)return;
1317 c->statebits &= ~DISORDER_PLAYING;
1318 c->log_callbacks->failed(c->log_v, vec[0], vec[1]);
1319 if(c->log_callbacks->state)
1320 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1323 static void logentry_moved(disorder_eclient *c,
1324 int attribute((unused)) nvec, char **vec) {
1325 if(!c->log_callbacks->moved) return;
1326 c->log_callbacks->moved(c->log_v, vec[0]);
1329 static void logentry_playing(disorder_eclient *c,
1330 int attribute((unused)) nvec, char **vec) {
1331 if(!c->log_callbacks->playing) return;
1332 c->statebits |= DISORDER_PLAYING;
1333 c->log_callbacks->playing(c->log_v, vec[0], vec[1]);
1334 if(c->log_callbacks->state)
1335 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1338 static void logentry_queue(disorder_eclient *c,
1339 int attribute((unused)) nvec, char **vec) {
1340 struct queue_entry *q;
1342 if(!c->log_callbacks->completed) return;
1343 q = xmalloc(sizeof *q);
1344 if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1346 c->log_callbacks->queue(c->log_v, q);
1349 static void logentry_recent_added(disorder_eclient *c,
1350 int attribute((unused)) nvec, char **vec) {
1351 struct queue_entry *q;
1353 if(!c->log_callbacks->recent_added) return;
1354 q = xmalloc(sizeof *q);
1355 if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1357 c->log_callbacks->recent_added(c->log_v, q);
1360 static void logentry_recent_removed(disorder_eclient *c,
1361 int attribute((unused)) nvec, char **vec) {
1362 if(!c->log_callbacks->recent_removed) return;
1363 c->log_callbacks->recent_removed(c->log_v, vec[0]);
1366 static void logentry_removed(disorder_eclient *c,
1367 int attribute((unused)) nvec, char **vec) {
1368 if(!c->log_callbacks->removed) return;
1369 c->log_callbacks->removed(c->log_v, vec[0], vec[1]);
1372 static void logentry_rescanned(disorder_eclient *c,
1373 int attribute((unused)) nvec,
1374 char attribute((unused)) **vec) {
1375 if(!c->log_callbacks->rescanned) return;
1376 c->log_callbacks->rescanned(c->log_v);
1379 static void logentry_scratched(disorder_eclient *c,
1380 int attribute((unused)) nvec, char **vec) {
1381 if(!c->log_callbacks->scratched) return;
1382 c->statebits &= ~DISORDER_PLAYING;
1383 c->log_callbacks->scratched(c->log_v, vec[0], vec[1]);
1384 if(c->log_callbacks->state)
1385 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1388 static const struct {
1391 const char *disable;
1392 } statestrings[] = {
1393 { DISORDER_PLAYING_ENABLED, "enable_play", "disable_play" },
1394 { DISORDER_RANDOM_ENABLED, "enable_random", "disable_random" },
1395 { DISORDER_TRACK_PAUSED, "pause", "resume" },
1396 { DISORDER_PLAYING, "playing", "completed" },
1397 { DISORDER_PLAYING, 0, "scratched" },
1398 { DISORDER_PLAYING, 0, "failed" },
1400 #define NSTATES (int)(sizeof statestrings / sizeof *statestrings)
1402 static void logentry_state(disorder_eclient *c,
1403 int attribute((unused)) nvec, char **vec) {
1406 for(n = 0; n < NSTATES; ++n)
1407 if(statestrings[n].enable && !strcmp(vec[0], statestrings[n].enable)) {
1408 c->statebits |= statestrings[n].bit;
1410 } else if(statestrings[n].disable && !strcmp(vec[0], statestrings[n].disable)) {
1411 c->statebits &= ~statestrings[n].bit;
1414 if(!c->log_callbacks->state) return;
1415 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1418 static void logentry_volume(disorder_eclient *c,
1419 int attribute((unused)) nvec, char **vec) {
1422 if(!c->log_callbacks->volume) return;
1423 if(xstrtol(&l, vec[0], 0, 10)
1424 || xstrtol(&r, vec[1], 0, 10)
1425 || l < 0 || l > INT_MAX
1426 || r < 0 || r > INT_MAX)
1428 c->log_callbacks->volume(c->log_v, (int)l, (int)r);
1431 /** @brief Convert @p statebits to a string */
1432 char *disorder_eclient_interpret_state(unsigned long statebits) {
1436 static const struct {
1440 { DISORDER_PLAYING_ENABLED, "playing_enabled" },
1441 { DISORDER_RANDOM_ENABLED, "random_enabled" },
1442 { DISORDER_TRACK_PAUSED, "track_paused" },
1443 { DISORDER_PLAYING, "playing" },
1444 { DISORDER_CONNECTED, "connected" },
1446 #define NBITS (sizeof bits / sizeof *bits)
1450 dynstr_append(d, '0');
1451 for(n = 0; n < NBITS; ++n)
1452 if(statebits & bits[n].bit) {
1454 dynstr_append(d, '|');
1455 dynstr_append_string(d, bits[n].name);
1456 statebits ^= bits[n].bit;
1462 dynstr_append(d, '|');
1463 sprintf(s, "%#lx", statebits);
1464 dynstr_append_string(d, s);
1466 dynstr_terminate(d);
1475 indent-tabs-mode:nil