2 * libcollectdclient - src/libcollectdclient/client.c
3 * Copyright (C) 2008 Florian octo Forster
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Florian octo Forster <octo at verplant.org>
22 /* Set to C99 and POSIX code */
23 #ifndef _ISOC99_SOURCE
24 # define _ISOC99_SOURCE
27 # define _POSIX_SOURCE
29 #ifndef _POSIX_C_SOURCE
30 # define _POSIX_C_SOURCE 200112L
33 # define _XOPEN_SOURCE 600
39 /* Disable non-standard extensions */
50 #if !defined(__GNUC__) || !__GNUC__
51 # define __attribute__(x) /**/
58 #include "lcc_features.h"
63 #include <sys/types.h>
64 #include <sys/socket.h>
74 /* NI_MAXHOST has been obsoleted by RFC 3493 which is a reason for SunOS 5.11
75 * to no longer define it. We'll use the old, RFC 2553 value here. */
77 # define NI_MAXHOST 1025
80 /* OpenBSD doesn't have EPROTO, FreeBSD doesn't have EILSEQ. Oh what joy! */
83 # define EILSEQ EPROTO
85 # define EILSEQ EINVAL
89 /* Secure/static macros. They work like `strcpy' and `strcat', but assure null
90 * termination. They work for static buffers only, because they use `sizeof'.
91 * The `SSTRCATF' combines the functionality of `snprintf' and `strcat' which
92 * is very useful to add formatted stuff to the end of a buffer. */
93 #define SSTRCPY(d,s) do { \
94 strncpy ((d), (s), sizeof (d)); \
95 (d)[sizeof (d) - 1] = 0; \
98 #define SSTRCAT(d,s) do { \
99 size_t _l = strlen (d); \
100 strncpy ((d) + _l, (s), sizeof (d) - _l); \
101 (d)[sizeof (d) - 1] = 0; \
104 #define SSTRCATF(d, ...) do { \
105 char _b[sizeof (d)]; \
106 snprintf (_b, sizeof (_b), __VA_ARGS__); \
107 _b[sizeof (_b) - 1] = 0; \
112 #define LCC_SET_ERRSTR(c, ...) do { \
113 snprintf ((c)->errbuf, sizeof ((c)->errbuf), __VA_ARGS__); \
114 (c)->errbuf[sizeof ((c)->errbuf) - 1] = 0; \
118 # define LCC_DEBUG(...) printf (__VA_ARGS__)
120 # define LCC_DEBUG(...) /**/
126 struct lcc_connection_s
132 struct lcc_response_s
139 typedef struct lcc_response_s lcc_response_t;
144 static int lcc_set_errno (lcc_connection_t *c, int err) /* {{{ */
149 strerror_r (err, c->errbuf, sizeof (c->errbuf));
150 c->errbuf[sizeof (c->errbuf) - 1] = 0;
153 } /* }}} int lcc_set_errno */
155 /* lcc_strdup: Since `strdup' is an XSI extension, we provide our own version
157 __attribute__((malloc, nonnull (1)))
158 static char *lcc_strdup (const char *str) /* {{{ */
163 strsize = strlen (str) + 1;
164 ret = (char *) malloc (strsize);
166 memcpy (ret, str, strsize);
168 } /* }}} char *lcc_strdup */
170 __attribute__((nonnull (1, 2)))
171 static char *lcc_strescape (char *dest, const char *src, size_t dest_size) /* {{{ */
179 assert (dest_size >= 3);
181 dest[dest_pos] = '"';
186 if ((dest_pos == (dest_size - 2))
187 || (src[src_pos] == 0))
190 if ((src[src_pos] == '"') || (src[src_pos] == '\\'))
192 /* Check if there is enough space for both characters.. */
193 if (dest_pos == (dest_size - 3))
196 dest[dest_pos] = '\\';
200 dest[dest_pos] = src[src_pos];
205 assert (dest_pos <= (dest_size - 2));
207 dest[dest_pos] = '"';
215 } /* }}} char *lcc_strescape */
217 /* lcc_chomp: Removes all control-characters at the end of a string. */
218 static void lcc_chomp (char *str) /* {{{ */
222 str_len = strlen (str);
225 if (str[str_len - 1] >= 32)
227 str[str_len - 1] = 0;
230 } /* }}} void lcc_chomp */
232 static void lcc_response_free (lcc_response_t *res) /* {{{ */
239 for (i = 0; i < res->lines_num; i++)
240 free (res->lines[i]);
243 } /* }}} void lcc_response_free */
245 static int lcc_send (lcc_connection_t *c, const char *command) /* {{{ */
249 LCC_DEBUG ("send: --> %s\n", command);
251 status = fprintf (c->fh, "%s\r\n", command);
254 lcc_set_errno (c, errno);
259 } /* }}} int lcc_send */
261 static int lcc_receive (lcc_connection_t *c, /* {{{ */
262 lcc_response_t *ret_res)
269 memset (&res, 0, sizeof (res));
271 /* Read the first line, containing the status and a message */
272 ptr = fgets (buffer, sizeof (buffer), c->fh);
275 lcc_set_errno (c, errno);
279 LCC_DEBUG ("receive: <-- %s\n", buffer);
281 /* Convert the leading status to an integer and make `ptr' to point to the
282 * beginning of the message. */
285 res.status = strtol (buffer, &ptr, 0);
286 if ((errno != 0) || (ptr == &buffer[0]))
288 lcc_set_errno (c, errno);
292 /* Skip white spaces after the status number */
293 while ((*ptr == ' ') || (*ptr == '\t'))
296 /* Now copy the message. */
297 strncpy (res.message, ptr, sizeof (res.message));
298 res.message[sizeof (res.message) - 1] = 0;
300 /* Error or no lines follow: We're done. */
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 = (char **) malloc (res.lines_num * sizeof (char *));
311 if (res.lines == NULL)
313 lcc_set_errno (c, ENOMEM);
317 /* Now receive all the lines */
318 for (i = 0; i < res.lines_num; i++)
320 ptr = fgets (buffer, sizeof (buffer), c->fh);
323 lcc_set_errno (c, errno);
327 LCC_DEBUG ("receive: <-- %s\n", buffer);
329 res.lines[i] = lcc_strdup (buffer);
330 if (res.lines[i] == NULL)
332 lcc_set_errno (c, ENOMEM);
337 /* Check if the for-loop exited with an error. */
338 if (i < res.lines_num)
349 memcpy (ret_res, &res, sizeof (res));
351 } /* }}} int lcc_receive */
353 static int lcc_sendreceive (lcc_connection_t *c, /* {{{ */
354 const char *command, lcc_response_t *ret_res)
361 lcc_set_errno (c, EBADF);
365 status = lcc_send (c, command);
369 memset (&res, 0, sizeof (res));
370 status = lcc_receive (c, &res);
372 memcpy (ret_res, &res, sizeof (*ret_res));
375 } /* }}} int lcc_sendreceive */
377 static int lcc_open_unixsocket (lcc_connection_t *c, const char *path) /* {{{ */
379 struct sockaddr_un sa;
384 assert (c->fh == NULL);
385 assert (path != NULL);
387 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
389 fd = socket (AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
392 lcc_set_errno (c, errno);
396 memset (&sa, 0, sizeof (sa));
397 sa.sun_family = AF_UNIX;
398 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
400 status = connect (fd, (struct sockaddr *) &sa, sizeof (sa));
403 lcc_set_errno (c, errno);
408 c->fh = fdopen (fd, "r+");
411 lcc_set_errno (c, errno);
417 } /* }}} int lcc_open_unixsocket */
419 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
420 const char *addr_orig)
422 struct addrinfo ai_hints;
423 struct addrinfo *ai_res;
424 struct addrinfo *ai_ptr;
425 char addr_copy[NI_MAXHOST];
432 assert (c->fh == NULL);
433 assert (addr_orig != NULL);
435 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
436 addr_copy[sizeof(addr_copy) - 1] = '\0';
439 memset (&ai_hints, 0, sizeof (ai_hints));
440 ai_hints.ai_flags = 0;
442 ai_hints.ai_flags |= AI_ADDRCONFIG;
444 ai_hints.ai_family = AF_UNSPEC;
445 ai_hints.ai_socktype = SOCK_STREAM;
448 if (*addr == '[') /* IPv6+port format */
450 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
453 port = strchr (addr, ']');
456 LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
468 LCC_SET_ERRSTR (c, "garbage after address: %s", port);
471 } /* if (*addr = ']') */
472 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
474 port = strrchr (addr, ':');
483 status = getaddrinfo (addr,
484 port == NULL ? LCC_DEFAULT_PORT : port,
488 LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
492 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
494 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
502 status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
511 c->fh = fdopen (fd, "r+");
520 assert (status == 0);
526 lcc_set_errno (c, status);
531 } /* }}} int lcc_open_netsocket */
533 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
541 assert (c->fh == NULL);
542 assert (addr != NULL);
544 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
545 status = lcc_open_unixsocket (c, addr + strlen ("unix:"));
546 else if (addr[0] == '/')
547 status = lcc_open_unixsocket (c, addr);
549 status = lcc_open_netsocket (c, addr);
552 } /* }}} int lcc_open_socket */
557 unsigned int lcc_version (void) /* {{{ */
559 return (LCC_VERSION);
560 } /* }}} unsigned int lcc_version */
562 const char *lcc_version_string (void) /* {{{ */
564 return (LCC_VERSION_STRING);
565 } /* }}} const char *lcc_version_string */
567 const char *lcc_version_extra (void) /* {{{ */
569 return (LCC_VERSION_EXTRA);
570 } /* }}} const char *lcc_version_extra */
572 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
583 c = (lcc_connection_t *) malloc (sizeof (*c));
586 memset (c, 0, sizeof (*c));
588 status = lcc_open_socket (c, address);
597 } /* }}} int lcc_connect */
599 int lcc_disconnect (lcc_connection_t *c) /* {{{ */
612 } /* }}} int lcc_disconnect */
614 int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
615 size_t *ret_values_num, gauge_t **ret_values, char ***ret_values_names)
617 char ident_str[6 * LCC_NAME_LEN];
618 char ident_esc[12 * LCC_NAME_LEN];
619 char command[14 * LCC_NAME_LEN];
623 gauge_t *values = NULL;
624 char **values_names = NULL;
634 lcc_set_errno (c, EINVAL);
638 /* Build a commend with an escaped version of the identifier string. */
639 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
643 snprintf (command, sizeof (command), "GETVAL %s",
644 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
645 command[sizeof (command) - 1] = 0;
647 /* Send talk to the daemon.. */
648 status = lcc_sendreceive (c, command, &res);
654 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
655 lcc_response_free (&res);
659 values_num = res.lines_num;
661 #define BAIL_OUT(e) do { \
662 lcc_set_errno (c, (e)); \
664 if (values_names != NULL) { \
665 for (i = 0; i < values_num; i++) { \
666 free (values_names[i]); \
669 free (values_names); \
670 lcc_response_free (&res); \
674 /* If neither the values nor the names are requested, return here.. */
675 if ((ret_values == NULL) && (ret_values_names == NULL))
677 if (ret_values_num != NULL)
678 *ret_values_num = values_num;
679 lcc_response_free (&res);
683 /* Allocate space for the values */
684 if (ret_values != NULL)
686 values = (gauge_t *) malloc (values_num * sizeof (*values));
691 if (ret_values_names != NULL)
693 values_names = (char **) calloc (values_num, sizeof (*values_names));
694 if (values_names == NULL)
698 for (i = 0; i < res.lines_num; i++)
705 value = strchr (key, '=');
716 values[i] = strtod (value, &endptr);
718 if ((endptr == value) || (errno != 0))
722 if (values_names != NULL)
724 values_names[i] = lcc_strdup (key);
725 if (values_names[i] == NULL)
728 } /* for (i = 0; i < res.lines_num; i++) */
730 if (ret_values_num != NULL)
731 *ret_values_num = values_num;
732 if (ret_values != NULL)
733 *ret_values = values;
734 if (ret_values_names != NULL)
735 *ret_values_names = values_names;
738 } /* }}} int lcc_getval */
740 int lcc_putval (lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
742 char ident_str[6 * LCC_NAME_LEN];
743 char ident_esc[12 * LCC_NAME_LEN];
744 char command[1024] = "";
749 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
750 || (vl->values == NULL) || (vl->values_types == NULL))
752 lcc_set_errno (c, EINVAL);
756 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
761 SSTRCATF (command, "PUTVAL %s",
762 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
764 if (vl->interval > 0)
765 SSTRCATF (command, " interval=%i", vl->interval);
768 SSTRCATF (command, "%u", (unsigned int) vl->time);
770 SSTRCAT (command, "N");
772 for (i = 0; i < vl->values_len; i++)
774 if (vl->values_types[i] == LCC_TYPE_COUNTER)
775 SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
776 else if (vl->values_types[i] == LCC_TYPE_GAUGE)
778 if (isnan (vl->values[i].gauge))
779 SSTRCPY (command, ":U");
781 SSTRCATF (command, ":%g", vl->values[i].gauge);
783 } /* for (i = 0; i < vl->values_len; i++) */
785 status = lcc_sendreceive (c, command, &res);
791 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
792 lcc_response_free (&res);
796 lcc_response_free (&res);
798 } /* }}} int lcc_putval */
800 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
801 lcc_identifier_t *ident, int timeout)
803 char command[1024] = "";
809 lcc_set_errno (c, EINVAL);
813 SSTRCPY (command, "FLUSH");
816 SSTRCATF (command, " timeout=%i", timeout);
820 char buffer[2 * LCC_NAME_LEN];
821 SSTRCATF (command, " plugin=%s",
822 lcc_strescape (buffer, plugin, sizeof (buffer)));
827 char ident_str[6 * LCC_NAME_LEN];
828 char ident_esc[12 * LCC_NAME_LEN];
830 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
834 SSTRCATF (command, " identifier=%s",
835 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
838 status = lcc_sendreceive (c, command, &res);
844 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
845 lcc_response_free (&res);
849 lcc_response_free (&res);
851 } /* }}} int lcc_flush */
853 /* TODO: Implement lcc_putnotif */
855 int lcc_listval (lcc_connection_t *c, /* {{{ */
856 lcc_identifier_t **ret_ident, size_t *ret_ident_num)
862 lcc_identifier_t *ident;
868 if ((ret_ident == NULL) || (ret_ident_num == NULL))
870 lcc_set_errno (c, EINVAL);
874 status = lcc_sendreceive (c, "LISTVAL", &res);
880 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
881 lcc_response_free (&res);
885 ident_num = res.lines_num;
886 ident = (lcc_identifier_t *) malloc (ident_num * sizeof (*ident));
889 lcc_response_free (&res);
890 lcc_set_errno (c, ENOMEM);
894 for (i = 0; i < res.lines_num; i++)
899 /* First field is the time. */
900 time_str = res.lines[i];
902 /* Set `ident_str' to the beginning of the second field. */
903 ident_str = time_str;
904 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
906 while ((*ident_str == ' ') || (*ident_str == '\t'))
914 lcc_set_errno (c, EILSEQ);
919 status = lcc_string_to_identifier (c, ident + i, ident_str);
924 lcc_response_free (&res);
933 *ret_ident_num = ident_num;
936 } /* }}} int lcc_listval */
938 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
941 return ("Invalid object");
943 } /* }}} const char *lcc_strerror */
945 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
946 char *string, size_t string_size, const lcc_identifier_t *ident)
948 if ((string == NULL) || (string_size < 6) || (ident == NULL))
950 lcc_set_errno (c, EINVAL);
954 if (ident->plugin_instance[0] == 0)
956 if (ident->type_instance[0] == 0)
957 snprintf (string, string_size, "%s/%s/%s",
962 snprintf (string, string_size, "%s/%s/%s-%s",
966 ident->type_instance);
970 if (ident->type_instance[0] == 0)
971 snprintf (string, string_size, "%s/%s-%s/%s",
974 ident->plugin_instance,
977 snprintf (string, string_size, "%s/%s-%s/%s-%s",
980 ident->plugin_instance,
982 ident->type_instance);
985 string[string_size - 1] = 0;
987 } /* }}} int lcc_identifier_to_string */
989 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
990 lcc_identifier_t *ident, const char *string)
995 char *plugin_instance;
999 string_copy = lcc_strdup (string);
1000 if (string_copy == NULL)
1002 lcc_set_errno (c, ENOMEM);
1007 plugin = strchr (host, '/');
1010 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1017 type = strchr (plugin, '/');
1020 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1027 plugin_instance = strchr (plugin, '-');
1028 if (plugin_instance != NULL)
1030 *plugin_instance = 0;
1034 type_instance = strchr (type, '-');
1035 if (type_instance != NULL)
1041 memset (ident, 0, sizeof (*ident));
1043 SSTRCPY (ident->host, host);
1044 SSTRCPY (ident->plugin, plugin);
1045 if (plugin_instance != NULL)
1046 SSTRCPY (ident->plugin_instance, plugin_instance);
1047 SSTRCPY (ident->type, type);
1048 if (type_instance != NULL)
1049 SSTRCPY (ident->type_instance, type_instance);
1053 } /* }}} int lcc_string_to_identifier */
1055 /* vim: set sw=2 sts=2 et fdm=marker : */