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>
29 #if !defined(__GNUC__) || !__GNUC__
30 #define __attribute__(x) /**/
33 #include "collectd/lcc_features.h"
43 #include <sys/socket.h>
44 #include <sys/types.h>
48 #include "collectd/client.h"
50 /* NI_MAXHOST has been obsoleted by RFC 3493 which is a reason for SunOS 5.11
51 * to no longer define it. We'll use the old, RFC 2553 value here. */
53 #define NI_MAXHOST 1025
56 /* OpenBSD doesn't have EPROTO, FreeBSD doesn't have EILSEQ. Oh what joy! */
65 /* Secure/static macros. They work like `strcpy' and `strcat', but assure null
66 * termination. They work for static buffers only, because they use `sizeof'.
67 * The `SSTRCATF' combines the functionality of `snprintf' and `strcat' which
68 * is very useful to add formatted stuff to the end of a buffer. */
69 #define SSTRCPY(d, s) \
71 strncpy((d), (s), sizeof(d)); \
72 (d)[sizeof(d) - 1] = 0; \
75 #define SSTRCAT(d, s) \
77 size_t _l = strlen(d); \
78 strncpy((d) + _l, (s), sizeof(d) - _l); \
79 (d)[sizeof(d) - 1] = 0; \
82 #define SSTRCATF(d, ...) \
85 snprintf(_b, sizeof(_b), __VA_ARGS__); \
86 _b[sizeof(_b) - 1] = 0; \
90 #define LCC_SET_ERRSTR(c, ...) \
92 snprintf((c)->errbuf, sizeof((c)->errbuf), __VA_ARGS__); \
98 struct lcc_connection_s {
103 struct lcc_response_s {
109 typedef struct lcc_response_s lcc_response_t;
114 __attribute__((format(printf, 1, 0))) static int lcc_tracef(char const *format,
119 char const *trace = getenv(LCC_TRACE_ENV);
120 if (!trace || (strcmp("", trace) == 0) || (strcmp("0", trace) == 0))
123 va_start(ap, format);
124 status = vprintf(format, ap);
130 /* Even though Posix requires "strerror_r" to return an "int",
131 * some systems (e.g. the GNU libc) return a "char *" _and_
132 * ignore the second argument ... -tokkee */
133 static char *sstrerror(int errnum, char *buf, size_t buflen) {
137 snprintf(buf, buflen, "Error #%i; strerror_r is not available.", errnum);
138 /* #endif !HAVE_STRERROR_R */
140 #elif STRERROR_R_CHAR_P
143 temp = strerror_r(errnum, buf, buflen);
145 if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
146 strncpy(buf, temp, buflen);
148 strncpy(buf, "strerror_r did not return "
153 /* #endif STRERROR_R_CHAR_P */
156 if (strerror_r(errnum, buf, buflen) != 0) {
157 snprintf(buf, buflen, "Error #%i; "
158 "Additionally, strerror_r failed.",
161 #endif /* STRERROR_R_CHAR_P */
166 } /* char *sstrerror */
168 static int lcc_set_errno(lcc_connection_t *c, int err) /* {{{ */
173 sstrerror(err, c->errbuf, sizeof(c->errbuf));
174 c->errbuf[sizeof(c->errbuf) - 1] = 0;
177 } /* }}} int lcc_set_errno */
179 static char *lcc_strescape(char *dest, const char *src,
180 size_t dest_size) /* {{{ */
185 if ((dest == NULL) || (src == NULL))
191 assert(dest_size >= 3);
193 dest[dest_pos] = '"';
197 if ((dest_pos == (dest_size - 2)) || (src[src_pos] == 0))
200 if ((src[src_pos] == '"') || (src[src_pos] == '\\')) {
201 /* Check if there is enough space for both characters.. */
202 if (dest_pos == (dest_size - 3))
205 dest[dest_pos] = '\\';
209 dest[dest_pos] = src[src_pos];
214 assert(dest_pos <= (dest_size - 2));
216 dest[dest_pos] = '"';
224 } /* }}} char *lcc_strescape */
226 /* lcc_chomp: Removes all control-characters at the end of a string. */
227 static void lcc_chomp(char *str) /* {{{ */
231 str_len = strlen(str);
232 while (str_len > 0) {
233 if (str[str_len - 1] >= 32)
235 str[str_len - 1] = 0;
238 } /* }}} void lcc_chomp */
240 static void lcc_response_free(lcc_response_t *res) /* {{{ */
245 for (size_t i = 0; i < res->lines_num; i++)
249 } /* }}} void lcc_response_free */
251 static int lcc_send(lcc_connection_t *c, const char *command) /* {{{ */
255 lcc_tracef("send: --> %s\n", command);
257 status = fprintf(c->fh, "%s\r\n", command);
259 lcc_set_errno(c, errno);
265 } /* }}} int lcc_send */
267 static int lcc_receive(lcc_connection_t *c, /* {{{ */
268 lcc_response_t *ret_res) {
269 lcc_response_t res = {0};
274 /* Read the first line, containing the status and a message */
275 ptr = fgets(buffer, sizeof(buffer), c->fh);
277 lcc_set_errno(c, errno);
281 lcc_tracef("receive: <-- %s\n", buffer);
283 /* Convert the leading status to an integer and make `ptr' to point to the
284 * beginning of the message. */
287 res.status = (int)strtol(buffer, &ptr, 0);
288 if ((errno != 0) || (ptr == &buffer[0])) {
289 lcc_set_errno(c, errno);
293 /* Skip white spaces after the status number */
294 while ((*ptr == ' ') || (*ptr == '\t'))
297 /* Now copy the message. */
298 strncpy(res.message, ptr, sizeof(res.message));
299 res.message[sizeof(res.message) - 1] = 0;
301 /* Error or no lines follow: We're done. */
302 if (res.status <= 0) {
303 memcpy(ret_res, &res, sizeof(res));
307 /* Allocate space for the char-pointers */
308 res.lines_num = (size_t)res.status;
310 res.lines = malloc(res.lines_num * sizeof(*res.lines));
311 if (res.lines == NULL) {
312 lcc_set_errno(c, ENOMEM);
316 /* Now receive all the lines */
317 for (i = 0; i < res.lines_num; i++) {
318 ptr = fgets(buffer, sizeof(buffer), c->fh);
320 lcc_set_errno(c, errno);
324 lcc_tracef("receive: <-- %s\n", buffer);
326 res.lines[i] = strdup(buffer);
327 if (res.lines[i] == NULL) {
328 lcc_set_errno(c, ENOMEM);
333 /* Check if the for-loop exited with an error. */
334 if (i < res.lines_num) {
343 memcpy(ret_res, &res, sizeof(res));
345 } /* }}} int lcc_receive */
347 static int lcc_sendreceive(lcc_connection_t *c, /* {{{ */
348 const char *command, lcc_response_t *ret_res) {
349 lcc_response_t res = {0};
353 lcc_set_errno(c, EBADF);
357 status = lcc_send(c, command);
361 status = lcc_receive(c, &res);
363 memcpy(ret_res, &res, sizeof(*ret_res));
366 } /* }}} int lcc_sendreceive */
368 static int lcc_open_unixsocket(lcc_connection_t *c, const char *path) /* {{{ */
370 struct sockaddr_un sa = {0};
375 assert(c->fh == NULL);
376 assert(path != NULL);
378 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
380 fd = socket(AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
382 lcc_set_errno(c, errno);
386 sa.sun_family = AF_UNIX;
387 strncpy(sa.sun_path, path, sizeof(sa.sun_path) - 1);
389 status = connect(fd, (struct sockaddr *)&sa, sizeof(sa));
391 lcc_set_errno(c, errno);
396 c->fh = fdopen(fd, "r+");
398 lcc_set_errno(c, errno);
404 } /* }}} int lcc_open_unixsocket */
406 static int lcc_open_netsocket(lcc_connection_t *c, /* {{{ */
407 const char *addr_orig) {
408 struct addrinfo *ai_res;
409 char addr_copy[NI_MAXHOST];
416 assert(c->fh == NULL);
417 assert(addr_orig != NULL);
419 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
420 addr_copy[sizeof(addr_copy) - 1] = '\0';
424 if (*addr == '[') /* IPv6+port format */
426 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
429 port = strchr(addr, ']');
431 LCC_SET_ERRSTR(c, "malformed address: %s", addr_orig);
442 LCC_SET_ERRSTR(c, "garbage after address: %s", port);
445 } /* if (*addr = ']') */
446 else if (strchr(addr, '.') != NULL) /* Hostname or IPv4 */
448 port = strrchr(addr, ':');
455 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
456 .ai_flags = AI_ADDRCONFIG,
457 .ai_socktype = SOCK_STREAM};
459 status = getaddrinfo(addr, port == NULL ? LCC_DEFAULT_PORT : port, &ai_hints,
462 LCC_SET_ERRSTR(c, "getaddrinfo: %s", gai_strerror(status));
466 for (struct addrinfo *ai_ptr = ai_res; ai_ptr != NULL;
467 ai_ptr = ai_ptr->ai_next) {
468 fd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
474 status = connect(fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
481 c->fh = fdopen(fd, "r+");
493 lcc_set_errno(c, status);
494 freeaddrinfo(ai_res);
498 freeaddrinfo(ai_res);
500 } /* }}} int lcc_open_netsocket */
502 static int lcc_open_socket(lcc_connection_t *c, const char *addr) /* {{{ */
510 assert(c->fh == NULL);
511 assert(addr != NULL);
513 if (strncmp("unix:", addr, strlen("unix:")) == 0)
514 status = lcc_open_unixsocket(c, addr + strlen("unix:"));
515 else if (addr[0] == '/')
516 status = lcc_open_unixsocket(c, addr);
518 status = lcc_open_netsocket(c, addr);
521 } /* }}} int lcc_open_socket */
526 unsigned int lcc_version(void) /* {{{ */
529 } /* }}} unsigned int lcc_version */
531 const char *lcc_version_string(void) /* {{{ */
533 return LCC_VERSION_STRING;
534 } /* }}} const char *lcc_version_string */
536 const char *lcc_version_extra(void) /* {{{ */
538 return LCC_VERSION_EXTRA;
539 } /* }}} const char *lcc_version_extra */
541 int lcc_connect(const char *address, lcc_connection_t **ret_con) /* {{{ */
552 c = calloc(1, sizeof(*c));
556 status = lcc_open_socket(c, address);
564 } /* }}} int lcc_connect */
566 int lcc_disconnect(lcc_connection_t *c) /* {{{ */
578 } /* }}} int lcc_disconnect */
580 int lcc_getval(lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
581 size_t *ret_values_num, gauge_t **ret_values,
582 char ***ret_values_names) {
583 char ident_str[6 * LCC_NAME_LEN];
584 char ident_esc[12 * LCC_NAME_LEN];
585 char command[14 * LCC_NAME_LEN];
589 gauge_t *values = NULL;
590 char **values_names = NULL;
599 lcc_set_errno(c, EINVAL);
603 /* Build a commend with an escaped version of the identifier string. */
604 status = lcc_identifier_to_string(c, ident_str, sizeof(ident_str), ident);
608 snprintf(command, sizeof(command), "GETVAL %s",
609 lcc_strescape(ident_esc, ident_str, sizeof(ident_esc)));
610 command[sizeof(command) - 1] = 0;
612 /* Send talk to the daemon.. */
613 status = lcc_sendreceive(c, command, &res);
617 if (res.status != 0) {
618 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
619 lcc_response_free(&res);
623 values_num = res.lines_num;
625 #define BAIL_OUT(e) \
627 lcc_set_errno(c, (e)); \
629 if (values_names != NULL) { \
630 for (i = 0; i < values_num; i++) { \
631 free(values_names[i]); \
634 free(values_names); \
635 lcc_response_free(&res); \
639 /* If neither the values nor the names are requested, return here.. */
640 if ((ret_values == NULL) && (ret_values_names == NULL)) {
641 if (ret_values_num != NULL)
642 *ret_values_num = values_num;
643 lcc_response_free(&res);
647 /* Allocate space for the values */
648 if (ret_values != NULL) {
649 values = malloc(values_num * sizeof(*values));
654 if (ret_values_names != NULL) {
655 values_names = calloc(values_num, sizeof(*values_names));
656 if (values_names == NULL)
660 for (i = 0; i < res.lines_num; i++) {
666 value = strchr(key, '=');
673 if (values != NULL) {
676 values[i] = strtod(value, &endptr);
678 if ((endptr == value) || (errno != 0))
682 if (values_names != NULL) {
683 values_names[i] = strdup(key);
684 if (values_names[i] == NULL)
687 } /* for (i = 0; i < res.lines_num; i++) */
689 if (ret_values_num != NULL)
690 *ret_values_num = values_num;
691 if (ret_values != NULL)
692 *ret_values = values;
693 if (ret_values_names != NULL)
694 *ret_values_names = values_names;
696 lcc_response_free(&res);
699 } /* }}} int lcc_getval */
701 int lcc_putval(lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
703 char ident_str[6 * LCC_NAME_LEN];
704 char ident_esc[12 * LCC_NAME_LEN];
705 char command[1024] = "";
709 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1) ||
710 (vl->values == NULL) || (vl->values_types == NULL)) {
711 lcc_set_errno(c, EINVAL);
715 status = lcc_identifier_to_string(c, ident_str, sizeof(ident_str),
720 SSTRCATF(command, "PUTVAL %s",
721 lcc_strescape(ident_esc, ident_str, sizeof(ident_esc)));
723 if (vl->interval > 0.0)
724 SSTRCATF(command, " interval=%.3f", vl->interval);
727 SSTRCATF(command, " %.3f", vl->time);
729 SSTRCAT(command, " N");
731 for (size_t i = 0; i < vl->values_len; i++) {
732 if (vl->values_types[i] == LCC_TYPE_COUNTER)
733 SSTRCATF(command, ":%" PRIu64, vl->values[i].counter);
734 else if (vl->values_types[i] == LCC_TYPE_GAUGE) {
735 if (isnan(vl->values[i].gauge))
736 SSTRCATF(command, ":U");
738 SSTRCATF(command, ":%g", vl->values[i].gauge);
739 } else if (vl->values_types[i] == LCC_TYPE_DERIVE)
740 SSTRCATF(command, ":%" PRIu64, vl->values[i].derive);
741 else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
742 SSTRCATF(command, ":%" PRIu64, vl->values[i].absolute);
744 } /* for (i = 0; i < vl->values_len; i++) */
746 status = lcc_sendreceive(c, command, &res);
750 if (res.status != 0) {
751 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
752 lcc_response_free(&res);
756 lcc_response_free(&res);
758 } /* }}} int lcc_putval */
760 int lcc_flush(lcc_connection_t *c, const char *plugin, /* {{{ */
761 lcc_identifier_t *ident, int timeout) {
762 char command[1024] = "";
767 lcc_set_errno(c, EINVAL);
771 SSTRCPY(command, "FLUSH");
774 SSTRCATF(command, " timeout=%i", timeout);
776 if (plugin != NULL) {
777 char buffer[2 * LCC_NAME_LEN];
778 SSTRCATF(command, " plugin=%s",
779 lcc_strescape(buffer, plugin, sizeof(buffer)));
783 char ident_str[6 * LCC_NAME_LEN];
784 char ident_esc[12 * LCC_NAME_LEN];
786 status = lcc_identifier_to_string(c, ident_str, sizeof(ident_str), ident);
790 SSTRCATF(command, " identifier=%s",
791 lcc_strescape(ident_esc, ident_str, sizeof(ident_esc)));
794 status = lcc_sendreceive(c, command, &res);
798 if (res.status != 0) {
799 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
800 lcc_response_free(&res);
804 lcc_response_free(&res);
806 } /* }}} int lcc_flush */
808 /* TODO: Implement lcc_putnotif */
810 int lcc_listval(lcc_connection_t *c, /* {{{ */
811 lcc_identifier_t **ret_ident, size_t *ret_ident_num) {
815 lcc_identifier_t *ident;
821 if ((ret_ident == NULL) || (ret_ident_num == NULL)) {
822 lcc_set_errno(c, EINVAL);
826 status = lcc_sendreceive(c, "LISTVAL", &res);
830 if (res.status != 0) {
831 LCC_SET_ERRSTR(c, "Server error: %s", res.message);
832 lcc_response_free(&res);
836 ident_num = res.lines_num;
837 ident = malloc(ident_num * sizeof(*ident));
839 lcc_response_free(&res);
840 lcc_set_errno(c, ENOMEM);
844 for (size_t i = 0; i < res.lines_num; i++) {
848 /* First field is the time. */
849 time_str = res.lines[i];
851 /* Set `ident_str' to the beginning of the second field. */
852 ident_str = time_str;
853 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
855 while ((*ident_str == ' ') || (*ident_str == '\t')) {
860 if (*ident_str == 0) {
861 lcc_set_errno(c, EILSEQ);
866 status = lcc_string_to_identifier(c, ident + i, ident_str);
871 lcc_response_free(&res);
879 *ret_ident_num = ident_num;
882 } /* }}} int lcc_listval */
884 const char *lcc_strerror(lcc_connection_t *c) /* {{{ */
887 return "Invalid object";
889 } /* }}} const char *lcc_strerror */
891 int lcc_identifier_to_string(lcc_connection_t *c, /* {{{ */
892 char *string, size_t string_size,
893 const lcc_identifier_t *ident) {
894 if ((string == NULL) || (string_size < 6) || (ident == NULL)) {
895 lcc_set_errno(c, EINVAL);
899 if (ident->plugin_instance[0] == 0) {
900 if (ident->type_instance[0] == 0)
901 snprintf(string, string_size, "%s/%s/%s", ident->host, ident->plugin,
904 snprintf(string, string_size, "%s/%s/%s-%s", ident->host, ident->plugin,
905 ident->type, ident->type_instance);
907 if (ident->type_instance[0] == 0)
908 snprintf(string, string_size, "%s/%s-%s/%s", ident->host, ident->plugin,
909 ident->plugin_instance, ident->type);
911 snprintf(string, string_size, "%s/%s-%s/%s-%s", ident->host,
912 ident->plugin, ident->plugin_instance, ident->type,
913 ident->type_instance);
916 string[string_size - 1] = 0;
918 } /* }}} int lcc_identifier_to_string */
920 int lcc_string_to_identifier(lcc_connection_t *c, /* {{{ */
921 lcc_identifier_t *ident, const char *string) {
925 char *plugin_instance;
929 string_copy = strdup(string);
930 if (string_copy == NULL) {
931 lcc_set_errno(c, ENOMEM);
936 plugin = strchr(host, '/');
937 if (plugin == NULL) {
938 LCC_SET_ERRSTR(c, "Malformed identifier string: %s", string);
945 type = strchr(plugin, '/');
947 LCC_SET_ERRSTR(c, "Malformed identifier string: %s", string);
954 plugin_instance = strchr(plugin, '-');
955 if (plugin_instance != NULL) {
956 *plugin_instance = 0;
960 type_instance = strchr(type, '-');
961 if (type_instance != NULL) {
966 memset(ident, 0, sizeof(*ident));
968 SSTRCPY(ident->host, host);
969 SSTRCPY(ident->plugin, plugin);
970 if (plugin_instance != NULL)
971 SSTRCPY(ident->plugin_instance, plugin_instance);
972 SSTRCPY(ident->type, type);
973 if (type_instance != NULL)
974 SSTRCPY(ident->type_instance, type_instance);
978 } /* }}} int lcc_string_to_identifier */
980 int lcc_identifier_compare(const void *a, /* {{{ */
982 const lcc_identifier_t *i0 = a;
983 const lcc_identifier_t *i1 = b;
986 if ((i0 == NULL) && (i1 == NULL))
993 #define CMP_FIELD(f) \
995 status = strcmp(i0->f, i1->f); \
1002 CMP_FIELD(plugin_instance);
1004 CMP_FIELD(type_instance);
1009 } /* }}} int lcc_identifier_compare */
1011 int lcc_sort_identifiers(lcc_connection_t *c, /* {{{ */
1012 lcc_identifier_t *idents, size_t idents_num) {
1013 if (idents == NULL) {
1014 lcc_set_errno(c, EINVAL);
1018 qsort(idents, idents_num, sizeof(*idents), lcc_identifier_compare);
1020 } /* }}} int lcc_sort_identifiers */