protogen: The bulk of the eclient code generation.
[disorder] / lib / client.c
1 /*
2 * This file is part of DisOrder.
3 * Copyright (C) 2004-2010 Richard Kettlewell
4 *
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.
9 *
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.
14 *
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/>.
17 */
18 /** @file lib/client.c
19 * @brief Simple C client
20 *
21 * See @ref lib/eclient.c for an asynchronous-capable client
22 * implementation.
23 */
24
25 #include "common.h"
26
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <sys/un.h>
31 #include <unistd.h>
32 #include <errno.h>
33 #include <netdb.h>
34 #include <pcre.h>
35
36 #include "log.h"
37 #include "mem.h"
38 #include "queue.h"
39 #include "client.h"
40 #include "charset.h"
41 #include "hex.h"
42 #include "split.h"
43 #include "vector.h"
44 #include "inputline.h"
45 #include "kvp.h"
46 #include "syscalls.h"
47 #include "printf.h"
48 #include "sink.h"
49 #include "addr.h"
50 #include "authhash.h"
51 #include "client-common.h"
52 #include "rights.h"
53 #include "trackdb.h"
54 #include "kvp.h"
55
56 /** @brief Client handle contents */
57 struct disorder_client {
58 /** @brief Stream to read from */
59 FILE *fpin;
60 /** @brief Stream to write to */
61 FILE *fpout;
62 /** @brief Peer description */
63 char *ident;
64 /** @brief Username */
65 char *user;
66 /** @brief Report errors to @c stderr */
67 int verbose;
68 /** @brief Last error string */
69 const char *last;
70 };
71
72 /** @brief Create a new client
73 * @param verbose If nonzero, write extra junk to stderr
74 * @return Pointer to new client
75 *
76 * You must call disorder_connect(), disorder_connect_user() or
77 * disorder_connect_cookie() to connect it. Use disorder_close() to
78 * dispose of the client when finished with it.
79 */
80 disorder_client *disorder_new(int verbose) {
81 disorder_client *c = xmalloc(sizeof (struct disorder_client));
82
83 c->verbose = verbose;
84 return c;
85 }
86
87 /** @brief Read a response line
88 * @param c Client
89 * @param rp Where to store response, or NULL (UTF-8)
90 * @return Response code 0-999 or -1 on error
91 */
92 static int response(disorder_client *c, char **rp) {
93 char *r;
94
95 if(inputline(c->ident, c->fpin, &r, '\n')) {
96 byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
97 return -1;
98 }
99 D(("response: %s", r));
100 if(rp)
101 *rp = r;
102 if(r[0] >= '0' && r[0] <= '9'
103 && r[1] >= '0' && r[1] <= '9'
104 && r[2] >= '0' && r[2] <= '9'
105 && r[3] == ' ') {
106 c->last = r + 4;
107 return (r[0] * 10 + r[1]) * 10 + r[2] - 111 * '0';
108 } else {
109 c->last = "invalid reply format";
110 disorder_error(0, "invalid reply format from %s", c->ident);
111 return -1;
112 }
113 }
114
115 /** @brief Return last response string
116 * @param c Client
117 * @return Last response string (UTF-8, English) or NULL
118 */
119 const char *disorder_last(disorder_client *c) {
120 return c->last;
121 }
122
123 /** @brief Read and partially parse a response
124 * @param c Client
125 * @param rp Where to store response text (or NULL) (UTF-8)
126 * @return 0 on success, non-0 on error
127 *
128 * 5xx responses count as errors.
129 *
130 * @p rp will NOT be filled in for xx9 responses (where it is just
131 * commentary for a command where it would normally be meaningful).
132 *
133 * NB that the response will NOT be converted to the local encoding.
134 */
135 static int check_response(disorder_client *c, char **rp) {
136 int rc;
137 char *r;
138
139 if((rc = response(c, &r)) == -1)
140 return -1;
141 else if(rc / 100 == 2) {
142 if(rp)
143 *rp = (rc % 10 == 9) ? 0 : xstrdup(r + 4);
144 xfree(r);
145 return 0;
146 } else {
147 if(c->verbose)
148 disorder_error(0, "from %s: %s", c->ident, utf82mb(r));
149 xfree(r);
150 return rc;
151 }
152 }
153
154 /** @brief Issue a command and parse a simple response
155 * @param c Client
156 * @param rp Where to store result, or NULL
157 * @param cmd Command
158 * @param ap Arguments (UTF-8), terminated by (char *)0
159 * @return 0 on success, non-0 on error
160 *
161 * 5xx responses count as errors.
162 *
163 * @p rp will NOT be filled in for xx9 responses (where it is just
164 * commentary for a command where it would normally be meaningful).
165 *
166 * NB that the response will NOT be converted to the local encoding
167 * nor will quotes be stripped. See dequote().
168 *
169 * Put @ref disorder__body in the argument list followed by a char **
170 * and int giving the body to follow the command. If the int is @c -1
171 * then the list is assumed to be NULL-terminated. This may be used
172 * only once.
173 *
174 * Put @ref disorder__list in the argument list followed by a char **
175 * and int giving a list of arguments to include. If the int is @c -1
176 * then the list is assumed to be NULL-terminated. This may be used
177 * any number of times.
178 *
179 * Usually you would call this via one of the following interfaces:
180 * - disorder_simple()
181 */
182 static int disorder_simple_v(disorder_client *c,
183 char **rp,
184 const char *cmd,
185 va_list ap) {
186 const char *arg;
187 struct dynstr d;
188 char **body = NULL;
189 int nbody = 0;
190 int has_body = 0;
191
192 if(!c->fpout) {
193 c->last = "not connected";
194 disorder_error(0, "not connected to server");
195 return -1;
196 }
197 if(cmd) {
198 dynstr_init(&d);
199 dynstr_append_string(&d, cmd);
200 while((arg = va_arg(ap, const char *))) {
201 if(arg == disorder__body) {
202 body = va_arg(ap, char **);
203 nbody = va_arg(ap, int);
204 has_body = 1;
205 } else if(arg == disorder__list) {
206 char **list = va_arg(ap, char **);
207 int nlist = va_arg(ap, int);
208 if(nlist < 0) {
209 for(nlist = 0; list[nlist]; ++nlist)
210 ;
211 }
212 for(int n = 0; n < nlist; ++n) {
213 dynstr_append(&d, ' ');
214 dynstr_append_string(&d, quoteutf8(arg));
215 }
216 } else {
217 dynstr_append(&d, ' ');
218 dynstr_append_string(&d, quoteutf8(arg));
219 }
220 }
221 dynstr_append(&d, '\n');
222 dynstr_terminate(&d);
223 D(("command: %s", d.vec));
224 if(fputs(d.vec, c->fpout) < 0)
225 goto write_error;
226 xfree(d.vec);
227 if(has_body) {
228 if(nbody < 0)
229 for(nbody = 0; body[nbody]; ++nbody)
230 ;
231 for(int n = 0; n < nbody; ++n) {
232 if(body[n][0] == '.')
233 if(fputc('.', c->fpout) < 0)
234 goto write_error;
235 if(fputs(body[n], c->fpout) < 0)
236 goto write_error;
237 if(fputc('\n', c->fpout) < 0)
238 goto write_error;
239 }
240 if(fputs(".\n", c->fpout) < 0)
241 goto write_error;
242 }
243 if(fflush(c->fpout))
244 goto write_error;
245 }
246 return check_response(c, rp);
247 write_error:
248 byte_xasprintf((char **)&c->last, "write error: %s", strerror(errno));
249 disorder_error(errno, "error writing to %s", c->ident);
250 return -1;
251 }
252
253 /** @brief Issue a command and parse a simple response
254 * @param c Client
255 * @param rp Where to store result, or NULL (UTF-8)
256 * @param cmd Command
257 * @return 0 on success, non-0 on error
258 *
259 * The remaining arguments are command arguments, terminated by (char
260 * *)0. They should be in UTF-8.
261 *
262 * 5xx responses count as errors.
263 *
264 * @p rp will NOT be filled in for xx9 responses (where it is just
265 * commentary for a command where it would normally be meaningful).
266 *
267 * NB that the response will NOT be converted to the local encoding
268 * nor will quotes be stripped. See dequote().
269 */
270 static int disorder_simple(disorder_client *c,
271 char **rp,
272 const char *cmd, ...) {
273 va_list ap;
274 int ret;
275
276 va_start(ap, cmd);
277 ret = disorder_simple_v(c, rp, cmd, ap);
278 va_end(ap);
279 return ret;
280 }
281
282 /** @brief Issue a command and split the response
283 * @param c Client
284 * @param vecp Where to store results
285 * @param nvecp Where to store count of results
286 * @param expected Expected count (or -1 to not check)
287 * @param cmd Command
288 * @return 0 on success, non-0 on error
289 *
290 * The remaining arguments are command arguments, terminated by (char
291 * *)0. They should be in UTF-8.
292 *
293 * 5xx responses count as errors.
294 *
295 * @p rp will NOT be filled in for xx9 responses (where it is just
296 * commentary for a command where it would normally be meaningful).
297 *
298 * NB that the response will NOT be converted to the local encoding
299 * nor will quotes be stripped. See dequote().
300 */
301 static int disorder_simple_split(disorder_client *c,
302 char ***vecp,
303 int *nvecp,
304 int expected,
305 const char *cmd, ...) {
306 va_list ap;
307 int ret;
308 char *r;
309 char **vec;
310 int nvec;
311
312 va_start(ap, cmd);
313 ret = disorder_simple_v(c, &r, cmd, ap);
314 va_end(ap);
315 if(!ret) {
316 vec = split(r, &nvec, SPLIT_QUOTES, 0, 0);
317 xfree(r);
318 if(expected < 0 || nvec == expected) {
319 *vecp = vec;
320 *nvecp = nvec;
321 } else {
322 disorder_error(0, "malformed reply to %s", cmd);
323 c->last = "malformed reply";
324 ret = -1;
325 free_strings(nvec, vec);
326 }
327 }
328 if(ret) {
329 *vecp = NULL;
330 *nvecp = 0;
331 }
332 return ret;
333 }
334
335 /** @brief Dequote a result string
336 * @param rc 0 on success, non-0 on error
337 * @param rp Where result string is stored (UTF-8)
338 * @return @p rc
339 *
340 * This is used as a wrapper around disorder_simple() to dequote
341 * results in place.
342 */
343 static int dequote(int rc, char **rp) {
344 char **rr;
345
346 if(!rc) {
347 if((rr = split(*rp, 0, SPLIT_QUOTES, 0, 0)) && *rr) {
348 xfree(*rp);
349 *rp = *rr;
350 xfree(rr);
351 return 0;
352 }
353 disorder_error(0, "invalid reply: %s", *rp);
354 }
355 return rc;
356 }
357
358 /** @brief Generic connection routine
359 * @param conf Configuration to follow
360 * @param c Client
361 * @param username Username to log in with or NULL
362 * @param password Password to log in with or NULL
363 * @param cookie Cookie to log in with or NULL
364 * @return 0 on success, non-0 on error
365 *
366 * @p cookie is tried first if not NULL. If it is NULL then @p
367 * username must not be. If @p username is not NULL then nor may @p
368 * password be.
369 */
370 int disorder_connect_generic(struct config *conf,
371 disorder_client *c,
372 const char *username,
373 const char *password,
374 const char *cookie) {
375 int fd = -1, fd2 = -1, nrvec = 0, rc;
376 unsigned char *nonce = NULL;
377 size_t nl;
378 char *res = NULL;
379 char *r = NULL, **rvec = NULL;
380 const char *protocol, *algorithm, *challenge;
381 struct sockaddr *sa = NULL;
382 socklen_t salen;
383
384 if((salen = find_server(conf, &sa, &c->ident)) == (socklen_t)-1)
385 return -1;
386 c->fpin = c->fpout = 0;
387 if((fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0) {
388 byte_xasprintf((char **)&c->last, "socket: %s", strerror(errno));
389 disorder_error(errno, "error calling socket");
390 return -1;
391 }
392 if(connect(fd, sa, salen) < 0) {
393 byte_xasprintf((char **)&c->last, "connect: %s", strerror(errno));
394 disorder_error(errno, "error calling connect");
395 goto error;
396 }
397 if((fd2 = dup(fd)) < 0) {
398 byte_xasprintf((char **)&c->last, "dup: %s", strerror(errno));
399 disorder_error(errno, "error calling dup");
400 goto error;
401 }
402 if(!(c->fpin = fdopen(fd, "rb"))) {
403 byte_xasprintf((char **)&c->last, "fdopen: %s", strerror(errno));
404 disorder_error(errno, "error calling fdopen");
405 goto error;
406 }
407 fd = -1;
408 if(!(c->fpout = fdopen(fd2, "wb"))) {
409 byte_xasprintf((char **)&c->last, "fdopen: %s", strerror(errno));
410 disorder_error(errno, "error calling fdopen");
411 goto error;
412 }
413 fd2 = -1;
414 if((rc = disorder_simple(c, &r, 0, (const char *)0)))
415 goto error_rc;
416 if(!(rvec = split(r, &nrvec, SPLIT_QUOTES, 0, 0)))
417 goto error;
418 if(nrvec != 3) {
419 c->last = "cannot parse server greeting";
420 disorder_error(0, "cannot parse server greeting %s", r);
421 goto error;
422 }
423 protocol = rvec[0];
424 if(strcmp(protocol, "2")) {
425 c->last = "unknown protocol version";
426 disorder_error(0, "unknown protocol version: %s", protocol);
427 goto error;
428 }
429 algorithm = rvec[1];
430 challenge = rvec[2];
431 if(!(nonce = unhex(challenge, &nl)))
432 goto error;
433 if(cookie) {
434 if(!dequote(disorder_simple(c, &c->user, "cookie", cookie, (char *)0),
435 &c->user))
436 return 0; /* success */
437 if(!username) {
438 c->last = "cookie failed and no username";
439 disorder_error(0, "cookie did not work and no username available");
440 goto error;
441 }
442 }
443 if(!(res = authhash(nonce, nl, password, algorithm))) {
444 c->last = "error computing authorization hash";
445 goto error;
446 }
447 if((rc = disorder_simple(c, 0, "user", username, res, (char *)0)))
448 goto error_rc;
449 c->user = xstrdup(username);
450 xfree(res);
451 free_strings(nrvec, rvec);
452 xfree(nonce);
453 xfree(sa);
454 xfree(r);
455 return 0;
456 error:
457 rc = -1;
458 error_rc:
459 if(c->fpin) {
460 fclose(c->fpin);
461 c->fpin = 0;
462 }
463 if(c->fpout) {
464 fclose(c->fpout);
465 c->fpout = 0;
466 }
467 if(fd2 != -1) close(fd2);
468 if(fd != -1) close(fd);
469 return rc;
470 }
471
472 /** @brief Connect a client with a specified username and password
473 * @param c Client
474 * @param username Username to log in with
475 * @param password Password to log in with
476 * @return 0 on success, non-0 on error
477 */
478 int disorder_connect_user(disorder_client *c,
479 const char *username,
480 const char *password) {
481 return disorder_connect_generic(config,
482 c,
483 username,
484 password,
485 0);
486 }
487
488 /** @brief Connect a client
489 * @param c Client
490 * @return 0 on success, non-0 on error
491 *
492 * The connection will use the username and password found in @ref
493 * config, or directly from the database if no password is found and
494 * the database is readable (usually only for root).
495 */
496 int disorder_connect(disorder_client *c) {
497 const char *username, *password;
498
499 if(!(username = config->username)) {
500 c->last = "no username";
501 disorder_error(0, "no username configured");
502 return -1;
503 }
504 password = config->password;
505 /* Maybe we can read the database */
506 if(!password && trackdb_readable()) {
507 trackdb_init(TRACKDB_NO_RECOVER|TRACKDB_NO_UPGRADE);
508 trackdb_open(TRACKDB_READ_ONLY);
509 password = trackdb_get_password(username);
510 trackdb_close();
511 }
512 if(!password) {
513 /* Oh well */
514 c->last = "no password";
515 disorder_error(0, "no password configured for user '%s'", username);
516 return -1;
517 }
518 return disorder_connect_generic(config,
519 c,
520 username,
521 password,
522 0);
523 }
524
525 /** @brief Connect a client
526 * @param c Client
527 * @param cookie Cookie to log in with, or NULL
528 * @return 0 on success, non-0 on error
529 *
530 * If @p cookie is NULL or does not work then we attempt to log in as
531 * guest instead (so when the cookie expires only an extra round trip
532 * is needed rathre than a complete new login).
533 */
534 int disorder_connect_cookie(disorder_client *c,
535 const char *cookie) {
536 return disorder_connect_generic(config,
537 c,
538 "guest",
539 "",
540 cookie);
541 }
542
543 /** @brief Close a client
544 * @param c Client
545 * @return 0 on succcess, non-0 on errior
546 *
547 * The client is still closed even on error. It might well be
548 * appropriate to ignore the return value.
549 */
550 int disorder_close(disorder_client *c) {
551 int ret = 0;
552
553 if(c->fpin) {
554 if(fclose(c->fpin) < 0) {
555 byte_xasprintf((char **)&c->last, "fclose: %s", strerror(errno));
556 disorder_error(errno, "error calling fclose");
557 ret = -1;
558 }
559 c->fpin = 0;
560 }
561 if(c->fpout) {
562 if(fclose(c->fpout) < 0) {
563 byte_xasprintf((char **)&c->last, "fclose: %s", strerror(errno));
564 disorder_error(errno, "error calling fclose");
565 ret = -1;
566 }
567 c->fpout = 0;
568 }
569 xfree(c->ident);
570 c->ident = 0;
571 xfree(c->user);
572 c->user = 0;
573 return ret;
574 }
575
576 static void client_error(const char *msg,
577 void attribute((unused)) *u) {
578 disorder_error(0, "error parsing reply: %s", msg);
579 }
580
581 /** @brief Get a single queue entry
582 * @param c Client
583 * @param cmd Command
584 * @param qp Where to store track information
585 * @return 0 on success, non-0 on error
586 */
587 static int onequeue(disorder_client *c, const char *cmd,
588 struct queue_entry **qp) {
589 char *r;
590 struct queue_entry *q;
591 int rc;
592
593 if((rc = disorder_simple(c, &r, cmd, (char *)0)))
594 return rc;
595 if(r) {
596 q = xmalloc(sizeof *q);
597 if(queue_unmarshall(q, r, client_error, 0))
598 return -1;
599 *qp = q;
600 } else
601 *qp = 0;
602 return 0;
603 }
604
605 /** @brief Fetch the queue, recent list, etc */
606 static int readqueue(disorder_client *c,
607 struct queue_entry **qp) {
608 struct queue_entry *qh, **qt = &qh, *q;
609 char *l;
610
611 while(inputline(c->ident, c->fpin, &l, '\n') >= 0) {
612 if(!strcmp(l, ".")) {
613 *qt = 0;
614 *qp = qh;
615 xfree(l);
616 return 0;
617 }
618 q = xmalloc(sizeof *q);
619 if(!queue_unmarshall(q, l, client_error, 0)) {
620 *qt = q;
621 qt = &q->next;
622 }
623 xfree(l);
624 }
625 if(ferror(c->fpin)) {
626 byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
627 disorder_error(errno, "error reading %s", c->ident);
628 } else {
629 c->last = "input error: unexpected EOF";
630 disorder_error(0, "error reading %s: unexpected EOF", c->ident);
631 }
632 return -1;
633 }
634
635 /** @brief Read a dot-stuffed list
636 * @param c Client
637 * @param vecp Where to store list (UTF-8)
638 * @param nvecp Where to store number of items, or NULL
639 * @return 0 on success, non-0 on error
640 *
641 * The list will have a final NULL not counted in @p nvecp.
642 */
643 static int readlist(disorder_client *c, char ***vecp, int *nvecp) {
644 char *l;
645 struct vector v;
646
647 vector_init(&v);
648 while(inputline(c->ident, c->fpin, &l, '\n') >= 0) {
649 if(!strcmp(l, ".")) {
650 vector_terminate(&v);
651 if(nvecp)
652 *nvecp = v.nvec;
653 *vecp = v.vec;
654 xfree(l);
655 return 0;
656 }
657 vector_append(&v, xstrdup(l + (*l == '.')));
658 xfree(l);
659 }
660 if(ferror(c->fpin)) {
661 byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
662 disorder_error(errno, "error reading %s", c->ident);
663 } else {
664 c->last = "input error: unexpxected EOF";
665 disorder_error(0, "error reading %s: unexpected EOF", c->ident);
666 }
667 return -1;
668 }
669
670 /** @brief Return the user we logged in with
671 * @param c Client
672 * @return User name (owned by @p c, don't modify)
673 */
674 char *disorder_user(disorder_client *c) {
675 return c->user;
676 }
677
678 static void pairlist_error_handler(const char *msg,
679 void attribute((unused)) *u) {
680 disorder_error(0, "error handling key-value pair reply: %s", msg);
681 }
682
683 /** @brief Get a list of key-value pairs
684 * @param c Client
685 * @param kp Where to store linked list of preferences
686 * @param cmd Command
687 * @param ... Arguments
688 * @return 0 on success, non-0 on error
689 */
690 static int pairlist(disorder_client *c, struct kvp **kp, const char *cmd, ...) {
691 char **vec, **pvec;
692 int nvec, npvec, n, rc;
693 struct kvp *k;
694 va_list ap;
695
696 va_start(ap, cmd);
697 rc = disorder_simple_v(c, 0, cmd, ap);
698 va_end(ap);
699 if(rc)
700 return rc;
701 if((rc = readlist(c, &vec, &nvec)))
702 return rc;
703 for(n = 0; n < nvec; ++n) {
704 if(!(pvec = split(vec[n], &npvec, SPLIT_QUOTES, pairlist_error_handler, 0)))
705 return -1;
706 if(npvec != 2) {
707 pairlist_error_handler("malformed response", 0);
708 return -1;
709 }
710 *kp = k = xmalloc(sizeof *k);
711 k->name = pvec[0];
712 k->value = pvec[1];
713 kp = &k->next;
714 xfree(pvec);
715 }
716 free_strings(nvec, vec);
717 *kp = 0;
718 return 0;
719 }
720
721 /** @brief Parse a boolean response
722 * @param cmd Command for use in error messsage
723 * @param value Result from server
724 * @param flagp Where to store result
725 * @return 0 on success, non-0 on error
726 */
727 static int boolean(const char *cmd, const char *value,
728 int *flagp) {
729 if(!strcmp(value, "yes")) *flagp = 1;
730 else if(!strcmp(value, "no")) *flagp = 0;
731 else {
732 disorder_error(0, "malformed response to '%s'", cmd);
733 return -1;
734 }
735 return 0;
736 }
737
738 /** @brief Log to a sink
739 * @param c Client
740 * @param s Sink to write log lines to
741 * @return 0 on success, non-0 on error
742 */
743 int disorder_log(disorder_client *c, struct sink *s) {
744 char *l;
745 int rc;
746
747 if((rc = disorder_simple(c, 0, "log", (char *)0)))
748 return rc;
749 while(inputline(c->ident, c->fpin, &l, '\n') >= 0 && strcmp(l, "."))
750 if(sink_printf(s, "%s\n", l) < 0) return -1;
751 if(ferror(c->fpin) || feof(c->fpin)) {
752 byte_xasprintf((char **)&c->last, "input error: %s",
753 ferror(c->fpin) ? strerror(errno) : "unexpxected EOF");
754 return -1;
755 }
756 return 0;
757 }
758
759 #include "client-stubs.c"
760
761 /*
762 Local Variables:
763 c-basic-offset:2
764 comment-column:40
765 End:
766 */