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"
68 /** @brief Client handle contents */
69 struct disorder_client {
70 /** @brief Stream to read from */
72 /** @brief Stream to write to */
74 /** @brief Peer description */
76 /** @brief Username */
78 /** @brief Report errors to @c stderr */
80 /** @brief Last error string */
82 /** @brief Address family */
84 /** @brief True if open */
86 /** @brief Socket I/O context */
90 /** @brief Create a new client
91 * @param verbose If nonzero, write extra junk to stderr
92 * @return Pointer to new client
94 * You must call disorder_connect(), disorder_connect_user() or
95 * disorder_connect_cookie() to connect it. Use disorder_close() to
96 * dispose of the client when finished with it.
98 disorder_client *disorder_new(int verbose) {
99 disorder_client *c = xmalloc(sizeof (struct disorder_client));
101 c->verbose = verbose;
106 /** @brief Return the address family used by this client */
107 int disorder_client_af(disorder_client *c) {
111 /** @brief Read a response line
113 * @param rp Where to store response, or NULL (UTF-8)
114 * @return Response code 0-999 or -1 on error
116 static int response(disorder_client *c, char **rp) {
120 if(inputlines(c->ident, c->input, &r, '\n')) {
121 byte_xasprintf((char **)&c->last, "input error: %s",
122 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
125 D(("response: %s", r));
128 if(r[0] >= '0' && r[0] <= '9'
129 && r[1] >= '0' && r[1] <= '9'
130 && r[2] >= '0' && r[2] <= '9'
133 return (r[0] * 10 + r[1]) * 10 + r[2] - 111 * '0';
135 c->last = "invalid reply format";
136 disorder_error(0, "invalid reply format from %s", c->ident);
141 /** @brief Return last response string
143 * @return Last response string (UTF-8, English) or NULL
145 const char *disorder_last(disorder_client *c) {
149 /** @brief Read and partially parse a response
151 * @param rp Where to store response text (or NULL) (UTF-8)
152 * @return 0 on success, non-0 on error
154 * 5xx responses count as errors.
156 * @p rp will NOT be filled in for xx9 responses (where it is just
157 * commentary for a command where it would normally be meaningful).
159 * NB that the response will NOT be converted to the local encoding.
161 static int check_response(disorder_client *c, char **rp) {
165 if((rc = response(c, &r)) == -1)
167 else if(rc / 100 == 2) {
169 *rp = (rc % 10 == 9) ? 0 : xstrdup(r + 4);
174 disorder_error(0, "from %s: %s", c->ident, utf82mb(r));
180 /** @brief Issue a command and parse a simple response
182 * @param rp Where to store result, or NULL
184 * @param ap Arguments (UTF-8), terminated by (char *)0
185 * @return 0 on success, non-0 on error
187 * 5xx responses count as errors.
189 * @p rp will NOT be filled in for xx9 responses (where it is just
190 * commentary for a command where it would normally be meaningful).
192 * NB that the response will NOT be converted to the local encoding
193 * nor will quotes be stripped. See dequote().
195 * Put @ref disorder__body in the argument list followed by a char **
196 * and int giving the body to follow the command. If the int is @c -1
197 * then the list is assumed to be NULL-terminated. This may be used
200 * Put @ref disorder__list in the argument list followed by a char **
201 * and int giving a list of arguments to include. If the int is @c -1
202 * then the list is assumed to be NULL-terminated. This may be used
203 * any number of times.
205 * Put @ref disorder__integer in the argument list followed by a long to
206 * send its value in decimal. This may be used any number of times.
208 * Put @ref disorder__time in the argument list followed by a time_t
209 * to send its value in decimal. This may be used any number of
212 * Usually you would call this via one of the following interfaces:
213 * - disorder_simple()
215 static int disorder_simple_v(disorder_client *c,
227 c->last = "not connected";
228 disorder_error(0, "not connected to server");
233 dynstr_append_string(&d, cmd);
234 while((arg = va_arg(ap, const char *))) {
235 if(arg == disorder__body) {
236 body = va_arg(ap, char **);
237 nbody = va_arg(ap, int);
239 } else if(arg == disorder__list) {
240 char **list = va_arg(ap, char **);
241 int nlist = va_arg(ap, int);
244 for(nlist = 0; list[nlist]; ++nlist)
247 for(n = 0; n < nlist; ++n) {
248 dynstr_append(&d, ' ');
249 dynstr_append_string(&d, quoteutf8(arg));
251 } else if(arg == disorder__integer) {
252 long n = va_arg(ap, long);
254 byte_snprintf(buffer, sizeof buffer, "%ld", n);
255 dynstr_append(&d, ' ');
256 dynstr_append_string(&d, buffer);
257 } else if(arg == disorder__time) {
258 time_t n = va_arg(ap, time_t);
260 byte_snprintf(buffer, sizeof buffer, "%lld", (long long)n);
261 dynstr_append(&d, ' ');
262 dynstr_append_string(&d, buffer);
264 dynstr_append(&d, ' ');
265 dynstr_append_string(&d, quoteutf8(arg));
268 dynstr_append(&d, '\n');
269 dynstr_terminate(&d);
270 D(("command: %s", d.vec));
271 if(sink_write(c->output, d.vec, d.nvec) < 0)
277 for(nbody = 0; body[nbody]; ++nbody)
279 for(n = 0; n < nbody; ++n) {
280 if(body[n][0] == '.')
281 if(sink_writec(c->output, '.') < 0)
283 if(sink_writes(c->output, body[n]) < 0)
285 if(sink_writec(c->output, '\n') < 0)
288 if(sink_writes(c->output, ".\n") < 0)
291 if(sink_flush(c->output))
294 return check_response(c, rp);
296 byte_xasprintf((char **)&c->last, "write error: %s",
297 format_error(c->output->eclass, sink_err(c->output), errbuf, sizeof errbuf));
298 disorder_error(0, "%s: %s", c->ident, c->last);
302 /** @brief Issue a command and parse a simple response
304 * @param rp Where to store result, or NULL (UTF-8)
306 * @return 0 on success, non-0 on error
308 * The remaining arguments are command arguments, terminated by (char
309 * *)0. They should be in UTF-8.
311 * 5xx responses count as errors.
313 * @p rp will NOT be filled in for xx9 responses (where it is just
314 * commentary for a command where it would normally be meaningful).
316 * NB that the response will NOT be converted to the local encoding
317 * nor will quotes be stripped. See dequote().
319 static int disorder_simple(disorder_client *c,
321 const char *cmd, ...) {
326 ret = disorder_simple_v(c, rp, cmd, ap);
331 /** @brief Issue a command and split the response
333 * @param vecp Where to store results
334 * @param nvecp Where to store count of results
335 * @param expected Expected count (or -1 to not check)
337 * @return 0 on success, non-0 on error
339 * The remaining arguments are command arguments, terminated by (char
340 * *)0. They should be in UTF-8.
342 * 5xx responses count as errors.
344 * @p rp will NOT be filled in for xx9 responses (where it is just
345 * commentary for a command where it would normally be meaningful).
347 * NB that the response will NOT be converted to the local encoding
348 * nor will quotes be stripped. See dequote().
350 static int disorder_simple_split(disorder_client *c,
354 const char *cmd, ...) {
362 ret = disorder_simple_v(c, &r, cmd, ap);
365 vec = split(r, &nvec, SPLIT_QUOTES, 0, 0);
367 if(expected < 0 || nvec == expected) {
371 disorder_error(0, "malformed reply to %s", cmd);
372 c->last = "malformed reply";
374 free_strings(nvec, vec);
384 /** @brief Dequote a result string
385 * @param rc 0 on success, non-0 on error
386 * @param rp Where result string is stored (UTF-8)
389 * This is used as a wrapper around disorder_simple() to dequote
392 static int dequote(int rc, char **rp) {
396 if((rr = split(*rp, 0, SPLIT_QUOTES, 0, 0)) && *rr) {
402 disorder_error(0, "invalid reply: %s", *rp);
407 /** @brief Generic connection routine
408 * @param conf Configuration to follow
410 * @param username Username to log in with or NULL
411 * @param password Password to log in with or NULL
412 * @param cookie Cookie to log in with or NULL
413 * @return 0 on success, non-0 on error
415 * @p cookie is tried first if not NULL. If it is NULL then @p
416 * username must not be. If @p username is not NULL then nor may @p
419 int disorder_connect_generic(struct config *conf,
421 const char *username,
422 const char *password,
423 const char *cookie) {
424 SOCKET sd = INVALID_SOCKET;
426 unsigned char *nonce = NULL;
429 char *r = NULL, **rvec = NULL;
430 const char *protocol, *algorithm, *challenge;
431 struct sockaddr *sa = NULL;
435 if((salen = find_server(conf, &sa, &c->ident)) == (socklen_t)-1)
439 if((sd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0) {
440 byte_xasprintf((char **)&c->last, "socket: %s",
441 format_error(ec_socket, socket_error(), errbuf, sizeof errbuf));
442 disorder_error(0, "%s", c->last);
445 c->family = sa->sa_family;
446 if(connect(sd, sa, salen) < 0) {
447 byte_xasprintf((char **)&c->last, "connect: %s",
448 format_error(ec_socket, socket_error(), errbuf, sizeof errbuf));
449 disorder_error(0, "%s", c->last);
452 socketio_init(&c->sio, sd);
455 c->output = sink_socketio(&c->sio);
456 c->input = source_socketio(&c->sio);
457 if((rc = disorder_simple(c, &r, 0, (const char *)0)))
459 if(!(rvec = split(r, &nrvec, SPLIT_QUOTES, 0, 0)))
462 c->last = "cannot parse server greeting";
463 disorder_error(0, "cannot parse server greeting %s", r);
467 if(strcmp(protocol, "2")) {
468 c->last = "unknown protocol version";
469 disorder_error(0, "unknown protocol version: %s", protocol);
474 if(!(nonce = unhex(challenge, &nl)))
477 if(!dequote(disorder_simple(c, &c->user, "cookie", cookie, (char *)0),
479 return 0; /* success */
481 c->last = "cookie failed and no username";
482 disorder_error(0, "cookie did not work and no username available");
486 if(!(res = authhash(nonce, nl, password, algorithm))) {
487 c->last = "error computing authorization hash";
490 if((rc = disorder_simple(c, 0, "user", username, res, (char *)0)))
492 c->user = xstrdup(username);
494 free_strings(nrvec, rvec);
506 if(c->open) { socketio_close(&c->sio); c->open = 0; }
507 if(sd != INVALID_SOCKET) closesocket(sd);
511 /** @brief Connect a client with a specified username and password
513 * @param username Username to log in with
514 * @param password Password to log in with
515 * @return 0 on success, non-0 on error
517 int disorder_connect_user(disorder_client *c,
518 const char *username,
519 const char *password) {
520 return disorder_connect_generic(config,
527 /** @brief Connect a client
529 * @return 0 on success, non-0 on error
531 * The connection will use the username and password found in @ref
532 * config, or directly from the database if no password is found and
533 * the database is readable (usually only for root).
535 int disorder_connect(disorder_client *c) {
536 const char *username, *password;
538 if(!(username = config->username)) {
539 c->last = "no username";
540 disorder_error(0, "no username configured");
543 password = config->password;
544 /* If we're connecting as 'root' guess that we're the system root
545 * user (or the jukebox user), both of which can use the privileged
546 * socket. They can also furtle with the db directly: that is why
547 * privileged socket does not represent a privilege escalation. */
549 && !strcmp(username, "root"))
550 password = "anything will do for root";
553 c->last = "no password";
554 disorder_error(0, "no password configured for user '%s'", username);
557 return disorder_connect_generic(config,
564 /** @brief Connect a client
566 * @param cookie Cookie to log in with, or NULL
567 * @return 0 on success, non-0 on error
569 * If @p cookie is NULL or does not work then we attempt to log in as
570 * guest instead (so when the cookie expires only an extra round trip
571 * is needed rather than a complete new login).
573 int disorder_connect_cookie(disorder_client *c,
574 const char *cookie) {
575 return disorder_connect_generic(config,
582 /** @brief Close a client
584 * @return 0 on succcess, non-0 on errior
586 * The client is still closed even on error. It might well be
587 * appropriate to ignore the return value.
589 int disorder_close(disorder_client *c) {
593 socketio_close(&c->sio);
605 static void client_error(const char *msg,
606 void attribute((unused)) *u) {
607 disorder_error(0, "error parsing reply: %s", msg);
610 /** @brief Get a single queue entry
613 * @param qp Where to store track information
614 * @return 0 on success, non-0 on error
616 static int onequeue(disorder_client *c, const char *cmd,
617 struct queue_entry **qp) {
619 struct queue_entry *q;
622 if((rc = disorder_simple(c, &r, cmd, (char *)0)))
625 q = xmalloc(sizeof *q);
626 if(queue_unmarshall(q, r, client_error, 0))
634 /** @brief Fetch the queue, recent list, etc */
635 static int readqueue(disorder_client *c,
636 struct queue_entry **qp) {
637 struct queue_entry *qh, **qt = &qh, *q;
641 while(inputlines(c->ident, c->input, &l, '\n') >= 0) {
642 if(!strcmp(l, ".")) {
648 q = xmalloc(sizeof *q);
649 if(!queue_unmarshall(q, l, client_error, 0)) {
655 if(source_err(c->input)) {
656 byte_xasprintf((char **)&c->last, "input error: %s",
657 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
659 c->last = "input error: unexpected EOF";
661 disorder_error(0, "%s: %s", c->ident, c->last);
665 /** @brief Read a dot-stuffed list
667 * @param vecp Where to store list (UTF-8)
668 * @param nvecp Where to store number of items, or NULL
669 * @return 0 on success, non-0 on error
671 * The list will have a final NULL not counted in @p nvecp.
673 static int readlist(disorder_client *c, char ***vecp, int *nvecp) {
679 while(inputlines(c->ident, c->input, &l, '\n') >= 0) {
680 if(!strcmp(l, ".")) {
681 vector_terminate(&v);
688 vector_append(&v, xstrdup(l + (*l == '.')));
691 if(source_err(c->input)) {
692 byte_xasprintf((char **)&c->last, "input error: %s",
693 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
695 c->last = "input error: unexpxected EOF";
697 disorder_error(0, "%s: %s", c->ident, c->last);
701 /** @brief Return the user we logged in with
703 * @return User name (owned by @p c, don't modify)
705 char *disorder_user(disorder_client *c) {
709 static void pairlist_error_handler(const char *msg,
710 void attribute((unused)) *u) {
711 disorder_error(0, "error handling key-value pair reply: %s", msg);
714 /** @brief Get a list of key-value pairs
716 * @param kp Where to store linked list of preferences
718 * @param ... Arguments
719 * @return 0 on success, non-0 on error
721 static int pairlist(disorder_client *c, struct kvp **kp, const char *cmd, ...) {
723 int nvec, npvec, n, rc;
728 rc = disorder_simple_v(c, 0, cmd, ap);
732 if((rc = readlist(c, &vec, &nvec)))
734 for(n = 0; n < nvec; ++n) {
735 if(!(pvec = split(vec[n], &npvec, SPLIT_QUOTES, pairlist_error_handler, 0)))
738 pairlist_error_handler("malformed response", 0);
741 *kp = k = xmalloc(sizeof *k);
747 free_strings(nvec, vec);
752 /** @brief Parse a boolean response
753 * @param cmd Command for use in error messsage
754 * @param value Result from server
755 * @param flagp Where to store result
756 * @return 0 on success, non-0 on error
758 static int boolean(const char *cmd, const char *value,
760 if(!strcmp(value, "yes")) *flagp = 1;
761 else if(!strcmp(value, "no")) *flagp = 0;
763 disorder_error(0, "malformed response to '%s'", cmd);
769 /** @brief Log to a sink
771 * @param s Sink to write log lines to
772 * @return 0 on success, non-0 on error
774 int disorder_log(disorder_client *c, struct sink *s) {
779 if((rc = disorder_simple(c, 0, "log", (char *)0)))
781 while(inputlines(c->ident, c->input, &l, '\n') >= 0 && strcmp(l, "."))
782 if(sink_printf(s, "%s\n", l) < 0) return -1;
783 if(source_err(c->input)) {
784 byte_xasprintf((char **)&c->last, "input error: %s",
785 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
787 } else if(source_eof(c->input)) {
788 byte_xasprintf((char **)&c->last, "input error: unexpected EOF");
794 #include "client-stubs.c"