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