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
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.
150 /** @brief Protocol version */
154 /* Forward declarations ******************************************************/
156 static int start_connect(disorder_eclient *c);
157 static void process_line(disorder_eclient *c, char *line);
158 static void maybe_connected(disorder_eclient *c);
159 static void authbanner_opcallback(disorder_eclient *c,
160 struct operation *op);
161 static void authuser_opcallback(disorder_eclient *c,
162 struct operation *op);
163 static void complete(disorder_eclient *c);
164 static void send_output(disorder_eclient *c);
165 static void put(disorder_eclient *c, const char *s, size_t n);
166 static void read_input(disorder_eclient *c);
167 static void stash_command(disorder_eclient *c,
169 operation_callback *opcallback,
174 static void log_opcallback(disorder_eclient *c, struct operation *op);
175 static void logline(disorder_eclient *c, const char *line);
176 static void logentry_completed(disorder_eclient *c, int nvec, char **vec);
177 static void logentry_failed(disorder_eclient *c, int nvec, char **vec);
178 static void logentry_moved(disorder_eclient *c, int nvec, char **vec);
179 static void logentry_playing(disorder_eclient *c, int nvec, char **vec);
180 static void logentry_queue(disorder_eclient *c, int nvec, char **vec);
181 static void logentry_recent_added(disorder_eclient *c, int nvec, char **vec);
182 static void logentry_recent_removed(disorder_eclient *c, int nvec, char **vec);
183 static void logentry_removed(disorder_eclient *c, int nvec, char **vec);
184 static void logentry_scratched(disorder_eclient *c, int nvec, char **vec);
185 static void logentry_state(disorder_eclient *c, int nvec, char **vec);
186 static void logentry_volume(disorder_eclient *c, int nvec, char **vec);
187 static void logentry_rescanned(disorder_eclient *c, int nvec, char **vec);
189 /* Tables ********************************************************************/
191 /** @brief One possible log entry */
192 struct logentry_handler {
193 const char *name; /**< @brief Entry name */
194 int min; /**< @brief Minimum arguments */
195 int max; /**< @brief Maximum arguments */
196 void (*handler)(disorder_eclient *c,
198 char **vec); /**< @brief Handler function */
201 /** @brief Table for parsing log entries */
202 static const struct logentry_handler logentry_handlers[] = {
203 #define LE(X, MIN, MAX) { #X, MIN, MAX, logentry_##X }
208 LE(queue, 2, INT_MAX),
209 LE(recent_added, 2, INT_MAX),
210 LE(recent_removed, 1, 1),
218 /* Setup and teardown ********************************************************/
220 /** @brief Create a new client
222 * Does NOT connect the client - connections are made (and re-made) on demand.
224 disorder_eclient *disorder_eclient_new(const disorder_eclient_callbacks *cb,
226 disorder_eclient *c = xmalloc(sizeof *c);
227 D(("disorder_eclient_new"));
231 c->opstail = &c->ops;
232 vector_init(&c->vec);
233 dynstr_init(&c->input);
234 dynstr_init(&c->output);
238 /** @brief Disconnect a client
239 * @param c Client to disconnect
241 * NB that this routine just disconnnects the TCP connection. It does not
242 * destroy the client! If you continue to use it then it will attempt to
245 void disorder_eclient_close(disorder_eclient *c) {
246 struct operation *op;
248 D(("disorder_eclient_close"));
250 D(("disorder_eclient_close closing fd %d", c->fd));
251 c->callbacks->poll(c->u, c, c->fd, 0);
254 c->state = state_disconnected;
260 c->authenticated = 0;
261 /* We'll need to resend all operations */
262 for(op = c->ops; op; op = op->next)
264 /* Drop our use a hint that we're disconnected */
265 if(c->log_callbacks && c->log_callbacks->state)
266 c->log_callbacks->state(c->log_v, c->statebits);
269 /** @brief Return current state */
270 unsigned long disorder_eclient_state(const disorder_eclient *c) {
271 return c->statebits | (c->state > state_connected ? DISORDER_CONNECTED : 0);
274 /* Error reporting ***********************************************************/
276 /** @brief called when a connection error occurs
278 * After this called we will be disconnected (by disorder_eclient_close()),
279 * so there will be a reconnection before any commands can be sent.
281 static int comms_error(disorder_eclient *c, const char *fmt, ...) {
287 byte_xvasprintf(&s, fmt, ap);
289 disorder_eclient_close(c);
290 c->callbacks->comms_error(c->u, s);
294 /** @brief called when the server reports an error */
295 static int protocol_error(disorder_eclient *c, struct operation *op,
296 int code, const char *fmt, ...) {
300 D(("protocol_error"));
302 byte_xvasprintf(&s, fmt, ap);
304 c->callbacks->protocol_error(c->u, op->v, code, s);
308 /* State machine *************************************************************/
310 /** @brief Called when there's something to do
312 * @param mode bitmap of @ref DISORDER_POLL_READ and/or @ref DISORDER_POLL_WRITE.
314 * This should be called from by your code when the file descriptor is readable
315 * or writable (as requested by the @c poll callback, see @ref
316 * disorder_eclient_callbacks) and in any case from time to time (with @p mode
317 * = 0) to allow for retries to work.
319 void disorder_eclient_polled(disorder_eclient *c, unsigned mode) {
320 struct operation *op;
323 D(("disorder_eclient_polled fd=%d state=%s mode=[%s %s]",
324 c->fd, states[c->state],
325 mode & DISORDER_POLL_READ ? "READ" : "",
326 mode & DISORDER_POLL_WRITE ? "WRITE" : ""));
327 /* The pattern here is to check each possible state in turn and try to
328 * advance (though on error we might go back). If we advance we leave open
329 * the possibility of falling through to the next state, but we set the mode
330 * bits to 0, to avoid false positives (which matter more in some cases than
333 if(c->state == state_disconnected) {
334 D(("state_disconnected"));
335 /* If there is no password yet then we cannot connect */
336 if(!config->password) {
337 comms_error(c, "no password is configured");
341 /* might now be state_disconnected (on error), state_connecting (slow
342 * connect) or state_connected (fast connect). If state_disconnected then
343 * we just rely on a periodic callback from the event loop sometime. */
347 if(c->state == state_connecting && mode) {
348 D(("state_connecting"));
350 /* Might be state_disconnected (on error) or state_connected (on success).
351 * In the former case we rely on the event loop for a periodic callback to
356 if(c->state == state_connected) {
357 D(("state_connected"));
358 /* We just connected. Initiate the authentication protocol. */
359 stash_command(c, 1/*queuejump*/, authbanner_opcallback,
360 0/*completed*/, 0/*v*/, 0/*cmd*/);
361 /* We never stay is state_connected very long. We could in principle jump
362 * straight to state_cmdresponse since there's actually no command to
363 * send, but that would arguably be cheating. */
364 c->state = state_idle;
367 if(c->state == state_idle) {
369 /* We are connected, and have finished any command we set off, look for
373 if(c->authenticated) {
374 /* Transmit all unsent operations */
375 for(op = c->ops; op; op = op->next) {
377 put(c, op->cmd, strlen(op->cmd));
382 /* Just send the head operation */
383 if(c->ops->cmd && !c->ops->sent) {
384 put(c, c->ops->cmd, strlen(c->ops->cmd));
388 /* Awaiting response for the operation at the head of the list */
389 c->state = state_cmdresponse;
392 c->callbacks->report(c->u, 0);
395 /* Queue up a byte to send */
396 if(c->state == state_log
397 && c->output.nvec == 0
398 && time(&now) - c->last_prod > LOG_PROD_INTERVAL) {
403 if(c->state == state_cmdresponse
404 || c->state == state_body
405 || c->state == state_log) {
406 D(("state_%s", states[c->state]));
407 /* We are awaiting a response */
408 if(mode & DISORDER_POLL_WRITE) send_output(c);
409 if(mode & DISORDER_POLL_READ) read_input(c);
410 /* There are a couple of reasons we might want to re-enter the state
411 * machine from the top. state_idle is obvious: there may be further
412 * commands to process. Re-entering on state_disconnected means that we
413 * immediately retry connection if a comms error occurs during a command.
414 * This is different to the case where a connection fails, where we await a
415 * spontaneous call to initiate the retry. */
417 case state_disconnected: /* lost connection */
418 case state_idle: /* completed a command */
420 disorder_eclient_polled(c, 0);
427 /* Figure out what to set the mode to */
429 case state_disconnected:
430 D(("state_disconnected (2)"));
431 /* Probably an error occurred. Await a retry. */
434 case state_connecting:
435 D(("state_connecting (2)"));
436 /* Waiting for connect to complete */
437 mode = DISORDER_POLL_READ|DISORDER_POLL_WRITE;
439 case state_connected:
440 D(("state_connected (2)"));
441 assert(!"should never be in state_connected here");
444 D(("state_idle (2)"));
445 /* Connected but nothing to do. */
448 case state_cmdresponse:
451 D(("state_%s (2)", states[c->state]));
452 /* Gathering a response. Wait for input. */
453 mode = DISORDER_POLL_READ;
454 /* Flush any pending output. */
455 if(c->output.nvec) mode |= DISORDER_POLL_WRITE;
458 D(("fd=%d new mode [%s %s]",
460 mode & DISORDER_POLL_READ ? "READ" : "",
461 mode & DISORDER_POLL_WRITE ? "WRITE" : ""));
462 if(c->fd != -1) c->callbacks->poll(c->u, c, c->fd, mode);
465 /** @brief Called to start connecting */
466 static int start_connect(disorder_eclient *c) {
470 D(("start_connect"));
471 if((len = find_server(&sa, &c->ident)) == (socklen_t)-1)
472 return comms_error(c, "cannot look up server"); /* TODO better error */
477 if((c->fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
478 return comms_error(c, "socket: %s", strerror(errno));
482 if(connect(c->fd, sa, len) < 0) {
486 c->state = state_connecting;
487 /* We are called from _polled so the state machine will get to do its
491 /* Signal the error to the caller. */
492 return comms_error(c, "connecting to %s: %s", c->ident, strerror(errno));
495 c->state = state_connected;
499 /** @brief Called when poll triggers while waiting for a connection */
500 static void maybe_connected(disorder_eclient *c) {
501 /* We either connected, or got an error. */
503 socklen_t len = sizeof err;
505 D(("maybe_connected"));
506 /* Work around over-enthusiastic error slippage */
507 if(getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0)
510 /* The connection failed */
511 comms_error(c, "connecting to %s: %s", c->ident, strerror(err));
512 /* sets state_disconnected */
516 /* The connection succeeded */
517 c->state = state_connected;
518 byte_xasprintf(&r, "connected to %s", c->ident);
519 c->callbacks->report(c->u, r);
520 /* If this is a log client we expect to get a bunch of updates from the
521 * server straight away */
525 /* Authentication ************************************************************/
527 static void authbanner_opcallback(disorder_eclient *c,
528 struct operation *op) {
530 const unsigned char *nonce;
534 const char *protocol, *algorithm, *challenge;
536 D(("authbanner_opcallback"));
538 || !(rvec = split(c->line + 4, &nrvec, SPLIT_QUOTES, 0, 0))
540 /* Banner told us to go away, or was malformed. We cannot proceed. */
541 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
542 disorder_eclient_close(c);
562 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
563 disorder_eclient_close(c);
566 c->protocol = atoi(protocol);
567 if(c->protocol < 1 || c->protocol > 2) {
568 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
569 disorder_eclient_close(c);
572 nonce = unhex(challenge, &nonce_len);
573 res = authhash(nonce, nonce_len, config->password, algorithm);
575 protocol_error(c, op, c->rc, "%s: unknown authentication algorithm '%s'",
576 c->ident, algorithm);
577 disorder_eclient_close(c);
580 stash_command(c, 1/*queuejump*/, authuser_opcallback, 0/*completed*/, 0/*v*/,
581 "user", quoteutf8(config->username), quoteutf8(res),
585 static void authuser_opcallback(disorder_eclient *c,
586 struct operation *op) {
589 D(("authuser_opcallback"));
590 if(c->rc / 100 != 2) {
591 /* Wrong password or something. We cannot proceed. */
592 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
593 disorder_eclient_close(c);
596 /* OK, we're authenticated now. */
597 c->authenticated = 1;
598 byte_xasprintf(&r, "authenticated with %s", c->ident);
599 c->callbacks->report(c->u, r);
600 if(c->log_callbacks && !(c->ops && c->ops->opcallback == log_opcallback))
601 /* We are a log client, switch to logging mode */
602 stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, c->log_v,
606 /* Output ********************************************************************/
608 /* Chop N bytes off the front of a dynstr */
609 static void consume(struct dynstr *d, int n) {
610 D(("consume %d", n));
611 assert(d->nvec >= n);
612 memmove(d->vec, d->vec + n, d->nvec - n);
616 /* Write some bytes */
617 static void put(disorder_eclient *c, const char *s, size_t n) {
618 D(("put %d %.*s", c->fd, (int)n, s));
619 dynstr_append_bytes(&c->output, s, n);
622 /* Called when we can write to our FD, or at any other time */
623 static void send_output(disorder_eclient *c) {
626 D(("send_output %d bytes pending", c->output.nvec));
627 if(c->state > state_connecting && c->output.nvec) {
628 n = write(c->fd, c->output.vec, c->output.nvec);
635 comms_error(c, "writing to %s: %s", c->ident, strerror(errno));
639 consume(&c->output, n);
643 /* Input *********************************************************************/
645 /* Called when c->fd might be readable, or at any other time */
646 static void read_input(disorder_eclient *c) {
651 D(("read_input in state %s", states[c->state]));
652 if(c->state <= state_connected) return; /* ignore bogus calls */
653 /* read some more input */
654 n = read(c->fd, buffer, sizeof buffer);
661 comms_error(c, "reading from %s: %s", c->ident, strerror(errno));
664 return; /* no new input to process */
666 D(("read %d bytes: [%.*s]", n, n, buffer));
667 dynstr_append_bytes(&c->input, buffer, n);
670 /* might have more than one line to process */
671 while(c->state > state_connecting
672 && (nl = memchr(c->input.vec, '\n', c->input.nvec))) {
673 process_line(c, xstrndup(c->input.vec, nl - c->input.vec));
674 /* we might have disconnected along the way, which zogs the input buffer */
675 if(c->state > state_connecting)
676 consume(&c->input, (nl - c->input.vec) + 1);
679 comms_error(c, "reading from %s: server disconnected", c->ident);
680 c->authenticated = 0;
684 /* called with a line that has just been read */
685 static void process_line(disorder_eclient *c, char *line) {
686 D(("process_line %d [%s]", c->fd, line));
688 case state_cmdresponse:
689 /* This is the first line of a response */
690 if(!(line[0] >= '0' && line[0] <= '9'
691 && line[1] >= '0' && line[1] <= '9'
692 && line[2] >= '0' && line[2] <= '9'
694 fatal(0, "invalid response from server: %s", line);
695 c->rc = (line[0] * 10 + line[1]) * 10 + line[2] - 111 * '0';
699 /* We need to collect the body. */
700 c->state = state_body;
701 vector_init(&c->vec);
704 assert(c->log_callbacks != 0);
705 if(c->log_callbacks->connected)
706 c->log_callbacks->connected(c->log_v);
707 c->state = state_log;
710 /* We've got the whole response. Go into the idle state so the state
711 * machine knows we're done and then call the operation callback. */
717 if(strcmp(line, ".")) {
718 /* A line from the body */
719 vector_append(&c->vec, line + (line[0] == '.'));
721 /* End of the body. */
722 vector_terminate(&c->vec);
727 if(strcmp(line, ".")) {
728 logline(c, line + (line[0] == '.'));
733 assert(!"wrong state for location");
738 /* Called when an operation completes */
739 static void complete(disorder_eclient *c) {
740 struct operation *op;
743 /* Pop the operation off the queue */
746 if(c->opstail == &op->next)
747 c->opstail = &c->ops;
748 /* If we've pipelined a command ahead then we go straight to cmdresponser.
749 * Otherwise we go to idle, which will arrange further sends. */
750 c->state = c->ops && c->ops->sent ? state_cmdresponse : state_idle;
751 op->opcallback(c, op);
752 /* Note that we always call the opcallback even on error, though command
753 * opcallbacks generally always do the same error handling, i.e. just call
754 * protocol_error(). It's the auth* opcallbacks that have different
758 /* Operation setup ***********************************************************/
760 static void stash_command_vector(disorder_eclient *c,
762 operation_callback *opcallback,
767 struct operation *op = xmalloc(sizeof *op);
773 for(n = 0; n < ncmd; ++n) {
775 dynstr_append(&d, ' ');
776 dynstr_append_string(&d, quoteutf8(cmd[n]));
778 dynstr_append(&d, '\n');
779 dynstr_terminate(&d);
782 op->cmd = 0; /* usually, awaiting challenge */
783 op->opcallback = opcallback;
784 op->completed = completed;
788 assert(op->sent == 0);
790 /* Authentication operations jump the queue of useful commands */
793 if(c->opstail == &c->ops)
794 c->opstail = &op->next;
795 for(op = c->ops; op; op = op->next)
799 c->opstail = &op->next;
803 static void vstash_command(disorder_eclient *c,
805 operation_callback *opcallback,
808 const char *cmd, va_list ap) {
812 D(("vstash_command %s", cmd ? cmd : "NULL"));
815 vector_append(&vec, (char *)cmd);
816 while((arg = va_arg(ap, char *)))
817 vector_append(&vec, arg);
818 stash_command_vector(c, queuejump, opcallback, completed, v,
821 stash_command_vector(c, queuejump, opcallback, completed, v, 0, 0);
824 static void stash_command(disorder_eclient *c,
826 operation_callback *opcallback,
834 vstash_command(c, queuejump, opcallback, completed, v, cmd, ap);
838 /* Command support ***********************************************************/
840 /* for commands with a quoted string response */
841 static void string_response_opcallback(disorder_eclient *c,
842 struct operation *op) {
843 D(("string_response_callback"));
844 if(c->rc / 100 == 2) {
846 if(c->protocol >= 2) {
847 char **rr = split(c->line + 4, 0, SPLIT_QUOTES, 0, 0);
850 ((disorder_eclient_string_response *)op->completed)(op->v, *rr);
852 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
854 ((disorder_eclient_string_response *)op->completed)(op->v,
858 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
861 /* for commands with a simple integer response */
862 static void integer_response_opcallback(disorder_eclient *c,
863 struct operation *op) {
864 D(("string_response_callback"));
865 if(c->rc / 100 == 2) {
867 ((disorder_eclient_integer_response *)op->completed)
868 (op->v, strtol(c->line + 4, 0, 10));
870 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
873 /* for commands with no response */
874 static void no_response_opcallback(disorder_eclient *c,
875 struct operation *op) {
876 D(("no_response_callback"));
877 if(c->rc / 100 == 2) {
879 ((disorder_eclient_no_response *)op->completed)(op->v);
881 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
884 /* error callback for queue_unmarshall */
885 static void eclient_queue_error(const char *msg,
887 struct operation *op = u;
889 protocol_error(op->client, op, -1, "error parsing queue entry: %s", msg);
892 /* for commands that expect a queue dump */
893 static void queue_response_opcallback(disorder_eclient *c,
894 struct operation *op) {
896 struct queue_entry *q, *qh = 0, **qtail = &qh, *qlast = 0;
898 D(("queue_response_callback"));
899 if(c->rc / 100 == 2) {
900 /* parse the queue */
901 for(n = 0; n < c->vec.nvec; ++n) {
902 q = xmalloc(sizeof *q);
903 D(("queue_unmarshall %s", c->vec.vec[n]));
904 if(!queue_unmarshall(q, c->vec.vec[n], eclient_queue_error, op)) {
912 ((disorder_eclient_queue_response *)op->completed)(op->v, qh);
914 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
918 static void playing_response_opcallback(disorder_eclient *c,
919 struct operation *op) {
920 struct queue_entry *q;
922 D(("playing_response_callback"));
923 if(c->rc / 100 == 2) {
926 if(queue_unmarshall(q = xmalloc(sizeof *q), c->line + 4,
927 eclient_queue_error, c))
934 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
938 ((disorder_eclient_queue_response *)op->completed)(op->v, q);
940 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
943 /* for commands that expect a list of some sort */
944 static void list_response_opcallback(disorder_eclient *c,
945 struct operation *op) {
946 D(("list_response_callback"));
947 if(c->rc / 100 == 2) {
949 ((disorder_eclient_list_response *)op->completed)(op->v,
953 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
957 static void volume_response_opcallback(disorder_eclient *c,
958 struct operation *op) {
961 D(("volume_response_callback"));
962 if(c->rc / 100 == 2) {
964 if(sscanf(c->line + 4, "%d %d", &l, &r) != 2 || l < 0 || r < 0)
965 protocol_error(c, op, -1, "%s: invalid volume response: %s",
968 ((disorder_eclient_volume_response *)op->completed)(op->v, l, r);
971 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
974 static int simple(disorder_eclient *c,
975 operation_callback *opcallback,
978 const char *cmd, ...) {
982 vstash_command(c, 0/*queuejump*/, opcallback, completed, v, cmd, ap);
984 /* Give the state machine a kick, since we might be in state_idle */
985 disorder_eclient_polled(c, 0);
989 /* Commands ******************************************************************/
991 int disorder_eclient_version(disorder_eclient *c,
992 disorder_eclient_string_response *completed,
994 return simple(c, string_response_opcallback, (void (*)())completed, v,
995 "version", (char *)0);
998 int disorder_eclient_namepart(disorder_eclient *c,
999 disorder_eclient_string_response *completed,
1001 const char *context,
1004 return simple(c, string_response_opcallback, (void (*)())completed, v,
1005 "part", track, context, part, (char *)0);
1008 int disorder_eclient_play(disorder_eclient *c,
1010 disorder_eclient_no_response *completed,
1012 return simple(c, no_response_opcallback, (void (*)())completed, v,
1013 "play", track, (char *)0);
1016 int disorder_eclient_pause(disorder_eclient *c,
1017 disorder_eclient_no_response *completed,
1019 return simple(c, no_response_opcallback, (void (*)())completed, v,
1020 "pause", (char *)0);
1023 int disorder_eclient_resume(disorder_eclient *c,
1024 disorder_eclient_no_response *completed,
1026 return simple(c, no_response_opcallback, (void (*)())completed, v,
1027 "resume", (char *)0);
1030 int disorder_eclient_scratch(disorder_eclient *c,
1032 disorder_eclient_no_response *completed,
1034 return simple(c, no_response_opcallback, (void (*)())completed, v,
1035 "scratch", id, (char *)0);
1038 int disorder_eclient_scratch_playing(disorder_eclient *c,
1039 disorder_eclient_no_response *completed,
1041 return disorder_eclient_scratch(c, 0, completed, v);
1044 int disorder_eclient_remove(disorder_eclient *c,
1046 disorder_eclient_no_response *completed,
1048 return simple(c, no_response_opcallback, (void (*)())completed, v,
1049 "remove", id, (char *)0);
1052 int disorder_eclient_moveafter(disorder_eclient *c,
1056 disorder_eclient_no_response *completed,
1062 vector_append(&vec, (char *)"moveafter");
1063 vector_append(&vec, (char *)target);
1064 for(n = 0; n < nids; ++n)
1065 vector_append(&vec, (char *)ids[n]);
1066 stash_command_vector(c, 0/*queuejump*/, no_response_opcallback, completed, v,
1068 disorder_eclient_polled(c, 0);
1072 int disorder_eclient_recent(disorder_eclient *c,
1073 disorder_eclient_queue_response *completed,
1075 return simple(c, queue_response_opcallback, (void (*)())completed, v,
1076 "recent", (char *)0);
1079 int disorder_eclient_queue(disorder_eclient *c,
1080 disorder_eclient_queue_response *completed,
1082 return simple(c, queue_response_opcallback, (void (*)())completed, v,
1083 "queue", (char *)0);
1086 int disorder_eclient_files(disorder_eclient *c,
1087 disorder_eclient_list_response *completed,
1091 return simple(c, list_response_opcallback, (void (*)())completed, v,
1092 "files", dir, re, (char *)0);
1095 int disorder_eclient_dirs(disorder_eclient *c,
1096 disorder_eclient_list_response *completed,
1100 return simple(c, list_response_opcallback, (void (*)())completed, v,
1101 "dirs", dir, re, (char *)0);
1104 int disorder_eclient_playing(disorder_eclient *c,
1105 disorder_eclient_queue_response *completed,
1107 return simple(c, playing_response_opcallback, (void (*)())completed, v,
1108 "playing", (char *)0);
1111 int disorder_eclient_length(disorder_eclient *c,
1112 disorder_eclient_integer_response *completed,
1115 return simple(c, integer_response_opcallback, (void (*)())completed, v,
1116 "length", track, (char *)0);
1119 int disorder_eclient_volume(disorder_eclient *c,
1120 disorder_eclient_volume_response *completed,
1123 char sl[64], sr[64];
1125 if(l < 0 && r < 0) {
1126 return simple(c, volume_response_opcallback, (void (*)())completed, v,
1127 "volume", (char *)0);
1128 } else if(l >= 0 && r >= 0) {
1131 byte_snprintf(sl, sizeof sl, "%d", l);
1132 byte_snprintf(sr, sizeof sr, "%d", r);
1133 return simple(c, volume_response_opcallback, (void (*)())completed, v,
1134 "volume", sl, sr, (char *)0);
1136 assert(!"invalid arguments to disorder_eclient_volume");
1137 return -1; /* gcc is being dim */
1141 int disorder_eclient_enable(disorder_eclient *c,
1142 disorder_eclient_no_response *completed,
1144 return simple(c, no_response_opcallback, (void (*)())completed, v,
1145 "enable", (char *)0);
1148 int disorder_eclient_disable(disorder_eclient *c,
1149 disorder_eclient_no_response *completed,
1151 return simple(c, no_response_opcallback, (void (*)())completed, v,
1152 "disable", (char *)0);
1155 int disorder_eclient_random_enable(disorder_eclient *c,
1156 disorder_eclient_no_response *completed,
1158 return simple(c, no_response_opcallback, (void (*)())completed, v,
1159 "random-enable", (char *)0);
1162 int disorder_eclient_random_disable(disorder_eclient *c,
1163 disorder_eclient_no_response *completed,
1165 return simple(c, no_response_opcallback, (void (*)())completed, v,
1166 "random-disable", (char *)0);
1169 int disorder_eclient_get(disorder_eclient *c,
1170 disorder_eclient_string_response *completed,
1171 const char *track, const char *pref,
1173 return simple(c, string_response_opcallback, (void (*)())completed, v,
1174 "get", track, pref, (char *)0);
1177 int disorder_eclient_set(disorder_eclient *c,
1178 disorder_eclient_no_response *completed,
1179 const char *track, const char *pref,
1182 return simple(c, no_response_opcallback, (void (*)())completed, v,
1183 "set", track, pref, value, (char *)0);
1186 int disorder_eclient_unset(disorder_eclient *c,
1187 disorder_eclient_no_response *completed,
1188 const char *track, const char *pref,
1190 return simple(c, no_response_opcallback, (void (*)())completed, v,
1191 "unset", track, pref, (char *)0);
1194 int disorder_eclient_resolve(disorder_eclient *c,
1195 disorder_eclient_string_response *completed,
1198 return simple(c, string_response_opcallback, (void (*)())completed, v,
1199 "resolve", track, (char *)0);
1202 int disorder_eclient_search(disorder_eclient *c,
1203 disorder_eclient_list_response *completed,
1206 if(!split(terms, 0, SPLIT_QUOTES, 0, 0)) return -1;
1207 return simple(c, list_response_opcallback, (void (*)())completed, v,
1208 "search", terms, (char *)0);
1211 int disorder_eclient_nop(disorder_eclient *c,
1212 disorder_eclient_no_response *completed,
1214 return simple(c, no_response_opcallback, (void (*)())completed, v,
1218 /** @brief Get the last @p max added tracks
1220 * @param completed Called with list
1221 * @param max Number of tracks to get, 0 for all
1222 * @param v Passed to @p completed
1224 * The first track in the list is the most recently added.
1226 int disorder_eclient_new_tracks(disorder_eclient *c,
1227 disorder_eclient_list_response *completed,
1232 sprintf(limit, "%d", max);
1233 return simple(c, list_response_opcallback, (void (*)())completed, v,
1234 "new", limit, (char *)0);
1237 static void rtp_response_opcallback(disorder_eclient *c,
1238 struct operation *op) {
1239 D(("rtp_response_opcallback"));
1240 if(c->rc / 100 == 2) {
1243 char **vec = split(c->line + 4, &nvec, SPLIT_QUOTES, 0, 0);
1245 ((disorder_eclient_list_response *)op->completed)(op->v, nvec, vec);
1248 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
1251 /** @brief Determine the RTP target address
1253 * @param completed Called with address details
1254 * @param v Passed to @p completed
1256 * The address details will be two elements, the first being the hostname and
1257 * the second the service (port).
1259 int disorder_eclient_rtp_address(disorder_eclient *c,
1260 disorder_eclient_list_response *completed,
1262 return simple(c, rtp_response_opcallback, (void (*)())completed, v,
1263 "rtp-address", (char *)0);
1266 /** @brief Get the list of users
1268 * @param completed Called with list of users
1269 * @param v Passed to @p completed
1271 * The user list is not sorted in any particular order.
1273 int disorder_eclient_users(disorder_eclient *c,
1274 disorder_eclient_list_response *completed,
1276 return simple(c, list_response_opcallback, (void (*)())completed, v,
1277 "users", (char *)0);
1280 /** @brief Delete a user
1282 * @param completed Called on completion
1283 * @param user User to delete
1284 * @param v Passed to @p completed
1286 int disorder_eclient_deluser(disorder_eclient *c,
1287 disorder_eclient_no_response *completed,
1290 return simple(c, no_response_opcallback, (void (*)())completed, v,
1291 "deluser", user, (char *)0);
1294 /** @brief Get a user property
1296 * @param completed Called on completion
1297 * @param user User to look up
1298 * @param property Property to look up
1299 * @param v Passed to @p completed
1301 int disorder_eclient_userinfo(disorder_eclient *c,
1302 disorder_eclient_string_response *completed,
1304 const char *property,
1306 return simple(c, string_response_opcallback, (void (*)())completed, v,
1307 "userinfo", user, property, (char *)0);
1310 /** @brief Modify a user property
1312 * @param completed Called on completion
1313 * @param user User to modify
1314 * @param property Property to modify
1315 * @param value New property value
1316 * @param v Passed to @p completed
1318 int disorder_eclient_edituser(disorder_eclient *c,
1319 disorder_eclient_no_response *completed,
1321 const char *property,
1324 return simple(c, no_response_opcallback, (void (*)())completed, v,
1325 "edituser", user, property, value, (char *)0);
1329 /* Log clients ***************************************************************/
1331 /** @brief Monitor the server log
1333 * @param callbacks Functions to call when anything happens
1334 * @param v Passed to @p callbacks functions
1336 * Once a client is being used for logging it cannot be used for anything else.
1337 * There is magic in authuser_opcallback() to re-submit the @c log command
1338 * after reconnection.
1340 * NB that the @c state callback may be called from within this function,
1341 * i.e. not solely later on from the event loop callback.
1343 int disorder_eclient_log(disorder_eclient *c,
1344 const disorder_eclient_log_callbacks *callbacks,
1346 if(c->log_callbacks) return -1;
1347 c->log_callbacks = callbacks;
1349 /* Repoort initial state */
1350 if(c->log_callbacks->state)
1351 c->log_callbacks->state(c->log_v, c->statebits);
1352 stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, v,
1354 disorder_eclient_polled(c, 0);
1358 /* If we get here we've stopped being a log client */
1359 static void log_opcallback(disorder_eclient *c,
1360 struct operation attribute((unused)) *op) {
1361 D(("log_opcallback"));
1362 c->log_callbacks = 0;
1366 /* error callback for log line parsing */
1367 static void logline_error(const char *msg, void *u) {
1368 disorder_eclient *c = u;
1369 protocol_error(c, c->ops, -1, "error parsing log line: %s", msg);
1372 /* process a single log line */
1373 static void logline(disorder_eclient *c, const char *line) {
1378 D(("logline [%s]", line));
1379 vec = split(line, &nvec, SPLIT_QUOTES, logline_error, c);
1380 if(nvec < 2) return; /* probably an error, already
1382 if(sscanf(vec[0], "%"SCNxMAX, &when) != 1) {
1383 /* probably the wrong side of a format change */
1384 protocol_error(c, c->ops, -1, "invalid log timestamp '%s'", vec[0]);
1387 /* TODO: do something with the time */
1388 n = TABLE_FIND(logentry_handlers, struct logentry_handler, name, vec[1]);
1389 if(n < 0) return; /* probably a future command */
1392 if(nvec < logentry_handlers[n].min || nvec > logentry_handlers[n].max)
1394 logentry_handlers[n].handler(c, nvec, vec);
1397 static void logentry_completed(disorder_eclient *c,
1398 int attribute((unused)) nvec, char **vec) {
1399 c->statebits &= ~DISORDER_PLAYING;
1400 if(c->log_callbacks->completed)
1401 c->log_callbacks->completed(c->log_v, vec[0]);
1402 if(c->log_callbacks->state)
1403 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1406 static void logentry_failed(disorder_eclient *c,
1407 int attribute((unused)) nvec, char **vec) {
1408 c->statebits &= ~DISORDER_PLAYING;
1409 if(c->log_callbacks->failed)
1410 c->log_callbacks->failed(c->log_v, vec[0], vec[1]);
1411 if(c->log_callbacks->state)
1412 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1415 static void logentry_moved(disorder_eclient *c,
1416 int attribute((unused)) nvec, char **vec) {
1417 if(c->log_callbacks->moved)
1418 c->log_callbacks->moved(c->log_v, vec[0]);
1421 static void logentry_playing(disorder_eclient *c,
1422 int attribute((unused)) nvec, char **vec) {
1423 c->statebits |= DISORDER_PLAYING;
1424 if(c->log_callbacks->playing)
1425 c->log_callbacks->playing(c->log_v, vec[0], vec[1]);
1426 if(c->log_callbacks->state)
1427 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1430 static void logentry_queue(disorder_eclient *c,
1431 int attribute((unused)) nvec, char **vec) {
1432 struct queue_entry *q;
1434 if(!c->log_callbacks->queue) return;
1435 q = xmalloc(sizeof *q);
1436 if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1438 c->log_callbacks->queue(c->log_v, q);
1441 static void logentry_recent_added(disorder_eclient *c,
1442 int attribute((unused)) nvec, char **vec) {
1443 struct queue_entry *q;
1445 if(!c->log_callbacks->recent_added) return;
1446 q = xmalloc(sizeof *q);
1447 if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1449 c->log_callbacks->recent_added(c->log_v, q);
1452 static void logentry_recent_removed(disorder_eclient *c,
1453 int attribute((unused)) nvec, char **vec) {
1454 if(c->log_callbacks->recent_removed)
1455 c->log_callbacks->recent_removed(c->log_v, vec[0]);
1458 static void logentry_removed(disorder_eclient *c,
1459 int attribute((unused)) nvec, char **vec) {
1460 if(c->log_callbacks->removed)
1461 c->log_callbacks->removed(c->log_v, vec[0], vec[1]);
1464 static void logentry_rescanned(disorder_eclient *c,
1465 int attribute((unused)) nvec,
1466 char attribute((unused)) **vec) {
1467 if(c->log_callbacks->rescanned)
1468 c->log_callbacks->rescanned(c->log_v);
1471 static void logentry_scratched(disorder_eclient *c,
1472 int attribute((unused)) nvec, char **vec) {
1473 c->statebits &= ~DISORDER_PLAYING;
1474 if(c->log_callbacks->scratched)
1475 c->log_callbacks->scratched(c->log_v, vec[0], vec[1]);
1476 if(c->log_callbacks->state)
1477 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1480 static const struct {
1483 const char *disable;
1484 } statestrings[] = {
1485 { DISORDER_PLAYING_ENABLED, "enable_play", "disable_play" },
1486 { DISORDER_RANDOM_ENABLED, "enable_random", "disable_random" },
1487 { DISORDER_TRACK_PAUSED, "pause", "resume" },
1488 { DISORDER_PLAYING, "playing", "completed" },
1489 { DISORDER_PLAYING, 0, "scratched" },
1490 { DISORDER_PLAYING, 0, "failed" },
1492 #define NSTATES (int)(sizeof statestrings / sizeof *statestrings)
1494 static void logentry_state(disorder_eclient *c,
1495 int attribute((unused)) nvec, char **vec) {
1498 for(n = 0; n < NSTATES; ++n)
1499 if(statestrings[n].enable && !strcmp(vec[0], statestrings[n].enable)) {
1500 c->statebits |= statestrings[n].bit;
1502 } else if(statestrings[n].disable && !strcmp(vec[0], statestrings[n].disable)) {
1503 c->statebits &= ~statestrings[n].bit;
1506 if(c->log_callbacks->state)
1507 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1510 static void logentry_volume(disorder_eclient *c,
1511 int attribute((unused)) nvec, char **vec) {
1514 if(!c->log_callbacks->volume) return;
1515 if(xstrtol(&l, vec[0], 0, 10)
1516 || xstrtol(&r, vec[1], 0, 10)
1517 || l < 0 || l > INT_MAX
1518 || r < 0 || r > INT_MAX)
1520 c->log_callbacks->volume(c->log_v, (int)l, (int)r);
1523 /** @brief Convert @p statebits to a string */
1524 char *disorder_eclient_interpret_state(unsigned long statebits) {
1528 static const struct {
1532 { DISORDER_PLAYING_ENABLED, "playing_enabled" },
1533 { DISORDER_RANDOM_ENABLED, "random_enabled" },
1534 { DISORDER_TRACK_PAUSED, "track_paused" },
1535 { DISORDER_PLAYING, "playing" },
1536 { DISORDER_CONNECTED, "connected" },
1538 #define NBITS (sizeof bits / sizeof *bits)
1542 dynstr_append(d, '0');
1543 for(n = 0; n < NBITS; ++n)
1544 if(statebits & bits[n].bit) {
1546 dynstr_append(d, '|');
1547 dynstr_append_string(d, bits[n].name);
1548 statebits ^= bits[n].bit;
1554 dynstr_append(d, '|');
1555 sprintf(s, "%#lx", statebits);
1556 dynstr_append_string(d, s);
1558 dynstr_terminate(d);
1567 indent-tabs-mode:nil