chiark / gitweb /
protogen: support schedule-add.
[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 Marker for a command body */
155 static const char disorder_body[1];
156
157 /** @brief Marker for a list of args */
158 static const char disorder_list[1];
159
160 /** @brief Issue a command and parse a simple response
161  * @param c Client
162  * @param rp Where to store result, or NULL
163  * @param cmd Command
164  * @param ap Arguments (UTF-8), terminated by (char *)0
165  * @return 0 on success, non-0 on error
166  *
167  * 5xx responses count as errors.
168  *
169  * @p rp will NOT be filled in for xx9 responses (where it is just
170  * commentary for a command where it would normally be meaningful).
171  *
172  * NB that the response will NOT be converted to the local encoding
173  * nor will quotes be stripped.  See dequote().
174  *
175  * Put @ref disorder_body in the argument list followed by a char **
176  * and int giving the body to follow the command.  If the int is @c -1
177  * then the list is assumed to be NULL-terminated.  This may be used
178  * only once.
179  *
180  * Put @ref disorder_list in the argument list followed by a char **
181  * and int giving a list of arguments to include.  If the int is @c -1
182  * then the list is assumed to be NULL-terminated.  This may be used
183  * any number of times.
184  *
185  * Usually you would call this via one of the following interfaces:
186  * - disorder_simple()
187  */
188 static int disorder_simple_v(disorder_client *c,
189                              char **rp,
190                              const char *cmd,
191                              va_list ap) {
192   const char *arg;
193   struct dynstr d;
194   char **body = NULL;
195   int nbody = 0;
196   int has_body = 0;
197
198   if(!c->fpout) {
199     c->last = "not connected";
200     disorder_error(0, "not connected to server");
201     return -1;
202   }
203   if(cmd) {
204     dynstr_init(&d);
205     dynstr_append_string(&d, cmd);
206     while((arg = va_arg(ap, const char *))) {
207       if(arg == disorder_body) {
208         body = va_arg(ap, char **);
209         nbody = va_arg(ap, int);
210         has_body = 1;
211       } else if(arg == disorder_list) {
212         char **list = va_arg(ap, char **);
213         int nlist = va_arg(ap, int);
214         if(nlist < 0) {
215           for(nlist = 0; list[nlist]; ++nlist)
216             ;
217         }
218         for(int n = 0; n < nlist; ++n) {
219           dynstr_append(&d, ' ');
220           dynstr_append_string(&d, quoteutf8(arg));
221         }
222       } else {
223         dynstr_append(&d, ' ');
224         dynstr_append_string(&d, quoteutf8(arg));
225       }
226     }
227     dynstr_append(&d, '\n');
228     dynstr_terminate(&d);
229     D(("command: %s", d.vec));
230     if(fputs(d.vec, c->fpout) < 0)
231       goto write_error;
232     xfree(d.vec);
233     if(has_body) {
234       if(nbody < 0)
235         for(nbody = 0; body[nbody]; ++nbody)
236           ;
237       for(int n = 0; n < nbody; ++n) {
238         if(body[n][0] == '.')
239           if(fputc('.', c->fpout) < 0)
240             goto write_error;
241         if(fputs(body[n], c->fpout) < 0)
242           goto write_error;
243         if(fputc('\n', c->fpout) < 0)
244           goto write_error;
245       }
246       if(fputs(".\n", c->fpout) < 0)
247         goto write_error;
248     }
249     if(fflush(c->fpout))
250       goto write_error;
251   }
252   return check_response(c, rp);
253 write_error:
254   byte_xasprintf((char **)&c->last, "write error: %s", strerror(errno));
255   disorder_error(errno, "error writing to %s", c->ident);
256   return -1;
257 }
258
259 /** @brief Issue a command and parse a simple response
260  * @param c Client
261  * @param rp Where to store result, or NULL (UTF-8)
262  * @param cmd Command
263  * @return 0 on success, non-0 on error
264  *
265  * The remaining arguments are command arguments, terminated by (char
266  * *)0.  They should be in UTF-8.
267  *
268  * 5xx responses count as errors.
269  *
270  * @p rp will NOT be filled in for xx9 responses (where it is just
271  * commentary for a command where it would normally be meaningful).
272  *
273  * NB that the response will NOT be converted to the local encoding
274  * nor will quotes be stripped.  See dequote().
275  */
276 static int disorder_simple(disorder_client *c,
277                            char **rp,
278                            const char *cmd, ...) {
279   va_list ap;
280   int ret;
281
282   va_start(ap, cmd);
283   ret = disorder_simple_v(c, rp, cmd, ap);
284   va_end(ap);
285   return ret;
286 }
287
288 /** @brief Dequote a result string
289  * @param rc 0 on success, non-0 on error
290  * @param rp Where result string is stored (UTF-8)
291  * @return @p rc
292  *
293  * This is used as a wrapper around disorder_simple() to dequote
294  * results in place.
295  */
296 static int dequote(int rc, char **rp) {
297   char **rr;
298
299   if(!rc) {
300     if((rr = split(*rp, 0, SPLIT_QUOTES, 0, 0)) && *rr) {
301       xfree(*rp);
302       *rp = *rr;
303       xfree(rr);
304       return 0;
305     }
306     disorder_error(0, "invalid reply: %s", *rp);
307   }
308   return rc;
309 }
310
311 /** @brief Generic connection routine
312  * @param conf Configuration to follow
313  * @param c Client
314  * @param username Username to log in with or NULL
315  * @param password Password to log in with or NULL
316  * @param cookie Cookie to log in with or NULL
317  * @return 0 on success, non-0 on error
318  *
319  * @p cookie is tried first if not NULL.  If it is NULL then @p
320  * username must not be.  If @p username is not NULL then nor may @p
321  * password be.
322  */
323 int disorder_connect_generic(struct config *conf,
324                              disorder_client *c,
325                              const char *username,
326                              const char *password,
327                              const char *cookie) {
328   int fd = -1, fd2 = -1, nrvec = 0, rc;
329   unsigned char *nonce = NULL;
330   size_t nl;
331   char *res = NULL;
332   char *r = NULL, **rvec = NULL;
333   const char *protocol, *algorithm, *challenge;
334   struct sockaddr *sa = NULL;
335   socklen_t salen;
336
337   if((salen = find_server(conf, &sa, &c->ident)) == (socklen_t)-1)
338     return -1;
339   c->fpin = c->fpout = 0;
340   if((fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0) {
341     byte_xasprintf((char **)&c->last, "socket: %s", strerror(errno));
342     disorder_error(errno, "error calling socket");
343     return -1;
344   }
345   if(connect(fd, sa, salen) < 0) {
346     byte_xasprintf((char **)&c->last, "connect: %s", strerror(errno));
347     disorder_error(errno, "error calling connect");
348     goto error;
349   }
350   if((fd2 = dup(fd)) < 0) {
351     byte_xasprintf((char **)&c->last, "dup: %s", strerror(errno));
352     disorder_error(errno, "error calling dup");
353     goto error;
354   }
355   if(!(c->fpin = fdopen(fd, "rb"))) {
356     byte_xasprintf((char **)&c->last, "fdopen: %s", strerror(errno));
357     disorder_error(errno, "error calling fdopen");
358     goto error;
359   }
360   fd = -1;
361   if(!(c->fpout = fdopen(fd2, "wb"))) {
362     byte_xasprintf((char **)&c->last, "fdopen: %s", strerror(errno));
363     disorder_error(errno, "error calling fdopen");
364     goto error;
365   }
366   fd2 = -1;
367   if((rc = disorder_simple(c, &r, 0, (const char *)0)))
368     goto error_rc;
369   if(!(rvec = split(r, &nrvec, SPLIT_QUOTES, 0, 0)))
370     goto error;
371   if(nrvec != 3) {
372     c->last = "cannot parse server greeting";
373     disorder_error(0, "cannot parse server greeting %s", r);
374     goto error;
375   }
376   protocol = rvec[0];
377   if(strcmp(protocol, "2")) {
378     c->last = "unknown protocol version";
379     disorder_error(0, "unknown protocol version: %s", protocol);
380     goto error;
381   }
382   algorithm = rvec[1];
383   challenge = rvec[2];
384   if(!(nonce = unhex(challenge, &nl)))
385     goto error;
386   if(cookie) {
387     if(!dequote(disorder_simple(c, &c->user, "cookie", cookie, (char *)0),
388                 &c->user))
389       return 0;                         /* success */
390     if(!username) {
391       c->last = "cookie failed and no username";
392       disorder_error(0, "cookie did not work and no username available");
393       goto error;
394     }
395   }
396   if(!(res = authhash(nonce, nl, password, algorithm))) {
397     c->last = "error computing authorization hash";
398     goto error;
399   }
400   if((rc = disorder_simple(c, 0, "user", username, res, (char *)0)))
401     goto error_rc;
402   c->user = xstrdup(username);
403   xfree(res);
404   free_strings(nrvec, rvec);
405   xfree(nonce);
406   xfree(sa);
407   xfree(r);
408   return 0;
409 error:
410   rc = -1;
411 error_rc:
412   if(c->fpin) {
413     fclose(c->fpin);
414     c->fpin = 0;
415   }
416   if(c->fpout) {
417     fclose(c->fpout);
418     c->fpout = 0;
419   }
420   if(fd2 != -1) close(fd2);
421   if(fd != -1) close(fd);
422   return rc;
423 }
424
425 /** @brief Connect a client with a specified username and password
426  * @param c Client
427  * @param username Username to log in with
428  * @param password Password to log in with
429  * @return 0 on success, non-0 on error
430  */
431 int disorder_connect_user(disorder_client *c,
432                           const char *username,
433                           const char *password) {
434   return disorder_connect_generic(config,
435                                   c,
436                                   username,
437                                   password,
438                                   0);
439 }
440
441 /** @brief Connect a client
442  * @param c Client
443  * @return 0 on success, non-0 on error
444  *
445  * The connection will use the username and password found in @ref
446  * config, or directly from the database if no password is found and
447  * the database is readable (usually only for root).
448  */
449 int disorder_connect(disorder_client *c) {
450   const char *username, *password;
451
452   if(!(username = config->username)) {
453     c->last = "no username";
454     disorder_error(0, "no username configured");
455     return -1;
456   }
457   password = config->password;
458   /* Maybe we can read the database */
459   if(!password && trackdb_readable()) {
460     trackdb_init(TRACKDB_NO_RECOVER|TRACKDB_NO_UPGRADE);
461     trackdb_open(TRACKDB_READ_ONLY);
462     password = trackdb_get_password(username);
463     trackdb_close();
464   }
465   if(!password) {
466     /* Oh well */
467     c->last = "no password";
468     disorder_error(0, "no password configured for user '%s'", username);
469     return -1;
470   }
471   return disorder_connect_generic(config,
472                                   c,
473                                   username,
474                                   password,
475                                   0);
476 }
477
478 /** @brief Connect a client
479  * @param c Client
480  * @param cookie Cookie to log in with, or NULL
481  * @return 0 on success, non-0 on error
482  *
483  * If @p cookie is NULL or does not work then we attempt to log in as
484  * guest instead (so when the cookie expires only an extra round trip
485  * is needed rathre than a complete new login).
486  */
487 int disorder_connect_cookie(disorder_client *c,
488                             const char *cookie) {
489   return disorder_connect_generic(config,
490                                   c,
491                                   "guest",
492                                   "",
493                                   cookie);
494 }
495
496 /** @brief Close a client
497  * @param c Client
498  * @return 0 on succcess, non-0 on errior
499  *
500  * The client is still closed even on error.  It might well be
501  * appropriate to ignore the return value.
502  */
503 int disorder_close(disorder_client *c) {
504   int ret = 0;
505
506   if(c->fpin) {
507     if(fclose(c->fpin) < 0) {
508       byte_xasprintf((char **)&c->last, "fclose: %s", strerror(errno));
509       disorder_error(errno, "error calling fclose");
510       ret = -1;
511     }
512     c->fpin = 0;
513   }
514   if(c->fpout) {
515     if(fclose(c->fpout) < 0) {
516       byte_xasprintf((char **)&c->last, "fclose: %s", strerror(errno));
517       disorder_error(errno, "error calling fclose");
518       ret = -1;
519     }
520     c->fpout = 0;
521   }
522   xfree(c->ident);
523   c->ident = 0;
524   xfree(c->user);
525   c->user = 0;
526   return ret;
527 }
528
529 static void client_error(const char *msg,
530                          void attribute((unused)) *u) {
531   disorder_error(0, "error parsing reply: %s", msg);
532 }
533
534 /** @brief Get a single queue entry
535  * @param c Client
536  * @param cmd Command
537  * @param qp Where to store track information
538  * @return 0 on success, non-0 on error
539  */
540 static int onequeue(disorder_client *c, const char *cmd,
541                     struct queue_entry **qp) {
542   char *r;
543   struct queue_entry *q;
544   int rc;
545
546   if((rc = disorder_simple(c, &r, cmd, (char *)0)))
547     return rc;
548   if(r) {
549     q = xmalloc(sizeof *q);
550     if(queue_unmarshall(q, r, client_error, 0))
551       return -1;
552     *qp = q;
553   } else
554     *qp = 0;
555   return 0;
556 }
557
558 /** @brief Fetch the queue, recent list, etc */
559 static int readqueue(disorder_client *c,
560                      struct queue_entry **qp) {
561   struct queue_entry *qh, **qt = &qh, *q;
562   char *l;
563
564   while(inputline(c->ident, c->fpin, &l, '\n') >= 0) {
565     if(!strcmp(l, ".")) {
566       *qt = 0;
567       *qp = qh;
568       xfree(l);
569       return 0;
570     }
571     q = xmalloc(sizeof *q);
572     if(!queue_unmarshall(q, l, client_error, 0)) {
573       *qt = q;
574       qt = &q->next;
575     }
576     xfree(l);
577   }
578   if(ferror(c->fpin)) {
579     byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
580     disorder_error(errno, "error reading %s", c->ident);
581   } else {
582     c->last = "input error: unexpected EOF";
583     disorder_error(0, "error reading %s: unexpected EOF", c->ident);
584   }
585   return -1;
586 }
587
588 /** @brief Read a dot-stuffed list
589  * @param c Client
590  * @param vecp Where to store list (UTF-8)
591  * @param nvecp Where to store number of items, or NULL
592  * @return 0 on success, non-0 on error
593  *
594  * The list will have a final NULL not counted in @p nvecp.
595  */
596 static int readlist(disorder_client *c, char ***vecp, int *nvecp) {
597   char *l;
598   struct vector v;
599
600   vector_init(&v);
601   while(inputline(c->ident, c->fpin, &l, '\n') >= 0) {
602     if(!strcmp(l, ".")) {
603       vector_terminate(&v);
604       if(nvecp)
605         *nvecp = v.nvec;
606       *vecp = v.vec;
607       xfree(l);
608       return 0;
609     }
610     vector_append(&v, xstrdup(l + (*l == '.')));
611     xfree(l);
612   }
613   if(ferror(c->fpin)) {
614     byte_xasprintf((char **)&c->last, "input error: %s", strerror(errno));
615     disorder_error(errno, "error reading %s", c->ident);
616   } else {
617     c->last = "input error: unexpxected EOF";
618     disorder_error(0, "error reading %s: unexpected EOF", c->ident);
619   }
620   return -1;
621 }
622
623 /** @brief Return the user we logged in with
624  * @param c Client
625  * @return User name (owned by @p c, don't modify)
626  */
627 char *disorder_user(disorder_client *c) {
628   return c->user;
629 }
630
631 static void pairlist_error_handler(const char *msg,
632                                void attribute((unused)) *u) {
633   disorder_error(0, "error handling key-value pair reply: %s", msg);
634 }
635
636 /** @brief Get a list of key-value pairs
637  * @param c Client
638  * @param kp Where to store linked list of preferences
639  * @param cmd Command
640  * @param ... Arguments
641  * @return 0 on success, non-0 on error
642  */
643 static int pairlist(disorder_client *c, struct kvp **kp, const char *cmd, ...) {
644   char **vec, **pvec;
645   int nvec, npvec, n, rc;
646   struct kvp *k;
647   va_list ap;
648
649   va_start(ap, cmd);
650   rc = disorder_simple_v(c, 0, cmd, ap);
651   va_end(ap);
652   if(rc)
653     return rc;
654   if((rc = readlist(c, &vec, &nvec)))
655      return rc;
656   for(n = 0; n < nvec; ++n) {
657     if(!(pvec = split(vec[n], &npvec, SPLIT_QUOTES, pairlist_error_handler, 0)))
658       return -1;
659     if(npvec != 2) {
660       pairlist_error_handler("malformed response", 0);
661       return -1;
662     }
663     *kp = k = xmalloc(sizeof *k);
664     k->name = pvec[0];
665     k->value = pvec[1];
666     kp = &k->next;
667     xfree(pvec);
668   }
669   free_strings(nvec, vec);
670   *kp = 0;
671   return 0;
672 }
673
674 /** @brief Parse a boolean response
675  * @param cmd Command for use in error messsage
676  * @param value Result from server
677  * @param flagp Where to store result
678  * @return 0 on success, non-0 on error
679  */
680 static int boolean(const char *cmd, const char *value,
681                    int *flagp) {
682   if(!strcmp(value, "yes")) *flagp = 1;
683   else if(!strcmp(value, "no")) *flagp = 0;
684   else {
685     disorder_error(0, "malformed response to '%s'", cmd);
686     return -1;
687   }
688   return 0;
689 }
690
691 /** @brief Log to a sink
692  * @param c Client
693  * @param s Sink to write log lines to
694  * @return 0 on success, non-0 on error
695  */
696 int disorder_log(disorder_client *c, struct sink *s) {
697   char *l;
698   int rc;
699     
700   if((rc = disorder_simple(c, 0, "log", (char *)0)))
701     return rc;
702   while(inputline(c->ident, c->fpin, &l, '\n') >= 0 && strcmp(l, "."))
703     if(sink_printf(s, "%s\n", l) < 0) return -1;
704   if(ferror(c->fpin) || feof(c->fpin)) {
705     byte_xasprintf((char **)&c->last, "input error: %s",
706                    ferror(c->fpin) ? strerror(errno) : "unexpxected EOF");
707     return -1;
708   }
709   return 0;
710 }
711
712 #include "client-stubs.c"
713
714 /*
715 Local Variables:
716 c-basic-offset:2
717 comment-column:40
718 End:
719 */