2 * This file is part of DisOrder.
3 * Copyright (C) 2004-2009 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/client.c
19 * @brief Simple C client
21 * See @ref lib/eclient.c for an asynchronous-capable client
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
44 #include "inputline.h"
51 #include "client-common.h"
56 /** @brief Client handle contents */
57 struct disorder_client
{
58 /** @brief Stream to read from */
60 /** @brief Stream to write to */
62 /** @brief Peer description */
64 /** @brief Username */
66 /** @brief Report errors to @c stderr */
68 /** @brief Last error string */
72 /** @brief Create a new client
73 * @param verbose If nonzero, write extra junk to stderr
74 * @return Pointer to new client
76 * You must call disorder_connect(), disorder_connect_user() or
77 * disorder_connect_cookie() to connect it. Use disorder_close() to
78 * dispose of the client when finished with it.
80 disorder_client
*disorder_new(int verbose
) {
81 disorder_client
*c
= xmalloc(sizeof (struct disorder_client
));
87 /** @brief Read a response line
89 * @param rp Where to store response, or NULL (UTF-8)
90 * @return Response code 0-999 or -1 on error
92 static int response(disorder_client
*c
, char **rp
) {
95 if(inputline(c
->ident
, c
->fpin
, &r
, '\n')) {
96 byte_xasprintf((char **)&c
->last
, "input error: %s", strerror(errno
));
99 D(("response: %s", r
));
102 if(r
[0] >= '0' && r
[0] <= '9'
103 && r
[1] >= '0' && r
[1] <= '9'
104 && r
[2] >= '0' && r
[2] <= '9'
107 return (r
[0] * 10 + r
[1]) * 10 + r
[2] - 111 * '0';
109 c
->last
= "invalid reply format";
110 disorder_error(0, "invalid reply format from %s", c
->ident
);
115 /** @brief Return last response string
117 * @return Last response string (UTF-8, English) or NULL
119 const char *disorder_last(disorder_client
*c
) {
123 /** @brief Read and partially parse a response
125 * @param rp Where to store response text (or NULL) (UTF-8)
126 * @return 0 on success, non-0 on error
128 * 5xx responses count as errors.
130 * @p rp will NOT be filled in for xx9 responses (where it is just
131 * commentary for a command where it would normally be meaningful).
133 * NB that the response will NOT be converted to the local encoding.
135 static int check_response(disorder_client
*c
, char **rp
) {
139 if((rc
= response(c
, &r
)) == -1)
141 else if(rc
/ 100 == 2) {
143 *rp
= (rc
% 10 == 9) ?
0 : xstrdup(r
+ 4);
148 disorder_error(0, "from %s: %s", c
->ident
, utf82mb(r
));
154 /** @brief Marker for a command body */
155 static const char disorder_body
[1];
157 /** @brief Issue a command and parse a simple response
159 * @param rp Where to store result, or NULL
161 * @param ap Arguments (UTF-8), terminated by (char *)0
162 * @return 0 on success, non-0 on error
164 * 5xx responses count as errors.
166 * @p rp will NOT be filled in for xx9 responses (where it is just
167 * commentary for a command where it would normally be meaningful).
169 * NB that the response will NOT be converted to the local encoding
170 * nor will quotes be stripped. See dequote().
172 * Put @ref disorder_body in the argument list followed by a char **
173 * and int giving the body to follow the command. If the int is @c -1
174 * then the list is assumed to be NULL-terminated.
176 * Usually you would call this via one of the following interfaces:
177 * - disorder_simple()
178 * - disorder_simple_list()
180 static int disorder_simple_v(disorder_client
*c
,
191 c
->last
= "not connected";
192 disorder_error(0, "not connected to server");
197 dynstr_append_string(&d
, cmd
);
198 while((arg
= va_arg(ap
, const char *))) {
199 if(arg
== disorder_body
) {
200 body
= va_arg(ap
, char **);
201 nbody
= va_arg(ap
, int);
204 dynstr_append(&d
, ' ');
205 dynstr_append_string(&d
, quoteutf8(arg
));
208 dynstr_append(&d
, '\n');
209 dynstr_terminate(&d
);
210 D(("command: %s", d
.vec
));
211 if(fputs(d
.vec
, c
->fpout
) < 0)
216 for(nbody
= 0; body
[nbody
]; ++nbody
)
218 for(int n
= 0; n
< nbody
; ++n
) {
219 if(body
[n
][0] == '.')
220 if(fputc('.', c
->fpout
) < 0)
222 if(fputs(body
[n
], c
->fpout
) < 0)
224 if(fputc('\n', c
->fpout
) < 0)
227 if(fputs(".\n", c
->fpout
) < 0)
233 return check_response(c
, rp
);
235 byte_xasprintf((char **)&c
->last
, "write error: %s", strerror(errno
));
236 disorder_error(errno
, "error writing to %s", c
->ident
);
240 /** @brief Issue a command and parse a simple response
242 * @param rp Where to store result, or NULL (UTF-8)
244 * @return 0 on success, non-0 on error
246 * The remaining arguments are command arguments, terminated by (char
247 * *)0. They should be in UTF-8.
249 * 5xx responses count as errors.
251 * @p rp will NOT be filled in for xx9 responses (where it is just
252 * commentary for a command where it would normally be meaningful).
254 * NB that the response will NOT be converted to the local encoding
255 * nor will quotes be stripped. See dequote().
257 static int disorder_simple(disorder_client
*c
,
259 const char *cmd
, ...) {
264 ret
= disorder_simple_v(c
, rp
, cmd
, ap
);
269 /** @brief Dequote a result string
270 * @param rc 0 on success, non-0 on error
271 * @param rp Where result string is stored (UTF-8)
274 * This is used as a wrapper around disorder_simple() to dequote
277 static int dequote(int rc
, char **rp
) {
281 if((rr
= split(*rp
, 0, SPLIT_QUOTES
, 0, 0)) && *rr
) {
287 disorder_error(0, "invalid reply: %s", *rp
);
292 /** @brief Generic connection routine
293 * @param conf Configuration to follow
295 * @param username Username to log in with or NULL
296 * @param password Password to log in with or NULL
297 * @param cookie Cookie to log in with or NULL
298 * @return 0 on success, non-0 on error
300 * @p cookie is tried first if not NULL. If it is NULL then @p
301 * username must not be. If @p username is not NULL then nor may @p
304 int disorder_connect_generic(struct config
*conf
,
306 const char *username
,
307 const char *password
,
308 const char *cookie
) {
309 int fd
= -1, fd2
= -1, nrvec
= 0, rc
;
310 unsigned char *nonce
= NULL
;
313 char *r
= NULL
, **rvec
= NULL
;
314 const char *protocol
, *algorithm
, *challenge
;
315 struct sockaddr
*sa
= NULL
;
318 if((salen
= find_server(conf
, &sa
, &c
->ident
)) == (socklen_t
)-1)
320 c
->fpin
= c
->fpout
= 0;
321 if((fd
= socket(sa
->sa_family
, SOCK_STREAM
, 0)) < 0) {
322 byte_xasprintf((char **)&c
->last
, "socket: %s", strerror(errno
));
323 disorder_error(errno
, "error calling socket");
326 if(connect(fd
, sa
, salen
) < 0) {
327 byte_xasprintf((char **)&c
->last
, "connect: %s", strerror(errno
));
328 disorder_error(errno
, "error calling connect");
331 if((fd2
= dup(fd
)) < 0) {
332 byte_xasprintf((char **)&c
->last
, "dup: %s", strerror(errno
));
333 disorder_error(errno
, "error calling dup");
336 if(!(c
->fpin
= fdopen(fd
, "rb"))) {
337 byte_xasprintf((char **)&c
->last
, "fdopen: %s", strerror(errno
));
338 disorder_error(errno
, "error calling fdopen");
342 if(!(c
->fpout
= fdopen(fd2
, "wb"))) {
343 byte_xasprintf((char **)&c
->last
, "fdopen: %s", strerror(errno
));
344 disorder_error(errno
, "error calling fdopen");
348 if((rc
= disorder_simple(c
, &r
, 0, (const char *)0)))
350 if(!(rvec
= split(r
, &nrvec
, SPLIT_QUOTES
, 0, 0)))
353 c
->last
= "cannot parse server greeting";
354 disorder_error(0, "cannot parse server greeting %s", r
);
358 if(strcmp(protocol
, "2")) {
359 c
->last
= "unknown protocol version";
360 disorder_error(0, "unknown protocol version: %s", protocol
);
365 if(!(nonce
= unhex(challenge
, &nl
)))
368 if(!dequote(disorder_simple(c
, &c
->user
, "cookie", cookie
, (char *)0),
370 return 0; /* success */
372 c
->last
= "cookie failed and no username";
373 disorder_error(0, "cookie did not work and no username available");
377 if(!(res
= authhash(nonce
, nl
, password
, algorithm
))) {
378 c
->last
= "error computing authorization hash";
381 if((rc
= disorder_simple(c
, 0, "user", username
, res
, (char *)0)))
383 c
->user
= xstrdup(username
);
385 free_strings(nrvec
, rvec
);
401 if(fd2
!= -1) close(fd2
);
402 if(fd
!= -1) close(fd
);
406 /** @brief Connect a client with a specified username and password
408 * @param username Username to log in with
409 * @param password Password to log in with
410 * @return 0 on success, non-0 on error
412 int disorder_connect_user(disorder_client
*c
,
413 const char *username
,
414 const char *password
) {
415 return disorder_connect_generic(config
,
422 /** @brief Connect a client
424 * @return 0 on success, non-0 on error
426 * The connection will use the username and password found in @ref
427 * config, or directly from the database if no password is found and
428 * the database is readable (usually only for root).
430 int disorder_connect(disorder_client
*c
) {
431 const char *username
, *password
;
433 if(!(username
= config
->username
)) {
434 c
->last
= "no username";
435 disorder_error(0, "no username configured");
438 password
= config
->password
;
439 /* Maybe we can read the database */
440 if(!password
&& trackdb_readable()) {
441 trackdb_init(TRACKDB_NO_RECOVER
|TRACKDB_NO_UPGRADE
);
442 trackdb_open(TRACKDB_READ_ONLY
);
443 password
= trackdb_get_password(username
);
448 c
->last
= "no password";
449 disorder_error(0, "no password configured for user '%s'", username
);
452 return disorder_connect_generic(config
,
459 /** @brief Connect a client
461 * @param cookie Cookie to log in with, or NULL
462 * @return 0 on success, non-0 on error
464 * If @p cookie is NULL or does not work then we attempt to log in as
465 * guest instead (so when the cookie expires only an extra round trip
466 * is needed rathre than a complete new login).
468 int disorder_connect_cookie(disorder_client
*c
,
469 const char *cookie
) {
470 return disorder_connect_generic(config
,
477 /** @brief Close a client
479 * @return 0 on succcess, non-0 on errior
481 * The client is still closed even on error. It might well be
482 * appropriate to ignore the return value.
484 int disorder_close(disorder_client
*c
) {
488 if(fclose(c
->fpin
) < 0) {
489 byte_xasprintf((char **)&c
->last
, "fclose: %s", strerror(errno
));
490 disorder_error(errno
, "error calling fclose");
496 if(fclose(c
->fpout
) < 0) {
497 byte_xasprintf((char **)&c
->last
, "fclose: %s", strerror(errno
));
498 disorder_error(errno
, "error calling fclose");
510 /** @brief Move a track
512 * @param track Track to move (UTF-8)
513 * @param delta Distance to move by
514 * @return 0 on success, non-0 on error
516 int disorder_move(disorder_client
*c
, const char *track
, int delta
) {
519 byte_snprintf(d
, sizeof d
, "%d", delta
);
520 return disorder_simple(c
, 0, "move", track
, d
, (char *)0);
523 static void client_error(const char *msg
,
524 void attribute((unused
)) *u
) {
525 disorder_error(0, "error parsing reply: %s", msg
);
528 /** @brief Get currently playing track
530 * @param qp Where to store track information
531 * @return 0 on success, non-0 on error
533 * @p qp gets NULL if no track is playing.
535 int disorder_playing(disorder_client
*c
, struct queue_entry
**qp
) {
537 struct queue_entry
*q
;
540 if((rc
= disorder_simple(c
, &r
, "playing", (char *)0)))
543 q
= xmalloc(sizeof *q
);
544 if(queue_unmarshall(q
, r
, client_error
, 0))
552 /** @brief Fetch the queue, recent list, etc */
553 static int disorder_somequeue(disorder_client
*c
,
554 const char *cmd
, struct queue_entry
**qp
) {
555 struct queue_entry
*qh
, **qt
= &qh
, *q
;
559 if((rc
= disorder_simple(c
, 0, cmd
, (char *)0)))
561 while(inputline(c
->ident
, c
->fpin
, &l
, '\n') >= 0) {
562 if(!strcmp(l
, ".")) {
568 q
= xmalloc(sizeof *q
);
569 if(!queue_unmarshall(q
, l
, client_error
, 0)) {
575 if(ferror(c
->fpin
)) {
576 byte_xasprintf((char **)&c
->last
, "input error: %s", strerror(errno
));
577 disorder_error(errno
, "error reading %s", c
->ident
);
579 c
->last
= "input error: unexpxected EOF";
580 disorder_error(0, "error reading %s: unexpected EOF", c
->ident
);
585 /** @brief Read a dot-stuffed list
587 * @param vecp Where to store list (UTF-8)
588 * @param nvecp Where to store number of items, or NULL
589 * @return 0 on success, non-0 on error
591 * The list will have a final NULL not counted in @p nvecp.
593 static int readlist(disorder_client
*c
, char ***vecp
, int *nvecp
) {
598 while(inputline(c
->ident
, c
->fpin
, &l
, '\n') >= 0) {
599 if(!strcmp(l
, ".")) {
600 vector_terminate(&v
);
607 vector_append(&v
, xstrdup(l
+ (*l
== '.')));
610 if(ferror(c
->fpin
)) {
611 byte_xasprintf((char **)&c
->last
, "input error: %s", strerror(errno
));
612 disorder_error(errno
, "error reading %s", c
->ident
);
614 c
->last
= "input error: unexpxected EOF";
615 disorder_error(0, "error reading %s: unexpected EOF", c
->ident
);
620 /** @brief Issue a comamnd and get a list response
622 * @param vecp Where to store list (UTF-8)
623 * @param nvecp Where to store number of items, or NULL
625 * @return 0 on success, non-0 on error
627 * The remaining arguments are command arguments, terminated by (char
628 * *)0. They should be in UTF-8.
630 * 5xx responses count as errors.
632 * See disorder_simple().
634 static int disorder_simple_list(disorder_client
*c
,
635 char ***vecp
, int *nvecp
,
636 const char *cmd
, ...) {
641 ret
= disorder_simple_v(c
, 0, cmd
, ap
);
644 return readlist(c
, vecp
, nvecp
);
647 /** @brief Return the user we logged in with
649 * @return User name (owned by @p c, don't modify)
651 char *disorder_user(disorder_client
*c
) {
655 static void pref_error_handler(const char *msg
,
656 void attribute((unused
)) *u
) {
657 disorder_error(0, "error handling 'prefs' reply: %s", msg
);
660 /** @brief Get all preferences for a trcak
662 * @param track Track name
663 * @param kp Where to store linked list of preferences
664 * @return 0 on success, non-0 on error
666 int disorder_prefs(disorder_client
*c
, const char *track
, struct kvp
**kp
) {
668 int nvec
, npvec
, n
, rc
;
671 if((rc
= disorder_simple_list(c
, &vec
, &nvec
, "prefs", track
, (char *)0)))
673 for(n
= 0; n
< nvec
; ++n
) {
674 if(!(pvec
= split(vec
[n
], &npvec
, SPLIT_QUOTES
, pref_error_handler
, 0)))
677 pref_error_handler("malformed response", 0);
680 *kp
= k
= xmalloc(sizeof *k
);
686 free_strings(nvec
, vec
);
691 /** @brief Parse a boolean response
692 * @param cmd Command for use in error messsage
693 * @param value Result from server
694 * @param flagp Where to store result
695 * @return 0 on success, non-0 on error
697 static int boolean(const char *cmd
, const char *value
,
699 if(!strcmp(value
, "yes")) *flagp
= 1;
700 else if(!strcmp(value
, "no")) *flagp
= 0;
702 disorder_error(0, "malformed response to '%s'", cmd
);
708 /** @brief Set volume
710 * @param left New left channel value
711 * @param right New right channel value
712 * @return 0 on success, non-0 on error
714 int disorder_set_volume(disorder_client
*c
, int left
, int right
) {
717 if(byte_asprintf(&ls
, "%d", left
) < 0
718 || byte_asprintf(&rs
, "%d", right
) < 0)
720 return disorder_simple(c
, 0, "volume", ls
, rs
, (char *)0);
723 /** @brief Get volume
725 * @param left Where to store left channel value
726 * @param right Where to store right channel value
727 * @return 0 on success, non-0 on error
729 int disorder_get_volume(disorder_client
*c
, int *left
, int *right
) {
733 if((rc
= disorder_simple(c
, &r
, "volume", (char *)0)))
735 if(sscanf(r
, "%d %d", left
, right
) != 2) {
736 c
->last
= "malformed volume response";
737 disorder_error(0, "error parsing response to 'volume': '%s'", r
);
743 /** @brief Log to a sink
745 * @param s Sink to write log lines to
746 * @return 0 on success, non-0 on error
748 int disorder_log(disorder_client
*c
, struct sink
*s
) {
752 if((rc
= disorder_simple(c
, 0, "log", (char *)0)))
754 while(inputline(c
->ident
, c
->fpin
, &l
, '\n') >= 0 && strcmp(l
, "."))
755 if(sink_printf(s
, "%s\n", l
) < 0) return -1;
756 if(ferror(c
->fpin
) || feof(c
->fpin
)) {
757 byte_xasprintf((char **)&c
->last
, "input error: %s",
758 ferror(c
->fpin
) ?
strerror(errno
) : "unexpxected EOF");
764 /** @brief Get recently added tracks
766 * @param vecp Where to store pointer to list (UTF-8)
767 * @param nvecp Where to store count
768 * @param max Maximum tracks to fetch, or 0 for all available
769 * @return 0 on success, non-0 on error
771 int disorder_new_tracks(disorder_client
*c
,
772 char ***vecp
, int *nvecp
,
776 sprintf(limit
, "%d", max
);
777 return disorder_simple_list(c
, vecp
, nvecp
, "new", limit
, (char *)0);
780 /** @brief Get server's RTP address information
782 * @param addressp Where to store address (UTF-8)
783 * @param portp Where to store port (UTF-8)
784 * @return 0 on success, non-0 on error
786 int disorder_rtp_address(disorder_client
*c
, char **addressp
, char **portp
) {
791 if((rc
= disorder_simple(c
, &r
, "rtp-address", (char *)0)))
793 vec
= split(r
, &n
, SPLIT_QUOTES
, 0, 0);
795 c
->last
= "malformed RTP address";
796 disorder_error(0, "malformed rtp-address reply");
804 /** @brief Get details of a scheduled event
807 * @param actiondatap Where to put details
808 * @return 0 on success, non-0 on error
810 int disorder_schedule_get(disorder_client
*c
, const char *id
,
811 struct kvp
**actiondatap
) {
812 char **lines
, **bits
;
816 if((rc
= disorder_simple_list(c
, &lines
, NULL
,
817 "schedule-get", id
, (char *)0)))
820 if(!(bits
= split(*lines
++, &nbits
, SPLIT_QUOTES
, 0, 0))) {
821 disorder_error(0, "invalid schedule-get reply: cannot split line");
825 disorder_error(0, "invalid schedule-get reply: wrong number of fields");
828 kvp_set(actiondatap
, bits
[0], bits
[1]);
833 /** @brief Add a scheduled event
835 * @param when When to trigger the event
836 * @param priority Event priority ("normal" or "junk")
837 * @param action What action to perform
838 * @param ... Action-specific arguments
839 * @return 0 on success, non-0 on error
841 * For action @c "play" the next argument is the track.
843 * For action @c "set-global" next argument is the global preference name
844 * and the final argument the value to set it to, or (char *)0 to unset it.
846 int disorder_schedule_add(disorder_client
*c
,
848 const char *priority
,
855 snprintf(when_str
, sizeof when_str
, "%lld", (long long)when
);
856 va_start(ap
, action
);
857 if(!strcmp(action
, "play"))
858 rc
= disorder_simple(c
, 0, "schedule-add", when_str
, priority
,
859 action
, va_arg(ap
, char *),
861 else if(!strcmp(action
, "set-global")) {
862 const char *key
= va_arg(ap
, char *);
863 const char *value
= va_arg(ap
, char *);
864 rc
= disorder_simple(c
, 0,"schedule-add", when_str
, priority
,
868 disorder_fatal(0, "unknown action '%s'", action
);
873 #include "client-stubs.c"