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 Determine the local socket address of this client */
118 int disorder_client_sockname(disorder_client *c,
119 struct sockaddr *sa, socklen_t *len_inout) {
121 if((rc = getsockname(c->sio.sd, sa, len_inout)))
122 disorder_error(errno, "failed to read client socket name");
126 /** @brief Determine the remote peer address for this client */
127 int disorder_client_peername(disorder_client *c,
128 struct sockaddr *sa, socklen_t *len_inout) {
130 if((rc = getpeername(c->sio.sd, sa, len_inout)))
131 disorder_error(errno, "failed to read client socket name");
135 /** @brief Read a response line
137 * @param rp Where to store response, or NULL (UTF-8)
138 * @return Response code 0-999 or -1 on error
140 static int response(disorder_client *c, char **rp) {
144 if(inputlines(c->ident, c->input, &r, '\n')) {
145 byte_xasprintf((char **)&c->last, "input error: %s",
146 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
149 D(("response: %s", r));
152 if(r[0] >= '0' && r[0] <= '9'
153 && r[1] >= '0' && r[1] <= '9'
154 && r[2] >= '0' && r[2] <= '9'
157 return (r[0] * 10 + r[1]) * 10 + r[2] - 111 * '0';
159 c->last = "invalid reply format";
160 disorder_error(0, "invalid reply format from %s", c->ident);
165 /** @brief Return last response string
167 * @return Last response string (UTF-8, English) or NULL
169 const char *disorder_last(disorder_client *c) {
173 /** @brief Read and partially parse a response
175 * @param rp Where to store response text (or NULL) (UTF-8)
176 * @return 0 on success, non-0 on error
178 * 5xx responses count as errors.
180 * @p rp will NOT be filled in for xx9 responses (where it is just
181 * commentary for a command where it would normally be meaningful).
183 * NB that the response will NOT be converted to the local encoding.
185 static int check_response(disorder_client *c, char **rp) {
189 if((rc = response(c, &r)) == -1)
191 else if(rc / 100 == 2) {
193 *rp = (rc % 10 == 9) ? 0 : xstrdup(r + 4);
198 disorder_error(0, "from %s: %s", c->ident, utf82mb(r));
204 /** @brief Issue a command and parse a simple response
206 * @param rp Where to store result, or NULL
208 * @param ap Arguments (UTF-8), terminated by (char *)0
209 * @return 0 on success, non-0 on error
211 * 5xx responses count as errors.
213 * @p rp will NOT be filled in for xx9 responses (where it is just
214 * commentary for a command where it would normally be meaningful).
216 * NB that the response will NOT be converted to the local encoding
217 * nor will quotes be stripped. See dequote().
219 * Put @ref disorder__body in the argument list followed by a char **
220 * and int giving the body to follow the command. If the int is @c -1
221 * then the list is assumed to be NULL-terminated. This may be used
224 * Put @ref disorder__list in the argument list followed by a char **
225 * and int giving a list of arguments to include. If the int is @c -1
226 * then the list is assumed to be NULL-terminated. This may be used
227 * any number of times.
229 * Put @ref disorder__integer in the argument list followed by a long to
230 * send its value in decimal. This may be used any number of times.
232 * Put @ref disorder__time in the argument list followed by a time_t
233 * to send its value in decimal. This may be used any number of
236 * Usually you would call this via one of the following interfaces:
237 * - disorder_simple()
239 static int disorder_simple_v(disorder_client *c,
251 c->last = "not connected";
252 disorder_error(0, "not connected to server");
257 dynstr_append_string(&d, cmd);
258 while((arg = va_arg(ap, const char *))) {
259 if(arg == disorder__body) {
260 body = va_arg(ap, char **);
261 nbody = va_arg(ap, int);
263 } else if(arg == disorder__list) {
264 char **list = va_arg(ap, char **);
265 int nlist = va_arg(ap, int);
268 for(nlist = 0; list[nlist]; ++nlist)
271 for(n = 0; n < nlist; ++n) {
272 dynstr_append(&d, ' ');
273 dynstr_append_string(&d, quoteutf8(arg));
275 } else if(arg == disorder__integer) {
276 long n = va_arg(ap, long);
278 byte_snprintf(buffer, sizeof buffer, "%ld", n);
279 dynstr_append(&d, ' ');
280 dynstr_append_string(&d, buffer);
281 } else if(arg == disorder__time) {
282 time_t n = va_arg(ap, time_t);
284 byte_snprintf(buffer, sizeof buffer, "%lld", (long long)n);
285 dynstr_append(&d, ' ');
286 dynstr_append_string(&d, buffer);
288 dynstr_append(&d, ' ');
289 dynstr_append_string(&d, quoteutf8(arg));
292 dynstr_append(&d, '\n');
293 dynstr_terminate(&d);
294 D(("command: %s", d.vec));
295 if(sink_write(c->output, d.vec, d.nvec) < 0)
301 for(nbody = 0; body[nbody]; ++nbody)
303 for(n = 0; n < nbody; ++n) {
304 if(body[n][0] == '.')
305 if(sink_writec(c->output, '.') < 0)
307 if(sink_writes(c->output, body[n]) < 0)
309 if(sink_writec(c->output, '\n') < 0)
312 if(sink_writes(c->output, ".\n") < 0)
315 if(sink_flush(c->output))
318 return check_response(c, rp);
320 byte_xasprintf((char **)&c->last, "write error: %s",
321 format_error(c->output->eclass, sink_err(c->output), errbuf, sizeof errbuf));
322 disorder_error(0, "%s: %s", c->ident, c->last);
326 /** @brief Issue a command and parse a simple response
328 * @param rp Where to store result, or NULL (UTF-8)
330 * @return 0 on success, non-0 on error
332 * The remaining arguments are command arguments, terminated by (char
333 * *)0. They should be in UTF-8.
335 * 5xx responses count as errors.
337 * @p rp will NOT be filled in for xx9 responses (where it is just
338 * commentary for a command where it would normally be meaningful).
340 * NB that the response will NOT be converted to the local encoding
341 * nor will quotes be stripped. See dequote().
343 static int disorder_simple(disorder_client *c,
345 const char *cmd, ...) {
350 ret = disorder_simple_v(c, rp, cmd, ap);
355 /** @brief Issue a command and split the response
357 * @param vecp Where to store results
358 * @param nvecp Where to store count of results
359 * @param expected Expected count (or -1 to not check)
361 * @return 0 on success, non-0 on error
363 * The remaining arguments are command arguments, terminated by (char
364 * *)0. They should be in UTF-8.
366 * 5xx responses count as errors.
368 * @p rp will NOT be filled in for xx9 responses (where it is just
369 * commentary for a command where it would normally be meaningful).
371 * NB that the response will NOT be converted to the local encoding
372 * nor will quotes be stripped. See dequote().
374 static int disorder_simple_split(disorder_client *c,
378 const char *cmd, ...) {
386 ret = disorder_simple_v(c, &r, cmd, ap);
389 vec = split(r, &nvec, SPLIT_QUOTES, 0, 0);
391 if(expected < 0 || nvec == expected) {
395 disorder_error(0, "malformed reply to %s", cmd);
396 c->last = "malformed reply";
398 free_strings(nvec, vec);
408 /** @brief Dequote a result string
409 * @param rc 0 on success, non-0 on error
410 * @param rp Where result string is stored (UTF-8)
413 * This is used as a wrapper around disorder_simple() to dequote
416 static int dequote(int rc, char **rp) {
420 if((rr = split(*rp, 0, SPLIT_QUOTES, 0, 0)) && *rr) {
426 disorder_error(0, "invalid reply: %s", *rp);
431 /** @brief Generic connection routine
432 * @param conf Configuration to follow
434 * @param username Username to log in with or NULL
435 * @param password Password to log in with or NULL
436 * @param cookie Cookie to log in with or NULL
437 * @return 0 on success, non-0 on error
439 * @p cookie is tried first if not NULL. If it is NULL then @p
440 * username must not be. If @p username is not NULL then nor may @p
443 int disorder_connect_generic(struct config *conf,
445 const char *username,
446 const char *password,
447 const char *cookie) {
448 SOCKET sd = INVALID_SOCKET;
450 unsigned char *nonce = NULL;
453 char *r = NULL, **rvec = NULL;
454 const char *protocol, *algorithm, *challenge;
455 struct sockaddr *sa = NULL;
459 if((salen = disorder_find_server(conf,
460 (c->trypriv ? 0 : DISORDER_FS_NOTPRIV),
461 &sa, &c->ident)) == (socklen_t)-1)
465 if((sd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0) {
466 byte_xasprintf((char **)&c->last, "socket: %s",
467 format_error(ec_socket, socket_error(), errbuf, sizeof errbuf));
468 disorder_error(0, "%s", c->last);
471 c->family = sa->sa_family;
472 if(connect(sd, sa, salen) < 0) {
473 byte_xasprintf((char **)&c->last, "connect: %s",
474 format_error(ec_socket, socket_error(), errbuf, sizeof errbuf));
475 disorder_error(0, "%s", c->last);
478 socketio_init(&c->sio, sd);
481 c->output = sink_socketio(&c->sio);
482 c->input = source_socketio(&c->sio);
483 if((rc = disorder_simple(c, &r, 0, (const char *)0)))
485 if(!(rvec = split(r, &nrvec, SPLIT_QUOTES, 0, 0)))
488 c->last = "cannot parse server greeting";
489 disorder_error(0, "cannot parse server greeting %s", r);
493 if(strcmp(protocol, "2")) {
494 c->last = "unknown protocol version";
495 disorder_error(0, "unknown protocol version: %s", protocol);
500 if(!(nonce = unhex(challenge, &nl)))
503 if(!dequote(disorder_simple(c, &c->user, "cookie", cookie, (char *)0),
505 return 0; /* success */
507 c->last = "cookie failed and no username";
508 disorder_error(0, "cookie did not work and no username available");
512 if(!(res = authhash(nonce, nl, password, algorithm))) {
513 c->last = "error computing authorization hash";
516 if((rc = disorder_simple(c, 0, "user", username, res, (char *)0)))
518 c->user = xstrdup(username);
520 free_strings(nrvec, rvec);
532 if(c->open) { socketio_close(&c->sio); c->open = 0; }
533 if(sd != INVALID_SOCKET) closesocket(sd);
537 /** @brief Connect a client with a specified username and password
539 * @param username Username to log in with
540 * @param password Password to log in with
541 * @return 0 on success, non-0 on error
543 int disorder_connect_user(disorder_client *c,
544 const char *username,
545 const char *password) {
546 return disorder_connect_generic(config,
553 /** @brief Connect a client
555 * @return 0 on success, non-0 on error
557 * The connection will use the username and password found in @ref
558 * config, or directly from the database if no password is found and
559 * the database is readable (usually only for root).
561 int disorder_connect(disorder_client *c) {
562 const char *username, *password;
564 if(!(username = config->username)) {
565 c->last = "no username";
566 disorder_error(0, "no username configured");
569 password = config->password;
570 /* If we're connecting as 'root' guess that we're the system root
571 * user (or the jukebox user), both of which can use the privileged
572 * socket. They can also furtle with the db directly: that is why
573 * privileged socket does not represent a privilege escalation. */
575 && !strcmp(username, "root"))
576 password = "anything will do for root";
579 c->last = "no password";
580 disorder_error(0, "no password configured for user '%s'", username);
583 return disorder_connect_generic(config,
590 /** @brief Connect a client
592 * @param cookie Cookie to log in with, or NULL
593 * @return 0 on success, non-0 on error
595 * If @p cookie is NULL or does not work then we attempt to log in as
596 * guest instead (so when the cookie expires only an extra round trip
597 * is needed rather than a complete new login).
599 int disorder_connect_cookie(disorder_client *c,
600 const char *cookie) {
601 return disorder_connect_generic(config,
608 /** @brief Close a client
610 * @return 0 on succcess, non-0 on errior
612 * The client is still closed even on error. It might well be
613 * appropriate to ignore the return value.
615 int disorder_close(disorder_client *c) {
619 socketio_close(&c->sio);
631 static void client_error(const char *msg,
632 void attribute((unused)) *u) {
633 disorder_error(0, "error parsing reply: %s", msg);
636 /** @brief Get a single queue entry
639 * @param qp Where to store track information
640 * @return 0 on success, non-0 on error
642 static int onequeue(disorder_client *c, const char *cmd,
643 struct queue_entry **qp) {
645 struct queue_entry *q;
648 if((rc = disorder_simple(c, &r, cmd, (char *)0)))
651 q = xmalloc(sizeof *q);
652 if(queue_unmarshall(q, r, client_error, 0))
660 /** @brief Fetch the queue, recent list, etc */
661 static int readqueue(disorder_client *c,
662 struct queue_entry **qp) {
663 struct queue_entry *qh, **qt = &qh, *q;
667 while(inputlines(c->ident, c->input, &l, '\n') >= 0) {
668 if(!strcmp(l, ".")) {
674 q = xmalloc(sizeof *q);
675 if(!queue_unmarshall(q, l, client_error, 0)) {
681 if(source_err(c->input)) {
682 byte_xasprintf((char **)&c->last, "input error: %s",
683 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
685 c->last = "input error: unexpected EOF";
687 disorder_error(0, "%s: %s", c->ident, c->last);
691 /** @brief Read a dot-stuffed list
693 * @param vecp Where to store list (UTF-8)
694 * @param nvecp Where to store number of items, or NULL
695 * @return 0 on success, non-0 on error
697 * The list will have a final NULL not counted in @p nvecp.
699 static int readlist(disorder_client *c, char ***vecp, int *nvecp) {
705 while(inputlines(c->ident, c->input, &l, '\n') >= 0) {
706 if(!strcmp(l, ".")) {
707 vector_terminate(&v);
714 vector_append(&v, xstrdup(l + (*l == '.')));
717 if(source_err(c->input)) {
718 byte_xasprintf((char **)&c->last, "input error: %s",
719 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
721 c->last = "input error: unexpxected EOF";
723 disorder_error(0, "%s: %s", c->ident, c->last);
727 /** @brief Return the user we logged in with
729 * @return User name (owned by @p c, don't modify)
731 char *disorder_user(disorder_client *c) {
735 static void pairlist_error_handler(const char *msg,
736 void attribute((unused)) *u) {
737 disorder_error(0, "error handling key-value pair reply: %s", msg);
740 /** @brief Get a list of key-value pairs
742 * @param kp Where to store linked list of preferences
744 * @param ... Arguments
745 * @return 0 on success, non-0 on error
747 static int pairlist(disorder_client *c, struct kvp **kp, const char *cmd, ...) {
749 int nvec, npvec, n, rc;
754 rc = disorder_simple_v(c, 0, cmd, ap);
758 if((rc = readlist(c, &vec, &nvec)))
760 for(n = 0; n < nvec; ++n) {
761 if(!(pvec = split(vec[n], &npvec, SPLIT_QUOTES, pairlist_error_handler, 0)))
764 pairlist_error_handler("malformed response", 0);
767 *kp = k = xmalloc(sizeof *k);
773 free_strings(nvec, vec);
779 # define boolean bodge_boolean
782 /** @brief Parse a boolean response
783 * @param cmd Command for use in error messsage
784 * @param value Result from server
785 * @param flagp Where to store result
786 * @return 0 on success, non-0 on error
788 static int boolean(const char *cmd, const char *value,
790 if(!strcmp(value, "yes")) *flagp = 1;
791 else if(!strcmp(value, "no")) *flagp = 0;
793 disorder_error(0, "malformed response to '%s'", cmd);
799 /** @brief Log to a sink
801 * @param s Sink to write log lines to
802 * @return 0 on success, non-0 on error
804 int disorder_log(disorder_client *c, struct sink *s) {
809 if((rc = disorder_simple(c, 0, "log", (char *)0)))
811 while(inputlines(c->ident, c->input, &l, '\n') >= 0 && strcmp(l, "."))
812 if(sink_printf(s, "%s\n", l) < 0) return -1;
813 if(source_err(c->input)) {
814 byte_xasprintf((char **)&c->last, "input error: %s",
815 format_error(c->input->eclass, source_err(c->input), errbuf, sizeof errbuf));
817 } else if(source_eof(c->input)) {
818 byte_xasprintf((char **)&c->last, "input error: unexpected EOF");
825 #include "client-stubs.c"