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