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 __attribute__((nonnull (1, 2)))
168 static char *lcc_strescape (char *dest, const char *src, size_t dest_size) /* {{{ */
176 assert (dest_size >= 3);
178 dest[dest_pos] = '"';
183 if ((dest_pos == (dest_size - 2))
184 || (src[src_pos] == 0))
187 if ((src[src_pos] == '"') || (src[src_pos] == '\\'))
189 /* Check if there is enough space for both characters.. */
190 if (dest_pos == (dest_size - 3))
193 dest[dest_pos] = '\\';
197 dest[dest_pos] = src[src_pos];
202 assert (dest_pos <= (dest_size - 2));
204 dest[dest_pos] = '"';
212 } /* }}} char *lcc_strescape */
214 /* lcc_chomp: Removes all control-characters at the end of a string. */
215 static void lcc_chomp (char *str) /* {{{ */
219 str_len = strlen (str);
222 if (str[str_len - 1] >= 32)
224 str[str_len - 1] = 0;
227 } /* }}} void lcc_chomp */
229 static void lcc_response_free (lcc_response_t *res) /* {{{ */
236 for (i = 0; i < res->lines_num; i++)
237 free (res->lines[i]);
240 } /* }}} void lcc_response_free */
242 static int lcc_send (lcc_connection_t *c, const char *command) /* {{{ */
246 LCC_DEBUG ("send: --> %s\n", command);
248 status = fprintf (c->fh, "%s\r\n", command);
251 lcc_set_errno (c, errno);
256 } /* }}} int lcc_send */
258 static int lcc_receive (lcc_connection_t *c, /* {{{ */
259 lcc_response_t *ret_res)
266 memset (&res, 0, sizeof (res));
268 /* Read the first line, containing the status and a message */
269 ptr = fgets (buffer, sizeof (buffer), c->fh);
272 lcc_set_errno (c, errno);
276 LCC_DEBUG ("receive: <-- %s\n", buffer);
278 /* Convert the leading status to an integer and make `ptr' to point to the
279 * beginning of the message. */
282 res.status = strtol (buffer, &ptr, 0);
283 if ((errno != 0) || (ptr == &buffer[0]))
285 lcc_set_errno (c, errno);
289 /* Skip white spaces after the status number */
290 while ((*ptr == ' ') || (*ptr == '\t'))
293 /* Now copy the message. */
294 strncpy (res.message, ptr, sizeof (res.message));
295 res.message[sizeof (res.message) - 1] = 0;
297 /* Error or no lines follow: We're done. */
300 memcpy (ret_res, &res, sizeof (res));
304 /* Allocate space for the char-pointers */
305 res.lines_num = (size_t) res.status;
307 res.lines = (char **) malloc (res.lines_num * sizeof (char *));
308 if (res.lines == NULL)
310 lcc_set_errno (c, ENOMEM);
314 /* Now receive all the lines */
315 for (i = 0; i < res.lines_num; i++)
317 ptr = fgets (buffer, sizeof (buffer), c->fh);
320 lcc_set_errno (c, errno);
324 LCC_DEBUG ("receive: <-- %s\n", buffer);
326 res.lines[i] = strdup (buffer);
327 if (res.lines[i] == NULL)
329 lcc_set_errno (c, ENOMEM);
334 /* Check if the for-loop exited with an error. */
335 if (i < res.lines_num)
346 memcpy (ret_res, &res, sizeof (res));
348 } /* }}} int lcc_receive */
350 static int lcc_sendreceive (lcc_connection_t *c, /* {{{ */
351 const char *command, lcc_response_t *ret_res)
358 lcc_set_errno (c, EBADF);
362 status = lcc_send (c, command);
366 memset (&res, 0, sizeof (res));
367 status = lcc_receive (c, &res);
369 memcpy (ret_res, &res, sizeof (*ret_res));
372 } /* }}} int lcc_sendreceive */
374 static int lcc_open_unixsocket (lcc_connection_t *c, const char *path) /* {{{ */
376 struct sockaddr_un sa;
381 assert (c->fh == NULL);
382 assert (path != NULL);
384 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
386 fd = socket (AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
389 lcc_set_errno (c, errno);
393 memset (&sa, 0, sizeof (sa));
394 sa.sun_family = AF_UNIX;
395 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
397 status = connect (fd, (struct sockaddr *) &sa, sizeof (sa));
400 lcc_set_errno (c, errno);
405 c->fh = fdopen (fd, "r+");
408 lcc_set_errno (c, errno);
414 } /* }}} int lcc_open_unixsocket */
416 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
417 const char *addr_orig)
419 struct addrinfo ai_hints;
420 struct addrinfo *ai_res;
421 struct addrinfo *ai_ptr;
422 char addr_copy[NI_MAXHOST];
429 assert (c->fh == NULL);
430 assert (addr_orig != NULL);
432 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
433 addr_copy[sizeof(addr_copy) - 1] = '\0';
436 memset (&ai_hints, 0, sizeof (ai_hints));
437 ai_hints.ai_flags = 0;
439 ai_hints.ai_flags |= AI_ADDRCONFIG;
441 ai_hints.ai_family = AF_UNSPEC;
442 ai_hints.ai_socktype = SOCK_STREAM;
445 if (*addr == '[') /* IPv6+port format */
447 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
450 port = strchr (addr, ']');
453 LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
465 LCC_SET_ERRSTR (c, "garbage after address: %s", port);
468 } /* if (*addr = ']') */
469 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
471 port = strrchr (addr, ':');
480 status = getaddrinfo (addr,
481 port == NULL ? LCC_DEFAULT_PORT : port,
485 LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
489 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
491 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
499 status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
508 c->fh = fdopen (fd, "r+");
517 assert (status == 0);
523 lcc_set_errno (c, status);
528 } /* }}} int lcc_open_netsocket */
530 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
538 assert (c->fh == NULL);
539 assert (addr != NULL);
541 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
542 status = lcc_open_unixsocket (c, addr + strlen ("unix:"));
543 else if (addr[0] == '/')
544 status = lcc_open_unixsocket (c, addr);
546 status = lcc_open_netsocket (c, addr);
549 } /* }}} int lcc_open_socket */
554 unsigned int lcc_version (void) /* {{{ */
556 return (LCC_VERSION);
557 } /* }}} unsigned int lcc_version */
559 const char *lcc_version_string (void) /* {{{ */
561 return (LCC_VERSION_STRING);
562 } /* }}} const char *lcc_version_string */
564 const char *lcc_version_extra (void) /* {{{ */
566 return (LCC_VERSION_EXTRA);
567 } /* }}} const char *lcc_version_extra */
569 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
580 c = (lcc_connection_t *) malloc (sizeof (*c));
583 memset (c, 0, sizeof (*c));
585 status = lcc_open_socket (c, address);
594 } /* }}} int lcc_connect */
596 int lcc_disconnect (lcc_connection_t *c) /* {{{ */
609 } /* }}} int lcc_disconnect */
611 int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
612 size_t *ret_values_num, gauge_t **ret_values, char ***ret_values_names)
614 char ident_str[6 * LCC_NAME_LEN];
615 char ident_esc[12 * LCC_NAME_LEN];
616 char command[14 * LCC_NAME_LEN];
620 gauge_t *values = NULL;
621 char **values_names = NULL;
631 lcc_set_errno (c, EINVAL);
635 /* Build a commend with an escaped version of the identifier string. */
636 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
640 snprintf (command, sizeof (command), "GETVAL %s",
641 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
642 command[sizeof (command) - 1] = 0;
644 /* Send talk to the daemon.. */
645 status = lcc_sendreceive (c, command, &res);
651 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
652 lcc_response_free (&res);
656 values_num = res.lines_num;
658 #define BAIL_OUT(e) do { \
659 lcc_set_errno (c, (e)); \
661 if (values_names != NULL) { \
662 for (i = 0; i < values_num; i++) { \
663 free (values_names[i]); \
666 free (values_names); \
667 lcc_response_free (&res); \
671 /* If neither the values nor the names are requested, return here.. */
672 if ((ret_values == NULL) && (ret_values_names == NULL))
674 if (ret_values_num != NULL)
675 *ret_values_num = values_num;
676 lcc_response_free (&res);
680 /* Allocate space for the values */
681 if (ret_values != NULL)
683 values = (gauge_t *) malloc (values_num * sizeof (*values));
688 if (ret_values_names != NULL)
690 values_names = (char **) calloc (values_num, sizeof (*values_names));
691 if (values_names == NULL)
695 for (i = 0; i < res.lines_num; i++)
702 value = strchr (key, '=');
713 values[i] = strtod (value, &endptr);
715 if ((endptr == value) || (errno != 0))
719 if (values_names != NULL)
721 values_names[i] = strdup (key);
722 if (values_names[i] == NULL)
725 } /* for (i = 0; i < res.lines_num; i++) */
727 if (ret_values_num != NULL)
728 *ret_values_num = values_num;
729 if (ret_values != NULL)
730 *ret_values = values;
731 if (ret_values_names != NULL)
732 *ret_values_names = values_names;
735 } /* }}} int lcc_getval */
737 int lcc_putval (lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
739 char ident_str[6 * LCC_NAME_LEN];
740 char ident_esc[12 * LCC_NAME_LEN];
741 char command[1024] = "";
746 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
747 || (vl->values == NULL) || (vl->values_types == NULL))
749 lcc_set_errno (c, EINVAL);
753 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
758 SSTRCATF (command, "PUTVAL %s",
759 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
761 if (vl->interval > 0)
762 SSTRCATF (command, " interval=%i", vl->interval);
765 SSTRCATF (command, " %u", (unsigned int) vl->time);
767 SSTRCAT (command, " N");
769 for (i = 0; i < vl->values_len; i++)
771 if (vl->values_types[i] == LCC_TYPE_COUNTER)
772 SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
773 else if (vl->values_types[i] == LCC_TYPE_GAUGE)
775 if (isnan (vl->values[i].gauge))
776 SSTRCATF (command, ":U");
778 SSTRCATF (command, ":%g", vl->values[i].gauge);
780 else if (vl->values_types[i] == LCC_TYPE_DERIVE)
781 SSTRCATF (command, ":%"PRIu64, vl->values[i].derive);
782 else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
783 SSTRCATF (command, ":%"PRIu64, vl->values[i].absolute);
785 } /* for (i = 0; i < vl->values_len; i++) */
787 status = lcc_sendreceive (c, command, &res);
793 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
794 lcc_response_free (&res);
798 lcc_response_free (&res);
800 } /* }}} int lcc_putval */
802 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
803 lcc_identifier_t *ident, int timeout)
805 char command[1024] = "";
811 lcc_set_errno (c, EINVAL);
815 SSTRCPY (command, "FLUSH");
818 SSTRCATF (command, " timeout=%i", timeout);
822 char buffer[2 * LCC_NAME_LEN];
823 SSTRCATF (command, " plugin=%s",
824 lcc_strescape (buffer, plugin, sizeof (buffer)));
829 char ident_str[6 * LCC_NAME_LEN];
830 char ident_esc[12 * LCC_NAME_LEN];
832 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
836 SSTRCATF (command, " identifier=%s",
837 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
840 status = lcc_sendreceive (c, command, &res);
846 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
847 lcc_response_free (&res);
851 lcc_response_free (&res);
853 } /* }}} int lcc_flush */
855 /* TODO: Implement lcc_putnotif */
857 int lcc_listval (lcc_connection_t *c, /* {{{ */
858 lcc_identifier_t **ret_ident, size_t *ret_ident_num)
864 lcc_identifier_t *ident;
870 if ((ret_ident == NULL) || (ret_ident_num == NULL))
872 lcc_set_errno (c, EINVAL);
876 status = lcc_sendreceive (c, "LISTVAL", &res);
882 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
883 lcc_response_free (&res);
887 ident_num = res.lines_num;
888 ident = (lcc_identifier_t *) malloc (ident_num * sizeof (*ident));
891 lcc_response_free (&res);
892 lcc_set_errno (c, ENOMEM);
896 for (i = 0; i < res.lines_num; i++)
901 /* First field is the time. */
902 time_str = res.lines[i];
904 /* Set `ident_str' to the beginning of the second field. */
905 ident_str = time_str;
906 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
908 while ((*ident_str == ' ') || (*ident_str == '\t'))
916 lcc_set_errno (c, EILSEQ);
921 status = lcc_string_to_identifier (c, ident + i, ident_str);
926 lcc_response_free (&res);
935 *ret_ident_num = ident_num;
938 } /* }}} int lcc_listval */
940 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
943 return ("Invalid object");
945 } /* }}} const char *lcc_strerror */
947 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
948 char *string, size_t string_size, const lcc_identifier_t *ident)
950 if ((string == NULL) || (string_size < 6) || (ident == NULL))
952 lcc_set_errno (c, EINVAL);
956 if (ident->plugin_instance[0] == 0)
958 if (ident->type_instance[0] == 0)
959 snprintf (string, string_size, "%s/%s/%s",
964 snprintf (string, string_size, "%s/%s/%s-%s",
968 ident->type_instance);
972 if (ident->type_instance[0] == 0)
973 snprintf (string, string_size, "%s/%s-%s/%s",
976 ident->plugin_instance,
979 snprintf (string, string_size, "%s/%s-%s/%s-%s",
982 ident->plugin_instance,
984 ident->type_instance);
987 string[string_size - 1] = 0;
989 } /* }}} int lcc_identifier_to_string */
991 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
992 lcc_identifier_t *ident, const char *string)
997 char *plugin_instance;
1001 string_copy = strdup (string);
1002 if (string_copy == NULL)
1004 lcc_set_errno (c, ENOMEM);
1009 plugin = strchr (host, '/');
1012 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1019 type = strchr (plugin, '/');
1022 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1029 plugin_instance = strchr (plugin, '-');
1030 if (plugin_instance != NULL)
1032 *plugin_instance = 0;
1036 type_instance = strchr (type, '-');
1037 if (type_instance != NULL)
1043 memset (ident, 0, sizeof (*ident));
1045 SSTRCPY (ident->host, host);
1046 SSTRCPY (ident->plugin, plugin);
1047 if (plugin_instance != NULL)
1048 SSTRCPY (ident->plugin_instance, plugin_instance);
1049 SSTRCPY (ident->type, type);
1050 if (type_instance != NULL)
1051 SSTRCPY (ident->type_instance, type_instance);
1055 } /* }}} int lcc_string_to_identifier */
1057 /* vim: set sw=2 sts=2 et fdm=marker : */