2 * libcollectdclient - src/libcollectdclient/client.c
3 * Copyright (C) 2008 Florian octo Forster
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Florian octo Forster <octo at verplant.org>
26 #if !defined(__GNUC__) || !__GNUC__
27 # define __attribute__(x) /**/
30 #include "lcc_features.h"
35 #include <sys/types.h>
36 #include <sys/socket.h>
46 /* NI_MAXHOST has been obsoleted by RFC 3493 which is a reason for SunOS 5.11
47 * to no longer define it. We'll use the old, RFC 2553 value here. */
49 # define NI_MAXHOST 1025
52 /* OpenBSD doesn't have EPROTO, FreeBSD doesn't have EILSEQ. Oh what joy! */
55 # define EILSEQ EPROTO
57 # define EILSEQ EINVAL
61 /* Secure/static macros. They work like `strcpy' and `strcat', but assure null
62 * termination. They work for static buffers only, because they use `sizeof'.
63 * The `SSTRCATF' combines the functionality of `snprintf' and `strcat' which
64 * is very useful to add formatted stuff to the end of a buffer. */
65 #define SSTRCPY(d,s) do { \
66 strncpy ((d), (s), sizeof (d)); \
67 (d)[sizeof (d) - 1] = 0; \
70 #define SSTRCAT(d,s) do { \
71 size_t _l = strlen (d); \
72 strncpy ((d) + _l, (s), sizeof (d) - _l); \
73 (d)[sizeof (d) - 1] = 0; \
76 #define SSTRCATF(d, ...) do { \
77 char _b[sizeof (d)]; \
78 snprintf (_b, sizeof (_b), __VA_ARGS__); \
79 _b[sizeof (_b) - 1] = 0; \
84 #define LCC_SET_ERRSTR(c, ...) do { \
85 snprintf ((c)->errbuf, sizeof ((c)->errbuf), __VA_ARGS__); \
86 (c)->errbuf[sizeof ((c)->errbuf) - 1] = 0; \
90 # define LCC_DEBUG(...) printf (__VA_ARGS__)
92 # define LCC_DEBUG(...) /**/
98 struct lcc_connection_s
104 struct lcc_response_s
111 typedef struct lcc_response_s lcc_response_t;
116 /* Even though Posix requires "strerror_r" to return an "int",
117 * some systems (e.g. the GNU libc) return a "char *" _and_
118 * ignore the second argument ... -tokkee */
119 static char *sstrerror (int errnum, char *buf, size_t buflen)
124 snprintf (buf, buflen, "Error #%i; strerror_r is not available.", errnum);
125 /* #endif !HAVE_STRERROR_R */
127 #elif STRERROR_R_CHAR_P
130 temp = strerror_r (errnum, buf, buflen);
133 if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
134 strncpy (buf, temp, buflen);
136 strncpy (buf, "strerror_r did not return "
137 "an error message", buflen);
140 /* #endif STRERROR_R_CHAR_P */
143 if (strerror_r (errnum, buf, buflen) != 0)
145 snprintf (buf, buflen, "Error #%i; "
146 "Additionally, strerror_r failed.",
149 #endif /* STRERROR_R_CHAR_P */
154 } /* char *sstrerror */
156 static int lcc_set_errno (lcc_connection_t *c, int err) /* {{{ */
161 sstrerror (err, c->errbuf, sizeof (c->errbuf));
162 c->errbuf[sizeof (c->errbuf) - 1] = 0;
165 } /* }}} int lcc_set_errno */
167 static char *lcc_strescape (char *dest, const char *src, size_t dest_size) /* {{{ */
172 if ((dest == NULL) || (src == NULL))
178 assert (dest_size >= 3);
180 dest[dest_pos] = '"';
185 if ((dest_pos == (dest_size - 2))
186 || (src[src_pos] == 0))
189 if ((src[src_pos] == '"') || (src[src_pos] == '\\'))
191 /* Check if there is enough space for both characters.. */
192 if (dest_pos == (dest_size - 3))
195 dest[dest_pos] = '\\';
199 dest[dest_pos] = src[src_pos];
204 assert (dest_pos <= (dest_size - 2));
206 dest[dest_pos] = '"';
214 } /* }}} char *lcc_strescape */
216 /* lcc_chomp: Removes all control-characters at the end of a string. */
217 static void lcc_chomp (char *str) /* {{{ */
221 str_len = strlen (str);
224 if (str[str_len - 1] >= 32)
226 str[str_len - 1] = 0;
229 } /* }}} void lcc_chomp */
231 static void lcc_response_free (lcc_response_t *res) /* {{{ */
238 for (i = 0; i < res->lines_num; i++)
239 free (res->lines[i]);
242 } /* }}} void lcc_response_free */
244 static int lcc_send (lcc_connection_t *c, const char *command) /* {{{ */
248 LCC_DEBUG ("send: --> %s\n", command);
250 status = fprintf (c->fh, "%s\r\n", command);
253 lcc_set_errno (c, errno);
258 } /* }}} int lcc_send */
260 static int lcc_receive (lcc_connection_t *c, /* {{{ */
261 lcc_response_t *ret_res)
268 memset (&res, 0, sizeof (res));
270 /* Read the first line, containing the status and a message */
271 ptr = fgets (buffer, sizeof (buffer), c->fh);
274 lcc_set_errno (c, errno);
278 LCC_DEBUG ("receive: <-- %s\n", buffer);
280 /* Convert the leading status to an integer and make `ptr' to point to the
281 * beginning of the message. */
284 res.status = strtol (buffer, &ptr, 0);
285 if ((errno != 0) || (ptr == &buffer[0]))
287 lcc_set_errno (c, errno);
291 /* Skip white spaces after the status number */
292 while ((*ptr == ' ') || (*ptr == '\t'))
295 /* Now copy the message. */
296 strncpy (res.message, ptr, sizeof (res.message));
297 res.message[sizeof (res.message) - 1] = 0;
299 /* Error or no lines follow: We're done. */
302 memcpy (ret_res, &res, sizeof (res));
306 /* Allocate space for the char-pointers */
307 res.lines_num = (size_t) res.status;
309 res.lines = (char **) malloc (res.lines_num * sizeof (char *));
310 if (res.lines == NULL)
312 lcc_set_errno (c, ENOMEM);
316 /* Now receive all the lines */
317 for (i = 0; i < res.lines_num; i++)
319 ptr = fgets (buffer, sizeof (buffer), c->fh);
322 lcc_set_errno (c, errno);
326 LCC_DEBUG ("receive: <-- %s\n", buffer);
328 res.lines[i] = strdup (buffer);
329 if (res.lines[i] == NULL)
331 lcc_set_errno (c, ENOMEM);
336 /* Check if the for-loop exited with an error. */
337 if (i < res.lines_num)
348 memcpy (ret_res, &res, sizeof (res));
350 } /* }}} int lcc_receive */
352 static int lcc_sendreceive (lcc_connection_t *c, /* {{{ */
353 const char *command, lcc_response_t *ret_res)
360 lcc_set_errno (c, EBADF);
364 status = lcc_send (c, command);
368 memset (&res, 0, sizeof (res));
369 status = lcc_receive (c, &res);
371 memcpy (ret_res, &res, sizeof (*ret_res));
374 } /* }}} int lcc_sendreceive */
376 static int lcc_open_unixsocket (lcc_connection_t *c, const char *path) /* {{{ */
378 struct sockaddr_un sa;
383 assert (c->fh == NULL);
384 assert (path != NULL);
386 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
388 fd = socket (AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
391 lcc_set_errno (c, errno);
395 memset (&sa, 0, sizeof (sa));
396 sa.sun_family = AF_UNIX;
397 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
399 status = connect (fd, (struct sockaddr *) &sa, sizeof (sa));
402 lcc_set_errno (c, errno);
407 c->fh = fdopen (fd, "r+");
410 lcc_set_errno (c, errno);
416 } /* }}} int lcc_open_unixsocket */
418 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
419 const char *addr_orig)
421 struct addrinfo ai_hints;
422 struct addrinfo *ai_res;
423 struct addrinfo *ai_ptr;
424 char addr_copy[NI_MAXHOST];
431 assert (c->fh == NULL);
432 assert (addr_orig != NULL);
434 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
435 addr_copy[sizeof(addr_copy) - 1] = '\0';
438 memset (&ai_hints, 0, sizeof (ai_hints));
439 ai_hints.ai_flags = 0;
441 ai_hints.ai_flags |= AI_ADDRCONFIG;
443 ai_hints.ai_family = AF_UNSPEC;
444 ai_hints.ai_socktype = SOCK_STREAM;
447 if (*addr == '[') /* IPv6+port format */
449 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
452 port = strchr (addr, ']');
455 LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
467 LCC_SET_ERRSTR (c, "garbage after address: %s", port);
470 } /* if (*addr = ']') */
471 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
473 port = strrchr (addr, ':');
482 status = getaddrinfo (addr,
483 port == NULL ? LCC_DEFAULT_PORT : port,
487 LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
491 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
493 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
501 status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
510 c->fh = fdopen (fd, "r+");
519 assert (status == 0);
525 lcc_set_errno (c, status);
530 } /* }}} int lcc_open_netsocket */
532 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
540 assert (c->fh == NULL);
541 assert (addr != NULL);
543 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
544 status = lcc_open_unixsocket (c, addr + strlen ("unix:"));
545 else if (addr[0] == '/')
546 status = lcc_open_unixsocket (c, addr);
548 status = lcc_open_netsocket (c, addr);
551 } /* }}} int lcc_open_socket */
556 unsigned int lcc_version (void) /* {{{ */
558 return (LCC_VERSION);
559 } /* }}} unsigned int lcc_version */
561 const char *lcc_version_string (void) /* {{{ */
563 return (LCC_VERSION_STRING);
564 } /* }}} const char *lcc_version_string */
566 const char *lcc_version_extra (void) /* {{{ */
568 return (LCC_VERSION_EXTRA);
569 } /* }}} const char *lcc_version_extra */
571 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
582 c = (lcc_connection_t *) malloc (sizeof (*c));
585 memset (c, 0, sizeof (*c));
587 status = lcc_open_socket (c, address);
596 } /* }}} int lcc_connect */
598 int lcc_disconnect (lcc_connection_t *c) /* {{{ */
611 } /* }}} int lcc_disconnect */
613 int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
614 size_t *ret_values_num, gauge_t **ret_values, char ***ret_values_names)
616 char ident_str[6 * LCC_NAME_LEN];
617 char ident_esc[12 * LCC_NAME_LEN];
618 char command[14 * LCC_NAME_LEN];
622 gauge_t *values = NULL;
623 char **values_names = NULL;
633 lcc_set_errno (c, EINVAL);
637 /* Build a commend with an escaped version of the identifier string. */
638 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
642 snprintf (command, sizeof (command), "GETVAL %s",
643 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
644 command[sizeof (command) - 1] = 0;
646 /* Send talk to the daemon.. */
647 status = lcc_sendreceive (c, command, &res);
653 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
654 lcc_response_free (&res);
658 values_num = res.lines_num;
660 #define BAIL_OUT(e) do { \
661 lcc_set_errno (c, (e)); \
663 if (values_names != NULL) { \
664 for (i = 0; i < values_num; i++) { \
665 free (values_names[i]); \
668 free (values_names); \
669 lcc_response_free (&res); \
673 /* If neither the values nor the names are requested, return here.. */
674 if ((ret_values == NULL) && (ret_values_names == NULL))
676 if (ret_values_num != NULL)
677 *ret_values_num = values_num;
678 lcc_response_free (&res);
682 /* Allocate space for the values */
683 if (ret_values != NULL)
685 values = (gauge_t *) malloc (values_num * sizeof (*values));
690 if (ret_values_names != NULL)
692 values_names = (char **) calloc (values_num, sizeof (*values_names));
693 if (values_names == NULL)
697 for (i = 0; i < res.lines_num; i++)
704 value = strchr (key, '=');
715 values[i] = strtod (value, &endptr);
717 if ((endptr == value) || (errno != 0))
721 if (values_names != NULL)
723 values_names[i] = strdup (key);
724 if (values_names[i] == NULL)
727 } /* for (i = 0; i < res.lines_num; i++) */
729 if (ret_values_num != NULL)
730 *ret_values_num = values_num;
731 if (ret_values != NULL)
732 *ret_values = values;
733 if (ret_values_names != NULL)
734 *ret_values_names = values_names;
736 lcc_response_free (&res);
739 } /* }}} int lcc_getval */
741 int lcc_putval (lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
743 char ident_str[6 * LCC_NAME_LEN];
744 char ident_esc[12 * LCC_NAME_LEN];
745 char command[1024] = "";
750 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
751 || (vl->values == NULL) || (vl->values_types == NULL))
753 lcc_set_errno (c, EINVAL);
757 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
762 SSTRCATF (command, "PUTVAL %s",
763 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
765 if (vl->interval > 0)
766 SSTRCATF (command, " interval=%i", vl->interval);
769 SSTRCATF (command, " %u", (unsigned int) vl->time);
771 SSTRCAT (command, " N");
773 for (i = 0; i < vl->values_len; i++)
775 if (vl->values_types[i] == LCC_TYPE_COUNTER)
776 SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
777 else if (vl->values_types[i] == LCC_TYPE_GAUGE)
779 if (isnan (vl->values[i].gauge))
780 SSTRCATF (command, ":U");
782 SSTRCATF (command, ":%g", vl->values[i].gauge);
784 else if (vl->values_types[i] == LCC_TYPE_DERIVE)
785 SSTRCATF (command, ":%"PRIu64, vl->values[i].derive);
786 else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
787 SSTRCATF (command, ":%"PRIu64, vl->values[i].absolute);
789 } /* for (i = 0; i < vl->values_len; i++) */
791 status = lcc_sendreceive (c, command, &res);
797 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
798 lcc_response_free (&res);
802 lcc_response_free (&res);
804 } /* }}} int lcc_putval */
806 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
807 lcc_identifier_t *ident, int timeout)
809 char command[1024] = "";
815 lcc_set_errno (c, EINVAL);
819 SSTRCPY (command, "FLUSH");
822 SSTRCATF (command, " timeout=%i", timeout);
826 char buffer[2 * LCC_NAME_LEN];
827 SSTRCATF (command, " plugin=%s",
828 lcc_strescape (buffer, plugin, sizeof (buffer)));
833 char ident_str[6 * LCC_NAME_LEN];
834 char ident_esc[12 * LCC_NAME_LEN];
836 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
840 SSTRCATF (command, " identifier=%s",
841 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
844 status = lcc_sendreceive (c, command, &res);
850 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
851 lcc_response_free (&res);
855 lcc_response_free (&res);
857 } /* }}} int lcc_flush */
859 /* TODO: Implement lcc_putnotif */
861 int lcc_listval (lcc_connection_t *c, /* {{{ */
862 lcc_identifier_t **ret_ident, size_t *ret_ident_num)
868 lcc_identifier_t *ident;
874 if ((ret_ident == NULL) || (ret_ident_num == NULL))
876 lcc_set_errno (c, EINVAL);
880 status = lcc_sendreceive (c, "LISTVAL", &res);
886 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
887 lcc_response_free (&res);
891 ident_num = res.lines_num;
892 ident = (lcc_identifier_t *) malloc (ident_num * sizeof (*ident));
895 lcc_response_free (&res);
896 lcc_set_errno (c, ENOMEM);
900 for (i = 0; i < res.lines_num; i++)
905 /* First field is the time. */
906 time_str = res.lines[i];
908 /* Set `ident_str' to the beginning of the second field. */
909 ident_str = time_str;
910 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
912 while ((*ident_str == ' ') || (*ident_str == '\t'))
920 lcc_set_errno (c, EILSEQ);
925 status = lcc_string_to_identifier (c, ident + i, ident_str);
930 lcc_response_free (&res);
939 *ret_ident_num = ident_num;
942 } /* }}} int lcc_listval */
944 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
947 return ("Invalid object");
949 } /* }}} const char *lcc_strerror */
951 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
952 char *string, size_t string_size, const lcc_identifier_t *ident)
954 if ((string == NULL) || (string_size < 6) || (ident == NULL))
956 lcc_set_errno (c, EINVAL);
960 if (ident->plugin_instance[0] == 0)
962 if (ident->type_instance[0] == 0)
963 snprintf (string, string_size, "%s/%s/%s",
968 snprintf (string, string_size, "%s/%s/%s-%s",
972 ident->type_instance);
976 if (ident->type_instance[0] == 0)
977 snprintf (string, string_size, "%s/%s-%s/%s",
980 ident->plugin_instance,
983 snprintf (string, string_size, "%s/%s-%s/%s-%s",
986 ident->plugin_instance,
988 ident->type_instance);
991 string[string_size - 1] = 0;
993 } /* }}} int lcc_identifier_to_string */
995 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
996 lcc_identifier_t *ident, const char *string)
1001 char *plugin_instance;
1003 char *type_instance;
1005 string_copy = strdup (string);
1006 if (string_copy == NULL)
1008 lcc_set_errno (c, ENOMEM);
1013 plugin = strchr (host, '/');
1016 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1023 type = strchr (plugin, '/');
1026 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1033 plugin_instance = strchr (plugin, '-');
1034 if (plugin_instance != NULL)
1036 *plugin_instance = 0;
1040 type_instance = strchr (type, '-');
1041 if (type_instance != NULL)
1047 memset (ident, 0, sizeof (*ident));
1049 SSTRCPY (ident->host, host);
1050 SSTRCPY (ident->plugin, plugin);
1051 if (plugin_instance != NULL)
1052 SSTRCPY (ident->plugin_instance, plugin_instance);
1053 SSTRCPY (ident->type, type);
1054 if (type_instance != NULL)
1055 SSTRCPY (ident->type_instance, type_instance);
1059 } /* }}} int lcc_string_to_identifier */
1061 /* vim: set sw=2 sts=2 et fdm=marker : */