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