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 /* lcc_strdup: Since `strdup' is an XSI extension, we provide our own version
169 __attribute__((malloc, nonnull (1)))
170 static char *lcc_strdup (const char *str) /* {{{ */
175 strsize = strlen (str) + 1;
176 ret = (char *) malloc (strsize);
178 memcpy (ret, str, strsize);
180 } /* }}} char *lcc_strdup */
182 __attribute__((nonnull (1, 2)))
183 static char *lcc_strescape (char *dest, const char *src, size_t dest_size) /* {{{ */
191 assert (dest_size >= 3);
193 dest[dest_pos] = '"';
198 if ((dest_pos == (dest_size - 2))
199 || (src[src_pos] == 0))
202 if ((src[src_pos] == '"') || (src[src_pos] == '\\'))
204 /* Check if there is enough space for both characters.. */
205 if (dest_pos == (dest_size - 3))
208 dest[dest_pos] = '\\';
212 dest[dest_pos] = src[src_pos];
217 assert (dest_pos <= (dest_size - 2));
219 dest[dest_pos] = '"';
227 } /* }}} char *lcc_strescape */
229 /* lcc_chomp: Removes all control-characters at the end of a string. */
230 static void lcc_chomp (char *str) /* {{{ */
234 str_len = strlen (str);
237 if (str[str_len - 1] >= 32)
239 str[str_len - 1] = 0;
242 } /* }}} void lcc_chomp */
244 static void lcc_response_free (lcc_response_t *res) /* {{{ */
251 for (i = 0; i < res->lines_num; i++)
252 free (res->lines[i]);
255 } /* }}} void lcc_response_free */
257 static int lcc_send (lcc_connection_t *c, const char *command) /* {{{ */
261 LCC_DEBUG ("send: --> %s\n", command);
263 status = fprintf (c->fh, "%s\r\n", command);
266 lcc_set_errno (c, errno);
271 } /* }}} int lcc_send */
273 static int lcc_receive (lcc_connection_t *c, /* {{{ */
274 lcc_response_t *ret_res)
281 memset (&res, 0, sizeof (res));
283 /* Read the first line, containing the status and a message */
284 ptr = fgets (buffer, sizeof (buffer), c->fh);
287 lcc_set_errno (c, errno);
291 LCC_DEBUG ("receive: <-- %s\n", buffer);
293 /* Convert the leading status to an integer and make `ptr' to point to the
294 * beginning of the message. */
297 res.status = strtol (buffer, &ptr, 0);
298 if ((errno != 0) || (ptr == &buffer[0]))
300 lcc_set_errno (c, errno);
304 /* Skip white spaces after the status number */
305 while ((*ptr == ' ') || (*ptr == '\t'))
308 /* Now copy the message. */
309 strncpy (res.message, ptr, sizeof (res.message));
310 res.message[sizeof (res.message) - 1] = 0;
312 /* Error or no lines follow: We're done. */
315 memcpy (ret_res, &res, sizeof (res));
319 /* Allocate space for the char-pointers */
320 res.lines_num = (size_t) res.status;
322 res.lines = (char **) malloc (res.lines_num * sizeof (char *));
323 if (res.lines == NULL)
325 lcc_set_errno (c, ENOMEM);
329 /* Now receive all the lines */
330 for (i = 0; i < res.lines_num; i++)
332 ptr = fgets (buffer, sizeof (buffer), c->fh);
335 lcc_set_errno (c, errno);
339 LCC_DEBUG ("receive: <-- %s\n", buffer);
341 res.lines[i] = lcc_strdup (buffer);
342 if (res.lines[i] == NULL)
344 lcc_set_errno (c, ENOMEM);
349 /* Check if the for-loop exited with an error. */
350 if (i < res.lines_num)
361 memcpy (ret_res, &res, sizeof (res));
363 } /* }}} int lcc_receive */
365 static int lcc_sendreceive (lcc_connection_t *c, /* {{{ */
366 const char *command, lcc_response_t *ret_res)
373 lcc_set_errno (c, EBADF);
377 status = lcc_send (c, command);
381 memset (&res, 0, sizeof (res));
382 status = lcc_receive (c, &res);
384 memcpy (ret_res, &res, sizeof (*ret_res));
387 } /* }}} int lcc_sendreceive */
389 static int lcc_open_unixsocket (lcc_connection_t *c, const char *path) /* {{{ */
391 struct sockaddr_un sa;
396 assert (c->fh == NULL);
397 assert (path != NULL);
399 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
401 fd = socket (AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
404 lcc_set_errno (c, errno);
408 memset (&sa, 0, sizeof (sa));
409 sa.sun_family = AF_UNIX;
410 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
412 status = connect (fd, (struct sockaddr *) &sa, sizeof (sa));
415 lcc_set_errno (c, errno);
420 c->fh = fdopen (fd, "r+");
423 lcc_set_errno (c, errno);
429 } /* }}} int lcc_open_unixsocket */
431 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
432 const char *addr_orig)
434 struct addrinfo ai_hints;
435 struct addrinfo *ai_res;
436 struct addrinfo *ai_ptr;
437 char addr_copy[NI_MAXHOST];
444 assert (c->fh == NULL);
445 assert (addr_orig != NULL);
447 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
448 addr_copy[sizeof(addr_copy) - 1] = '\0';
451 memset (&ai_hints, 0, sizeof (ai_hints));
452 ai_hints.ai_flags = 0;
454 ai_hints.ai_flags |= AI_ADDRCONFIG;
456 ai_hints.ai_family = AF_UNSPEC;
457 ai_hints.ai_socktype = SOCK_STREAM;
460 if (*addr == '[') /* IPv6+port format */
462 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
465 port = strchr (addr, ']');
468 LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
480 LCC_SET_ERRSTR (c, "garbage after address: %s", port);
483 } /* if (*addr = ']') */
484 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
486 port = strrchr (addr, ':');
495 status = getaddrinfo (addr,
496 port == NULL ? LCC_DEFAULT_PORT : port,
500 LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
504 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
506 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
514 status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
523 c->fh = fdopen (fd, "r+");
532 assert (status == 0);
538 lcc_set_errno (c, status);
543 } /* }}} int lcc_open_netsocket */
545 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
553 assert (c->fh == NULL);
554 assert (addr != NULL);
556 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
557 status = lcc_open_unixsocket (c, addr + strlen ("unix:"));
558 else if (addr[0] == '/')
559 status = lcc_open_unixsocket (c, addr);
561 status = lcc_open_netsocket (c, addr);
564 } /* }}} int lcc_open_socket */
569 unsigned int lcc_version (void) /* {{{ */
571 return (LCC_VERSION);
572 } /* }}} unsigned int lcc_version */
574 const char *lcc_version_string (void) /* {{{ */
576 return (LCC_VERSION_STRING);
577 } /* }}} const char *lcc_version_string */
579 const char *lcc_version_extra (void) /* {{{ */
581 return (LCC_VERSION_EXTRA);
582 } /* }}} const char *lcc_version_extra */
584 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
595 c = (lcc_connection_t *) malloc (sizeof (*c));
598 memset (c, 0, sizeof (*c));
600 status = lcc_open_socket (c, address);
609 } /* }}} int lcc_connect */
611 int lcc_disconnect (lcc_connection_t *c) /* {{{ */
624 } /* }}} int lcc_disconnect */
626 int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
627 size_t *ret_values_num, gauge_t **ret_values, char ***ret_values_names)
629 char ident_str[6 * LCC_NAME_LEN];
630 char ident_esc[12 * LCC_NAME_LEN];
631 char command[14 * LCC_NAME_LEN];
635 gauge_t *values = NULL;
636 char **values_names = NULL;
646 lcc_set_errno (c, EINVAL);
650 /* Build a commend with an escaped version of the identifier string. */
651 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
655 snprintf (command, sizeof (command), "GETVAL %s",
656 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
657 command[sizeof (command) - 1] = 0;
659 /* Send talk to the daemon.. */
660 status = lcc_sendreceive (c, command, &res);
666 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
667 lcc_response_free (&res);
671 values_num = res.lines_num;
673 #define BAIL_OUT(e) do { \
674 lcc_set_errno (c, (e)); \
676 if (values_names != NULL) { \
677 for (i = 0; i < values_num; i++) { \
678 free (values_names[i]); \
681 free (values_names); \
682 lcc_response_free (&res); \
686 /* If neither the values nor the names are requested, return here.. */
687 if ((ret_values == NULL) && (ret_values_names == NULL))
689 if (ret_values_num != NULL)
690 *ret_values_num = values_num;
691 lcc_response_free (&res);
695 /* Allocate space for the values */
696 if (ret_values != NULL)
698 values = (gauge_t *) malloc (values_num * sizeof (*values));
703 if (ret_values_names != NULL)
705 values_names = (char **) calloc (values_num, sizeof (*values_names));
706 if (values_names == NULL)
710 for (i = 0; i < res.lines_num; i++)
717 value = strchr (key, '=');
728 values[i] = strtod (value, &endptr);
730 if ((endptr == value) || (errno != 0))
734 if (values_names != NULL)
736 values_names[i] = lcc_strdup (key);
737 if (values_names[i] == NULL)
740 } /* for (i = 0; i < res.lines_num; i++) */
742 if (ret_values_num != NULL)
743 *ret_values_num = values_num;
744 if (ret_values != NULL)
745 *ret_values = values;
746 if (ret_values_names != NULL)
747 *ret_values_names = values_names;
749 lcc_response_free (&res);
752 } /* }}} int lcc_getval */
754 int lcc_putval (lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
756 char ident_str[6 * LCC_NAME_LEN];
757 char ident_esc[12 * LCC_NAME_LEN];
758 char command[1024] = "";
763 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
764 || (vl->values == NULL) || (vl->values_types == NULL))
766 lcc_set_errno (c, EINVAL);
770 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
775 SSTRCATF (command, "PUTVAL %s",
776 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
778 if (vl->interval > 0)
779 SSTRCATF (command, " interval=%i", vl->interval);
782 SSTRCATF (command, " %u", (unsigned int) vl->time);
784 SSTRCAT (command, " N");
786 for (i = 0; i < vl->values_len; i++)
788 if (vl->values_types[i] == LCC_TYPE_COUNTER)
789 SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
790 else if (vl->values_types[i] == LCC_TYPE_GAUGE)
792 if (isnan (vl->values[i].gauge))
793 SSTRCPY (command, ":U");
795 SSTRCATF (command, ":%g", vl->values[i].gauge);
797 else if (vl->values_types[i] == LCC_TYPE_DERIVE)
798 SSTRCATF (command, ":%"PRIu64, vl->values[i].derive);
799 else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
800 SSTRCATF (command, ":%"PRIu64, vl->values[i].absolute);
802 } /* for (i = 0; i < vl->values_len; i++) */
804 status = lcc_sendreceive (c, command, &res);
810 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
811 lcc_response_free (&res);
815 lcc_response_free (&res);
817 } /* }}} int lcc_putval */
819 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
820 lcc_identifier_t *ident, int timeout)
822 char command[1024] = "";
828 lcc_set_errno (c, EINVAL);
832 SSTRCPY (command, "FLUSH");
835 SSTRCATF (command, " timeout=%i", timeout);
839 char buffer[2 * LCC_NAME_LEN];
840 SSTRCATF (command, " plugin=%s",
841 lcc_strescape (buffer, plugin, sizeof (buffer)));
846 char ident_str[6 * LCC_NAME_LEN];
847 char ident_esc[12 * LCC_NAME_LEN];
849 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
853 SSTRCATF (command, " identifier=%s",
854 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
857 status = lcc_sendreceive (c, command, &res);
863 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
864 lcc_response_free (&res);
868 lcc_response_free (&res);
870 } /* }}} int lcc_flush */
872 /* TODO: Implement lcc_putnotif */
874 int lcc_listval (lcc_connection_t *c, /* {{{ */
875 lcc_identifier_t **ret_ident, size_t *ret_ident_num)
881 lcc_identifier_t *ident;
887 if ((ret_ident == NULL) || (ret_ident_num == NULL))
889 lcc_set_errno (c, EINVAL);
893 status = lcc_sendreceive (c, "LISTVAL", &res);
899 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
900 lcc_response_free (&res);
904 ident_num = res.lines_num;
905 ident = (lcc_identifier_t *) malloc (ident_num * sizeof (*ident));
908 lcc_response_free (&res);
909 lcc_set_errno (c, ENOMEM);
913 for (i = 0; i < res.lines_num; i++)
918 /* First field is the time. */
919 time_str = res.lines[i];
921 /* Set `ident_str' to the beginning of the second field. */
922 ident_str = time_str;
923 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
925 while ((*ident_str == ' ') || (*ident_str == '\t'))
933 lcc_set_errno (c, EILSEQ);
938 status = lcc_string_to_identifier (c, ident + i, ident_str);
943 lcc_response_free (&res);
952 *ret_ident_num = ident_num;
955 } /* }}} int lcc_listval */
957 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
960 return ("Invalid object");
962 } /* }}} const char *lcc_strerror */
964 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
965 char *string, size_t string_size, const lcc_identifier_t *ident)
967 if ((string == NULL) || (string_size < 6) || (ident == NULL))
969 lcc_set_errno (c, EINVAL);
973 if (ident->plugin_instance[0] == 0)
975 if (ident->type_instance[0] == 0)
976 snprintf (string, string_size, "%s/%s/%s",
981 snprintf (string, string_size, "%s/%s/%s-%s",
985 ident->type_instance);
989 if (ident->type_instance[0] == 0)
990 snprintf (string, string_size, "%s/%s-%s/%s",
993 ident->plugin_instance,
996 snprintf (string, string_size, "%s/%s-%s/%s-%s",
999 ident->plugin_instance,
1001 ident->type_instance);
1004 string[string_size - 1] = 0;
1006 } /* }}} int lcc_identifier_to_string */
1008 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
1009 lcc_identifier_t *ident, const char *string)
1014 char *plugin_instance;
1016 char *type_instance;
1018 string_copy = lcc_strdup (string);
1019 if (string_copy == NULL)
1021 lcc_set_errno (c, ENOMEM);
1026 plugin = strchr (host, '/');
1029 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1036 type = strchr (plugin, '/');
1039 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1046 plugin_instance = strchr (plugin, '-');
1047 if (plugin_instance != NULL)
1049 *plugin_instance = 0;
1053 type_instance = strchr (type, '-');
1054 if (type_instance != NULL)
1060 memset (ident, 0, sizeof (*ident));
1062 SSTRCPY (ident->host, host);
1063 SSTRCPY (ident->plugin, plugin);
1064 if (plugin_instance != NULL)
1065 SSTRCPY (ident->plugin_instance, plugin_instance);
1066 SSTRCPY (ident->type, type);
1067 if (type_instance != NULL)
1068 SSTRCPY (ident->type_instance, type_instance);
1072 } /* }}} int lcc_string_to_identifier */
1074 /* vim: set sw=2 sts=2 et fdm=marker : */