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 __attribute__ ((format (printf, 1, 0)))
117 static int lcc_tracef(char const *format, ...)
122 char const *trace = getenv (LCC_TRACE_ENV);
123 if (!trace || (strcmp ("", trace) == 0) || (strcmp ("0", trace) == 0))
126 va_start (ap, format);
127 status = vprintf (format, ap);
133 /* Even though Posix requires "strerror_r" to return an "int",
134 * some systems (e.g. the GNU libc) return a "char *" _and_
135 * ignore the second argument ... -tokkee */
136 static char *sstrerror (int errnum, char *buf, size_t buflen)
141 snprintf (buf, buflen, "Error #%i; strerror_r is not available.", errnum);
142 /* #endif !HAVE_STRERROR_R */
144 #elif STRERROR_R_CHAR_P
147 temp = strerror_r (errnum, buf, buflen);
150 if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
151 strncpy (buf, temp, buflen);
153 strncpy (buf, "strerror_r did not return "
154 "an error message", buflen);
157 /* #endif STRERROR_R_CHAR_P */
160 if (strerror_r (errnum, buf, buflen) != 0)
162 snprintf (buf, buflen, "Error #%i; "
163 "Additionally, strerror_r failed.",
166 #endif /* STRERROR_R_CHAR_P */
171 } /* char *sstrerror */
173 static int lcc_set_errno (lcc_connection_t *c, int err) /* {{{ */
178 sstrerror (err, c->errbuf, sizeof (c->errbuf));
179 c->errbuf[sizeof (c->errbuf) - 1] = 0;
182 } /* }}} int lcc_set_errno */
184 static char *lcc_strescape (char *dest, const char *src, size_t dest_size) /* {{{ */
189 if ((dest == NULL) || (src == NULL))
195 assert (dest_size >= 3);
197 dest[dest_pos] = '"';
202 if ((dest_pos == (dest_size - 2))
203 || (src[src_pos] == 0))
206 if ((src[src_pos] == '"') || (src[src_pos] == '\\'))
208 /* Check if there is enough space for both characters.. */
209 if (dest_pos == (dest_size - 3))
212 dest[dest_pos] = '\\';
216 dest[dest_pos] = src[src_pos];
221 assert (dest_pos <= (dest_size - 2));
223 dest[dest_pos] = '"';
231 } /* }}} char *lcc_strescape */
233 /* lcc_chomp: Removes all control-characters at the end of a string. */
234 static void lcc_chomp (char *str) /* {{{ */
238 str_len = strlen (str);
241 if (str[str_len - 1] >= 32)
243 str[str_len - 1] = 0;
246 } /* }}} void lcc_chomp */
248 static void lcc_response_free (lcc_response_t *res) /* {{{ */
253 for (size_t i = 0; i < res->lines_num; i++)
254 free (res->lines[i]);
257 } /* }}} void lcc_response_free */
259 static int lcc_send (lcc_connection_t *c, const char *command) /* {{{ */
263 lcc_tracef ("send: --> %s\n", command);
265 status = fprintf (c->fh, "%s\r\n", command);
268 lcc_set_errno (c, errno);
274 } /* }}} int lcc_send */
276 static int lcc_receive (lcc_connection_t *c, /* {{{ */
277 lcc_response_t *ret_res)
279 lcc_response_t res = { 0 };
284 /* Read the first line, containing the status and a message */
285 ptr = fgets (buffer, sizeof (buffer), c->fh);
288 lcc_set_errno (c, errno);
292 lcc_tracef ("receive: <-- %s\n", buffer);
294 /* Convert the leading status to an integer and make `ptr' to point to the
295 * beginning of the message. */
298 res.status = (int) strtol (buffer, &ptr, 0);
299 if ((errno != 0) || (ptr == &buffer[0]))
301 lcc_set_errno (c, errno);
305 /* Skip white spaces after the status number */
306 while ((*ptr == ' ') || (*ptr == '\t'))
309 /* Now copy the message. */
310 strncpy (res.message, ptr, sizeof (res.message));
311 res.message[sizeof (res.message) - 1] = 0;
313 /* Error or no lines follow: We're done. */
316 memcpy (ret_res, &res, sizeof (res));
320 /* Allocate space for the char-pointers */
321 res.lines_num = (size_t) res.status;
323 res.lines = malloc (res.lines_num * sizeof (*res.lines));
324 if (res.lines == NULL)
326 lcc_set_errno (c, ENOMEM);
330 /* Now receive all the lines */
331 for (i = 0; i < res.lines_num; i++)
333 ptr = fgets (buffer, sizeof (buffer), c->fh);
336 lcc_set_errno (c, errno);
340 lcc_tracef ("receive: <-- %s\n", buffer);
342 res.lines[i] = strdup (buffer);
343 if (res.lines[i] == NULL)
345 lcc_set_errno (c, ENOMEM);
350 /* Check if the for-loop exited with an error. */
351 if (i < res.lines_num)
362 memcpy (ret_res, &res, sizeof (res));
364 } /* }}} int lcc_receive */
366 static int lcc_sendreceive (lcc_connection_t *c, /* {{{ */
367 const char *command, lcc_response_t *ret_res)
369 lcc_response_t res = { 0 };
374 lcc_set_errno (c, EBADF);
378 status = lcc_send (c, command);
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 = { 0 };
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 sa.sun_family = AF_UNIX;
409 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
411 status = connect (fd, (struct sockaddr *) &sa, sizeof (sa));
414 lcc_set_errno (c, errno);
419 c->fh = fdopen (fd, "r+");
422 lcc_set_errno (c, errno);
428 } /* }}} int lcc_open_unixsocket */
430 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
431 const char *addr_orig)
433 struct addrinfo *ai_res;
434 char addr_copy[NI_MAXHOST];
441 assert (c->fh == NULL);
442 assert (addr_orig != NULL);
444 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
445 addr_copy[sizeof(addr_copy) - 1] = '\0';
449 if (*addr == '[') /* IPv6+port format */
451 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
454 port = strchr (addr, ']');
457 LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
469 LCC_SET_ERRSTR (c, "garbage after address: %s", port);
472 } /* if (*addr = ']') */
473 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
475 port = strrchr (addr, ':');
483 struct addrinfo ai_hints = {
484 .ai_family = AF_UNSPEC,
485 .ai_flags = AI_ADDRCONFIG,
486 .ai_socktype = SOCK_STREAM
489 status = getaddrinfo (addr,
490 port == NULL ? LCC_DEFAULT_PORT : port,
494 LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
498 for (struct addrinfo *ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
500 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
507 status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
515 c->fh = fdopen (fd, "r+");
523 assert (status == 0);
529 lcc_set_errno (c, status);
530 freeaddrinfo (ai_res);
534 freeaddrinfo (ai_res);
536 } /* }}} int lcc_open_netsocket */
538 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
546 assert (c->fh == NULL);
547 assert (addr != NULL);
549 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
550 status = lcc_open_unixsocket (c, addr + strlen ("unix:"));
551 else if (addr[0] == '/')
552 status = lcc_open_unixsocket (c, addr);
554 status = lcc_open_netsocket (c, addr);
557 } /* }}} int lcc_open_socket */
562 unsigned int lcc_version (void) /* {{{ */
564 return (LCC_VERSION);
565 } /* }}} unsigned int lcc_version */
567 const char *lcc_version_string (void) /* {{{ */
569 return (LCC_VERSION_STRING);
570 } /* }}} const char *lcc_version_string */
572 const char *lcc_version_extra (void) /* {{{ */
574 return (LCC_VERSION_EXTRA);
575 } /* }}} const char *lcc_version_extra */
577 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
588 c = calloc (1, sizeof (*c));
592 status = lcc_open_socket (c, address);
601 } /* }}} int lcc_connect */
603 int lcc_disconnect (lcc_connection_t *c) /* {{{ */
616 } /* }}} int lcc_disconnect */
618 int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
619 size_t *ret_values_num, gauge_t **ret_values, char ***ret_values_names)
621 char ident_str[6 * LCC_NAME_LEN];
622 char ident_esc[12 * LCC_NAME_LEN];
623 char command[14 * LCC_NAME_LEN];
627 gauge_t *values = NULL;
628 char **values_names = NULL;
638 lcc_set_errno (c, EINVAL);
642 /* Build a commend with an escaped version of the identifier string. */
643 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
647 snprintf (command, sizeof (command), "GETVAL %s",
648 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
649 command[sizeof (command) - 1] = 0;
651 /* Send talk to the daemon.. */
652 status = lcc_sendreceive (c, command, &res);
658 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
659 lcc_response_free (&res);
663 values_num = res.lines_num;
665 #define BAIL_OUT(e) do { \
666 lcc_set_errno (c, (e)); \
668 if (values_names != NULL) { \
669 for (i = 0; i < values_num; i++) { \
670 free (values_names[i]); \
673 free (values_names); \
674 lcc_response_free (&res); \
678 /* If neither the values nor the names are requested, return here.. */
679 if ((ret_values == NULL) && (ret_values_names == NULL))
681 if (ret_values_num != NULL)
682 *ret_values_num = values_num;
683 lcc_response_free (&res);
687 /* Allocate space for the values */
688 if (ret_values != NULL)
690 values = malloc (values_num * sizeof (*values));
695 if (ret_values_names != NULL)
697 values_names = calloc (values_num, sizeof (*values_names));
698 if (values_names == NULL)
702 for (i = 0; i < res.lines_num; i++)
709 value = strchr (key, '=');
720 values[i] = strtod (value, &endptr);
722 if ((endptr == value) || (errno != 0))
726 if (values_names != NULL)
728 values_names[i] = strdup (key);
729 if (values_names[i] == NULL)
732 } /* for (i = 0; i < res.lines_num; i++) */
734 if (ret_values_num != NULL)
735 *ret_values_num = values_num;
736 if (ret_values != NULL)
737 *ret_values = values;
738 if (ret_values_names != NULL)
739 *ret_values_names = values_names;
741 lcc_response_free (&res);
744 } /* }}} int lcc_getval */
746 int lcc_putval (lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
748 char ident_str[6 * LCC_NAME_LEN];
749 char ident_esc[12 * LCC_NAME_LEN];
750 char command[1024] = "";
754 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
755 || (vl->values == NULL) || (vl->values_types == NULL))
757 lcc_set_errno (c, EINVAL);
761 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
766 SSTRCATF (command, "PUTVAL %s",
767 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
769 if (vl->interval > 0.0)
770 SSTRCATF (command, " interval=%.3f", vl->interval);
773 SSTRCATF (command, " %.3f", vl->time);
775 SSTRCAT (command, " N");
777 for (size_t i = 0; i < vl->values_len; i++)
779 if (vl->values_types[i] == LCC_TYPE_COUNTER)
780 SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
781 else if (vl->values_types[i] == LCC_TYPE_GAUGE)
783 if (isnan (vl->values[i].gauge))
784 SSTRCATF (command, ":U");
786 SSTRCATF (command, ":%g", vl->values[i].gauge);
788 else if (vl->values_types[i] == LCC_TYPE_DERIVE)
789 SSTRCATF (command, ":%"PRIu64, vl->values[i].derive);
790 else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
791 SSTRCATF (command, ":%"PRIu64, vl->values[i].absolute);
793 } /* for (i = 0; i < vl->values_len; i++) */
795 status = lcc_sendreceive (c, command, &res);
801 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
802 lcc_response_free (&res);
806 lcc_response_free (&res);
808 } /* }}} int lcc_putval */
810 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
811 lcc_identifier_t *ident, int timeout)
813 char command[1024] = "";
819 lcc_set_errno (c, EINVAL);
823 SSTRCPY (command, "FLUSH");
826 SSTRCATF (command, " timeout=%i", timeout);
830 char buffer[2 * LCC_NAME_LEN];
831 SSTRCATF (command, " plugin=%s",
832 lcc_strescape (buffer, plugin, sizeof (buffer)));
837 char ident_str[6 * LCC_NAME_LEN];
838 char ident_esc[12 * LCC_NAME_LEN];
840 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
844 SSTRCATF (command, " identifier=%s",
845 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
848 status = lcc_sendreceive (c, command, &res);
854 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
855 lcc_response_free (&res);
859 lcc_response_free (&res);
861 } /* }}} int lcc_flush */
863 /* TODO: Implement lcc_putnotif */
865 int lcc_listval (lcc_connection_t *c, /* {{{ */
866 lcc_identifier_t **ret_ident, size_t *ret_ident_num)
871 lcc_identifier_t *ident;
877 if ((ret_ident == NULL) || (ret_ident_num == NULL))
879 lcc_set_errno (c, EINVAL);
883 status = lcc_sendreceive (c, "LISTVAL", &res);
889 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
890 lcc_response_free (&res);
894 ident_num = res.lines_num;
895 ident = malloc (ident_num * sizeof (*ident));
898 lcc_response_free (&res);
899 lcc_set_errno (c, ENOMEM);
903 for (size_t i = 0; i < res.lines_num; i++)
908 /* First field is the time. */
909 time_str = res.lines[i];
911 /* Set `ident_str' to the beginning of the second field. */
912 ident_str = time_str;
913 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
915 while ((*ident_str == ' ') || (*ident_str == '\t'))
923 lcc_set_errno (c, EILSEQ);
928 status = lcc_string_to_identifier (c, ident + i, ident_str);
933 lcc_response_free (&res);
942 *ret_ident_num = ident_num;
945 } /* }}} int lcc_listval */
947 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
950 return ("Invalid object");
952 } /* }}} const char *lcc_strerror */
954 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
955 char *string, size_t string_size, const lcc_identifier_t *ident)
957 if ((string == NULL) || (string_size < 6) || (ident == NULL))
959 lcc_set_errno (c, EINVAL);
963 if (ident->plugin_instance[0] == 0)
965 if (ident->type_instance[0] == 0)
966 snprintf (string, string_size, "%s/%s/%s",
971 snprintf (string, string_size, "%s/%s/%s-%s",
975 ident->type_instance);
979 if (ident->type_instance[0] == 0)
980 snprintf (string, string_size, "%s/%s-%s/%s",
983 ident->plugin_instance,
986 snprintf (string, string_size, "%s/%s-%s/%s-%s",
989 ident->plugin_instance,
991 ident->type_instance);
994 string[string_size - 1] = 0;
996 } /* }}} int lcc_identifier_to_string */
998 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
999 lcc_identifier_t *ident, const char *string)
1004 char *plugin_instance;
1006 char *type_instance;
1008 string_copy = strdup (string);
1009 if (string_copy == NULL)
1011 lcc_set_errno (c, ENOMEM);
1016 plugin = strchr (host, '/');
1019 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1026 type = strchr (plugin, '/');
1029 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1036 plugin_instance = strchr (plugin, '-');
1037 if (plugin_instance != NULL)
1039 *plugin_instance = 0;
1043 type_instance = strchr (type, '-');
1044 if (type_instance != NULL)
1050 memset (ident, 0, sizeof (*ident));
1052 SSTRCPY (ident->host, host);
1053 SSTRCPY (ident->plugin, plugin);
1054 if (plugin_instance != NULL)
1055 SSTRCPY (ident->plugin_instance, plugin_instance);
1056 SSTRCPY (ident->type, type);
1057 if (type_instance != NULL)
1058 SSTRCPY (ident->type_instance, type_instance);
1062 } /* }}} int lcc_string_to_identifier */
1064 int lcc_identifier_compare (const void *a, /* {{{ */
1067 const lcc_identifier_t *i0 = a;
1068 const lcc_identifier_t *i1 = b;
1071 if ((i0 == NULL) && (i1 == NULL))
1073 else if (i0 == NULL)
1075 else if (i1 == NULL)
1078 #define CMP_FIELD(f) do { \
1079 status = strcmp (i0->f, i1->f); \
1086 CMP_FIELD (plugin_instance);
1088 CMP_FIELD (type_instance);
1093 } /* }}} int lcc_identifier_compare */
1095 int lcc_sort_identifiers (lcc_connection_t *c, /* {{{ */
1096 lcc_identifier_t *idents, size_t idents_num)
1100 lcc_set_errno (c, EINVAL);
1104 qsort (idents, idents_num, sizeof (*idents),
1105 lcc_identifier_compare);
1107 } /* }}} int lcc_sort_identifiers */
1109 /* vim: set sw=2 sts=2 et fdm=marker : */