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