chiark / gitweb /
Improve doc comments.
[disorder] / lib / client.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004-2008 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     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     return 0;
145   } else {
146     if(c->verbose)
147       error(0, "from %s: %s", c->ident, utf82mb(r));
148     return rc;
149   }
150 }
151
152 /** @brief Issue a command and parse a simple response
153  * @param c Client
154  * @param rp Where to store result, or NULL
155  * @param cmd Command
156  * @param body Body or NULL
157  * @param nbody Length of body or -1
158  * @param ap Arguments (UTF-8), terminated by (char *)0
159  * @return 0 on success, non-0 on error
160  *
161  * 5xx responses count as errors.
162  *
163  * @p rp will NOT be filled in for xx9 responses (where it is just
164  * commentary for a command where it would normally be meaningful).
165  *
166  * NB that the response will NOT be converted to the local encoding
167  * nor will quotes be stripped.  See dequote().
168  *
169  * If @p body is not NULL then the body is sent immediately after the
170  * command.  @p nbody should be the number of lines or @c -1 to count
171  * them if @p body is NULL-terminated.
172  *
173  * Usually you would call this via one of the following interfaces:
174  * - disorder_simple()
175  * - disorder_simple_body()
176  * - disorder_simple_list()
177  */
178 static int disorder_simple_v(disorder_client *c,
179                              char **rp,
180                              const char *cmd,
181                              char **body, int nbody,
182                              va_list ap) {
183   const char *arg;
184   struct dynstr d;
185
186   if(!c->fpout) {
187     c->last = "not connected";
188     error(0, "not connected to server");
189     return -1;
190   }
191   if(cmd) {
192     dynstr_init(&d);
193     dynstr_append_string(&d, cmd);
194     while((arg = va_arg(ap, const char *))) {
195       dynstr_append(&d, ' ');
196       dynstr_append_string(&d, quoteutf8(arg));
197     }
198     dynstr_append(&d, '\n');
199     dynstr_terminate(&d);
200     D(("command: %s", d.vec));
201     if(fputs(d.vec, c->fpout) < 0)
202       goto write_error;
203     if(body) {
204       if(nbody < 0)
205         for(nbody = 0; body[nbody]; ++nbody)
206           ;
207       for(int n = 0; n < nbody; ++n) {
208         if(body[n][0] == '.')
209           if(fputc('.', c->fpout) < 0)
210             goto write_error;
211         if(fputs(body[n], c->fpout) < 0)
212           goto write_error;
213         if(fputc('\n', c->fpout) < 0)
214           goto write_error;
215       }
216       if(fputs(".\n", c->fpout) < 0)
217         goto write_error;
218     }
219     if(fflush(c->fpout))
220       goto write_error;
221   }
222   return check_response(c, rp);
223 write_error:
224   byte_xasprintf((char **)&c->last, "write error: %s", strerror(errno));
225   error(errno, "error writing to %s", c->ident);
226   return -1;
227 }
228
229 /** @brief Issue a command and parse a simple response
230  * @param c Client
231  * @param rp Where to store result, or NULL (UTF-8)
232  * @param cmd Command
233  * @return 0 on success, non-0 on error
234  *
235  * The remaining arguments are command arguments, terminated by (char
236  * *)0.  They should be in UTF-8.
237  *
238  * 5xx responses count as errors.
239  *
240  * @p rp will NOT be filled in for xx9 responses (where it is just
241  * commentary for a command where it would normally be meaningful).
242  *
243  * NB that the response will NOT be converted to the local encoding
244  * nor will quotes be stripped.  See dequote().
245  */
246 static int disorder_simple(disorder_client *c,
247                            char **rp,
248                            const char *cmd, ...) {
249   va_list ap;
250   int ret;
251
252   va_start(ap, cmd);
253   ret = disorder_simple_v(c, rp, cmd, 0, 0, ap);
254   va_end(ap);
255   return ret;
256 }
257
258 /** @brief Issue a command with a body and parse a simple response
259  * @param c Client
260  * @param rp Where to store result, or NULL (UTF-8)
261  * @param body Pointer to body
262  * @param nbody Size of body
263  * @param cmd Command
264  * @return 0 on success, non-0 on error
265  *
266  * See disorder_simple().
267  */
268 static int disorder_simple_body(disorder_client *c,
269                                 char **rp,
270                                 char **body, int nbody,
271                                 const char *cmd, ...) {
272   va_list ap;
273   int ret;
274
275   va_start(ap, cmd);
276   ret = disorder_simple_v(c, rp, cmd, body, nbody, ap);
277   va_end(ap);
278   return ret;
279 }
280
281 /** @brief Dequote a result string
282  * @param rc 0 on success, non-0 on error
283  * @param rp Where result string is stored (UTF-8)
284  * @return @p rc
285  *
286  * This is used as a wrapper around disorder_simple() to dequote
287  * results in place.
288  */
289 static int dequote(int rc, char **rp) {
290   char **rr;
291
292   if(!rc) {
293     if((rr = split(*rp, 0, SPLIT_QUOTES, 0, 0)) && *rr) {
294       *rp = *rr;
295       return 0;
296     }
297     error(0, "invalid reply: %s", *rp);
298   }
299   return rc;
300 }
301
302 /** @brief Generic connection routine
303  * @param conf Configuration to follow
304  * @param c Client
305  * @param username Username to log in with or NULL
306  * @param password Password to log in with or NULL
307  * @param cookie Cookie to log in with or NULL
308  * @return 0 on success, non-0 on error
309  *
310  * @p cookie is tried first if not NULL.  If it is NULL then @p
311  * username must not be.  If @p username is not NULL then nor may @p
312  * password be.
313  */
314 int disorder_connect_generic(struct config *conf,
315                              disorder_client *c,
316                              const char *username,
317                              const char *password,
318                              const char *cookie) {
319   int fd = -1, fd2 = -1, nrvec, rc;
320   unsigned char *nonce;
321   size_t nl;
322   const char *res;
323   char *r, **rvec;
324   const char *protocol, *algorithm, *challenge;
325   struct sockaddr *sa;
326   socklen_t salen;
327
328   if((salen = find_server(conf, &sa, &c->ident)) == (socklen_t)-1)
329     return -1;
330   c->fpin = c->fpout = 0;
331   if((fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0) {
332     byte_xasprintf((char **)&c->last, "socket: %s", strerror(errno));
333     error(errno, "error calling socket");
334     return -1;
335   }
336   if(connect(fd, sa, salen) < 0) {
337     byte_xasprintf((char **)&c->last, "connect: %s", strerror(errno));
338     error(errno, "error calling connect");
339     goto error;
340   }
341   if((fd2 = dup(fd)) < 0) {
342     byte_xasprintf((char **)&c->last, "dup: %s", strerror(errno));
343     error(errno, "error calling dup");
344     goto error;
345   }
346   if(!(c->fpin = fdopen(fd, "rb"))) {
347     byte_xasprintf((char **)&c->last, "fdopen: %s", strerror(errno));
348     error(errno, "error calling fdopen");
349     goto error;
350   }
351   fd = -1;
352   if(!(c->fpout = fdopen(fd2, "wb"))) {
353     byte_xasprintf((char **)&c->last, "fdopen: %s", strerror(errno));
354     error(errno, "error calling fdopen");
355     goto error;
356   }
357   fd2 = -1;
358   if((rc = disorder_simple(c, &r, 0, (const char *)0)))
359     goto error_rc;
360   if(!(rvec = split(r, &nrvec, SPLIT_QUOTES, 0, 0)))
361     goto error;
362   if(nrvec != 3) {
363     c->last = "cannot parse server greeting";
364     error(0, "cannot parse server greeting %s", r);
365     goto error;
366   }
367   protocol = *rvec++;
368   if(strcmp(protocol, "2")) {
369     c->last = "unknown protocol version";
370     error(0, "unknown protocol version: %s", protocol);
371     goto error;
372   }
373   algorithm = *rvec++;
374   challenge = *rvec++;
375   if(!(nonce = unhex(challenge, &nl)))
376     goto error;
377   if(cookie) {
378     if(!dequote(disorder_simple(c, &c->user, "cookie", cookie, (char *)0),
379                 &c->user))
380       return 0;                         /* success */
381     if(!username) {
382       c->last = "cookie failed and no username";
383       error(0, "cookie did not work and no username available");
384       goto error;
385     }
386   }
387   if(!(res = authhash(nonce, nl, password, algorithm))) {
388     c->last = "error computing authorization hash";
389     goto error;
390   }
391   if((rc = disorder_simple(c, 0, "user", username, res, (char *)0)))
392     goto error_rc;
393   c->user = xstrdup(username);
394   return 0;
395 error:
396   rc = -1;
397 error_rc:
398   if(c->fpin) {
399     fclose(c->fpin);
400     c->fpin = 0;
401   }
402   if(c->fpout) {
403     fclose(c->fpout);
404     c->fpout = 0;
405   }
406   if(fd2 != -1) close(fd2);
407   if(fd != -1) close(fd);
408   return rc;
409 }
410
411 /** @brief Connect a client with a specified username and password
412  * @param c Client
413  * @param username Username to log in with
414  * @param password Password to log in with
415  * @return 0 on success, non-0 on error
416  */
417 int disorder_connect_user(disorder_client *c,
418                           const char *username,
419                           const char *password) {
420   return disorder_connect_generic(config,
421                                   c,
422                                   username,
423                                   password,
424                                   0);
425 }
426
427 /** @brief Connect a client
428  * @param c Client
429  * @return 0 on success, non-0 on error
430  *
431  * The connection will use the username and password found in @ref
432  * config, or directly from the database if no password is found and
433  * the database is readable (usually only for root).
434  */
435 int disorder_connect(disorder_client *c) {
436   const char *username, *password;
437
438   if(!(username = config->username)) {
439     c->last = "no username";
440     error(0, "no username configured");
441     return -1;
442   }
443   password = config->password;
444   /* Maybe we can read the database */
445   if(!password && trackdb_readable()) {
446     trackdb_init(TRACKDB_NO_RECOVER|TRACKDB_NO_UPGRADE);
447     trackdb_open(TRACKDB_READ_ONLY);
448     password = trackdb_get_password(username);
449     trackdb_close();
450   }
451   if(!password) {
452     /* Oh well */
453     c->last = "no password";
454     error(0, "no password configured for user '%s'", username);
455     return -1;
456   }
457   return disorder_connect_generic(config,
458                                   c,
459                                   username,
460                                   password,
461                                   0);
462 }
463
464 /** @brief Connect a client
465  * @param c Client
466  * @param cookie Cookie to log in with, or NULL
467  * @return 0 on success, non-0 on error
468  *
469  * If @p cookie is NULL or does not work then we attempt to log in as
470  * guest instead (so when the cookie expires only an extra round trip
471  * is needed rathre than a complete new login).
472  */
473 int disorder_connect_cookie(disorder_client *c,
474                             const char *cookie) {
475   return disorder_connect_generic(config,
476                                   c,
477                                   "guest",
478                                   "",
479                                   cookie);
480 }
481
482 /** @brief Close a client
483  * @param c Client
484  * @return 0 on succcess, non-0 on errior
485  *
486  * The client is still closed even on error.  It might well be
487  * appropriate to ignore the return value.
488  */
489 int disorder_close(disorder_client *c) {
490   int ret = 0;
491
492   if(c->fpin) {
493     if(fclose(c->fpin) < 0) {
494       byte_xasprintf((char **)&c->last, "fclose: %s", strerror(errno));
495       error(errno, "error calling fclose");
496       ret = -1;
497     }
498     c->fpin = 0;
499   }
500   if(c->fpout) {
501     if(fclose(c->fpout) < 0) {
502       byte_xasprintf((char **)&c->last, "fclose: %s", strerror(errno));
503       error(errno, "error calling fclose");
504       ret = -1;
505     }
506     c->fpout = 0;
507   }
508   c->ident = 0;
509   c->user = 0;
510   return 0;
511 }
512
513 /** @brief Play a track
514  * @param c Client
515  * @param track Track to play (UTF-8)
516  * @return 0 on success, non-0 on error
517  */
518 int disorder_play(disorder_client *c, const char *track) {
519   return disorder_simple(c, 0, "play", track, (char *)0);
520 }
521
522 /** @brief Remove a track
523  * @param c Client
524  * @param track Track to remove (UTF-8)
525  * @return 0 on success, non-0 on error
526  */
527 int disorder_remove(disorder_client *c, const char *track) {
528   return disorder_simple(c, 0, "remove", track, (char *)0);
529 }
530
531 /** @brief Move a track
532  * @param c Client
533  * @param track Track to move (UTF-8)
534  * @param delta Distance to move by
535  * @return 0 on success, non-0 on error
536  */
537 int disorder_move(disorder_client *c, const char *track, int delta) {
538   char d[16];
539
540   byte_snprintf(d, sizeof d, "%d", delta);
541   return disorder_simple(c, 0, "move", track, d, (char *)0);
542 }
543
544 /** @brief Enable play
545  * @param c Client
546  * @return 0 on success, non-0 on error
547  */
548 int disorder_enable(disorder_client *c) {
549   return disorder_simple(c, 0, "enable", (char *)0);
550 }
551
552 /** @brief Disable play
553  * @param c Client
554  * @return 0 on success, non-0 on error
555  */
556 int disorder_disable(disorder_client *c) {
557   return disorder_simple(c, 0, "disable", (char *)0);
558 }
559
560 /** @brief Scratch the currently playing track
561  * @param id Playing track ID or NULL (UTF-8)
562  * @param c Client
563  * @return 0 on success, non-0 on error
564  */
565 int disorder_scratch(disorder_client *c, const char *id) {
566   return disorder_simple(c, 0, "scratch", id, (char *)0);
567 }
568
569 /** @brief Shut down the server
570  * @param c Client
571  * @return 0 on success, non-0 on error
572  */
573 int disorder_shutdown(disorder_client *c) {
574   return disorder_simple(c, 0, "shutdown", (char *)0);
575 }
576
577 /** @brief Make the server re-read its configuration
578  * @param c Client
579  * @return 0 on success, non-0 on error
580  */
581 int disorder_reconfigure(disorder_client *c) {
582   return disorder_simple(c, 0, "reconfigure", (char *)0);
583 }
584
585 /** @brief Rescan tracks
586  * @param c Client
587  * @return 0 on success, non-0 on error
588  */
589 int disorder_rescan(disorder_client *c) {
590   return disorder_simple(c, 0, "rescan", (char *)0);
591 }
592
593 /** @brief Get server version number
594  * @param c Client
595  * @param rp Where to store version string (UTF-8)
596  * @return 0 on success, non-0 on error
597  */
598 int disorder_version(disorder_client *c, char **rp) {
599   return dequote(disorder_simple(c, rp, "version", (char *)0), rp);
600 }
601
602 static void client_error(const char *msg,
603                          void attribute((unused)) *u) {
604   error(0, "error parsing reply: %s", msg);
605 }
606
607 /** @brief Get currently playing track
608  * @param c Client
609  * @param qp Where to store track information
610  * @return 0 on success, non-0 on error
611  *
612  * @p qp gets NULL if no track is playing.
613  */
614 int disorder_playing(disorder_client *c, struct queue_entry **qp) {
615   char *r;
616   struct queue_entry *q;
617   int rc;
618
619   if((rc = disorder_simple(c, &r, "playing", (char *)0)))
620     return rc;
621   if(r) {
622     q = xmalloc(sizeof *q);
623     if(queue_unmarshall(q, r, client_error, 0))
624       return -1;
625     *qp = q;
626   } else
627     *qp = 0;
628   return 0;
629 }
630
631 /** @brief Fetch the queue, recent list, etc */
632 static int disorder_somequeue(disorder_client *c,
633                               const char *cmd, struct queue_entry **qp) {
634   struct queue_entry *qh, **qt = &qh, *q;
635   char *l;
636   int rc;
637
638   if((rc = disorder_simple(c, 0, cmd, (char *)0)))
639     return rc;
640   while(inputline(c->ident, c->fpin, &l, '\n') >= 0) {
641     if(!strcmp(l, ".")) {
642       *qt = 0;
643       *qp = qh;
644       return 0;
645     }
646     q = xmalloc(sizeof *q);
647     if(!queue_unmarshall(q, l, client_error, 0)) {
648       *qt = q;
649       qt = &q->next;
650     }
651   }
652   if(ferror(c->fpin)) {
653     byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
654     error(errno, "error reading %s", c->ident);
655   } else {
656     c->last = "input error: unexpxected EOF";
657     error(0, "error reading %s: unexpected EOF", c->ident);
658   }
659   return -1;
660 }
661
662 /** @brief Get recently played tracks
663  * @param c Client
664  * @param qp Where to store track information
665  * @return 0 on success, non-0 on error
666  *
667  * The last entry in the list is the most recently played track.
668  */
669 int disorder_recent(disorder_client *c, struct queue_entry **qp) {
670   return disorder_somequeue(c, "recent", qp);
671 }
672
673 /** @brief Get queue
674  * @param c Client
675  * @param qp Where to store track information
676  * @return 0 on success, non-0 on error
677  *
678  * The first entry in the list will be played next.
679  */
680 int disorder_queue(disorder_client *c, struct queue_entry **qp) {
681   return disorder_somequeue(c, "queue", qp);
682 }
683
684 /** @brief Read a dot-stuffed list
685  * @param c Client
686  * @param vecp Where to store list (UTF-8)
687  * @param nvecp Where to store number of items, or NULL
688  * @return 0 on success, non-0 on error
689  *
690  * The list will have a final NULL not counted in @p nvecp.
691  */
692 static int readlist(disorder_client *c, char ***vecp, int *nvecp) {
693   char *l;
694   struct vector v;
695
696   vector_init(&v);
697   while(inputline(c->ident, c->fpin, &l, '\n') >= 0) {
698     if(!strcmp(l, ".")) {
699       vector_terminate(&v);
700       if(nvecp)
701         *nvecp = v.nvec;
702       *vecp = v.vec;
703       return 0;
704     }
705     vector_append(&v, l + (*l == '.'));
706   }
707   if(ferror(c->fpin)) {
708     byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
709     error(errno, "error reading %s", c->ident);
710   } else {
711     c->last = "input error: unexpxected EOF";
712     error(0, "error reading %s: unexpected EOF", c->ident);
713   }
714   return -1;
715 }
716
717 /** @brief Issue a comamnd and get a list response
718  * @param c Client
719  * @param vecp Where to store list (UTF-8)
720  * @param nvecp Where to store number of items, or NULL
721  * @param cmd Command
722  * @return 0 on success, non-0 on error
723  *
724  * The remaining arguments are command arguments, terminated by (char
725  * *)0.  They should be in UTF-8.
726  *
727  * 5xx responses count as errors.
728  *
729  * See disorder_simple().
730  */
731 static int disorder_simple_list(disorder_client *c,
732                                 char ***vecp, int *nvecp,
733                                 const char *cmd, ...) {
734   va_list ap;
735   int ret;
736
737   va_start(ap, cmd);
738   ret = disorder_simple_v(c, 0, cmd, 0, 0, ap);
739   va_end(ap);
740   if(ret) return ret;
741   return readlist(c, vecp, nvecp);
742 }
743
744 /** @brief List directories below @p dir
745  * @param c Client
746  * @param dir Directory to list, or NULL for root (UTF-8)
747  * @param re Regexp that results must match, or NULL (UTF-8)
748  * @param vecp Where to store list (UTF-8)
749  * @param nvecp Where to store number of items, or NULL
750  * @return 0 on success, non-0 on error
751  */
752 int disorder_directories(disorder_client *c, const char *dir, const char *re,
753                          char ***vecp, int *nvecp) {
754   return disorder_simple_list(c, vecp, nvecp, "dirs", dir, re, (char *)0);
755 }
756
757 /** @brief List files below @p dir
758  * @param c Client
759  * @param dir Directory to list, or NULL for root (UTF-8)
760  * @param re Regexp that results must match, or NULL (UTF-8)
761  * @param vecp Where to store list (UTF-8)
762  * @param nvecp Where to store number of items, or NULL
763  * @return 0 on success, non-0 on error
764  */
765 int disorder_files(disorder_client *c, const char *dir, const char *re,
766                    char ***vecp, int *nvecp) {
767   return disorder_simple_list(c, vecp, nvecp, "files", dir, re, (char *)0);
768 }
769
770 /** @brief List files and directories below @p dir
771  * @param c Client
772  * @param dir Directory to list, or NULL for root (UTF-8)
773  * @param re Regexp that results must match, or NULL (UTF-8)
774  * @param vecp Where to store list (UTF-8)
775  * @param nvecp Where to store number of items, or NULL
776  * @return 0 on success, non-0 on error
777  */
778 int disorder_allfiles(disorder_client *c, const char *dir, const char *re,
779                       char ***vecp, int *nvecp) {
780   return disorder_simple_list(c, vecp, nvecp, "allfiles", dir, re, (char *)0);
781 }
782
783 /** @brief Return the user we logged in with
784  * @param c Client
785  * @return User name (owned by @p c, don't modify)
786  */
787 char *disorder_user(disorder_client *c) {
788   return c->user;
789 }
790
791 /** @brief Set a track preference
792  * @param c Client
793  * @param track Track name (UTF-8)
794  * @param key Preference name (UTF-8)
795  * @param value Preference value (UTF-8)
796  * @return 0 on success, non-0 on error
797  */
798 int disorder_set(disorder_client *c, const char *track,
799                  const char *key, const char *value) {
800   return disorder_simple(c, 0, "set", track, key, value, (char *)0);
801 }
802
803 /** @brief Unset a track preference
804  * @param c Client
805  * @param track Track name (UTF-8)
806  * @param key Preference name (UTF-8)
807  * @return 0 on success, non-0 on error
808  */
809 int disorder_unset(disorder_client *c, const char *track,
810                    const char *key) {
811   return disorder_simple(c, 0, "unset", track, key, (char *)0);
812 }
813
814 /** @brief Get a track preference
815  * @param c Client
816  * @param track Track name (UTF-8)
817  * @param key Preference name (UTF-8)
818  * @param valuep Where to store preference value (UTF-8)
819  * @return 0 on success, non-0 on error
820  */
821 int disorder_get(disorder_client *c,
822                  const char *track, const char *key, char **valuep) {
823   return dequote(disorder_simple(c, valuep, "get", track, key, (char *)0),
824                  valuep);
825 }
826
827 static void pref_error_handler(const char *msg,
828                                void attribute((unused)) *u) {
829   error(0, "error handling 'prefs' reply: %s", msg);
830 }
831
832 /** @brief Get all preferences for a trcak
833  * @param c Client
834  * @param track Track name
835  * @param kp Where to store linked list of preferences
836  * @return 0 on success, non-0 on error
837  */
838 int disorder_prefs(disorder_client *c, const char *track, struct kvp **kp) {
839   char **vec, **pvec;
840   int nvec, npvec, n, rc;
841   struct kvp *k;
842
843   if((rc = disorder_simple_list(c, &vec, &nvec, "prefs", track, (char *)0)))
844     return rc;
845   for(n = 0; n < nvec; ++n) {
846     if(!(pvec = split(vec[n], &npvec, SPLIT_QUOTES, pref_error_handler, 0)))
847       return -1;
848     if(npvec != 2) {
849       pref_error_handler("malformed response", 0);
850       return -1;
851     }
852     *kp = k = xmalloc(sizeof *k);
853     k->name = pvec[0];
854     k->value = pvec[1];
855     kp = &k->next;
856   }
857   *kp = 0;
858   return 0;
859 }
860
861 /** @brief Parse a boolean response
862  * @param cmd Command for use in error messsage
863  * @param value Result from server
864  * @param flagp Where to store result
865  * @return 0 on success, non-0 on error
866  */
867 static int boolean(const char *cmd, const char *value,
868                    int *flagp) {
869   if(!strcmp(value, "yes")) *flagp = 1;
870   else if(!strcmp(value, "no")) *flagp = 0;
871   else {
872     error(0, "malformed response to '%s'", cmd);
873     return -1;
874   }
875   return 0;
876 }
877
878 /** @brief Test whether a track exists
879  * @param c Client
880  * @param track Track name (UTF-8)
881  * @param existsp Where to store result (non-0 iff does exist)
882  * @return 0 on success, non-0 on error
883  */
884 int disorder_exists(disorder_client *c, const char *track, int *existsp) {
885   char *v;
886   int rc;
887
888   if((rc = disorder_simple(c, &v, "exists", track, (char *)0)))
889     return rc;
890   return boolean("exists", v, existsp);
891 }
892
893 /** @brief Test whether playing is enabled
894  * @param c Client
895  * @param enabledp Where to store result (non-0 iff enabled)
896  * @return 0 on success, non-0 on error
897  */
898 int disorder_enabled(disorder_client *c, int *enabledp) {
899   char *v;
900   int rc;
901
902   if((rc = disorder_simple(c, &v, "enabled", (char *)0)))
903     return rc;
904   return boolean("enabled", v, enabledp);
905 }
906
907 /** @brief Get the length of a track
908  * @param c Client
909  * @param track Track name (UTF-8)
910  * @param valuep Where to store length in seconds
911  * @return 0 on success, non-0 on error
912  *
913  * If the length is unknown 0 is returned.
914  */
915 int disorder_length(disorder_client *c, const char *track,
916                     long *valuep) {
917   char *value;
918   int rc;
919
920   if((rc = disorder_simple(c, &value, "length", track, (char *)0)))
921     return rc;
922   *valuep = atol(value);
923   return 0;
924 }
925
926 /** @brief Search for tracks
927  * @param c Client
928  * @param terms Search terms (UTF-8)
929  * @param vecp Where to store list (UTF-8)
930  * @param nvecp Where to store number of items, or NULL
931  * @return 0 on success, non-0 on error
932  */
933 int disorder_search(disorder_client *c, const char *terms,
934                     char ***vecp, int *nvecp) {
935   return disorder_simple_list(c, vecp, nvecp, "search", terms, (char *)0);
936 }
937
938 /** @brief Enable random play
939  * @param c Client
940  * @return 0 on success, non-0 on error
941  */
942 int disorder_random_enable(disorder_client *c) {
943   return disorder_simple(c, 0, "random-enable", (char *)0);
944 }
945
946 /** @brief Disable random play
947  * @param c Client
948  * @return 0 on success, non-0 on error
949  */
950 int disorder_random_disable(disorder_client *c) {
951   return disorder_simple(c, 0, "random-disable", (char *)0);
952 }
953
954 /** @brief Test whether random play is enabled
955  * @param c Client
956  * @param enabledp Where to store result (non-0 iff enabled)
957  * @return 0 on success, non-0 on error
958  */
959 int disorder_random_enabled(disorder_client *c, int *enabledp) {
960   char *v;
961   int rc;
962
963   if((rc = disorder_simple(c, &v, "random-enabled", (char *)0)))
964     return rc;
965   return boolean("random-enabled", v, enabledp);
966 }
967
968 /** @brief Get server stats
969  * @param c Client
970  * @param vecp Where to store list (UTF-8)
971  * @param nvecp Where to store number of items, or NULL
972  * @return 0 on success, non-0 on error
973  */
974 int disorder_stats(disorder_client *c,
975                    char ***vecp, int *nvecp) {
976   return disorder_simple_list(c, vecp, nvecp, "stats", (char *)0);
977 }
978
979 /** @brief Set volume
980  * @param c Client
981  * @param left New left channel value
982  * @param right New right channel value
983  * @return 0 on success, non-0 on error
984  */
985 int disorder_set_volume(disorder_client *c, int left, int right) {
986   char *ls, *rs;
987
988   if(byte_asprintf(&ls, "%d", left) < 0
989      || byte_asprintf(&rs, "%d", right) < 0)
990     return -1;
991   return disorder_simple(c, 0, "volume", ls, rs, (char *)0);
992 }
993
994 /** @brief Get volume
995  * @param c Client
996  * @param left Where to store left channel value
997  * @param right Where to store right channel value
998  * @return 0 on success, non-0 on error
999  */
1000 int disorder_get_volume(disorder_client *c, int *left, int *right) {
1001   char *r;
1002   int rc;
1003
1004   if((rc = disorder_simple(c, &r, "volume", (char *)0)))
1005     return rc;
1006   if(sscanf(r, "%d %d", left, right) != 2) {
1007     c->last = "malformed volume response";
1008     error(0, "error parsing response to 'volume': '%s'", r);
1009     return -1;
1010   }
1011   return 0;
1012 }
1013
1014 /** @brief Log to a sink
1015  * @param c Client
1016  * @param s Sink to write log lines to
1017  * @return 0 on success, non-0 on error
1018  */
1019 int disorder_log(disorder_client *c, struct sink *s) {
1020   char *l;
1021   int rc;
1022     
1023   if((rc = disorder_simple(c, 0, "log", (char *)0)))
1024     return rc;
1025   while(inputline(c->ident, c->fpin, &l, '\n') >= 0 && strcmp(l, "."))
1026     if(sink_printf(s, "%s\n", l) < 0) return -1;
1027   if(ferror(c->fpin) || feof(c->fpin)) {
1028     byte_xasprintf((char **)&c->last, "input error: %s",
1029                    ferror(c->fpin) ? strerror(errno) : "unexpxected EOF");
1030     return -1;
1031   }
1032   return 0;
1033 }
1034
1035 /** @brief Look up a track name part
1036  * @param c Client
1037  * @param partp Where to store result (UTF-8)
1038  * @param track Track name (UTF-8)
1039  * @param context Context (usually "sort" or "display") (UTF-8)
1040  * @param part Track part (UTF-8)
1041  * @return 0 on success, non-0 on error
1042  */
1043 int disorder_part(disorder_client *c, char **partp,
1044                   const char *track, const char *context, const char *part) {
1045   return dequote(disorder_simple(c, partp, "part",
1046                                  track, context, part, (char *)0), partp);
1047 }
1048
1049 /** @brief Resolve aliases
1050  * @param c Client
1051  * @param trackp Where to store canonical name (UTF-8)
1052  * @param track Track name (UTF-8)
1053  * @return 0 on success, non-0 on error
1054  */
1055 int disorder_resolve(disorder_client *c, char **trackp, const char *track) {
1056   return dequote(disorder_simple(c, trackp, "resolve", track, (char *)0),
1057                  trackp);
1058 }
1059
1060 /** @brief Pause the current track
1061  * @param c Client
1062  * @return 0 on success, non-0 on error
1063  */
1064 int disorder_pause(disorder_client *c) {
1065   return disorder_simple(c, 0, "pause", (char *)0);
1066 }
1067
1068 /** @brief Resume the current track
1069  * @param c Client
1070  * @return 0 on success, non-0 on error
1071  */
1072 int disorder_resume(disorder_client *c) {
1073   return disorder_simple(c, 0, "resume", (char *)0);
1074 }
1075
1076 /** @brief List all known tags
1077  * @param c Client
1078  * @param vecp Where to store list (UTF-8)
1079  * @param nvecp Where to store number of items, or NULL
1080  * @return 0 on success, non-0 on error
1081  */
1082 int disorder_tags(disorder_client *c,
1083                    char ***vecp, int *nvecp) {
1084   return disorder_simple_list(c, vecp, nvecp, "tags", (char *)0);
1085 }
1086
1087 /** @brief List all known users
1088  * @param c Client
1089  * @param vecp Where to store list (UTF-8)
1090  * @param nvecp Where to store number of items, or NULL
1091  * @return 0 on success, non-0 on error
1092  */
1093 int disorder_users(disorder_client *c,
1094                    char ***vecp, int *nvecp) {
1095   return disorder_simple_list(c, vecp, nvecp, "users", (char *)0);
1096 }
1097
1098 /** @brief Get recently added tracks
1099  * @param c Client
1100  * @param vecp Where to store pointer to list (UTF-8)
1101  * @param nvecp Where to store count
1102  * @param max Maximum tracks to fetch, or 0 for all available
1103  * @return 0 on success, non-0 on error
1104  */
1105 int disorder_new_tracks(disorder_client *c,
1106                         char ***vecp, int *nvecp,
1107                         int max) {
1108   char limit[32];
1109
1110   sprintf(limit, "%d", max);
1111   return disorder_simple_list(c, vecp, nvecp, "new", limit, (char *)0);
1112 }
1113
1114 /** @brief Set a global preference
1115  * @param c Client
1116  * @param key Preference name (UTF-8)
1117  * @param value Preference value (UTF-8)
1118  * @return 0 on success, non-0 on error
1119  */
1120 int disorder_set_global(disorder_client *c,
1121                         const char *key, const char *value) {
1122   return disorder_simple(c, 0, "set-global", key, value, (char *)0);
1123 }
1124
1125 /** @brief Unset a global preference
1126  * @param c Client
1127  * @param key Preference name (UTF-8)
1128  * @return 0 on success, non-0 on error
1129  */
1130 int disorder_unset_global(disorder_client *c, const char *key) {
1131   return disorder_simple(c, 0, "unset-global", key, (char *)0);
1132 }
1133
1134 /** @brief Get a global preference
1135  * @param c Client
1136  * @param key Preference name (UTF-8)
1137  * @param valuep Where to store preference value (UTF-8)
1138  * @return 0 on success, non-0 on error
1139  */
1140 int disorder_get_global(disorder_client *c, const char *key, char **valuep) {
1141   return dequote(disorder_simple(c, valuep, "get-global", key, (char *)0),
1142                  valuep);
1143 }
1144
1145 /** @brief Get server's RTP address information
1146  * @param c Client
1147  * @param addressp Where to store address (UTF-8)
1148  * @param portp Where to store port (UTF-8)
1149  * @return 0 on success, non-0 on error
1150  */
1151 int disorder_rtp_address(disorder_client *c, char **addressp, char **portp) {
1152   char *r;
1153   int rc, n;
1154   char **vec;
1155
1156   if((rc = disorder_simple(c, &r, "rtp-address", (char *)0)))
1157     return rc;
1158   vec = split(r, &n, SPLIT_QUOTES, 0, 0);
1159   if(n != 2) {
1160     c->last = "malformed RTP address";
1161     error(0, "malformed rtp-address reply");
1162     return -1;
1163   }
1164   *addressp = vec[0];
1165   *portp = vec[1];
1166   return 0;
1167 }
1168
1169 /** @brief Create a user
1170  * @param c Client
1171  * @param user Username
1172  * @param password Password
1173  * @param rights Initial rights or NULL to use default
1174  * @return 0 on success, non-0 on error
1175  */
1176 int disorder_adduser(disorder_client *c,
1177                      const char *user, const char *password,
1178                      const char *rights) {
1179   return disorder_simple(c, 0, "adduser", user, password, rights, (char *)0);
1180 }
1181
1182 /** @brief Delete a user
1183  * @param c Client
1184  * @param user Username
1185  * @return 0 on success, non-0 on error
1186  */
1187 int disorder_deluser(disorder_client *c, const char *user) {
1188   return disorder_simple(c, 0, "deluser", user, (char *)0);
1189 }
1190
1191 /** @brief Get user information
1192  * @param c Client
1193  * @param user Username
1194  * @param key Property name (UTF-8)
1195  * @param valuep Where to store value (UTF-8)
1196  * @return 0 on success, non-0 on error
1197  */
1198 int disorder_userinfo(disorder_client *c, const char *user, const char *key,
1199                       char **valuep) {
1200   return dequote(disorder_simple(c, valuep, "userinfo", user, key, (char *)0),
1201                  valuep);
1202 }
1203
1204 /** @brief Set user information
1205  * @param c Client
1206  * @param user Username
1207  * @param key Property name (UTF-8)
1208  * @param value New property value (UTF-8)
1209  * @return 0 on success, non-0 on error
1210  */
1211 int disorder_edituser(disorder_client *c, const char *user,
1212                       const char *key, const char *value) {
1213   return disorder_simple(c, 0, "edituser", user, key, value, (char *)0);
1214 }
1215
1216 /** @brief Register a user
1217  * @param c Client
1218  * @param user Username
1219  * @param password Password
1220  * @param email Email address (UTF-8)
1221  * @param confirmp Where to store confirmation string
1222  * @return 0 on success, non-0 on error
1223  */
1224 int disorder_register(disorder_client *c, const char *user,
1225                       const char *password, const char *email,
1226                       char **confirmp) {
1227   return dequote(disorder_simple(c, confirmp, "register",
1228                                  user, password, email, (char *)0),
1229                  confirmp);
1230 }
1231
1232 /** @brief Confirm a user
1233  * @param c Client
1234  * @param confirm Confirmation string
1235  * @return 0 on success, non-0 on error
1236  */
1237 int disorder_confirm(disorder_client *c, const char *confirm) {
1238   char *u;
1239   int rc;
1240   
1241   if(!(rc = dequote(disorder_simple(c, &u, "confirm", confirm, (char *)0),
1242                     &u)))
1243     c->user = u;
1244   return rc;
1245 }
1246
1247 /** @brief Make a cookie for this login
1248  * @param c Client
1249  * @param cookiep Where to store cookie string
1250  * @return 0 on success, non-0 on error
1251  */
1252 int disorder_make_cookie(disorder_client *c, char **cookiep) {
1253   return dequote(disorder_simple(c, cookiep, "make-cookie", (char *)0),
1254                  cookiep);
1255 }
1256
1257 /** @brief Revoke the cookie used by this session
1258  * @param c Client
1259  * @return 0 on success, non-0 on error
1260  */
1261 int disorder_revoke(disorder_client *c) {
1262   return disorder_simple(c, 0, "revoke", (char *)0);
1263 }
1264
1265 /** @brief Request a password reminder email
1266  * @param c Client
1267  * @param user Username
1268  * @return 0 on success, non-0 on error
1269  */
1270 int disorder_reminder(disorder_client *c, const char *user) {
1271   return disorder_simple(c, 0, "reminder", user, (char *)0);
1272 }
1273
1274 /** @brief List scheduled events
1275  * @param c Client
1276  * @param idsp Where to put list of event IDs
1277  * @param nidsp Where to put count of event IDs, or NULL
1278  * @return 0 on success, non-0 on error
1279  */
1280 int disorder_schedule_list(disorder_client *c, char ***idsp, int *nidsp) {
1281   return disorder_simple_list(c, idsp, nidsp, "schedule-list", (char *)0);
1282 }
1283
1284 /** @brief Delete a scheduled event
1285  * @param c Client
1286  * @param id Event ID to delete
1287  * @return 0 on success, non-0 on error
1288  */
1289 int disorder_schedule_del(disorder_client *c, const char *id) {
1290   return disorder_simple(c, 0, "schedule-del", id, (char *)0);
1291 }
1292
1293 /** @brief Get details of a scheduled event
1294  * @param c Client
1295  * @param id Event ID
1296  * @param actiondatap Where to put details
1297  * @return 0 on success, non-0 on error
1298  */
1299 int disorder_schedule_get(disorder_client *c, const char *id,
1300                           struct kvp **actiondatap) {
1301   char **lines, **bits;
1302   int rc, nbits;
1303
1304   *actiondatap = 0;
1305   if((rc = disorder_simple_list(c, &lines, NULL,
1306                                 "schedule-get", id, (char *)0)))
1307     return rc;
1308   while(*lines) {
1309     if(!(bits = split(*lines++, &nbits, SPLIT_QUOTES, 0, 0))) {
1310       error(0, "invalid schedule-get reply: cannot split line");
1311       return -1;
1312     }
1313     if(nbits != 2) {
1314       error(0, "invalid schedule-get reply: wrong number of fields");
1315       return -1;
1316     }
1317     kvp_set(actiondatap, bits[0], bits[1]);
1318   }
1319   return 0;
1320 }
1321
1322 /** @brief Add a scheduled event
1323  * @param c Client
1324  * @param when When to trigger the event
1325  * @param priority Event priority ("normal" or "junk")
1326  * @param action What action to perform
1327  * @param ... Action-specific arguments
1328  * @return 0 on success, non-0 on error
1329  *
1330  * For action @c "play" the next argument is the track.
1331  *
1332  * For action @c "set-global" next argument is the global preference name
1333  * and the final argument the value to set it to, or (char *)0 to unset it.
1334  */
1335 int disorder_schedule_add(disorder_client *c,
1336                           time_t when,
1337                           const char *priority,
1338                           const char *action,
1339                           ...) {
1340   va_list ap;
1341   char when_str[64];
1342   int rc;
1343
1344   snprintf(when_str, sizeof when_str, "%lld", (long long)when);
1345   va_start(ap, action);
1346   if(!strcmp(action, "play"))
1347     rc = disorder_simple(c, 0, "schedule-add", when_str, priority,
1348                          action, va_arg(ap, char *),
1349                          (char *)0);
1350   else if(!strcmp(action, "set-global")) {
1351     const char *key = va_arg(ap, char *);
1352     const char *value = va_arg(ap, char *);
1353     rc = disorder_simple(c, 0,"schedule-add",  when_str, priority,
1354                          action, key, value,
1355                          (char *)0);
1356   } else
1357     fatal(0, "unknown action '%s'", action);
1358   va_end(ap);
1359   return rc;
1360 }
1361
1362 /** @brief Adopt a track
1363  * @param c Client
1364  * @param id Track ID to adopt
1365  * @return 0 on success, non-0 on error
1366  */
1367 int disorder_adopt(disorder_client *c, const char *id) {
1368   return disorder_simple(c, 0, "adopt", id, (char *)0);
1369 }
1370
1371 /** @brief Delete a playlist
1372  * @param c Client
1373  * @param playlist Playlist to delete
1374  * @return 0 on success, non-0 on error
1375  */
1376 int disorder_playlist_delete(disorder_client *c,
1377                              const char *playlist) {
1378   return disorder_simple(c, 0, "playlist-delete", playlist, (char *)0);
1379 }
1380
1381 /** @brief Get the contents of a playlist
1382  * @param c Client
1383  * @param playlist Playlist to get
1384  * @param tracksp Where to put list of tracks
1385  * @param ntracksp Where to put count of tracks
1386  * @return 0 on success, non-0 on error
1387  */
1388 int disorder_playlist_get(disorder_client *c, const char *playlist,
1389                           char ***tracksp, int *ntracksp) {
1390   return disorder_simple_list(c, tracksp, ntracksp,
1391                               "playlist-get", playlist, (char *)0);
1392 }
1393
1394 /** @brief List all readable playlists
1395  * @param c Client
1396  * @param playlistsp Where to put list of playlists
1397  * @param nplaylistsp Where to put count of playlists
1398  * @return 0 on success, non-0 on error
1399  */
1400 int disorder_playlists(disorder_client *c,
1401                        char ***playlistsp, int *nplaylistsp) {
1402   return disorder_simple_list(c, playlistsp, nplaylistsp,
1403                               "playlists", (char *)0);
1404 }
1405
1406 /** @brief Get the sharing status of a playlist
1407  * @param c Client
1408  * @param playlist Playlist to inspect
1409  * @param sharep Where to put sharing status
1410  * @return 0 on success, non-0 on error
1411  *
1412  * Possible @p sharep values are @c public, @c private and @c shared.
1413  */
1414 int disorder_playlist_get_share(disorder_client *c, const char *playlist,
1415                                 char **sharep) {
1416   return disorder_simple(c, sharep,
1417                          "playlist-get-share", playlist, (char *)0);
1418 }
1419
1420 /** @brief Get the sharing status of a playlist
1421  * @param c Client
1422  * @param playlist Playlist to modify
1423  * @param share New sharing status
1424  * @return 0 on success, non-0 on error
1425  *
1426  * Possible @p share values are @c public, @c private and @c shared.
1427  */
1428 int disorder_playlist_set_share(disorder_client *c, const char *playlist,
1429                                 const char *share) {
1430   return disorder_simple(c, 0,
1431                          "playlist-set-share", playlist, share, (char *)0);
1432 }
1433
1434 /** @brief Lock a playlist for modifications
1435  * @param c Client
1436  * @param playlist Playlist to lock
1437  * @return 0 on success, non-0 on error
1438  */
1439 int disorder_playlist_lock(disorder_client *c, const char *playlist) {
1440   return disorder_simple(c, 0,
1441                          "playlist-lock", playlist, (char *)0);
1442 }
1443
1444 /** @brief Unlock the locked playlist
1445  * @param c Client
1446  * @return 0 on success, non-0 on error
1447  */
1448 int disorder_playlist_unlock(disorder_client *c) {
1449   return disorder_simple(c, 0,
1450                          "playlist-unlock", (char *)0);
1451 }
1452
1453 /** @brief Set the contents of a playlst
1454  * @param c Client
1455  * @param playlist Playlist to modify
1456  * @param tracks List of tracks
1457  * @param ntracks Length of @p tracks (or -1 to count up to the first NULL)
1458  * @return 0 on success, non-0 on error
1459  */
1460 int disorder_playlist_set(disorder_client *c,
1461                           const char *playlist,
1462                           char **tracks,
1463                           int ntracks) {
1464   return disorder_simple_body(c, 0, tracks, ntracks,
1465                               "playlist-set", playlist, (char *)0);
1466 }
1467
1468 /*
1469 Local Variables:
1470 c-basic-offset:2
1471 comment-column:40
1472 End:
1473 */