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>
53 #include "inputline.h"
60 #include "client-common.h"
65 /** @brief Client handle contents */
66 struct disorder_client {
67 /** @brief Stream to read from */
69 /** @brief Stream to write to */
71 /** @brief Peer description */
73 /** @brief Username */
75 /** @brief Report errors to @c stderr */
77 /** @brief Last error string */
79 /** @brief Address family */
81 /** @brief True if open */
83 /** @brief Socket I/O context */
85 /** @brief Whether to try to open a privileged connection */
89 /** @brief Create a new client
90 * @param verbose If nonzero, write extra junk to stderr
91 * @return Pointer to new client
93 * You must call disorder_connect(), disorder_connect_user() or
94 * disorder_connect_cookie() to connect it. Use disorder_close() to
95 * dispose of the client when finished with it.
97 disorder_client *disorder_new(int verbose) {
98 disorder_client *c = xmalloc(sizeof (struct disorder_client));
100 c->verbose = verbose;
106 /** @brief Don't try to make a privileged connection
109 * You must call this before any of the connection functions (e.g.,
110 * disorder_connect(), disorder_connect_user()), if at all.
112 void disorder_force_unpriv(disorder_client *c) {
117 /** @brief Return the address family used by this client */
118 int disorder_client_af(disorder_client *c) {
122 /** @brief Read a response line
124 * @param rp Where to store response, or NULL (UTF-8)
125 * @return Response code 0-999 or -1 on error
127 static int response(disorder_client *c, char **rp) {
131 if(inputlines(c->ident, c->input, &r, '\n')) {
132 byte_xasprintf((char **)&c->last, "input error: %s",
133 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
136 D(("response: %s", r));
139 if(r[0] >= '0' && r[0] <= '9'
140 && r[1] >= '0' && r[1] <= '9'
141 && r[2] >= '0' && r[2] <= '9'
144 return (r[0] * 10 + r[1]) * 10 + r[2] - 111 * '0';
146 c->last = "invalid reply format";
147 disorder_error(0, "invalid reply format from %s", c->ident);
152 /** @brief Return last response string
154 * @return Last response string (UTF-8, English) or NULL
156 const char *disorder_last(disorder_client *c) {
160 /** @brief Read and partially parse a response
162 * @param rp Where to store response text (or NULL) (UTF-8)
163 * @return 0 on success, non-0 on error
165 * 5xx responses count as errors.
167 * @p rp will NOT be filled in for xx9 responses (where it is just
168 * commentary for a command where it would normally be meaningful).
170 * NB that the response will NOT be converted to the local encoding.
172 static int check_response(disorder_client *c, char **rp) {
176 if((rc = response(c, &r)) == -1)
178 else if(rc / 100 == 2) {
180 *rp = (rc % 10 == 9) ? 0 : xstrdup(r + 4);
185 disorder_error(0, "from %s: %s", c->ident, utf82mb(r));
191 /** @brief Issue a command and parse a simple response
193 * @param rp Where to store result, or NULL
195 * @param ap Arguments (UTF-8), terminated by (char *)0
196 * @return 0 on success, non-0 on error
198 * 5xx responses count as errors.
200 * @p rp will NOT be filled in for xx9 responses (where it is just
201 * commentary for a command where it would normally be meaningful).
203 * NB that the response will NOT be converted to the local encoding
204 * nor will quotes be stripped. See dequote().
206 * Put @ref disorder__body in the argument list followed by a char **
207 * and int giving the body to follow the command. If the int is @c -1
208 * then the list is assumed to be NULL-terminated. This may be used
211 * Put @ref disorder__list in the argument list followed by a char **
212 * and int giving a list of arguments to include. If the int is @c -1
213 * then the list is assumed to be NULL-terminated. This may be used
214 * any number of times.
216 * Put @ref disorder__integer in the argument list followed by a long to
217 * send its value in decimal. This may be used any number of times.
219 * Put @ref disorder__time in the argument list followed by a time_t
220 * to send its value in decimal. This may be used any number of
223 * Usually you would call this via one of the following interfaces:
224 * - disorder_simple()
226 static int disorder_simple_v(disorder_client *c,
238 c->last = "not connected";
239 disorder_error(0, "not connected to server");
244 dynstr_append_string(&d, cmd);
245 while((arg = va_arg(ap, const char *))) {
246 if(arg == disorder__body) {
247 body = va_arg(ap, char **);
248 nbody = va_arg(ap, int);
250 } else if(arg == disorder__list) {
251 char **list = va_arg(ap, char **);
252 int nlist = va_arg(ap, int);
255 for(nlist = 0; list[nlist]; ++nlist)
258 for(n = 0; n < nlist; ++n) {
259 dynstr_append(&d, ' ');
260 dynstr_append_string(&d, quoteutf8(arg));
262 } else if(arg == disorder__integer) {
263 long n = va_arg(ap, long);
265 byte_snprintf(buffer, sizeof buffer, "%ld", n);
266 dynstr_append(&d, ' ');
267 dynstr_append_string(&d, buffer);
268 } else if(arg == disorder__time) {
269 time_t n = va_arg(ap, time_t);
271 byte_snprintf(buffer, sizeof buffer, "%lld", (long long)n);
272 dynstr_append(&d, ' ');
273 dynstr_append_string(&d, buffer);
275 dynstr_append(&d, ' ');
276 dynstr_append_string(&d, quoteutf8(arg));
279 dynstr_append(&d, '\n');
280 dynstr_terminate(&d);
281 D(("command: %s", d.vec));
282 if(sink_write(c->output, d.vec, d.nvec) < 0)
288 for(nbody = 0; body[nbody]; ++nbody)
290 for(n = 0; n < nbody; ++n) {
291 if(body[n][0] == '.')
292 if(sink_writec(c->output, '.') < 0)
294 if(sink_writes(c->output, body[n]) < 0)
296 if(sink_writec(c->output, '\n') < 0)
299 if(sink_writes(c->output, ".\n") < 0)
302 if(sink_flush(c->output))
305 return check_response(c, rp);
307 byte_xasprintf((char **)&c->last, "write error: %s",
308 format_error(c->output->eclass, sink_err(c->output), errbuf, sizeof errbuf));
309 disorder_error(0, "%s: %s", c->ident, c->last);
313 /** @brief Issue a command and parse a simple response
315 * @param rp Where to store result, or NULL (UTF-8)
317 * @return 0 on success, non-0 on error
319 * The remaining arguments are command arguments, terminated by (char
320 * *)0. They should be in UTF-8.
322 * 5xx responses count as errors.
324 * @p rp will NOT be filled in for xx9 responses (where it is just
325 * commentary for a command where it would normally be meaningful).
327 * NB that the response will NOT be converted to the local encoding
328 * nor will quotes be stripped. See dequote().
330 static int disorder_simple(disorder_client *c,
332 const char *cmd, ...) {
337 ret = disorder_simple_v(c, rp, cmd, ap);
342 /** @brief Issue a command and split the response
344 * @param vecp Where to store results
345 * @param nvecp Where to store count of results
346 * @param expected Expected count (or -1 to not check)
348 * @return 0 on success, non-0 on error
350 * The remaining arguments are command arguments, terminated by (char
351 * *)0. They should be in UTF-8.
353 * 5xx responses count as errors.
355 * @p rp will NOT be filled in for xx9 responses (where it is just
356 * commentary for a command where it would normally be meaningful).
358 * NB that the response will NOT be converted to the local encoding
359 * nor will quotes be stripped. See dequote().
361 static int disorder_simple_split(disorder_client *c,
365 const char *cmd, ...) {
373 ret = disorder_simple_v(c, &r, cmd, ap);
376 vec = split(r, &nvec, SPLIT_QUOTES, 0, 0);
378 if(expected < 0 || nvec == expected) {
382 disorder_error(0, "malformed reply to %s", cmd);
383 c->last = "malformed reply";
385 free_strings(nvec, vec);
395 /** @brief Dequote a result string
396 * @param rc 0 on success, non-0 on error
397 * @param rp Where result string is stored (UTF-8)
400 * This is used as a wrapper around disorder_simple() to dequote
403 static int dequote(int rc, char **rp) {
407 if((rr = split(*rp, 0, SPLIT_QUOTES, 0, 0)) && *rr) {
413 disorder_error(0, "invalid reply: %s", *rp);
418 /** @brief Generic connection routine
419 * @param conf Configuration to follow
421 * @param username Username to log in with or NULL
422 * @param password Password to log in with or NULL
423 * @param cookie Cookie to log in with or NULL
424 * @return 0 on success, non-0 on error
426 * @p cookie is tried first if not NULL. If it is NULL then @p
427 * username must not be. If @p username is not NULL then nor may @p
430 int disorder_connect_generic(struct config *conf,
432 const char *username,
433 const char *password,
434 const char *cookie) {
435 SOCKET sd = INVALID_SOCKET;
437 unsigned char *nonce = NULL;
440 char *r = NULL, **rvec = NULL;
441 const char *protocol, *algorithm, *challenge;
442 struct sockaddr *sa = NULL;
446 if((salen = disorder_find_server(conf,
447 (c->trypriv ? 0 : DISORDER_FS_NOTPRIV),
448 &sa, &c->ident)) == (socklen_t)-1)
452 if((sd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0) {
453 byte_xasprintf((char **)&c->last, "socket: %s",
454 format_error(ec_socket, socket_error(), errbuf, sizeof errbuf));
455 disorder_error(0, "%s", c->last);
458 c->family = sa->sa_family;
459 if(connect(sd, sa, salen) < 0) {
460 byte_xasprintf((char **)&c->last, "connect: %s",
461 format_error(ec_socket, socket_error(), errbuf, sizeof errbuf));
462 disorder_error(0, "%s", c->last);
465 socketio_init(&c->sio, sd);
468 c->output = sink_socketio(&c->sio);
469 c->input = source_socketio(&c->sio);
470 if((rc = disorder_simple(c, &r, 0, (const char *)0)))
472 if(!(rvec = split(r, &nrvec, SPLIT_QUOTES, 0, 0)))
475 c->last = "cannot parse server greeting";
476 disorder_error(0, "cannot parse server greeting %s", r);
480 if(strcmp(protocol, "2")) {
481 c->last = "unknown protocol version";
482 disorder_error(0, "unknown protocol version: %s", protocol);
487 if(!(nonce = unhex(challenge, &nl)))
490 if(!dequote(disorder_simple(c, &c->user, "cookie", cookie, (char *)0),
492 return 0; /* success */
494 c->last = "cookie failed and no username";
495 disorder_error(0, "cookie did not work and no username available");
499 if(!(res = authhash(nonce, nl, password, algorithm))) {
500 c->last = "error computing authorization hash";
503 if((rc = disorder_simple(c, 0, "user", username, res, (char *)0)))
505 c->user = xstrdup(username);
507 free_strings(nrvec, rvec);
519 if(c->open) { socketio_close(&c->sio); c->open = 0; }
520 if(sd != INVALID_SOCKET) closesocket(sd);
524 /** @brief Connect a client with a specified username and password
526 * @param username Username to log in with
527 * @param password Password to log in with
528 * @return 0 on success, non-0 on error
530 int disorder_connect_user(disorder_client *c,
531 const char *username,
532 const char *password) {
533 return disorder_connect_generic(config,
540 /** @brief Connect a client
542 * @return 0 on success, non-0 on error
544 * The connection will use the username and password found in @ref
545 * config, or directly from the database if no password is found and
546 * the database is readable (usually only for root).
548 int disorder_connect(disorder_client *c) {
549 const char *username, *password;
551 if(!(username = config->username)) {
552 c->last = "no username";
553 disorder_error(0, "no username configured");
556 password = config->password;
557 /* If we're connecting as 'root' guess that we're the system root
558 * user (or the jukebox user), both of which can use the privileged
559 * socket. They can also furtle with the db directly: that is why
560 * privileged socket does not represent a privilege escalation. */
562 && !strcmp(username, "root"))
563 password = "anything will do for root";
566 c->last = "no password";
567 disorder_error(0, "no password configured for user '%s'", username);
570 return disorder_connect_generic(config,
577 /** @brief Connect a client
579 * @param cookie Cookie to log in with, or NULL
580 * @return 0 on success, non-0 on error
582 * If @p cookie is NULL or does not work then we attempt to log in as
583 * guest instead (so when the cookie expires only an extra round trip
584 * is needed rather than a complete new login).
586 int disorder_connect_cookie(disorder_client *c,
587 const char *cookie) {
588 return disorder_connect_generic(config,
595 /** @brief Close a client
597 * @return 0 on succcess, non-0 on errior
599 * The client is still closed even on error. It might well be
600 * appropriate to ignore the return value.
602 int disorder_close(disorder_client *c) {
606 socketio_close(&c->sio);
618 static void client_error(const char *msg,
619 void attribute((unused)) *u) {
620 disorder_error(0, "error parsing reply: %s", msg);
623 /** @brief Get a single queue entry
626 * @param qp Where to store track information
627 * @return 0 on success, non-0 on error
629 static int onequeue(disorder_client *c, const char *cmd,
630 struct queue_entry **qp) {
632 struct queue_entry *q;
635 if((rc = disorder_simple(c, &r, cmd, (char *)0)))
638 q = xmalloc(sizeof *q);
639 if(queue_unmarshall(q, r, client_error, 0))
647 /** @brief Fetch the queue, recent list, etc */
648 static int readqueue(disorder_client *c,
649 struct queue_entry **qp) {
650 struct queue_entry *qh, **qt = &qh, *q;
654 while(inputlines(c->ident, c->input, &l, '\n') >= 0) {
655 if(!strcmp(l, ".")) {
661 q = xmalloc(sizeof *q);
662 if(!queue_unmarshall(q, l, client_error, 0)) {
668 if(source_err(c->input)) {
669 byte_xasprintf((char **)&c->last, "input error: %s",
670 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
672 c->last = "input error: unexpected EOF";
674 disorder_error(0, "%s: %s", c->ident, c->last);
678 /** @brief Read a dot-stuffed list
680 * @param vecp Where to store list (UTF-8)
681 * @param nvecp Where to store number of items, or NULL
682 * @return 0 on success, non-0 on error
684 * The list will have a final NULL not counted in @p nvecp.
686 static int readlist(disorder_client *c, char ***vecp, int *nvecp) {
692 while(inputlines(c->ident, c->input, &l, '\n') >= 0) {
693 if(!strcmp(l, ".")) {
694 vector_terminate(&v);
701 vector_append(&v, xstrdup(l + (*l == '.')));
704 if(source_err(c->input)) {
705 byte_xasprintf((char **)&c->last, "input error: %s",
706 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
708 c->last = "input error: unexpxected EOF";
710 disorder_error(0, "%s: %s", c->ident, c->last);
714 /** @brief Return the user we logged in with
716 * @return User name (owned by @p c, don't modify)
718 char *disorder_user(disorder_client *c) {
722 static void pairlist_error_handler(const char *msg,
723 void attribute((unused)) *u) {
724 disorder_error(0, "error handling key-value pair reply: %s", msg);
727 /** @brief Get a list of key-value pairs
729 * @param kp Where to store linked list of preferences
731 * @param ... Arguments
732 * @return 0 on success, non-0 on error
734 static int pairlist(disorder_client *c, struct kvp **kp, const char *cmd, ...) {
736 int nvec, npvec, n, rc;
741 rc = disorder_simple_v(c, 0, cmd, ap);
745 if((rc = readlist(c, &vec, &nvec)))
747 for(n = 0; n < nvec; ++n) {
748 if(!(pvec = split(vec[n], &npvec, SPLIT_QUOTES, pairlist_error_handler, 0)))
751 pairlist_error_handler("malformed response", 0);
754 *kp = k = xmalloc(sizeof *k);
760 free_strings(nvec, vec);
766 # define boolean bodge_boolean
769 /** @brief Parse a boolean response
770 * @param cmd Command for use in error messsage
771 * @param value Result from server
772 * @param flagp Where to store result
773 * @return 0 on success, non-0 on error
775 static int boolean(const char *cmd, const char *value,
777 if(!strcmp(value, "yes")) *flagp = 1;
778 else if(!strcmp(value, "no")) *flagp = 0;
780 disorder_error(0, "malformed response to '%s'", cmd);
786 /** @brief Log to a sink
788 * @param s Sink to write log lines to
789 * @return 0 on success, non-0 on error
791 int disorder_log(disorder_client *c, struct sink *s) {
796 if((rc = disorder_simple(c, 0, "log", (char *)0)))
798 while(inputlines(c->ident, c->input, &l, '\n') >= 0 && strcmp(l, "."))
799 if(sink_printf(s, "%s\n", l) < 0) return -1;
800 if(source_err(c->input)) {
801 byte_xasprintf((char **)&c->last, "input error: %s",
802 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
804 } else if(source_eof(c->input)) {
805 byte_xasprintf((char **)&c->last, "input error: unexpected EOF");
812 #include "client-stubs.c"