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)); \
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);
160 strncpy(buf, "strerror_r did not return "
165 /* #endif STRERROR_R_CHAR_P */
168 if (strerror_r(errnum, buf, buflen) != 0) {
169 snprintf(buf, buflen, "Error #%i; "
170 "Additionally, strerror_r failed.",
173 #endif /* STRERROR_R_CHAR_P */
178 } /* char *sstrerror */
180 static int lcc_set_errno(lcc_connection_t *c, int err) /* {{{ */
185 sstrerror(err, c->errbuf, sizeof(c->errbuf));
186 c->errbuf[sizeof(c->errbuf) - 1] = 0;
189 } /* }}} int lcc_set_errno */
191 static char *lcc_strescape(char *dest, const char *src,
192 size_t dest_size) /* {{{ */
197 if ((dest == NULL) || (src == NULL))
203 assert(dest_size >= 3);
205 dest[dest_pos] = '"';
209 if ((dest_pos == (dest_size - 2)) || (src[src_pos] == 0))
212 if ((src[src_pos] == '"') || (src[src_pos] == '\\')) {
213 /* Check if there is enough space for both characters.. */
214 if (dest_pos == (dest_size - 3))
217 dest[dest_pos] = '\\';
221 dest[dest_pos] = src[src_pos];
226 assert(dest_pos <= (dest_size - 2));
228 dest[dest_pos] = '"';
236 } /* }}} char *lcc_strescape */
238 /* lcc_chomp: Removes all control-characters at the end of a string. */
239 static void lcc_chomp(char *str) /* {{{ */
243 str_len = strlen(str);
244 while (str_len > 0) {
245 if (str[str_len - 1] >= 32)
247 str[str_len - 1] = 0;
250 } /* }}} void lcc_chomp */
252 static void lcc_response_free(lcc_response_t *res) /* {{{ */
257 for (size_t i = 0; i < res->lines_num; i++)
261 } /* }}} void lcc_response_free */
263 static int lcc_send(lcc_connection_t *c, const char *command) /* {{{ */
267 lcc_tracef("send: --> %s\n", command);
269 status = fprintf(c->fh, "%s\r\n", command);
271 lcc_set_errno(c, errno);
277 } /* }}} int lcc_send */
279 static int lcc_receive(lcc_connection_t *c, /* {{{ */
280 lcc_response_t *ret_res) {
281 lcc_response_t res = {0};
286 /* Read the first line, containing the status and a message */
287 ptr = fgets(buffer, sizeof(buffer), c->fh);
289 lcc_set_errno(c, errno);
293 lcc_tracef("receive: <-- %s\n", buffer);
295 /* Convert the leading status to an integer and make `ptr' to point to the
296 * beginning of the message. */
299 res.status = (int)strtol(buffer, &ptr, 0);
300 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. */
314 if (res.status <= 0) {
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) {
324 lcc_set_errno(c, ENOMEM);
328 /* Now receive all the lines */
329 for (i = 0; i < res.lines_num; i++) {
330 ptr = fgets(buffer, sizeof(buffer), c->fh);
332 lcc_set_errno(c, errno);
336 lcc_tracef("receive: <-- %s\n", buffer);
338 res.lines[i] = strdup(buffer);
339 if (res.lines[i] == NULL) {
340 lcc_set_errno(c, ENOMEM);
345 /* Check if the for-loop exited with an error. */
346 if (i < res.lines_num) {
355 memcpy(ret_res, &res, sizeof(res));
357 } /* }}} int lcc_receive */
359 static int lcc_sendreceive(lcc_connection_t *c, /* {{{ */
360 const char *command, lcc_response_t *ret_res) {
361 lcc_response_t res = {0};
365 lcc_set_errno(c, EBADF);
369 status = lcc_send(c, command);
373 status = lcc_receive(c, &res);
375 memcpy(ret_res, &res, sizeof(*ret_res));
378 } /* }}} int lcc_sendreceive */
380 static int lcc_open_unixsocket(lcc_connection_t *c, const char *path) /* {{{ */
383 lcc_set_errno(c, ENOTSUP);
386 struct sockaddr_un sa = {0};
391 assert(c->fh == NULL);
392 assert(path != NULL);
394 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
396 fd = socket(AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
398 lcc_set_errno(c, errno);
402 sa.sun_family = AF_UNIX;
403 strncpy(sa.sun_path, path, sizeof(sa.sun_path) - 1);
405 status = connect(fd, (struct sockaddr *)&sa, sizeof(sa));
407 lcc_set_errno(c, errno);
412 c->fh = fdopen(fd, "r+");
414 lcc_set_errno(c, errno);
421 } /* }}} int lcc_open_unixsocket */
423 static int lcc_open_netsocket(lcc_connection_t *c, /* {{{ */
424 const char *addr_orig) {
425 struct addrinfo *ai_res;
426 char addr_copy[NI_MAXHOST];
433 assert(c->fh == NULL);
434 assert(addr_orig != NULL);
436 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
437 addr_copy[sizeof(addr_copy) - 1] = '\0';
441 if (*addr == '[') /* IPv6+port format */
443 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
446 port = strchr(addr, ']');
448 LCC_SET_ERRSTR(c, "malformed address: %s", addr_orig);
459 LCC_SET_ERRSTR(c, "garbage after address: %s", port);
462 } /* if (*addr = ']') */
463 else if (strchr(addr, '.') != NULL) /* Hostname or IPv4 */
465 port = strrchr(addr, ':');
472 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
473 .ai_flags = AI_ADDRCONFIG,
474 .ai_socktype = SOCK_STREAM};
476 status = getaddrinfo(addr, port == NULL ? LCC_DEFAULT_PORT : port, &ai_hints,
479 LCC_SET_ERRSTR(c, "getaddrinfo: %s", gai_strerror(status));
483 for (struct addrinfo *ai_ptr = ai_res; ai_ptr != NULL;
484 ai_ptr = ai_ptr->ai_next) {
485 fd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
491 status = connect(fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
498 c->fh = fdopen(fd, "r+");
510 lcc_set_errno(c, status);
511 freeaddrinfo(ai_res);
515 freeaddrinfo(ai_res);
517 } /* }}} int lcc_open_netsocket */
519 static int lcc_open_socket(lcc_connection_t *c, const char *addr) /* {{{ */
527 assert(c->fh == NULL);
528 assert(addr != NULL);
530 if (strncmp("unix:", addr, strlen("unix:")) == 0)
531 status = lcc_open_unixsocket(c, addr + strlen("unix:"));
532 else if (addr[0] == '/')
533 status = lcc_open_unixsocket(c, addr);
535 status = lcc_open_netsocket(c, addr);
538 } /* }}} int lcc_open_socket */
543 unsigned int lcc_version(void) /* {{{ */
546 } /* }}} unsigned int lcc_version */
548 const char *lcc_version_string(void) /* {{{ */
550 return LCC_VERSION_STRING;
551 } /* }}} const char *lcc_version_string */
553 const char *lcc_version_extra(void) /* {{{ */
555 return LCC_VERSION_EXTRA;
556 } /* }}} const char *lcc_version_extra */
558 int lcc_connect(const char *address, lcc_connection_t **ret_con) /* {{{ */
569 c = calloc(1, sizeof(*c));
573 status = lcc_open_socket(c, address);
581 } /* }}} int lcc_connect */
583 int lcc_disconnect(lcc_connection_t *c) /* {{{ */
595 } /* }}} int lcc_disconnect */
597 int lcc_getval(lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
598 size_t *ret_values_num, gauge_t **ret_values,
599 char ***ret_values_names) {
600 char ident_str[6 * LCC_NAME_LEN];
601 char ident_esc[12 * LCC_NAME_LEN];
602 char command[14 * LCC_NAME_LEN];
606 gauge_t *values = NULL;
607 char **values_names = NULL;
616 lcc_set_errno(c, EINVAL);
620 /* Build a commend with an escaped version of the identifier string. */
621 status = lcc_identifier_to_string(c, ident_str, sizeof(ident_str), ident);
625 snprintf(command, sizeof(command), "GETVAL %s",
626 lcc_strescape(ident_esc, ident_str, sizeof(ident_esc)));
627 command[sizeof(command) - 1] = 0;
629 /* Send talk to the daemon.. */
630 status = lcc_sendreceive(c, command, &res);
634 if (res.status != 0) {
635 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
636 lcc_response_free(&res);
640 values_num = res.lines_num;
642 #define BAIL_OUT(e) \
644 lcc_set_errno(c, (e)); \
646 if (values_names != NULL) { \
647 for (i = 0; i < values_num; i++) { \
648 free(values_names[i]); \
651 free(values_names); \
652 lcc_response_free(&res); \
656 /* If neither the values nor the names are requested, return here.. */
657 if ((ret_values == NULL) && (ret_values_names == NULL)) {
658 if (ret_values_num != NULL)
659 *ret_values_num = values_num;
660 lcc_response_free(&res);
664 /* Allocate space for the values */
665 if (ret_values != NULL) {
666 values = malloc(values_num * sizeof(*values));
671 if (ret_values_names != NULL) {
672 values_names = calloc(values_num, sizeof(*values_names));
673 if (values_names == NULL)
677 for (i = 0; i < res.lines_num; i++) {
683 value = strchr(key, '=');
690 if (values != NULL) {
693 values[i] = strtod(value, &endptr);
695 if ((endptr == value) || (errno != 0))
699 if (values_names != NULL) {
700 values_names[i] = strdup(key);
701 if (values_names[i] == NULL)
704 } /* for (i = 0; i < res.lines_num; i++) */
706 if (ret_values_num != NULL)
707 *ret_values_num = values_num;
708 if (ret_values != NULL)
709 *ret_values = values;
710 if (ret_values_names != NULL)
711 *ret_values_names = values_names;
713 lcc_response_free(&res);
716 } /* }}} int lcc_getval */
718 int lcc_putval(lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
720 char ident_str[6 * LCC_NAME_LEN];
721 char ident_esc[12 * LCC_NAME_LEN];
722 char command[1024] = "";
726 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1) ||
727 (vl->values == NULL) || (vl->values_types == NULL)) {
728 lcc_set_errno(c, EINVAL);
732 status = lcc_identifier_to_string(c, ident_str, sizeof(ident_str),
737 SSTRCATF(command, "PUTVAL %s",
738 lcc_strescape(ident_esc, ident_str, sizeof(ident_esc)));
740 if (vl->interval > 0.0)
741 SSTRCATF(command, " interval=%.3f", vl->interval);
744 SSTRCATF(command, " %.3f", vl->time);
746 SSTRCAT(command, " N");
748 for (size_t i = 0; i < vl->values_len; i++) {
749 if (vl->values_types[i] == LCC_TYPE_COUNTER)
750 SSTRCATF(command, ":%" PRIu64, vl->values[i].counter);
751 else if (vl->values_types[i] == LCC_TYPE_GAUGE) {
752 if (isnan(vl->values[i].gauge))
753 SSTRCATF(command, ":U");
755 SSTRCATF(command, ":%g", vl->values[i].gauge);
756 } else if (vl->values_types[i] == LCC_TYPE_DERIVE)
757 SSTRCATF(command, ":%" PRIu64, vl->values[i].derive);
758 else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
759 SSTRCATF(command, ":%" PRIu64, vl->values[i].absolute);
761 } /* for (i = 0; i < vl->values_len; i++) */
763 status = lcc_sendreceive(c, command, &res);
767 if (res.status != 0) {
768 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
769 lcc_response_free(&res);
773 lcc_response_free(&res);
775 } /* }}} int lcc_putval */
777 int lcc_flush(lcc_connection_t *c, const char *plugin, /* {{{ */
778 lcc_identifier_t *ident, int timeout) {
779 char command[1024] = "";
784 lcc_set_errno(c, EINVAL);
788 SSTRCPY(command, "FLUSH");
791 SSTRCATF(command, " timeout=%i", timeout);
793 if (plugin != NULL) {
794 char buffer[2 * LCC_NAME_LEN];
795 SSTRCATF(command, " plugin=%s",
796 lcc_strescape(buffer, plugin, sizeof(buffer)));
800 char ident_str[6 * LCC_NAME_LEN];
801 char ident_esc[12 * LCC_NAME_LEN];
803 status = lcc_identifier_to_string(c, ident_str, sizeof(ident_str), ident);
807 SSTRCATF(command, " identifier=%s",
808 lcc_strescape(ident_esc, ident_str, sizeof(ident_esc)));
811 status = lcc_sendreceive(c, command, &res);
815 if (res.status != 0) {
816 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
817 lcc_response_free(&res);
821 lcc_response_free(&res);
823 } /* }}} int lcc_flush */
825 /* TODO: Implement lcc_putnotif */
827 int lcc_listval(lcc_connection_t *c, /* {{{ */
828 lcc_identifier_t **ret_ident, size_t *ret_ident_num) {
832 lcc_identifier_t *ident;
838 if ((ret_ident == NULL) || (ret_ident_num == NULL)) {
839 lcc_set_errno(c, EINVAL);
843 status = lcc_sendreceive(c, "LISTVAL", &res);
847 if (res.status != 0) {
848 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
849 lcc_response_free(&res);
853 ident_num = res.lines_num;
854 ident = malloc(ident_num * sizeof(*ident));
856 lcc_response_free(&res);
857 lcc_set_errno(c, ENOMEM);
861 for (size_t i = 0; i < res.lines_num; i++) {
865 /* First field is the time. */
866 time_str = res.lines[i];
868 /* Set `ident_str' to the beginning of the second field. */
869 ident_str = time_str;
870 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
872 while ((*ident_str == ' ') || (*ident_str == '\t')) {
877 if (*ident_str == 0) {
878 lcc_set_errno(c, EILSEQ);
883 status = lcc_string_to_identifier(c, ident + i, ident_str);
888 lcc_response_free(&res);
896 *ret_ident_num = ident_num;
899 } /* }}} int lcc_listval */
901 const char *lcc_strerror(lcc_connection_t *c) /* {{{ */
904 return "Invalid object";
906 } /* }}} const char *lcc_strerror */
908 int lcc_identifier_to_string(lcc_connection_t *c, /* {{{ */
909 char *string, size_t string_size,
910 const lcc_identifier_t *ident) {
911 if ((string == NULL) || (string_size < 6) || (ident == NULL)) {
912 lcc_set_errno(c, EINVAL);
916 if (ident->plugin_instance[0] == 0) {
917 if (ident->type_instance[0] == 0)
918 snprintf(string, string_size, "%s/%s/%s", ident->host, ident->plugin,
921 snprintf(string, string_size, "%s/%s/%s-%s", ident->host, ident->plugin,
922 ident->type, ident->type_instance);
924 if (ident->type_instance[0] == 0)
925 snprintf(string, string_size, "%s/%s-%s/%s", ident->host, ident->plugin,
926 ident->plugin_instance, ident->type);
928 snprintf(string, string_size, "%s/%s-%s/%s-%s", ident->host,
929 ident->plugin, ident->plugin_instance, ident->type,
930 ident->type_instance);
933 string[string_size - 1] = 0;
935 } /* }}} int lcc_identifier_to_string */
937 int lcc_string_to_identifier(lcc_connection_t *c, /* {{{ */
938 lcc_identifier_t *ident, const char *string) {
942 char *plugin_instance;
946 string_copy = strdup(string);
947 if (string_copy == NULL) {
948 lcc_set_errno(c, ENOMEM);
953 plugin = strchr(host, '/');
954 if (plugin == NULL) {
955 LCC_SET_ERRSTR(c, "Malformed identifier string: %s", string);
962 type = strchr(plugin, '/');
964 LCC_SET_ERRSTR(c, "Malformed identifier string: %s", string);
971 plugin_instance = strchr(plugin, '-');
972 if (plugin_instance != NULL) {
973 *plugin_instance = 0;
977 type_instance = strchr(type, '-');
978 if (type_instance != NULL) {
983 memset(ident, 0, sizeof(*ident));
985 SSTRCPY(ident->host, host);
986 SSTRCPY(ident->plugin, plugin);
987 if (plugin_instance != NULL)
988 SSTRCPY(ident->plugin_instance, plugin_instance);
989 SSTRCPY(ident->type, type);
990 if (type_instance != NULL)
991 SSTRCPY(ident->type_instance, type_instance);
995 } /* }}} int lcc_string_to_identifier */
997 int lcc_identifier_compare(const void *a, /* {{{ */
999 const lcc_identifier_t *i0 = a;
1000 const lcc_identifier_t *i1 = b;
1003 if ((i0 == NULL) && (i1 == NULL))
1005 else if (i0 == NULL)
1007 else if (i1 == NULL)
1010 #define CMP_FIELD(f) \
1012 status = strcmp(i0->f, i1->f); \
1019 CMP_FIELD(plugin_instance);
1021 CMP_FIELD(type_instance);
1026 } /* }}} int lcc_identifier_compare */
1028 int lcc_sort_identifiers(lcc_connection_t *c, /* {{{ */
1029 lcc_identifier_t *idents, size_t idents_num) {
1030 if (idents == NULL) {
1031 lcc_set_errno(c, EINVAL);
1035 qsort(idents, idents_num, sizeof(*idents), lcc_identifier_compare);
1037 } /* }}} int lcc_sort_identifiers */