2 * This file is part of DisOrder.
3 * Copyright (C) 2004-2010 Richard Kettlewell
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 /** @file lib/client.c
19 * @brief Simple C client
21 * See @ref lib/eclient.c for an asynchronous-capable client
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
44 #include "inputline.h"
51 #include "client-common.h"
55 /** @brief Client handle contents */
56 struct disorder_client {
57 /** @brief Stream to read from */
59 /** @brief Stream to write to */
61 /** @brief Peer description */
63 /** @brief Username */
65 /** @brief Report errors to @c stderr */
67 /** @brief Last error string */
69 /** @brief Address family */
73 /** @brief Create a new client
74 * @param verbose If nonzero, write extra junk to stderr
75 * @return Pointer to new client
77 * You must call disorder_connect(), disorder_connect_user() or
78 * disorder_connect_cookie() to connect it. Use disorder_close() to
79 * dispose of the client when finished with it.
81 disorder_client *disorder_new(int verbose) {
82 disorder_client *c = xmalloc(sizeof (struct disorder_client));
89 /** @brief Return the address family used by this client */
90 int disorder_client_af(disorder_client *c) {
94 /** @brief Read a response line
96 * @param rp Where to store response, or NULL (UTF-8)
97 * @return Response code 0-999 or -1 on error
99 static int response(disorder_client *c, char **rp) {
102 if(inputline(c->ident, c->fpin, &r, '\n')) {
103 byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
106 D(("response: %s", r));
109 if(r[0] >= '0' && r[0] <= '9'
110 && r[1] >= '0' && r[1] <= '9'
111 && r[2] >= '0' && r[2] <= '9'
114 return (r[0] * 10 + r[1]) * 10 + r[2] - 111 * '0';
116 c->last = "invalid reply format";
117 disorder_error(0, "invalid reply format from %s", c->ident);
122 /** @brief Return last response string
124 * @return Last response string (UTF-8, English) or NULL
126 const char *disorder_last(disorder_client *c) {
130 /** @brief Read and partially parse a response
132 * @param rp Where to store response text (or NULL) (UTF-8)
133 * @return 0 on success, non-0 on error
135 * 5xx responses count as errors.
137 * @p rp will NOT be filled in for xx9 responses (where it is just
138 * commentary for a command where it would normally be meaningful).
140 * NB that the response will NOT be converted to the local encoding.
142 static int check_response(disorder_client *c, char **rp) {
146 if((rc = response(c, &r)) == -1)
148 else if(rc / 100 == 2) {
150 *rp = (rc % 10 == 9) ? 0 : xstrdup(r + 4);
155 disorder_error(0, "from %s: %s", c->ident, utf82mb(r));
161 /** @brief Issue a command and parse a simple response
163 * @param rp Where to store result, or NULL
165 * @param ap Arguments (UTF-8), terminated by (char *)0
166 * @return 0 on success, non-0 on error
168 * 5xx responses count as errors.
170 * @p rp will NOT be filled in for xx9 responses (where it is just
171 * commentary for a command where it would normally be meaningful).
173 * NB that the response will NOT be converted to the local encoding
174 * nor will quotes be stripped. See dequote().
176 * Put @ref disorder__body in the argument list followed by a char **
177 * and int giving the body to follow the command. If the int is @c -1
178 * then the list is assumed to be NULL-terminated. This may be used
181 * Put @ref disorder__list in the argument list followed by a char **
182 * and int giving a list of arguments to include. If the int is @c -1
183 * then the list is assumed to be NULL-terminated. This may be used
184 * any number of times.
186 * Put @ref disorder__integer in the argument list followed by a long to
187 * send its value in decimal. This may be used any number of times.
189 * Put @ref disorder__time in the argument list followed by a time_t
190 * to send its value in decimal. This may be used any number of
193 * Usually you would call this via one of the following interfaces:
194 * - disorder_simple()
196 static int disorder_simple_v(disorder_client *c,
207 c->last = "not connected";
208 disorder_error(0, "not connected to server");
213 dynstr_append_string(&d, cmd);
214 while((arg = va_arg(ap, const char *))) {
215 if(arg == disorder__body) {
216 body = va_arg(ap, char **);
217 nbody = va_arg(ap, int);
219 } else if(arg == disorder__list) {
220 char **list = va_arg(ap, char **);
221 int nlist = va_arg(ap, int);
223 for(nlist = 0; list[nlist]; ++nlist)
226 for(int n = 0; n < nlist; ++n) {
227 dynstr_append(&d, ' ');
228 dynstr_append_string(&d, quoteutf8(arg));
230 } else if(arg == disorder__integer) {
231 long n = va_arg(ap, long);
233 snprintf(buffer, sizeof buffer, "%ld", n);
234 dynstr_append(&d, ' ');
235 dynstr_append_string(&d, buffer);
236 } else if(arg == disorder__time) {
237 time_t n = va_arg(ap, time_t);
239 snprintf(buffer, sizeof buffer, "%lld", (long long)n);
240 dynstr_append(&d, ' ');
241 dynstr_append_string(&d, buffer);
243 dynstr_append(&d, ' ');
244 dynstr_append_string(&d, quoteutf8(arg));
247 dynstr_append(&d, '\n');
248 dynstr_terminate(&d);
249 D(("command: %s", d.vec));
250 if(fputs(d.vec, c->fpout) < 0)
255 for(nbody = 0; body[nbody]; ++nbody)
257 for(int n = 0; n < nbody; ++n) {
258 if(body[n][0] == '.')
259 if(fputc('.', c->fpout) < 0)
261 if(fputs(body[n], c->fpout) < 0)
263 if(fputc('\n', c->fpout) < 0)
266 if(fputs(".\n", c->fpout) < 0)
272 return check_response(c, rp);
274 byte_xasprintf((char **)&c->last, "write error: %s", strerror(errno));
275 disorder_error(errno, "error writing to %s", c->ident);
279 /** @brief Issue a command and parse a simple response
281 * @param rp Where to store result, or NULL (UTF-8)
283 * @return 0 on success, non-0 on error
285 * The remaining arguments are command arguments, terminated by (char
286 * *)0. They should be in UTF-8.
288 * 5xx responses count as errors.
290 * @p rp will NOT be filled in for xx9 responses (where it is just
291 * commentary for a command where it would normally be meaningful).
293 * NB that the response will NOT be converted to the local encoding
294 * nor will quotes be stripped. See dequote().
296 static int disorder_simple(disorder_client *c,
298 const char *cmd, ...) {
303 ret = disorder_simple_v(c, rp, cmd, ap);
308 /** @brief Issue a command and split the response
310 * @param vecp Where to store results
311 * @param nvecp Where to store count of results
312 * @param expected Expected count (or -1 to not check)
314 * @return 0 on success, non-0 on error
316 * The remaining arguments are command arguments, terminated by (char
317 * *)0. They should be in UTF-8.
319 * 5xx responses count as errors.
321 * @p rp will NOT be filled in for xx9 responses (where it is just
322 * commentary for a command where it would normally be meaningful).
324 * NB that the response will NOT be converted to the local encoding
325 * nor will quotes be stripped. See dequote().
327 static int disorder_simple_split(disorder_client *c,
331 const char *cmd, ...) {
339 ret = disorder_simple_v(c, &r, cmd, ap);
342 vec = split(r, &nvec, SPLIT_QUOTES, 0, 0);
344 if(expected < 0 || nvec == expected) {
348 disorder_error(0, "malformed reply to %s", cmd);
349 c->last = "malformed reply";
351 free_strings(nvec, vec);
361 /** @brief Dequote a result string
362 * @param rc 0 on success, non-0 on error
363 * @param rp Where result string is stored (UTF-8)
366 * This is used as a wrapper around disorder_simple() to dequote
369 static int dequote(int rc, char **rp) {
373 if((rr = split(*rp, 0, SPLIT_QUOTES, 0, 0)) && *rr) {
379 disorder_error(0, "invalid reply: %s", *rp);
384 /** @brief Generic connection routine
385 * @param conf Configuration to follow
387 * @param username Username to log in with or NULL
388 * @param password Password to log in with or NULL
389 * @param cookie Cookie to log in with or NULL
390 * @return 0 on success, non-0 on error
392 * @p cookie is tried first if not NULL. If it is NULL then @p
393 * username must not be. If @p username is not NULL then nor may @p
396 int disorder_connect_generic(struct config *conf,
398 const char *username,
399 const char *password,
400 const char *cookie) {
401 int fd = -1, fd2 = -1, nrvec = 0, rc;
402 unsigned char *nonce = NULL;
405 char *r = NULL, **rvec = NULL;
406 const char *protocol, *algorithm, *challenge;
407 struct sockaddr *sa = NULL;
410 if((salen = find_server(conf, &sa, &c->ident)) == (socklen_t)-1)
412 c->fpin = c->fpout = 0;
413 if((fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0) {
414 byte_xasprintf((char **)&c->last, "socket: %s", strerror(errno));
415 disorder_error(errno, "error calling socket");
418 c->family = sa->sa_family;
419 if(connect(fd, sa, salen) < 0) {
420 byte_xasprintf((char **)&c->last, "connect: %s", strerror(errno));
421 disorder_error(errno, "error calling connect");
424 if((fd2 = dup(fd)) < 0) {
425 byte_xasprintf((char **)&c->last, "dup: %s", strerror(errno));
426 disorder_error(errno, "error calling dup");
429 if(!(c->fpin = fdopen(fd, "rb"))) {
430 byte_xasprintf((char **)&c->last, "fdopen: %s", strerror(errno));
431 disorder_error(errno, "error calling fdopen");
435 if(!(c->fpout = fdopen(fd2, "wb"))) {
436 byte_xasprintf((char **)&c->last, "fdopen: %s", strerror(errno));
437 disorder_error(errno, "error calling fdopen");
441 if((rc = disorder_simple(c, &r, 0, (const char *)0)))
443 if(!(rvec = split(r, &nrvec, SPLIT_QUOTES, 0, 0)))
446 c->last = "cannot parse server greeting";
447 disorder_error(0, "cannot parse server greeting %s", r);
451 if(strcmp(protocol, "2")) {
452 c->last = "unknown protocol version";
453 disorder_error(0, "unknown protocol version: %s", protocol);
458 if(!(nonce = unhex(challenge, &nl)))
461 if(!dequote(disorder_simple(c, &c->user, "cookie", cookie, (char *)0),
463 return 0; /* success */
465 c->last = "cookie failed and no username";
466 disorder_error(0, "cookie did not work and no username available");
470 if(!(res = authhash(nonce, nl, password, algorithm))) {
471 c->last = "error computing authorization hash";
474 if((rc = disorder_simple(c, 0, "user", username, res, (char *)0)))
476 c->user = xstrdup(username);
478 free_strings(nrvec, rvec);
494 if(fd2 != -1) close(fd2);
495 if(fd != -1) close(fd);
499 /** @brief Connect a client with a specified username and password
501 * @param username Username to log in with
502 * @param password Password to log in with
503 * @return 0 on success, non-0 on error
505 int disorder_connect_user(disorder_client *c,
506 const char *username,
507 const char *password) {
508 return disorder_connect_generic(config,
515 /** @brief Connect a client
517 * @return 0 on success, non-0 on error
519 * The connection will use the username and password found in @ref
520 * config, or directly from the database if no password is found and
521 * the database is readable (usually only for root).
523 int disorder_connect(disorder_client *c) {
524 const char *username, *password;
526 if(!(username = config->username)) {
527 c->last = "no username";
528 disorder_error(0, "no username configured");
531 password = config->password;
532 /* If we're connecting as 'root' guess that we're the system root
533 * user (or the jukebox user), both of which can use the privileged
534 * socket. They can also furtle with the db directly: that is why
535 * privileged socket does not represent a privilege escalation. */
537 && !strcmp(username, "root"))
538 password = "anything will do for root";
541 c->last = "no password";
542 disorder_error(0, "no password configured for user '%s'", username);
545 return disorder_connect_generic(config,
552 /** @brief Connect a client
554 * @param cookie Cookie to log in with, or NULL
555 * @return 0 on success, non-0 on error
557 * If @p cookie is NULL or does not work then we attempt to log in as
558 * guest instead (so when the cookie expires only an extra round trip
559 * is needed rathre than a complete new login).
561 int disorder_connect_cookie(disorder_client *c,
562 const char *cookie) {
563 return disorder_connect_generic(config,
570 /** @brief Close a client
572 * @return 0 on succcess, non-0 on errior
574 * The client is still closed even on error. It might well be
575 * appropriate to ignore the return value.
577 int disorder_close(disorder_client *c) {
581 if(fclose(c->fpin) < 0) {
582 byte_xasprintf((char **)&c->last, "fclose: %s", strerror(errno));
583 disorder_error(errno, "error calling fclose");
589 if(fclose(c->fpout) < 0) {
590 byte_xasprintf((char **)&c->last, "fclose: %s", strerror(errno));
591 disorder_error(errno, "error calling fclose");
603 static void client_error(const char *msg,
604 void attribute((unused)) *u) {
605 disorder_error(0, "error parsing reply: %s", msg);
608 /** @brief Get a single queue entry
611 * @param qp Where to store track information
612 * @return 0 on success, non-0 on error
614 static int onequeue(disorder_client *c, const char *cmd,
615 struct queue_entry **qp) {
617 struct queue_entry *q;
620 if((rc = disorder_simple(c, &r, cmd, (char *)0)))
623 q = xmalloc(sizeof *q);
624 if(queue_unmarshall(q, r, client_error, 0))
632 /** @brief Fetch the queue, recent list, etc */
633 static int readqueue(disorder_client *c,
634 struct queue_entry **qp) {
635 struct queue_entry *qh, **qt = &qh, *q;
638 while(inputline(c->ident, c->fpin, &l, '\n') >= 0) {
639 if(!strcmp(l, ".")) {
645 q = xmalloc(sizeof *q);
646 if(!queue_unmarshall(q, l, client_error, 0)) {
652 if(ferror(c->fpin)) {
653 byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
654 disorder_error(errno, "error reading %s", c->ident);
656 c->last = "input error: unexpected EOF";
657 disorder_error(0, "error reading %s: unexpected EOF", c->ident);
662 /** @brief Read a dot-stuffed list
664 * @param vecp Where to store list (UTF-8)
665 * @param nvecp Where to store number of items, or NULL
666 * @return 0 on success, non-0 on error
668 * The list will have a final NULL not counted in @p nvecp.
670 static int readlist(disorder_client *c, char ***vecp, int *nvecp) {
675 while(inputline(c->ident, c->fpin, &l, '\n') >= 0) {
676 if(!strcmp(l, ".")) {
677 vector_terminate(&v);
684 vector_append(&v, xstrdup(l + (*l == '.')));
687 if(ferror(c->fpin)) {
688 byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
689 disorder_error(errno, "error reading %s", c->ident);
691 c->last = "input error: unexpxected EOF";
692 disorder_error(0, "error reading %s: unexpected EOF", c->ident);
697 /** @brief Return the user we logged in with
699 * @return User name (owned by @p c, don't modify)
701 char *disorder_user(disorder_client *c) {
705 static void pairlist_error_handler(const char *msg,
706 void attribute((unused)) *u) {
707 disorder_error(0, "error handling key-value pair reply: %s", msg);
710 /** @brief Get a list of key-value pairs
712 * @param kp Where to store linked list of preferences
714 * @param ... Arguments
715 * @return 0 on success, non-0 on error
717 static int pairlist(disorder_client *c, struct kvp **kp, const char *cmd, ...) {
719 int nvec, npvec, n, rc;
724 rc = disorder_simple_v(c, 0, cmd, ap);
728 if((rc = readlist(c, &vec, &nvec)))
730 for(n = 0; n < nvec; ++n) {
731 if(!(pvec = split(vec[n], &npvec, SPLIT_QUOTES, pairlist_error_handler, 0)))
734 pairlist_error_handler("malformed response", 0);
737 *kp = k = xmalloc(sizeof *k);
743 free_strings(nvec, vec);
748 /** @brief Parse a boolean response
749 * @param cmd Command for use in error messsage
750 * @param value Result from server
751 * @param flagp Where to store result
752 * @return 0 on success, non-0 on error
754 static int boolean(const char *cmd, const char *value,
756 if(!strcmp(value, "yes")) *flagp = 1;
757 else if(!strcmp(value, "no")) *flagp = 0;
759 disorder_error(0, "malformed response to '%s'", cmd);
765 /** @brief Log to a sink
767 * @param s Sink to write log lines to
768 * @return 0 on success, non-0 on error
770 int disorder_log(disorder_client *c, struct sink *s) {
774 if((rc = disorder_simple(c, 0, "log", (char *)0)))
776 while(inputline(c->ident, c->fpin, &l, '\n') >= 0 && strcmp(l, "."))
777 if(sink_printf(s, "%s\n", l) < 0) return -1;
778 if(ferror(c->fpin) || feof(c->fpin)) {
779 byte_xasprintf((char **)&c->last, "input error: %s",
780 ferror(c->fpin) ? strerror(errno) : "unexpxected EOF");
786 #include "client-stubs.c"