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