chiark / gitweb /
play command
[disorder] / lib / client.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004-2009 Richard Kettlewell
4  *
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.
9  * 
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.
14  * 
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/>.
17  */
18 /** @file lib/client.c
19  * @brief Simple C client
20  *
21  * See @ref lib/eclient.c for an asynchronous-capable client
22  * implementation.
23  */
24
25 #include "common.h"
26
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <sys/un.h>
31 #include <unistd.h>
32 #include <errno.h>
33 #include <netdb.h>
34 #include <pcre.h>
35
36 #include "log.h"
37 #include "mem.h"
38 #include "queue.h"
39 #include "client.h"
40 #include "charset.h"
41 #include "hex.h"
42 #include "split.h"
43 #include "vector.h"
44 #include "inputline.h"
45 #include "kvp.h"
46 #include "syscalls.h"
47 #include "printf.h"
48 #include "sink.h"
49 #include "addr.h"
50 #include "authhash.h"
51 #include "client-common.h"
52 #include "rights.h"
53 #include "trackdb.h"
54 #include "kvp.h"
55
56 /** @brief Client handle contents */
57 struct disorder_client {
58   /** @brief Stream to read from */
59   FILE *fpin;
60   /** @brief Stream to write to */
61   FILE *fpout;
62   /** @brief Peer description */
63   char *ident;
64   /** @brief Username */
65   char *user;
66   /** @brief Report errors to @c stderr */
67   int verbose;
68   /** @brief Last error string */
69   const char *last;
70 };
71
72 /** @brief Create a new client
73  * @param verbose If nonzero, write extra junk to stderr
74  * @return Pointer to new client
75  *
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.
79  */
80 disorder_client *disorder_new(int verbose) {
81   disorder_client *c = xmalloc(sizeof (struct disorder_client));
82
83   c->verbose = verbose;
84   return c;
85 }
86
87 /** @brief Read a response line
88  * @param c Client
89  * @param rp Where to store response, or NULL (UTF-8)
90  * @return Response code 0-999 or -1 on error
91  */
92 static int response(disorder_client *c, char **rp) {
93   char *r;
94
95   if(inputline(c->ident, c->fpin, &r, '\n')) {
96     byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
97     return -1;
98   }
99   D(("response: %s", r));
100   if(rp)
101     *rp = r;
102   if(r[0] >= '0' && r[0] <= '9'
103      && r[1] >= '0' && r[1] <= '9'
104      && r[2] >= '0' && r[2] <= '9'
105      && r[3] == ' ') {
106     c->last = r + 4;
107     return (r[0] * 10 + r[1]) * 10 + r[2] - 111 * '0';
108   } else {
109     c->last = "invalid reply format";
110     disorder_error(0, "invalid reply format from %s", c->ident);
111     return -1;
112   }
113 }
114
115 /** @brief Return last response string
116  * @param c Client
117  * @return Last response string (UTF-8, English) or NULL
118  */
119 const char *disorder_last(disorder_client *c) {
120   return c->last;
121 }
122
123 /** @brief Read and partially parse a response
124  * @param c Client
125  * @param rp Where to store response text (or NULL) (UTF-8)
126  * @return 0 on success, non-0 on error
127  *
128  * 5xx responses count as errors.
129  *
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).
132  *
133  * NB that the response will NOT be converted to the local encoding.
134  */
135 static int check_response(disorder_client *c, char **rp) {
136   int rc;
137   char *r;
138
139   if((rc = response(c, &r)) == -1)
140     return -1;
141   else if(rc / 100 == 2) {
142     if(rp)
143       *rp = (rc % 10 == 9) ? 0 : xstrdup(r + 4);
144     xfree(r);
145     return 0;
146   } else {
147     if(c->verbose)
148       disorder_error(0, "from %s: %s", c->ident, utf82mb(r));
149     xfree(r);
150     return rc;
151   }
152 }
153
154 /** @brief Issue a command and parse a simple response
155  * @param c Client
156  * @param rp Where to store result, or NULL
157  * @param cmd Command
158  * @param body Body or NULL
159  * @param nbody Length of body or -1
160  * @param ap Arguments (UTF-8), terminated by (char *)0
161  * @return 0 on success, non-0 on error
162  *
163  * 5xx responses count as errors.
164  *
165  * @p rp will NOT be filled in for xx9 responses (where it is just
166  * commentary for a command where it would normally be meaningful).
167  *
168  * NB that the response will NOT be converted to the local encoding
169  * nor will quotes be stripped.  See dequote().
170  *
171  * If @p body is not NULL then the body is sent immediately after the
172  * command.  @p nbody should be the number of lines or @c -1 to count
173  * them if @p body is NULL-terminated.
174  *
175  * Usually you would call this via one of the following interfaces:
176  * - disorder_simple()
177  * - disorder_simple_body()
178  * - disorder_simple_list()
179  */
180 static int disorder_simple_v(disorder_client *c,
181                              char **rp,
182                              const char *cmd,
183                              char **body, int nbody,
184                              va_list ap) {
185   const char *arg;
186   struct dynstr d;
187
188   if(!c->fpout) {
189     c->last = "not connected";
190     disorder_error(0, "not connected to server");
191     return -1;
192   }
193   if(cmd) {
194     dynstr_init(&d);
195     dynstr_append_string(&d, cmd);
196     while((arg = va_arg(ap, const char *))) {
197       dynstr_append(&d, ' ');
198       dynstr_append_string(&d, quoteutf8(arg));
199     }
200     dynstr_append(&d, '\n');
201     dynstr_terminate(&d);
202     D(("command: %s", d.vec));
203     if(fputs(d.vec, c->fpout) < 0)
204       goto write_error;
205     xfree(d.vec);
206     if(body) {
207       if(nbody < 0)
208         for(nbody = 0; body[nbody]; ++nbody)
209           ;
210       for(int n = 0; n < nbody; ++n) {
211         if(body[n][0] == '.')
212           if(fputc('.', c->fpout) < 0)
213             goto write_error;
214         if(fputs(body[n], c->fpout) < 0)
215           goto write_error;
216         if(fputc('\n', c->fpout) < 0)
217           goto write_error;
218       }
219       if(fputs(".\n", c->fpout) < 0)
220         goto write_error;
221     }
222     if(fflush(c->fpout))
223       goto write_error;
224   }
225   return check_response(c, rp);
226 write_error:
227   byte_xasprintf((char **)&c->last, "write error: %s", strerror(errno));
228   disorder_error(errno, "error writing to %s", c->ident);
229   return -1;
230 }
231
232 /** @brief Issue a command and parse a simple response
233  * @param c Client
234  * @param rp Where to store result, or NULL (UTF-8)
235  * @param cmd Command
236  * @return 0 on success, non-0 on error
237  *
238  * The remaining arguments are command arguments, terminated by (char
239  * *)0.  They should be in UTF-8.
240  *
241  * 5xx responses count as errors.
242  *
243  * @p rp will NOT be filled in for xx9 responses (where it is just
244  * commentary for a command where it would normally be meaningful).
245  *
246  * NB that the response will NOT be converted to the local encoding
247  * nor will quotes be stripped.  See dequote().
248  */
249 static int disorder_simple(disorder_client *c,
250                            char **rp,
251                            const char *cmd, ...) {
252   va_list ap;
253   int ret;
254
255   va_start(ap, cmd);
256   ret = disorder_simple_v(c, rp, cmd, 0, 0, ap);
257   va_end(ap);
258   return ret;
259 }
260
261 /** @brief Issue a command with a body and parse a simple response
262  * @param c Client
263  * @param rp Where to store result, or NULL (UTF-8)
264  * @param body Pointer to body
265  * @param nbody Size of body
266  * @param cmd Command
267  * @return 0 on success, non-0 on error
268  *
269  * See disorder_simple().
270  */
271 static int disorder_simple_body(disorder_client *c,
272                                 char **rp,
273                                 char **body, int nbody,
274                                 const char *cmd, ...) {
275   va_list ap;
276   int ret;
277
278   va_start(ap, cmd);
279   ret = disorder_simple_v(c, rp, cmd, body, nbody, ap);
280   va_end(ap);
281   return ret;
282 }
283
284 /** @brief Dequote a result string
285  * @param rc 0 on success, non-0 on error
286  * @param rp Where result string is stored (UTF-8)
287  * @return @p rc
288  *
289  * This is used as a wrapper around disorder_simple() to dequote
290  * results in place.
291  */
292 static int dequote(int rc, char **rp) {
293   char **rr;
294
295   if(!rc) {
296     if((rr = split(*rp, 0, SPLIT_QUOTES, 0, 0)) && *rr) {
297       xfree(*rp);
298       *rp = *rr;
299       xfree(rr);
300       return 0;
301     }
302     disorder_error(0, "invalid reply: %s", *rp);
303   }
304   return rc;
305 }
306
307 /** @brief Generic connection routine
308  * @param conf Configuration to follow
309  * @param c Client
310  * @param username Username to log in with or NULL
311  * @param password Password to log in with or NULL
312  * @param cookie Cookie to log in with or NULL
313  * @return 0 on success, non-0 on error
314  *
315  * @p cookie is tried first if not NULL.  If it is NULL then @p
316  * username must not be.  If @p username is not NULL then nor may @p
317  * password be.
318  */
319 int disorder_connect_generic(struct config *conf,
320                              disorder_client *c,
321                              const char *username,
322                              const char *password,
323                              const char *cookie) {
324   int fd = -1, fd2 = -1, nrvec = 0, rc;
325   unsigned char *nonce = NULL;
326   size_t nl;
327   char *res = NULL;
328   char *r = NULL, **rvec = NULL;
329   const char *protocol, *algorithm, *challenge;
330   struct sockaddr *sa = NULL;
331   socklen_t salen;
332
333   if((salen = find_server(conf, &sa, &c->ident)) == (socklen_t)-1)
334     return -1;
335   c->fpin = c->fpout = 0;
336   if((fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0) {
337     byte_xasprintf((char **)&c->last, "socket: %s", strerror(errno));
338     disorder_error(errno, "error calling socket");
339     return -1;
340   }
341   if(connect(fd, sa, salen) < 0) {
342     byte_xasprintf((char **)&c->last, "connect: %s", strerror(errno));
343     disorder_error(errno, "error calling connect");
344     goto error;
345   }
346   if((fd2 = dup(fd)) < 0) {
347     byte_xasprintf((char **)&c->last, "dup: %s", strerror(errno));
348     disorder_error(errno, "error calling dup");
349     goto error;
350   }
351   if(!(c->fpin = fdopen(fd, "rb"))) {
352     byte_xasprintf((char **)&c->last, "fdopen: %s", strerror(errno));
353     disorder_error(errno, "error calling fdopen");
354     goto error;
355   }
356   fd = -1;
357   if(!(c->fpout = fdopen(fd2, "wb"))) {
358     byte_xasprintf((char **)&c->last, "fdopen: %s", strerror(errno));
359     disorder_error(errno, "error calling fdopen");
360     goto error;
361   }
362   fd2 = -1;
363   if((rc = disorder_simple(c, &r, 0, (const char *)0)))
364     goto error_rc;
365   if(!(rvec = split(r, &nrvec, SPLIT_QUOTES, 0, 0)))
366     goto error;
367   if(nrvec != 3) {
368     c->last = "cannot parse server greeting";
369     disorder_error(0, "cannot parse server greeting %s", r);
370     goto error;
371   }
372   protocol = rvec[0];
373   if(strcmp(protocol, "2")) {
374     c->last = "unknown protocol version";
375     disorder_error(0, "unknown protocol version: %s", protocol);
376     goto error;
377   }
378   algorithm = rvec[1];
379   challenge = rvec[2];
380   if(!(nonce = unhex(challenge, &nl)))
381     goto error;
382   if(cookie) {
383     if(!dequote(disorder_simple(c, &c->user, "cookie", cookie, (char *)0),
384                 &c->user))
385       return 0;                         /* success */
386     if(!username) {
387       c->last = "cookie failed and no username";
388       disorder_error(0, "cookie did not work and no username available");
389       goto error;
390     }
391   }
392   if(!(res = authhash(nonce, nl, password, algorithm))) {
393     c->last = "error computing authorization hash";
394     goto error;
395   }
396   if((rc = disorder_simple(c, 0, "user", username, res, (char *)0)))
397     goto error_rc;
398   c->user = xstrdup(username);
399   xfree(res);
400   free_strings(nrvec, rvec);
401   xfree(nonce);
402   xfree(sa);
403   xfree(r);
404   return 0;
405 error:
406   rc = -1;
407 error_rc:
408   if(c->fpin) {
409     fclose(c->fpin);
410     c->fpin = 0;
411   }
412   if(c->fpout) {
413     fclose(c->fpout);
414     c->fpout = 0;
415   }
416   if(fd2 != -1) close(fd2);
417   if(fd != -1) close(fd);
418   return rc;
419 }
420
421 /** @brief Connect a client with a specified username and password
422  * @param c Client
423  * @param username Username to log in with
424  * @param password Password to log in with
425  * @return 0 on success, non-0 on error
426  */
427 int disorder_connect_user(disorder_client *c,
428                           const char *username,
429                           const char *password) {
430   return disorder_connect_generic(config,
431                                   c,
432                                   username,
433                                   password,
434                                   0);
435 }
436
437 /** @brief Connect a client
438  * @param c Client
439  * @return 0 on success, non-0 on error
440  *
441  * The connection will use the username and password found in @ref
442  * config, or directly from the database if no password is found and
443  * the database is readable (usually only for root).
444  */
445 int disorder_connect(disorder_client *c) {
446   const char *username, *password;
447
448   if(!(username = config->username)) {
449     c->last = "no username";
450     disorder_error(0, "no username configured");
451     return -1;
452   }
453   password = config->password;
454   /* Maybe we can read the database */
455   if(!password && trackdb_readable()) {
456     trackdb_init(TRACKDB_NO_RECOVER|TRACKDB_NO_UPGRADE);
457     trackdb_open(TRACKDB_READ_ONLY);
458     password = trackdb_get_password(username);
459     trackdb_close();
460   }
461   if(!password) {
462     /* Oh well */
463     c->last = "no password";
464     disorder_error(0, "no password configured for user '%s'", username);
465     return -1;
466   }
467   return disorder_connect_generic(config,
468                                   c,
469                                   username,
470                                   password,
471                                   0);
472 }
473
474 /** @brief Connect a client
475  * @param c Client
476  * @param cookie Cookie to log in with, or NULL
477  * @return 0 on success, non-0 on error
478  *
479  * If @p cookie is NULL or does not work then we attempt to log in as
480  * guest instead (so when the cookie expires only an extra round trip
481  * is needed rathre than a complete new login).
482  */
483 int disorder_connect_cookie(disorder_client *c,
484                             const char *cookie) {
485   return disorder_connect_generic(config,
486                                   c,
487                                   "guest",
488                                   "",
489                                   cookie);
490 }
491
492 /** @brief Close a client
493  * @param c Client
494  * @return 0 on succcess, non-0 on errior
495  *
496  * The client is still closed even on error.  It might well be
497  * appropriate to ignore the return value.
498  */
499 int disorder_close(disorder_client *c) {
500   int ret = 0;
501
502   if(c->fpin) {
503     if(fclose(c->fpin) < 0) {
504       byte_xasprintf((char **)&c->last, "fclose: %s", strerror(errno));
505       disorder_error(errno, "error calling fclose");
506       ret = -1;
507     }
508     c->fpin = 0;
509   }
510   if(c->fpout) {
511     if(fclose(c->fpout) < 0) {
512       byte_xasprintf((char **)&c->last, "fclose: %s", strerror(errno));
513       disorder_error(errno, "error calling fclose");
514       ret = -1;
515     }
516     c->fpout = 0;
517   }
518   xfree(c->ident);
519   c->ident = 0;
520   xfree(c->user);
521   c->user = 0;
522   return ret;
523 }
524
525 /** @brief Move a track
526  * @param c Client
527  * @param track Track to move (UTF-8)
528  * @param delta Distance to move by
529  * @return 0 on success, non-0 on error
530  */
531 int disorder_move(disorder_client *c, const char *track, int delta) {
532   char d[16];
533
534   byte_snprintf(d, sizeof d, "%d", delta);
535   return disorder_simple(c, 0, "move", track, d, (char *)0);
536 }
537
538 static void client_error(const char *msg,
539                          void attribute((unused)) *u) {
540   disorder_error(0, "error parsing reply: %s", msg);
541 }
542
543 /** @brief Get currently playing track
544  * @param c Client
545  * @param qp Where to store track information
546  * @return 0 on success, non-0 on error
547  *
548  * @p qp gets NULL if no track is playing.
549  */
550 int disorder_playing(disorder_client *c, struct queue_entry **qp) {
551   char *r;
552   struct queue_entry *q;
553   int rc;
554
555   if((rc = disorder_simple(c, &r, "playing", (char *)0)))
556     return rc;
557   if(r) {
558     q = xmalloc(sizeof *q);
559     if(queue_unmarshall(q, r, client_error, 0))
560       return -1;
561     *qp = q;
562   } else
563     *qp = 0;
564   return 0;
565 }
566
567 /** @brief Fetch the queue, recent list, etc */
568 static int disorder_somequeue(disorder_client *c,
569                               const char *cmd, struct queue_entry **qp) {
570   struct queue_entry *qh, **qt = &qh, *q;
571   char *l;
572   int rc;
573
574   if((rc = disorder_simple(c, 0, cmd, (char *)0)))
575     return rc;
576   while(inputline(c->ident, c->fpin, &l, '\n') >= 0) {
577     if(!strcmp(l, ".")) {
578       *qt = 0;
579       *qp = qh;
580       xfree(l);
581       return 0;
582     }
583     q = xmalloc(sizeof *q);
584     if(!queue_unmarshall(q, l, client_error, 0)) {
585       *qt = q;
586       qt = &q->next;
587     }
588     xfree(l);
589   }
590   if(ferror(c->fpin)) {
591     byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
592     disorder_error(errno, "error reading %s", c->ident);
593   } else {
594     c->last = "input error: unexpxected EOF";
595     disorder_error(0, "error reading %s: unexpected EOF", c->ident);
596   }
597   return -1;
598 }
599
600 /** @brief Get recently played tracks
601  * @param c Client
602  * @param qp Where to store track information
603  * @return 0 on success, non-0 on error
604  *
605  * The last entry in the list is the most recently played track.
606  */
607 int disorder_recent(disorder_client *c, struct queue_entry **qp) {
608   return disorder_somequeue(c, "recent", qp);
609 }
610
611 /** @brief Get queue
612  * @param c Client
613  * @param qp Where to store track information
614  * @return 0 on success, non-0 on error
615  *
616  * The first entry in the list will be played next.
617  */
618 int disorder_queue(disorder_client *c, struct queue_entry **qp) {
619   return disorder_somequeue(c, "queue", qp);
620 }
621
622 /** @brief Read a dot-stuffed list
623  * @param c Client
624  * @param vecp Where to store list (UTF-8)
625  * @param nvecp Where to store number of items, or NULL
626  * @return 0 on success, non-0 on error
627  *
628  * The list will have a final NULL not counted in @p nvecp.
629  */
630 static int readlist(disorder_client *c, char ***vecp, int *nvecp) {
631   char *l;
632   struct vector v;
633
634   vector_init(&v);
635   while(inputline(c->ident, c->fpin, &l, '\n') >= 0) {
636     if(!strcmp(l, ".")) {
637       vector_terminate(&v);
638       if(nvecp)
639         *nvecp = v.nvec;
640       *vecp = v.vec;
641       xfree(l);
642       return 0;
643     }
644     vector_append(&v, xstrdup(l + (*l == '.')));
645     xfree(l);
646   }
647   if(ferror(c->fpin)) {
648     byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
649     disorder_error(errno, "error reading %s", c->ident);
650   } else {
651     c->last = "input error: unexpxected EOF";
652     disorder_error(0, "error reading %s: unexpected EOF", c->ident);
653   }
654   return -1;
655 }
656
657 /** @brief Issue a comamnd and get a list response
658  * @param c Client
659  * @param vecp Where to store list (UTF-8)
660  * @param nvecp Where to store number of items, or NULL
661  * @param cmd Command
662  * @return 0 on success, non-0 on error
663  *
664  * The remaining arguments are command arguments, terminated by (char
665  * *)0.  They should be in UTF-8.
666  *
667  * 5xx responses count as errors.
668  *
669  * See disorder_simple().
670  */
671 static int disorder_simple_list(disorder_client *c,
672                                 char ***vecp, int *nvecp,
673                                 const char *cmd, ...) {
674   va_list ap;
675   int ret;
676
677   va_start(ap, cmd);
678   ret = disorder_simple_v(c, 0, cmd, 0, 0, ap);
679   va_end(ap);
680   if(ret) return ret;
681   return readlist(c, vecp, nvecp);
682 }
683
684 /** @brief Return the user we logged in with
685  * @param c Client
686  * @return User name (owned by @p c, don't modify)
687  */
688 char *disorder_user(disorder_client *c) {
689   return c->user;
690 }
691
692 static void pref_error_handler(const char *msg,
693                                void attribute((unused)) *u) {
694   disorder_error(0, "error handling 'prefs' reply: %s", msg);
695 }
696
697 /** @brief Get all preferences for a trcak
698  * @param c Client
699  * @param track Track name
700  * @param kp Where to store linked list of preferences
701  * @return 0 on success, non-0 on error
702  */
703 int disorder_prefs(disorder_client *c, const char *track, struct kvp **kp) {
704   char **vec, **pvec;
705   int nvec, npvec, n, rc;
706   struct kvp *k;
707
708   if((rc = disorder_simple_list(c, &vec, &nvec, "prefs", track, (char *)0)))
709     return rc;
710   for(n = 0; n < nvec; ++n) {
711     if(!(pvec = split(vec[n], &npvec, SPLIT_QUOTES, pref_error_handler, 0)))
712       return -1;
713     if(npvec != 2) {
714       pref_error_handler("malformed response", 0);
715       return -1;
716     }
717     *kp = k = xmalloc(sizeof *k);
718     k->name = pvec[0];
719     k->value = pvec[1];
720     kp = &k->next;
721     xfree(pvec);
722   }
723   free_strings(nvec, vec);
724   *kp = 0;
725   return 0;
726 }
727
728 /** @brief Parse a boolean response
729  * @param cmd Command for use in error messsage
730  * @param value Result from server
731  * @param flagp Where to store result
732  * @return 0 on success, non-0 on error
733  */
734 static int boolean(const char *cmd, const char *value,
735                    int *flagp) {
736   if(!strcmp(value, "yes")) *flagp = 1;
737   else if(!strcmp(value, "no")) *flagp = 0;
738   else {
739     disorder_error(0, "malformed response to '%s'", cmd);
740     return -1;
741   }
742   return 0;
743 }
744
745 /** @brief Get the length of a track
746  * @param c Client
747  * @param track Track name (UTF-8)
748  * @param valuep Where to store length in seconds
749  * @return 0 on success, non-0 on error
750  *
751  * If the length is unknown 0 is returned.
752  */
753 int disorder_length(disorder_client *c, const char *track,
754                     long *valuep) {
755   char *value;
756   int rc;
757
758   if((rc = disorder_simple(c, &value, "length", track, (char *)0)))
759     return rc;
760   *valuep = atol(value);
761   return 0;
762 }
763
764 /** @brief Set volume
765  * @param c Client
766  * @param left New left channel value
767  * @param right New right channel value
768  * @return 0 on success, non-0 on error
769  */
770 int disorder_set_volume(disorder_client *c, int left, int right) {
771   char *ls, *rs;
772
773   if(byte_asprintf(&ls, "%d", left) < 0
774      || byte_asprintf(&rs, "%d", right) < 0)
775     return -1;
776   return disorder_simple(c, 0, "volume", ls, rs, (char *)0);
777 }
778
779 /** @brief Get volume
780  * @param c Client
781  * @param left Where to store left channel value
782  * @param right Where to store right channel value
783  * @return 0 on success, non-0 on error
784  */
785 int disorder_get_volume(disorder_client *c, int *left, int *right) {
786   char *r;
787   int rc;
788
789   if((rc = disorder_simple(c, &r, "volume", (char *)0)))
790     return rc;
791   if(sscanf(r, "%d %d", left, right) != 2) {
792     c->last = "malformed volume response";
793     disorder_error(0, "error parsing response to 'volume': '%s'", r);
794     return -1;
795   }
796   return 0;
797 }
798
799 /** @brief Log to a sink
800  * @param c Client
801  * @param s Sink to write log lines to
802  * @return 0 on success, non-0 on error
803  */
804 int disorder_log(disorder_client *c, struct sink *s) {
805   char *l;
806   int rc;
807     
808   if((rc = disorder_simple(c, 0, "log", (char *)0)))
809     return rc;
810   while(inputline(c->ident, c->fpin, &l, '\n') >= 0 && strcmp(l, "."))
811     if(sink_printf(s, "%s\n", l) < 0) return -1;
812   if(ferror(c->fpin) || feof(c->fpin)) {
813     byte_xasprintf((char **)&c->last, "input error: %s",
814                    ferror(c->fpin) ? strerror(errno) : "unexpxected EOF");
815     return -1;
816   }
817   return 0;
818 }
819
820 /** @brief Get recently added tracks
821  * @param c Client
822  * @param vecp Where to store pointer to list (UTF-8)
823  * @param nvecp Where to store count
824  * @param max Maximum tracks to fetch, or 0 for all available
825  * @return 0 on success, non-0 on error
826  */
827 int disorder_new_tracks(disorder_client *c,
828                         char ***vecp, int *nvecp,
829                         int max) {
830   char limit[32];
831
832   sprintf(limit, "%d", max);
833   return disorder_simple_list(c, vecp, nvecp, "new", limit, (char *)0);
834 }
835
836 /** @brief Get server's RTP address information
837  * @param c Client
838  * @param addressp Where to store address (UTF-8)
839  * @param portp Where to store port (UTF-8)
840  * @return 0 on success, non-0 on error
841  */
842 int disorder_rtp_address(disorder_client *c, char **addressp, char **portp) {
843   char *r;
844   int rc, n;
845   char **vec;
846
847   if((rc = disorder_simple(c, &r, "rtp-address", (char *)0)))
848     return rc;
849   vec = split(r, &n, SPLIT_QUOTES, 0, 0);
850   if(n != 2) {
851     c->last = "malformed RTP address";
852     disorder_error(0, "malformed rtp-address reply");
853     return -1;
854   }
855   *addressp = vec[0];
856   *portp = vec[1];
857   return 0;
858 }
859
860 /** @brief Get details of a scheduled event
861  * @param c Client
862  * @param id Event ID
863  * @param actiondatap Where to put details
864  * @return 0 on success, non-0 on error
865  */
866 int disorder_schedule_get(disorder_client *c, const char *id,
867                           struct kvp **actiondatap) {
868   char **lines, **bits;
869   int rc, nbits;
870
871   *actiondatap = 0;
872   if((rc = disorder_simple_list(c, &lines, NULL,
873                                 "schedule-get", id, (char *)0)))
874     return rc;
875   while(*lines) {
876     if(!(bits = split(*lines++, &nbits, SPLIT_QUOTES, 0, 0))) {
877       disorder_error(0, "invalid schedule-get reply: cannot split line");
878       return -1;
879     }
880     if(nbits != 2) {
881       disorder_error(0, "invalid schedule-get reply: wrong number of fields");
882       return -1;
883     }
884     kvp_set(actiondatap, bits[0], bits[1]);
885   }
886   return 0;
887 }
888
889 /** @brief Add a scheduled event
890  * @param c Client
891  * @param when When to trigger the event
892  * @param priority Event priority ("normal" or "junk")
893  * @param action What action to perform
894  * @param ... Action-specific arguments
895  * @return 0 on success, non-0 on error
896  *
897  * For action @c "play" the next argument is the track.
898  *
899  * For action @c "set-global" next argument is the global preference name
900  * and the final argument the value to set it to, or (char *)0 to unset it.
901  */
902 int disorder_schedule_add(disorder_client *c,
903                           time_t when,
904                           const char *priority,
905                           const char *action,
906                           ...) {
907   va_list ap;
908   char when_str[64];
909   int rc;
910
911   snprintf(when_str, sizeof when_str, "%lld", (long long)when);
912   va_start(ap, action);
913   if(!strcmp(action, "play"))
914     rc = disorder_simple(c, 0, "schedule-add", when_str, priority,
915                          action, va_arg(ap, char *),
916                          (char *)0);
917   else if(!strcmp(action, "set-global")) {
918     const char *key = va_arg(ap, char *);
919     const char *value = va_arg(ap, char *);
920     rc = disorder_simple(c, 0,"schedule-add",  when_str, priority,
921                          action, key, value,
922                          (char *)0);
923   } else
924     disorder_fatal(0, "unknown action '%s'", action);
925   va_end(ap);
926   return rc;
927 }
928
929 /** @brief Set the contents of a playlst
930  * @param c Client
931  * @param playlist Playlist to modify
932  * @param tracks List of tracks
933  * @param ntracks Length of @p tracks (or -1 to count up to the first NULL)
934  * @return 0 on success, non-0 on error
935  */
936 int disorder_playlist_set(disorder_client *c,
937                           const char *playlist,
938                           char **tracks,
939                           int ntracks) {
940   return disorder_simple_body(c, 0, tracks, ntracks,
941                               "playlist-set", playlist, (char *)0);
942 }
943
944 #include "client-stubs.c"
945
946 /*
947 Local Variables:
948 c-basic-offset:2
949 comment-column:40
950 End:
951 */