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 int lcc_identifier_cmp (const void *a, const void *b)
233 const lcc_identifier_t *ident_a, *ident_b;
240 status = strcasecmp (ident_a->host, ident_b->host);
244 status = strcmp (ident_a->plugin, ident_b->plugin);
248 if ((*ident_a->plugin_instance != '\0') || (*ident_b->plugin_instance != '\0'))
250 if (*ident_a->plugin_instance == '\0')
252 else if (*ident_b->plugin_instance == '\0')
255 status = strcmp (ident_a->plugin_instance, ident_b->plugin_instance);
260 status = strcmp (ident_a->type, ident_b->type);
264 if ((*ident_a->type_instance != '\0') || (*ident_b->type_instance != '\0'))
266 if (*ident_a->type_instance == '\0')
268 else if (*ident_b->type_instance == '\0')
271 status = strcmp (ident_a->type_instance, ident_b->type_instance);
276 } /* }}} int lcc_identifier_cmp */
278 static void lcc_response_free (lcc_response_t *res) /* {{{ */
285 for (i = 0; i < res->lines_num; i++)
286 free (res->lines[i]);
289 } /* }}} void lcc_response_free */
291 static int lcc_send (lcc_connection_t *c, const char *command) /* {{{ */
295 LCC_DEBUG ("send: --> %s\n", command);
297 status = fprintf (c->fh, "%s\r\n", command);
300 lcc_set_errno (c, errno);
305 } /* }}} int lcc_send */
307 static int lcc_receive (lcc_connection_t *c, /* {{{ */
308 lcc_response_t *ret_res)
315 memset (&res, 0, sizeof (res));
317 /* Read the first line, containing the status and a message */
318 ptr = fgets (buffer, sizeof (buffer), c->fh);
321 lcc_set_errno (c, errno);
325 LCC_DEBUG ("receive: <-- %s\n", buffer);
327 /* Convert the leading status to an integer and make `ptr' to point to the
328 * beginning of the message. */
331 res.status = strtol (buffer, &ptr, 0);
332 if ((errno != 0) || (ptr == &buffer[0]))
334 lcc_set_errno (c, errno);
338 /* Skip white spaces after the status number */
339 while ((*ptr == ' ') || (*ptr == '\t'))
342 /* Now copy the message. */
343 strncpy (res.message, ptr, sizeof (res.message));
344 res.message[sizeof (res.message) - 1] = 0;
346 /* Error or no lines follow: We're done. */
349 memcpy (ret_res, &res, sizeof (res));
353 /* Allocate space for the char-pointers */
354 res.lines_num = (size_t) res.status;
356 res.lines = (char **) malloc (res.lines_num * sizeof (char *));
357 if (res.lines == NULL)
359 lcc_set_errno (c, ENOMEM);
363 /* Now receive all the lines */
364 for (i = 0; i < res.lines_num; i++)
366 ptr = fgets (buffer, sizeof (buffer), c->fh);
369 lcc_set_errno (c, errno);
373 LCC_DEBUG ("receive: <-- %s\n", buffer);
375 res.lines[i] = strdup (buffer);
376 if (res.lines[i] == NULL)
378 lcc_set_errno (c, ENOMEM);
383 /* Check if the for-loop exited with an error. */
384 if (i < res.lines_num)
395 memcpy (ret_res, &res, sizeof (res));
397 } /* }}} int lcc_receive */
399 static int lcc_sendreceive (lcc_connection_t *c, /* {{{ */
400 const char *command, lcc_response_t *ret_res)
407 lcc_set_errno (c, EBADF);
411 status = lcc_send (c, command);
415 memset (&res, 0, sizeof (res));
416 status = lcc_receive (c, &res);
418 memcpy (ret_res, &res, sizeof (*ret_res));
421 } /* }}} int lcc_sendreceive */
423 static int lcc_open_unixsocket (lcc_connection_t *c, const char *path) /* {{{ */
425 struct sockaddr_un sa;
430 assert (c->fh == NULL);
431 assert (path != NULL);
433 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
435 fd = socket (AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
438 lcc_set_errno (c, errno);
442 memset (&sa, 0, sizeof (sa));
443 sa.sun_family = AF_UNIX;
444 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
446 status = connect (fd, (struct sockaddr *) &sa, sizeof (sa));
449 lcc_set_errno (c, errno);
454 c->fh = fdopen (fd, "r+");
457 lcc_set_errno (c, errno);
463 } /* }}} int lcc_open_unixsocket */
465 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
466 const char *addr_orig)
468 struct addrinfo ai_hints;
469 struct addrinfo *ai_res;
470 struct addrinfo *ai_ptr;
471 char addr_copy[NI_MAXHOST];
478 assert (c->fh == NULL);
479 assert (addr_orig != NULL);
481 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
482 addr_copy[sizeof(addr_copy) - 1] = '\0';
485 memset (&ai_hints, 0, sizeof (ai_hints));
486 ai_hints.ai_flags = 0;
488 ai_hints.ai_flags |= AI_ADDRCONFIG;
490 ai_hints.ai_family = AF_UNSPEC;
491 ai_hints.ai_socktype = SOCK_STREAM;
494 if (*addr == '[') /* IPv6+port format */
496 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
499 port = strchr (addr, ']');
502 LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
514 LCC_SET_ERRSTR (c, "garbage after address: %s", port);
517 } /* if (*addr = ']') */
518 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
520 port = strrchr (addr, ':');
529 status = getaddrinfo (addr,
530 port == NULL ? LCC_DEFAULT_PORT : port,
534 LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
538 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
540 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
548 status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
557 c->fh = fdopen (fd, "r+");
566 assert (status == 0);
572 lcc_set_errno (c, status);
577 } /* }}} int lcc_open_netsocket */
579 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
587 assert (c->fh == NULL);
588 assert (addr != NULL);
590 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
591 status = lcc_open_unixsocket (c, addr + strlen ("unix:"));
592 else if (addr[0] == '/')
593 status = lcc_open_unixsocket (c, addr);
595 status = lcc_open_netsocket (c, addr);
598 } /* }}} int lcc_open_socket */
603 unsigned int lcc_version (void) /* {{{ */
605 return (LCC_VERSION);
606 } /* }}} unsigned int lcc_version */
608 const char *lcc_version_string (void) /* {{{ */
610 return (LCC_VERSION_STRING);
611 } /* }}} const char *lcc_version_string */
613 const char *lcc_version_extra (void) /* {{{ */
615 return (LCC_VERSION_EXTRA);
616 } /* }}} const char *lcc_version_extra */
618 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
629 c = (lcc_connection_t *) malloc (sizeof (*c));
632 memset (c, 0, sizeof (*c));
634 status = lcc_open_socket (c, address);
643 } /* }}} int lcc_connect */
645 int lcc_disconnect (lcc_connection_t *c) /* {{{ */
658 } /* }}} int lcc_disconnect */
660 int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
661 size_t *ret_values_num, gauge_t **ret_values, char ***ret_values_names)
663 char ident_str[6 * LCC_NAME_LEN];
664 char ident_esc[12 * LCC_NAME_LEN];
665 char command[14 * LCC_NAME_LEN];
669 gauge_t *values = NULL;
670 char **values_names = NULL;
680 lcc_set_errno (c, EINVAL);
684 /* Build a commend with an escaped version of the identifier string. */
685 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
689 snprintf (command, sizeof (command), "GETVAL %s",
690 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
691 command[sizeof (command) - 1] = 0;
693 /* Send talk to the daemon.. */
694 status = lcc_sendreceive (c, command, &res);
700 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
701 lcc_response_free (&res);
705 values_num = res.lines_num;
707 #define BAIL_OUT(e) do { \
708 lcc_set_errno (c, (e)); \
710 if (values_names != NULL) { \
711 for (i = 0; i < values_num; i++) { \
712 free (values_names[i]); \
715 free (values_names); \
716 lcc_response_free (&res); \
720 /* If neither the values nor the names are requested, return here.. */
721 if ((ret_values == NULL) && (ret_values_names == NULL))
723 if (ret_values_num != NULL)
724 *ret_values_num = values_num;
725 lcc_response_free (&res);
729 /* Allocate space for the values */
730 if (ret_values != NULL)
732 values = (gauge_t *) malloc (values_num * sizeof (*values));
737 if (ret_values_names != NULL)
739 values_names = (char **) calloc (values_num, sizeof (*values_names));
740 if (values_names == NULL)
744 for (i = 0; i < res.lines_num; i++)
751 value = strchr (key, '=');
762 values[i] = strtod (value, &endptr);
764 if ((endptr == value) || (errno != 0))
768 if (values_names != NULL)
770 values_names[i] = strdup (key);
771 if (values_names[i] == NULL)
774 } /* for (i = 0; i < res.lines_num; i++) */
776 if (ret_values_num != NULL)
777 *ret_values_num = values_num;
778 if (ret_values != NULL)
779 *ret_values = values;
780 if (ret_values_names != NULL)
781 *ret_values_names = values_names;
783 lcc_response_free (&res);
786 } /* }}} int lcc_getval */
788 int lcc_putval (lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
790 char ident_str[6 * LCC_NAME_LEN];
791 char ident_esc[12 * LCC_NAME_LEN];
792 char command[1024] = "";
797 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
798 || (vl->values == NULL) || (vl->values_types == NULL))
800 lcc_set_errno (c, EINVAL);
804 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
809 SSTRCATF (command, "PUTVAL %s",
810 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
812 if (vl->interval > 0)
813 SSTRCATF (command, " interval=%i", vl->interval);
816 SSTRCATF (command, " %u", (unsigned int) vl->time);
818 SSTRCAT (command, " N");
820 for (i = 0; i < vl->values_len; i++)
822 if (vl->values_types[i] == LCC_TYPE_COUNTER)
823 SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
824 else if (vl->values_types[i] == LCC_TYPE_GAUGE)
826 if (isnan (vl->values[i].gauge))
827 SSTRCATF (command, ":U");
829 SSTRCATF (command, ":%g", vl->values[i].gauge);
831 else if (vl->values_types[i] == LCC_TYPE_DERIVE)
832 SSTRCATF (command, ":%"PRIu64, vl->values[i].derive);
833 else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
834 SSTRCATF (command, ":%"PRIu64, vl->values[i].absolute);
836 } /* for (i = 0; i < vl->values_len; i++) */
838 status = lcc_sendreceive (c, command, &res);
844 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
845 lcc_response_free (&res);
849 lcc_response_free (&res);
851 } /* }}} int lcc_putval */
853 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
854 lcc_identifier_t *ident, int timeout)
856 char command[1024] = "";
862 lcc_set_errno (c, EINVAL);
866 SSTRCPY (command, "FLUSH");
869 SSTRCATF (command, " timeout=%i", timeout);
873 char buffer[2 * LCC_NAME_LEN];
874 SSTRCATF (command, " plugin=%s",
875 lcc_strescape (buffer, plugin, sizeof (buffer)));
880 char ident_str[6 * LCC_NAME_LEN];
881 char ident_esc[12 * LCC_NAME_LEN];
883 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
887 SSTRCATF (command, " identifier=%s",
888 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
891 status = lcc_sendreceive (c, command, &res);
897 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
898 lcc_response_free (&res);
902 lcc_response_free (&res);
904 } /* }}} int lcc_flush */
906 /* TODO: Implement lcc_putnotif */
908 int lcc_listval (lcc_connection_t *c, /* {{{ */
909 lcc_identifier_t **ret_ident, size_t *ret_ident_num)
915 lcc_identifier_t *ident;
921 if ((ret_ident == NULL) || (ret_ident_num == NULL))
923 lcc_set_errno (c, EINVAL);
927 status = lcc_sendreceive (c, "LISTVAL", &res);
933 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
934 lcc_response_free (&res);
938 ident_num = res.lines_num;
939 ident = (lcc_identifier_t *) malloc (ident_num * sizeof (*ident));
942 lcc_response_free (&res);
943 lcc_set_errno (c, ENOMEM);
947 for (i = 0; i < res.lines_num; i++)
952 /* First field is the time. */
953 time_str = res.lines[i];
955 /* Set `ident_str' to the beginning of the second field. */
956 ident_str = time_str;
957 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
959 while ((*ident_str == ' ') || (*ident_str == '\t'))
967 lcc_set_errno (c, EILSEQ);
972 status = lcc_string_to_identifier (c, ident + i, ident_str);
977 lcc_response_free (&res);
986 *ret_ident_num = ident_num;
989 } /* }}} int lcc_listval */
991 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
994 return ("Invalid object");
996 } /* }}} const char *lcc_strerror */
998 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
999 char *string, size_t string_size, const lcc_identifier_t *ident)
1001 if ((string == NULL) || (string_size < 6) || (ident == NULL))
1003 lcc_set_errno (c, EINVAL);
1007 if (ident->plugin_instance[0] == 0)
1009 if (ident->type_instance[0] == 0)
1010 snprintf (string, string_size, "%s/%s/%s",
1015 snprintf (string, string_size, "%s/%s/%s-%s",
1019 ident->type_instance);
1023 if (ident->type_instance[0] == 0)
1024 snprintf (string, string_size, "%s/%s-%s/%s",
1027 ident->plugin_instance,
1030 snprintf (string, string_size, "%s/%s-%s/%s-%s",
1033 ident->plugin_instance,
1035 ident->type_instance);
1038 string[string_size - 1] = 0;
1040 } /* }}} int lcc_identifier_to_string */
1042 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
1043 lcc_identifier_t *ident, const char *string)
1048 char *plugin_instance;
1050 char *type_instance;
1052 string_copy = strdup (string);
1053 if (string_copy == NULL)
1055 lcc_set_errno (c, ENOMEM);
1060 plugin = strchr (host, '/');
1063 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1070 type = strchr (plugin, '/');
1073 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1080 plugin_instance = strchr (plugin, '-');
1081 if (plugin_instance != NULL)
1083 *plugin_instance = 0;
1087 type_instance = strchr (type, '-');
1088 if (type_instance != NULL)
1094 memset (ident, 0, sizeof (*ident));
1096 SSTRCPY (ident->host, host);
1097 SSTRCPY (ident->plugin, plugin);
1098 if (plugin_instance != NULL)
1099 SSTRCPY (ident->plugin_instance, plugin_instance);
1100 SSTRCPY (ident->type, type);
1101 if (type_instance != NULL)
1102 SSTRCPY (ident->type_instance, type_instance);
1106 } /* }}} int lcc_string_to_identifier */
1108 int lcc_sort_identifiers (lcc_connection_t *c, /* {{{ */
1109 lcc_identifier_t *idents, size_t idents_num)
1113 lcc_set_errno (c, EINVAL);
1117 qsort (idents, idents_num, sizeof (*idents), lcc_identifier_cmp);
1119 } /* }}} int lcc_sort_identifiers */
1121 /* vim: set sw=2 sts=2 et fdm=marker : */