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 */
88 /** @brief Whether to try to open a privileged connection */
92 /** @brief Create a new client
93 * @param verbose If nonzero, write extra junk to stderr
94 * @return Pointer to new client
96 * You must call disorder_connect(), disorder_connect_user() or
97 * disorder_connect_cookie() to connect it. Use disorder_close() to
98 * dispose of the client when finished with it.
100 disorder_client
*disorder_new(int verbose
) {
101 disorder_client
*c
= xmalloc(sizeof (struct disorder_client
));
103 c
->verbose
= verbose
;
109 /** @brief Don't try to make a privileged connection
112 * You must call this before any of the connection functions (e.g.,
113 * disorder_connect(), disorder_connect_user()), if at all.
115 void disorder_force_unpriv(disorder_client
*c
) {
120 /** @brief Return the address family used by this client */
121 int disorder_client_af(disorder_client
*c
) {
125 /** @brief Read a response line
127 * @param rp Where to store response, or NULL (UTF-8)
128 * @return Response code 0-999 or -1 on error
130 static int response(disorder_client
*c
, char **rp
) {
134 if(inputlines(c
->ident
, c
->input
, &r
, '\n')) {
135 byte_xasprintf((char **)&c
->last
, "input error: %s",
136 format_error(c
->input
->eclass
, source_err(c
->input
), errbuf
, sizeof errbuf
));
139 D(("response: %s", r
));
142 if(r
[0] >= '0' && r
[0] <= '9'
143 && r
[1] >= '0' && r
[1] <= '9'
144 && r
[2] >= '0' && r
[2] <= '9'
147 return (r
[0] * 10 + r
[1]) * 10 + r
[2] - 111 * '0';
149 c
->last
= "invalid reply format";
150 disorder_error(0, "invalid reply format from %s", c
->ident
);
155 /** @brief Return last response string
157 * @return Last response string (UTF-8, English) or NULL
159 const char *disorder_last(disorder_client
*c
) {
163 /** @brief Read and partially parse a response
165 * @param rp Where to store response text (or NULL) (UTF-8)
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.
175 static int check_response(disorder_client
*c
, char **rp
) {
179 if((rc
= response(c
, &r
)) == -1)
181 else if(rc
/ 100 == 2) {
183 *rp
= (rc
% 10 == 9) ?
0 : xstrdup(r
+ 4);
188 disorder_error(0, "from %s: %s", c
->ident
, utf82mb(r
));
194 /** @brief Issue a command and parse a simple response
196 * @param rp Where to store result, or NULL
198 * @param ap Arguments (UTF-8), terminated by (char *)0
199 * @return 0 on success, non-0 on error
201 * 5xx responses count as errors.
203 * @p rp will NOT be filled in for xx9 responses (where it is just
204 * commentary for a command where it would normally be meaningful).
206 * NB that the response will NOT be converted to the local encoding
207 * nor will quotes be stripped. See dequote().
209 * Put @ref disorder__body in the argument list followed by a char **
210 * and int giving the body to follow the command. If the int is @c -1
211 * then the list is assumed to be NULL-terminated. This may be used
214 * Put @ref disorder__list in the argument list followed by a char **
215 * and int giving a list of arguments to include. If the int is @c -1
216 * then the list is assumed to be NULL-terminated. This may be used
217 * any number of times.
219 * Put @ref disorder__integer in the argument list followed by a long to
220 * send its value in decimal. This may be used any number of times.
222 * Put @ref disorder__time in the argument list followed by a time_t
223 * to send its value in decimal. This may be used any number of
226 * Usually you would call this via one of the following interfaces:
227 * - disorder_simple()
229 static int disorder_simple_v(disorder_client
*c
,
241 c
->last
= "not connected";
242 disorder_error(0, "not connected to server");
247 dynstr_append_string(&d
, cmd
);
248 while((arg
= va_arg(ap
, const char *))) {
249 if(arg
== disorder__body
) {
250 body
= va_arg(ap
, char **);
251 nbody
= va_arg(ap
, int);
253 } else if(arg
== disorder__list
) {
254 char **list
= va_arg(ap
, char **);
255 int nlist
= va_arg(ap
, int);
258 for(nlist
= 0; list
[nlist
]; ++nlist
)
261 for(n
= 0; n
< nlist
; ++n
) {
262 dynstr_append(&d
, ' ');
263 dynstr_append_string(&d
, quoteutf8(arg
));
265 } else if(arg
== disorder__integer
) {
266 long n
= va_arg(ap
, long);
268 byte_snprintf(buffer
, sizeof buffer
, "%ld", n
);
269 dynstr_append(&d
, ' ');
270 dynstr_append_string(&d
, buffer
);
271 } else if(arg
== disorder__time
) {
272 time_t n
= va_arg(ap
, time_t);
274 byte_snprintf(buffer
, sizeof buffer
, "%lld", (long long)n
);
275 dynstr_append(&d
, ' ');
276 dynstr_append_string(&d
, buffer
);
278 dynstr_append(&d
, ' ');
279 dynstr_append_string(&d
, quoteutf8(arg
));
282 dynstr_append(&d
, '\n');
283 dynstr_terminate(&d
);
284 D(("command: %s", d
.vec
));
285 if(sink_write(c
->output
, d
.vec
, d
.nvec
) < 0)
291 for(nbody
= 0; body
[nbody
]; ++nbody
)
293 for(n
= 0; n
< nbody
; ++n
) {
294 if(body
[n
][0] == '.')
295 if(sink_writec(c
->output
, '.') < 0)
297 if(sink_writes(c
->output
, body
[n
]) < 0)
299 if(sink_writec(c
->output
, '\n') < 0)
302 if(sink_writes(c
->output
, ".\n") < 0)
305 if(sink_flush(c
->output
))
308 return check_response(c
, rp
);
310 byte_xasprintf((char **)&c
->last
, "write error: %s",
311 format_error(c
->output
->eclass
, sink_err(c
->output
), errbuf
, sizeof errbuf
));
312 disorder_error(0, "%s: %s", c
->ident
, c
->last
);
316 /** @brief Issue a command and parse a simple response
318 * @param rp Where to store result, or NULL (UTF-8)
320 * @return 0 on success, non-0 on error
322 * The remaining arguments are command arguments, terminated by (char
323 * *)0. They should be in UTF-8.
325 * 5xx responses count as errors.
327 * @p rp will NOT be filled in for xx9 responses (where it is just
328 * commentary for a command where it would normally be meaningful).
330 * NB that the response will NOT be converted to the local encoding
331 * nor will quotes be stripped. See dequote().
333 static int disorder_simple(disorder_client
*c
,
335 const char *cmd
, ...) {
340 ret
= disorder_simple_v(c
, rp
, cmd
, ap
);
345 /** @brief Issue a command and split the response
347 * @param vecp Where to store results
348 * @param nvecp Where to store count of results
349 * @param expected Expected count (or -1 to not check)
351 * @return 0 on success, non-0 on error
353 * The remaining arguments are command arguments, terminated by (char
354 * *)0. They should be in UTF-8.
356 * 5xx responses count as errors.
358 * @p rp will NOT be filled in for xx9 responses (where it is just
359 * commentary for a command where it would normally be meaningful).
361 * NB that the response will NOT be converted to the local encoding
362 * nor will quotes be stripped. See dequote().
364 static int disorder_simple_split(disorder_client
*c
,
368 const char *cmd
, ...) {
376 ret
= disorder_simple_v(c
, &r
, cmd
, ap
);
379 vec
= split(r
, &nvec
, SPLIT_QUOTES
, 0, 0);
381 if(expected
< 0 || nvec
== expected
) {
385 disorder_error(0, "malformed reply to %s", cmd
);
386 c
->last
= "malformed reply";
388 free_strings(nvec
, vec
);
398 /** @brief Dequote a result string
399 * @param rc 0 on success, non-0 on error
400 * @param rp Where result string is stored (UTF-8)
403 * This is used as a wrapper around disorder_simple() to dequote
406 static int dequote(int rc
, char **rp
) {
410 if((rr
= split(*rp
, 0, SPLIT_QUOTES
, 0, 0)) && *rr
) {
416 disorder_error(0, "invalid reply: %s", *rp
);
421 /** @brief Generic connection routine
422 * @param conf Configuration to follow
424 * @param username Username to log in with or NULL
425 * @param password Password to log in with or NULL
426 * @param cookie Cookie to log in with or NULL
427 * @return 0 on success, non-0 on error
429 * @p cookie is tried first if not NULL. If it is NULL then @p
430 * username must not be. If @p username is not NULL then nor may @p
433 int disorder_connect_generic(struct config
*conf
,
435 const char *username
,
436 const char *password
,
437 const char *cookie
) {
438 SOCKET sd
= INVALID_SOCKET
;
440 unsigned char *nonce
= NULL
;
443 char *r
= NULL
, **rvec
= NULL
;
444 const char *protocol
, *algorithm
, *challenge
;
445 struct sockaddr
*sa
= NULL
;
449 if((salen
= disorder_find_server(conf
,
450 (c
->trypriv ?
0 : DISORDER_FS_NOTPRIV
),
451 &sa
, &c
->ident
)) == (socklen_t
)-1)
455 if((sd
= socket(sa
->sa_family
, SOCK_STREAM
, 0)) < 0) {
456 byte_xasprintf((char **)&c
->last
, "socket: %s",
457 format_error(ec_socket
, socket_error(), errbuf
, sizeof errbuf
));
458 disorder_error(0, "%s", c
->last
);
461 c
->family
= sa
->sa_family
;
462 if(connect(sd
, sa
, salen
) < 0) {
463 byte_xasprintf((char **)&c
->last
, "connect: %s",
464 format_error(ec_socket
, socket_error(), errbuf
, sizeof errbuf
));
465 disorder_error(0, "%s", c
->last
);
468 socketio_init(&c
->sio
, sd
);
471 c
->output
= sink_socketio(&c
->sio
);
472 c
->input
= source_socketio(&c
->sio
);
473 if((rc
= disorder_simple(c
, &r
, 0, (const char *)0)))
475 if(!(rvec
= split(r
, &nrvec
, SPLIT_QUOTES
, 0, 0)))
478 c
->last
= "cannot parse server greeting";
479 disorder_error(0, "cannot parse server greeting %s", r
);
483 if(strcmp(protocol
, "2")) {
484 c
->last
= "unknown protocol version";
485 disorder_error(0, "unknown protocol version: %s", protocol
);
490 if(!(nonce
= unhex(challenge
, &nl
)))
493 if(!dequote(disorder_simple(c
, &c
->user
, "cookie", cookie
, (char *)0),
495 return 0; /* success */
497 c
->last
= "cookie failed and no username";
498 disorder_error(0, "cookie did not work and no username available");
502 if(!(res
= authhash(nonce
, nl
, password
, algorithm
))) {
503 c
->last
= "error computing authorization hash";
506 if((rc
= disorder_simple(c
, 0, "user", username
, res
, (char *)0)))
508 c
->user
= xstrdup(username
);
510 free_strings(nrvec
, rvec
);
522 if(c
->open
) { socketio_close(&c
->sio
); c
->open
= 0; }
523 if(sd
!= INVALID_SOCKET
) closesocket(sd
);
527 /** @brief Connect a client with a specified username and password
529 * @param username Username to log in with
530 * @param password Password to log in with
531 * @return 0 on success, non-0 on error
533 int disorder_connect_user(disorder_client
*c
,
534 const char *username
,
535 const char *password
) {
536 return disorder_connect_generic(config
,
543 /** @brief Connect a client
545 * @return 0 on success, non-0 on error
547 * The connection will use the username and password found in @ref
548 * config, or directly from the database if no password is found and
549 * the database is readable (usually only for root).
551 int disorder_connect(disorder_client
*c
) {
552 const char *username
, *password
;
554 if(!(username
= config
->username
)) {
555 c
->last
= "no username";
556 disorder_error(0, "no username configured");
559 password
= config
->password
;
560 /* If we're connecting as 'root' guess that we're the system root
561 * user (or the jukebox user), both of which can use the privileged
562 * socket. They can also furtle with the db directly: that is why
563 * privileged socket does not represent a privilege escalation. */
565 && !strcmp(username
, "root"))
566 password
= "anything will do for root";
569 c
->last
= "no password";
570 disorder_error(0, "no password configured for user '%s'", username
);
573 return disorder_connect_generic(config
,
580 /** @brief Connect a client
582 * @param cookie Cookie to log in with, or NULL
583 * @return 0 on success, non-0 on error
585 * If @p cookie is NULL or does not work then we attempt to log in as
586 * guest instead (so when the cookie expires only an extra round trip
587 * is needed rather than a complete new login).
589 int disorder_connect_cookie(disorder_client
*c
,
590 const char *cookie
) {
591 return disorder_connect_generic(config
,
598 /** @brief Close a client
600 * @return 0 on succcess, non-0 on errior
602 * The client is still closed even on error. It might well be
603 * appropriate to ignore the return value.
605 int disorder_close(disorder_client
*c
) {
609 socketio_close(&c
->sio
);
621 static void client_error(const char *msg
,
622 void attribute((unused
)) *u
) {
623 disorder_error(0, "error parsing reply: %s", msg
);
626 /** @brief Get a single queue entry
629 * @param qp Where to store track information
630 * @return 0 on success, non-0 on error
632 static int onequeue(disorder_client
*c
, const char *cmd
,
633 struct queue_entry
**qp
) {
635 struct queue_entry
*q
;
638 if((rc
= disorder_simple(c
, &r
, cmd
, (char *)0)))
641 q
= xmalloc(sizeof *q
);
642 if(queue_unmarshall(q
, r
, client_error
, 0))
650 /** @brief Fetch the queue, recent list, etc */
651 static int readqueue(disorder_client
*c
,
652 struct queue_entry
**qp
) {
653 struct queue_entry
*qh
, **qt
= &qh
, *q
;
657 while(inputlines(c
->ident
, c
->input
, &l
, '\n') >= 0) {
658 if(!strcmp(l
, ".")) {
664 q
= xmalloc(sizeof *q
);
665 if(!queue_unmarshall(q
, l
, client_error
, 0)) {
671 if(source_err(c
->input
)) {
672 byte_xasprintf((char **)&c
->last
, "input error: %s",
673 format_error(c
->input
->eclass
, source_err(c
->input
), errbuf
, sizeof errbuf
));
675 c
->last
= "input error: unexpected EOF";
677 disorder_error(0, "%s: %s", c
->ident
, c
->last
);
681 /** @brief Read a dot-stuffed list
683 * @param vecp Where to store list (UTF-8)
684 * @param nvecp Where to store number of items, or NULL
685 * @return 0 on success, non-0 on error
687 * The list will have a final NULL not counted in @p nvecp.
689 static int readlist(disorder_client
*c
, char ***vecp
, int *nvecp
) {
695 while(inputlines(c
->ident
, c
->input
, &l
, '\n') >= 0) {
696 if(!strcmp(l
, ".")) {
697 vector_terminate(&v
);
704 vector_append(&v
, xstrdup(l
+ (*l
== '.')));
707 if(source_err(c
->input
)) {
708 byte_xasprintf((char **)&c
->last
, "input error: %s",
709 format_error(c
->input
->eclass
, source_err(c
->input
), errbuf
, sizeof errbuf
));
711 c
->last
= "input error: unexpxected EOF";
713 disorder_error(0, "%s: %s", c
->ident
, c
->last
);
717 /** @brief Return the user we logged in with
719 * @return User name (owned by @p c, don't modify)
721 char *disorder_user(disorder_client
*c
) {
725 static void pairlist_error_handler(const char *msg
,
726 void attribute((unused
)) *u
) {
727 disorder_error(0, "error handling key-value pair reply: %s", msg
);
730 /** @brief Get a list of key-value pairs
732 * @param kp Where to store linked list of preferences
734 * @param ... Arguments
735 * @return 0 on success, non-0 on error
737 static int pairlist(disorder_client
*c
, struct kvp
**kp
, const char *cmd
, ...) {
739 int nvec
, npvec
, n
, rc
;
744 rc
= disorder_simple_v(c
, 0, cmd
, ap
);
748 if((rc
= readlist(c
, &vec
, &nvec
)))
750 for(n
= 0; n
< nvec
; ++n
) {
751 if(!(pvec
= split(vec
[n
], &npvec
, SPLIT_QUOTES
, pairlist_error_handler
, 0)))
754 pairlist_error_handler("malformed response", 0);
757 *kp
= k
= xmalloc(sizeof *k
);
763 free_strings(nvec
, vec
);
769 # define boolean bodge_boolean
772 /** @brief Parse a boolean response
773 * @param cmd Command for use in error messsage
774 * @param value Result from server
775 * @param flagp Where to store result
776 * @return 0 on success, non-0 on error
778 static int boolean(const char *cmd
, const char *value
,
780 if(!strcmp(value
, "yes")) *flagp
= 1;
781 else if(!strcmp(value
, "no")) *flagp
= 0;
783 disorder_error(0, "malformed response to '%s'", cmd
);
789 /** @brief Log to a sink
791 * @param s Sink to write log lines to
792 * @return 0 on success, non-0 on error
794 int disorder_log(disorder_client
*c
, struct sink
*s
) {
799 if((rc
= disorder_simple(c
, 0, "log", (char *)0)))
801 while(inputlines(c
->ident
, c
->input
, &l
, '\n') >= 0 && strcmp(l
, "."))
802 if(sink_printf(s
, "%s\n", l
) < 0) return -1;
803 if(source_err(c
->input
)) {
804 byte_xasprintf((char **)&c
->last
, "input error: %s",
805 format_error(c
->input
->eclass
, source_err(c
->input
), errbuf
, sizeof errbuf
));
807 } else if(source_eof(c
->input
)) {
808 byte_xasprintf((char **)&c
->last
, "input error: unexpected EOF");
815 #include "client-stubs.c"