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"
45 #include <sys/socket.h>
46 #include <sys/types.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! */
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) \
73 strncpy((d), (s), sizeof(d)); \
74 (d)[sizeof(d) - 1] = 0; \
77 #define SSTRCAT(d, s) \
79 size_t _l = strlen(d); \
80 strncpy((d) + _l, (s), sizeof(d) - _l); \
81 (d)[sizeof(d) - 1] = 0; \
84 #define SSTRCATF(d, ...) \
87 snprintf(_b, sizeof(_b), __VA_ARGS__); \
88 _b[sizeof(_b) - 1] = 0; \
92 #define LCC_SET_ERRSTR(c, ...) \
94 snprintf((c)->errbuf, sizeof((c)->errbuf), __VA_ARGS__); \
95 (c)->errbuf[sizeof((c)->errbuf) - 1] = 0; \
101 struct lcc_connection_s {
106 struct lcc_response_s {
112 typedef struct lcc_response_s lcc_response_t;
117 __attribute__((format(printf, 1, 0))) 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) {
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);
148 if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
149 strncpy(buf, temp, buflen);
151 strncpy(buf, "strerror_r did not return "
156 /* #endif STRERROR_R_CHAR_P */
159 if (strerror_r(errnum, buf, buflen) != 0) {
160 snprintf(buf, buflen, "Error #%i; "
161 "Additionally, strerror_r failed.",
164 #endif /* STRERROR_R_CHAR_P */
169 } /* char *sstrerror */
171 static int lcc_set_errno(lcc_connection_t *c, int err) /* {{{ */
176 sstrerror(err, c->errbuf, sizeof(c->errbuf));
177 c->errbuf[sizeof(c->errbuf) - 1] = 0;
180 } /* }}} int lcc_set_errno */
182 static char *lcc_strescape(char *dest, const char *src,
183 size_t dest_size) /* {{{ */
188 if ((dest == NULL) || (src == NULL))
194 assert(dest_size >= 3);
196 dest[dest_pos] = '"';
200 if ((dest_pos == (dest_size - 2)) || (src[src_pos] == 0))
203 if ((src[src_pos] == '"') || (src[src_pos] == '\\')) {
204 /* Check if there is enough space for both characters.. */
205 if (dest_pos == (dest_size - 3))
208 dest[dest_pos] = '\\';
212 dest[dest_pos] = src[src_pos];
217 assert(dest_pos <= (dest_size - 2));
219 dest[dest_pos] = '"';
227 } /* }}} char *lcc_strescape */
229 /* lcc_chomp: Removes all control-characters at the end of a string. */
230 static void lcc_chomp(char *str) /* {{{ */
234 str_len = strlen(str);
235 while (str_len > 0) {
236 if (str[str_len - 1] >= 32)
238 str[str_len - 1] = 0;
241 } /* }}} void lcc_chomp */
243 static void lcc_response_free(lcc_response_t *res) /* {{{ */
248 for (size_t i = 0; i < res->lines_num; i++)
252 } /* }}} void lcc_response_free */
254 static int lcc_send(lcc_connection_t *c, const char *command) /* {{{ */
258 lcc_tracef("send: --> %s\n", command);
260 status = fprintf(c->fh, "%s\r\n", command);
262 lcc_set_errno(c, errno);
268 } /* }}} int lcc_send */
270 static int lcc_receive(lcc_connection_t *c, /* {{{ */
271 lcc_response_t *ret_res) {
272 lcc_response_t res = {0};
277 /* Read the first line, containing the status and a message */
278 ptr = fgets(buffer, sizeof(buffer), c->fh);
280 lcc_set_errno(c, errno);
284 lcc_tracef("receive: <-- %s\n", buffer);
286 /* Convert the leading status to an integer and make `ptr' to point to the
287 * beginning of the message. */
290 res.status = (int)strtol(buffer, &ptr, 0);
291 if ((errno != 0) || (ptr == &buffer[0])) {
292 lcc_set_errno(c, errno);
296 /* Skip white spaces after the status number */
297 while ((*ptr == ' ') || (*ptr == '\t'))
300 /* Now copy the message. */
301 strncpy(res.message, ptr, sizeof(res.message));
302 res.message[sizeof(res.message) - 1] = 0;
304 /* Error or no lines follow: We're done. */
305 if (res.status <= 0) {
306 memcpy(ret_res, &res, sizeof(res));
310 /* Allocate space for the char-pointers */
311 res.lines_num = (size_t)res.status;
313 res.lines = malloc(res.lines_num * sizeof(*res.lines));
314 if (res.lines == NULL) {
315 lcc_set_errno(c, ENOMEM);
319 /* Now receive all the lines */
320 for (i = 0; i < res.lines_num; i++) {
321 ptr = fgets(buffer, sizeof(buffer), c->fh);
323 lcc_set_errno(c, errno);
327 lcc_tracef("receive: <-- %s\n", buffer);
329 res.lines[i] = strdup(buffer);
330 if (res.lines[i] == NULL) {
331 lcc_set_errno(c, ENOMEM);
336 /* Check if the for-loop exited with an error. */
337 if (i < res.lines_num) {
346 memcpy(ret_res, &res, sizeof(res));
348 } /* }}} int lcc_receive */
350 static int lcc_sendreceive(lcc_connection_t *c, /* {{{ */
351 const char *command, lcc_response_t *ret_res) {
352 lcc_response_t res = {0};
356 lcc_set_errno(c, EBADF);
360 status = lcc_send(c, command);
364 status = lcc_receive(c, &res);
366 memcpy(ret_res, &res, sizeof(*ret_res));
369 } /* }}} int lcc_sendreceive */
371 static int lcc_open_unixsocket(lcc_connection_t *c, const char *path) /* {{{ */
373 struct sockaddr_un sa = {0};
378 assert(c->fh == NULL);
379 assert(path != NULL);
381 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
383 fd = socket(AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
385 lcc_set_errno(c, errno);
389 sa.sun_family = AF_UNIX;
390 strncpy(sa.sun_path, path, sizeof(sa.sun_path) - 1);
392 status = connect(fd, (struct sockaddr *)&sa, sizeof(sa));
394 lcc_set_errno(c, errno);
399 c->fh = fdopen(fd, "r+");
401 lcc_set_errno(c, errno);
407 } /* }}} int lcc_open_unixsocket */
409 static int lcc_open_netsocket(lcc_connection_t *c, /* {{{ */
410 const char *addr_orig) {
411 struct addrinfo *ai_res;
412 char addr_copy[NI_MAXHOST];
419 assert(c->fh == NULL);
420 assert(addr_orig != NULL);
422 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
423 addr_copy[sizeof(addr_copy) - 1] = '\0';
427 if (*addr == '[') /* IPv6+port format */
429 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
432 port = strchr(addr, ']');
434 LCC_SET_ERRSTR(c, "malformed address: %s", addr_orig);
445 LCC_SET_ERRSTR(c, "garbage after address: %s", port);
448 } /* if (*addr = ']') */
449 else if (strchr(addr, '.') != NULL) /* Hostname or IPv4 */
451 port = strrchr(addr, ':');
458 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
459 .ai_flags = AI_ADDRCONFIG,
460 .ai_socktype = SOCK_STREAM};
462 status = getaddrinfo(addr, port == NULL ? LCC_DEFAULT_PORT : port, &ai_hints,
465 LCC_SET_ERRSTR(c, "getaddrinfo: %s", gai_strerror(status));
469 for (struct addrinfo *ai_ptr = ai_res; ai_ptr != NULL;
470 ai_ptr = ai_ptr->ai_next) {
471 fd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
477 status = connect(fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
484 c->fh = fdopen(fd, "r+");
496 lcc_set_errno(c, status);
497 freeaddrinfo(ai_res);
501 freeaddrinfo(ai_res);
503 } /* }}} int lcc_open_netsocket */
505 static int lcc_open_socket(lcc_connection_t *c, const char *addr) /* {{{ */
513 assert(c->fh == NULL);
514 assert(addr != NULL);
516 if (strncmp("unix:", addr, strlen("unix:")) == 0)
517 status = lcc_open_unixsocket(c, addr + strlen("unix:"));
518 else if (addr[0] == '/')
519 status = lcc_open_unixsocket(c, addr);
521 status = lcc_open_netsocket(c, addr);
524 } /* }}} int lcc_open_socket */
529 unsigned int lcc_version(void) /* {{{ */
532 } /* }}} unsigned int lcc_version */
534 const char *lcc_version_string(void) /* {{{ */
536 return LCC_VERSION_STRING;
537 } /* }}} const char *lcc_version_string */
539 const char *lcc_version_extra(void) /* {{{ */
541 return LCC_VERSION_EXTRA;
542 } /* }}} const char *lcc_version_extra */
544 int lcc_connect(const char *address, lcc_connection_t **ret_con) /* {{{ */
555 c = calloc(1, sizeof(*c));
559 status = lcc_open_socket(c, address);
567 } /* }}} int lcc_connect */
569 int lcc_disconnect(lcc_connection_t *c) /* {{{ */
581 } /* }}} int lcc_disconnect */
583 int lcc_getval(lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
584 size_t *ret_values_num, gauge_t **ret_values,
585 char ***ret_values_names) {
586 char ident_str[6 * LCC_NAME_LEN];
587 char ident_esc[12 * LCC_NAME_LEN];
588 char command[14 * LCC_NAME_LEN];
592 gauge_t *values = NULL;
593 char **values_names = NULL;
602 lcc_set_errno(c, EINVAL);
606 /* Build a commend with an escaped version of the identifier string. */
607 status = lcc_identifier_to_string(c, ident_str, sizeof(ident_str), ident);
611 snprintf(command, sizeof(command), "GETVAL %s",
612 lcc_strescape(ident_esc, ident_str, sizeof(ident_esc)));
613 command[sizeof(command) - 1] = 0;
615 /* Send talk to the daemon.. */
616 status = lcc_sendreceive(c, command, &res);
620 if (res.status != 0) {
621 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
622 lcc_response_free(&res);
626 values_num = res.lines_num;
628 #define BAIL_OUT(e) \
630 lcc_set_errno(c, (e)); \
632 if (values_names != NULL) { \
633 for (i = 0; i < values_num; i++) { \
634 free(values_names[i]); \
637 free(values_names); \
638 lcc_response_free(&res); \
642 /* If neither the values nor the names are requested, return here.. */
643 if ((ret_values == NULL) && (ret_values_names == NULL)) {
644 if (ret_values_num != NULL)
645 *ret_values_num = values_num;
646 lcc_response_free(&res);
650 /* Allocate space for the values */
651 if (ret_values != NULL) {
652 values = malloc(values_num * sizeof(*values));
657 if (ret_values_names != NULL) {
658 values_names = calloc(values_num, sizeof(*values_names));
659 if (values_names == NULL)
663 for (i = 0; i < res.lines_num; i++) {
669 value = strchr(key, '=');
676 if (values != NULL) {
679 values[i] = strtod(value, &endptr);
681 if ((endptr == value) || (errno != 0))
685 if (values_names != NULL) {
686 values_names[i] = strdup(key);
687 if (values_names[i] == NULL)
690 } /* for (i = 0; i < res.lines_num; i++) */
692 if (ret_values_num != NULL)
693 *ret_values_num = values_num;
694 if (ret_values != NULL)
695 *ret_values = values;
696 if (ret_values_names != NULL)
697 *ret_values_names = values_names;
699 lcc_response_free(&res);
702 } /* }}} int lcc_getval */
704 int lcc_putval(lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
706 char ident_str[6 * LCC_NAME_LEN];
707 char ident_esc[12 * LCC_NAME_LEN];
708 char command[1024] = "";
712 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1) ||
713 (vl->values == NULL) || (vl->values_types == NULL)) {
714 lcc_set_errno(c, EINVAL);
718 status = lcc_identifier_to_string(c, ident_str, sizeof(ident_str),
723 SSTRCATF(command, "PUTVAL %s",
724 lcc_strescape(ident_esc, ident_str, sizeof(ident_esc)));
726 if (vl->interval > 0.0)
727 SSTRCATF(command, " interval=%.3f", vl->interval);
730 SSTRCATF(command, " %.3f", vl->time);
732 SSTRCAT(command, " N");
734 for (size_t i = 0; i < vl->values_len; i++) {
735 if (vl->values_types[i] == LCC_TYPE_COUNTER)
736 SSTRCATF(command, ":%" PRIu64, vl->values[i].counter);
737 else if (vl->values_types[i] == LCC_TYPE_GAUGE) {
738 if (isnan(vl->values[i].gauge))
739 SSTRCATF(command, ":U");
741 SSTRCATF(command, ":%g", vl->values[i].gauge);
742 } else if (vl->values_types[i] == LCC_TYPE_DERIVE)
743 SSTRCATF(command, ":%" PRIu64, vl->values[i].derive);
744 else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
745 SSTRCATF(command, ":%" PRIu64, vl->values[i].absolute);
747 } /* for (i = 0; i < vl->values_len; i++) */
749 status = lcc_sendreceive(c, command, &res);
753 if (res.status != 0) {
754 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
755 lcc_response_free(&res);
759 lcc_response_free(&res);
761 } /* }}} int lcc_putval */
763 int lcc_flush(lcc_connection_t *c, const char *plugin, /* {{{ */
764 lcc_identifier_t *ident, int timeout) {
765 char command[1024] = "";
770 lcc_set_errno(c, EINVAL);
774 SSTRCPY(command, "FLUSH");
777 SSTRCATF(command, " timeout=%i", timeout);
779 if (plugin != NULL) {
780 char buffer[2 * LCC_NAME_LEN];
781 SSTRCATF(command, " plugin=%s",
782 lcc_strescape(buffer, plugin, sizeof(buffer)));
786 char ident_str[6 * LCC_NAME_LEN];
787 char ident_esc[12 * LCC_NAME_LEN];
789 status = lcc_identifier_to_string(c, ident_str, sizeof(ident_str), ident);
793 SSTRCATF(command, " identifier=%s",
794 lcc_strescape(ident_esc, ident_str, sizeof(ident_esc)));
797 status = lcc_sendreceive(c, command, &res);
801 if (res.status != 0) {
802 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
803 lcc_response_free(&res);
807 lcc_response_free(&res);
809 } /* }}} int lcc_flush */
811 /* TODO: Implement lcc_putnotif */
813 int lcc_listval(lcc_connection_t *c, /* {{{ */
814 lcc_identifier_t **ret_ident, size_t *ret_ident_num) {
818 lcc_identifier_t *ident;
824 if ((ret_ident == NULL) || (ret_ident_num == NULL)) {
825 lcc_set_errno(c, EINVAL);
829 status = lcc_sendreceive(c, "LISTVAL", &res);
833 if (res.status != 0) {
834 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
835 lcc_response_free(&res);
839 ident_num = res.lines_num;
840 ident = malloc(ident_num * sizeof(*ident));
842 lcc_response_free(&res);
843 lcc_set_errno(c, ENOMEM);
847 for (size_t i = 0; i < res.lines_num; i++) {
851 /* First field is the time. */
852 time_str = res.lines[i];
854 /* Set `ident_str' to the beginning of the second field. */
855 ident_str = time_str;
856 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
858 while ((*ident_str == ' ') || (*ident_str == '\t')) {
863 if (*ident_str == 0) {
864 lcc_set_errno(c, EILSEQ);
869 status = lcc_string_to_identifier(c, ident + i, ident_str);
874 lcc_response_free(&res);
882 *ret_ident_num = ident_num;
885 } /* }}} int lcc_listval */
887 const char *lcc_strerror(lcc_connection_t *c) /* {{{ */
890 return "Invalid object";
892 } /* }}} const char *lcc_strerror */
894 int lcc_identifier_to_string(lcc_connection_t *c, /* {{{ */
895 char *string, size_t string_size,
896 const lcc_identifier_t *ident) {
897 if ((string == NULL) || (string_size < 6) || (ident == NULL)) {
898 lcc_set_errno(c, EINVAL);
902 if (ident->plugin_instance[0] == 0) {
903 if (ident->type_instance[0] == 0)
904 snprintf(string, string_size, "%s/%s/%s", ident->host, ident->plugin,
907 snprintf(string, string_size, "%s/%s/%s-%s", ident->host, ident->plugin,
908 ident->type, ident->type_instance);
910 if (ident->type_instance[0] == 0)
911 snprintf(string, string_size, "%s/%s-%s/%s", ident->host, ident->plugin,
912 ident->plugin_instance, ident->type);
914 snprintf(string, string_size, "%s/%s-%s/%s-%s", ident->host,
915 ident->plugin, ident->plugin_instance, ident->type,
916 ident->type_instance);
919 string[string_size - 1] = 0;
921 } /* }}} int lcc_identifier_to_string */
923 int lcc_string_to_identifier(lcc_connection_t *c, /* {{{ */
924 lcc_identifier_t *ident, const char *string) {
928 char *plugin_instance;
932 string_copy = strdup(string);
933 if (string_copy == NULL) {
934 lcc_set_errno(c, ENOMEM);
939 plugin = strchr(host, '/');
940 if (plugin == NULL) {
941 LCC_SET_ERRSTR(c, "Malformed identifier string: %s", string);
948 type = strchr(plugin, '/');
950 LCC_SET_ERRSTR(c, "Malformed identifier string: %s", string);
957 plugin_instance = strchr(plugin, '-');
958 if (plugin_instance != NULL) {
959 *plugin_instance = 0;
963 type_instance = strchr(type, '-');
964 if (type_instance != NULL) {
969 memset(ident, 0, sizeof(*ident));
971 SSTRCPY(ident->host, host);
972 SSTRCPY(ident->plugin, plugin);
973 if (plugin_instance != NULL)
974 SSTRCPY(ident->plugin_instance, plugin_instance);
975 SSTRCPY(ident->type, type);
976 if (type_instance != NULL)
977 SSTRCPY(ident->type_instance, type_instance);
981 } /* }}} int lcc_string_to_identifier */
983 int lcc_identifier_compare(const void *a, /* {{{ */
985 const lcc_identifier_t *i0 = a;
986 const lcc_identifier_t *i1 = b;
989 if ((i0 == NULL) && (i1 == NULL))
996 #define CMP_FIELD(f) \
998 status = strcmp(i0->f, i1->f); \
1005 CMP_FIELD(plugin_instance);
1007 CMP_FIELD(type_instance);
1012 } /* }}} int lcc_identifier_compare */
1014 int lcc_sort_identifiers(lcc_connection_t *c, /* {{{ */
1015 lcc_identifier_t *idents, size_t idents_num) {
1016 if (idents == NULL) {
1017 lcc_set_errno(c, EINVAL);
1021 qsort(idents, idents_num, sizeof(*idents), lcc_identifier_compare);
1023 } /* }}} int lcc_sort_identifiers */