2 * libcollectdclient - src/libcollectdclient/client.c
3 * Copyright (C) 2008-2012 Florian octo Forster
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:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
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.
24 * Florian octo Forster <octo at collectd.org>
31 #if !defined(__GNUC__) || !__GNUC__
32 # define __attribute__(x) /**/
35 #include "collectd/lcc_features.h"
41 #include <sys/types.h>
42 #include <sys/socket.h>
50 #include "collectd/client.h"
52 /* NI_MAXHOST has been obsoleted by RFC 3493 which is a reason for SunOS 5.11
53 * to no longer define it. We'll use the old, RFC 2553 value here. */
55 # define NI_MAXHOST 1025
58 /* OpenBSD doesn't have EPROTO, FreeBSD doesn't have EILSEQ. Oh what joy! */
61 # define EILSEQ EPROTO
63 # define EILSEQ EINVAL
67 /* Secure/static macros. They work like `strcpy' and `strcat', but assure null
68 * termination. They work for static buffers only, because they use `sizeof'.
69 * The `SSTRCATF' combines the functionality of `snprintf' and `strcat' which
70 * is very useful to add formatted stuff to the end of a buffer. */
71 #define SSTRCPY(d,s) do { \
72 strncpy ((d), (s), sizeof (d)); \
73 (d)[sizeof (d) - 1] = 0; \
76 #define SSTRCAT(d,s) do { \
77 size_t _l = strlen (d); \
78 strncpy ((d) + _l, (s), sizeof (d) - _l); \
79 (d)[sizeof (d) - 1] = 0; \
82 #define SSTRCATF(d, ...) do { \
83 char _b[sizeof (d)]; \
84 snprintf (_b, sizeof (_b), __VA_ARGS__); \
85 _b[sizeof (_b) - 1] = 0; \
90 #define LCC_SET_ERRSTR(c, ...) do { \
91 snprintf ((c)->errbuf, sizeof ((c)->errbuf), __VA_ARGS__); \
92 (c)->errbuf[sizeof ((c)->errbuf) - 1] = 0; \
98 struct lcc_connection_s
104 struct lcc_response_s
111 typedef struct lcc_response_s lcc_response_t;
116 static int lcc_tracef(char const *format, ...)
121 char const *trace = getenv (LCC_TRACE_ENV);
122 if (!trace || (strcmp ("", trace) == 0) || (strcmp ("0", trace) == 0))
125 va_start (ap, format);
126 status = vprintf (format, ap);
132 /* Even though Posix requires "strerror_r" to return an "int",
133 * some systems (e.g. the GNU libc) return a "char *" _and_
134 * ignore the second argument ... -tokkee */
135 static char *sstrerror (int errnum, char *buf, size_t buflen)
140 snprintf (buf, buflen, "Error #%i; strerror_r is not available.", errnum);
141 /* #endif !HAVE_STRERROR_R */
143 #elif STRERROR_R_CHAR_P
146 temp = strerror_r (errnum, buf, buflen);
149 if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
150 strncpy (buf, temp, buflen);
152 strncpy (buf, "strerror_r did not return "
153 "an error message", buflen);
156 /* #endif STRERROR_R_CHAR_P */
159 if (strerror_r (errnum, buf, buflen) != 0)
161 snprintf (buf, buflen, "Error #%i; "
162 "Additionally, strerror_r failed.",
165 #endif /* STRERROR_R_CHAR_P */
170 } /* char *sstrerror */
172 static int lcc_set_errno (lcc_connection_t *c, int err) /* {{{ */
177 sstrerror (err, c->errbuf, sizeof (c->errbuf));
178 c->errbuf[sizeof (c->errbuf) - 1] = 0;
181 } /* }}} int lcc_set_errno */
183 static char *lcc_strescape (char *dest, const char *src, size_t dest_size) /* {{{ */
188 if ((dest == NULL) || (src == NULL))
194 assert (dest_size >= 3);
196 dest[dest_pos] = '"';
201 if ((dest_pos == (dest_size - 2))
202 || (src[src_pos] == 0))
205 if ((src[src_pos] == '"') || (src[src_pos] == '\\'))
207 /* Check if there is enough space for both characters.. */
208 if (dest_pos == (dest_size - 3))
211 dest[dest_pos] = '\\';
215 dest[dest_pos] = src[src_pos];
220 assert (dest_pos <= (dest_size - 2));
222 dest[dest_pos] = '"';
230 } /* }}} char *lcc_strescape */
232 /* lcc_chomp: Removes all control-characters at the end of a string. */
233 static void lcc_chomp (char *str) /* {{{ */
237 str_len = strlen (str);
240 if (str[str_len - 1] >= 32)
242 str[str_len - 1] = 0;
245 } /* }}} void lcc_chomp */
247 static void lcc_response_free (lcc_response_t *res) /* {{{ */
252 for (size_t i = 0; i < res->lines_num; i++)
253 free (res->lines[i]);
256 } /* }}} void lcc_response_free */
258 static int lcc_send (lcc_connection_t *c, const char *command) /* {{{ */
262 lcc_tracef ("send: --> %s\n", command);
264 status = fprintf (c->fh, "%s\r\n", command);
267 lcc_set_errno (c, errno);
273 } /* }}} int lcc_send */
275 static int lcc_receive (lcc_connection_t *c, /* {{{ */
276 lcc_response_t *ret_res)
278 lcc_response_t res = { 0 };
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_tracef ("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 = (int) 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 = malloc (res.lines_num * sizeof (*res.lines));
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_tracef ("receive: <-- %s\n", buffer);
341 res.lines[i] = 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)
368 lcc_response_t res = { 0 };
373 lcc_set_errno (c, EBADF);
377 status = lcc_send (c, command);
381 status = lcc_receive (c, &res);
383 memcpy (ret_res, &res, sizeof (*ret_res));
386 } /* }}} int lcc_sendreceive */
388 static int lcc_open_unixsocket (lcc_connection_t *c, const char *path) /* {{{ */
390 struct sockaddr_un sa = { 0 };
395 assert (c->fh == NULL);
396 assert (path != NULL);
398 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
400 fd = socket (AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
403 lcc_set_errno (c, errno);
407 sa.sun_family = AF_UNIX;
408 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
410 status = connect (fd, (struct sockaddr *) &sa, sizeof (sa));
413 lcc_set_errno (c, errno);
418 c->fh = fdopen (fd, "r+");
421 lcc_set_errno (c, errno);
427 } /* }}} int lcc_open_unixsocket */
429 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
430 const char *addr_orig)
432 struct addrinfo *ai_res;
433 char addr_copy[NI_MAXHOST];
440 assert (c->fh == NULL);
441 assert (addr_orig != NULL);
443 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
444 addr_copy[sizeof(addr_copy) - 1] = '\0';
448 if (*addr == '[') /* IPv6+port format */
450 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
453 port = strchr (addr, ']');
456 LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
468 LCC_SET_ERRSTR (c, "garbage after address: %s", port);
471 } /* if (*addr = ']') */
472 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
474 port = strrchr (addr, ':');
482 struct addrinfo ai_hints = {
483 .ai_family = AF_UNSPEC,
484 .ai_flags = AI_ADDRCONFIG,
485 .ai_socktype = SOCK_STREAM
488 status = getaddrinfo (addr,
489 port == NULL ? LCC_DEFAULT_PORT : port,
493 LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
497 for (struct addrinfo *ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
499 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
506 status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
514 c->fh = fdopen (fd, "r+");
522 assert (status == 0);
528 lcc_set_errno (c, status);
529 freeaddrinfo (ai_res);
533 freeaddrinfo (ai_res);
535 } /* }}} int lcc_open_netsocket */
537 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
545 assert (c->fh == NULL);
546 assert (addr != NULL);
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);
553 status = lcc_open_netsocket (c, addr);
556 } /* }}} int lcc_open_socket */
561 unsigned int lcc_version (void) /* {{{ */
563 return (LCC_VERSION);
564 } /* }}} unsigned int lcc_version */
566 const char *lcc_version_string (void) /* {{{ */
568 return (LCC_VERSION_STRING);
569 } /* }}} const char *lcc_version_string */
571 const char *lcc_version_extra (void) /* {{{ */
573 return (LCC_VERSION_EXTRA);
574 } /* }}} const char *lcc_version_extra */
576 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
587 c = calloc (1, sizeof (*c));
591 status = lcc_open_socket (c, address);
600 } /* }}} int lcc_connect */
602 int lcc_disconnect (lcc_connection_t *c) /* {{{ */
615 } /* }}} int lcc_disconnect */
617 int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
618 size_t *ret_values_num, gauge_t **ret_values, char ***ret_values_names)
620 char ident_str[6 * LCC_NAME_LEN];
621 char ident_esc[12 * LCC_NAME_LEN];
622 char command[14 * LCC_NAME_LEN];
626 gauge_t *values = NULL;
627 char **values_names = NULL;
637 lcc_set_errno (c, EINVAL);
641 /* Build a commend with an escaped version of the identifier string. */
642 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
646 snprintf (command, sizeof (command), "GETVAL %s",
647 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
648 command[sizeof (command) - 1] = 0;
650 /* Send talk to the daemon.. */
651 status = lcc_sendreceive (c, command, &res);
657 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
658 lcc_response_free (&res);
662 values_num = res.lines_num;
664 #define BAIL_OUT(e) do { \
665 lcc_set_errno (c, (e)); \
667 if (values_names != NULL) { \
668 for (i = 0; i < values_num; i++) { \
669 free (values_names[i]); \
672 free (values_names); \
673 lcc_response_free (&res); \
677 /* If neither the values nor the names are requested, return here.. */
678 if ((ret_values == NULL) && (ret_values_names == NULL))
680 if (ret_values_num != NULL)
681 *ret_values_num = values_num;
682 lcc_response_free (&res);
686 /* Allocate space for the values */
687 if (ret_values != NULL)
689 values = malloc (values_num * sizeof (*values));
694 if (ret_values_names != NULL)
696 values_names = calloc (values_num, sizeof (*values_names));
697 if (values_names == NULL)
701 for (i = 0; i < res.lines_num; i++)
708 value = strchr (key, '=');
719 values[i] = strtod (value, &endptr);
721 if ((endptr == value) || (errno != 0))
725 if (values_names != NULL)
727 values_names[i] = strdup (key);
728 if (values_names[i] == NULL)
731 } /* for (i = 0; i < res.lines_num; i++) */
733 if (ret_values_num != NULL)
734 *ret_values_num = values_num;
735 if (ret_values != NULL)
736 *ret_values = values;
737 if (ret_values_names != NULL)
738 *ret_values_names = values_names;
740 lcc_response_free (&res);
743 } /* }}} int lcc_getval */
745 int lcc_putval (lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
747 char ident_str[6 * LCC_NAME_LEN];
748 char ident_esc[12 * LCC_NAME_LEN];
749 char command[1024] = "";
753 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
754 || (vl->values == NULL) || (vl->values_types == NULL))
756 lcc_set_errno (c, EINVAL);
760 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
765 SSTRCATF (command, "PUTVAL %s",
766 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
768 if (vl->interval > 0.0)
769 SSTRCATF (command, " interval=%.3f", vl->interval);
772 SSTRCATF (command, " %.3f", vl->time);
774 SSTRCAT (command, " N");
776 for (size_t i = 0; i < vl->values_len; i++)
778 if (vl->values_types[i] == LCC_TYPE_COUNTER)
779 SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
780 else if (vl->values_types[i] == LCC_TYPE_GAUGE)
782 if (isnan (vl->values[i].gauge))
783 SSTRCATF (command, ":U");
785 SSTRCATF (command, ":%g", vl->values[i].gauge);
787 else if (vl->values_types[i] == LCC_TYPE_DERIVE)
788 SSTRCATF (command, ":%"PRIu64, vl->values[i].derive);
789 else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
790 SSTRCATF (command, ":%"PRIu64, vl->values[i].absolute);
792 } /* for (i = 0; i < vl->values_len; i++) */
794 status = lcc_sendreceive (c, command, &res);
800 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
801 lcc_response_free (&res);
805 lcc_response_free (&res);
807 } /* }}} int lcc_putval */
809 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
810 lcc_identifier_t *ident, int timeout)
812 char command[1024] = "";
818 lcc_set_errno (c, EINVAL);
822 SSTRCPY (command, "FLUSH");
825 SSTRCATF (command, " timeout=%i", timeout);
829 char buffer[2 * LCC_NAME_LEN];
830 SSTRCATF (command, " plugin=%s",
831 lcc_strescape (buffer, plugin, sizeof (buffer)));
836 char ident_str[6 * LCC_NAME_LEN];
837 char ident_esc[12 * LCC_NAME_LEN];
839 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
843 SSTRCATF (command, " identifier=%s",
844 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
847 status = lcc_sendreceive (c, command, &res);
853 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
854 lcc_response_free (&res);
858 lcc_response_free (&res);
860 } /* }}} int lcc_flush */
862 /* TODO: Implement lcc_putnotif */
864 int lcc_listval (lcc_connection_t *c, /* {{{ */
865 lcc_identifier_t **ret_ident, size_t *ret_ident_num)
870 lcc_identifier_t *ident;
876 if ((ret_ident == NULL) || (ret_ident_num == NULL))
878 lcc_set_errno (c, EINVAL);
882 status = lcc_sendreceive (c, "LISTVAL", &res);
888 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
889 lcc_response_free (&res);
893 ident_num = res.lines_num;
894 ident = malloc (ident_num * sizeof (*ident));
897 lcc_response_free (&res);
898 lcc_set_errno (c, ENOMEM);
902 for (size_t i = 0; i < res.lines_num; i++)
907 /* First field is the time. */
908 time_str = res.lines[i];
910 /* Set `ident_str' to the beginning of the second field. */
911 ident_str = time_str;
912 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
914 while ((*ident_str == ' ') || (*ident_str == '\t'))
922 lcc_set_errno (c, EILSEQ);
927 status = lcc_string_to_identifier (c, ident + i, ident_str);
932 lcc_response_free (&res);
941 *ret_ident_num = ident_num;
944 } /* }}} int lcc_listval */
946 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
949 return ("Invalid object");
951 } /* }}} const char *lcc_strerror */
953 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
954 char *string, size_t string_size, const lcc_identifier_t *ident)
956 if ((string == NULL) || (string_size < 6) || (ident == NULL))
958 lcc_set_errno (c, EINVAL);
962 if (ident->plugin_instance[0] == 0)
964 if (ident->type_instance[0] == 0)
965 snprintf (string, string_size, "%s/%s/%s",
970 snprintf (string, string_size, "%s/%s/%s-%s",
974 ident->type_instance);
978 if (ident->type_instance[0] == 0)
979 snprintf (string, string_size, "%s/%s-%s/%s",
982 ident->plugin_instance,
985 snprintf (string, string_size, "%s/%s-%s/%s-%s",
988 ident->plugin_instance,
990 ident->type_instance);
993 string[string_size - 1] = 0;
995 } /* }}} int lcc_identifier_to_string */
997 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
998 lcc_identifier_t *ident, const char *string)
1003 char *plugin_instance;
1005 char *type_instance;
1007 string_copy = strdup (string);
1008 if (string_copy == NULL)
1010 lcc_set_errno (c, ENOMEM);
1015 plugin = strchr (host, '/');
1018 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1025 type = strchr (plugin, '/');
1028 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1035 plugin_instance = strchr (plugin, '-');
1036 if (plugin_instance != NULL)
1038 *plugin_instance = 0;
1042 type_instance = strchr (type, '-');
1043 if (type_instance != NULL)
1049 memset (ident, 0, sizeof (*ident));
1051 SSTRCPY (ident->host, host);
1052 SSTRCPY (ident->plugin, plugin);
1053 if (plugin_instance != NULL)
1054 SSTRCPY (ident->plugin_instance, plugin_instance);
1055 SSTRCPY (ident->type, type);
1056 if (type_instance != NULL)
1057 SSTRCPY (ident->type_instance, type_instance);
1061 } /* }}} int lcc_string_to_identifier */
1063 int lcc_identifier_compare (const void *a, /* {{{ */
1066 const lcc_identifier_t *i0 = a;
1067 const lcc_identifier_t *i1 = b;
1070 if ((i0 == NULL) && (i1 == NULL))
1072 else if (i0 == NULL)
1074 else if (i1 == NULL)
1077 #define CMP_FIELD(f) do { \
1078 status = strcmp (i0->f, i1->f); \
1085 CMP_FIELD (plugin_instance);
1087 CMP_FIELD (type_instance);
1092 } /* }}} int lcc_identifier_compare */
1094 int lcc_sort_identifiers (lcc_connection_t *c, /* {{{ */
1095 lcc_identifier_t *idents, size_t idents_num)
1099 lcc_set_errno (c, EINVAL);
1103 qsort (idents, idents_num, sizeof (*idents),
1104 lcc_identifier_compare);
1106 } /* }}} int lcc_sort_identifiers */
1108 /* vim: set sw=2 sts=2 et fdm=marker : */