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 char **body
; /**< @brief command body */
96 operation_callback
*opcallback
; /**< @brief internal completion callback */
97 void (*completed
)(); /**< @brief user completion callback or 0 */
98 void *v
; /**< @brief data for COMPLETED */
99 disorder_eclient
*client
; /**< @brief owning client */
101 /** @brief true if sent to server
103 * This is cleared by disorder_eclient_close(), forcing all queued
104 * commands to be transparently resent.
109 /** @brief Client structure */
110 struct disorder_eclient
{
112 int fd
; /**< @brief connection to server */
113 enum client_state state
; /**< @brief current state */
114 int authenticated
; /**< @brief true when authenicated */
115 struct dynstr output
; /**< @brief output buffer */
116 struct dynstr input
; /**< @brief input buffer */
117 int eof
; /**< @brief input buffer is at EOF */
118 const disorder_eclient_callbacks
*callbacks
; /**< @brief error callbacks */
119 void *u
; /**< @brief user data */
120 struct operation
*ops
; /**< @brief queue of operations */
121 struct operation
**opstail
; /**< @brief queue tail */
122 /* accumulated response */
123 int rc
; /**< @brief response code */
124 char *line
; /**< @brief complete line */
125 struct vector vec
; /**< @brief body */
127 const disorder_eclient_log_callbacks
*log_callbacks
;
128 /**< @brief log callbacks
130 * Once disorder_eclient_log() has been issued this is always set. When we
131 * re-connect it is checked to re-issue the log command.
133 void *log_v
; /**< @brief user data */
134 unsigned long statebits
; /**< @brief latest state */
137 /**< @brief last time we sent a prod
139 * When we are receiving log data we send a "prod" byte to the server from
140 * time to time so that we detect broken connections reasonably quickly. The
141 * server just ignores these bytes.
144 /** @brief Protocol version */
147 /** @brief True if enabled */
151 /* Forward declarations ******************************************************/
153 static int start_connect(disorder_eclient
*c
);
154 static void process_line(disorder_eclient
*c
, char *line
);
155 static void maybe_connected(disorder_eclient
*c
);
156 static void authbanner_opcallback(disorder_eclient
*c
,
157 struct operation
*op
);
158 static void authuser_opcallback(disorder_eclient
*c
,
159 struct operation
*op
);
160 static void complete(disorder_eclient
*c
);
161 static void send_output(disorder_eclient
*c
);
162 static void put(disorder_eclient
*c
, const char *s
, size_t n
);
163 static void read_input(disorder_eclient
*c
);
164 static void stash_command(disorder_eclient
*c
,
166 operation_callback
*opcallback
,
173 static void log_opcallback(disorder_eclient
*c
, struct operation
*op
);
174 static void logline(disorder_eclient
*c
, const char *line
);
175 static void logentry_completed(disorder_eclient
*c
, int nvec
, char **vec
);
176 static void logentry_failed(disorder_eclient
*c
, int nvec
, char **vec
);
177 static void logentry_moved(disorder_eclient
*c
, int nvec
, char **vec
);
178 static void logentry_playing(disorder_eclient
*c
, int nvec
, char **vec
);
179 static void logentry_queue(disorder_eclient
*c
, int nvec
, char **vec
);
180 static void logentry_recent_added(disorder_eclient
*c
, int nvec
, char **vec
);
181 static void logentry_recent_removed(disorder_eclient
*c
, int nvec
, char **vec
);
182 static void logentry_removed(disorder_eclient
*c
, int nvec
, char **vec
);
183 static void logentry_scratched(disorder_eclient
*c
, int nvec
, char **vec
);
184 static void logentry_state(disorder_eclient
*c
, int nvec
, char **vec
);
185 static void logentry_volume(disorder_eclient
*c
, int nvec
, char **vec
);
186 static void logentry_rescanned(disorder_eclient
*c
, int nvec
, char **vec
);
187 static void logentry_user_add(disorder_eclient
*c
, int nvec
, char **vec
);
188 static void logentry_user_confirm(disorder_eclient
*c
, int nvec
, char **vec
);
189 static void logentry_user_delete(disorder_eclient
*c
, int nvec
, char **vec
);
190 static void logentry_user_edit(disorder_eclient
*c
, int nvec
, char **vec
);
191 static void logentry_rights_changed(disorder_eclient
*c
, int nvec
, char **vec
);
192 static void logentry_adopted(disorder_eclient
*c
, int nvec
, char **vec
);
193 static void logentry_playlist_created(disorder_eclient
*c
, int nvec
, char **vec
);
194 static void logentry_playlist_deleted(disorder_eclient
*c
, int nvec
, char **vec
);
195 static void logentry_playlist_modified(disorder_eclient
*c
, int nvec
, char **vec
);
196 static void logentry_global_pref(disorder_eclient
*c
, int nvec
, char **vec
);
198 /* Tables ********************************************************************/
200 /** @brief One possible log entry */
201 struct logentry_handler
{
202 const char *name
; /**< @brief Entry name */
203 int min
; /**< @brief Minimum arguments */
204 int max
; /**< @brief Maximum arguments */
205 void (*handler
)(disorder_eclient
*c
,
207 char **vec
); /**< @brief Handler function */
210 /** @brief Table for parsing log entries */
211 static const struct logentry_handler logentry_handlers
[] = {
212 #define LE(X, MIN, MAX) { #X, MIN, MAX, logentry_##X }
216 LE(global_pref
, 1, 2),
219 LE(playlist_created
, 2, 2),
220 LE(playlist_deleted
, 1, 1),
221 LE(playlist_modified
, 2, 2),
222 LE(queue
, 2, INT_MAX
),
223 LE(recent_added
, 2, INT_MAX
),
224 LE(recent_removed
, 1, 1),
227 LE(rights_changed
, 1, 1),
231 LE(user_confirm
, 1, 1),
232 LE(user_delete
, 1, 1),
237 /* Setup and teardown ********************************************************/
239 /** @brief Create a new client
241 * Does NOT connect the client - connections are made (and re-made) on demand.
243 disorder_eclient
*disorder_eclient_new(const disorder_eclient_callbacks
*cb
,
245 disorder_eclient
*c
= xmalloc(sizeof *c
);
246 D(("disorder_eclient_new"));
250 c
->opstail
= &c
->ops
;
252 vector_init(&c
->vec
);
253 dynstr_init(&c
->input
);
254 dynstr_init(&c
->output
);
258 /** @brief Disconnect a client
259 * @param c Client to disconnect
261 * NB that this routine just disconnnects the TCP connection. It does not
262 * destroy the client! If you continue to use it then it will attempt to
265 void disorder_eclient_close(disorder_eclient
*c
) {
266 struct operation
*op
;
268 D(("disorder_eclient_close"));
270 D(("disorder_eclient_close closing fd %d", c
->fd
));
271 c
->callbacks
->poll(c
->u
, c
, c
->fd
, 0);
274 c
->state
= state_disconnected
;
280 c
->authenticated
= 0;
281 /* We'll need to resend all operations */
282 for(op
= c
->ops
; op
; op
= op
->next
)
284 /* Drop our use a hint that we're disconnected */
285 if(c
->log_callbacks
&& c
->log_callbacks
->state
)
286 c
->log_callbacks
->state(c
->log_v
, c
->statebits
);
289 /** @brief Permit new connection activity */
290 void disorder_eclient_enable_connect(disorder_eclient
*c
) {
294 /** @brief Suppress new connection activity */
295 void disorder_eclient_disable_connect(disorder_eclient
*c
) {
299 /** @brief Return current state */
300 unsigned long disorder_eclient_state(const disorder_eclient
*c
) {
301 return c
->statebits
| (c
->state
> state_connected ? DISORDER_CONNECTED
: 0);
304 /* Error reporting ***********************************************************/
306 /** @brief called when a connection error occurs
308 * After this called we will be disconnected (by disorder_eclient_close()),
309 * so there will be a reconnection before any commands can be sent.
311 static int comms_error(disorder_eclient
*c
, const char *fmt
, ...) {
317 byte_xvasprintf(&s
, fmt
, ap
);
319 disorder_eclient_close(c
);
320 c
->callbacks
->comms_error(c
->u
, s
);
324 /** @brief called when the server reports an error */
325 static int protocol_error(disorder_eclient
*c
, struct operation
*op
,
326 int code
, const char *fmt
, ...) {
330 D(("protocol_error"));
332 byte_xvasprintf(&s
, fmt
, ap
);
334 c
->callbacks
->protocol_error(c
->u
, op
->v
, code
, s
);
338 /* State machine *************************************************************/
340 /** @brief Send an operation (into the output buffer)
341 * @param op Operation to send
343 static void op_send(struct operation
*op
) {
344 disorder_eclient
*const c
= op
->client
;
345 put(c
, op
->cmd
, strlen(op
->cmd
));
347 for(int n
= 0; op
->body
[n
]; ++n
) {
348 if(op
->body
[n
][0] == '.')
350 put(c
, op
->body
[n
], strlen(op
->body
[n
]));
358 /** @brief Called when there's something to do
360 * @param mode bitmap of @ref DISORDER_POLL_READ and/or @ref DISORDER_POLL_WRITE.
362 * This should be called from by your code when the file descriptor is readable
363 * or writable (as requested by the @c poll callback, see @ref
364 * disorder_eclient_callbacks) and in any case from time to time (with @p mode
365 * = 0) to allow for retries to work.
367 void disorder_eclient_polled(disorder_eclient
*c
, unsigned mode
) {
368 struct operation
*op
;
371 D(("disorder_eclient_polled fd=%d state=%s mode=[%s %s]",
372 c
->fd
, states
[c
->state
],
373 mode
& DISORDER_POLL_READ ?
"READ" : "",
374 mode
& DISORDER_POLL_WRITE ?
"WRITE" : ""));
375 /* The pattern here is to check each possible state in turn and try to
376 * advance (though on error we might go back). If we advance we leave open
377 * the possibility of falling through to the next state, but we set the mode
378 * bits to 0, to avoid false positives (which matter more in some cases than
381 if(c
->state
== state_disconnected
) {
382 D(("state_disconnected"));
383 /* If there is no password yet then we cannot connect */
384 if(!config
->password
) {
385 comms_error(c
, "no password is configured");
389 /* Only try to connect if enabled */
392 /* might now be state_disconnected (on error), state_connecting (slow
393 * connect) or state_connected (fast connect). If state_disconnected then
394 * we just rely on a periodic callback from the event loop sometime. */
398 if(c
->state
== state_connecting
&& mode
) {
399 D(("state_connecting"));
401 /* Might be state_disconnected (on error) or state_connected (on success).
402 * In the former case we rely on the event loop for a periodic callback to
407 if(c
->state
== state_connected
) {
408 D(("state_connected"));
409 /* We just connected. Initiate the authentication protocol. */
410 stash_command(c
, 1/*queuejump*/, authbanner_opcallback
,
411 0/*completed*/, 0/*v*/, -1/*nbody*/, 0/*body*/, 0/*cmd*/);
412 /* We never stay is state_connected very long. We could in principle jump
413 * straight to state_cmdresponse since there's actually no command to
414 * send, but that would arguably be cheating. */
415 c
->state
= state_idle
;
418 if(c
->state
== state_idle
) {
420 /* We are connected, and have finished any command we set off, look for
424 if(c
->authenticated
) {
425 /* Transmit all unsent operations */
426 for(op
= c
->ops
; op
; op
= op
->next
) {
431 /* Just send the head operation */
432 if(c
->ops
->cmd
&& !c
->ops
->sent
)
435 /* Awaiting response for the operation at the head of the list */
436 c
->state
= state_cmdresponse
;
439 c
->callbacks
->report(c
->u
, 0);
442 /* Queue up a byte to send */
443 if(c
->state
== state_log
444 && c
->output
.nvec
== 0
445 && xtime(&now
) - c
->last_prod
> LOG_PROD_INTERVAL
) {
450 if(c
->state
== state_cmdresponse
451 || c
->state
== state_body
452 || c
->state
== state_log
) {
453 D(("state_%s", states
[c
->state
]));
454 /* We are awaiting a response */
455 if(mode
& DISORDER_POLL_WRITE
) send_output(c
);
456 if(mode
& DISORDER_POLL_READ
) read_input(c
);
457 /* There are a couple of reasons we might want to re-enter the state
458 * machine from the top. state_idle is obvious: there may be further
459 * commands to process. Re-entering on state_disconnected means that we
460 * immediately retry connection if a comms error occurs during a command.
461 * This is different to the case where a connection fails, where we await a
462 * spontaneous call to initiate the retry. */
464 case state_disconnected
: /* lost connection */
465 case state_idle
: /* completed a command */
467 disorder_eclient_polled(c
, 0);
474 /* Figure out what to set the mode to */
476 case state_disconnected
:
477 D(("state_disconnected (2)"));
478 /* Probably an error occurred. Await a retry. */
481 case state_connecting
:
482 D(("state_connecting (2)"));
483 /* Waiting for connect to complete */
484 mode
= DISORDER_POLL_READ
|DISORDER_POLL_WRITE
;
486 case state_connected
:
487 D(("state_connected (2)"));
488 assert(!"should never be in state_connected here");
491 D(("state_idle (2)"));
492 /* Connected but nothing to do. */
495 case state_cmdresponse
:
498 D(("state_%s (2)", states
[c
->state
]));
499 /* Gathering a response. Wait for input. */
500 mode
= DISORDER_POLL_READ
;
501 /* Flush any pending output. */
502 if(c
->output
.nvec
) mode
|= DISORDER_POLL_WRITE
;
505 D(("fd=%d new mode [%s %s]",
507 mode
& DISORDER_POLL_READ ?
"READ" : "",
508 mode
& DISORDER_POLL_WRITE ?
"WRITE" : ""));
509 if(c
->fd
!= -1) c
->callbacks
->poll(c
->u
, c
, c
->fd
, mode
);
512 /** @brief Called to start connecting */
513 static int start_connect(disorder_eclient
*c
) {
517 D(("start_connect"));
518 if((len
= find_server(config
, &sa
, &c
->ident
)) == (socklen_t
)-1)
519 return comms_error(c
, "cannot look up server"); /* TODO better error */
524 if((c
->fd
= socket(sa
->sa_family
, SOCK_STREAM
, 0)) < 0)
525 return comms_error(c
, "socket: %s", strerror(errno
));
529 if(connect(c
->fd
, sa
, len
) < 0) {
533 c
->state
= state_connecting
;
534 /* We are called from _polled so the state machine will get to do its
538 /* Signal the error to the caller. */
539 return comms_error(c
, "connecting to %s: %s", c
->ident
, strerror(errno
));
542 c
->state
= state_connected
;
546 /** @brief Called when poll triggers while waiting for a connection */
547 static void maybe_connected(disorder_eclient
*c
) {
548 /* We either connected, or got an error. */
550 socklen_t len
= sizeof err
;
552 D(("maybe_connected"));
553 /* Work around over-enthusiastic error slippage */
554 if(getsockopt(c
->fd
, SOL_SOCKET
, SO_ERROR
, &err
, &len
) < 0)
557 /* The connection failed */
558 comms_error(c
, "connecting to %s: %s", c
->ident
, strerror(err
));
559 /* sets state_disconnected */
563 /* The connection succeeded */
564 c
->state
= state_connected
;
565 byte_xasprintf(&r
, "connected to %s", c
->ident
);
566 c
->callbacks
->report(c
->u
, r
);
567 /* If this is a log client we expect to get a bunch of updates from the
568 * server straight away */
572 /* Authentication ************************************************************/
574 /** @brief Called with the greeting from the server */
575 static void authbanner_opcallback(disorder_eclient
*c
,
576 struct operation
*op
) {
578 const unsigned char *nonce
;
582 const char *protocol
, *algorithm
, *challenge
;
584 D(("authbanner_opcallback"));
586 || !(rvec
= split(c
->line
+ 4, &nrvec
, SPLIT_QUOTES
, 0, 0))
588 /* Banner told us to go away, or was malformed. We cannot proceed. */
589 protocol_error(c
, op
, c
->rc
, "%s [%s]", c
->line
, c
->ident
);
590 disorder_eclient_close(c
);
610 protocol_error(c
, op
, c
->rc
, "%s [%s]", c
->line
, c
->ident
);
611 disorder_eclient_close(c
);
614 c
->protocol
= atoi(protocol
);
615 if(c
->protocol
< 1 || c
->protocol
> 2) {
616 protocol_error(c
, op
, c
->rc
, "%s [%s]", c
->line
, c
->ident
);
617 disorder_eclient_close(c
);
620 nonce
= unhex(challenge
, &nonce_len
);
621 res
= authhash(nonce
, nonce_len
, config
->password
, algorithm
);
623 protocol_error(c
, op
, c
->rc
, "unknown authentication algorithm '%s' [%s]",
624 algorithm
, c
->ident
);
625 disorder_eclient_close(c
);
628 stash_command(c
, 1/*queuejump*/, authuser_opcallback
, 0/*completed*/, 0/*v*/,
629 -1/*nbody*/, 0/*body*/,
630 "user", quoteutf8(config
->username
), quoteutf8(res
),
634 /** @brief Called with the response to the @c user command */
635 static void authuser_opcallback(disorder_eclient
*c
,
636 struct operation
*op
) {
639 D(("authuser_opcallback"));
640 if(c
->rc
/ 100 != 2) {
641 /* Wrong password or something. We cannot proceed. */
642 protocol_error(c
, op
, c
->rc
, "%s [%s]", c
->line
, c
->ident
);
644 disorder_eclient_close(c
);
647 /* OK, we're authenticated now. */
648 c
->authenticated
= 1;
649 byte_xasprintf(&r
, "authenticated with %s", c
->ident
);
650 c
->callbacks
->report(c
->u
, r
);
651 if(c
->log_callbacks
&& !(c
->ops
&& c
->ops
->opcallback
== log_opcallback
))
652 /* We are a log client, switch to logging mode */
653 stash_command(c
, 0/*queuejump*/, log_opcallback
, 0/*completed*/, c
->log_v
,
654 -1/*nbody*/, 0/*body*/,
658 /* Output ********************************************************************/
660 /* Chop N bytes off the front of a dynstr */
661 static void consume(struct dynstr
*d
, int n
) {
662 D(("consume %d", n
));
663 assert(d
->nvec
>= n
);
664 memmove(d
->vec
, d
->vec
+ n
, d
->nvec
- n
);
668 /* Write some bytes */
669 static void put(disorder_eclient
*c
, const char *s
, size_t n
) {
670 D(("put %d %.*s", c
->fd
, (int)n
, s
));
671 dynstr_append_bytes(&c
->output
, s
, n
);
674 /* Called when we can write to our FD, or at any other time */
675 static void send_output(disorder_eclient
*c
) {
678 D(("send_output %d bytes pending", c
->output
.nvec
));
679 if(c
->state
> state_connecting
&& c
->output
.nvec
) {
680 n
= write(c
->fd
, c
->output
.vec
, c
->output
.nvec
);
687 comms_error(c
, "writing to %s: %s", c
->ident
, strerror(errno
));
691 consume(&c
->output
, n
);
695 /* Input *********************************************************************/
697 /* Called when c->fd might be readable, or at any other time */
698 static void read_input(disorder_eclient
*c
) {
703 D(("read_input in state %s", states
[c
->state
]));
704 if(c
->state
<= state_connected
) return; /* ignore bogus calls */
705 /* read some more input */
706 n
= read(c
->fd
, buffer
, sizeof buffer
);
713 comms_error(c
, "reading from %s: %s", c
->ident
, strerror(errno
));
716 return; /* no new input to process */
718 D(("read %d bytes: [%.*s]", n
, n
, buffer
));
719 dynstr_append_bytes(&c
->input
, buffer
, n
);
722 /* might have more than one line to process */
723 while(c
->state
> state_connecting
724 && (nl
= memchr(c
->input
.vec
, '\n', c
->input
.nvec
))) {
725 process_line(c
, xstrndup(c
->input
.vec
, nl
- c
->input
.vec
));
726 /* we might have disconnected along the way, which zogs the input buffer */
727 if(c
->state
> state_connecting
)
728 consume(&c
->input
, (nl
- c
->input
.vec
) + 1);
731 comms_error(c
, "reading from %s: server disconnected", c
->ident
);
732 c
->authenticated
= 0;
736 /* called with a line that has just been read */
737 static void process_line(disorder_eclient
*c
, char *line
) {
738 D(("process_line %d [%s]", c
->fd
, line
));
740 case state_cmdresponse
:
741 /* This is the first line of a response */
742 if(!(line
[0] >= '0' && line
[0] <= '9'
743 && line
[1] >= '0' && line
[1] <= '9'
744 && line
[2] >= '0' && line
[2] <= '9'
746 disorder_fatal(0, "invalid response from server: %s", line
);
747 c
->rc
= (line
[0] * 10 + line
[1]) * 10 + line
[2] - 111 * '0';
751 /* We need to collect the body. */
752 c
->state
= state_body
;
753 vector_init(&c
->vec
);
756 assert(c
->log_callbacks
!= 0);
757 if(c
->log_callbacks
->connected
)
758 c
->log_callbacks
->connected(c
->log_v
);
759 c
->state
= state_log
;
762 /* We've got the whole response. Go into the idle state so the state
763 * machine knows we're done and then call the operation callback. */
769 if(strcmp(line
, ".")) {
770 /* A line from the body */
771 vector_append(&c
->vec
, line
+ (line
[0] == '.'));
773 /* End of the body. */
774 vector_terminate(&c
->vec
);
779 if(strcmp(line
, ".")) {
780 logline(c
, line
+ (line
[0] == '.'));
785 assert(!"wrong state for location");
790 /* Called when an operation completes */
791 static void complete(disorder_eclient
*c
) {
792 struct operation
*op
;
795 /* Pop the operation off the queue */
798 if(c
->opstail
== &op
->next
)
799 c
->opstail
= &c
->ops
;
800 /* If we've pipelined a command ahead then we go straight to cmdresponser.
801 * Otherwise we go to idle, which will arrange further sends. */
802 c
->state
= c
->ops
&& c
->ops
->sent ? state_cmdresponse
: state_idle
;
803 op
->opcallback(c
, op
);
804 /* Note that we always call the opcallback even on error, though command
805 * opcallbacks generally always do the same error handling, i.e. just call
806 * protocol_error(). It's the auth* opcallbacks that have different
810 /* Operation setup ***********************************************************/
812 static void stash_command_vector(disorder_eclient
*c
,
814 operation_callback
*opcallback
,
821 struct operation
*op
= xmalloc(sizeof *op
);
827 for(n
= 0; n
< ncmd
; ++n
) {
829 dynstr_append(&d
, ' ');
830 dynstr_append_string(&d
, quoteutf8(cmd
[n
]));
832 dynstr_append(&d
, '\n');
833 dynstr_terminate(&d
);
836 op
->cmd
= 0; /* usually, awaiting challenge */
838 op
->body
= xcalloc(nbody
+ 1, sizeof (char *));
839 for(n
= 0; n
< nbody
; ++n
)
840 op
->body
[n
] = xstrdup(body
[n
]);
844 op
->opcallback
= opcallback
;
845 op
->completed
= completed
;
849 assert(op
->sent
== 0);
851 /* Authentication operations jump the queue of useful commands */
854 if(c
->opstail
== &c
->ops
)
855 c
->opstail
= &op
->next
;
856 for(op
= c
->ops
; op
; op
= op
->next
)
860 c
->opstail
= &op
->next
;
864 static void vstash_command(disorder_eclient
*c
,
866 operation_callback
*opcallback
,
871 const char *cmd
, va_list ap
) {
875 D(("vstash_command %s", cmd ? cmd
: "NULL"));
878 vector_append(&vec
, (char *)cmd
);
879 while((arg
= va_arg(ap
, char *))) {
880 if(arg
== disorder__list
) {
881 char **list
= va_arg(ap
, char **);
882 int nlist
= va_arg(ap
, int);
884 for(nlist
= 0; list
[nlist
]; ++nlist
)
887 vector_append_many(&vec
, list
, nlist
);
888 } else if(arg
== disorder__body
) {
889 body
= va_arg(ap
, char **);
890 nbody
= va_arg(ap
, int);
891 } else if(arg
== disorder__integer
) {
892 long n
= va_arg(ap
, long);
894 snprintf(buffer
, sizeof buffer
, "%ld", n
);
895 vector_append(&vec
, xstrdup(buffer
));
896 } else if(arg
== disorder__time
) {
897 time_t n
= va_arg(ap
, time_t);
899 snprintf(buffer
, sizeof buffer
, "%lld", (long long)n
);
900 vector_append(&vec
, xstrdup(buffer
));
902 vector_append(&vec
, arg
);
904 stash_command_vector(c
, queuejump
, opcallback
, completed
, v
,
905 nbody
, body
, vec
.nvec
, vec
.vec
);
907 stash_command_vector(c
, queuejump
, opcallback
, completed
, v
,
912 static void stash_command(disorder_eclient
*c
,
914 operation_callback
*opcallback
,
924 vstash_command(c
, queuejump
, opcallback
, completed
, v
, nbody
, body
, cmd
, ap
);
928 /* Command support ***********************************************************/
930 static const char *errorstring(disorder_eclient
*c
) {
933 byte_xasprintf(&s
, "%s [%s]", c
->line
, c
->ident
);
937 /* for commands with a quoted string response */
938 static void string_response_opcallback(disorder_eclient
*c
,
939 struct operation
*op
) {
940 disorder_eclient_string_response
*completed
941 = (disorder_eclient_string_response
*)op
->completed
;
943 D(("string_response_callback"));
945 if(c
->rc
/ 100 == 2 || c
->rc
== 555) {
947 completed(op
->v
, NULL
, NULL
);
948 else if(c
->protocol
>= 2) {
949 char **rr
= split(c
->line
+ 4, 0, SPLIT_QUOTES
, 0, 0);
952 completed(op
->v
, NULL
, *rr
);
954 /* TODO error message a is bit lame but generally indicates a server
955 * bug rather than anything the user can address */
956 completed(op
->v
, "error parsing response", NULL
);
958 completed(op
->v
, NULL
, c
->line
+ 4);
960 completed(op
->v
, errorstring(c
), NULL
);
964 /* for commands with a simple integer response */
965 static void integer_response_opcallback(disorder_eclient
*c
,
966 struct operation
*op
) {
967 disorder_eclient_integer_response
*completed
968 = (disorder_eclient_integer_response
*)op
->completed
;
970 D(("string_response_callback"));
971 if(c
->rc
/ 100 == 2) {
975 e
= xstrtol(&n
, c
->line
+ 4, 0, 10);
977 completed(op
->v
, strerror(e
), 0);
979 completed(op
->v
, 0, n
);
981 completed(op
->v
, errorstring(c
), 0);
984 /* for commands with no response */
985 static void no_response_opcallback(disorder_eclient
*c
,
986 struct operation
*op
) {
987 disorder_eclient_no_response
*completed
988 = (disorder_eclient_no_response
*)op
->completed
;
990 D(("no_response_callback"));
993 completed(op
->v
, NULL
);
995 completed(op
->v
, errorstring(c
));
999 /* error callback for queue_unmarshall */
1000 static void eclient_queue_error(const char *msg
,
1002 struct operation
*op
= u
;
1004 /* TODO don't use protocol_error here */
1005 protocol_error(op
->client
, op
, -1, "error parsing queue entry: %s", msg
);
1008 /* for commands that expect a queue dump */
1009 static void queue_response_opcallback(disorder_eclient
*c
,
1010 struct operation
*op
) {
1011 disorder_eclient_queue_response
*const completed
1012 = (disorder_eclient_queue_response
*)op
->completed
;
1014 int parse_failed
= 0;
1015 struct queue_entry
*q
, *qh
= 0, **qtail
= &qh
, *qlast
= 0;
1017 D(("queue_response_callback"));
1018 if(c
->rc
/ 100 == 2) {
1019 /* parse the queue */
1020 for(n
= 0; n
< c
->vec
.nvec
; ++n
) {
1021 q
= xmalloc(sizeof *q
);
1022 D(("queue_unmarshall %s", c
->vec
.vec
[n
]));
1023 if(!queue_unmarshall(q
, c
->vec
.vec
[n
], NULL
, op
)) {
1031 /* Currently we pass the partial queue to the callback along with the
1032 * error. This might not be very useful in practice... */
1034 completed(op
->v
, "cannot parse result", qh
);
1036 completed(op
->v
, 0, qh
);
1038 completed(op
->v
, errorstring(c
), 0);
1042 static void playing_response_opcallback(disorder_eclient
*c
,
1043 struct operation
*op
) {
1044 disorder_eclient_queue_response
*const completed
1045 = (disorder_eclient_queue_response
*)op
->completed
;
1046 struct queue_entry
*q
;
1048 D(("playing_response_callback"));
1049 if(c
->rc
/ 100 == 2) {
1050 switch(c
->rc
% 10) {
1052 if(queue_unmarshall(q
= xmalloc(sizeof *q
), c
->line
+ 4,
1054 completed(op
->v
, "cannot parse result", 0);
1056 completed(op
->v
, 0, q
);
1059 completed(op
->v
, 0, 0);
1062 completed(op
->v
, errorstring(c
), 0);
1066 completed(op
->v
, errorstring(c
), 0);
1069 /* for commands that expect a list of some sort */
1070 static void list_response_opcallback(disorder_eclient
*c
,
1071 struct operation
*op
) {
1072 disorder_eclient_list_response
*const completed
=
1073 (disorder_eclient_list_response
*)op
->completed
;
1075 D(("list_response_callback"));
1076 if(c
->rc
/ 100 == 2)
1077 completed(op
->v
, NULL
, c
->vec
.nvec
, c
->vec
.vec
);
1078 else if(c
->rc
== 555)
1079 completed(op
->v
, NULL
, -1, NULL
);
1081 completed(op
->v
, errorstring(c
), 0, 0);
1085 static void pair_integer_response_opcallback(disorder_eclient
*c
,
1086 struct operation
*op
) {
1087 disorder_eclient_pair_integer_response
*completed
1088 = (disorder_eclient_pair_integer_response
*)op
->completed
;
1091 D(("volume_response_callback"));
1092 if(c
->rc
/ 100 == 2) {
1094 if(sscanf(c
->line
+ 4, "%ld %ld", &l
, &r
) != 2 || l
< 0 || r
< 0)
1095 completed(op
->v
, "cannot parse volume response", 0, 0);
1097 completed(op
->v
, 0, l
, r
);
1100 completed(op
->v
, errorstring(c
), 0, 0);
1103 static int simple(disorder_eclient
*c
,
1104 operation_callback
*opcallback
,
1105 void (*completed
)(),
1107 const char *cmd
, ...) {
1111 vstash_command(c
, 0/*queuejump*/, opcallback
, completed
, v
, -1, 0, cmd
, ap
);
1113 /* Give the state machine a kick, since we might be in state_idle */
1114 disorder_eclient_polled(c
, 0);
1118 /* Commands ******************************************************************/
1120 int disorder_eclient_scratch_playing(disorder_eclient
*c
,
1121 disorder_eclient_no_response
*completed
,
1123 return disorder_eclient_scratch(c
, completed
, 0, v
);
1126 static void rtp_response_opcallback(disorder_eclient
*c
,
1127 struct operation
*op
) {
1128 disorder_eclient_list_response
*const completed
=
1129 (disorder_eclient_list_response
*)op
->completed
;
1130 D(("rtp_response_opcallback"));
1131 if(c
->rc
/ 100 == 2) {
1133 char **vec
= split(c
->line
+ 4, &nvec
, SPLIT_QUOTES
, 0, 0);
1136 completed(op
->v
, NULL
, nvec
, vec
);
1138 completed(op
->v
, "error parsing response", 0, 0);
1140 completed(op
->v
, errorstring(c
), 0, 0);
1143 /** @brief Determine the RTP target address
1145 * @param completed Called with address details
1146 * @param v Passed to @p completed
1148 * The address details will be two elements, the first being the hostname and
1149 * the second the service (port).
1151 int disorder_eclient_rtp_address(disorder_eclient
*c
,
1152 disorder_eclient_list_response
*completed
,
1154 return simple(c
, rtp_response_opcallback
, (void (*)())completed
, v
,
1155 "rtp-address", (char *)0);
1158 /* Log clients ***************************************************************/
1160 /** @brief Monitor the server log
1162 * @param callbacks Functions to call when anything happens
1163 * @param v Passed to @p callbacks functions
1165 * Once a client is being used for logging it cannot be used for anything else.
1166 * There is magic in authuser_opcallback() to re-submit the @c log command
1167 * after reconnection.
1169 * NB that the @c state callback may be called from within this function,
1170 * i.e. not solely later on from the event loop callback.
1172 int disorder_eclient_log(disorder_eclient
*c
,
1173 const disorder_eclient_log_callbacks
*callbacks
,
1175 if(c
->log_callbacks
) return -1;
1176 c
->log_callbacks
= callbacks
;
1178 /* Repoort initial state */
1179 if(c
->log_callbacks
->state
)
1180 c
->log_callbacks
->state(c
->log_v
, c
->statebits
);
1181 stash_command(c
, 0/*queuejump*/, log_opcallback
, 0/*completed*/, v
,
1182 -1, 0, "log", (char *)0);
1183 disorder_eclient_polled(c
, 0);
1187 /* If we get here we've stopped being a log client */
1188 static void log_opcallback(disorder_eclient
*c
,
1189 struct operation
attribute((unused
)) *op
) {
1190 D(("log_opcallback"));
1191 c
->log_callbacks
= 0;
1195 /* error callback for log line parsing */
1196 static void logline_error(const char *msg
, void *u
) {
1197 disorder_eclient
*c
= u
;
1198 /* TODO don't use protocol_error here */
1199 protocol_error(c
, c
->ops
, -1, "error parsing log line: %s", msg
);
1202 /* process a single log line */
1203 static void logline(disorder_eclient
*c
, const char *line
) {
1208 D(("logline [%s]", line
));
1209 vec
= split(line
, &nvec
, SPLIT_QUOTES
, logline_error
, c
);
1210 if(nvec
< 2) return; /* probably an error, already
1212 if(sscanf(vec
[0], "%"SCNxMAX
, &when
) != 1) {
1213 /* probably the wrong side of a format change */
1214 /* TODO don't use protocol_error here */
1215 protocol_error(c
, c
->ops
, -1, "invalid log timestamp '%s'", vec
[0]);
1218 /* TODO: do something with the time */
1219 //fprintf(stderr, "log key: %s\n", vec[1]);
1220 n
= TABLE_FIND(logentry_handlers
, name
, vec
[1]);
1222 //fprintf(stderr, "...not found\n");
1223 return; /* probably a future command */
1227 if(nvec
< logentry_handlers
[n
].min
|| nvec
> logentry_handlers
[n
].max
) {
1228 //fprintf(stderr, "...wrong # args\n");
1231 logentry_handlers
[n
].handler(c
, nvec
, vec
);
1234 static void logentry_completed(disorder_eclient
*c
,
1235 int attribute((unused
)) nvec
, char **vec
) {
1236 c
->statebits
&= ~DISORDER_PLAYING
;
1237 if(c
->log_callbacks
->completed
)
1238 c
->log_callbacks
->completed(c
->log_v
, vec
[0]);
1239 if(c
->log_callbacks
->state
)
1240 c
->log_callbacks
->state(c
->log_v
, c
->statebits
| DISORDER_CONNECTED
);
1243 static void logentry_failed(disorder_eclient
*c
,
1244 int attribute((unused
)) nvec
, char **vec
) {
1245 c
->statebits
&= ~DISORDER_PLAYING
;
1246 if(c
->log_callbacks
->failed
)
1247 c
->log_callbacks
->failed(c
->log_v
, vec
[0], vec
[1]);
1248 if(c
->log_callbacks
->state
)
1249 c
->log_callbacks
->state(c
->log_v
, c
->statebits
| DISORDER_CONNECTED
);
1252 static void logentry_moved(disorder_eclient
*c
,
1253 int attribute((unused
)) nvec
, char **vec
) {
1254 if(c
->log_callbacks
->moved
)
1255 c
->log_callbacks
->moved(c
->log_v
, vec
[0]);
1258 static void logentry_playing(disorder_eclient
*c
,
1259 int attribute((unused
)) nvec
, char **vec
) {
1260 c
->statebits
|= DISORDER_PLAYING
;
1261 if(c
->log_callbacks
->playing
)
1262 c
->log_callbacks
->playing(c
->log_v
, vec
[0], vec
[1]);
1263 if(c
->log_callbacks
->state
)
1264 c
->log_callbacks
->state(c
->log_v
, c
->statebits
| DISORDER_CONNECTED
);
1267 static void logentry_queue(disorder_eclient
*c
,
1268 int attribute((unused
)) nvec
, char **vec
) {
1269 struct queue_entry
*q
;
1271 if(!c
->log_callbacks
->queue
) return;
1272 q
= xmalloc(sizeof *q
);
1273 if(queue_unmarshall_vec(q
, nvec
, vec
, eclient_queue_error
, c
))
1275 c
->log_callbacks
->queue(c
->log_v
, q
);
1278 static void logentry_recent_added(disorder_eclient
*c
,
1279 int attribute((unused
)) nvec
, char **vec
) {
1280 struct queue_entry
*q
;
1282 if(!c
->log_callbacks
->recent_added
) return;
1283 q
= xmalloc(sizeof *q
);
1284 if(queue_unmarshall_vec(q
, nvec
, vec
, eclient_queue_error
, c
))
1286 c
->log_callbacks
->recent_added(c
->log_v
, q
);
1289 static void logentry_recent_removed(disorder_eclient
*c
,
1290 int attribute((unused
)) nvec
, char **vec
) {
1291 if(c
->log_callbacks
->recent_removed
)
1292 c
->log_callbacks
->recent_removed(c
->log_v
, vec
[0]);
1295 static void logentry_removed(disorder_eclient
*c
,
1296 int attribute((unused
)) nvec
, char **vec
) {
1297 if(c
->log_callbacks
->removed
)
1298 c
->log_callbacks
->removed(c
->log_v
, vec
[0], vec
[1]);
1301 static void logentry_rescanned(disorder_eclient
*c
,
1302 int attribute((unused
)) nvec
,
1303 char attribute((unused
)) **vec
) {
1304 if(c
->log_callbacks
->rescanned
)
1305 c
->log_callbacks
->rescanned(c
->log_v
);
1308 static void logentry_scratched(disorder_eclient
*c
,
1309 int attribute((unused
)) nvec
, char **vec
) {
1310 c
->statebits
&= ~DISORDER_PLAYING
;
1311 if(c
->log_callbacks
->scratched
)
1312 c
->log_callbacks
->scratched(c
->log_v
, vec
[0], vec
[1]);
1313 if(c
->log_callbacks
->state
)
1314 c
->log_callbacks
->state(c
->log_v
, c
->statebits
| DISORDER_CONNECTED
);
1317 static void logentry_user_add(disorder_eclient
*c
,
1318 int attribute((unused
)) nvec
, char **vec
) {
1319 if(c
->log_callbacks
->user_add
)
1320 c
->log_callbacks
->user_add(c
->log_v
, vec
[0]);
1323 static void logentry_user_confirm(disorder_eclient
*c
,
1324 int attribute((unused
)) nvec
, char **vec
) {
1325 if(c
->log_callbacks
->user_confirm
)
1326 c
->log_callbacks
->user_confirm(c
->log_v
, vec
[0]);
1329 static void logentry_user_delete(disorder_eclient
*c
,
1330 int attribute((unused
)) nvec
, char **vec
) {
1331 if(c
->log_callbacks
->user_delete
)
1332 c
->log_callbacks
->user_delete(c
->log_v
, vec
[0]);
1335 static void logentry_user_edit(disorder_eclient
*c
,
1336 int attribute((unused
)) nvec
, char **vec
) {
1337 if(c
->log_callbacks
->user_edit
)
1338 c
->log_callbacks
->user_edit(c
->log_v
, vec
[0], vec
[1]);
1341 static void logentry_rights_changed(disorder_eclient
*c
,
1342 int attribute((unused
)) nvec
, char **vec
) {
1343 if(c
->log_callbacks
->rights_changed
) {
1345 if(!parse_rights(vec
[0], &r
, 0/*report*/))
1346 c
->log_callbacks
->rights_changed(c
->log_v
, r
);
1350 static void logentry_playlist_created(disorder_eclient
*c
,
1351 int attribute((unused
)) nvec
,
1353 if(c
->log_callbacks
->playlist_created
)
1354 c
->log_callbacks
->playlist_created(c
->log_v
, vec
[0], vec
[1]);
1357 static void logentry_playlist_deleted(disorder_eclient
*c
,
1358 int attribute((unused
)) nvec
,
1360 if(c
->log_callbacks
->playlist_deleted
)
1361 c
->log_callbacks
->playlist_deleted(c
->log_v
, vec
[0]);
1364 static void logentry_playlist_modified(disorder_eclient
*c
,
1365 int attribute((unused
)) nvec
,
1367 if(c
->log_callbacks
->playlist_modified
)
1368 c
->log_callbacks
->playlist_modified(c
->log_v
, vec
[0], vec
[1]);
1371 static const struct {
1374 const char *disable
;
1375 } statestrings
[] = {
1376 { DISORDER_PLAYING_ENABLED
, "enable_play", "disable_play" },
1377 { DISORDER_RANDOM_ENABLED
, "enable_random", "disable_random" },
1378 { DISORDER_TRACK_PAUSED
, "pause", "resume" },
1379 { DISORDER_PLAYING
, "playing", "completed" },
1380 { DISORDER_PLAYING
, 0, "scratched" },
1381 { DISORDER_PLAYING
, 0, "failed" },
1383 #define NSTATES (int)(sizeof statestrings / sizeof *statestrings)
1385 static void logentry_state(disorder_eclient
*c
,
1386 int attribute((unused
)) nvec
, char **vec
) {
1389 for(n
= 0; n
< NSTATES
; ++n
)
1390 if(statestrings
[n
].enable
&& !strcmp(vec
[0], statestrings
[n
].enable
)) {
1391 c
->statebits
|= statestrings
[n
].bit
;
1393 } else if(statestrings
[n
].disable
&& !strcmp(vec
[0], statestrings
[n
].disable
)) {
1394 c
->statebits
&= ~statestrings
[n
].bit
;
1397 if(c
->log_callbacks
->state
)
1398 c
->log_callbacks
->state(c
->log_v
, c
->statebits
| DISORDER_CONNECTED
);
1401 static void logentry_volume(disorder_eclient
*c
,
1402 int attribute((unused
)) nvec
, char **vec
) {
1405 if(!c
->log_callbacks
->volume
) return;
1406 if(xstrtol(&l
, vec
[0], 0, 10)
1407 || xstrtol(&r
, vec
[1], 0, 10)
1408 || l
< 0 || l
> INT_MAX
1409 || r
< 0 || r
> INT_MAX
)
1411 c
->log_callbacks
->volume(c
->log_v
, (int)l
, (int)r
);
1414 /** @brief Convert @p statebits to a string */
1415 char *disorder_eclient_interpret_state(unsigned long statebits
) {
1419 static const struct {
1423 { DISORDER_PLAYING_ENABLED
, "playing_enabled" },
1424 { DISORDER_RANDOM_ENABLED
, "random_enabled" },
1425 { DISORDER_TRACK_PAUSED
, "track_paused" },
1426 { DISORDER_PLAYING
, "playing" },
1427 { DISORDER_CONNECTED
, "connected" },
1429 #define NBITS (sizeof bits / sizeof *bits)
1433 dynstr_append(d
, '0');
1434 for(n
= 0; n
< NBITS
; ++n
)
1435 if(statebits
& bits
[n
].bit
) {
1437 dynstr_append(d
, '|');
1438 dynstr_append_string(d
, bits
[n
].name
);
1439 statebits
^= bits
[n
].bit
;
1445 dynstr_append(d
, '|');
1446 sprintf(s
, "%#lx", statebits
);
1447 dynstr_append_string(d
, s
);
1449 dynstr_terminate(d
);
1453 static void logentry_adopted(disorder_eclient
*c
,
1454 int attribute((unused
)) nvec
, char **vec
) {
1455 if(c
->log_callbacks
->adopted
)
1456 c
->log_callbacks
->adopted(c
->log_v
, vec
[0], vec
[1]);
1459 static void logentry_global_pref(disorder_eclient
*c
,
1460 int nvec
, char **vec
) {
1461 if(c
->log_callbacks
->global_pref
)
1462 c
->log_callbacks
->global_pref(c
->log_v
, vec
[0], nvec
> 1 ? vec
[1] : 0);
1465 #include "eclient-stubs.c"
1472 indent-tabs-mode:nil