2 * This file is part of DisOrder.
3 * Copyright (C) 2004-13 Richard Kettlewell
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 /** @file lib/client.c
19 * @brief Simple C client
21 * See @ref lib/eclient.c for an asynchronous-capable client
27 #include <sys/types.h>
29 # include <sys/socket.h>
32 # include <netinet/in.h>
56 #include "inputline.h"
63 #include "client-common.h"
67 /** @brief Client handle contents */
68 struct disorder_client {
69 /** @brief Stream to read from */
71 /** @brief Stream to write to */
73 /** @brief Peer description */
75 /** @brief Username */
77 /** @brief Report errors to @c stderr */
79 /** @brief Last error string */
81 /** @brief Address family */
85 /** @brief Create a new client
86 * @param verbose If nonzero, write extra junk to stderr
87 * @return Pointer to new client
89 * You must call disorder_connect(), disorder_connect_user() or
90 * disorder_connect_cookie() to connect it. Use disorder_close() to
91 * dispose of the client when finished with it.
93 disorder_client *disorder_new(int verbose) {
94 disorder_client *c = xmalloc(sizeof (struct disorder_client));
101 /** @brief Return the address family used by this client */
102 int disorder_client_af(disorder_client *c) {
106 /** @brief Read a response line
108 * @param rp Where to store response, or NULL (UTF-8)
109 * @return Response code 0-999 or -1 on error
111 static int response(disorder_client *c, char **rp) {
114 if(inputline(c->ident, c->fpin, &r, '\n')) {
115 byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
118 D(("response: %s", r));
121 if(r[0] >= '0' && r[0] <= '9'
122 && r[1] >= '0' && r[1] <= '9'
123 && r[2] >= '0' && r[2] <= '9'
126 return (r[0] * 10 + r[1]) * 10 + r[2] - 111 * '0';
128 c->last = "invalid reply format";
129 disorder_error(0, "invalid reply format from %s", c->ident);
134 /** @brief Return last response string
136 * @return Last response string (UTF-8, English) or NULL
138 const char *disorder_last(disorder_client *c) {
142 /** @brief Read and partially parse a response
144 * @param rp Where to store response text (or NULL) (UTF-8)
145 * @return 0 on success, non-0 on error
147 * 5xx responses count as errors.
149 * @p rp will NOT be filled in for xx9 responses (where it is just
150 * commentary for a command where it would normally be meaningful).
152 * NB that the response will NOT be converted to the local encoding.
154 static int check_response(disorder_client *c, char **rp) {
158 if((rc = response(c, &r)) == -1)
160 else if(rc / 100 == 2) {
162 *rp = (rc % 10 == 9) ? 0 : xstrdup(r + 4);
167 disorder_error(0, "from %s: %s", c->ident, utf82mb(r));
173 /** @brief Issue a command and parse a simple response
175 * @param rp Where to store result, or NULL
177 * @param ap Arguments (UTF-8), terminated by (char *)0
178 * @return 0 on success, non-0 on error
180 * 5xx responses count as errors.
182 * @p rp will NOT be filled in for xx9 responses (where it is just
183 * commentary for a command where it would normally be meaningful).
185 * NB that the response will NOT be converted to the local encoding
186 * nor will quotes be stripped. See dequote().
188 * Put @ref disorder__body in the argument list followed by a char **
189 * and int giving the body to follow the command. If the int is @c -1
190 * then the list is assumed to be NULL-terminated. This may be used
193 * Put @ref disorder__list in the argument list followed by a char **
194 * and int giving a list of arguments to include. If the int is @c -1
195 * then the list is assumed to be NULL-terminated. This may be used
196 * any number of times.
198 * Put @ref disorder__integer in the argument list followed by a long to
199 * send its value in decimal. This may be used any number of times.
201 * Put @ref disorder__time in the argument list followed by a time_t
202 * to send its value in decimal. This may be used any number of
205 * Usually you would call this via one of the following interfaces:
206 * - disorder_simple()
208 static int disorder_simple_v(disorder_client *c,
219 c->last = "not connected";
220 disorder_error(0, "not connected to server");
225 dynstr_append_string(&d, cmd);
226 while((arg = va_arg(ap, const char *))) {
227 if(arg == disorder__body) {
228 body = va_arg(ap, char **);
229 nbody = va_arg(ap, int);
231 } else if(arg == disorder__list) {
232 char **list = va_arg(ap, char **);
233 int nlist = va_arg(ap, int);
236 for(nlist = 0; list[nlist]; ++nlist)
239 for(n = 0; n < nlist; ++n) {
240 dynstr_append(&d, ' ');
241 dynstr_append_string(&d, quoteutf8(arg));
243 } else if(arg == disorder__integer) {
244 long n = va_arg(ap, long);
246 byte_snprintf(buffer, sizeof buffer, "%ld", n);
247 dynstr_append(&d, ' ');
248 dynstr_append_string(&d, buffer);
249 } else if(arg == disorder__time) {
250 time_t n = va_arg(ap, time_t);
252 byte_snprintf(buffer, sizeof buffer, "%lld", (long long)n);
253 dynstr_append(&d, ' ');
254 dynstr_append_string(&d, buffer);
256 dynstr_append(&d, ' ');
257 dynstr_append_string(&d, quoteutf8(arg));
260 dynstr_append(&d, '\n');
261 dynstr_terminate(&d);
262 D(("command: %s", d.vec));
263 if(fputs(d.vec, c->fpout) < 0)
269 for(nbody = 0; body[nbody]; ++nbody)
271 for(n = 0; n < nbody; ++n) {
272 if(body[n][0] == '.')
273 if(fputc('.', c->fpout) < 0)
275 if(fputs(body[n], c->fpout) < 0)
277 if(fputc('\n', c->fpout) < 0)
280 if(fputs(".\n", c->fpout) < 0)
286 return check_response(c, rp);
288 byte_xasprintf((char **)&c->last, "write error: %s", strerror(errno));
289 disorder_error(errno, "error writing to %s", c->ident);
293 /** @brief Issue a command and parse a simple response
295 * @param rp Where to store result, or NULL (UTF-8)
297 * @return 0 on success, non-0 on error
299 * The remaining arguments are command arguments, terminated by (char
300 * *)0. They should be in UTF-8.
302 * 5xx responses count as errors.
304 * @p rp will NOT be filled in for xx9 responses (where it is just
305 * commentary for a command where it would normally be meaningful).
307 * NB that the response will NOT be converted to the local encoding
308 * nor will quotes be stripped. See dequote().
310 static int disorder_simple(disorder_client *c,
312 const char *cmd, ...) {
317 ret = disorder_simple_v(c, rp, cmd, ap);
322 /** @brief Issue a command and split the response
324 * @param vecp Where to store results
325 * @param nvecp Where to store count of results
326 * @param expected Expected count (or -1 to not check)
328 * @return 0 on success, non-0 on error
330 * The remaining arguments are command arguments, terminated by (char
331 * *)0. They should be in UTF-8.
333 * 5xx responses count as errors.
335 * @p rp will NOT be filled in for xx9 responses (where it is just
336 * commentary for a command where it would normally be meaningful).
338 * NB that the response will NOT be converted to the local encoding
339 * nor will quotes be stripped. See dequote().
341 static int disorder_simple_split(disorder_client *c,
345 const char *cmd, ...) {
353 ret = disorder_simple_v(c, &r, cmd, ap);
356 vec = split(r, &nvec, SPLIT_QUOTES, 0, 0);
358 if(expected < 0 || nvec == expected) {
362 disorder_error(0, "malformed reply to %s", cmd);
363 c->last = "malformed reply";
365 free_strings(nvec, vec);
375 /** @brief Dequote a result string
376 * @param rc 0 on success, non-0 on error
377 * @param rp Where result string is stored (UTF-8)
380 * This is used as a wrapper around disorder_simple() to dequote
383 static int dequote(int rc, char **rp) {
387 if((rr = split(*rp, 0, SPLIT_QUOTES, 0, 0)) && *rr) {
393 disorder_error(0, "invalid reply: %s", *rp);
398 /** @brief Generic connection routine
399 * @param conf Configuration to follow
401 * @param username Username to log in with or NULL
402 * @param password Password to log in with or NULL
403 * @param cookie Cookie to log in with or NULL
404 * @return 0 on success, non-0 on error
406 * @p cookie is tried first if not NULL. If it is NULL then @p
407 * username must not be. If @p username is not NULL then nor may @p
410 int disorder_connect_generic(struct config *conf,
412 const char *username,
413 const char *password,
414 const char *cookie) {
415 int fd = -1, fd2 = -1, nrvec = 0, rc;
416 unsigned char *nonce = NULL;
419 char *r = NULL, **rvec = NULL;
420 const char *protocol, *algorithm, *challenge;
421 struct sockaddr *sa = NULL;
424 if((salen = find_server(conf, &sa, &c->ident)) == (socklen_t)-1)
426 c->fpin = c->fpout = 0;
427 if((fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0) {
428 byte_xasprintf((char **)&c->last, "socket: %s", strerror(errno));
429 disorder_error(errno, "error calling socket");
432 c->family = sa->sa_family;
433 if(connect(fd, sa, salen) < 0) {
434 byte_xasprintf((char **)&c->last, "connect: %s", strerror(errno));
435 disorder_error(errno, "error calling connect");
438 if((fd2 = dup(fd)) < 0) {
439 byte_xasprintf((char **)&c->last, "dup: %s", strerror(errno));
440 disorder_error(errno, "error calling dup");
443 if(!(c->fpin = fdopen(fd, "rb"))) {
444 byte_xasprintf((char **)&c->last, "fdopen: %s", strerror(errno));
445 disorder_error(errno, "error calling fdopen");
449 if(!(c->fpout = fdopen(fd2, "wb"))) {
450 byte_xasprintf((char **)&c->last, "fdopen: %s", strerror(errno));
451 disorder_error(errno, "error calling fdopen");
455 if((rc = disorder_simple(c, &r, 0, (const char *)0)))
457 if(!(rvec = split(r, &nrvec, SPLIT_QUOTES, 0, 0)))
460 c->last = "cannot parse server greeting";
461 disorder_error(0, "cannot parse server greeting %s", r);
465 if(strcmp(protocol, "2")) {
466 c->last = "unknown protocol version";
467 disorder_error(0, "unknown protocol version: %s", protocol);
472 if(!(nonce = unhex(challenge, &nl)))
475 if(!dequote(disorder_simple(c, &c->user, "cookie", cookie, (char *)0),
477 return 0; /* success */
479 c->last = "cookie failed and no username";
480 disorder_error(0, "cookie did not work and no username available");
484 if(!(res = authhash(nonce, nl, password, algorithm))) {
485 c->last = "error computing authorization hash";
488 if((rc = disorder_simple(c, 0, "user", username, res, (char *)0)))
490 c->user = xstrdup(username);
492 free_strings(nrvec, rvec);
508 if(fd2 != -1) close(fd2);
509 if(fd != -1) close(fd);
513 /** @brief Connect a client with a specified username and password
515 * @param username Username to log in with
516 * @param password Password to log in with
517 * @return 0 on success, non-0 on error
519 int disorder_connect_user(disorder_client *c,
520 const char *username,
521 const char *password) {
522 return disorder_connect_generic(config,
529 /** @brief Connect a client
531 * @return 0 on success, non-0 on error
533 * The connection will use the username and password found in @ref
534 * config, or directly from the database if no password is found and
535 * the database is readable (usually only for root).
537 int disorder_connect(disorder_client *c) {
538 const char *username, *password;
540 if(!(username = config->username)) {
541 c->last = "no username";
542 disorder_error(0, "no username configured");
545 password = config->password;
546 /* If we're connecting as 'root' guess that we're the system root
547 * user (or the jukebox user), both of which can use the privileged
548 * socket. They can also furtle with the db directly: that is why
549 * privileged socket does not represent a privilege escalation. */
551 && !strcmp(username, "root"))
552 password = "anything will do for root";
555 c->last = "no password";
556 disorder_error(0, "no password configured for user '%s'", username);
559 return disorder_connect_generic(config,
566 /** @brief Connect a client
568 * @param cookie Cookie to log in with, or NULL
569 * @return 0 on success, non-0 on error
571 * If @p cookie is NULL or does not work then we attempt to log in as
572 * guest instead (so when the cookie expires only an extra round trip
573 * is needed rather than a complete new login).
575 int disorder_connect_cookie(disorder_client *c,
576 const char *cookie) {
577 return disorder_connect_generic(config,
584 /** @brief Close a client
586 * @return 0 on succcess, non-0 on errior
588 * The client is still closed even on error. It might well be
589 * appropriate to ignore the return value.
591 int disorder_close(disorder_client *c) {
595 if(fclose(c->fpin) < 0) {
596 byte_xasprintf((char **)&c->last, "fclose: %s", strerror(errno));
597 disorder_error(errno, "error calling fclose");
603 if(fclose(c->fpout) < 0) {
604 byte_xasprintf((char **)&c->last, "fclose: %s", strerror(errno));
605 disorder_error(errno, "error calling fclose");
617 static void client_error(const char *msg,
618 void attribute((unused)) *u) {
619 disorder_error(0, "error parsing reply: %s", msg);
622 /** @brief Get a single queue entry
625 * @param qp Where to store track information
626 * @return 0 on success, non-0 on error
628 static int onequeue(disorder_client *c, const char *cmd,
629 struct queue_entry **qp) {
631 struct queue_entry *q;
634 if((rc = disorder_simple(c, &r, cmd, (char *)0)))
637 q = xmalloc(sizeof *q);
638 if(queue_unmarshall(q, r, client_error, 0))
646 /** @brief Fetch the queue, recent list, etc */
647 static int readqueue(disorder_client *c,
648 struct queue_entry **qp) {
649 struct queue_entry *qh, **qt = &qh, *q;
652 while(inputline(c->ident, c->fpin, &l, '\n') >= 0) {
653 if(!strcmp(l, ".")) {
659 q = xmalloc(sizeof *q);
660 if(!queue_unmarshall(q, l, client_error, 0)) {
666 if(ferror(c->fpin)) {
667 byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
668 disorder_error(errno, "error reading %s", c->ident);
670 c->last = "input error: unexpected EOF";
671 disorder_error(0, "error reading %s: unexpected EOF", c->ident);
676 /** @brief Read a dot-stuffed list
678 * @param vecp Where to store list (UTF-8)
679 * @param nvecp Where to store number of items, or NULL
680 * @return 0 on success, non-0 on error
682 * The list will have a final NULL not counted in @p nvecp.
684 static int readlist(disorder_client *c, char ***vecp, int *nvecp) {
689 while(inputline(c->ident, c->fpin, &l, '\n') >= 0) {
690 if(!strcmp(l, ".")) {
691 vector_terminate(&v);
698 vector_append(&v, xstrdup(l + (*l == '.')));
701 if(ferror(c->fpin)) {
702 byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
703 disorder_error(errno, "error reading %s", c->ident);
705 c->last = "input error: unexpxected EOF";
706 disorder_error(0, "error reading %s: unexpected EOF", c->ident);
711 /** @brief Return the user we logged in with
713 * @return User name (owned by @p c, don't modify)
715 char *disorder_user(disorder_client *c) {
719 static void pairlist_error_handler(const char *msg,
720 void attribute((unused)) *u) {
721 disorder_error(0, "error handling key-value pair reply: %s", msg);
724 /** @brief Get a list of key-value pairs
726 * @param kp Where to store linked list of preferences
728 * @param ... Arguments
729 * @return 0 on success, non-0 on error
731 static int pairlist(disorder_client *c, struct kvp **kp, const char *cmd, ...) {
733 int nvec, npvec, n, rc;
738 rc = disorder_simple_v(c, 0, cmd, ap);
742 if((rc = readlist(c, &vec, &nvec)))
744 for(n = 0; n < nvec; ++n) {
745 if(!(pvec = split(vec[n], &npvec, SPLIT_QUOTES, pairlist_error_handler, 0)))
748 pairlist_error_handler("malformed response", 0);
751 *kp = k = xmalloc(sizeof *k);
757 free_strings(nvec, vec);
762 /** @brief Parse a boolean response
763 * @param cmd Command for use in error messsage
764 * @param value Result from server
765 * @param flagp Where to store result
766 * @return 0 on success, non-0 on error
768 static int boolean(const char *cmd, const char *value,
770 if(!strcmp(value, "yes")) *flagp = 1;
771 else if(!strcmp(value, "no")) *flagp = 0;
773 disorder_error(0, "malformed response to '%s'", cmd);
779 /** @brief Log to a sink
781 * @param s Sink to write log lines to
782 * @return 0 on success, non-0 on error
784 int disorder_log(disorder_client *c, struct sink *s) {
788 if((rc = disorder_simple(c, 0, "log", (char *)0)))
790 while(inputline(c->ident, c->fpin, &l, '\n') >= 0 && strcmp(l, "."))
791 if(sink_printf(s, "%s\n", l) < 0) return -1;
792 if(ferror(c->fpin) || feof(c->fpin)) {
793 byte_xasprintf((char **)&c->last, "input error: %s",
794 ferror(c->fpin) ? strerror(errno) : "unexpxected EOF");
800 #include "client-stubs.c"