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>
28 #include "gnulib_config.h"
34 #if !defined(__GNUC__) || !__GNUC__
35 #define __attribute__(x) /**/
38 #include "collectd/lcc_features.h"
48 #include <sys/types.h>
52 #include <sys/socket.h>
56 #include "collectd/client.h"
58 /* NI_MAXHOST has been obsoleted by RFC 3493 which is a reason for SunOS 5.11
59 * to no longer define it. We'll use the old, RFC 2553 value here. */
61 #define NI_MAXHOST 1025
64 /* OpenBSD doesn't have EPROTO, FreeBSD doesn't have EILSEQ. Oh what joy! */
74 #define AI_ADDRCONFIG 0
77 /* Secure/static macros. They work like `strcpy' and `strcat', but assure null
78 * termination. They work for static buffers only, because they use `sizeof'.
79 * The `SSTRCATF' combines the functionality of `snprintf' and `strcat' which
80 * is very useful to add formatted stuff to the end of a buffer. */
81 #define SSTRCPY(d, s) \
83 strncpy((d), (s), sizeof(d) - 1); \
84 (d)[sizeof(d) - 1] = '\0'; \
87 #define SSTRCAT(d, s) \
89 size_t _l = strlen(d); \
90 strncpy((d) + _l, (s), sizeof(d) - _l); \
91 (d)[sizeof(d) - 1] = '\0'; \
94 #define SSTRCATF(d, ...) \
97 snprintf(_b, sizeof(_b), __VA_ARGS__); \
98 _b[sizeof(_b) - 1] = '\0'; \
102 #define LCC_SET_ERRSTR(c, ...) \
104 snprintf((c)->errbuf, sizeof((c)->errbuf), __VA_ARGS__); \
110 struct lcc_connection_s {
115 struct lcc_response_s {
121 typedef struct lcc_response_s lcc_response_t;
126 __attribute__((format(printf, 1, 0))) static int lcc_tracef(char const *format,
131 char const *trace = getenv(LCC_TRACE_ENV);
132 if (!trace || (strcmp("", trace) == 0) || (strcmp("0", trace) == 0))
135 va_start(ap, format);
136 status = vprintf(format, ap);
142 /* Even though Posix requires "strerror_r" to return an "int",
143 * some systems (e.g. the GNU libc) return a "char *" _and_
144 * ignore the second argument ... -tokkee */
145 static char *sstrerror(int errnum, char *buf, size_t buflen) {
149 snprintf(buf, buflen, "Error #%i; strerror_r is not available.", errnum);
150 /* #endif !HAVE_STRERROR_R */
152 #elif STRERROR_R_CHAR_P
155 temp = strerror_r(errnum, buf, buflen);
157 if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
158 strncpy(buf, temp, buflen);
161 "strerror_r did not return "
166 /* #endif STRERROR_R_CHAR_P */
169 if (strerror_r(errnum, buf, buflen) != 0) {
170 snprintf(buf, buflen,
172 "Additionally, strerror_r failed.",
175 #endif /* STRERROR_R_CHAR_P */
177 buf[buflen - 1] = '\0';
180 } /* char *sstrerror */
182 static int lcc_set_errno(lcc_connection_t *c, int err) /* {{{ */
187 sstrerror(err, c->errbuf, sizeof(c->errbuf));
188 c->errbuf[sizeof(c->errbuf) - 1] = '\0';
191 } /* }}} int lcc_set_errno */
193 static char *lcc_strescape(char *dest, const char *src,
194 size_t dest_size) /* {{{ */
199 if ((dest == NULL) || (src == NULL))
205 assert(dest_size >= 3);
207 dest[dest_pos] = '"';
211 if ((dest_pos == (dest_size - 2)) || (src[src_pos] == 0))
214 if ((src[src_pos] == '"') || (src[src_pos] == '\\')) {
215 /* Check if there is enough space for both characters.. */
216 if (dest_pos == (dest_size - 3))
219 dest[dest_pos] = '\\';
223 dest[dest_pos] = src[src_pos];
228 assert(dest_pos <= (dest_size - 2));
230 dest[dest_pos] = '"';
238 } /* }}} char *lcc_strescape */
240 /* lcc_chomp: Removes all control-characters at the end of a string. */
241 static void lcc_chomp(char *str) /* {{{ */
245 str_len = strlen(str);
246 while (str_len > 0) {
247 if (str[str_len - 1] >= 32)
249 str[str_len - 1] = '\0';
252 } /* }}} void lcc_chomp */
254 static void lcc_response_free(lcc_response_t *res) /* {{{ */
259 for (size_t i = 0; i < res->lines_num; i++)
263 } /* }}} void lcc_response_free */
265 static int lcc_send(lcc_connection_t *c, const char *command) /* {{{ */
269 lcc_tracef("send: --> %s\n", command);
271 status = fprintf(c->fh, "%s\r\n", command);
273 lcc_set_errno(c, errno);
279 } /* }}} int lcc_send */
281 static int lcc_receive(lcc_connection_t *c, /* {{{ */
282 lcc_response_t *ret_res) {
283 lcc_response_t res = {0};
288 /* Read the first line, containing the status and a message */
289 ptr = fgets(buffer, sizeof(buffer), c->fh);
291 lcc_set_errno(c, errno);
295 lcc_tracef("receive: <-- %s\n", buffer);
297 /* Convert the leading status to an integer and make `ptr' to point to the
298 * beginning of the message. */
301 res.status = (int)strtol(buffer, &ptr, 0);
302 if ((errno != 0) || (ptr == &buffer[0])) {
303 lcc_set_errno(c, errno);
307 /* Skip white spaces after the status number */
308 while ((*ptr == ' ') || (*ptr == '\t'))
311 /* Now copy the message. */
312 strncpy(res.message, ptr, sizeof(res.message));
313 res.message[sizeof(res.message) - 1] = '\0';
315 /* Error or no lines follow: We're done. */
316 if (res.status <= 0) {
317 memcpy(ret_res, &res, sizeof(res));
321 /* Allocate space for the char-pointers */
322 res.lines_num = (size_t)res.status;
324 res.lines = malloc(res.lines_num * sizeof(*res.lines));
325 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++) {
332 ptr = fgets(buffer, sizeof(buffer), c->fh);
334 lcc_set_errno(c, errno);
338 lcc_tracef("receive: <-- %s\n", buffer);
340 res.lines[i] = strdup(buffer);
341 if (res.lines[i] == NULL) {
342 lcc_set_errno(c, ENOMEM);
347 /* Check if the for-loop exited with an error. */
348 if (i < res.lines_num) {
357 memcpy(ret_res, &res, sizeof(res));
359 } /* }}} int lcc_receive */
361 static int lcc_sendreceive(lcc_connection_t *c, /* {{{ */
362 const char *command, lcc_response_t *ret_res) {
363 lcc_response_t res = {0};
367 lcc_set_errno(c, EBADF);
371 status = lcc_send(c, command);
375 status = lcc_receive(c, &res);
377 memcpy(ret_res, &res, sizeof(*ret_res));
380 } /* }}} int lcc_sendreceive */
382 static int lcc_open_unixsocket(lcc_connection_t *c, const char *path) /* {{{ */
385 lcc_set_errno(c, ENOTSUP);
388 struct sockaddr_un sa = {0};
393 assert(c->fh == NULL);
394 assert(path != NULL);
396 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
398 fd = socket(AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
400 lcc_set_errno(c, errno);
404 sa.sun_family = AF_UNIX;
405 strncpy(sa.sun_path, path, sizeof(sa.sun_path) - 1);
407 status = connect(fd, (struct sockaddr *)&sa, sizeof(sa));
409 lcc_set_errno(c, errno);
414 c->fh = fdopen(fd, "r+");
416 lcc_set_errno(c, errno);
423 } /* }}} int lcc_open_unixsocket */
425 static int lcc_open_netsocket(lcc_connection_t *c, /* {{{ */
426 const char *addr_orig) {
427 struct addrinfo *ai_res;
428 char addr_copy[NI_MAXHOST];
435 assert(c->fh == NULL);
436 assert(addr_orig != NULL);
438 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
439 addr_copy[sizeof(addr_copy) - 1] = '\0';
443 if (*addr == '[') /* IPv6+port format */
445 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
448 port = strchr(addr, ']');
450 LCC_SET_ERRSTR(c, "malformed address: %s", addr_orig);
461 LCC_SET_ERRSTR(c, "garbage after address: %s", port);
464 } /* if (*addr = ']') */
465 else if (strchr(addr, '.') != NULL) /* Hostname or IPv4 */
467 port = strrchr(addr, ':');
474 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
475 .ai_flags = AI_ADDRCONFIG,
476 .ai_socktype = SOCK_STREAM};
478 status = getaddrinfo(addr, port == NULL ? LCC_DEFAULT_PORT : port, &ai_hints,
481 LCC_SET_ERRSTR(c, "getaddrinfo: %s", gai_strerror(status));
485 for (struct addrinfo *ai_ptr = ai_res; ai_ptr != NULL;
486 ai_ptr = ai_ptr->ai_next) {
487 fd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
493 status = connect(fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
500 c->fh = fdopen(fd, "r+");
512 lcc_set_errno(c, status);
513 freeaddrinfo(ai_res);
517 freeaddrinfo(ai_res);
519 } /* }}} int lcc_open_netsocket */
521 static int lcc_open_socket(lcc_connection_t *c, const char *addr) /* {{{ */
529 assert(c->fh == NULL);
530 assert(addr != NULL);
532 if (strncmp("unix:", addr, strlen("unix:")) == 0)
533 status = lcc_open_unixsocket(c, addr + strlen("unix:"));
534 else if (addr[0] == '/')
535 status = lcc_open_unixsocket(c, addr);
537 status = lcc_open_netsocket(c, addr);
540 } /* }}} int lcc_open_socket */
545 unsigned int lcc_version(void) /* {{{ */
548 } /* }}} unsigned int lcc_version */
550 const char *lcc_version_string(void) /* {{{ */
552 return LCC_VERSION_STRING;
553 } /* }}} const char *lcc_version_string */
555 const char *lcc_version_extra(void) /* {{{ */
557 return LCC_VERSION_EXTRA;
558 } /* }}} const char *lcc_version_extra */
560 int lcc_connect(const char *address, lcc_connection_t **ret_con) /* {{{ */
571 c = calloc(1, sizeof(*c));
575 status = lcc_open_socket(c, address);
583 } /* }}} int lcc_connect */
585 int lcc_disconnect(lcc_connection_t *c) /* {{{ */
597 } /* }}} int lcc_disconnect */
599 int lcc_getval(lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
600 size_t *ret_values_num, gauge_t **ret_values,
601 char ***ret_values_names) {
602 char ident_str[6 * LCC_NAME_LEN];
603 char ident_esc[12 * LCC_NAME_LEN];
604 char command[14 * LCC_NAME_LEN];
608 gauge_t *values = NULL;
609 char **values_names = NULL;
618 lcc_set_errno(c, EINVAL);
622 /* Build a commend with an escaped version of the identifier string. */
623 status = lcc_identifier_to_string(c, ident_str, sizeof(ident_str), ident);
627 snprintf(command, sizeof(command), "GETVAL %s",
628 lcc_strescape(ident_esc, ident_str, sizeof(ident_esc)));
629 command[sizeof(command) - 1] = '\0';
631 /* Send talk to the daemon.. */
632 status = lcc_sendreceive(c, command, &res);
636 if (res.status != 0) {
637 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
638 lcc_response_free(&res);
642 values_num = res.lines_num;
644 #define BAIL_OUT(e) \
646 lcc_set_errno(c, (e)); \
648 if (values_names != NULL) { \
649 for (i = 0; i < values_num; i++) { \
650 free(values_names[i]); \
653 free(values_names); \
654 lcc_response_free(&res); \
658 /* If neither the values nor the names are requested, return here.. */
659 if ((ret_values == NULL) && (ret_values_names == NULL)) {
660 if (ret_values_num != NULL)
661 *ret_values_num = values_num;
662 lcc_response_free(&res);
666 /* Allocate space for the values */
667 if (ret_values != NULL) {
668 values = malloc(values_num * sizeof(*values));
673 if (ret_values_names != NULL) {
674 values_names = calloc(values_num, sizeof(*values_names));
675 if (values_names == NULL)
679 for (i = 0; i < res.lines_num; i++) {
685 value = strchr(key, '=');
692 if (values != NULL) {
695 values[i] = strtod(value, &endptr);
697 if ((endptr == value) || (errno != 0))
701 if (values_names != NULL) {
702 values_names[i] = strdup(key);
703 if (values_names[i] == NULL)
706 } /* for (i = 0; i < res.lines_num; i++) */
708 if (ret_values_num != NULL)
709 *ret_values_num = values_num;
710 if (ret_values != NULL)
711 *ret_values = values;
712 if (ret_values_names != NULL)
713 *ret_values_names = values_names;
715 lcc_response_free(&res);
718 } /* }}} int lcc_getval */
720 int lcc_putval(lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
722 char ident_str[6 * LCC_NAME_LEN];
723 char ident_esc[12 * LCC_NAME_LEN];
724 char command[1024] = "";
728 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1) ||
729 (vl->values == NULL) || (vl->values_types == NULL)) {
730 lcc_set_errno(c, EINVAL);
734 status = lcc_identifier_to_string(c, ident_str, sizeof(ident_str),
739 SSTRCATF(command, "PUTVAL %s",
740 lcc_strescape(ident_esc, ident_str, sizeof(ident_esc)));
742 if (vl->interval > 0.0)
743 SSTRCATF(command, " interval=%.3f", vl->interval);
746 SSTRCATF(command, " %.3f", vl->time);
748 SSTRCAT(command, " N");
750 for (size_t i = 0; i < vl->values_len; i++) {
751 if (vl->values_types[i] == LCC_TYPE_COUNTER)
752 SSTRCATF(command, ":%" PRIu64, vl->values[i].counter);
753 else if (vl->values_types[i] == LCC_TYPE_GAUGE) {
754 if (isnan(vl->values[i].gauge))
755 SSTRCATF(command, ":U");
757 SSTRCATF(command, ":%g", vl->values[i].gauge);
758 } else if (vl->values_types[i] == LCC_TYPE_DERIVE)
759 SSTRCATF(command, ":%" PRIu64, vl->values[i].derive);
760 else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
761 SSTRCATF(command, ":%" PRIu64, vl->values[i].absolute);
763 } /* for (i = 0; i < vl->values_len; i++) */
765 status = lcc_sendreceive(c, command, &res);
769 if (res.status != 0) {
770 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
771 lcc_response_free(&res);
775 lcc_response_free(&res);
777 } /* }}} int lcc_putval */
779 int lcc_flush(lcc_connection_t *c, const char *plugin, /* {{{ */
780 lcc_identifier_t *ident, int timeout) {
781 char command[1024] = "";
786 lcc_set_errno(c, EINVAL);
790 SSTRCPY(command, "FLUSH");
793 SSTRCATF(command, " timeout=%i", timeout);
795 if (plugin != NULL) {
796 char buffer[2 * LCC_NAME_LEN];
797 SSTRCATF(command, " plugin=%s",
798 lcc_strescape(buffer, plugin, sizeof(buffer)));
802 char ident_str[6 * LCC_NAME_LEN];
803 char ident_esc[12 * LCC_NAME_LEN];
805 status = lcc_identifier_to_string(c, ident_str, sizeof(ident_str), ident);
809 SSTRCATF(command, " identifier=%s",
810 lcc_strescape(ident_esc, ident_str, sizeof(ident_esc)));
813 status = lcc_sendreceive(c, command, &res);
817 if (res.status != 0) {
818 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
819 lcc_response_free(&res);
823 lcc_response_free(&res);
825 } /* }}} int lcc_flush */
827 /* TODO: Implement lcc_putnotif */
829 int lcc_listval(lcc_connection_t *c, /* {{{ */
830 lcc_identifier_t **ret_ident, size_t *ret_ident_num) {
834 lcc_identifier_t *ident;
840 if ((ret_ident == NULL) || (ret_ident_num == NULL)) {
841 lcc_set_errno(c, EINVAL);
845 status = lcc_sendreceive(c, "LISTVAL", &res);
849 if (res.status != 0) {
850 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
851 lcc_response_free(&res);
855 ident_num = res.lines_num;
856 ident = malloc(ident_num * sizeof(*ident));
858 lcc_response_free(&res);
859 lcc_set_errno(c, ENOMEM);
863 for (size_t i = 0; i < res.lines_num; i++) {
867 /* First field is the time. */
868 time_str = res.lines[i];
870 /* Set `ident_str' to the beginning of the second field. */
871 ident_str = time_str;
872 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
874 while ((*ident_str == ' ') || (*ident_str == '\t')) {
879 if (*ident_str == 0) {
880 lcc_set_errno(c, EILSEQ);
885 status = lcc_string_to_identifier(c, ident + i, ident_str);
890 lcc_response_free(&res);
898 *ret_ident_num = ident_num;
901 } /* }}} int lcc_listval */
903 const char *lcc_strerror(lcc_connection_t *c) /* {{{ */
906 return "Invalid object";
908 } /* }}} const char *lcc_strerror */
910 int lcc_identifier_to_string(lcc_connection_t *c, /* {{{ */
911 char *string, size_t string_size,
912 const lcc_identifier_t *ident) {
913 if ((string == NULL) || (string_size < 6) || (ident == NULL)) {
914 lcc_set_errno(c, EINVAL);
918 if (ident->plugin_instance[0] == 0) {
919 if (ident->type_instance[0] == 0)
920 snprintf(string, string_size, "%s/%s/%s", ident->host, ident->plugin,
923 snprintf(string, string_size, "%s/%s/%s-%s", ident->host, ident->plugin,
924 ident->type, ident->type_instance);
926 if (ident->type_instance[0] == 0)
927 snprintf(string, string_size, "%s/%s-%s/%s", ident->host, ident->plugin,
928 ident->plugin_instance, ident->type);
930 snprintf(string, string_size, "%s/%s-%s/%s-%s", ident->host,
931 ident->plugin, ident->plugin_instance, ident->type,
932 ident->type_instance);
935 string[string_size - 1] = '\0';
937 } /* }}} int lcc_identifier_to_string */
939 int lcc_string_to_identifier(lcc_connection_t *c, /* {{{ */
940 lcc_identifier_t *ident, const char *string) {
944 char *plugin_instance;
948 string_copy = strdup(string);
949 if (string_copy == NULL) {
950 lcc_set_errno(c, ENOMEM);
955 plugin = strchr(host, '/');
956 if (plugin == NULL) {
957 LCC_SET_ERRSTR(c, "Malformed identifier string: %s", string);
964 type = strchr(plugin, '/');
966 LCC_SET_ERRSTR(c, "Malformed identifier string: %s", string);
973 plugin_instance = strchr(plugin, '-');
974 if (plugin_instance != NULL) {
975 *plugin_instance = 0;
979 type_instance = strchr(type, '-');
980 if (type_instance != NULL) {
985 memset(ident, 0, sizeof(*ident));
987 SSTRCPY(ident->host, host);
988 SSTRCPY(ident->plugin, plugin);
989 if (plugin_instance != NULL)
990 SSTRCPY(ident->plugin_instance, plugin_instance);
991 SSTRCPY(ident->type, type);
992 if (type_instance != NULL)
993 SSTRCPY(ident->type_instance, type_instance);
997 } /* }}} int lcc_string_to_identifier */
999 int lcc_identifier_compare(const void *a, /* {{{ */
1001 const lcc_identifier_t *i0 = a;
1002 const lcc_identifier_t *i1 = b;
1005 if ((i0 == NULL) && (i1 == NULL))
1007 else if (i0 == NULL)
1009 else if (i1 == NULL)
1012 #define CMP_FIELD(f) \
1014 status = strcmp(i0->f, i1->f); \
1021 CMP_FIELD(plugin_instance);
1023 CMP_FIELD(type_instance);
1028 } /* }}} int lcc_identifier_compare */
1030 int lcc_sort_identifiers(lcc_connection_t *c, /* {{{ */
1031 lcc_identifier_t *idents, size_t idents_num) {
1032 if (idents == NULL) {
1033 lcc_set_errno(c, EINVAL);
1037 qsort(idents, idents_num, sizeof(*idents), lcc_identifier_compare);
1039 } /* }}} int lcc_sort_identifiers */