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