2 * This file is part of DisOrder.
3 * Copyright (C) 2006-2008 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
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <netinet/in.h>
39 #include "configuration.h"
46 #include "inputline.h"
53 #include "client-common.h"
55 /* TODO: more commands */
57 /** @brief How often to send data to the server when receiving logs */
58 #define LOG_PROD_INTERVAL 10
60 /* Types *********************************************************************/
62 /** @brief Client state */
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 */
73 /** @brief Names for @ref client_state */
74 static const char *const states[] = {
84 struct operation; /* forward decl */
86 /** @brief Type of an operation callback */
87 typedef void operation_callback(disorder_eclient *c, struct operation *op);
89 /** @brief A pending operation.
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. */
95 struct operation *next; /**< @brief next operation */
96 char *cmd; /**< @brief command to send or 0 */
97 operation_callback *opcallback; /**< @brief internal completion callback */
98 void (*completed)(); /**< @brief user completion callback or 0 */
99 void *v; /**< @brief data for COMPLETED */
100 disorder_eclient *client; /**< @brief owning client */
102 /** @brief true if sent to server
104 * This is cleared by disorder_eclient_close(), forcing all queued
105 * commands to be transparently resent.
110 /** @brief Client structure */
111 struct disorder_eclient {
113 int fd; /**< @brief connection to server */
114 enum client_state state; /**< @brief current state */
115 int authenticated; /**< @brief true when authenicated */
116 struct dynstr output; /**< @brief output buffer */
117 struct dynstr input; /**< @brief input buffer */
118 int eof; /**< @brief input buffer is at EOF */
119 const disorder_eclient_callbacks *callbacks; /**< @brief error callbacks */
120 void *u; /**< @brief user data */
121 struct operation *ops; /**< @brief queue of operations */
122 struct operation **opstail; /**< @brief queue tail */
123 /* accumulated response */
124 int rc; /**< @brief response code */
125 char *line; /**< @brief complete line */
126 struct vector vec; /**< @brief body */
128 const disorder_eclient_log_callbacks *log_callbacks;
129 /**< @brief log callbacks
131 * Once disorder_eclient_log() has been issued this is always set. When we
132 * re-connect it is checked to re-issue the log command.
134 void *log_v; /**< @brief user data */
135 unsigned long statebits; /**< @brief latest state */
138 /**< @brief last time we sent a prod
140 * When we are receiving log data we send a "prod" byte to the server from
141 * time to time so that we detect broken connections reasonably quickly. The
142 * server just ignores these bytes.
145 /** @brief Protocol version */
149 /* Forward declarations ******************************************************/
151 static int start_connect(disorder_eclient *c);
152 static void process_line(disorder_eclient *c, char *line);
153 static void maybe_connected(disorder_eclient *c);
154 static void authbanner_opcallback(disorder_eclient *c,
155 struct operation *op);
156 static void authuser_opcallback(disorder_eclient *c,
157 struct operation *op);
158 static void complete(disorder_eclient *c);
159 static void send_output(disorder_eclient *c);
160 static void put(disorder_eclient *c, const char *s, size_t n);
161 static void read_input(disorder_eclient *c);
162 static void stash_command(disorder_eclient *c,
164 operation_callback *opcallback,
169 static void log_opcallback(disorder_eclient *c, struct operation *op);
170 static void logline(disorder_eclient *c, const char *line);
171 static void logentry_completed(disorder_eclient *c, int nvec, char **vec);
172 static void logentry_failed(disorder_eclient *c, int nvec, char **vec);
173 static void logentry_moved(disorder_eclient *c, int nvec, char **vec);
174 static void logentry_playing(disorder_eclient *c, int nvec, char **vec);
175 static void logentry_queue(disorder_eclient *c, int nvec, char **vec);
176 static void logentry_recent_added(disorder_eclient *c, int nvec, char **vec);
177 static void logentry_recent_removed(disorder_eclient *c, int nvec, char **vec);
178 static void logentry_removed(disorder_eclient *c, int nvec, char **vec);
179 static void logentry_scratched(disorder_eclient *c, int nvec, char **vec);
180 static void logentry_state(disorder_eclient *c, int nvec, char **vec);
181 static void logentry_volume(disorder_eclient *c, int nvec, char **vec);
182 static void logentry_rescanned(disorder_eclient *c, int nvec, char **vec);
184 /* Tables ********************************************************************/
186 /** @brief One possible log entry */
187 struct logentry_handler {
188 const char *name; /**< @brief Entry name */
189 int min; /**< @brief Minimum arguments */
190 int max; /**< @brief Maximum arguments */
191 void (*handler)(disorder_eclient *c,
193 char **vec); /**< @brief Handler function */
196 /** @brief Table for parsing log entries */
197 static const struct logentry_handler logentry_handlers[] = {
198 #define LE(X, MIN, MAX) { #X, MIN, MAX, logentry_##X }
203 LE(queue, 2, INT_MAX),
204 LE(recent_added, 2, INT_MAX),
205 LE(recent_removed, 1, 1),
213 /* Setup and teardown ********************************************************/
215 /** @brief Create a new client
217 * Does NOT connect the client - connections are made (and re-made) on demand.
219 disorder_eclient *disorder_eclient_new(const disorder_eclient_callbacks *cb,
221 disorder_eclient *c = xmalloc(sizeof *c);
222 D(("disorder_eclient_new"));
226 c->opstail = &c->ops;
227 vector_init(&c->vec);
228 dynstr_init(&c->input);
229 dynstr_init(&c->output);
233 /** @brief Disconnect a client
234 * @param c Client to disconnect
236 * NB that this routine just disconnnects the TCP connection. It does not
237 * destroy the client! If you continue to use it then it will attempt to
240 void disorder_eclient_close(disorder_eclient *c) {
241 struct operation *op;
243 D(("disorder_eclient_close"));
245 D(("disorder_eclient_close closing fd %d", c->fd));
246 c->callbacks->poll(c->u, c, c->fd, 0);
249 c->state = state_disconnected;
255 c->authenticated = 0;
256 /* We'll need to resend all operations */
257 for(op = c->ops; op; op = op->next)
259 /* Drop our use a hint that we're disconnected */
260 if(c->log_callbacks && c->log_callbacks->state)
261 c->log_callbacks->state(c->log_v, c->statebits);
264 /** @brief Return current state */
265 unsigned long disorder_eclient_state(const disorder_eclient *c) {
266 return c->statebits | (c->state > state_connected ? DISORDER_CONNECTED : 0);
269 /* Error reporting ***********************************************************/
271 /** @brief called when a connection error occurs
273 * After this called we will be disconnected (by disorder_eclient_close()),
274 * so there will be a reconnection before any commands can be sent.
276 static int comms_error(disorder_eclient *c, const char *fmt, ...) {
282 byte_xvasprintf(&s, fmt, ap);
284 disorder_eclient_close(c);
285 c->callbacks->comms_error(c->u, s);
289 /** @brief called when the server reports an error */
290 static int protocol_error(disorder_eclient *c, struct operation *op,
291 int code, const char *fmt, ...) {
295 D(("protocol_error"));
297 byte_xvasprintf(&s, fmt, ap);
299 c->callbacks->protocol_error(c->u, op->v, code, s);
303 /* State machine *************************************************************/
305 /** @brief Called when there's something to do
307 * @param mode bitmap of @ref DISORDER_POLL_READ and/or @ref DISORDER_POLL_WRITE.
309 * This should be called from by your code when the file descriptor is readable
310 * or writable (as requested by the @c poll callback, see @ref
311 * disorder_eclient_callbacks) and in any case from time to time (with @p mode
312 * = 0) to allow for retries to work.
314 void disorder_eclient_polled(disorder_eclient *c, unsigned mode) {
315 struct operation *op;
318 D(("disorder_eclient_polled fd=%d state=%s mode=[%s %s]",
319 c->fd, states[c->state],
320 mode & DISORDER_POLL_READ ? "READ" : "",
321 mode & DISORDER_POLL_WRITE ? "WRITE" : ""));
322 /* The pattern here is to check each possible state in turn and try to
323 * advance (though on error we might go back). If we advance we leave open
324 * the possibility of falling through to the next state, but we set the mode
325 * bits to 0, to avoid false positives (which matter more in some cases than
328 if(c->state == state_disconnected) {
329 D(("state_disconnected"));
330 /* If there is no password yet then we cannot connect */
331 if(!config->password) {
332 comms_error(c, "no password is configured");
336 /* might now be state_disconnected (on error), state_connecting (slow
337 * connect) or state_connected (fast connect). If state_disconnected then
338 * we just rely on a periodic callback from the event loop sometime. */
342 if(c->state == state_connecting && mode) {
343 D(("state_connecting"));
345 /* Might be state_disconnected (on error) or state_connected (on success).
346 * In the former case we rely on the event loop for a periodic callback to
351 if(c->state == state_connected) {
352 D(("state_connected"));
353 /* We just connected. Initiate the authentication protocol. */
354 stash_command(c, 1/*queuejump*/, authbanner_opcallback,
355 0/*completed*/, 0/*v*/, 0/*cmd*/);
356 /* We never stay is state_connected very long. We could in principle jump
357 * straight to state_cmdresponse since there's actually no command to
358 * send, but that would arguably be cheating. */
359 c->state = state_idle;
362 if(c->state == state_idle) {
364 /* We are connected, and have finished any command we set off, look for
368 if(c->authenticated) {
369 /* Transmit all unsent operations */
370 for(op = c->ops; op; op = op->next) {
372 put(c, op->cmd, strlen(op->cmd));
377 /* Just send the head operation */
378 if(c->ops->cmd && !c->ops->sent) {
379 put(c, c->ops->cmd, strlen(c->ops->cmd));
383 /* Awaiting response for the operation at the head of the list */
384 c->state = state_cmdresponse;
387 c->callbacks->report(c->u, 0);
390 /* Queue up a byte to send */
391 if(c->state == state_log
392 && c->output.nvec == 0
393 && time(&now) - c->last_prod > LOG_PROD_INTERVAL) {
398 if(c->state == state_cmdresponse
399 || c->state == state_body
400 || c->state == state_log) {
401 D(("state_%s", states[c->state]));
402 /* We are awaiting a response */
403 if(mode & DISORDER_POLL_WRITE) send_output(c);
404 if(mode & DISORDER_POLL_READ) read_input(c);
405 /* There are a couple of reasons we might want to re-enter the state
406 * machine from the top. state_idle is obvious: there may be further
407 * commands to process. Re-entering on state_disconnected means that we
408 * immediately retry connection if a comms error occurs during a command.
409 * This is different to the case where a connection fails, where we await a
410 * spontaneous call to initiate the retry. */
412 case state_disconnected: /* lost connection */
413 case state_idle: /* completed a command */
415 disorder_eclient_polled(c, 0);
422 /* Figure out what to set the mode to */
424 case state_disconnected:
425 D(("state_disconnected (2)"));
426 /* Probably an error occurred. Await a retry. */
429 case state_connecting:
430 D(("state_connecting (2)"));
431 /* Waiting for connect to complete */
432 mode = DISORDER_POLL_READ|DISORDER_POLL_WRITE;
434 case state_connected:
435 D(("state_connected (2)"));
436 assert(!"should never be in state_connected here");
439 D(("state_idle (2)"));
440 /* Connected but nothing to do. */
443 case state_cmdresponse:
446 D(("state_%s (2)", states[c->state]));
447 /* Gathering a response. Wait for input. */
448 mode = DISORDER_POLL_READ;
449 /* Flush any pending output. */
450 if(c->output.nvec) mode |= DISORDER_POLL_WRITE;
453 D(("fd=%d new mode [%s %s]",
455 mode & DISORDER_POLL_READ ? "READ" : "",
456 mode & DISORDER_POLL_WRITE ? "WRITE" : ""));
457 if(c->fd != -1) c->callbacks->poll(c->u, c, c->fd, mode);
460 /** @brief Called to start connecting */
461 static int start_connect(disorder_eclient *c) {
465 D(("start_connect"));
466 if((len = find_server(&sa, &c->ident)) == (socklen_t)-1)
467 return comms_error(c, "cannot look up server"); /* TODO better error */
472 if((c->fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
473 return comms_error(c, "socket: %s", strerror(errno));
477 if(connect(c->fd, sa, len) < 0) {
481 c->state = state_connecting;
482 /* We are called from _polled so the state machine will get to do its
486 /* Signal the error to the caller. */
487 return comms_error(c, "connecting to %s: %s", c->ident, strerror(errno));
490 c->state = state_connected;
494 /** @brief Called when poll triggers while waiting for a connection */
495 static void maybe_connected(disorder_eclient *c) {
496 /* We either connected, or got an error. */
498 socklen_t len = sizeof err;
500 D(("maybe_connected"));
501 /* Work around over-enthusiastic error slippage */
502 if(getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0)
505 /* The connection failed */
506 comms_error(c, "connecting to %s: %s", c->ident, strerror(err));
507 /* sets state_disconnected */
511 /* The connection succeeded */
512 c->state = state_connected;
513 byte_xasprintf(&r, "connected to %s", c->ident);
514 c->callbacks->report(c->u, r);
515 /* If this is a log client we expect to get a bunch of updates from the
516 * server straight away */
520 /* Authentication ************************************************************/
522 /** @brief Called with the greeting from the server */
523 static void authbanner_opcallback(disorder_eclient *c,
524 struct operation *op) {
526 const unsigned char *nonce;
530 const char *protocol, *algorithm, *challenge;
532 D(("authbanner_opcallback"));
534 || !(rvec = split(c->line + 4, &nrvec, SPLIT_QUOTES, 0, 0))
536 /* Banner told us to go away, or was malformed. We cannot proceed. */
537 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
538 disorder_eclient_close(c);
558 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
559 disorder_eclient_close(c);
562 c->protocol = atoi(protocol);
563 if(c->protocol < 1 || c->protocol > 2) {
564 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
565 disorder_eclient_close(c);
568 nonce = unhex(challenge, &nonce_len);
569 res = authhash(nonce, nonce_len, config->password, algorithm);
571 protocol_error(c, op, c->rc, "%s: unknown authentication algorithm '%s'",
572 c->ident, algorithm);
573 disorder_eclient_close(c);
576 stash_command(c, 1/*queuejump*/, authuser_opcallback, 0/*completed*/, 0/*v*/,
577 "user", quoteutf8(config->username), quoteutf8(res),
581 /** @brief Called with the response to the @c user command */
582 static void authuser_opcallback(disorder_eclient *c,
583 struct operation *op) {
586 D(("authuser_opcallback"));
587 if(c->rc / 100 != 2) {
588 /* Wrong password or something. We cannot proceed. */
589 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
590 disorder_eclient_close(c);
593 /* OK, we're authenticated now. */
594 c->authenticated = 1;
595 byte_xasprintf(&r, "authenticated with %s", c->ident);
596 c->callbacks->report(c->u, r);
597 if(c->log_callbacks && !(c->ops && c->ops->opcallback == log_opcallback))
598 /* We are a log client, switch to logging mode */
599 stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, c->log_v,
603 /* Output ********************************************************************/
605 /* Chop N bytes off the front of a dynstr */
606 static void consume(struct dynstr *d, int n) {
607 D(("consume %d", n));
608 assert(d->nvec >= n);
609 memmove(d->vec, d->vec + n, d->nvec - n);
613 /* Write some bytes */
614 static void put(disorder_eclient *c, const char *s, size_t n) {
615 D(("put %d %.*s", c->fd, (int)n, s));
616 dynstr_append_bytes(&c->output, s, n);
619 /* Called when we can write to our FD, or at any other time */
620 static void send_output(disorder_eclient *c) {
623 D(("send_output %d bytes pending", c->output.nvec));
624 if(c->state > state_connecting && c->output.nvec) {
625 n = write(c->fd, c->output.vec, c->output.nvec);
632 comms_error(c, "writing to %s: %s", c->ident, strerror(errno));
636 consume(&c->output, n);
640 /* Input *********************************************************************/
642 /* Called when c->fd might be readable, or at any other time */
643 static void read_input(disorder_eclient *c) {
648 D(("read_input in state %s", states[c->state]));
649 if(c->state <= state_connected) return; /* ignore bogus calls */
650 /* read some more input */
651 n = read(c->fd, buffer, sizeof buffer);
658 comms_error(c, "reading from %s: %s", c->ident, strerror(errno));
661 return; /* no new input to process */
663 D(("read %d bytes: [%.*s]", n, n, buffer));
664 dynstr_append_bytes(&c->input, buffer, n);
667 /* might have more than one line to process */
668 while(c->state > state_connecting
669 && (nl = memchr(c->input.vec, '\n', c->input.nvec))) {
670 process_line(c, xstrndup(c->input.vec, nl - c->input.vec));
671 /* we might have disconnected along the way, which zogs the input buffer */
672 if(c->state > state_connecting)
673 consume(&c->input, (nl - c->input.vec) + 1);
676 comms_error(c, "reading from %s: server disconnected", c->ident);
677 c->authenticated = 0;
681 /* called with a line that has just been read */
682 static void process_line(disorder_eclient *c, char *line) {
683 D(("process_line %d [%s]", c->fd, line));
685 case state_cmdresponse:
686 /* This is the first line of a response */
687 if(!(line[0] >= '0' && line[0] <= '9'
688 && line[1] >= '0' && line[1] <= '9'
689 && line[2] >= '0' && line[2] <= '9'
691 fatal(0, "invalid response from server: %s", line);
692 c->rc = (line[0] * 10 + line[1]) * 10 + line[2] - 111 * '0';
696 /* We need to collect the body. */
697 c->state = state_body;
698 vector_init(&c->vec);
701 assert(c->log_callbacks != 0);
702 if(c->log_callbacks->connected)
703 c->log_callbacks->connected(c->log_v);
704 c->state = state_log;
707 /* We've got the whole response. Go into the idle state so the state
708 * machine knows we're done and then call the operation callback. */
714 if(strcmp(line, ".")) {
715 /* A line from the body */
716 vector_append(&c->vec, line + (line[0] == '.'));
718 /* End of the body. */
719 vector_terminate(&c->vec);
724 if(strcmp(line, ".")) {
725 logline(c, line + (line[0] == '.'));
730 assert(!"wrong state for location");
735 /* Called when an operation completes */
736 static void complete(disorder_eclient *c) {
737 struct operation *op;
740 /* Pop the operation off the queue */
743 if(c->opstail == &op->next)
744 c->opstail = &c->ops;
745 /* If we've pipelined a command ahead then we go straight to cmdresponser.
746 * Otherwise we go to idle, which will arrange further sends. */
747 c->state = c->ops && c->ops->sent ? state_cmdresponse : state_idle;
748 op->opcallback(c, op);
749 /* Note that we always call the opcallback even on error, though command
750 * opcallbacks generally always do the same error handling, i.e. just call
751 * protocol_error(). It's the auth* opcallbacks that have different
755 /* Operation setup ***********************************************************/
757 static void stash_command_vector(disorder_eclient *c,
759 operation_callback *opcallback,
764 struct operation *op = xmalloc(sizeof *op);
770 for(n = 0; n < ncmd; ++n) {
772 dynstr_append(&d, ' ');
773 dynstr_append_string(&d, quoteutf8(cmd[n]));
775 dynstr_append(&d, '\n');
776 dynstr_terminate(&d);
779 op->cmd = 0; /* usually, awaiting challenge */
780 op->opcallback = opcallback;
781 op->completed = completed;
785 assert(op->sent == 0);
787 /* Authentication operations jump the queue of useful commands */
790 if(c->opstail == &c->ops)
791 c->opstail = &op->next;
792 for(op = c->ops; op; op = op->next)
796 c->opstail = &op->next;
800 static void vstash_command(disorder_eclient *c,
802 operation_callback *opcallback,
805 const char *cmd, va_list ap) {
809 D(("vstash_command %s", cmd ? cmd : "NULL"));
812 vector_append(&vec, (char *)cmd);
813 while((arg = va_arg(ap, char *)))
814 vector_append(&vec, arg);
815 stash_command_vector(c, queuejump, opcallback, completed, v,
818 stash_command_vector(c, queuejump, opcallback, completed, v, 0, 0);
821 static void stash_command(disorder_eclient *c,
823 operation_callback *opcallback,
831 vstash_command(c, queuejump, opcallback, completed, v, cmd, ap);
835 /* Command support ***********************************************************/
837 static const char *errorstring(disorder_eclient *c) {
840 byte_xasprintf(&s, "%s: %s: %d", c->ident, c->line, c->rc);
844 /* for commands with a quoted string response */
845 static void string_response_opcallback(disorder_eclient *c,
846 struct operation *op) {
847 disorder_eclient_string_response *completed
848 = (disorder_eclient_string_response *)op->completed;
850 D(("string_response_callback"));
851 if(c->rc / 100 == 2 || c->rc == 555) {
854 completed(op->v, NULL, NULL);
855 else if(c->protocol >= 2) {
856 char **rr = split(c->line + 4, 0, SPLIT_QUOTES, 0, 0);
859 completed(op->v, NULL, *rr);
861 /* TODO error message a is bit lame but generally indicates a server
862 * bug rather than anything the user can address */
863 completed(op->v, "error parsing response", NULL);
865 completed(op->v, NULL, c->line + 4);
868 completed(op->v, errorstring(c), NULL);
871 /* for commands with a simple integer response */
872 static void integer_response_opcallback(disorder_eclient *c,
873 struct operation *op) {
874 disorder_eclient_integer_response *completed
875 = (disorder_eclient_integer_response *)op->completed;
877 D(("string_response_callback"));
878 if(c->rc / 100 == 2) {
882 e = xstrtol(&n, c->line + 4, 0, 10);
884 completed(op->v, strerror(e), 0);
886 completed(op->v, 0, n);
888 completed(op->v, errorstring(c), 0);
891 /* for commands with no response */
892 static void no_response_opcallback(disorder_eclient *c,
893 struct operation *op) {
894 disorder_eclient_no_response *completed
895 = (disorder_eclient_no_response *)op->completed;
897 D(("no_response_callback"));
899 completed(op->v, NULL);
901 completed(op->v, errorstring(c));
904 /* error callback for queue_unmarshall */
905 static void eclient_queue_error(const char *msg,
907 struct operation *op = u;
909 /* TODO don't use protocol_error here */
910 protocol_error(op->client, op, -1, "error parsing queue entry: %s", msg);
913 /* for commands that expect a queue dump */
914 static void queue_response_opcallback(disorder_eclient *c,
915 struct operation *op) {
916 disorder_eclient_queue_response *const completed
917 = (disorder_eclient_queue_response *)op->completed;
919 int parse_failed = 0;
920 struct queue_entry *q, *qh = 0, **qtail = &qh, *qlast = 0;
922 D(("queue_response_callback"));
923 if(c->rc / 100 == 2) {
924 /* parse the queue */
925 for(n = 0; n < c->vec.nvec; ++n) {
926 q = xmalloc(sizeof *q);
927 D(("queue_unmarshall %s", c->vec.vec[n]));
928 if(!queue_unmarshall(q, c->vec.vec[n], eclient_queue_error, op)) {
936 /* Currently we pass the partial queue to the callback along with the
937 * error. This might not be very useful in practice... */
939 completed(op->v, "cannot parse result", qh);
941 completed(op->v, 0, qh);
943 completed(op->v, errorstring(c), 0);
947 static void playing_response_opcallback(disorder_eclient *c,
948 struct operation *op) {
949 disorder_eclient_queue_response *const completed
950 = (disorder_eclient_queue_response *)op->completed;
951 struct queue_entry *q;
953 D(("playing_response_callback"));
954 if(c->rc / 100 == 2) {
957 if(queue_unmarshall(q = xmalloc(sizeof *q), c->line + 4,
958 eclient_queue_error, c))
959 completed(op->v, "cannot parse result", 0);
961 completed(op->v, 0, q);
964 completed(op->v, 0, 0);
967 completed(op->v, errorstring(c), 0);
971 completed(op->v, errorstring(c), 0);
974 /* for commands that expect a list of some sort */
975 static void list_response_opcallback(disorder_eclient *c,
976 struct operation *op) {
977 D(("list_response_callback"));
978 if(c->rc / 100 == 2) {
980 ((disorder_eclient_list_response *)op->completed)(op->v,
984 /* TODO don't use protocol_error here */
985 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
989 static void volume_response_opcallback(disorder_eclient *c,
990 struct operation *op) {
991 disorder_eclient_volume_response *completed
992 = (disorder_eclient_volume_response *)op->completed;
995 D(("volume_response_callback"));
996 if(c->rc / 100 == 2) {
998 if(sscanf(c->line + 4, "%d %d", &l, &r) != 2 || l < 0 || r < 0)
999 completed(op->v, "cannot parse volume response", 0, 0);
1001 completed(op->v, 0, l, r);
1004 completed(op->v, errorstring(c), 0, 0);
1007 static int simple(disorder_eclient *c,
1008 operation_callback *opcallback,
1009 void (*completed)(),
1011 const char *cmd, ...) {
1015 vstash_command(c, 0/*queuejump*/, opcallback, completed, v, cmd, ap);
1017 /* Give the state machine a kick, since we might be in state_idle */
1018 disorder_eclient_polled(c, 0);
1022 /* Commands ******************************************************************/
1024 int disorder_eclient_version(disorder_eclient *c,
1025 disorder_eclient_string_response *completed,
1027 return simple(c, string_response_opcallback, (void (*)())completed, v,
1028 "version", (char *)0);
1031 int disorder_eclient_namepart(disorder_eclient *c,
1032 disorder_eclient_string_response *completed,
1034 const char *context,
1037 return simple(c, string_response_opcallback, (void (*)())completed, v,
1038 "part", track, context, part, (char *)0);
1041 int disorder_eclient_play(disorder_eclient *c,
1043 disorder_eclient_no_response *completed,
1045 return simple(c, no_response_opcallback, (void (*)())completed, v,
1046 "play", track, (char *)0);
1049 int disorder_eclient_pause(disorder_eclient *c,
1050 disorder_eclient_no_response *completed,
1052 return simple(c, no_response_opcallback, (void (*)())completed, v,
1053 "pause", (char *)0);
1056 int disorder_eclient_resume(disorder_eclient *c,
1057 disorder_eclient_no_response *completed,
1059 return simple(c, no_response_opcallback, (void (*)())completed, v,
1060 "resume", (char *)0);
1063 int disorder_eclient_scratch(disorder_eclient *c,
1065 disorder_eclient_no_response *completed,
1067 return simple(c, no_response_opcallback, (void (*)())completed, v,
1068 "scratch", id, (char *)0);
1071 int disorder_eclient_scratch_playing(disorder_eclient *c,
1072 disorder_eclient_no_response *completed,
1074 return disorder_eclient_scratch(c, 0, completed, v);
1077 int disorder_eclient_remove(disorder_eclient *c,
1079 disorder_eclient_no_response *completed,
1081 return simple(c, no_response_opcallback, (void (*)())completed, v,
1082 "remove", id, (char *)0);
1085 int disorder_eclient_moveafter(disorder_eclient *c,
1089 disorder_eclient_no_response *completed,
1095 vector_append(&vec, (char *)"moveafter");
1096 vector_append(&vec, (char *)target);
1097 for(n = 0; n < nids; ++n)
1098 vector_append(&vec, (char *)ids[n]);
1099 stash_command_vector(c, 0/*queuejump*/, no_response_opcallback, completed, v,
1101 disorder_eclient_polled(c, 0);
1105 int disorder_eclient_recent(disorder_eclient *c,
1106 disorder_eclient_queue_response *completed,
1108 return simple(c, queue_response_opcallback, (void (*)())completed, v,
1109 "recent", (char *)0);
1112 int disorder_eclient_queue(disorder_eclient *c,
1113 disorder_eclient_queue_response *completed,
1115 return simple(c, queue_response_opcallback, (void (*)())completed, v,
1116 "queue", (char *)0);
1119 int disorder_eclient_files(disorder_eclient *c,
1120 disorder_eclient_list_response *completed,
1124 return simple(c, list_response_opcallback, (void (*)())completed, v,
1125 "files", dir, re, (char *)0);
1128 int disorder_eclient_dirs(disorder_eclient *c,
1129 disorder_eclient_list_response *completed,
1133 return simple(c, list_response_opcallback, (void (*)())completed, v,
1134 "dirs", dir, re, (char *)0);
1137 int disorder_eclient_playing(disorder_eclient *c,
1138 disorder_eclient_queue_response *completed,
1140 return simple(c, playing_response_opcallback, (void (*)())completed, v,
1141 "playing", (char *)0);
1144 int disorder_eclient_length(disorder_eclient *c,
1145 disorder_eclient_integer_response *completed,
1148 return simple(c, integer_response_opcallback, (void (*)())completed, v,
1149 "length", track, (char *)0);
1152 int disorder_eclient_volume(disorder_eclient *c,
1153 disorder_eclient_volume_response *completed,
1156 char sl[64], sr[64];
1158 if(l < 0 && r < 0) {
1159 return simple(c, volume_response_opcallback, (void (*)())completed, v,
1160 "volume", (char *)0);
1161 } else if(l >= 0 && r >= 0) {
1164 byte_snprintf(sl, sizeof sl, "%d", l);
1165 byte_snprintf(sr, sizeof sr, "%d", r);
1166 return simple(c, volume_response_opcallback, (void (*)())completed, v,
1167 "volume", sl, sr, (char *)0);
1169 assert(!"invalid arguments to disorder_eclient_volume");
1170 return -1; /* gcc is being dim */
1174 int disorder_eclient_enable(disorder_eclient *c,
1175 disorder_eclient_no_response *completed,
1177 return simple(c, no_response_opcallback, (void (*)())completed, v,
1178 "enable", (char *)0);
1181 int disorder_eclient_disable(disorder_eclient *c,
1182 disorder_eclient_no_response *completed,
1184 return simple(c, no_response_opcallback, (void (*)())completed, v,
1185 "disable", (char *)0);
1188 int disorder_eclient_random_enable(disorder_eclient *c,
1189 disorder_eclient_no_response *completed,
1191 return simple(c, no_response_opcallback, (void (*)())completed, v,
1192 "random-enable", (char *)0);
1195 int disorder_eclient_random_disable(disorder_eclient *c,
1196 disorder_eclient_no_response *completed,
1198 return simple(c, no_response_opcallback, (void (*)())completed, v,
1199 "random-disable", (char *)0);
1202 int disorder_eclient_get(disorder_eclient *c,
1203 disorder_eclient_string_response *completed,
1204 const char *track, const char *pref,
1206 return simple(c, string_response_opcallback, (void (*)())completed, v,
1207 "get", track, pref, (char *)0);
1210 int disorder_eclient_set(disorder_eclient *c,
1211 disorder_eclient_no_response *completed,
1212 const char *track, const char *pref,
1215 return simple(c, no_response_opcallback, (void (*)())completed, v,
1216 "set", track, pref, value, (char *)0);
1219 int disorder_eclient_unset(disorder_eclient *c,
1220 disorder_eclient_no_response *completed,
1221 const char *track, const char *pref,
1223 return simple(c, no_response_opcallback, (void (*)())completed, v,
1224 "unset", track, pref, (char *)0);
1227 int disorder_eclient_resolve(disorder_eclient *c,
1228 disorder_eclient_string_response *completed,
1231 return simple(c, string_response_opcallback, (void (*)())completed, v,
1232 "resolve", track, (char *)0);
1235 int disorder_eclient_search(disorder_eclient *c,
1236 disorder_eclient_list_response *completed,
1239 if(!split(terms, 0, SPLIT_QUOTES, 0, 0)) return -1;
1240 return simple(c, list_response_opcallback, (void (*)())completed, v,
1241 "search", terms, (char *)0);
1244 int disorder_eclient_nop(disorder_eclient *c,
1245 disorder_eclient_no_response *completed,
1247 return simple(c, no_response_opcallback, (void (*)())completed, v,
1251 /** @brief Get the last @p max added tracks
1253 * @param completed Called with list
1254 * @param max Number of tracks to get, 0 for all
1255 * @param v Passed to @p completed
1257 * The first track in the list is the most recently added.
1259 int disorder_eclient_new_tracks(disorder_eclient *c,
1260 disorder_eclient_list_response *completed,
1265 sprintf(limit, "%d", max);
1266 return simple(c, list_response_opcallback, (void (*)())completed, v,
1267 "new", limit, (char *)0);
1270 static void rtp_response_opcallback(disorder_eclient *c,
1271 struct operation *op) {
1272 D(("rtp_response_opcallback"));
1273 if(c->rc / 100 == 2) {
1276 char **vec = split(c->line + 4, &nvec, SPLIT_QUOTES, 0, 0);
1278 ((disorder_eclient_list_response *)op->completed)(op->v, nvec, vec);
1281 /* TODO don't use protocol_error here */
1282 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
1285 /** @brief Determine the RTP target address
1287 * @param completed Called with address details
1288 * @param v Passed to @p completed
1290 * The address details will be two elements, the first being the hostname and
1291 * the second the service (port).
1293 int disorder_eclient_rtp_address(disorder_eclient *c,
1294 disorder_eclient_list_response *completed,
1296 return simple(c, rtp_response_opcallback, (void (*)())completed, v,
1297 "rtp-address", (char *)0);
1300 /** @brief Get the list of users
1302 * @param completed Called with list of users
1303 * @param v Passed to @p completed
1305 * The user list is not sorted in any particular order.
1307 int disorder_eclient_users(disorder_eclient *c,
1308 disorder_eclient_list_response *completed,
1310 return simple(c, list_response_opcallback, (void (*)())completed, v,
1311 "users", (char *)0);
1314 /** @brief Delete a user
1316 * @param completed Called on completion
1317 * @param user User to delete
1318 * @param v Passed to @p completed
1320 int disorder_eclient_deluser(disorder_eclient *c,
1321 disorder_eclient_no_response *completed,
1324 return simple(c, no_response_opcallback, (void (*)())completed, v,
1325 "deluser", user, (char *)0);
1328 /** @brief Get a user property
1330 * @param completed Called on completion
1331 * @param user User to look up
1332 * @param property Property to look up
1333 * @param v Passed to @p completed
1335 int disorder_eclient_userinfo(disorder_eclient *c,
1336 disorder_eclient_string_response *completed,
1338 const char *property,
1340 return simple(c, string_response_opcallback, (void (*)())completed, v,
1341 "userinfo", user, property, (char *)0);
1344 /** @brief Modify a user property
1346 * @param completed Called on completion
1347 * @param user User to modify
1348 * @param property Property to modify
1349 * @param value New property value
1350 * @param v Passed to @p completed
1352 int disorder_eclient_edituser(disorder_eclient *c,
1353 disorder_eclient_no_response *completed,
1355 const char *property,
1358 return simple(c, no_response_opcallback, (void (*)())completed, v,
1359 "edituser", user, property, value, (char *)0);
1362 /** @brief Create a new user
1364 * @param completed Called on completion
1365 * @param user User to create
1366 * @param password Initial password
1367 * @param rights Initial rights or NULL
1368 * @param v Passed to @p completed
1370 int disorder_eclient_adduser(disorder_eclient *c,
1371 disorder_eclient_no_response *completed,
1373 const char *password,
1376 return simple(c, no_response_opcallback, (void (*)())completed, v,
1377 "adduser", user, password, rights, (char *)0);
1380 /* Log clients ***************************************************************/
1382 /** @brief Monitor the server log
1384 * @param callbacks Functions to call when anything happens
1385 * @param v Passed to @p callbacks functions
1387 * Once a client is being used for logging it cannot be used for anything else.
1388 * There is magic in authuser_opcallback() to re-submit the @c log command
1389 * after reconnection.
1391 * NB that the @c state callback may be called from within this function,
1392 * i.e. not solely later on from the event loop callback.
1394 int disorder_eclient_log(disorder_eclient *c,
1395 const disorder_eclient_log_callbacks *callbacks,
1397 if(c->log_callbacks) return -1;
1398 c->log_callbacks = callbacks;
1400 /* Repoort initial state */
1401 if(c->log_callbacks->state)
1402 c->log_callbacks->state(c->log_v, c->statebits);
1403 stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, v,
1405 disorder_eclient_polled(c, 0);
1409 /* If we get here we've stopped being a log client */
1410 static void log_opcallback(disorder_eclient *c,
1411 struct operation attribute((unused)) *op) {
1412 D(("log_opcallback"));
1413 c->log_callbacks = 0;
1417 /* error callback for log line parsing */
1418 static void logline_error(const char *msg, void *u) {
1419 disorder_eclient *c = u;
1420 /* TODO don't use protocol_error here */
1421 protocol_error(c, c->ops, -1, "error parsing log line: %s", msg);
1424 /* process a single log line */
1425 static void logline(disorder_eclient *c, const char *line) {
1430 D(("logline [%s]", line));
1431 vec = split(line, &nvec, SPLIT_QUOTES, logline_error, c);
1432 if(nvec < 2) return; /* probably an error, already
1434 if(sscanf(vec[0], "%"SCNxMAX, &when) != 1) {
1435 /* probably the wrong side of a format change */
1436 /* TODO don't use protocol_error here */
1437 protocol_error(c, c->ops, -1, "invalid log timestamp '%s'", vec[0]);
1440 /* TODO: do something with the time */
1441 n = TABLE_FIND(logentry_handlers, name, vec[1]);
1442 if(n < 0) return; /* probably a future command */
1445 if(nvec < logentry_handlers[n].min || nvec > logentry_handlers[n].max)
1447 logentry_handlers[n].handler(c, nvec, vec);
1450 static void logentry_completed(disorder_eclient *c,
1451 int attribute((unused)) nvec, char **vec) {
1452 c->statebits &= ~DISORDER_PLAYING;
1453 if(c->log_callbacks->completed)
1454 c->log_callbacks->completed(c->log_v, vec[0]);
1455 if(c->log_callbacks->state)
1456 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1459 static void logentry_failed(disorder_eclient *c,
1460 int attribute((unused)) nvec, char **vec) {
1461 c->statebits &= ~DISORDER_PLAYING;
1462 if(c->log_callbacks->failed)
1463 c->log_callbacks->failed(c->log_v, vec[0], vec[1]);
1464 if(c->log_callbacks->state)
1465 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1468 static void logentry_moved(disorder_eclient *c,
1469 int attribute((unused)) nvec, char **vec) {
1470 if(c->log_callbacks->moved)
1471 c->log_callbacks->moved(c->log_v, vec[0]);
1474 static void logentry_playing(disorder_eclient *c,
1475 int attribute((unused)) nvec, char **vec) {
1476 c->statebits |= DISORDER_PLAYING;
1477 if(c->log_callbacks->playing)
1478 c->log_callbacks->playing(c->log_v, vec[0], vec[1]);
1479 if(c->log_callbacks->state)
1480 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1483 static void logentry_queue(disorder_eclient *c,
1484 int attribute((unused)) nvec, char **vec) {
1485 struct queue_entry *q;
1487 if(!c->log_callbacks->queue) return;
1488 q = xmalloc(sizeof *q);
1489 if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1491 c->log_callbacks->queue(c->log_v, q);
1494 static void logentry_recent_added(disorder_eclient *c,
1495 int attribute((unused)) nvec, char **vec) {
1496 struct queue_entry *q;
1498 if(!c->log_callbacks->recent_added) return;
1499 q = xmalloc(sizeof *q);
1500 if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1502 c->log_callbacks->recent_added(c->log_v, q);
1505 static void logentry_recent_removed(disorder_eclient *c,
1506 int attribute((unused)) nvec, char **vec) {
1507 if(c->log_callbacks->recent_removed)
1508 c->log_callbacks->recent_removed(c->log_v, vec[0]);
1511 static void logentry_removed(disorder_eclient *c,
1512 int attribute((unused)) nvec, char **vec) {
1513 if(c->log_callbacks->removed)
1514 c->log_callbacks->removed(c->log_v, vec[0], vec[1]);
1517 static void logentry_rescanned(disorder_eclient *c,
1518 int attribute((unused)) nvec,
1519 char attribute((unused)) **vec) {
1520 if(c->log_callbacks->rescanned)
1521 c->log_callbacks->rescanned(c->log_v);
1524 static void logentry_scratched(disorder_eclient *c,
1525 int attribute((unused)) nvec, char **vec) {
1526 c->statebits &= ~DISORDER_PLAYING;
1527 if(c->log_callbacks->scratched)
1528 c->log_callbacks->scratched(c->log_v, vec[0], vec[1]);
1529 if(c->log_callbacks->state)
1530 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1533 static const struct {
1536 const char *disable;
1537 } statestrings[] = {
1538 { DISORDER_PLAYING_ENABLED, "enable_play", "disable_play" },
1539 { DISORDER_RANDOM_ENABLED, "enable_random", "disable_random" },
1540 { DISORDER_TRACK_PAUSED, "pause", "resume" },
1541 { DISORDER_PLAYING, "playing", "completed" },
1542 { DISORDER_PLAYING, 0, "scratched" },
1543 { DISORDER_PLAYING, 0, "failed" },
1545 #define NSTATES (int)(sizeof statestrings / sizeof *statestrings)
1547 static void logentry_state(disorder_eclient *c,
1548 int attribute((unused)) nvec, char **vec) {
1551 for(n = 0; n < NSTATES; ++n)
1552 if(statestrings[n].enable && !strcmp(vec[0], statestrings[n].enable)) {
1553 c->statebits |= statestrings[n].bit;
1555 } else if(statestrings[n].disable && !strcmp(vec[0], statestrings[n].disable)) {
1556 c->statebits &= ~statestrings[n].bit;
1559 if(c->log_callbacks->state)
1560 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1563 static void logentry_volume(disorder_eclient *c,
1564 int attribute((unused)) nvec, char **vec) {
1567 if(!c->log_callbacks->volume) return;
1568 if(xstrtol(&l, vec[0], 0, 10)
1569 || xstrtol(&r, vec[1], 0, 10)
1570 || l < 0 || l > INT_MAX
1571 || r < 0 || r > INT_MAX)
1573 c->log_callbacks->volume(c->log_v, (int)l, (int)r);
1576 /** @brief Convert @p statebits to a string */
1577 char *disorder_eclient_interpret_state(unsigned long statebits) {
1581 static const struct {
1585 { DISORDER_PLAYING_ENABLED, "playing_enabled" },
1586 { DISORDER_RANDOM_ENABLED, "random_enabled" },
1587 { DISORDER_TRACK_PAUSED, "track_paused" },
1588 { DISORDER_PLAYING, "playing" },
1589 { DISORDER_CONNECTED, "connected" },
1591 #define NBITS (sizeof bits / sizeof *bits)
1595 dynstr_append(d, '0');
1596 for(n = 0; n < NBITS; ++n)
1597 if(statebits & bits[n].bit) {
1599 dynstr_append(d, '|');
1600 dynstr_append_string(d, bits[n].name);
1601 statebits ^= bits[n].bit;
1607 dynstr_append(d, '|');
1608 sprintf(s, "%#lx", statebits);
1609 dynstr_append_string(d, s);
1611 dynstr_terminate(d);
1620 indent-tabs-mode:nil