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 Determine the local socket address of this client */
123 int disorder_client_sockname(disorder_client *c,
124 struct sockaddr *sa, socklen_t *len_inout) {
126 if((rc = getsockname(c->sio.sd, sa, len_inout)))
127 disorder_error(errno, "failed to read client socket name");
131 /** @brief Determine the remote peer address for this client */
132 int disorder_client_peername(disorder_client *c,
133 struct sockaddr *sa, socklen_t *len_inout) {
135 if((rc = getpeername(c->sio.sd, sa, len_inout)))
136 disorder_error(errno, "failed to read client socket name");
140 /** @brief Read a response line
142 * @param rp Where to store response, or NULL (UTF-8)
143 * @return Response code 0-999 or -1 on error
145 static int response(disorder_client *c, char **rp) {
149 if(inputlines(c->ident, c->input, &r, '\n')) {
150 byte_xasprintf((char **)&c->last, "input error: %s",
151 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
154 D(("response: %s", r));
157 if(r[0] >= '0' && r[0] <= '9'
158 && r[1] >= '0' && r[1] <= '9'
159 && r[2] >= '0' && r[2] <= '9'
162 return (r[0] * 10 + r[1]) * 10 + r[2] - 111 * '0';
164 c->last = "invalid reply format";
165 disorder_error(0, "invalid reply format from %s", c->ident);
170 /** @brief Return last response string
172 * @return Last response string (UTF-8, English) or NULL
174 const char *disorder_last(disorder_client *c) {
178 /** @brief Read and partially parse a response
180 * @param rp Where to store response text (or NULL) (UTF-8)
181 * @return 0 on success, non-0 on error
183 * 5xx responses count as errors.
185 * @p rp will NOT be filled in for xx9 responses (where it is just
186 * commentary for a command where it would normally be meaningful).
188 * NB that the response will NOT be converted to the local encoding.
190 static int check_response(disorder_client *c, char **rp) {
194 if((rc = response(c, &r)) == -1)
196 else if(rc / 100 == 2) {
198 *rp = (rc % 10 == 9) ? 0 : xstrdup(r + 4);
203 disorder_error(0, "from %s: %s", c->ident, utf82mb(r));
209 /** @brief Issue a command and parse a simple response
211 * @param rp Where to store result, or NULL
213 * @param ap Arguments (UTF-8), terminated by (char *)0
214 * @return 0 on success, non-0 on error
216 * 5xx responses count as errors.
218 * @p rp will NOT be filled in for xx9 responses (where it is just
219 * commentary for a command where it would normally be meaningful).
221 * NB that the response will NOT be converted to the local encoding
222 * nor will quotes be stripped. See dequote().
224 * Put @ref disorder__body in the argument list followed by a char **
225 * and int giving the body to follow the command. If the int is @c -1
226 * then the list is assumed to be NULL-terminated. This may be used
229 * Put @ref disorder__list in the argument list followed by a char **
230 * and int giving a list of arguments to include. If the int is @c -1
231 * then the list is assumed to be NULL-terminated. This may be used
232 * any number of times.
234 * Put @ref disorder__integer in the argument list followed by a long to
235 * send its value in decimal. This may be used any number of times.
237 * Put @ref disorder__time in the argument list followed by a time_t
238 * to send its value in decimal. This may be used any number of
241 * Usually you would call this via one of the following interfaces:
242 * - disorder_simple()
244 static int disorder_simple_v(disorder_client *c,
256 c->last = "not connected";
257 disorder_error(0, "not connected to server");
262 dynstr_append_string(&d, cmd);
263 while((arg = va_arg(ap, const char *))) {
264 if(arg == disorder__body) {
265 body = va_arg(ap, char **);
266 nbody = va_arg(ap, int);
268 } else if(arg == disorder__list) {
269 char **list = va_arg(ap, char **);
270 int nlist = va_arg(ap, int);
273 for(nlist = 0; list[nlist]; ++nlist)
276 for(n = 0; n < nlist; ++n) {
277 dynstr_append(&d, ' ');
278 dynstr_append_string(&d, quoteutf8(arg));
280 } else if(arg == disorder__integer) {
281 long n = va_arg(ap, long);
283 byte_snprintf(buffer, sizeof buffer, "%ld", n);
284 dynstr_append(&d, ' ');
285 dynstr_append_string(&d, buffer);
286 } else if(arg == disorder__time) {
287 time_t n = va_arg(ap, time_t);
289 byte_snprintf(buffer, sizeof buffer, "%lld", (long long)n);
290 dynstr_append(&d, ' ');
291 dynstr_append_string(&d, buffer);
293 dynstr_append(&d, ' ');
294 dynstr_append_string(&d, quoteutf8(arg));
297 dynstr_append(&d, '\n');
298 dynstr_terminate(&d);
299 D(("command: %s", d.vec));
300 if(sink_write(c->output, d.vec, d.nvec) < 0)
306 for(nbody = 0; body[nbody]; ++nbody)
308 for(n = 0; n < nbody; ++n) {
309 if(body[n][0] == '.')
310 if(sink_writec(c->output, '.') < 0)
312 if(sink_writes(c->output, body[n]) < 0)
314 if(sink_writec(c->output, '\n') < 0)
317 if(sink_writes(c->output, ".\n") < 0)
320 if(sink_flush(c->output))
323 return check_response(c, rp);
325 byte_xasprintf((char **)&c->last, "write error: %s",
326 format_error(c->output->eclass, sink_err(c->output), errbuf, sizeof errbuf));
327 disorder_error(0, "%s: %s", c->ident, c->last);
331 /** @brief Issue a command and parse a simple response
333 * @param rp Where to store result, or NULL (UTF-8)
335 * @return 0 on success, non-0 on error
337 * The remaining arguments are command arguments, terminated by (char
338 * *)0. They should be in UTF-8.
340 * 5xx responses count as errors.
342 * @p rp will NOT be filled in for xx9 responses (where it is just
343 * commentary for a command where it would normally be meaningful).
345 * NB that the response will NOT be converted to the local encoding
346 * nor will quotes be stripped. See dequote().
348 static int disorder_simple(disorder_client *c,
350 const char *cmd, ...) {
355 ret = disorder_simple_v(c, rp, cmd, ap);
360 /** @brief Issue a command and split the response
362 * @param vecp Where to store results
363 * @param nvecp Where to store count of results
364 * @param expected Expected count (or -1 to not check)
366 * @return 0 on success, non-0 on error
368 * The remaining arguments are command arguments, terminated by (char
369 * *)0. They should be in UTF-8.
371 * 5xx responses count as errors.
373 * @p rp will NOT be filled in for xx9 responses (where it is just
374 * commentary for a command where it would normally be meaningful).
376 * NB that the response will NOT be converted to the local encoding
377 * nor will quotes be stripped. See dequote().
379 static int disorder_simple_split(disorder_client *c,
383 const char *cmd, ...) {
391 ret = disorder_simple_v(c, &r, cmd, ap);
394 vec = split(r, &nvec, SPLIT_QUOTES, 0, 0);
396 if(expected < 0 || nvec == expected) {
400 disorder_error(0, "malformed reply to %s", cmd);
401 c->last = "malformed reply";
403 free_strings(nvec, vec);
413 /** @brief Dequote a result string
414 * @param rc 0 on success, non-0 on error
415 * @param rp Where result string is stored (UTF-8)
418 * This is used as a wrapper around disorder_simple() to dequote
421 static int dequote(int rc, char **rp) {
425 if((rr = split(*rp, 0, SPLIT_QUOTES, 0, 0)) && *rr) {
431 disorder_error(0, "invalid reply: %s", *rp);
436 /** @brief Generic connection routine
437 * @param conf Configuration to follow
439 * @param username Username to log in with or NULL
440 * @param password Password to log in with or NULL
441 * @param cookie Cookie to log in with or NULL
442 * @return 0 on success, non-0 on error
444 * @p cookie is tried first if not NULL. If it is NULL then @p
445 * username must not be. If @p username is not NULL then nor may @p
448 int disorder_connect_generic(struct config *conf,
450 const char *username,
451 const char *password,
452 const char *cookie) {
453 SOCKET sd = INVALID_SOCKET;
455 unsigned char *nonce = NULL;
458 char *r = NULL, **rvec = NULL;
459 const char *protocol, *algorithm, *challenge;
460 struct sockaddr *sa = NULL;
464 if((salen = disorder_find_server(conf,
465 (c->trypriv ? 0 : DISORDER_FS_NOTPRIV),
466 &sa, &c->ident)) == (socklen_t)-1)
470 if((sd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0) {
471 byte_xasprintf((char **)&c->last, "socket: %s",
472 format_error(ec_socket, socket_error(), errbuf, sizeof errbuf));
473 disorder_error(0, "%s", c->last);
476 c->family = sa->sa_family;
477 if(connect(sd, sa, salen) < 0) {
478 byte_xasprintf((char **)&c->last, "connect: %s",
479 format_error(ec_socket, socket_error(), errbuf, sizeof errbuf));
480 disorder_error(0, "%s", c->last);
483 socketio_init(&c->sio, sd);
486 c->output = sink_socketio(&c->sio);
487 c->input = source_socketio(&c->sio);
488 if((rc = disorder_simple(c, &r, 0, (const char *)0)))
490 if(!(rvec = split(r, &nrvec, SPLIT_QUOTES, 0, 0)))
493 c->last = "cannot parse server greeting";
494 disorder_error(0, "cannot parse server greeting %s", r);
498 if(strcmp(protocol, "2")) {
499 c->last = "unknown protocol version";
500 disorder_error(0, "unknown protocol version: %s", protocol);
505 if(!(nonce = unhex(challenge, &nl)))
508 if(!dequote(disorder_simple(c, &c->user, "cookie", cookie, (char *)0),
510 return 0; /* success */
512 c->last = "cookie failed and no username";
513 disorder_error(0, "cookie did not work and no username available");
517 if(!(res = authhash(nonce, nl, password, algorithm))) {
518 c->last = "error computing authorization hash";
521 if((rc = disorder_simple(c, 0, "user", username, res, (char *)0)))
523 c->user = xstrdup(username);
525 free_strings(nrvec, rvec);
537 if(c->open) { socketio_close(&c->sio); c->open = 0; }
538 if(sd != INVALID_SOCKET) closesocket(sd);
542 /** @brief Connect a client with a specified username and password
544 * @param username Username to log in with
545 * @param password Password to log in with
546 * @return 0 on success, non-0 on error
548 int disorder_connect_user(disorder_client *c,
549 const char *username,
550 const char *password) {
551 return disorder_connect_generic(config,
558 /** @brief Connect a client
560 * @return 0 on success, non-0 on error
562 * The connection will use the username and password found in @ref
563 * config, or directly from the database if no password is found and
564 * the database is readable (usually only for root).
566 int disorder_connect(disorder_client *c) {
567 const char *username, *password;
569 if(!(username = config->username)) {
570 c->last = "no username";
571 disorder_error(0, "no username configured");
574 password = config->password;
575 /* If we're connecting as 'root' guess that we're the system root
576 * user (or the jukebox user), both of which can use the privileged
577 * socket. They can also furtle with the db directly: that is why
578 * privileged socket does not represent a privilege escalation. */
580 && !strcmp(username, "root"))
581 password = "anything will do for root";
584 c->last = "no password";
585 disorder_error(0, "no password configured for user '%s'", username);
588 return disorder_connect_generic(config,
595 /** @brief Connect a client
597 * @param cookie Cookie to log in with, or NULL
598 * @return 0 on success, non-0 on error
600 * If @p cookie is NULL or does not work then we attempt to log in as
601 * guest instead (so when the cookie expires only an extra round trip
602 * is needed rather than a complete new login).
604 int disorder_connect_cookie(disorder_client *c,
605 const char *cookie) {
606 return disorder_connect_generic(config,
613 /** @brief Close a client
615 * @return 0 on succcess, non-0 on errior
617 * The client is still closed even on error. It might well be
618 * appropriate to ignore the return value.
620 int disorder_close(disorder_client *c) {
624 socketio_close(&c->sio);
636 static void client_error(const char *msg,
637 void attribute((unused)) *u) {
638 disorder_error(0, "error parsing reply: %s", msg);
641 /** @brief Get a single queue entry
644 * @param qp Where to store track information
645 * @return 0 on success, non-0 on error
647 static int onequeue(disorder_client *c, const char *cmd,
648 struct queue_entry **qp) {
650 struct queue_entry *q;
653 if((rc = disorder_simple(c, &r, cmd, (char *)0)))
656 q = xmalloc(sizeof *q);
657 if(queue_unmarshall(q, r, client_error, 0))
665 /** @brief Fetch the queue, recent list, etc */
666 static int readqueue(disorder_client *c,
667 struct queue_entry **qp) {
668 struct queue_entry *qh, **qt = &qh, *q;
672 while(inputlines(c->ident, c->input, &l, '\n') >= 0) {
673 if(!strcmp(l, ".")) {
679 q = xmalloc(sizeof *q);
680 if(!queue_unmarshall(q, l, client_error, 0)) {
686 if(source_err(c->input)) {
687 byte_xasprintf((char **)&c->last, "input error: %s",
688 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
690 c->last = "input error: unexpected EOF";
692 disorder_error(0, "%s: %s", c->ident, c->last);
696 /** @brief Read a dot-stuffed list
698 * @param vecp Where to store list (UTF-8)
699 * @param nvecp Where to store number of items, or NULL
700 * @return 0 on success, non-0 on error
702 * The list will have a final NULL not counted in @p nvecp.
704 static int readlist(disorder_client *c, char ***vecp, int *nvecp) {
710 while(inputlines(c->ident, c->input, &l, '\n') >= 0) {
711 if(!strcmp(l, ".")) {
712 vector_terminate(&v);
719 vector_append(&v, xstrdup(l + (*l == '.')));
722 if(source_err(c->input)) {
723 byte_xasprintf((char **)&c->last, "input error: %s",
724 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
726 c->last = "input error: unexpxected EOF";
728 disorder_error(0, "%s: %s", c->ident, c->last);
732 /** @brief Return the user we logged in with
734 * @return User name (owned by @p c, don't modify)
736 char *disorder_user(disorder_client *c) {
740 static void pairlist_error_handler(const char *msg,
741 void attribute((unused)) *u) {
742 disorder_error(0, "error handling key-value pair reply: %s", msg);
745 /** @brief Get a list of key-value pairs
747 * @param kp Where to store linked list of preferences
749 * @param ... Arguments
750 * @return 0 on success, non-0 on error
752 static int pairlist(disorder_client *c, struct kvp **kp, const char *cmd, ...) {
754 int nvec, npvec, n, rc;
759 rc = disorder_simple_v(c, 0, cmd, ap);
763 if((rc = readlist(c, &vec, &nvec)))
765 for(n = 0; n < nvec; ++n) {
766 if(!(pvec = split(vec[n], &npvec, SPLIT_QUOTES, pairlist_error_handler, 0)))
769 pairlist_error_handler("malformed response", 0);
772 *kp = k = xmalloc(sizeof *k);
778 free_strings(nvec, vec);
784 # define boolean bodge_boolean
787 /** @brief Parse a boolean response
788 * @param cmd Command for use in error messsage
789 * @param value Result from server
790 * @param flagp Where to store result
791 * @return 0 on success, non-0 on error
793 static int boolean(const char *cmd, const char *value,
795 if(!strcmp(value, "yes")) *flagp = 1;
796 else if(!strcmp(value, "no")) *flagp = 0;
798 disorder_error(0, "malformed response to '%s'", cmd);
804 /** @brief Log to a sink
806 * @param s Sink to write log lines to
807 * @return 0 on success, non-0 on error
809 int disorder_log(disorder_client *c, struct sink *s) {
814 if((rc = disorder_simple(c, 0, "log", (char *)0)))
816 while(inputlines(c->ident, c->input, &l, '\n') >= 0 && strcmp(l, "."))
817 if(sink_printf(s, "%s\n", l) < 0) return -1;
818 if(source_err(c->input)) {
819 byte_xasprintf((char **)&c->last, "input error: %s",
820 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
822 } else if(source_eof(c->input)) {
823 byte_xasprintf((char **)&c->last, "input error: unexpected EOF");
830 #include "client-stubs.c"