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 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU 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, see <http://www.gnu.org/licenses/>.
18 /** @file lib/eclient.c
19 * @brief Client code for event-driven programs
24 #include <sys/types.h>
25 #include <sys/socket.h>
26 #include <netinet/in.h>
37 #include "configuration.h"
44 #include "inputline.h"
51 #include "client-common.h"
53 /* TODO: more commands */
55 /** @brief How often to send data to the server when receiving logs */
56 #define LOG_PROD_INTERVAL 10
58 /* Types *********************************************************************/
60 /** @brief Client state */
62 state_disconnected, /**< @brief not connected */
63 state_connecting, /**< @brief waiting for connect() */
64 state_connected, /**< @brief connected but not authenticated */
65 state_idle, /**< @brief not doing anything */
66 state_cmdresponse, /**< @brief waiting for command resonse */
67 state_body, /**< @brief accumulating body */
68 state_log, /**< @brief monitoring log */
71 /** @brief Names for @ref client_state */
72 static const char *const states[] = {
82 struct operation; /* forward decl */
84 /** @brief Type of an operation callback */
85 typedef void operation_callback(disorder_eclient *c, struct operation *op);
87 /** @brief A pending operation.
89 * This can be either a command or part of the authentication protocol. In the
90 * former case new commands are appended to the list, in the latter case they
91 * are inserted at the front. */
93 struct operation *next; /**< @brief next operation */
94 char *cmd; /**< @brief command to send or 0 */
95 operation_callback *opcallback; /**< @brief internal completion callback */
96 void (*completed)(); /**< @brief user completion callback or 0 */
97 void *v; /**< @brief data for COMPLETED */
98 disorder_eclient *client; /**< @brief owning client */
100 /** @brief true if sent to server
102 * This is cleared by disorder_eclient_close(), forcing all queued
103 * commands to be transparently resent.
108 /** @brief Client structure */
109 struct disorder_eclient {
111 int fd; /**< @brief connection to server */
112 enum client_state state; /**< @brief current state */
113 int authenticated; /**< @brief true when authenicated */
114 struct dynstr output; /**< @brief output buffer */
115 struct dynstr input; /**< @brief input buffer */
116 int eof; /**< @brief input buffer is at EOF */
117 const disorder_eclient_callbacks *callbacks; /**< @brief error callbacks */
118 void *u; /**< @brief user data */
119 struct operation *ops; /**< @brief queue of operations */
120 struct operation **opstail; /**< @brief queue tail */
121 /* accumulated response */
122 int rc; /**< @brief response code */
123 char *line; /**< @brief complete line */
124 struct vector vec; /**< @brief body */
126 const disorder_eclient_log_callbacks *log_callbacks;
127 /**< @brief log callbacks
129 * Once disorder_eclient_log() has been issued this is always set. When we
130 * re-connect it is checked to re-issue the log command.
132 void *log_v; /**< @brief user data */
133 unsigned long statebits; /**< @brief latest state */
136 /**< @brief last time we sent a prod
138 * When we are receiving log data we send a "prod" byte to the server from
139 * time to time so that we detect broken connections reasonably quickly. The
140 * server just ignores these bytes.
143 /** @brief Protocol version */
146 /** @brief True if enabled */
150 /* Forward declarations ******************************************************/
152 static int start_connect(disorder_eclient *c);
153 static void process_line(disorder_eclient *c, char *line);
154 static void maybe_connected(disorder_eclient *c);
155 static void authbanner_opcallback(disorder_eclient *c,
156 struct operation *op);
157 static void authuser_opcallback(disorder_eclient *c,
158 struct operation *op);
159 static void complete(disorder_eclient *c);
160 static void send_output(disorder_eclient *c);
161 static void put(disorder_eclient *c, const char *s, size_t n);
162 static void read_input(disorder_eclient *c);
163 static void stash_command(disorder_eclient *c,
165 operation_callback *opcallback,
170 static void log_opcallback(disorder_eclient *c, struct operation *op);
171 static void logline(disorder_eclient *c, const char *line);
172 static void logentry_completed(disorder_eclient *c, int nvec, char **vec);
173 static void logentry_failed(disorder_eclient *c, int nvec, char **vec);
174 static void logentry_moved(disorder_eclient *c, int nvec, char **vec);
175 static void logentry_playing(disorder_eclient *c, int nvec, char **vec);
176 static void logentry_queue(disorder_eclient *c, int nvec, char **vec);
177 static void logentry_recent_added(disorder_eclient *c, int nvec, char **vec);
178 static void logentry_recent_removed(disorder_eclient *c, int nvec, char **vec);
179 static void logentry_removed(disorder_eclient *c, int nvec, char **vec);
180 static void logentry_scratched(disorder_eclient *c, int nvec, char **vec);
181 static void logentry_state(disorder_eclient *c, int nvec, char **vec);
182 static void logentry_volume(disorder_eclient *c, int nvec, char **vec);
183 static void logentry_rescanned(disorder_eclient *c, int nvec, char **vec);
184 static void logentry_user_add(disorder_eclient *c, int nvec, char **vec);
185 static void logentry_user_confirm(disorder_eclient *c, int nvec, char **vec);
186 static void logentry_user_delete(disorder_eclient *c, int nvec, char **vec);
187 static void logentry_user_edit(disorder_eclient *c, int nvec, char **vec);
188 static void logentry_rights_changed(disorder_eclient *c, int nvec, char **vec);
190 /* Tables ********************************************************************/
192 /** @brief One possible log entry */
193 struct logentry_handler {
194 const char *name; /**< @brief Entry name */
195 int min; /**< @brief Minimum arguments */
196 int max; /**< @brief Maximum arguments */
197 void (*handler)(disorder_eclient *c,
199 char **vec); /**< @brief Handler function */
202 /** @brief Table for parsing log entries */
203 static const struct logentry_handler logentry_handlers[] = {
204 #define LE(X, MIN, MAX) { #X, MIN, MAX, logentry_##X }
209 LE(queue, 2, INT_MAX),
210 LE(recent_added, 2, INT_MAX),
211 LE(recent_removed, 1, 1),
214 LE(rights_changed, 1, 1),
218 LE(user_confirm, 1, 1),
219 LE(user_delete, 1, 1),
224 /* Setup and teardown ********************************************************/
226 /** @brief Create a new client
228 * Does NOT connect the client - connections are made (and re-made) on demand.
230 disorder_eclient *disorder_eclient_new(const disorder_eclient_callbacks *cb,
232 disorder_eclient *c = xmalloc(sizeof *c);
233 D(("disorder_eclient_new"));
237 c->opstail = &c->ops;
239 vector_init(&c->vec);
240 dynstr_init(&c->input);
241 dynstr_init(&c->output);
245 /** @brief Disconnect a client
246 * @param c Client to disconnect
248 * NB that this routine just disconnnects the TCP connection. It does not
249 * destroy the client! If you continue to use it then it will attempt to
252 void disorder_eclient_close(disorder_eclient *c) {
253 struct operation *op;
255 D(("disorder_eclient_close"));
257 D(("disorder_eclient_close closing fd %d", c->fd));
258 c->callbacks->poll(c->u, c, c->fd, 0);
261 c->state = state_disconnected;
267 c->authenticated = 0;
268 /* We'll need to resend all operations */
269 for(op = c->ops; op; op = op->next)
271 /* Drop our use a hint that we're disconnected */
272 if(c->log_callbacks && c->log_callbacks->state)
273 c->log_callbacks->state(c->log_v, c->statebits);
276 /** @brief Permit new connection activity */
277 void disorder_eclient_enable_connect(disorder_eclient *c) {
281 /** @brief Suppress new connection activity */
282 void disorder_eclient_disable_connect(disorder_eclient *c) {
286 /** @brief Return current state */
287 unsigned long disorder_eclient_state(const disorder_eclient *c) {
288 return c->statebits | (c->state > state_connected ? DISORDER_CONNECTED : 0);
291 /* Error reporting ***********************************************************/
293 /** @brief called when a connection error occurs
295 * After this called we will be disconnected (by disorder_eclient_close()),
296 * so there will be a reconnection before any commands can be sent.
298 static int comms_error(disorder_eclient *c, const char *fmt, ...) {
304 byte_xvasprintf(&s, fmt, ap);
306 disorder_eclient_close(c);
307 c->callbacks->comms_error(c->u, s);
311 /** @brief called when the server reports an error */
312 static int protocol_error(disorder_eclient *c, struct operation *op,
313 int code, const char *fmt, ...) {
317 D(("protocol_error"));
319 byte_xvasprintf(&s, fmt, ap);
321 c->callbacks->protocol_error(c->u, op->v, code, s);
325 /* State machine *************************************************************/
327 /** @brief Called when there's something to do
329 * @param mode bitmap of @ref DISORDER_POLL_READ and/or @ref DISORDER_POLL_WRITE.
331 * This should be called from by your code when the file descriptor is readable
332 * or writable (as requested by the @c poll callback, see @ref
333 * disorder_eclient_callbacks) and in any case from time to time (with @p mode
334 * = 0) to allow for retries to work.
336 void disorder_eclient_polled(disorder_eclient *c, unsigned mode) {
337 struct operation *op;
340 D(("disorder_eclient_polled fd=%d state=%s mode=[%s %s]",
341 c->fd, states[c->state],
342 mode & DISORDER_POLL_READ ? "READ" : "",
343 mode & DISORDER_POLL_WRITE ? "WRITE" : ""));
344 /* The pattern here is to check each possible state in turn and try to
345 * advance (though on error we might go back). If we advance we leave open
346 * the possibility of falling through to the next state, but we set the mode
347 * bits to 0, to avoid false positives (which matter more in some cases than
350 if(c->state == state_disconnected) {
351 D(("state_disconnected"));
352 /* If there is no password yet then we cannot connect */
353 if(!config->password) {
354 comms_error(c, "no password is configured");
358 /* Only try to connect if enabled */
361 /* might now be state_disconnected (on error), state_connecting (slow
362 * connect) or state_connected (fast connect). If state_disconnected then
363 * we just rely on a periodic callback from the event loop sometime. */
367 if(c->state == state_connecting && mode) {
368 D(("state_connecting"));
370 /* Might be state_disconnected (on error) or state_connected (on success).
371 * In the former case we rely on the event loop for a periodic callback to
376 if(c->state == state_connected) {
377 D(("state_connected"));
378 /* We just connected. Initiate the authentication protocol. */
379 stash_command(c, 1/*queuejump*/, authbanner_opcallback,
380 0/*completed*/, 0/*v*/, 0/*cmd*/);
381 /* We never stay is state_connected very long. We could in principle jump
382 * straight to state_cmdresponse since there's actually no command to
383 * send, but that would arguably be cheating. */
384 c->state = state_idle;
387 if(c->state == state_idle) {
389 /* We are connected, and have finished any command we set off, look for
393 if(c->authenticated) {
394 /* Transmit all unsent operations */
395 for(op = c->ops; op; op = op->next) {
397 put(c, op->cmd, strlen(op->cmd));
402 /* Just send the head operation */
403 if(c->ops->cmd && !c->ops->sent) {
404 put(c, c->ops->cmd, strlen(c->ops->cmd));
408 /* Awaiting response for the operation at the head of the list */
409 c->state = state_cmdresponse;
412 c->callbacks->report(c->u, 0);
415 /* Queue up a byte to send */
416 if(c->state == state_log
417 && c->output.nvec == 0
418 && time(&now) - c->last_prod > LOG_PROD_INTERVAL) {
423 if(c->state == state_cmdresponse
424 || c->state == state_body
425 || c->state == state_log) {
426 D(("state_%s", states[c->state]));
427 /* We are awaiting a response */
428 if(mode & DISORDER_POLL_WRITE) send_output(c);
429 if(mode & DISORDER_POLL_READ) read_input(c);
430 /* There are a couple of reasons we might want to re-enter the state
431 * machine from the top. state_idle is obvious: there may be further
432 * commands to process. Re-entering on state_disconnected means that we
433 * immediately retry connection if a comms error occurs during a command.
434 * This is different to the case where a connection fails, where we await a
435 * spontaneous call to initiate the retry. */
437 case state_disconnected: /* lost connection */
438 case state_idle: /* completed a command */
440 disorder_eclient_polled(c, 0);
447 /* Figure out what to set the mode to */
449 case state_disconnected:
450 D(("state_disconnected (2)"));
451 /* Probably an error occurred. Await a retry. */
454 case state_connecting:
455 D(("state_connecting (2)"));
456 /* Waiting for connect to complete */
457 mode = DISORDER_POLL_READ|DISORDER_POLL_WRITE;
459 case state_connected:
460 D(("state_connected (2)"));
461 assert(!"should never be in state_connected here");
464 D(("state_idle (2)"));
465 /* Connected but nothing to do. */
468 case state_cmdresponse:
471 D(("state_%s (2)", states[c->state]));
472 /* Gathering a response. Wait for input. */
473 mode = DISORDER_POLL_READ;
474 /* Flush any pending output. */
475 if(c->output.nvec) mode |= DISORDER_POLL_WRITE;
478 D(("fd=%d new mode [%s %s]",
480 mode & DISORDER_POLL_READ ? "READ" : "",
481 mode & DISORDER_POLL_WRITE ? "WRITE" : ""));
482 if(c->fd != -1) c->callbacks->poll(c->u, c, c->fd, mode);
485 /** @brief Called to start connecting */
486 static int start_connect(disorder_eclient *c) {
490 D(("start_connect"));
491 if((len = find_server(config, &sa, &c->ident)) == (socklen_t)-1)
492 return comms_error(c, "cannot look up server"); /* TODO better error */
497 if((c->fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
498 return comms_error(c, "socket: %s", strerror(errno));
502 if(connect(c->fd, sa, len) < 0) {
506 c->state = state_connecting;
507 /* We are called from _polled so the state machine will get to do its
511 /* Signal the error to the caller. */
512 return comms_error(c, "connecting to %s: %s", c->ident, strerror(errno));
515 c->state = state_connected;
519 /** @brief Called when poll triggers while waiting for a connection */
520 static void maybe_connected(disorder_eclient *c) {
521 /* We either connected, or got an error. */
523 socklen_t len = sizeof err;
525 D(("maybe_connected"));
526 /* Work around over-enthusiastic error slippage */
527 if(getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0)
530 /* The connection failed */
531 comms_error(c, "connecting to %s: %s", c->ident, strerror(err));
532 /* sets state_disconnected */
536 /* The connection succeeded */
537 c->state = state_connected;
538 byte_xasprintf(&r, "connected to %s", c->ident);
539 c->callbacks->report(c->u, r);
540 /* If this is a log client we expect to get a bunch of updates from the
541 * server straight away */
545 /* Authentication ************************************************************/
547 /** @brief Called with the greeting from the server */
548 static void authbanner_opcallback(disorder_eclient *c,
549 struct operation *op) {
551 const unsigned char *nonce;
555 const char *protocol, *algorithm, *challenge;
557 D(("authbanner_opcallback"));
559 || !(rvec = split(c->line + 4, &nrvec, SPLIT_QUOTES, 0, 0))
561 /* Banner told us to go away, or was malformed. We cannot proceed. */
562 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
563 disorder_eclient_close(c);
583 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
584 disorder_eclient_close(c);
587 c->protocol = atoi(protocol);
588 if(c->protocol < 1 || c->protocol > 2) {
589 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
590 disorder_eclient_close(c);
593 nonce = unhex(challenge, &nonce_len);
594 res = authhash(nonce, nonce_len, config->password, algorithm);
596 protocol_error(c, op, c->rc, "%s: unknown authentication algorithm '%s'",
597 c->ident, algorithm);
598 disorder_eclient_close(c);
601 stash_command(c, 1/*queuejump*/, authuser_opcallback, 0/*completed*/, 0/*v*/,
602 "user", quoteutf8(config->username), quoteutf8(res),
606 /** @brief Called with the response to the @c user command */
607 static void authuser_opcallback(disorder_eclient *c,
608 struct operation *op) {
611 D(("authuser_opcallback"));
612 if(c->rc / 100 != 2) {
613 /* Wrong password or something. We cannot proceed. */
614 protocol_error(c, op, c->rc, "%s: %s", c->ident, c->line);
616 disorder_eclient_close(c);
619 /* OK, we're authenticated now. */
620 c->authenticated = 1;
621 byte_xasprintf(&r, "authenticated with %s", c->ident);
622 c->callbacks->report(c->u, r);
623 if(c->log_callbacks && !(c->ops && c->ops->opcallback == log_opcallback))
624 /* We are a log client, switch to logging mode */
625 stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, c->log_v,
629 /* Output ********************************************************************/
631 /* Chop N bytes off the front of a dynstr */
632 static void consume(struct dynstr *d, int n) {
633 D(("consume %d", n));
634 assert(d->nvec >= n);
635 memmove(d->vec, d->vec + n, d->nvec - n);
639 /* Write some bytes */
640 static void put(disorder_eclient *c, const char *s, size_t n) {
641 D(("put %d %.*s", c->fd, (int)n, s));
642 dynstr_append_bytes(&c->output, s, n);
645 /* Called when we can write to our FD, or at any other time */
646 static void send_output(disorder_eclient *c) {
649 D(("send_output %d bytes pending", c->output.nvec));
650 if(c->state > state_connecting && c->output.nvec) {
651 n = write(c->fd, c->output.vec, c->output.nvec);
658 comms_error(c, "writing to %s: %s", c->ident, strerror(errno));
662 consume(&c->output, n);
666 /* Input *********************************************************************/
668 /* Called when c->fd might be readable, or at any other time */
669 static void read_input(disorder_eclient *c) {
674 D(("read_input in state %s", states[c->state]));
675 if(c->state <= state_connected) return; /* ignore bogus calls */
676 /* read some more input */
677 n = read(c->fd, buffer, sizeof buffer);
684 comms_error(c, "reading from %s: %s", c->ident, strerror(errno));
687 return; /* no new input to process */
689 D(("read %d bytes: [%.*s]", n, n, buffer));
690 dynstr_append_bytes(&c->input, buffer, n);
693 /* might have more than one line to process */
694 while(c->state > state_connecting
695 && (nl = memchr(c->input.vec, '\n', c->input.nvec))) {
696 process_line(c, xstrndup(c->input.vec, nl - c->input.vec));
697 /* we might have disconnected along the way, which zogs the input buffer */
698 if(c->state > state_connecting)
699 consume(&c->input, (nl - c->input.vec) + 1);
702 comms_error(c, "reading from %s: server disconnected", c->ident);
703 c->authenticated = 0;
707 /* called with a line that has just been read */
708 static void process_line(disorder_eclient *c, char *line) {
709 D(("process_line %d [%s]", c->fd, line));
711 case state_cmdresponse:
712 /* This is the first line of a response */
713 if(!(line[0] >= '0' && line[0] <= '9'
714 && line[1] >= '0' && line[1] <= '9'
715 && line[2] >= '0' && line[2] <= '9'
717 fatal(0, "invalid response from server: %s", line);
718 c->rc = (line[0] * 10 + line[1]) * 10 + line[2] - 111 * '0';
722 /* We need to collect the body. */
723 c->state = state_body;
724 vector_init(&c->vec);
727 assert(c->log_callbacks != 0);
728 if(c->log_callbacks->connected)
729 c->log_callbacks->connected(c->log_v);
730 c->state = state_log;
733 /* We've got the whole response. Go into the idle state so the state
734 * machine knows we're done and then call the operation callback. */
740 if(strcmp(line, ".")) {
741 /* A line from the body */
742 vector_append(&c->vec, line + (line[0] == '.'));
744 /* End of the body. */
745 vector_terminate(&c->vec);
750 if(strcmp(line, ".")) {
751 logline(c, line + (line[0] == '.'));
756 assert(!"wrong state for location");
761 /* Called when an operation completes */
762 static void complete(disorder_eclient *c) {
763 struct operation *op;
766 /* Pop the operation off the queue */
769 if(c->opstail == &op->next)
770 c->opstail = &c->ops;
771 /* If we've pipelined a command ahead then we go straight to cmdresponser.
772 * Otherwise we go to idle, which will arrange further sends. */
773 c->state = c->ops && c->ops->sent ? state_cmdresponse : state_idle;
774 op->opcallback(c, op);
775 /* Note that we always call the opcallback even on error, though command
776 * opcallbacks generally always do the same error handling, i.e. just call
777 * protocol_error(). It's the auth* opcallbacks that have different
781 /* Operation setup ***********************************************************/
783 static void stash_command_vector(disorder_eclient *c,
785 operation_callback *opcallback,
790 struct operation *op = xmalloc(sizeof *op);
796 for(n = 0; n < ncmd; ++n) {
798 dynstr_append(&d, ' ');
799 dynstr_append_string(&d, quoteutf8(cmd[n]));
801 dynstr_append(&d, '\n');
802 dynstr_terminate(&d);
805 op->cmd = 0; /* usually, awaiting challenge */
806 op->opcallback = opcallback;
807 op->completed = completed;
811 assert(op->sent == 0);
813 /* Authentication operations jump the queue of useful commands */
816 if(c->opstail == &c->ops)
817 c->opstail = &op->next;
818 for(op = c->ops; op; op = op->next)
822 c->opstail = &op->next;
826 static void vstash_command(disorder_eclient *c,
828 operation_callback *opcallback,
831 const char *cmd, va_list ap) {
835 D(("vstash_command %s", cmd ? cmd : "NULL"));
838 vector_append(&vec, (char *)cmd);
839 while((arg = va_arg(ap, char *)))
840 vector_append(&vec, arg);
841 stash_command_vector(c, queuejump, opcallback, completed, v,
844 stash_command_vector(c, queuejump, opcallback, completed, v, 0, 0);
847 static void stash_command(disorder_eclient *c,
849 operation_callback *opcallback,
857 vstash_command(c, queuejump, opcallback, completed, v, cmd, ap);
861 /* Command support ***********************************************************/
863 static const char *errorstring(disorder_eclient *c) {
866 byte_xasprintf(&s, "%s: %s: %d", c->ident, c->line, c->rc);
870 /* for commands with a quoted string response */
871 static void string_response_opcallback(disorder_eclient *c,
872 struct operation *op) {
873 disorder_eclient_string_response *completed
874 = (disorder_eclient_string_response *)op->completed;
876 D(("string_response_callback"));
877 if(c->rc / 100 == 2 || c->rc == 555) {
880 completed(op->v, NULL, NULL);
881 else if(c->protocol >= 2) {
882 char **rr = split(c->line + 4, 0, SPLIT_QUOTES, 0, 0);
885 completed(op->v, NULL, *rr);
887 /* TODO error message a is bit lame but generally indicates a server
888 * bug rather than anything the user can address */
889 completed(op->v, "error parsing response", NULL);
891 completed(op->v, NULL, c->line + 4);
894 completed(op->v, errorstring(c), NULL);
897 /* for commands with a simple integer response */
898 static void integer_response_opcallback(disorder_eclient *c,
899 struct operation *op) {
900 disorder_eclient_integer_response *completed
901 = (disorder_eclient_integer_response *)op->completed;
903 D(("string_response_callback"));
904 if(c->rc / 100 == 2) {
908 e = xstrtol(&n, c->line + 4, 0, 10);
910 completed(op->v, strerror(e), 0);
912 completed(op->v, 0, n);
914 completed(op->v, errorstring(c), 0);
917 /* for commands with no response */
918 static void no_response_opcallback(disorder_eclient *c,
919 struct operation *op) {
920 disorder_eclient_no_response *completed
921 = (disorder_eclient_no_response *)op->completed;
923 D(("no_response_callback"));
925 completed(op->v, NULL);
927 completed(op->v, errorstring(c));
930 /* error callback for queue_unmarshall */
931 static void eclient_queue_error(const char *msg,
933 struct operation *op = u;
935 /* TODO don't use protocol_error here */
936 protocol_error(op->client, op, -1, "error parsing queue entry: %s", msg);
939 /* for commands that expect a queue dump */
940 static void queue_response_opcallback(disorder_eclient *c,
941 struct operation *op) {
942 disorder_eclient_queue_response *const completed
943 = (disorder_eclient_queue_response *)op->completed;
945 int parse_failed = 0;
946 struct queue_entry *q, *qh = 0, **qtail = &qh, *qlast = 0;
948 D(("queue_response_callback"));
949 if(c->rc / 100 == 2) {
950 /* parse the queue */
951 for(n = 0; n < c->vec.nvec; ++n) {
952 q = xmalloc(sizeof *q);
953 D(("queue_unmarshall %s", c->vec.vec[n]));
954 if(!queue_unmarshall(q, c->vec.vec[n], NULL, op)) {
962 /* Currently we pass the partial queue to the callback along with the
963 * error. This might not be very useful in practice... */
965 completed(op->v, "cannot parse result", qh);
967 completed(op->v, 0, qh);
969 completed(op->v, errorstring(c), 0);
973 static void playing_response_opcallback(disorder_eclient *c,
974 struct operation *op) {
975 disorder_eclient_queue_response *const completed
976 = (disorder_eclient_queue_response *)op->completed;
977 struct queue_entry *q;
979 D(("playing_response_callback"));
980 if(c->rc / 100 == 2) {
983 if(queue_unmarshall(q = xmalloc(sizeof *q), c->line + 4,
985 completed(op->v, "cannot parse result", 0);
987 completed(op->v, 0, q);
990 completed(op->v, 0, 0);
993 completed(op->v, errorstring(c), 0);
997 completed(op->v, errorstring(c), 0);
1000 /* for commands that expect a list of some sort */
1001 static void list_response_opcallback(disorder_eclient *c,
1002 struct operation *op) {
1003 disorder_eclient_list_response *const completed =
1004 (disorder_eclient_list_response *)op->completed;
1006 D(("list_response_callback"));
1007 if(c->rc / 100 == 2)
1008 completed(op->v, NULL, c->vec.nvec, c->vec.vec);
1010 completed(op->v, errorstring(c), 0, 0);
1014 static void volume_response_opcallback(disorder_eclient *c,
1015 struct operation *op) {
1016 disorder_eclient_volume_response *completed
1017 = (disorder_eclient_volume_response *)op->completed;
1020 D(("volume_response_callback"));
1021 if(c->rc / 100 == 2) {
1023 if(sscanf(c->line + 4, "%d %d", &l, &r) != 2 || l < 0 || r < 0)
1024 completed(op->v, "cannot parse volume response", 0, 0);
1026 completed(op->v, 0, l, r);
1029 completed(op->v, errorstring(c), 0, 0);
1032 static int simple(disorder_eclient *c,
1033 operation_callback *opcallback,
1034 void (*completed)(),
1036 const char *cmd, ...) {
1040 vstash_command(c, 0/*queuejump*/, opcallback, completed, v, cmd, ap);
1042 /* Give the state machine a kick, since we might be in state_idle */
1043 disorder_eclient_polled(c, 0);
1047 /* Commands ******************************************************************/
1049 int disorder_eclient_version(disorder_eclient *c,
1050 disorder_eclient_string_response *completed,
1052 return simple(c, string_response_opcallback, (void (*)())completed, v,
1053 "version", (char *)0);
1056 int disorder_eclient_namepart(disorder_eclient *c,
1057 disorder_eclient_string_response *completed,
1059 const char *context,
1062 return simple(c, string_response_opcallback, (void (*)())completed, v,
1063 "part", track, context, part, (char *)0);
1066 int disorder_eclient_play(disorder_eclient *c,
1068 disorder_eclient_no_response *completed,
1070 return simple(c, no_response_opcallback, (void (*)())completed, v,
1071 "play", track, (char *)0);
1074 int disorder_eclient_pause(disorder_eclient *c,
1075 disorder_eclient_no_response *completed,
1077 return simple(c, no_response_opcallback, (void (*)())completed, v,
1078 "pause", (char *)0);
1081 int disorder_eclient_resume(disorder_eclient *c,
1082 disorder_eclient_no_response *completed,
1084 return simple(c, no_response_opcallback, (void (*)())completed, v,
1085 "resume", (char *)0);
1088 int disorder_eclient_scratch(disorder_eclient *c,
1090 disorder_eclient_no_response *completed,
1092 return simple(c, no_response_opcallback, (void (*)())completed, v,
1093 "scratch", id, (char *)0);
1096 int disorder_eclient_scratch_playing(disorder_eclient *c,
1097 disorder_eclient_no_response *completed,
1099 return disorder_eclient_scratch(c, 0, completed, v);
1102 int disorder_eclient_remove(disorder_eclient *c,
1104 disorder_eclient_no_response *completed,
1106 return simple(c, no_response_opcallback, (void (*)())completed, v,
1107 "remove", id, (char *)0);
1110 int disorder_eclient_moveafter(disorder_eclient *c,
1114 disorder_eclient_no_response *completed,
1120 vector_append(&vec, (char *)"moveafter");
1121 vector_append(&vec, (char *)target);
1122 for(n = 0; n < nids; ++n)
1123 vector_append(&vec, (char *)ids[n]);
1124 stash_command_vector(c, 0/*queuejump*/, no_response_opcallback, completed, v,
1126 disorder_eclient_polled(c, 0);
1130 int disorder_eclient_recent(disorder_eclient *c,
1131 disorder_eclient_queue_response *completed,
1133 return simple(c, queue_response_opcallback, (void (*)())completed, v,
1134 "recent", (char *)0);
1137 int disorder_eclient_queue(disorder_eclient *c,
1138 disorder_eclient_queue_response *completed,
1140 return simple(c, queue_response_opcallback, (void (*)())completed, v,
1141 "queue", (char *)0);
1144 int disorder_eclient_files(disorder_eclient *c,
1145 disorder_eclient_list_response *completed,
1149 return simple(c, list_response_opcallback, (void (*)())completed, v,
1150 "files", dir, re, (char *)0);
1153 int disorder_eclient_dirs(disorder_eclient *c,
1154 disorder_eclient_list_response *completed,
1158 return simple(c, list_response_opcallback, (void (*)())completed, v,
1159 "dirs", dir, re, (char *)0);
1162 int disorder_eclient_playing(disorder_eclient *c,
1163 disorder_eclient_queue_response *completed,
1165 return simple(c, playing_response_opcallback, (void (*)())completed, v,
1166 "playing", (char *)0);
1169 int disorder_eclient_length(disorder_eclient *c,
1170 disorder_eclient_integer_response *completed,
1173 return simple(c, integer_response_opcallback, (void (*)())completed, v,
1174 "length", track, (char *)0);
1177 int disorder_eclient_volume(disorder_eclient *c,
1178 disorder_eclient_volume_response *completed,
1181 char sl[64], sr[64];
1183 if(l < 0 && r < 0) {
1184 return simple(c, volume_response_opcallback, (void (*)())completed, v,
1185 "volume", (char *)0);
1186 } else if(l >= 0 && r >= 0) {
1189 byte_snprintf(sl, sizeof sl, "%d", l);
1190 byte_snprintf(sr, sizeof sr, "%d", r);
1191 return simple(c, volume_response_opcallback, (void (*)())completed, v,
1192 "volume", sl, sr, (char *)0);
1194 assert(!"invalid arguments to disorder_eclient_volume");
1195 return -1; /* gcc is being dim */
1199 int disorder_eclient_enable(disorder_eclient *c,
1200 disorder_eclient_no_response *completed,
1202 return simple(c, no_response_opcallback, (void (*)())completed, v,
1203 "enable", (char *)0);
1206 int disorder_eclient_disable(disorder_eclient *c,
1207 disorder_eclient_no_response *completed,
1209 return simple(c, no_response_opcallback, (void (*)())completed, v,
1210 "disable", (char *)0);
1213 int disorder_eclient_random_enable(disorder_eclient *c,
1214 disorder_eclient_no_response *completed,
1216 return simple(c, no_response_opcallback, (void (*)())completed, v,
1217 "random-enable", (char *)0);
1220 int disorder_eclient_random_disable(disorder_eclient *c,
1221 disorder_eclient_no_response *completed,
1223 return simple(c, no_response_opcallback, (void (*)())completed, v,
1224 "random-disable", (char *)0);
1227 int disorder_eclient_get(disorder_eclient *c,
1228 disorder_eclient_string_response *completed,
1229 const char *track, const char *pref,
1231 return simple(c, string_response_opcallback, (void (*)())completed, v,
1232 "get", track, pref, (char *)0);
1235 int disorder_eclient_set(disorder_eclient *c,
1236 disorder_eclient_no_response *completed,
1237 const char *track, const char *pref,
1240 return simple(c, no_response_opcallback, (void (*)())completed, v,
1241 "set", track, pref, value, (char *)0);
1244 int disorder_eclient_unset(disorder_eclient *c,
1245 disorder_eclient_no_response *completed,
1246 const char *track, const char *pref,
1248 return simple(c, no_response_opcallback, (void (*)())completed, v,
1249 "unset", track, pref, (char *)0);
1252 int disorder_eclient_resolve(disorder_eclient *c,
1253 disorder_eclient_string_response *completed,
1256 return simple(c, string_response_opcallback, (void (*)())completed, v,
1257 "resolve", track, (char *)0);
1260 int disorder_eclient_search(disorder_eclient *c,
1261 disorder_eclient_list_response *completed,
1264 if(!split(terms, 0, SPLIT_QUOTES, 0, 0)) return -1;
1265 return simple(c, list_response_opcallback, (void (*)())completed, v,
1266 "search", terms, (char *)0);
1269 int disorder_eclient_nop(disorder_eclient *c,
1270 disorder_eclient_no_response *completed,
1272 return simple(c, no_response_opcallback, (void (*)())completed, v,
1276 /** @brief Get the last @p max added tracks
1278 * @param completed Called with list
1279 * @param max Number of tracks to get, 0 for all
1280 * @param v Passed to @p completed
1282 * The first track in the list is the most recently added.
1284 int disorder_eclient_new_tracks(disorder_eclient *c,
1285 disorder_eclient_list_response *completed,
1290 sprintf(limit, "%d", max);
1291 return simple(c, list_response_opcallback, (void (*)())completed, v,
1292 "new", limit, (char *)0);
1295 static void rtp_response_opcallback(disorder_eclient *c,
1296 struct operation *op) {
1297 disorder_eclient_list_response *const completed =
1298 (disorder_eclient_list_response *)op->completed;
1299 D(("rtp_response_opcallback"));
1300 if(c->rc / 100 == 2) {
1302 char **vec = split(c->line + 4, &nvec, SPLIT_QUOTES, 0, 0);
1305 completed(op->v, NULL, nvec, vec);
1307 completed(op->v, "error parsing response", 0, 0);
1309 completed(op->v, errorstring(c), 0, 0);
1312 /** @brief Determine the RTP target address
1314 * @param completed Called with address details
1315 * @param v Passed to @p completed
1317 * The address details will be two elements, the first being the hostname and
1318 * the second the service (port).
1320 int disorder_eclient_rtp_address(disorder_eclient *c,
1321 disorder_eclient_list_response *completed,
1323 return simple(c, rtp_response_opcallback, (void (*)())completed, v,
1324 "rtp-address", (char *)0);
1327 /** @brief Get the list of users
1329 * @param completed Called with list of users
1330 * @param v Passed to @p completed
1332 * The user list is not sorted in any particular order.
1334 int disorder_eclient_users(disorder_eclient *c,
1335 disorder_eclient_list_response *completed,
1337 return simple(c, list_response_opcallback, (void (*)())completed, v,
1338 "users", (char *)0);
1341 /** @brief Delete a user
1343 * @param completed Called on completion
1344 * @param user User to delete
1345 * @param v Passed to @p completed
1347 int disorder_eclient_deluser(disorder_eclient *c,
1348 disorder_eclient_no_response *completed,
1351 return simple(c, no_response_opcallback, (void (*)())completed, v,
1352 "deluser", user, (char *)0);
1355 /** @brief Get a user property
1357 * @param completed Called on completion
1358 * @param user User to look up
1359 * @param property Property to look up
1360 * @param v Passed to @p completed
1362 int disorder_eclient_userinfo(disorder_eclient *c,
1363 disorder_eclient_string_response *completed,
1365 const char *property,
1367 return simple(c, string_response_opcallback, (void (*)())completed, v,
1368 "userinfo", user, property, (char *)0);
1371 /** @brief Modify a user property
1373 * @param completed Called on completion
1374 * @param user User to modify
1375 * @param property Property to modify
1376 * @param value New property value
1377 * @param v Passed to @p completed
1379 int disorder_eclient_edituser(disorder_eclient *c,
1380 disorder_eclient_no_response *completed,
1382 const char *property,
1385 return simple(c, no_response_opcallback, (void (*)())completed, v,
1386 "edituser", user, property, value, (char *)0);
1389 /** @brief Create a new user
1391 * @param completed Called on completion
1392 * @param user User to create
1393 * @param password Initial password
1394 * @param rights Initial rights or NULL
1395 * @param v Passed to @p completed
1397 int disorder_eclient_adduser(disorder_eclient *c,
1398 disorder_eclient_no_response *completed,
1400 const char *password,
1403 return simple(c, no_response_opcallback, (void (*)())completed, v,
1404 "adduser", user, password, rights, (char *)0);
1407 /* Log clients ***************************************************************/
1409 /** @brief Monitor the server log
1411 * @param callbacks Functions to call when anything happens
1412 * @param v Passed to @p callbacks functions
1414 * Once a client is being used for logging it cannot be used for anything else.
1415 * There is magic in authuser_opcallback() to re-submit the @c log command
1416 * after reconnection.
1418 * NB that the @c state callback may be called from within this function,
1419 * i.e. not solely later on from the event loop callback.
1421 int disorder_eclient_log(disorder_eclient *c,
1422 const disorder_eclient_log_callbacks *callbacks,
1424 if(c->log_callbacks) return -1;
1425 c->log_callbacks = callbacks;
1427 /* Repoort initial state */
1428 if(c->log_callbacks->state)
1429 c->log_callbacks->state(c->log_v, c->statebits);
1430 stash_command(c, 0/*queuejump*/, log_opcallback, 0/*completed*/, v,
1432 disorder_eclient_polled(c, 0);
1436 /* If we get here we've stopped being a log client */
1437 static void log_opcallback(disorder_eclient *c,
1438 struct operation attribute((unused)) *op) {
1439 D(("log_opcallback"));
1440 c->log_callbacks = 0;
1444 /* error callback for log line parsing */
1445 static void logline_error(const char *msg, void *u) {
1446 disorder_eclient *c = u;
1447 /* TODO don't use protocol_error here */
1448 protocol_error(c, c->ops, -1, "error parsing log line: %s", msg);
1451 /* process a single log line */
1452 static void logline(disorder_eclient *c, const char *line) {
1457 D(("logline [%s]", line));
1458 vec = split(line, &nvec, SPLIT_QUOTES, logline_error, c);
1459 if(nvec < 2) return; /* probably an error, already
1461 if(sscanf(vec[0], "%"SCNxMAX, &when) != 1) {
1462 /* probably the wrong side of a format change */
1463 /* TODO don't use protocol_error here */
1464 protocol_error(c, c->ops, -1, "invalid log timestamp '%s'", vec[0]);
1467 /* TODO: do something with the time */
1468 //fprintf(stderr, "log key: %s\n", vec[1]);
1469 n = TABLE_FIND(logentry_handlers, name, vec[1]);
1471 //fprintf(stderr, "...not found\n");
1472 return; /* probably a future command */
1476 if(nvec < logentry_handlers[n].min || nvec > logentry_handlers[n].max) {
1477 //fprintf(stderr, "...wrong # args\n");
1480 logentry_handlers[n].handler(c, nvec, vec);
1483 static void logentry_completed(disorder_eclient *c,
1484 int attribute((unused)) nvec, char **vec) {
1485 c->statebits &= ~DISORDER_PLAYING;
1486 if(c->log_callbacks->completed)
1487 c->log_callbacks->completed(c->log_v, vec[0]);
1488 if(c->log_callbacks->state)
1489 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1492 static void logentry_failed(disorder_eclient *c,
1493 int attribute((unused)) nvec, char **vec) {
1494 c->statebits &= ~DISORDER_PLAYING;
1495 if(c->log_callbacks->failed)
1496 c->log_callbacks->failed(c->log_v, vec[0], vec[1]);
1497 if(c->log_callbacks->state)
1498 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1501 static void logentry_moved(disorder_eclient *c,
1502 int attribute((unused)) nvec, char **vec) {
1503 if(c->log_callbacks->moved)
1504 c->log_callbacks->moved(c->log_v, vec[0]);
1507 static void logentry_playing(disorder_eclient *c,
1508 int attribute((unused)) nvec, char **vec) {
1509 c->statebits |= DISORDER_PLAYING;
1510 if(c->log_callbacks->playing)
1511 c->log_callbacks->playing(c->log_v, vec[0], vec[1]);
1512 if(c->log_callbacks->state)
1513 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1516 static void logentry_queue(disorder_eclient *c,
1517 int attribute((unused)) nvec, char **vec) {
1518 struct queue_entry *q;
1520 if(!c->log_callbacks->queue) return;
1521 q = xmalloc(sizeof *q);
1522 if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1524 c->log_callbacks->queue(c->log_v, q);
1527 static void logentry_recent_added(disorder_eclient *c,
1528 int attribute((unused)) nvec, char **vec) {
1529 struct queue_entry *q;
1531 if(!c->log_callbacks->recent_added) return;
1532 q = xmalloc(sizeof *q);
1533 if(queue_unmarshall_vec(q, nvec, vec, eclient_queue_error, c))
1535 c->log_callbacks->recent_added(c->log_v, q);
1538 static void logentry_recent_removed(disorder_eclient *c,
1539 int attribute((unused)) nvec, char **vec) {
1540 if(c->log_callbacks->recent_removed)
1541 c->log_callbacks->recent_removed(c->log_v, vec[0]);
1544 static void logentry_removed(disorder_eclient *c,
1545 int attribute((unused)) nvec, char **vec) {
1546 if(c->log_callbacks->removed)
1547 c->log_callbacks->removed(c->log_v, vec[0], vec[1]);
1550 static void logentry_rescanned(disorder_eclient *c,
1551 int attribute((unused)) nvec,
1552 char attribute((unused)) **vec) {
1553 if(c->log_callbacks->rescanned)
1554 c->log_callbacks->rescanned(c->log_v);
1557 static void logentry_scratched(disorder_eclient *c,
1558 int attribute((unused)) nvec, char **vec) {
1559 c->statebits &= ~DISORDER_PLAYING;
1560 if(c->log_callbacks->scratched)
1561 c->log_callbacks->scratched(c->log_v, vec[0], vec[1]);
1562 if(c->log_callbacks->state)
1563 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1566 static void logentry_user_add(disorder_eclient *c,
1567 int attribute((unused)) nvec, char **vec) {
1568 if(c->log_callbacks->user_add)
1569 c->log_callbacks->user_add(c->log_v, vec[0]);
1572 static void logentry_user_confirm(disorder_eclient *c,
1573 int attribute((unused)) nvec, char **vec) {
1574 if(c->log_callbacks->user_confirm)
1575 c->log_callbacks->user_confirm(c->log_v, vec[0]);
1578 static void logentry_user_delete(disorder_eclient *c,
1579 int attribute((unused)) nvec, char **vec) {
1580 if(c->log_callbacks->user_delete)
1581 c->log_callbacks->user_delete(c->log_v, vec[0]);
1584 static void logentry_user_edit(disorder_eclient *c,
1585 int attribute((unused)) nvec, char **vec) {
1586 if(c->log_callbacks->user_edit)
1587 c->log_callbacks->user_edit(c->log_v, vec[0], vec[1]);
1590 static void logentry_rights_changed(disorder_eclient *c,
1591 int attribute((unused)) nvec, char **vec) {
1592 if(c->log_callbacks->rights_changed) {
1594 if(!parse_rights(vec[0], &r, 0/*report*/))
1595 c->log_callbacks->rights_changed(c->log_v, r);
1599 static const struct {
1602 const char *disable;
1603 } statestrings[] = {
1604 { DISORDER_PLAYING_ENABLED, "enable_play", "disable_play" },
1605 { DISORDER_RANDOM_ENABLED, "enable_random", "disable_random" },
1606 { DISORDER_TRACK_PAUSED, "pause", "resume" },
1607 { DISORDER_PLAYING, "playing", "completed" },
1608 { DISORDER_PLAYING, 0, "scratched" },
1609 { DISORDER_PLAYING, 0, "failed" },
1611 #define NSTATES (int)(sizeof statestrings / sizeof *statestrings)
1613 static void logentry_state(disorder_eclient *c,
1614 int attribute((unused)) nvec, char **vec) {
1617 for(n = 0; n < NSTATES; ++n)
1618 if(statestrings[n].enable && !strcmp(vec[0], statestrings[n].enable)) {
1619 c->statebits |= statestrings[n].bit;
1621 } else if(statestrings[n].disable && !strcmp(vec[0], statestrings[n].disable)) {
1622 c->statebits &= ~statestrings[n].bit;
1625 if(c->log_callbacks->state)
1626 c->log_callbacks->state(c->log_v, c->statebits | DISORDER_CONNECTED);
1629 static void logentry_volume(disorder_eclient *c,
1630 int attribute((unused)) nvec, char **vec) {
1633 if(!c->log_callbacks->volume) return;
1634 if(xstrtol(&l, vec[0], 0, 10)
1635 || xstrtol(&r, vec[1], 0, 10)
1636 || l < 0 || l > INT_MAX
1637 || r < 0 || r > INT_MAX)
1639 c->log_callbacks->volume(c->log_v, (int)l, (int)r);
1642 /** @brief Convert @p statebits to a string */
1643 char *disorder_eclient_interpret_state(unsigned long statebits) {
1647 static const struct {
1651 { DISORDER_PLAYING_ENABLED, "playing_enabled" },
1652 { DISORDER_RANDOM_ENABLED, "random_enabled" },
1653 { DISORDER_TRACK_PAUSED, "track_paused" },
1654 { DISORDER_PLAYING, "playing" },
1655 { DISORDER_CONNECTED, "connected" },
1657 #define NBITS (sizeof bits / sizeof *bits)
1661 dynstr_append(d, '0');
1662 for(n = 0; n < NBITS; ++n)
1663 if(statebits & bits[n].bit) {
1665 dynstr_append(d, '|');
1666 dynstr_append_string(d, bits[n].name);
1667 statebits ^= bits[n].bit;
1673 dynstr_append(d, '|');
1674 sprintf(s, "%#lx", statebits);
1675 dynstr_append_string(d, s);
1677 dynstr_terminate(d);
1686 indent-tabs-mode:nil