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(disorder_eclient *c);
154 static void process_line(disorder_eclient *c, char *line);
155 static void maybe_connected(disorder_eclient *c);
156 static void authbanner_opcallback(disorder_eclient *c,
157 struct operation *op);
158 static void authuser_opcallback(disorder_eclient *c,
159 struct operation *op);
160 static void complete(disorder_eclient *c);
161 static void send_output(disorder_eclient *c);
162 static void put(disorder_eclient *c, const char *s, size_t n);
163 static void read_input(disorder_eclient *c);
164 static void stash_command(disorder_eclient *c,
166 operation_callback *opcallback,
171 static void log_opcallback(disorder_eclient *c, struct operation *op);
172 static void logline(disorder_eclient *c, const char *line);
173 static void logentry_completed(disorder_eclient *c, int nvec, char **vec);
174 static void logentry_failed(disorder_eclient *c, int nvec, char **vec);
175 static void logentry_moved(disorder_eclient *c, int nvec, char **vec);
176 static void logentry_playing(disorder_eclient *c, int nvec, char **vec);
177 static void logentry_queue(disorder_eclient *c, int nvec, char **vec);
178 static void logentry_recent_added(disorder_eclient *c, int nvec, char **vec);
179 static void logentry_recent_removed(disorder_eclient *c, int nvec, char **vec);
180 static void logentry_removed(disorder_eclient *c, int nvec, char **vec);
181 static void logentry_scratched(disorder_eclient *c, int nvec, char **vec);
182 static void logentry_state(disorder_eclient *c, int nvec, char **vec);
183 static void logentry_volume(disorder_eclient *c, int nvec, char **vec);
184 static void logentry_rescanned(disorder_eclient *c, int nvec, char **vec);
186 /* Tables ********************************************************************/
188 /** @brief One possible log entry */
189 struct logentry_handler {
190 const char *name; /**< @brief Entry name */
191 int min; /**< @brief Minimum arguments */
192 int max; /**< @brief Maximum arguments */
193 void (*handler)(disorder_eclient *c,
195 char **vec); /**< @brief Handler function */
198 /** @brief Table for parsing log entries */
199 static const struct logentry_handler logentry_handlers[] = {
200 #define LE(X, MIN, MAX) { #X, MIN, MAX, logentry_##X }
205 LE(queue, 2, INT_MAX),
206 LE(recent_added, 2, INT_MAX),
207 LE(recent_removed, 1, 1),
215 /* Setup and teardown ********************************************************/
217 /** @brief Create a new client
219 * Does NOT connect the client - connections are made (and re-made) on demand.
221 disorder_eclient *disorder_eclient_new(const disorder_eclient_callbacks *cb,
223 disorder_eclient *c = xmalloc(sizeof *c);
224 D(("disorder_eclient_new"));
228 c->opstail = &c->ops;
229 vector_init(&c->vec);
230 dynstr_init(&c->input);
231 dynstr_init(&c->output);
235 /** @brief Disconnect a client
236 * @param c Client to disconnect
238 * NB that this routine just disconnnects the TCP connection. It does not
239 * destroy the client! If you continue to use it then it will attempt to
242 void disorder_eclient_close(disorder_eclient *c) {
243 struct operation *op;
245 D(("disorder_eclient_close"));
247 D(("disorder_eclient_close closing fd %d", c->fd));
248 c->callbacks->poll(c->u, c, c->fd, 0);
251 c->state = state_disconnected;
257 c->authenticated = 0;
258 /* We'll need to resend all operations */
259 for(op = c->ops; op; op = op->next)
261 /* Drop our use a hint that we're disconnected */
262 if(c->log_callbacks && c->log_callbacks->state)
263 c->log_callbacks->state(c->log_v, c->statebits);
266 /** @brief Return current state */
267 unsigned long disorder_eclient_state(const disorder_eclient *c) {
268 return c->statebits | (c->state > state_connected ? DISORDER_CONNECTED : 0);
271 /* Error reporting ***********************************************************/
273 /** @brief called when a connection error occurs
275 * After this called we will be disconnected (by disorder_eclient_close()),
276 * so there will be a reconnection before any commands can be sent.
278 static int comms_error(disorder_eclient *c, const char *fmt, ...) {
284 byte_xvasprintf(&s, fmt, ap);
286 disorder_eclient_close(c);
287 c->callbacks->comms_error(c->u, s);
291 /** @brief called when the server reports an error */
292 static int protocol_error(disorder_eclient *c, struct operation *op,
293 int code, const char *fmt, ...) {
297 D(("protocol_error"));
299 byte_xvasprintf(&s, fmt, ap);
301 c->callbacks->protocol_error(c->u, op->v, code, s);
305 /* State machine *************************************************************/
307 /** @brief Called when there's something to do
309 * @param mode bitmap of @ref DISORDER_POLL_READ and/or @ref DISORDER_POLL_WRITE.
311 * This should be called from by your code when the file descriptor is readable
312 * or writable (as requested by the @c poll callback, see @ref
313 * disorder_eclient_callbacks) and in any case from time to time (with @p mode
314 * = 0) to allow for retries to work.
316 void disorder_eclient_polled(disorder_eclient *c, unsigned mode) {
317 struct operation *op;
320 D(("disorder_eclient_polled fd=%d state=%s mode=[%s %s]",
321 c->fd, states[c->state],
322 mode & DISORDER_POLL_READ ? "READ" : "",
323 mode & DISORDER_POLL_WRITE ? "WRITE" : ""));
324 /* The pattern here is to check each possible state in turn and try to
325 * advance (though on error we might go back). If we advance we leave open
326 * the possibility of falling through to the next state, but we set the mode
327 * bits to 0, to avoid false positives (which matter more in some cases than
330 if(c->state == state_disconnected) {
331 D(("state_disconnected"));
332 /* If there is no password yet then we cannot connect */
333 if(!config->password) {
334 comms_error(c, "no password is configured");
338 /* might now be state_disconnected (on error), state_connecting (slow
339 * connect) or state_connected (fast connect). If state_disconnected then
340 * we just rely on a periodic callback from the event loop sometime. */
344 if(c->state == state_connecting && mode) {
345 D(("state_connecting"));
347 /* Might be state_disconnected (on error) or state_connected (on success).
348 * In the former case we rely on the event loop for a periodic callback to
353 if(c->state == state_connected) {
354 D(("state_connected"));
355 /* We just connected. Initiate the authentication protocol. */
356 stash_command(c, 1/*queuejump*/, authbanner_opcallback,
357 0/*completed*/, 0/*v*/, 0/*cmd*/);
358 /* We never stay is state_connected very long. We could in principle jump
359 * straight to state_cmdresponse since there's actually no command to
360 * send, but that would arguably be cheating. */
361 c->state = state_idle;
364 if(c->state == state_idle) {
366 /* We are connected, and have finished any command we set off, look for
370 if(c->authenticated) {
371 /* Transmit all unsent operations */
372 for(op = c->ops; op; op = op->next) {
374 put(c, op->cmd, strlen(op->cmd));
379 /* Just send the head operation */
380 if(c->ops->cmd && !c->ops->sent) {
381 put(c, c->ops->cmd, strlen(c->ops->cmd));
385 /* Awaiting response for the operation at the head of the list */
386 c->state = state_cmdresponse;
389 c->callbacks->report(c->u, 0);
392 /* Queue up a byte to send */
393 if(c->state == state_log
394 && c->output.nvec == 0
395 && time(&now) - c->last_prod > LOG_PROD_INTERVAL) {
400 if(c->state == state_cmdresponse
401 || c->state == state_body
402 || c->state == state_log) {
403 D(("state_%s", states[c->state]));
404 /* We are awaiting a response */
405 if(mode & DISORDER_POLL_WRITE) send_output(c);
406 if(mode & DISORDER_POLL_READ) read_input(c);
407 /* There are a couple of reasons we might want to re-enter the state
408 * machine from the top. state_idle is obvious: there may be further
409 * commands to process. Re-entering on state_disconnected means that we
410 * immediately retry connection if a comms error occurs during a command.
411 * This is different to the case where a connection fails, where we await a
412 * spontaneous call to initiate the retry. */
414 case state_disconnected: /* lost connection */
415 case state_idle: /* completed a command */
417 disorder_eclient_polled(c, 0);
424 /* Figure out what to set the mode to */
426 case state_disconnected:
427 D(("state_disconnected (2)"));
428 /* Probably an error occurred. Await a retry. */
431 case state_connecting:
432 D(("state_connecting (2)"));
433 /* Waiting for connect to complete */
434 mode = DISORDER_POLL_READ|DISORDER_POLL_WRITE;
436 case state_connected:
437 D(("state_connected (2)"));
438 assert(!"should never be in state_connected here");
441 D(("state_idle (2)"));
442 /* Connected but nothing to do. */
445 case state_cmdresponse:
448 D(("state_%s (2)", states[c->state]));
449 /* Gathering a response. Wait for input. */
450 mode = DISORDER_POLL_READ;
451 /* Flush any pending output. */
452 if(c->output.nvec) mode |= DISORDER_POLL_WRITE;
455 D(("fd=%d new mode [%s %s]",
457 mode & DISORDER_POLL_READ ? "READ" : "",
458 mode & DISORDER_POLL_WRITE ? "WRITE" : ""));
459 if(c->fd != -1) c->callbacks->poll(c->u, c, c->fd, mode);
462 /** @brief Called to start connecting */
463 static int start_connect(disorder_eclient *c) {
467 D(("start_connect"));
468 if((len = find_server(&sa, &c->ident)) == (socklen_t)-1)
469 return comms_error(c, "cannot look up server"); /* TODO better error */
474 if((c->fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
475 return comms_error(c, "socket: %s", strerror(errno));
479 if(connect(c->fd, sa, len) < 0) {
483 c->state = state_connecting;
484 /* We are called from _polled so the state machine will get to do its
488 /* Signal the error to the caller. */
489 return comms_error(c, "connecting to %s: %s", c->ident, strerror(errno));
492 c->state = state_connected;
496 /** @brief Called when poll triggers while waiting for a connection */
497 static void maybe_connected(disorder_eclient *c) {
498 /* We either connected, or got an error. */
500 socklen_t len = sizeof err;
502 D(("maybe_connected"));
503 /* Work around over-enthusiastic error slippage */
504 if(getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0)
507 /* The connection failed */
508 comms_error(c, "connecting to %s: %s", c->ident, strerror(err));
509 /* sets state_disconnected */
513 /* The connection succeeded */
514 c->state = state_connected;
515 byte_xasprintf(&r, "connected to %s", c->ident);
516 c->callbacks->report(c->u, r);
517 /* If this is a log client we expect to get a bunch of updates from the
518 * server straight away */
522 /* Authentication ************************************************************/
524 static void authbanner_opcallback(disorder_eclient *c,
525 struct operation *op) {
527 const unsigned char *nonce;
531 const char *protocol, *algorithm, *challenge;
533 D(("authbanner_opcallback"));
535 || !(rvec = split(c->line + 4, &nrvec, SPLIT_QUOTES, 0, 0))
537 /* Banner told us to go away, or was malformed. We cannot proceed. */
538 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
539 disorder_eclient_close(c);
543 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
544 disorder_eclient_close(c);
549 if(strcmp(protocol, "2")) {
550 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
551 disorder_eclient_close(c);
553 nonce = unhex(challenge, &nonce_len);
554 res = authhash(nonce, nonce_len, config->password, algorithm);
556 protocol_error(c, op, c->rc, "%s: unknown authentication algorithm '%s'",
557 c->ident, algorithm);
558 disorder_eclient_close(c);
561 stash_command(c, 1/*queuejump*/, authuser_opcallback, 0/*completed*/, 0/*v*/,
562 "user", quoteutf8(config->username), quoteutf8(res),
566 static void authuser_opcallback(disorder_eclient *c,
567 struct operation *op) {
570 D(("authuser_opcallback"));
571 if(c->rc / 100 != 2) {
572 /* Wrong password or something. We cannot proceed. */
573 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
574 disorder_eclient_close(c);
577 /* OK, we're authenticated now. */
578 c->authenticated = 1;
579 byte_xasprintf(&r, "authenticated with %s", c->ident);
580 c->callbacks->report(c->u, r);
581 if(c->log_callbacks && !(c->ops && c->ops->opcallback == log_opcallback))
582 /* We are a log client, switch to logging mode */
583 stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, c->log_v,
587 /* Output ********************************************************************/
589 /* Chop N bytes off the front of a dynstr */
590 static void consume(struct dynstr *d, int n) {
591 D(("consume %d", n));
592 assert(d->nvec >= n);
593 memmove(d->vec, d->vec + n, d->nvec - n);
597 /* Write some bytes */
598 static void put(disorder_eclient *c, const char *s, size_t n) {
599 D(("put %d %.*s", c->fd, (int)n, s));
600 dynstr_append_bytes(&c->output, s, n);
603 /* Called when we can write to our FD, or at any other time */
604 static void send_output(disorder_eclient *c) {
607 D(("send_output %d bytes pending", c->output.nvec));
608 if(c->state > state_connecting && c->output.nvec) {
609 n = write(c->fd, c->output.vec, c->output.nvec);
616 comms_error(c, "writing to %s: %s", c->ident, strerror(errno));
620 consume(&c->output, n);
624 /* Input *********************************************************************/
626 /* Called when c->fd might be readable, or at any other time */
627 static void read_input(disorder_eclient *c) {
632 D(("read_input in state %s", states[c->state]));
633 if(c->state <= state_connected) return; /* ignore bogus calls */
634 /* read some more input */
635 n = read(c->fd, buffer, sizeof buffer);
642 comms_error(c, "reading from %s: %s", c->ident, strerror(errno));
645 return; /* no new input to process */
647 D(("read %d bytes: [%.*s]", n, n, buffer));
648 dynstr_append_bytes(&c->input, buffer, n);
651 /* might have more than one line to process */
652 while(c->state > state_connecting
653 && (nl = memchr(c->input.vec, '\n', c->input.nvec))) {
654 process_line(c, xstrndup(c->input.vec, nl - c->input.vec));
655 /* we might have disconnected along the way, which zogs the input buffer */
656 if(c->state > state_connecting)
657 consume(&c->input, (nl - c->input.vec) + 1);
660 comms_error(c, "reading from %s: server disconnected", c->ident);
661 c->authenticated = 0;
665 /* called with a line that has just been read */
666 static void process_line(disorder_eclient *c, char *line) {
667 D(("process_line %d [%s]", c->fd, line));
669 case state_cmdresponse:
670 /* This is the first line of a response */
671 if(!(line[0] >= '0' && line[0] <= '9'
672 && line[1] >= '0' && line[1] <= '9'
673 && line[2] >= '0' && line[2] <= '9'
675 fatal(0, "invalid response from server: %s", line);
676 c->rc = (line[0] * 10 + line[1]) * 10 + line[2] - 111 * '0';
680 /* We need to collect the body. */
681 c->state = state_body;
682 vector_init(&c->vec);
685 assert(c->log_callbacks != 0);
686 if(c->log_callbacks->connected)
687 c->log_callbacks->connected(c->log_v);
688 c->state = state_log;
691 /* We've got the whole response. Go into the idle state so the state
692 * machine knows we're done and then call the operation callback. */
698 if(strcmp(line, ".")) {
699 /* A line from the body */
700 vector_append(&c->vec, line + (line[0] == '.'));
702 /* End of the body. */
703 vector_terminate(&c->vec);
708 if(strcmp(line, ".")) {
709 logline(c, line + (line[0] == '.'));
714 assert(!"wrong state for location");
719 /* Called when an operation completes */
720 static void complete(disorder_eclient *c) {
721 struct operation *op;
724 /* Pop the operation off the queue */
727 if(c->opstail == &op->next)
728 c->opstail = &c->ops;
729 /* If we've pipelined a command ahead then we go straight to cmdresponser.
730 * Otherwise we go to idle, which will arrange further sends. */
731 c->state = c->ops && c->ops->sent ? state_cmdresponse : state_idle;
732 op->opcallback(c, op);
733 /* Note that we always call the opcallback even on error, though command
734 * opcallbacks generally always do the same error handling, i.e. just call
735 * protocol_error(). It's the auth* opcallbacks that have different
739 /* Operation setup ***********************************************************/
741 static void stash_command_vector(disorder_eclient *c,
743 operation_callback *opcallback,
748 struct operation *op = xmalloc(sizeof *op);
754 for(n = 0; n < ncmd; ++n) {
756 dynstr_append(&d, ' ');
757 dynstr_append_string(&d, quoteutf8(cmd[n]));
759 dynstr_append(&d, '\n');
760 dynstr_terminate(&d);
763 op->cmd = 0; /* usually, awaiting challenge */
764 op->opcallback = opcallback;
765 op->completed = completed;
769 assert(op->sent == 0);
771 /* Authentication operations jump the queue of useful commands */
774 if(c->opstail == &c->ops)
775 c->opstail = &op->next;
776 for(op = c->ops; op; op = op->next)
780 c->opstail = &op->next;
784 static void vstash_command(disorder_eclient *c,
786 operation_callback *opcallback,
789 const char *cmd, va_list ap) {
793 D(("vstash_command %s", cmd ? cmd : "NULL"));
796 vector_append(&vec, (char *)cmd);
797 while((arg = va_arg(ap, char *)))
798 vector_append(&vec, arg);
799 stash_command_vector(c, queuejump, opcallback, completed, v,
802 stash_command_vector(c, queuejump, opcallback, completed, v, 0, 0);
805 static void stash_command(disorder_eclient *c,
807 operation_callback *opcallback,
815 vstash_command(c, queuejump, opcallback, completed, v, cmd, ap);
819 /* Command support ***********************************************************/
821 /* for commands with a quoted string response */
822 static void string_response_opcallback(disorder_eclient *c,
823 struct operation *op) {
824 D(("string_response_callback"));
825 if(c->rc / 100 == 2) {
827 char **rr = split(c->line + 4, 0, SPLIT_QUOTES, 0, 0);
830 ((disorder_eclient_string_response *)op->completed)(op->v, *rr);
832 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
835 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
838 /* for commands with a simple integer response */
839 static void integer_response_opcallback(disorder_eclient *c,
840 struct operation *op) {
841 D(("string_response_callback"));
842 if(c->rc / 100 == 2) {
844 ((disorder_eclient_integer_response *)op->completed)
845 (op->v, strtol(c->line + 4, 0, 10));
847 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
850 /* for commands with no response */
851 static void no_response_opcallback(disorder_eclient *c,
852 struct operation *op) {
853 D(("no_response_callback"));
854 if(c->rc / 100 == 2) {
856 ((disorder_eclient_no_response *)op->completed)(op->v);
858 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
861 /* error callback for queue_unmarshall */
862 static void eclient_queue_error(const char *msg,
864 struct operation *op = u;
866 protocol_error(op->client, op, -1, "error parsing queue entry: %s", msg);
869 /* for commands that expect a queue dump */
870 static void queue_response_opcallback(disorder_eclient *c,
871 struct operation *op) {
873 struct queue_entry *q, *qh = 0, **qtail = &qh, *qlast = 0;
875 D(("queue_response_callback"));
876 if(c->rc / 100 == 2) {
877 /* parse the queue */
878 for(n = 0; n < c->vec.nvec; ++n) {
879 q = xmalloc(sizeof *q);
880 D(("queue_unmarshall %s", c->vec.vec[n]));
881 if(!queue_unmarshall(q, c->vec.vec[n], eclient_queue_error, op)) {
889 ((disorder_eclient_queue_response *)op->completed)(op->v, qh);
891 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
895 static void playing_response_opcallback(disorder_eclient *c,
896 struct operation *op) {
897 struct queue_entry *q;
899 D(("playing_response_callback"));
900 if(c->rc / 100 == 2) {
903 if(queue_unmarshall(q = xmalloc(sizeof *q), c->line + 4,
904 eclient_queue_error, c))
911 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
915 ((disorder_eclient_queue_response *)op->completed)(op->v, q);
917 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
920 /* for commands that expect a list of some sort */
921 static void list_response_opcallback(disorder_eclient *c,
922 struct operation *op) {
923 D(("list_response_callback"));
924 if(c->rc / 100 == 2) {
926 ((disorder_eclient_list_response *)op->completed)(op->v,
930 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
934 static void volume_response_opcallback(disorder_eclient *c,
935 struct operation *op) {
938 D(("volume_response_callback"));
939 if(c->rc / 100 == 2) {
941 if(sscanf(c->line + 4, "%d %d", &l, &r) != 2 || l < 0 || r < 0)
942 protocol_error(c, op, -1, "%s: invalid volume response: %s",
945 ((disorder_eclient_volume_response *)op->completed)(op->v, l, r);
948 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
951 static int simple(disorder_eclient *c,
952 operation_callback *opcallback,
955 const char *cmd, ...) {
959 vstash_command(c, 0/*queuejump*/, opcallback, completed, v, cmd, ap);
961 /* Give the state machine a kick, since we might be in state_idle */
962 disorder_eclient_polled(c, 0);
966 /* Commands ******************************************************************/
968 int disorder_eclient_version(disorder_eclient *c,
969 disorder_eclient_string_response *completed,
971 return simple(c, string_response_opcallback, (void (*)())completed, v,
972 "version", (char *)0);
975 int disorder_eclient_namepart(disorder_eclient *c,
976 disorder_eclient_string_response *completed,
981 return simple(c, string_response_opcallback, (void (*)())completed, v,
982 "part", track, context, part, (char *)0);
985 int disorder_eclient_play(disorder_eclient *c,
987 disorder_eclient_no_response *completed,
989 return simple(c, no_response_opcallback, (void (*)())completed, v,
990 "play", track, (char *)0);
993 int disorder_eclient_pause(disorder_eclient *c,
994 disorder_eclient_no_response *completed,
996 return simple(c, no_response_opcallback, (void (*)())completed, v,
1000 int disorder_eclient_resume(disorder_eclient *c,
1001 disorder_eclient_no_response *completed,
1003 return simple(c, no_response_opcallback, (void (*)())completed, v,
1004 "resume", (char *)0);
1007 int disorder_eclient_scratch(disorder_eclient *c,
1009 disorder_eclient_no_response *completed,
1011 return simple(c, no_response_opcallback, (void (*)())completed, v,
1012 "scratch", id, (char *)0);
1015 int disorder_eclient_scratch_playing(disorder_eclient *c,
1016 disorder_eclient_no_response *completed,
1018 return disorder_eclient_scratch(c, 0, completed, v);
1021 int disorder_eclient_remove(disorder_eclient *c,
1023 disorder_eclient_no_response *completed,
1025 return simple(c, no_response_opcallback, (void (*)())completed, v,
1026 "remove", id, (char *)0);
1029 int disorder_eclient_moveafter(disorder_eclient *c,
1033 disorder_eclient_no_response *completed,
1039 vector_append(&vec, (char *)"moveafter");
1040 vector_append(&vec, (char *)target);
1041 for(n = 0; n < nids; ++n)
1042 vector_append(&vec, (char *)ids[n]);
1043 stash_command_vector(c, 0/*queuejump*/, no_response_opcallback, completed, v,
1045 disorder_eclient_polled(c, 0);
1049 int disorder_eclient_recent(disorder_eclient *c,
1050 disorder_eclient_queue_response *completed,
1052 return simple(c, queue_response_opcallback, (void (*)())completed, v,
1053 "recent", (char *)0);
1056 int disorder_eclient_queue(disorder_eclient *c,
1057 disorder_eclient_queue_response *completed,
1059 return simple(c, queue_response_opcallback, (void (*)())completed, v,
1060 "queue", (char *)0);
1063 int disorder_eclient_files(disorder_eclient *c,
1064 disorder_eclient_list_response *completed,
1068 return simple(c, list_response_opcallback, (void (*)())completed, v,
1069 "files", dir, re, (char *)0);
1072 int disorder_eclient_dirs(disorder_eclient *c,
1073 disorder_eclient_list_response *completed,
1077 return simple(c, list_response_opcallback, (void (*)())completed, v,
1078 "dirs", dir, re, (char *)0);
1081 int disorder_eclient_playing(disorder_eclient *c,
1082 disorder_eclient_queue_response *completed,
1084 return simple(c, playing_response_opcallback, (void (*)())completed, v,
1085 "playing", (char *)0);
1088 int disorder_eclient_length(disorder_eclient *c,
1089 disorder_eclient_integer_response *completed,
1092 return simple(c, integer_response_opcallback, (void (*)())completed, v,
1093 "length", track, (char *)0);
1096 int disorder_eclient_volume(disorder_eclient *c,
1097 disorder_eclient_volume_response *completed,
1100 char sl[64], sr[64];
1102 if(l < 0 && r < 0) {
1103 return simple(c, volume_response_opcallback, (void (*)())completed, v,
1104 "volume", (char *)0);
1105 } else if(l >= 0 && r >= 0) {
1108 byte_snprintf(sl, sizeof sl, "%d", l);
1109 byte_snprintf(sr, sizeof sr, "%d", r);
1110 return simple(c, volume_response_opcallback, (void (*)())completed, v,
1111 "volume", sl, sr, (char *)0);
1113 assert(!"invalid arguments to disorder_eclient_volume");
1114 return -1; /* gcc is being dim */
1118 int disorder_eclient_enable(disorder_eclient *c,
1119 disorder_eclient_no_response *completed,
1121 return simple(c, no_response_opcallback, (void (*)())completed, v,
1122 "enable", (char *)0);
1125 int disorder_eclient_disable(disorder_eclient *c,
1126 disorder_eclient_no_response *completed,
1128 return simple(c, no_response_opcallback, (void (*)())completed, v,
1129 "disable", (char *)0);
1132 int disorder_eclient_random_enable(disorder_eclient *c,
1133 disorder_eclient_no_response *completed,
1135 return simple(c, no_response_opcallback, (void (*)())completed, v,
1136 "random-enable", (char *)0);
1139 int disorder_eclient_random_disable(disorder_eclient *c,
1140 disorder_eclient_no_response *completed,
1142 return simple(c, no_response_opcallback, (void (*)())completed, v,
1143 "random-disable", (char *)0);
1146 int disorder_eclient_get(disorder_eclient *c,
1147 disorder_eclient_string_response *completed,
1148 const char *track, const char *pref,
1150 return simple(c, string_response_opcallback, (void (*)())completed, v,
1151 "get", track, pref, (char *)0);
1154 int disorder_eclient_set(disorder_eclient *c,
1155 disorder_eclient_no_response *completed,
1156 const char *track, const char *pref,
1159 return simple(c, no_response_opcallback, (void (*)())completed, v,
1160 "set", track, pref, value, (char *)0);
1163 int disorder_eclient_unset(disorder_eclient *c,
1164 disorder_eclient_no_response *completed,
1165 const char *track, const char *pref,
1167 return simple(c, no_response_opcallback, (void (*)())completed, v,
1168 "unset", track, pref, (char *)0);
1171 int disorder_eclient_resolve(disorder_eclient *c,
1172 disorder_eclient_string_response *completed,
1175 return simple(c, string_response_opcallback, (void (*)())completed, v,
1176 "resolve", track, (char *)0);
1179 int disorder_eclient_search(disorder_eclient *c,
1180 disorder_eclient_list_response *completed,
1183 if(!split(terms, 0, SPLIT_QUOTES, 0, 0)) return -1;
1184 return simple(c, list_response_opcallback, (void (*)())completed, v,
1185 "search", terms, (char *)0);
1188 int disorder_eclient_nop(disorder_eclient *c,
1189 disorder_eclient_no_response *completed,
1191 return simple(c, no_response_opcallback, (void (*)())completed, v,
1195 /** @brief Get the last @p max added tracks
1197 * @param completed Called with list
1198 * @param max Number of tracks to get, 0 for all
1199 * @param v Passed to @p completed
1201 * The first track in the list is the most recently added.
1203 int disorder_eclient_new_tracks(disorder_eclient *c,
1204 disorder_eclient_list_response *completed,
1209 sprintf(limit, "%d", max);
1210 return simple(c, list_response_opcallback, (void (*)())completed, v,
1211 "new", limit, (char *)0);
1214 static void rtp_response_opcallback(disorder_eclient *c,
1215 struct operation *op) {
1216 D(("rtp_response_opcallback"));
1217 if(c->rc / 100 == 2) {
1220 char **vec = split(c->line + 4, &nvec, SPLIT_QUOTES, 0, 0);
1222 ((disorder_eclient_list_response *)op->completed)(op->v, nvec, vec);
1225 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
1228 /** @brief Determine the RTP target address
1230 * @param completed Called with address details
1231 * @param v Passed to @p completed
1233 * The address details will be two elements, the first being the hostname and
1234 * the second the service (port).
1236 int disorder_eclient_rtp_address(disorder_eclient *c,
1237 disorder_eclient_list_response *completed,
1239 return simple(c, rtp_response_opcallback, (void (*)())completed, v,
1240 "rtp-address", (char *)0);
1243 /* Log clients ***************************************************************/
1245 /** @brief Monitor the server log
1247 * @param callbacks Functions to call when anything happens
1248 * @param v Passed to @p callbacks functions
1250 * Once a client is being used for logging it cannot be used for anything else.
1251 * There is magic in authuser_opcallback() to re-submit the @c log command
1252 * after reconnection.
1254 * NB that the @c state callback may be called from within this function,
1255 * i.e. not solely later on from the event loop callback.
1257 int disorder_eclient_log(disorder_eclient *c,
1258 const disorder_eclient_log_callbacks *callbacks,
1260 if(c->log_callbacks) return -1;
1261 c->log_callbacks = callbacks;
1263 /* Repoort initial state */
1264 if(c->log_callbacks->state)
1265 c->log_callbacks->state(c->log_v, c->statebits);
1266 stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, v,
1271 /* If we get here we've stopped being a log client */
1272 static void log_opcallback(disorder_eclient *c,
1273 struct operation attribute((unused)) *op) {
1274 D(("log_opcallback"));
1275 c->log_callbacks = 0;
1279 /* error callback for log line parsing */
1280 static void logline_error(const char *msg, void *u) {
1281 disorder_eclient *c = u;
1282 protocol_error(c, c->ops, -1, "error parsing log line: %s", msg);
1285 /* process a single log line */
1286 static void logline(disorder_eclient *c, const char *line) {
1291 D(("logline [%s]", line));
1292 vec = split(line, &nvec, SPLIT_QUOTES, logline_error, c);
1293 if(nvec < 2) return; /* probably an error, already
1295 if(sscanf(vec[0], "%"SCNxMAX, &when) != 1) {
1296 /* probably the wrong side of a format change */
1297 protocol_error(c, c->ops, -1, "invalid log timestamp '%s'", vec[0]);
1300 /* TODO: do something with the time */
1301 n = TABLE_FIND(logentry_handlers, struct logentry_handler, name, vec[1]);
1302 if(n < 0) return; /* probably a future command */
1305 if(nvec < logentry_handlers[n].min || nvec > logentry_handlers[n].max)
1307 logentry_handlers[n].handler(c, nvec, vec);
1310 static void logentry_completed(disorder_eclient *c,
1311 int attribute((unused)) nvec, char **vec) {
1312 if(!c->log_callbacks->completed) return;
1313 c->statebits &= ~DISORDER_PLAYING;
1314 c->log_callbacks->completed(c->log_v, vec[0]);
1315 if(c->log_callbacks->state)
1316 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1319 static void logentry_failed(disorder_eclient *c,
1320 int attribute((unused)) nvec, char **vec) {
1321 if(!c->log_callbacks->failed)return;
1322 c->statebits &= ~DISORDER_PLAYING;
1323 c->log_callbacks->failed(c->log_v, vec[0], vec[1]);
1324 if(c->log_callbacks->state)
1325 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1328 static void logentry_moved(disorder_eclient *c,
1329 int attribute((unused)) nvec, char **vec) {
1330 if(!c->log_callbacks->moved) return;
1331 c->log_callbacks->moved(c->log_v, vec[0]);
1334 static void logentry_playing(disorder_eclient *c,
1335 int attribute((unused)) nvec, char **vec) {
1336 if(!c->log_callbacks->playing) return;
1337 c->statebits |= DISORDER_PLAYING;
1338 c->log_callbacks->playing(c->log_v, vec[0], vec[1]);
1339 if(c->log_callbacks->state)
1340 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1343 static void logentry_queue(disorder_eclient *c,
1344 int attribute((unused)) nvec, char **vec) {
1345 struct queue_entry *q;
1347 if(!c->log_callbacks->completed) return;
1348 q = xmalloc(sizeof *q);
1349 if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1351 c->log_callbacks->queue(c->log_v, q);
1354 static void logentry_recent_added(disorder_eclient *c,
1355 int attribute((unused)) nvec, char **vec) {
1356 struct queue_entry *q;
1358 if(!c->log_callbacks->recent_added) return;
1359 q = xmalloc(sizeof *q);
1360 if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1362 c->log_callbacks->recent_added(c->log_v, q);
1365 static void logentry_recent_removed(disorder_eclient *c,
1366 int attribute((unused)) nvec, char **vec) {
1367 if(!c->log_callbacks->recent_removed) return;
1368 c->log_callbacks->recent_removed(c->log_v, vec[0]);
1371 static void logentry_removed(disorder_eclient *c,
1372 int attribute((unused)) nvec, char **vec) {
1373 if(!c->log_callbacks->removed) return;
1374 c->log_callbacks->removed(c->log_v, vec[0], vec[1]);
1377 static void logentry_rescanned(disorder_eclient *c,
1378 int attribute((unused)) nvec,
1379 char attribute((unused)) **vec) {
1380 if(!c->log_callbacks->rescanned) return;
1381 c->log_callbacks->rescanned(c->log_v);
1384 static void logentry_scratched(disorder_eclient *c,
1385 int attribute((unused)) nvec, char **vec) {
1386 if(!c->log_callbacks->scratched) return;
1387 c->statebits &= ~DISORDER_PLAYING;
1388 c->log_callbacks->scratched(c->log_v, vec[0], vec[1]);
1389 if(c->log_callbacks->state)
1390 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1393 static const struct {
1396 const char *disable;
1397 } statestrings[] = {
1398 { DISORDER_PLAYING_ENABLED, "enable_play", "disable_play" },
1399 { DISORDER_RANDOM_ENABLED, "enable_random", "disable_random" },
1400 { DISORDER_TRACK_PAUSED, "pause", "resume" },
1401 { DISORDER_PLAYING, "playing", "completed" },
1402 { DISORDER_PLAYING, 0, "scratched" },
1403 { DISORDER_PLAYING, 0, "failed" },
1405 #define NSTATES (int)(sizeof statestrings / sizeof *statestrings)
1407 static void logentry_state(disorder_eclient *c,
1408 int attribute((unused)) nvec, char **vec) {
1411 for(n = 0; n < NSTATES; ++n)
1412 if(statestrings[n].enable && !strcmp(vec[0], statestrings[n].enable)) {
1413 c->statebits |= statestrings[n].bit;
1415 } else if(statestrings[n].disable && !strcmp(vec[0], statestrings[n].disable)) {
1416 c->statebits &= ~statestrings[n].bit;
1419 if(!c->log_callbacks->state) return;
1420 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1423 static void logentry_volume(disorder_eclient *c,
1424 int attribute((unused)) nvec, char **vec) {
1427 if(!c->log_callbacks->volume) return;
1428 if(xstrtol(&l, vec[0], 0, 10)
1429 || xstrtol(&r, vec[1], 0, 10)
1430 || l < 0 || l > INT_MAX
1431 || r < 0 || r > INT_MAX)
1433 c->log_callbacks->volume(c->log_v, (int)l, (int)r);
1436 /** @brief Convert @p statebits to a string */
1437 char *disorder_eclient_interpret_state(unsigned long statebits) {
1441 static const struct {
1445 { DISORDER_PLAYING_ENABLED, "playing_enabled" },
1446 { DISORDER_RANDOM_ENABLED, "random_enabled" },
1447 { DISORDER_TRACK_PAUSED, "track_paused" },
1448 { DISORDER_PLAYING, "playing" },
1449 { DISORDER_CONNECTED, "connected" },
1451 #define NBITS (sizeof bits / sizeof *bits)
1455 dynstr_append(d, '0');
1456 for(n = 0; n < NBITS; ++n)
1457 if(statebits & bits[n].bit) {
1459 dynstr_append(d, '|');
1460 dynstr_append_string(d, bits[n].name);
1461 statebits ^= bits[n].bit;
1467 dynstr_append(d, '|');
1468 sprintf(s, "%#lx", statebits);
1469 dynstr_append_string(d, s);
1471 dynstr_terminate(d);
1480 indent-tabs-mode:nil