Merge branch 'collectd-5.5'
[collectd.git] / src / libcollectdclient / client.c
1 /**
2  * libcollectdclient - src/libcollectdclient/client.c
3  * Copyright (C) 2008-2012  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  **/
26
27 #if HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #if !defined(__GNUC__) || !__GNUC__
32 # define __attribute__(x) /**/
33 #endif
34
35 #include "collectd/lcc_features.h"
36
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <unistd.h>
40 #include <sys/types.h>
41 #include <sys/socket.h>
42 #include <sys/un.h>
43 #include <string.h>
44 #include <assert.h>
45 #include <errno.h>
46 #include <math.h>
47 #include <netdb.h>
48
49 #include "collectd/client.h"
50
51 /* NI_MAXHOST has been obsoleted by RFC 3493 which is a reason for SunOS 5.11
52  * to no longer define it. We'll use the old, RFC 2553 value here. */
53 #ifndef NI_MAXHOST
54 # define NI_MAXHOST 1025
55 #endif
56
57 /* OpenBSD doesn't have EPROTO, FreeBSD doesn't have EILSEQ. Oh what joy! */
58 #ifndef EILSEQ
59 # ifdef EPROTO
60 #  define EILSEQ EPROTO
61 # else
62 #  define EILSEQ EINVAL
63 # endif
64 #endif
65
66 /* Secure/static macros. They work like `strcpy' and `strcat', but assure null
67  * termination. They work for static buffers only, because they use `sizeof'.
68  * The `SSTRCATF' combines the functionality of `snprintf' and `strcat' which
69  * is very useful to add formatted stuff to the end of a buffer. */
70 #define SSTRCPY(d,s) do { \
71     strncpy ((d), (s), sizeof (d)); \
72     (d)[sizeof (d) - 1] = 0; \
73   } while (0)
74
75 #define SSTRCAT(d,s) do { \
76     size_t _l = strlen (d); \
77     strncpy ((d) + _l, (s), sizeof (d) - _l); \
78     (d)[sizeof (d) - 1] = 0; \
79   } while (0)
80
81 #define SSTRCATF(d, ...) do { \
82     char _b[sizeof (d)]; \
83     snprintf (_b, sizeof (_b), __VA_ARGS__); \
84     _b[sizeof (_b) - 1] = 0; \
85     SSTRCAT ((d), _b); \
86   } while (0)
87
88
89 #define LCC_SET_ERRSTR(c, ...) do { \
90   snprintf ((c)->errbuf, sizeof ((c)->errbuf), __VA_ARGS__); \
91   (c)->errbuf[sizeof ((c)->errbuf) - 1] = 0; \
92 } while (0)
93
94 #if COLLECT_DEBUG
95 # define LCC_DEBUG(...) printf (__VA_ARGS__)
96 #else
97 # define LCC_DEBUG(...) /**/
98 #endif
99
100 /*
101  * Types
102  */
103 struct lcc_connection_s
104 {
105   FILE *fh;
106   char errbuf[1024];
107 };
108
109 struct lcc_response_s
110 {
111   int status;
112   char message[1024];
113   char **lines;
114   size_t lines_num;
115 };
116 typedef struct lcc_response_s lcc_response_t;
117
118 /*
119  * Private functions
120  */
121 /* Even though Posix requires "strerror_r" to return an "int",
122  * some systems (e.g. the GNU libc) return a "char *" _and_
123  * ignore the second argument ... -tokkee */
124 static char *sstrerror (int errnum, char *buf, size_t buflen)
125 {
126   buf[0] = 0;
127
128 #if !HAVE_STRERROR_R
129   snprintf (buf, buflen, "Error #%i; strerror_r is not available.", errnum);
130 /* #endif !HAVE_STRERROR_R */
131
132 #elif STRERROR_R_CHAR_P
133   {
134     char *temp;
135     temp = strerror_r (errnum, buf, buflen);
136     if (buf[0] == 0)
137     {
138       if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
139         strncpy (buf, temp, buflen);
140       else
141         strncpy (buf, "strerror_r did not return "
142             "an error message", buflen);
143     }
144   }
145 /* #endif STRERROR_R_CHAR_P */
146
147 #else
148   if (strerror_r (errnum, buf, buflen) != 0)
149   {
150     snprintf (buf, buflen, "Error #%i; "
151         "Additionally, strerror_r failed.",
152         errnum);
153   }
154 #endif /* STRERROR_R_CHAR_P */
155
156   buf[buflen - 1] = 0;
157
158   return (buf);
159 } /* char *sstrerror */
160
161 static int lcc_set_errno (lcc_connection_t *c, int err) /* {{{ */
162 {
163   if (c == NULL)
164     return (-1);
165
166   sstrerror (err, c->errbuf, sizeof (c->errbuf));
167   c->errbuf[sizeof (c->errbuf) - 1] = 0;
168
169   return (0);
170 } /* }}} int lcc_set_errno */
171
172 static char *lcc_strescape (char *dest, const char *src, size_t dest_size) /* {{{ */
173 {
174   size_t dest_pos;
175   size_t src_pos;
176
177   if ((dest == NULL) || (src == NULL))
178     return (NULL);
179
180   dest_pos = 0;
181   src_pos = 0;
182
183   assert (dest_size >= 3);
184
185   dest[dest_pos] = '"';
186   dest_pos++;
187
188   while (42)
189   {
190     if ((dest_pos == (dest_size - 2))
191         || (src[src_pos] == 0))
192       break;
193
194     if ((src[src_pos] == '"') || (src[src_pos] == '\\'))
195     {
196       /* Check if there is enough space for both characters.. */
197       if (dest_pos == (dest_size - 3))
198         break;
199
200       dest[dest_pos] = '\\';
201       dest_pos++;
202     }
203
204     dest[dest_pos] = src[src_pos];
205     dest_pos++;
206     src_pos++;
207   }
208
209   assert (dest_pos <= (dest_size - 2));
210
211   dest[dest_pos] = '"';
212   dest_pos++;
213
214   dest[dest_pos] = 0;
215   dest_pos++;
216   src_pos++;
217
218   return (dest);
219 } /* }}} char *lcc_strescape */
220
221 /* lcc_chomp: Removes all control-characters at the end of a string. */
222 static void lcc_chomp (char *str) /* {{{ */
223 {
224   size_t str_len;
225
226   str_len = strlen (str);
227   while (str_len > 0)
228   {
229     if (str[str_len - 1] >= 32)
230       break;
231     str[str_len - 1] = 0;
232     str_len--;
233   }
234 } /* }}} void lcc_chomp */
235
236 static void lcc_response_free (lcc_response_t *res) /* {{{ */
237 {
238   size_t i;
239
240   if (res == NULL)
241     return;
242
243   for (i = 0; i < res->lines_num; i++)
244     free (res->lines[i]);
245   free (res->lines);
246   res->lines = NULL;
247 } /* }}} void lcc_response_free */
248
249 static int lcc_send (lcc_connection_t *c, const char *command) /* {{{ */
250 {
251   int status;
252
253   LCC_DEBUG ("send:    --> %s\n", command);
254
255   status = fprintf (c->fh, "%s\r\n", command);
256   if (status < 0)
257   {
258     lcc_set_errno (c, errno);
259     return (-1);
260   }
261   fflush(c->fh);
262
263   return (0);
264 } /* }}} int lcc_send */
265
266 static int lcc_receive (lcc_connection_t *c, /* {{{ */
267     lcc_response_t *ret_res)
268 {
269   lcc_response_t res;
270   char *ptr;
271   char buffer[4096];
272   size_t i;
273
274   memset (&res, 0, sizeof (res));
275
276   /* Read the first line, containing the status and a message */
277   ptr = fgets (buffer, sizeof (buffer), c->fh);
278   if (ptr == NULL)
279   {
280     lcc_set_errno (c, errno);
281     return (-1);
282   }
283   lcc_chomp (buffer);
284   LCC_DEBUG ("receive: <-- %s\n", buffer);
285
286   /* Convert the leading status to an integer and make `ptr' to point to the
287    * beginning of the message. */
288   ptr = NULL;
289   errno = 0;
290   res.status = (int) strtol (buffer, &ptr, 0);
291   if ((errno != 0) || (ptr == &buffer[0]))
292   {
293     lcc_set_errno (c, errno);
294     return (-1);
295   }
296
297   /* Skip white spaces after the status number */
298   while ((*ptr == ' ') || (*ptr == '\t'))
299     ptr++;
300
301   /* Now copy the message. */
302   strncpy (res.message, ptr, sizeof (res.message));
303   res.message[sizeof (res.message) - 1] = 0;
304
305   /* Error or no lines follow: We're done. */
306   if (res.status <= 0)
307   {
308     memcpy (ret_res, &res, sizeof (res));
309     return (0);
310   }
311
312   /* Allocate space for the char-pointers */
313   res.lines_num = (size_t) res.status;
314   res.status = 0;
315   res.lines = malloc (res.lines_num * sizeof (*res.lines));
316   if (res.lines == NULL)
317   {
318     lcc_set_errno (c, ENOMEM);
319     return (-1);
320   }
321
322   /* Now receive all the lines */
323   for (i = 0; i < res.lines_num; i++)
324   {
325     ptr = fgets (buffer, sizeof (buffer), c->fh);
326     if (ptr == NULL)
327     {
328       lcc_set_errno (c, errno);
329       break;
330     }
331     lcc_chomp (buffer);
332     LCC_DEBUG ("receive: <-- %s\n", buffer);
333
334     res.lines[i] = strdup (buffer);
335     if (res.lines[i] == NULL)
336     {
337       lcc_set_errno (c, ENOMEM);
338       break;
339     }
340   }
341
342   /* Check if the for-loop exited with an error. */
343   if (i < res.lines_num)
344   {
345     while (i > 0)
346     {
347       i--;
348       free (res.lines[i]);
349     }
350     free (res.lines);
351     return (-1);
352   }
353
354   memcpy (ret_res, &res, sizeof (res));
355   return (0);
356 } /* }}} int lcc_receive */
357
358 static int lcc_sendreceive (lcc_connection_t *c, /* {{{ */
359     const char *command, lcc_response_t *ret_res)
360 {
361   lcc_response_t res;
362   int status;
363
364   if (c->fh == NULL)
365   {
366     lcc_set_errno (c, EBADF);
367     return (-1);
368   }
369
370   status = lcc_send (c, command);
371   if (status != 0)
372     return (status);
373
374   memset (&res, 0, sizeof (res));
375   status = lcc_receive (c, &res);
376   if (status == 0)
377     memcpy (ret_res, &res, sizeof (*ret_res));
378
379   return (status);
380 } /* }}} int lcc_sendreceive */
381
382 static int lcc_open_unixsocket (lcc_connection_t *c, const char *path) /* {{{ */
383 {
384   struct sockaddr_un sa;
385   int fd;
386   int status;
387
388   assert (c != NULL);
389   assert (c->fh == NULL);
390   assert (path != NULL);
391
392   /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
393    * others). */
394   fd = socket (AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
395   if (fd < 0)
396   {
397     lcc_set_errno (c, errno);
398     return (-1);
399   }
400
401   memset (&sa, 0, sizeof (sa));
402   sa.sun_family = AF_UNIX;
403   strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
404
405   status = connect (fd, (struct sockaddr *) &sa, sizeof (sa));
406   if (status != 0)
407   {
408     lcc_set_errno (c, errno);
409     close (fd);
410     return (-1);
411   }
412
413   c->fh = fdopen (fd, "r+");
414   if (c->fh == NULL)
415   {
416     lcc_set_errno (c, errno);
417     close (fd);
418     return (-1);
419   }
420
421   return (0);
422 } /* }}} int lcc_open_unixsocket */
423
424 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
425     const char *addr_orig)
426 {
427   struct addrinfo ai_hints;
428   struct addrinfo *ai_res;
429   struct addrinfo *ai_ptr;
430   char addr_copy[NI_MAXHOST];
431   char *addr;
432   char *port;
433   int fd;
434   int status;
435
436   assert (c != NULL);
437   assert (c->fh == NULL);
438   assert (addr_orig != NULL);
439
440   strncpy(addr_copy, addr_orig, sizeof(addr_copy));
441   addr_copy[sizeof(addr_copy) - 1] = '\0';
442   addr = addr_copy;
443
444   memset (&ai_hints, 0, sizeof (ai_hints));
445   ai_hints.ai_flags = 0;
446 #ifdef AI_ADDRCONFIG
447   ai_hints.ai_flags |= AI_ADDRCONFIG;
448 #endif
449   ai_hints.ai_family = AF_UNSPEC;
450   ai_hints.ai_socktype = SOCK_STREAM;
451
452   port = NULL;
453   if (*addr == '[') /* IPv6+port format */
454   {
455     /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
456     addr++;
457
458     port = strchr (addr, ']');
459     if (port == NULL)
460     {
461       LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
462       return (-1);
463     }
464     *port = 0;
465     port++;
466
467     if (*port == ':')
468       port++;
469     else if (*port == 0)
470       port = NULL;
471     else
472     {
473       LCC_SET_ERRSTR (c, "garbage after address: %s", port);
474       return (-1);
475     }
476   } /* if (*addr = ']') */
477   else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
478   {
479     port = strrchr (addr, ':');
480     if (port != NULL)
481     {
482       *port = 0;
483       port++;
484     }
485   }
486
487   ai_res = NULL;
488   status = getaddrinfo (addr,
489                         port == NULL ? LCC_DEFAULT_PORT : port,
490                         &ai_hints, &ai_res);
491   if (status != 0)
492   {
493     LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
494     return (-1);
495   }
496
497   for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
498   {
499     fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
500     if (fd < 0)
501     {
502       status = errno;
503       continue;
504     }
505
506     status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
507     if (status != 0)
508     {
509       status = errno;
510       close (fd);
511       continue;
512     }
513
514     c->fh = fdopen (fd, "r+");
515     if (c->fh == NULL)
516     {
517       status = errno;
518       close (fd);
519       continue;
520     }
521
522     assert (status == 0);
523     break;
524   } /* for (ai_ptr) */
525
526   if (status != 0)
527   {
528     lcc_set_errno (c, status);
529     freeaddrinfo (ai_res);
530     return (-1);
531   }
532
533   freeaddrinfo (ai_res);
534   return (0);
535 } /* }}} int lcc_open_netsocket */
536
537 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
538 {
539   int status = 0;
540
541   if (addr == NULL)
542     return (-1);
543
544   assert (c != NULL);
545   assert (c->fh == NULL);
546   assert (addr != NULL);
547
548   if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
549     status = lcc_open_unixsocket (c, addr + strlen ("unix:"));
550   else if (addr[0] == '/')
551     status = lcc_open_unixsocket (c, addr);
552   else
553     status = lcc_open_netsocket (c, addr);
554
555   return (status);
556 } /* }}} int lcc_open_socket */
557
558 /*
559  * Public functions
560  */
561 unsigned int lcc_version (void) /* {{{ */
562 {
563   return (LCC_VERSION);
564 } /* }}} unsigned int lcc_version */
565
566 const char *lcc_version_string (void) /* {{{ */
567 {
568   return (LCC_VERSION_STRING);
569 } /* }}} const char *lcc_version_string */
570
571 const char *lcc_version_extra (void) /* {{{ */
572 {
573   return (LCC_VERSION_EXTRA);
574 } /* }}} const char *lcc_version_extra */
575
576 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
577 {
578   lcc_connection_t *c;
579   int status;
580
581   if (address == NULL)
582     return (-1);
583
584   if (ret_con == NULL)
585     return (-1);
586
587   c = calloc (1, sizeof (*c));
588   if (c == NULL)
589     return (-1);
590
591   status = lcc_open_socket (c, address);
592   if (status != 0)
593   {
594     lcc_disconnect (c);
595     return (status);
596   }
597
598   *ret_con = c;
599   return (0);
600 } /* }}} int lcc_connect */
601
602 int lcc_disconnect (lcc_connection_t *c) /* {{{ */
603 {
604   if (c == NULL)
605     return (-1);
606
607   if (c->fh != NULL)
608   {
609     fclose (c->fh);
610     c->fh = NULL;
611   }
612
613   free (c);
614   return (0);
615 } /* }}} int lcc_disconnect */
616
617 int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
618     size_t *ret_values_num, gauge_t **ret_values, char ***ret_values_names)
619 {
620   char ident_str[6 * LCC_NAME_LEN];
621   char ident_esc[12 * LCC_NAME_LEN];
622   char command[14 * LCC_NAME_LEN];
623
624   lcc_response_t res;
625   size_t   values_num;
626   gauge_t *values = NULL;
627   char   **values_names = NULL;
628
629   size_t i;
630   int status;
631
632   if (c == NULL)
633     return (-1);
634
635   if (ident == NULL)
636   {
637     lcc_set_errno (c, EINVAL);
638     return (-1);
639   }
640
641   /* Build a commend with an escaped version of the identifier string. */
642   status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
643   if (status != 0)
644     return (status);
645
646   snprintf (command, sizeof (command), "GETVAL %s",
647       lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
648   command[sizeof (command) - 1] = 0;
649
650   /* Send talk to the daemon.. */
651   status = lcc_sendreceive (c, command, &res);
652   if (status != 0)
653     return (status);
654
655   if (res.status != 0)
656   {
657     LCC_SET_ERRSTR (c, "Server error: %s", res.message);
658     lcc_response_free (&res);
659     return (-1);
660   }
661
662   values_num = res.lines_num;
663
664 #define BAIL_OUT(e) do { \
665   lcc_set_errno (c, (e)); \
666   free (values); \
667   if (values_names != NULL) { \
668     for (i = 0; i < values_num; i++) { \
669       free (values_names[i]); \
670     } \
671   } \
672   free (values_names); \
673   lcc_response_free (&res); \
674   return (-1); \
675 } while (0)
676
677   /* If neither the values nor the names are requested, return here.. */
678   if ((ret_values == NULL) && (ret_values_names == NULL))
679   {
680     if (ret_values_num != NULL)
681       *ret_values_num = values_num;
682     lcc_response_free (&res);
683     return (0);
684   }
685
686   /* Allocate space for the values */
687   if (ret_values != NULL)
688   {
689     values = malloc (values_num * sizeof (*values));
690     if (values == NULL)
691       BAIL_OUT (ENOMEM);
692   }
693
694   if (ret_values_names != NULL)
695   {
696     values_names = (char **) calloc (values_num, sizeof (*values_names));
697     if (values_names == NULL)
698       BAIL_OUT (ENOMEM);
699   }
700
701   for (i = 0; i < res.lines_num; i++)
702   {
703     char *key;
704     char *value;
705     char *endptr;
706
707     key = res.lines[i];
708     value = strchr (key, '=');
709     if (value == NULL)
710       BAIL_OUT (EILSEQ);
711
712     *value = 0;
713     value++;
714
715     if (values != NULL)
716     {
717       endptr = NULL;
718       errno = 0;
719       values[i] = strtod (value, &endptr);
720
721       if ((endptr == value) || (errno != 0))
722         BAIL_OUT (errno);
723     }
724
725     if (values_names != NULL)
726     {
727       values_names[i] = strdup (key);
728       if (values_names[i] == NULL)
729         BAIL_OUT (ENOMEM);
730     }
731   } /* for (i = 0; i < res.lines_num; i++) */
732
733   if (ret_values_num != NULL)
734     *ret_values_num = values_num;
735   if (ret_values != NULL)
736     *ret_values = values;
737   if (ret_values_names != NULL)
738     *ret_values_names = values_names;
739
740   lcc_response_free (&res);
741
742   return (0);
743 } /* }}} int lcc_getval */
744
745 int lcc_putval (lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
746 {
747   char ident_str[6 * LCC_NAME_LEN];
748   char ident_esc[12 * LCC_NAME_LEN];
749   char command[1024] = "";
750   lcc_response_t res;
751   int status;
752   size_t i;
753
754   if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
755       || (vl->values == NULL) || (vl->values_types == NULL))
756   {
757     lcc_set_errno (c, EINVAL);
758     return (-1);
759   }
760
761   status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
762       &vl->identifier);
763   if (status != 0)
764     return (status);
765
766   SSTRCATF (command, "PUTVAL %s",
767       lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
768
769   if (vl->interval > 0.0)
770     SSTRCATF (command, " interval=%.3f", vl->interval);
771
772   if (vl->time > 0.0)
773     SSTRCATF (command, " %.3f", vl->time);
774   else
775     SSTRCAT (command, " N");
776
777   for (i = 0; i < vl->values_len; i++)
778   {
779     if (vl->values_types[i] == LCC_TYPE_COUNTER)
780       SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
781     else if (vl->values_types[i] == LCC_TYPE_GAUGE)
782     {
783       if (isnan (vl->values[i].gauge))
784         SSTRCATF (command, ":U");
785       else
786         SSTRCATF (command, ":%g", vl->values[i].gauge);
787     }
788     else if (vl->values_types[i] == LCC_TYPE_DERIVE)
789         SSTRCATF (command, ":%"PRIu64, vl->values[i].derive);
790     else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
791         SSTRCATF (command, ":%"PRIu64, vl->values[i].absolute);
792
793   } /* for (i = 0; i < vl->values_len; i++) */
794
795   status = lcc_sendreceive (c, command, &res);
796   if (status != 0)
797     return (status);
798
799   if (res.status != 0)
800   {
801     LCC_SET_ERRSTR (c, "Server error: %s", res.message);
802     lcc_response_free (&res);
803     return (-1);
804   }
805
806   lcc_response_free (&res);
807   return (0);
808 } /* }}} int lcc_putval */
809
810 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
811     lcc_identifier_t *ident, int timeout)
812 {
813   char command[1024] = "";
814   lcc_response_t res;
815   int status;
816
817   if (c == NULL)
818   {
819     lcc_set_errno (c, EINVAL);
820     return (-1);
821   }
822
823   SSTRCPY (command, "FLUSH");
824
825   if (timeout > 0)
826     SSTRCATF (command, " timeout=%i", timeout);
827
828   if (plugin != NULL)
829   {
830     char buffer[2 * LCC_NAME_LEN];
831     SSTRCATF (command, " plugin=%s",
832         lcc_strescape (buffer, plugin, sizeof (buffer)));
833   }
834
835   if (ident != NULL)
836   {
837     char ident_str[6 * LCC_NAME_LEN];
838     char ident_esc[12 * LCC_NAME_LEN];
839
840     status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
841     if (status != 0)
842       return (status);
843
844     SSTRCATF (command, " identifier=%s",
845         lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
846   }
847
848   status = lcc_sendreceive (c, command, &res);
849   if (status != 0)
850     return (status);
851
852   if (res.status != 0)
853   {
854     LCC_SET_ERRSTR (c, "Server error: %s", res.message);
855     lcc_response_free (&res);
856     return (-1);
857   }
858
859   lcc_response_free (&res);
860   return (0);
861 } /* }}} int lcc_flush */
862
863 /* TODO: Implement lcc_putnotif */
864
865 int lcc_listval (lcc_connection_t *c, /* {{{ */
866     lcc_identifier_t **ret_ident, size_t *ret_ident_num)
867 {
868   lcc_response_t res;
869   size_t i;
870   int status;
871
872   lcc_identifier_t *ident;
873   size_t ident_num;
874
875   if (c == NULL)
876     return (-1);
877
878   if ((ret_ident == NULL) || (ret_ident_num == NULL))
879   {
880     lcc_set_errno (c, EINVAL);
881     return (-1);
882   }
883
884   status = lcc_sendreceive (c, "LISTVAL", &res);
885   if (status != 0)
886     return (status);
887
888   if (res.status != 0)
889   {
890     LCC_SET_ERRSTR (c, "Server error: %s", res.message);
891     lcc_response_free (&res);
892     return (-1);
893   }
894
895   ident_num = res.lines_num;
896   ident = malloc (ident_num * sizeof (*ident));
897   if (ident == NULL)
898   {
899     lcc_response_free (&res);
900     lcc_set_errno (c, ENOMEM);
901     return (-1);
902   }
903
904   for (i = 0; i < res.lines_num; i++)
905   {
906     char *time_str;
907     char *ident_str;
908
909     /* First field is the time. */
910     time_str = res.lines[i];
911
912     /* Set `ident_str' to the beginning of the second field. */
913     ident_str = time_str;
914     while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
915       ident_str++;
916     while ((*ident_str == ' ') || (*ident_str == '\t'))
917     {
918       *ident_str = 0;
919       ident_str++;
920     }
921
922     if (*ident_str == 0)
923     {
924       lcc_set_errno (c, EILSEQ);
925       status = -1;
926       break;
927     }
928
929     status = lcc_string_to_identifier (c, ident + i, ident_str);
930     if (status != 0)
931       break;
932   }
933
934   lcc_response_free (&res);
935
936   if (status != 0)
937   {
938     free (ident);
939     return (-1);
940   }
941
942   *ret_ident = ident;
943   *ret_ident_num = ident_num;
944
945   return (0);
946 } /* }}} int lcc_listval */
947
948 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
949 {
950   if (c == NULL)
951     return ("Invalid object");
952   return (c->errbuf);
953 } /* }}} const char *lcc_strerror */
954
955 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
956     char *string, size_t string_size, const lcc_identifier_t *ident)
957 {
958   if ((string == NULL) || (string_size < 6) || (ident == NULL))
959   {
960     lcc_set_errno (c, EINVAL);
961     return (-1);
962   }
963
964   if (ident->plugin_instance[0] == 0)
965   {
966     if (ident->type_instance[0] == 0)
967       snprintf (string, string_size, "%s/%s/%s",
968           ident->host,
969           ident->plugin,
970           ident->type);
971     else
972       snprintf (string, string_size, "%s/%s/%s-%s",
973           ident->host,
974           ident->plugin,
975           ident->type,
976           ident->type_instance);
977   }
978   else
979   {
980     if (ident->type_instance[0] == 0)
981       snprintf (string, string_size, "%s/%s-%s/%s",
982           ident->host,
983           ident->plugin,
984           ident->plugin_instance,
985           ident->type);
986     else
987       snprintf (string, string_size, "%s/%s-%s/%s-%s",
988           ident->host,
989           ident->plugin,
990           ident->plugin_instance,
991           ident->type,
992           ident->type_instance);
993   }
994
995   string[string_size - 1] = 0;
996   return (0);
997 } /* }}} int lcc_identifier_to_string */
998
999 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
1000     lcc_identifier_t *ident, const char *string)
1001 {
1002   char *string_copy;
1003   char *host;
1004   char *plugin;
1005   char *plugin_instance;
1006   char *type;
1007   char *type_instance;
1008
1009   string_copy = strdup (string);
1010   if (string_copy == NULL)
1011   {
1012     lcc_set_errno (c, ENOMEM);
1013     return (-1);
1014   }
1015
1016   host = string_copy;
1017   plugin = strchr (host, '/');
1018   if (plugin == NULL)
1019   {
1020     LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1021     free (string_copy);
1022     return (-1);
1023   }
1024   *plugin = 0;
1025   plugin++;
1026
1027   type = strchr (plugin, '/');
1028   if (type == NULL)
1029   {
1030     LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1031     free (string_copy);
1032     return (-1);
1033   }
1034   *type = 0;
1035   type++;
1036
1037   plugin_instance = strchr (plugin, '-');
1038   if (plugin_instance != NULL)
1039   {
1040     *plugin_instance = 0;
1041     plugin_instance++;
1042   }
1043
1044   type_instance = strchr (type, '-');
1045   if (type_instance != NULL)
1046   {
1047     *type_instance = 0;
1048     type_instance++;
1049   }
1050
1051   memset (ident, 0, sizeof (*ident));
1052
1053   SSTRCPY (ident->host, host);
1054   SSTRCPY (ident->plugin, plugin);
1055   if (plugin_instance != NULL)
1056     SSTRCPY (ident->plugin_instance, plugin_instance);
1057   SSTRCPY (ident->type, type);
1058   if (type_instance != NULL)
1059     SSTRCPY (ident->type_instance, type_instance);
1060
1061   free (string_copy);
1062   return (0);
1063 } /* }}} int lcc_string_to_identifier */
1064
1065 int lcc_identifier_compare (const lcc_identifier_t *i0, /* {{{ */
1066     const lcc_identifier_t *i1)
1067 {
1068   int status;
1069
1070   if ((i0 == NULL) && (i1 == NULL))
1071     return (0);
1072   else if (i0 == NULL)
1073     return (-1);
1074   else if (i1 == NULL)
1075     return (1);
1076
1077 #define CMP_FIELD(f) do {         \
1078   status = strcmp (i0->f, i1->f); \
1079   if (status != 0)                \
1080     return (status);              \
1081 } while (0);
1082
1083     CMP_FIELD (host);
1084     CMP_FIELD (plugin);
1085     CMP_FIELD (plugin_instance);
1086     CMP_FIELD (type);
1087     CMP_FIELD (type_instance);
1088
1089 #undef CMP_FIELD
1090
1091     return (0);
1092 } /* }}} int lcc_identifier_compare */
1093
1094 int lcc_sort_identifiers (lcc_connection_t *c, /* {{{ */
1095     lcc_identifier_t *idents, size_t idents_num)
1096 {
1097   if (idents == NULL)
1098   {
1099     lcc_set_errno (c, EINVAL);
1100     return (-1);
1101   }
1102
1103   qsort (idents, idents_num, sizeof (*idents),
1104       (void *) lcc_identifier_compare);
1105   return (0);
1106 } /* }}} int lcc_sort_identifiers */
1107
1108 /* vim: set sw=2 sts=2 et fdm=marker : */