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"
40 #include <sys/types.h>
41 #include <sys/socket.h>
49 #include "collectd/client.h"
51 /* NI_MAXHOST has been obsoleted by RFC 3493 which is a reason for SunOS 5.11
52 * to no longer define it. We'll use the old, RFC 2553 value here. */
54 # define NI_MAXHOST 1025
57 /* OpenBSD doesn't have EPROTO, FreeBSD doesn't have EILSEQ. Oh what joy! */
60 # define EILSEQ EPROTO
62 # define EILSEQ EINVAL
66 /* Secure/static macros. They work like `strcpy' and `strcat', but assure null
67 * termination. They work for static buffers only, because they use `sizeof'.
68 * The `SSTRCATF' combines the functionality of `snprintf' and `strcat' which
69 * is very useful to add formatted stuff to the end of a buffer. */
70 #define SSTRCPY(d,s) do { \
71 strncpy ((d), (s), sizeof (d)); \
72 (d)[sizeof (d) - 1] = 0; \
75 #define SSTRCAT(d,s) do { \
76 size_t _l = strlen (d); \
77 strncpy ((d) + _l, (s), sizeof (d) - _l); \
78 (d)[sizeof (d) - 1] = 0; \
81 #define SSTRCATF(d, ...) do { \
82 char _b[sizeof (d)]; \
83 snprintf (_b, sizeof (_b), __VA_ARGS__); \
84 _b[sizeof (_b) - 1] = 0; \
89 #define LCC_SET_ERRSTR(c, ...) do { \
90 snprintf ((c)->errbuf, sizeof ((c)->errbuf), __VA_ARGS__); \
91 (c)->errbuf[sizeof ((c)->errbuf) - 1] = 0; \
95 # define LCC_DEBUG(...) printf (__VA_ARGS__)
97 # define LCC_DEBUG(...) /**/
103 struct lcc_connection_s
109 struct lcc_response_s
116 typedef struct lcc_response_s lcc_response_t;
121 /* Even though Posix requires "strerror_r" to return an "int",
122 * some systems (e.g. the GNU libc) return a "char *" _and_
123 * ignore the second argument ... -tokkee */
124 static char *sstrerror (int errnum, char *buf, size_t buflen)
129 snprintf (buf, buflen, "Error #%i; strerror_r is not available.", errnum);
130 /* #endif !HAVE_STRERROR_R */
132 #elif STRERROR_R_CHAR_P
135 temp = strerror_r (errnum, buf, buflen);
138 if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
139 strncpy (buf, temp, buflen);
141 strncpy (buf, "strerror_r did not return "
142 "an error message", buflen);
145 /* #endif STRERROR_R_CHAR_P */
148 if (strerror_r (errnum, buf, buflen) != 0)
150 snprintf (buf, buflen, "Error #%i; "
151 "Additionally, strerror_r failed.",
154 #endif /* STRERROR_R_CHAR_P */
159 } /* char *sstrerror */
161 static int lcc_set_errno (lcc_connection_t *c, int err) /* {{{ */
166 sstrerror (err, c->errbuf, sizeof (c->errbuf));
167 c->errbuf[sizeof (c->errbuf) - 1] = 0;
170 } /* }}} int lcc_set_errno */
172 static char *lcc_strescape (char *dest, const char *src, size_t dest_size) /* {{{ */
177 if ((dest == NULL) || (src == NULL))
183 assert (dest_size >= 3);
185 dest[dest_pos] = '"';
190 if ((dest_pos == (dest_size - 2))
191 || (src[src_pos] == 0))
194 if ((src[src_pos] == '"') || (src[src_pos] == '\\'))
196 /* Check if there is enough space for both characters.. */
197 if (dest_pos == (dest_size - 3))
200 dest[dest_pos] = '\\';
204 dest[dest_pos] = src[src_pos];
209 assert (dest_pos <= (dest_size - 2));
211 dest[dest_pos] = '"';
219 } /* }}} char *lcc_strescape */
221 /* lcc_chomp: Removes all control-characters at the end of a string. */
222 static void lcc_chomp (char *str) /* {{{ */
226 str_len = strlen (str);
229 if (str[str_len - 1] >= 32)
231 str[str_len - 1] = 0;
234 } /* }}} void lcc_chomp */
236 static void lcc_response_free (lcc_response_t *res) /* {{{ */
243 for (i = 0; i < res->lines_num; i++)
244 free (res->lines[i]);
247 } /* }}} void lcc_response_free */
249 static int lcc_send (lcc_connection_t *c, const char *command) /* {{{ */
253 LCC_DEBUG ("send: --> %s\n", command);
255 status = fprintf (c->fh, "%s\r\n", command);
258 lcc_set_errno (c, errno);
264 } /* }}} int lcc_send */
266 static int lcc_receive (lcc_connection_t *c, /* {{{ */
267 lcc_response_t *ret_res)
274 memset (&res, 0, sizeof (res));
276 /* Read the first line, containing the status and a message */
277 ptr = fgets (buffer, sizeof (buffer), c->fh);
280 lcc_set_errno (c, errno);
284 LCC_DEBUG ("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 = strtol (buffer, &ptr, 0);
291 if ((errno != 0) || (ptr == &buffer[0]))
293 lcc_set_errno (c, errno);
297 /* Skip white spaces after the status number */
298 while ((*ptr == ' ') || (*ptr == '\t'))
301 /* Now copy the message. */
302 strncpy (res.message, ptr, sizeof (res.message));
303 res.message[sizeof (res.message) - 1] = 0;
305 /* Error or no lines follow: We're done. */
308 memcpy (ret_res, &res, sizeof (res));
312 /* Allocate space for the char-pointers */
313 res.lines_num = (size_t) res.status;
315 res.lines = (char **) malloc (res.lines_num * sizeof (char *));
316 if (res.lines == NULL)
318 lcc_set_errno (c, ENOMEM);
322 /* Now receive all the lines */
323 for (i = 0; i < res.lines_num; i++)
325 ptr = fgets (buffer, sizeof (buffer), c->fh);
328 lcc_set_errno (c, errno);
332 LCC_DEBUG ("receive: <-- %s\n", buffer);
334 res.lines[i] = strdup (buffer);
335 if (res.lines[i] == NULL)
337 lcc_set_errno (c, ENOMEM);
342 /* Check if the for-loop exited with an error. */
343 if (i < res.lines_num)
354 memcpy (ret_res, &res, sizeof (res));
356 } /* }}} int lcc_receive */
358 static int lcc_sendreceive (lcc_connection_t *c, /* {{{ */
359 const char *command, lcc_response_t *ret_res)
366 lcc_set_errno (c, EBADF);
370 status = lcc_send (c, command);
374 memset (&res, 0, sizeof (res));
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) /* {{{ */
384 struct sockaddr_un sa;
389 assert (c->fh == NULL);
390 assert (path != NULL);
392 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
394 fd = socket (AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
397 lcc_set_errno (c, errno);
401 memset (&sa, 0, sizeof (sa));
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));
408 lcc_set_errno (c, errno);
413 c->fh = fdopen (fd, "r+");
416 lcc_set_errno (c, errno);
422 } /* }}} int lcc_open_unixsocket */
424 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
425 const char *addr_orig)
427 struct addrinfo ai_hints;
428 struct addrinfo *ai_res;
429 struct addrinfo *ai_ptr;
430 char addr_copy[NI_MAXHOST];
437 assert (c->fh == NULL);
438 assert (addr_orig != NULL);
440 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
441 addr_copy[sizeof(addr_copy) - 1] = '\0';
444 memset (&ai_hints, 0, sizeof (ai_hints));
445 ai_hints.ai_flags = 0;
447 ai_hints.ai_flags |= AI_ADDRCONFIG;
449 ai_hints.ai_family = AF_UNSPEC;
450 ai_hints.ai_socktype = SOCK_STREAM;
453 if (*addr == '[') /* IPv6+port format */
455 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
458 port = strchr (addr, ']');
461 LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
473 LCC_SET_ERRSTR (c, "garbage after address: %s", port);
476 } /* if (*addr = ']') */
477 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
479 port = strrchr (addr, ':');
488 status = getaddrinfo (addr,
489 port == NULL ? LCC_DEFAULT_PORT : port,
493 LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
497 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
499 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
506 status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
514 c->fh = fdopen (fd, "r+");
522 assert (status == 0);
528 lcc_set_errno (c, status);
529 freeaddrinfo (ai_res);
533 freeaddrinfo (ai_res);
535 } /* }}} int lcc_open_netsocket */
537 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
545 assert (c->fh == NULL);
546 assert (addr != NULL);
548 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
549 status = lcc_open_unixsocket (c, addr + strlen ("unix:"));
550 else if (addr[0] == '/')
551 status = lcc_open_unixsocket (c, addr);
553 status = lcc_open_netsocket (c, addr);
556 } /* }}} int lcc_open_socket */
561 unsigned int lcc_version (void) /* {{{ */
563 return (LCC_VERSION);
564 } /* }}} unsigned int lcc_version */
566 const char *lcc_version_string (void) /* {{{ */
568 return (LCC_VERSION_STRING);
569 } /* }}} const char *lcc_version_string */
571 const char *lcc_version_extra (void) /* {{{ */
573 return (LCC_VERSION_EXTRA);
574 } /* }}} const char *lcc_version_extra */
576 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
587 c = (lcc_connection_t *) malloc (sizeof (*c));
590 memset (c, 0, 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 = (gauge_t *) malloc (values_num * sizeof (*values));
695 if (ret_values_names != NULL)
697 values_names = (char **) 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] = "";
755 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
756 || (vl->values == NULL) || (vl->values_types == NULL))
758 lcc_set_errno (c, EINVAL);
762 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
767 SSTRCATF (command, "PUTVAL %s",
768 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
770 if (vl->interval > 0.0)
771 SSTRCATF (command, " interval=%.3f", vl->interval);
774 SSTRCATF (command, " %.3f", vl->time);
776 SSTRCAT (command, " N");
778 for (i = 0; i < vl->values_len; i++)
780 if (vl->values_types[i] == LCC_TYPE_COUNTER)
781 SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
782 else if (vl->values_types[i] == LCC_TYPE_GAUGE)
784 if (isnan (vl->values[i].gauge))
785 SSTRCATF (command, ":U");
787 SSTRCATF (command, ":%g", vl->values[i].gauge);
789 else if (vl->values_types[i] == LCC_TYPE_DERIVE)
790 SSTRCATF (command, ":%"PRIu64, vl->values[i].derive);
791 else if (vl->values_types[i] == LCC_TYPE_ABSOLUTE)
792 SSTRCATF (command, ":%"PRIu64, vl->values[i].absolute);
794 } /* for (i = 0; i < vl->values_len; i++) */
796 status = lcc_sendreceive (c, command, &res);
802 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
803 lcc_response_free (&res);
807 lcc_response_free (&res);
809 } /* }}} int lcc_putval */
811 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
812 lcc_identifier_t *ident, int timeout)
814 char command[1024] = "";
820 lcc_set_errno (c, EINVAL);
824 SSTRCPY (command, "FLUSH");
827 SSTRCATF (command, " timeout=%i", timeout);
831 char buffer[2 * LCC_NAME_LEN];
832 SSTRCATF (command, " plugin=%s",
833 lcc_strescape (buffer, plugin, sizeof (buffer)));
838 char ident_str[6 * LCC_NAME_LEN];
839 char ident_esc[12 * LCC_NAME_LEN];
841 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
845 SSTRCATF (command, " identifier=%s",
846 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
849 status = lcc_sendreceive (c, command, &res);
855 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
856 lcc_response_free (&res);
860 lcc_response_free (&res);
862 } /* }}} int lcc_flush */
864 /* TODO: Implement lcc_putnotif */
866 int lcc_listval (lcc_connection_t *c, /* {{{ */
867 lcc_identifier_t **ret_ident, size_t *ret_ident_num)
873 lcc_identifier_t *ident;
879 if ((ret_ident == NULL) || (ret_ident_num == NULL))
881 lcc_set_errno (c, EINVAL);
885 status = lcc_sendreceive (c, "LISTVAL", &res);
891 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
892 lcc_response_free (&res);
896 ident_num = res.lines_num;
897 ident = (lcc_identifier_t *) malloc (ident_num * sizeof (*ident));
900 lcc_response_free (&res);
901 lcc_set_errno (c, ENOMEM);
905 for (i = 0; i < res.lines_num; i++)
910 /* First field is the time. */
911 time_str = res.lines[i];
913 /* Set `ident_str' to the beginning of the second field. */
914 ident_str = time_str;
915 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
917 while ((*ident_str == ' ') || (*ident_str == '\t'))
925 lcc_set_errno (c, EILSEQ);
930 status = lcc_string_to_identifier (c, ident + i, ident_str);
935 lcc_response_free (&res);
944 *ret_ident_num = ident_num;
947 } /* }}} int lcc_listval */
949 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
952 return ("Invalid object");
954 } /* }}} const char *lcc_strerror */
956 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
957 char *string, size_t string_size, const lcc_identifier_t *ident)
959 if ((string == NULL) || (string_size < 6) || (ident == NULL))
961 lcc_set_errno (c, EINVAL);
965 if (ident->plugin_instance[0] == 0)
967 if (ident->type_instance[0] == 0)
968 snprintf (string, string_size, "%s/%s/%s",
973 snprintf (string, string_size, "%s/%s/%s-%s",
977 ident->type_instance);
981 if (ident->type_instance[0] == 0)
982 snprintf (string, string_size, "%s/%s-%s/%s",
985 ident->plugin_instance,
988 snprintf (string, string_size, "%s/%s-%s/%s-%s",
991 ident->plugin_instance,
993 ident->type_instance);
996 string[string_size - 1] = 0;
998 } /* }}} int lcc_identifier_to_string */
1000 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
1001 lcc_identifier_t *ident, const char *string)
1006 char *plugin_instance;
1008 char *type_instance;
1010 string_copy = strdup (string);
1011 if (string_copy == NULL)
1013 lcc_set_errno (c, ENOMEM);
1018 plugin = strchr (host, '/');
1021 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1028 type = strchr (plugin, '/');
1031 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1038 plugin_instance = strchr (plugin, '-');
1039 if (plugin_instance != NULL)
1041 *plugin_instance = 0;
1045 type_instance = strchr (type, '-');
1046 if (type_instance != NULL)
1052 memset (ident, 0, sizeof (*ident));
1054 SSTRCPY (ident->host, host);
1055 SSTRCPY (ident->plugin, plugin);
1056 if (plugin_instance != NULL)
1057 SSTRCPY (ident->plugin_instance, plugin_instance);
1058 SSTRCPY (ident->type, type);
1059 if (type_instance != NULL)
1060 SSTRCPY (ident->type_instance, type_instance);
1064 } /* }}} int lcc_string_to_identifier */
1066 int lcc_identifier_compare (const lcc_identifier_t *i0, /* {{{ */
1067 const lcc_identifier_t *i1)
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 (void *) lcc_identifier_compare);
1107 } /* }}} int lcc_sort_identifiers */
1109 /* vim: set sw=2 sts=2 et fdm=marker : */