Merge pull request #1821 from rubenk/memset
[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 = { 0 };
270   char *ptr;
271   char buffer[4096];
272   size_t i;
273
274   /* Read the first line, containing the status and a message */
275   ptr = fgets (buffer, sizeof (buffer), c->fh);
276   if (ptr == NULL)
277   {
278     lcc_set_errno (c, errno);
279     return (-1);
280   }
281   lcc_chomp (buffer);
282   LCC_DEBUG ("receive: <-- %s\n", buffer);
283
284   /* Convert the leading status to an integer and make `ptr' to point to the
285    * beginning of the message. */
286   ptr = NULL;
287   errno = 0;
288   res.status = (int) strtol (buffer, &ptr, 0);
289   if ((errno != 0) || (ptr == &buffer[0]))
290   {
291     lcc_set_errno (c, errno);
292     return (-1);
293   }
294
295   /* Skip white spaces after the status number */
296   while ((*ptr == ' ') || (*ptr == '\t'))
297     ptr++;
298
299   /* Now copy the message. */
300   strncpy (res.message, ptr, sizeof (res.message));
301   res.message[sizeof (res.message) - 1] = 0;
302
303   /* Error or no lines follow: We're done. */
304   if (res.status <= 0)
305   {
306     memcpy (ret_res, &res, sizeof (res));
307     return (0);
308   }
309
310   /* Allocate space for the char-pointers */
311   res.lines_num = (size_t) res.status;
312   res.status = 0;
313   res.lines = malloc (res.lines_num * sizeof (*res.lines));
314   if (res.lines == NULL)
315   {
316     lcc_set_errno (c, ENOMEM);
317     return (-1);
318   }
319
320   /* Now receive all the lines */
321   for (i = 0; i < res.lines_num; i++)
322   {
323     ptr = fgets (buffer, sizeof (buffer), c->fh);
324     if (ptr == NULL)
325     {
326       lcc_set_errno (c, errno);
327       break;
328     }
329     lcc_chomp (buffer);
330     LCC_DEBUG ("receive: <-- %s\n", buffer);
331
332     res.lines[i] = strdup (buffer);
333     if (res.lines[i] == NULL)
334     {
335       lcc_set_errno (c, ENOMEM);
336       break;
337     }
338   }
339
340   /* Check if the for-loop exited with an error. */
341   if (i < res.lines_num)
342   {
343     while (i > 0)
344     {
345       i--;
346       free (res.lines[i]);
347     }
348     free (res.lines);
349     return (-1);
350   }
351
352   memcpy (ret_res, &res, sizeof (res));
353   return (0);
354 } /* }}} int lcc_receive */
355
356 static int lcc_sendreceive (lcc_connection_t *c, /* {{{ */
357     const char *command, lcc_response_t *ret_res)
358 {
359   lcc_response_t res = { 0 };
360   int status;
361
362   if (c->fh == NULL)
363   {
364     lcc_set_errno (c, EBADF);
365     return (-1);
366   }
367
368   status = lcc_send (c, command);
369   if (status != 0)
370     return (status);
371
372   status = lcc_receive (c, &res);
373   if (status == 0)
374     memcpy (ret_res, &res, sizeof (*ret_res));
375
376   return (status);
377 } /* }}} int lcc_sendreceive */
378
379 static int lcc_open_unixsocket (lcc_connection_t *c, const char *path) /* {{{ */
380 {
381   struct sockaddr_un sa = { 0 };
382   int fd;
383   int status;
384
385   assert (c != NULL);
386   assert (c->fh == NULL);
387   assert (path != NULL);
388
389   /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
390    * others). */
391   fd = socket (AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
392   if (fd < 0)
393   {
394     lcc_set_errno (c, errno);
395     return (-1);
396   }
397
398   sa.sun_family = AF_UNIX;
399   strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
400
401   status = connect (fd, (struct sockaddr *) &sa, sizeof (sa));
402   if (status != 0)
403   {
404     lcc_set_errno (c, errno);
405     close (fd);
406     return (-1);
407   }
408
409   c->fh = fdopen (fd, "r+");
410   if (c->fh == NULL)
411   {
412     lcc_set_errno (c, errno);
413     close (fd);
414     return (-1);
415   }
416
417   return (0);
418 } /* }}} int lcc_open_unixsocket */
419
420 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
421     const char *addr_orig)
422 {
423   struct addrinfo ai_hints = { 0 };
424   struct addrinfo *ai_res;
425   struct addrinfo *ai_ptr;
426   char addr_copy[NI_MAXHOST];
427   char *addr;
428   char *port;
429   int fd;
430   int status;
431
432   assert (c != NULL);
433   assert (c->fh == NULL);
434   assert (addr_orig != NULL);
435
436   strncpy(addr_copy, addr_orig, sizeof(addr_copy));
437   addr_copy[sizeof(addr_copy) - 1] = '\0';
438   addr = addr_copy;
439
440 #ifdef AI_ADDRCONFIG
441   ai_hints.ai_flags |= AI_ADDRCONFIG;
442 #endif
443   ai_hints.ai_family = AF_UNSPEC;
444   ai_hints.ai_socktype = SOCK_STREAM;
445
446   port = NULL;
447   if (*addr == '[') /* IPv6+port format */
448   {
449     /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
450     addr++;
451
452     port = strchr (addr, ']');
453     if (port == NULL)
454     {
455       LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
456       return (-1);
457     }
458     *port = 0;
459     port++;
460
461     if (*port == ':')
462       port++;
463     else if (*port == 0)
464       port = NULL;
465     else
466     {
467       LCC_SET_ERRSTR (c, "garbage after address: %s", port);
468       return (-1);
469     }
470   } /* if (*addr = ']') */
471   else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
472   {
473     port = strrchr (addr, ':');
474     if (port != NULL)
475     {
476       *port = 0;
477       port++;
478     }
479   }
480
481   ai_res = NULL;
482   status = getaddrinfo (addr,
483                         port == NULL ? LCC_DEFAULT_PORT : port,
484                         &ai_hints, &ai_res);
485   if (status != 0)
486   {
487     LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
488     return (-1);
489   }
490
491   for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
492   {
493     fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
494     if (fd < 0)
495     {
496       status = errno;
497       continue;
498     }
499
500     status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
501     if (status != 0)
502     {
503       status = errno;
504       close (fd);
505       continue;
506     }
507
508     c->fh = fdopen (fd, "r+");
509     if (c->fh == NULL)
510     {
511       status = errno;
512       close (fd);
513       continue;
514     }
515
516     assert (status == 0);
517     break;
518   } /* for (ai_ptr) */
519
520   if (status != 0)
521   {
522     lcc_set_errno (c, status);
523     freeaddrinfo (ai_res);
524     return (-1);
525   }
526
527   freeaddrinfo (ai_res);
528   return (0);
529 } /* }}} int lcc_open_netsocket */
530
531 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
532 {
533   int status = 0;
534
535   if (addr == NULL)
536     return (-1);
537
538   assert (c != NULL);
539   assert (c->fh == NULL);
540   assert (addr != NULL);
541
542   if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
543     status = lcc_open_unixsocket (c, addr + strlen ("unix:"));
544   else if (addr[0] == '/')
545     status = lcc_open_unixsocket (c, addr);
546   else
547     status = lcc_open_netsocket (c, addr);
548
549   return (status);
550 } /* }}} int lcc_open_socket */
551
552 /*
553  * Public functions
554  */
555 unsigned int lcc_version (void) /* {{{ */
556 {
557   return (LCC_VERSION);
558 } /* }}} unsigned int lcc_version */
559
560 const char *lcc_version_string (void) /* {{{ */
561 {
562   return (LCC_VERSION_STRING);
563 } /* }}} const char *lcc_version_string */
564
565 const char *lcc_version_extra (void) /* {{{ */
566 {
567   return (LCC_VERSION_EXTRA);
568 } /* }}} const char *lcc_version_extra */
569
570 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
571 {
572   lcc_connection_t *c;
573   int status;
574
575   if (address == NULL)
576     return (-1);
577
578   if (ret_con == NULL)
579     return (-1);
580
581   c = calloc (1, sizeof (*c));
582   if (c == NULL)
583     return (-1);
584
585   status = lcc_open_socket (c, address);
586   if (status != 0)
587   {
588     lcc_disconnect (c);
589     return (status);
590   }
591
592   *ret_con = c;
593   return (0);
594 } /* }}} int lcc_connect */
595
596 int lcc_disconnect (lcc_connection_t *c) /* {{{ */
597 {
598   if (c == NULL)
599     return (-1);
600
601   if (c->fh != NULL)
602   {
603     fclose (c->fh);
604     c->fh = NULL;
605   }
606
607   free (c);
608   return (0);
609 } /* }}} int lcc_disconnect */
610
611 int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
612     size_t *ret_values_num, gauge_t **ret_values, char ***ret_values_names)
613 {
614   char ident_str[6 * LCC_NAME_LEN];
615   char ident_esc[12 * LCC_NAME_LEN];
616   char command[14 * LCC_NAME_LEN];
617
618   lcc_response_t res;
619   size_t   values_num;
620   gauge_t *values = NULL;
621   char   **values_names = NULL;
622
623   size_t i;
624   int status;
625
626   if (c == NULL)
627     return (-1);
628
629   if (ident == NULL)
630   {
631     lcc_set_errno (c, EINVAL);
632     return (-1);
633   }
634
635   /* Build a commend with an escaped version of the identifier string. */
636   status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
637   if (status != 0)
638     return (status);
639
640   snprintf (command, sizeof (command), "GETVAL %s",
641       lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
642   command[sizeof (command) - 1] = 0;
643
644   /* Send talk to the daemon.. */
645   status = lcc_sendreceive (c, command, &res);
646   if (status != 0)
647     return (status);
648
649   if (res.status != 0)
650   {
651     LCC_SET_ERRSTR (c, "Server error: %s", res.message);
652     lcc_response_free (&res);
653     return (-1);
654   }
655
656   values_num = res.lines_num;
657
658 #define BAIL_OUT(e) do { \
659   lcc_set_errno (c, (e)); \
660   free (values); \
661   if (values_names != NULL) { \
662     for (i = 0; i < values_num; i++) { \
663       free (values_names[i]); \
664     } \
665   } \
666   free (values_names); \
667   lcc_response_free (&res); \
668   return (-1); \
669 } while (0)
670
671   /* If neither the values nor the names are requested, return here.. */
672   if ((ret_values == NULL) && (ret_values_names == NULL))
673   {
674     if (ret_values_num != NULL)
675       *ret_values_num = values_num;
676     lcc_response_free (&res);
677     return (0);
678   }
679
680   /* Allocate space for the values */
681   if (ret_values != NULL)
682   {
683     values = malloc (values_num * sizeof (*values));
684     if (values == NULL)
685       BAIL_OUT (ENOMEM);
686   }
687
688   if (ret_values_names != NULL)
689   {
690     values_names = calloc (values_num, sizeof (*values_names));
691     if (values_names == NULL)
692       BAIL_OUT (ENOMEM);
693   }
694
695   for (i = 0; i < res.lines_num; i++)
696   {
697     char *key;
698     char *value;
699     char *endptr;
700
701     key = res.lines[i];
702     value = strchr (key, '=');
703     if (value == NULL)
704       BAIL_OUT (EILSEQ);
705
706     *value = 0;
707     value++;
708
709     if (values != NULL)
710     {
711       endptr = NULL;
712       errno = 0;
713       values[i] = strtod (value, &endptr);
714
715       if ((endptr == value) || (errno != 0))
716         BAIL_OUT (errno);
717     }
718
719     if (values_names != NULL)
720     {
721       values_names[i] = strdup (key);
722       if (values_names[i] == NULL)
723         BAIL_OUT (ENOMEM);
724     }
725   } /* for (i = 0; i < res.lines_num; i++) */
726
727   if (ret_values_num != NULL)
728     *ret_values_num = values_num;
729   if (ret_values != NULL)
730     *ret_values = values;
731   if (ret_values_names != NULL)
732     *ret_values_names = values_names;
733
734   lcc_response_free (&res);
735
736   return (0);
737 } /* }}} int lcc_getval */
738
739 int lcc_putval (lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
740 {
741   char ident_str[6 * LCC_NAME_LEN];
742   char ident_esc[12 * LCC_NAME_LEN];
743   char command[1024] = "";
744   lcc_response_t res;
745   int status;
746   size_t i;
747
748   if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
749       || (vl->values == NULL) || (vl->values_types == NULL))
750   {
751     lcc_set_errno (c, EINVAL);
752     return (-1);
753   }
754
755   status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
756       &vl->identifier);
757   if (status != 0)
758     return (status);
759
760   SSTRCATF (command, "PUTVAL %s",
761       lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
762
763   if (vl->interval > 0.0)
764     SSTRCATF (command, " interval=%.3f", vl->interval);
765
766   if (vl->time > 0.0)
767     SSTRCATF (command, " %.3f", vl->time);
768   else
769     SSTRCAT (command, " N");
770
771   for (i = 0; i < vl->values_len; i++)
772   {
773     if (vl->values_types[i] == LCC_TYPE_COUNTER)
774       SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
775     else if (vl->values_types[i] == LCC_TYPE_GAUGE)
776     {
777       if (isnan (vl->values[i].gauge))
778         SSTRCATF (command, ":U");
779       else
780         SSTRCATF (command, ":%g", vl->values[i].gauge);
781     }
782     else if (vl->values_types[i] == LCC_TYPE_DERIVE)
783         SSTRCATF (command, ":%"PRIu64, vl->values[i].derive);
784     else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
785         SSTRCATF (command, ":%"PRIu64, vl->values[i].absolute);
786
787   } /* for (i = 0; i < vl->values_len; i++) */
788
789   status = lcc_sendreceive (c, command, &res);
790   if (status != 0)
791     return (status);
792
793   if (res.status != 0)
794   {
795     LCC_SET_ERRSTR (c, "Server error: %s", res.message);
796     lcc_response_free (&res);
797     return (-1);
798   }
799
800   lcc_response_free (&res);
801   return (0);
802 } /* }}} int lcc_putval */
803
804 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
805     lcc_identifier_t *ident, int timeout)
806 {
807   char command[1024] = "";
808   lcc_response_t res;
809   int status;
810
811   if (c == NULL)
812   {
813     lcc_set_errno (c, EINVAL);
814     return (-1);
815   }
816
817   SSTRCPY (command, "FLUSH");
818
819   if (timeout > 0)
820     SSTRCATF (command, " timeout=%i", timeout);
821
822   if (plugin != NULL)
823   {
824     char buffer[2 * LCC_NAME_LEN];
825     SSTRCATF (command, " plugin=%s",
826         lcc_strescape (buffer, plugin, sizeof (buffer)));
827   }
828
829   if (ident != NULL)
830   {
831     char ident_str[6 * LCC_NAME_LEN];
832     char ident_esc[12 * LCC_NAME_LEN];
833
834     status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
835     if (status != 0)
836       return (status);
837
838     SSTRCATF (command, " identifier=%s",
839         lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
840   }
841
842   status = lcc_sendreceive (c, command, &res);
843   if (status != 0)
844     return (status);
845
846   if (res.status != 0)
847   {
848     LCC_SET_ERRSTR (c, "Server error: %s", res.message);
849     lcc_response_free (&res);
850     return (-1);
851   }
852
853   lcc_response_free (&res);
854   return (0);
855 } /* }}} int lcc_flush */
856
857 /* TODO: Implement lcc_putnotif */
858
859 int lcc_listval (lcc_connection_t *c, /* {{{ */
860     lcc_identifier_t **ret_ident, size_t *ret_ident_num)
861 {
862   lcc_response_t res;
863   size_t i;
864   int status;
865
866   lcc_identifier_t *ident;
867   size_t ident_num;
868
869   if (c == NULL)
870     return (-1);
871
872   if ((ret_ident == NULL) || (ret_ident_num == NULL))
873   {
874     lcc_set_errno (c, EINVAL);
875     return (-1);
876   }
877
878   status = lcc_sendreceive (c, "LISTVAL", &res);
879   if (status != 0)
880     return (status);
881
882   if (res.status != 0)
883   {
884     LCC_SET_ERRSTR (c, "Server error: %s", res.message);
885     lcc_response_free (&res);
886     return (-1);
887   }
888
889   ident_num = res.lines_num;
890   ident = malloc (ident_num * sizeof (*ident));
891   if (ident == NULL)
892   {
893     lcc_response_free (&res);
894     lcc_set_errno (c, ENOMEM);
895     return (-1);
896   }
897
898   for (i = 0; i < res.lines_num; i++)
899   {
900     char *time_str;
901     char *ident_str;
902
903     /* First field is the time. */
904     time_str = res.lines[i];
905
906     /* Set `ident_str' to the beginning of the second field. */
907     ident_str = time_str;
908     while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
909       ident_str++;
910     while ((*ident_str == ' ') || (*ident_str == '\t'))
911     {
912       *ident_str = 0;
913       ident_str++;
914     }
915
916     if (*ident_str == 0)
917     {
918       lcc_set_errno (c, EILSEQ);
919       status = -1;
920       break;
921     }
922
923     status = lcc_string_to_identifier (c, ident + i, ident_str);
924     if (status != 0)
925       break;
926   }
927
928   lcc_response_free (&res);
929
930   if (status != 0)
931   {
932     free (ident);
933     return (-1);
934   }
935
936   *ret_ident = ident;
937   *ret_ident_num = ident_num;
938
939   return (0);
940 } /* }}} int lcc_listval */
941
942 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
943 {
944   if (c == NULL)
945     return ("Invalid object");
946   return (c->errbuf);
947 } /* }}} const char *lcc_strerror */
948
949 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
950     char *string, size_t string_size, const lcc_identifier_t *ident)
951 {
952   if ((string == NULL) || (string_size < 6) || (ident == NULL))
953   {
954     lcc_set_errno (c, EINVAL);
955     return (-1);
956   }
957
958   if (ident->plugin_instance[0] == 0)
959   {
960     if (ident->type_instance[0] == 0)
961       snprintf (string, string_size, "%s/%s/%s",
962           ident->host,
963           ident->plugin,
964           ident->type);
965     else
966       snprintf (string, string_size, "%s/%s/%s-%s",
967           ident->host,
968           ident->plugin,
969           ident->type,
970           ident->type_instance);
971   }
972   else
973   {
974     if (ident->type_instance[0] == 0)
975       snprintf (string, string_size, "%s/%s-%s/%s",
976           ident->host,
977           ident->plugin,
978           ident->plugin_instance,
979           ident->type);
980     else
981       snprintf (string, string_size, "%s/%s-%s/%s-%s",
982           ident->host,
983           ident->plugin,
984           ident->plugin_instance,
985           ident->type,
986           ident->type_instance);
987   }
988
989   string[string_size - 1] = 0;
990   return (0);
991 } /* }}} int lcc_identifier_to_string */
992
993 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
994     lcc_identifier_t *ident, const char *string)
995 {
996   char *string_copy;
997   char *host;
998   char *plugin;
999   char *plugin_instance;
1000   char *type;
1001   char *type_instance;
1002
1003   string_copy = strdup (string);
1004   if (string_copy == NULL)
1005   {
1006     lcc_set_errno (c, ENOMEM);
1007     return (-1);
1008   }
1009
1010   host = string_copy;
1011   plugin = strchr (host, '/');
1012   if (plugin == NULL)
1013   {
1014     LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1015     free (string_copy);
1016     return (-1);
1017   }
1018   *plugin = 0;
1019   plugin++;
1020
1021   type = strchr (plugin, '/');
1022   if (type == NULL)
1023   {
1024     LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1025     free (string_copy);
1026     return (-1);
1027   }
1028   *type = 0;
1029   type++;
1030
1031   plugin_instance = strchr (plugin, '-');
1032   if (plugin_instance != NULL)
1033   {
1034     *plugin_instance = 0;
1035     plugin_instance++;
1036   }
1037
1038   type_instance = strchr (type, '-');
1039   if (type_instance != NULL)
1040   {
1041     *type_instance = 0;
1042     type_instance++;
1043   }
1044
1045   memset (ident, 0, sizeof (*ident));
1046
1047   SSTRCPY (ident->host, host);
1048   SSTRCPY (ident->plugin, plugin);
1049   if (plugin_instance != NULL)
1050     SSTRCPY (ident->plugin_instance, plugin_instance);
1051   SSTRCPY (ident->type, type);
1052   if (type_instance != NULL)
1053     SSTRCPY (ident->type_instance, type_instance);
1054
1055   free (string_copy);
1056   return (0);
1057 } /* }}} int lcc_string_to_identifier */
1058
1059 int lcc_identifier_compare (const void *a, /* {{{ */
1060     const void *b)
1061 {
1062   const lcc_identifier_t *i0 = a;
1063   const lcc_identifier_t *i1 = b;
1064   int status;
1065
1066   if ((i0 == NULL) && (i1 == NULL))
1067     return (0);
1068   else if (i0 == NULL)
1069     return (-1);
1070   else if (i1 == NULL)
1071     return (1);
1072
1073 #define CMP_FIELD(f) do {         \
1074   status = strcmp (i0->f, i1->f); \
1075   if (status != 0)                \
1076     return (status);              \
1077 } while (0);
1078
1079     CMP_FIELD (host);
1080     CMP_FIELD (plugin);
1081     CMP_FIELD (plugin_instance);
1082     CMP_FIELD (type);
1083     CMP_FIELD (type_instance);
1084
1085 #undef CMP_FIELD
1086
1087     return (0);
1088 } /* }}} int lcc_identifier_compare */
1089
1090 int lcc_sort_identifiers (lcc_connection_t *c, /* {{{ */
1091     lcc_identifier_t *idents, size_t idents_num)
1092 {
1093   if (idents == NULL)
1094   {
1095     lcc_set_errno (c, EINVAL);
1096     return (-1);
1097   }
1098
1099   qsort (idents, idents_num, sizeof (*idents),
1100       lcc_identifier_compare);
1101   return (0);
1102 } /* }}} int lcc_sort_identifiers */
1103
1104 /* vim: set sw=2 sts=2 et fdm=marker : */