2 * libcollectdclient - src/libcollectdclient/client.c
3 * Copyright (C) 2008-2014 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"
52 #include <sys/types.h>
53 #include <sys/socket.h>
63 #include "collectd/client.h"
65 /* NI_MAXHOST has been obsoleted by RFC 3493 which is a reason for SunOS 5.11
66 * to no longer define it. We'll use the old, RFC 2553 value here. */
68 # define NI_MAXHOST 1025
71 /* OpenBSD doesn't have EPROTO, FreeBSD doesn't have EILSEQ. Oh what joy! */
74 # define EILSEQ EPROTO
76 # define EILSEQ EINVAL
80 /* Secure/static macros. They work like `strcpy' and `strcat', but assure null
81 * termination. They work for static buffers only, because they use `sizeof'.
82 * The `SSTRCATF' combines the functionality of `snprintf' and `strcat' which
83 * is very useful to add formatted stuff to the end of a buffer. */
84 #define SSTRCPY(d,s) do { \
85 strncpy ((d), (s), sizeof (d)); \
86 (d)[sizeof (d) - 1] = 0; \
89 #define SSTRCAT(d,s) do { \
90 size_t _l = strlen (d); \
91 strncpy ((d) + _l, (s), sizeof (d) - _l); \
92 (d)[sizeof (d) - 1] = 0; \
95 #define SSTRCATF(d, ...) do { \
96 char _b[sizeof (d)]; \
97 snprintf (_b, sizeof (_b), __VA_ARGS__); \
98 _b[sizeof (_b) - 1] = 0; \
103 #define LCC_SET_ERRSTR(c, ...) do { \
104 snprintf ((c)->errbuf, sizeof ((c)->errbuf), __VA_ARGS__); \
105 (c)->errbuf[sizeof ((c)->errbuf) - 1] = 0; \
109 # define LCC_DEBUG(...) printf (__VA_ARGS__)
111 # define LCC_DEBUG(...) /**/
117 struct lcc_connection_s
123 struct lcc_response_s
130 typedef struct lcc_response_s lcc_response_t;
135 /* Even though Posix requires "strerror_r" to return an "int",
136 * some systems (e.g. the GNU libc) return a "char *" _and_
137 * ignore the second argument ... -tokkee */
138 static char *sstrerror (int errnum, char *buf, size_t buflen)
143 snprintf (buf, buflen, "Error #%i; strerror_r is not available.", errnum);
144 /* #endif !HAVE_STRERROR_R */
146 #elif STRERROR_R_CHAR_P
149 temp = strerror_r (errnum, buf, buflen);
152 if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
153 strncpy (buf, temp, buflen);
155 strncpy (buf, "strerror_r did not return "
156 "an error message", buflen);
159 /* #endif STRERROR_R_CHAR_P */
162 if (strerror_r (errnum, buf, buflen) != 0)
164 snprintf (buf, buflen, "Error #%i; "
165 "Additionally, strerror_r failed.",
168 #endif /* STRERROR_R_CHAR_P */
173 } /* char *sstrerror */
175 static int lcc_set_errno (lcc_connection_t *c, int err) /* {{{ */
180 sstrerror (err, c->errbuf, sizeof (c->errbuf));
181 c->errbuf[sizeof (c->errbuf) - 1] = 0;
184 } /* }}} int lcc_set_errno */
186 static char *lcc_strescape (char *dest, const char *src, size_t dest_size) /* {{{ */
191 if ((dest == NULL) || (src == NULL))
197 assert (dest_size >= 3);
199 dest[dest_pos] = '"';
204 if ((dest_pos == (dest_size - 2))
205 || (src[src_pos] == 0))
208 if ((src[src_pos] == '"') || (src[src_pos] == '\\'))
210 /* Check if there is enough space for both characters.. */
211 if (dest_pos == (dest_size - 3))
214 dest[dest_pos] = '\\';
218 dest[dest_pos] = src[src_pos];
223 assert (dest_pos <= (dest_size - 2));
225 dest[dest_pos] = '"';
233 } /* }}} char *lcc_strescape */
235 /* lcc_chomp: Removes all control-characters at the end of a string. */
236 static void lcc_chomp (char *str) /* {{{ */
240 str_len = strlen (str);
243 if (str[str_len - 1] >= 32)
245 str[str_len - 1] = 0;
248 } /* }}} void lcc_chomp */
250 static void lcc_response_free (lcc_response_t *res) /* {{{ */
257 for (i = 0; i < res->lines_num; i++)
258 free (res->lines[i]);
261 } /* }}} void lcc_response_free */
263 static int lcc_send (lcc_connection_t *c, const char *command) /* {{{ */
267 LCC_DEBUG ("send: --> %s\n", command);
269 status = fprintf (c->fh, "%s\r\n", command);
272 lcc_set_errno (c, errno);
277 } /* }}} int lcc_send */
279 static int lcc_receive (lcc_connection_t *c, /* {{{ */
280 lcc_response_t *ret_res)
287 memset (&res, 0, sizeof (res));
289 /* Read the first line, containing the status and a message */
290 ptr = fgets (buffer, sizeof (buffer), c->fh);
293 lcc_set_errno (c, errno);
297 LCC_DEBUG ("receive: <-- %s\n", buffer);
299 /* Convert the leading status to an integer and make `ptr' to point to the
300 * beginning of the message. */
303 res.status = strtol (buffer, &ptr, 0);
304 if ((errno != 0) || (ptr == &buffer[0]))
306 lcc_set_errno (c, errno);
310 /* Skip white spaces after the status number */
311 while ((*ptr == ' ') || (*ptr == '\t'))
314 /* Now copy the message. */
315 strncpy (res.message, ptr, sizeof (res.message));
316 res.message[sizeof (res.message) - 1] = 0;
318 /* Error or no lines follow: We're done. */
321 memcpy (ret_res, &res, sizeof (res));
325 /* Allocate space for the char-pointers */
326 res.lines_num = (size_t) res.status;
328 res.lines = (char **) malloc (res.lines_num * sizeof (char *));
329 if (res.lines == NULL)
331 lcc_set_errno (c, ENOMEM);
335 /* Now receive all the lines */
336 for (i = 0; i < res.lines_num; i++)
338 ptr = fgets (buffer, sizeof (buffer), c->fh);
341 lcc_set_errno (c, errno);
345 LCC_DEBUG ("receive: <-- %s\n", buffer);
347 res.lines[i] = strdup (buffer);
348 if (res.lines[i] == NULL)
350 lcc_set_errno (c, ENOMEM);
355 /* Check if the for-loop exited with an error. */
356 if (i < res.lines_num)
367 memcpy (ret_res, &res, sizeof (res));
369 } /* }}} int lcc_receive */
371 static int lcc_sendreceive (lcc_connection_t *c, /* {{{ */
372 const char *command, lcc_response_t *ret_res)
379 lcc_set_errno (c, EBADF);
383 status = lcc_send (c, command);
387 memset (&res, 0, sizeof (res));
388 status = lcc_receive (c, &res);
390 memcpy (ret_res, &res, sizeof (*ret_res));
393 } /* }}} int lcc_sendreceive */
396 static int lcc_open_unixsocket (lcc_connection_t *c, const char *path) /* {{{ */
398 struct sockaddr_un sa;
403 assert (c->fh == NULL);
404 assert (path != NULL);
406 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
408 fd = socket (AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
411 lcc_set_errno (c, errno);
415 memset (&sa, 0, sizeof (sa));
416 sa.sun_family = AF_UNIX;
417 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
419 status = connect (fd, (struct sockaddr *) &sa, sizeof (sa));
422 lcc_set_errno (c, errno);
427 c->fh = fdopen (fd, "r+");
430 lcc_set_errno (c, errno);
436 } /* }}} int lcc_open_unixsocket */
439 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
440 const char *addr_orig)
442 struct addrinfo ai_hints;
443 struct addrinfo *ai_res;
444 struct addrinfo *ai_ptr;
445 char addr_copy[NI_MAXHOST];
452 assert (c->fh == NULL);
453 assert (addr_orig != NULL);
455 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
456 addr_copy[sizeof(addr_copy) - 1] = '\0';
459 memset (&ai_hints, 0, sizeof (ai_hints));
460 ai_hints.ai_flags = 0;
462 ai_hints.ai_flags |= AI_ADDRCONFIG;
464 ai_hints.ai_family = AF_UNSPEC;
465 ai_hints.ai_socktype = SOCK_STREAM;
468 if (*addr == '[') /* IPv6+port format */
470 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
473 port = strchr (addr, ']');
476 LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
488 LCC_SET_ERRSTR (c, "garbage after address: %s", port);
491 } /* if (*addr = ']') */
492 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
494 port = strrchr (addr, ':');
503 status = getaddrinfo (addr,
504 port == NULL ? LCC_DEFAULT_PORT : port,
508 LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
512 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
514 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
522 status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
531 c->fh = fdopen (fd, "r+");
540 assert (status == 0);
546 lcc_set_errno (c, status);
551 } /* }}} int lcc_open_netsocket */
553 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
561 assert (c->fh == NULL);
562 assert (addr != NULL);
565 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
566 status = lcc_open_unixsocket (c, addr + strlen ("unix:"));
567 else if (addr[0] == '/')
568 status = lcc_open_unixsocket (c, addr);
571 status = lcc_open_netsocket (c, addr);
574 } /* }}} int lcc_open_socket */
579 unsigned int lcc_version (void) /* {{{ */
581 return (LCC_VERSION);
582 } /* }}} unsigned int lcc_version */
584 const char *lcc_version_string (void) /* {{{ */
586 return (LCC_VERSION_STRING);
587 } /* }}} const char *lcc_version_string */
589 const char *lcc_version_extra (void) /* {{{ */
591 return (LCC_VERSION_EXTRA);
592 } /* }}} const char *lcc_version_extra */
594 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
605 c = (lcc_connection_t *) malloc (sizeof (*c));
608 memset (c, 0, sizeof (*c));
610 status = lcc_open_socket (c, address);
619 } /* }}} int lcc_connect */
621 int lcc_disconnect (lcc_connection_t *c) /* {{{ */
634 } /* }}} int lcc_disconnect */
636 int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
637 size_t *ret_values_num, gauge_t **ret_values, char ***ret_values_names)
639 char ident_str[6 * LCC_NAME_LEN];
640 char ident_esc[12 * LCC_NAME_LEN];
641 char command[14 * LCC_NAME_LEN];
645 gauge_t *values = NULL;
646 char **values_names = NULL;
656 lcc_set_errno (c, EINVAL);
660 /* Build a commend with an escaped version of the identifier string. */
661 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
665 snprintf (command, sizeof (command), "GETVAL %s",
666 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
667 command[sizeof (command) - 1] = 0;
669 /* Send talk to the daemon.. */
670 status = lcc_sendreceive (c, command, &res);
676 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
677 lcc_response_free (&res);
681 values_num = res.lines_num;
683 #define BAIL_OUT(e) do { \
684 lcc_set_errno (c, (e)); \
686 if (values_names != NULL) { \
687 for (i = 0; i < values_num; i++) { \
688 free (values_names[i]); \
691 free (values_names); \
692 lcc_response_free (&res); \
696 /* If neither the values nor the names are requested, return here.. */
697 if ((ret_values == NULL) && (ret_values_names == NULL))
699 if (ret_values_num != NULL)
700 *ret_values_num = values_num;
701 lcc_response_free (&res);
705 /* Allocate space for the values */
706 if (ret_values != NULL)
708 values = (gauge_t *) malloc (values_num * sizeof (*values));
713 if (ret_values_names != NULL)
715 values_names = (char **) calloc (values_num, sizeof (*values_names));
716 if (values_names == NULL)
720 for (i = 0; i < res.lines_num; i++)
727 value = strchr (key, '=');
738 values[i] = strtod (value, &endptr);
740 if ((endptr == value) || (errno != 0))
744 if (values_names != NULL)
746 values_names[i] = strdup (key);
747 if (values_names[i] == NULL)
750 } /* for (i = 0; i < res.lines_num; i++) */
752 if (ret_values_num != NULL)
753 *ret_values_num = values_num;
754 if (ret_values != NULL)
755 *ret_values = values;
756 if (ret_values_names != NULL)
757 *ret_values_names = values_names;
759 lcc_response_free (&res);
762 } /* }}} int lcc_getval */
764 int lcc_putval (lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
766 char ident_str[6 * LCC_NAME_LEN];
767 char ident_esc[12 * LCC_NAME_LEN];
768 char command[1024] = "";
773 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
774 || (vl->values == NULL) || (vl->values_types == NULL))
776 lcc_set_errno (c, EINVAL);
780 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
785 SSTRCATF (command, "PUTVAL %s",
786 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
788 if (vl->interval > 0.0)
789 SSTRCATF (command, " interval=%.3f", vl->interval);
792 SSTRCATF (command, " %.3f", vl->time);
794 SSTRCAT (command, " N");
796 for (i = 0; i < vl->values_len; i++)
798 if (vl->values_types[i] == LCC_TYPE_COUNTER)
799 SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
800 else if (vl->values_types[i] == LCC_TYPE_GAUGE)
802 if (isnan (vl->values[i].gauge))
803 SSTRCATF (command, ":U");
805 SSTRCATF (command, ":%g", vl->values[i].gauge);
807 else if (vl->values_types[i] == LCC_TYPE_DERIVE)
808 SSTRCATF (command, ":%"PRIu64, vl->values[i].derive);
809 else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
810 SSTRCATF (command, ":%"PRIu64, vl->values[i].absolute);
812 } /* for (i = 0; i < vl->values_len; i++) */
814 status = lcc_sendreceive (c, command, &res);
820 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
821 lcc_response_free (&res);
825 lcc_response_free (&res);
827 } /* }}} int lcc_putval */
829 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
830 lcc_identifier_t *ident, int timeout)
832 char command[1024] = "";
838 lcc_set_errno (c, EINVAL);
842 SSTRCPY (command, "FLUSH");
845 SSTRCATF (command, " timeout=%i", timeout);
849 char buffer[2 * LCC_NAME_LEN];
850 SSTRCATF (command, " plugin=%s",
851 lcc_strescape (buffer, plugin, sizeof (buffer)));
856 char ident_str[6 * LCC_NAME_LEN];
857 char ident_esc[12 * LCC_NAME_LEN];
859 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
863 SSTRCATF (command, " identifier=%s",
864 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
867 status = lcc_sendreceive (c, command, &res);
873 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
874 lcc_response_free (&res);
878 lcc_response_free (&res);
880 } /* }}} int lcc_flush */
882 /* TODO: Implement lcc_putnotif */
884 int lcc_listval (lcc_connection_t *c, /* {{{ */
885 lcc_identifier_t **ret_ident, size_t *ret_ident_num)
891 lcc_identifier_t *ident;
897 if ((ret_ident == NULL) || (ret_ident_num == NULL))
899 lcc_set_errno (c, EINVAL);
903 status = lcc_sendreceive (c, "LISTVAL", &res);
909 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
910 lcc_response_free (&res);
914 ident_num = res.lines_num;
915 ident = (lcc_identifier_t *) malloc (ident_num * sizeof (*ident));
918 lcc_response_free (&res);
919 lcc_set_errno (c, ENOMEM);
923 for (i = 0; i < res.lines_num; i++)
928 /* First field is the time. */
929 time_str = res.lines[i];
931 /* Set `ident_str' to the beginning of the second field. */
932 ident_str = time_str;
933 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
935 while ((*ident_str == ' ') || (*ident_str == '\t'))
943 lcc_set_errno (c, EILSEQ);
948 status = lcc_string_to_identifier (c, ident + i, ident_str);
953 lcc_response_free (&res);
962 *ret_ident_num = ident_num;
965 } /* }}} int lcc_listval */
967 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
970 return ("Invalid object");
972 } /* }}} const char *lcc_strerror */
974 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
975 char *string, size_t string_size, const lcc_identifier_t *ident)
977 if ((string == NULL) || (string_size < 6) || (ident == NULL))
979 lcc_set_errno (c, EINVAL);
983 if (ident->plugin_instance[0] == 0)
985 if (ident->type_instance[0] == 0)
986 snprintf (string, string_size, "%s/%s/%s",
991 snprintf (string, string_size, "%s/%s/%s-%s",
995 ident->type_instance);
999 if (ident->type_instance[0] == 0)
1000 snprintf (string, string_size, "%s/%s-%s/%s",
1003 ident->plugin_instance,
1006 snprintf (string, string_size, "%s/%s-%s/%s-%s",
1009 ident->plugin_instance,
1011 ident->type_instance);
1014 string[string_size - 1] = 0;
1016 } /* }}} int lcc_identifier_to_string */
1018 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
1019 lcc_identifier_t *ident, const char *string)
1024 char *plugin_instance;
1026 char *type_instance;
1028 string_copy = strdup (string);
1029 if (string_copy == NULL)
1031 lcc_set_errno (c, ENOMEM);
1036 plugin = strchr (host, '/');
1039 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1046 type = strchr (plugin, '/');
1049 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1056 plugin_instance = strchr (plugin, '-');
1057 if (plugin_instance != NULL)
1059 *plugin_instance = 0;
1063 type_instance = strchr (type, '-');
1064 if (type_instance != NULL)
1070 memset (ident, 0, sizeof (*ident));
1072 SSTRCPY (ident->host, host);
1073 SSTRCPY (ident->plugin, plugin);
1074 if (plugin_instance != NULL)
1075 SSTRCPY (ident->plugin_instance, plugin_instance);
1076 SSTRCPY (ident->type, type);
1077 if (type_instance != NULL)
1078 SSTRCPY (ident->type_instance, type_instance);
1082 } /* }}} int lcc_string_to_identifier */
1084 int lcc_identifier_compare (const lcc_identifier_t *i0, /* {{{ */
1085 const lcc_identifier_t *i1)
1089 if ((i0 == NULL) && (i1 == NULL))
1091 else if (i0 == NULL)
1093 else if (i1 == NULL)
1096 #define CMP_FIELD(f) do { \
1097 status = strcmp (i0->f, i1->f); \
1104 CMP_FIELD (plugin_instance);
1106 CMP_FIELD (type_instance);
1111 } /* }}} int lcc_identifier_compare */
1113 int lcc_sort_identifiers (lcc_connection_t *c, /* {{{ */
1114 lcc_identifier_t *idents, size_t idents_num)
1118 lcc_set_errno (c, EINVAL);
1122 qsort (idents, idents_num, sizeof (*idents),
1123 (void *) lcc_identifier_compare);
1125 } /* }}} int lcc_sort_identifiers */
1127 /* vim: set sw=2 sts=2 et fdm=marker : */