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>
26 /* Set to C99 and POSIX code */
28 # include "standards.h"
29 #endif /* COLLECT_STANDARDS */
31 #if !defined(__GNUC__) || !__GNUC__
32 # define __attribute__(x) /**/
35 #include "lcc_features.h"
40 #include <sys/types.h>
41 #include <sys/socket.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 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 /* lcc_strdup: Since `strdup' is an XSI extension, we provide our own version
174 __attribute__((malloc, nonnull (1)))
175 static char *lcc_strdup (const char *str) /* {{{ */
180 strsize = strlen (str) + 1;
181 ret = (char *) malloc (strsize);
183 memcpy (ret, str, strsize);
185 } /* }}} char *lcc_strdup */
187 __attribute__((nonnull (1, 2)))
188 static char *lcc_strescape (char *dest, const char *src, size_t dest_size) /* {{{ */
196 assert (dest_size >= 3);
198 dest[dest_pos] = '"';
203 if ((dest_pos == (dest_size - 2))
204 || (src[src_pos] == 0))
207 if ((src[src_pos] == '"') || (src[src_pos] == '\\'))
209 /* Check if there is enough space for both characters.. */
210 if (dest_pos == (dest_size - 3))
213 dest[dest_pos] = '\\';
217 dest[dest_pos] = src[src_pos];
222 assert (dest_pos <= (dest_size - 2));
224 dest[dest_pos] = '"';
232 } /* }}} char *lcc_strescape */
234 /* lcc_chomp: Removes all control-characters at the end of a string. */
235 static void lcc_chomp (char *str) /* {{{ */
239 str_len = strlen (str);
242 if (str[str_len - 1] >= 32)
244 str[str_len - 1] = 0;
247 } /* }}} void lcc_chomp */
249 static void lcc_response_free (lcc_response_t *res) /* {{{ */
256 for (i = 0; i < res->lines_num; i++)
257 free (res->lines[i]);
260 } /* }}} void lcc_response_free */
262 static int lcc_send (lcc_connection_t *c, const char *command) /* {{{ */
266 LCC_DEBUG ("send: --> %s\n", command);
268 status = fprintf (c->fh, "%s\r\n", command);
271 lcc_set_errno (c, errno);
276 } /* }}} int lcc_send */
278 static int lcc_receive (lcc_connection_t *c, /* {{{ */
279 lcc_response_t *ret_res)
286 memset (&res, 0, sizeof (res));
288 /* Read the first line, containing the status and a message */
289 ptr = fgets (buffer, sizeof (buffer), c->fh);
292 lcc_set_errno (c, errno);
296 LCC_DEBUG ("receive: <-- %s\n", buffer);
298 /* Convert the leading status to an integer and make `ptr' to point to the
299 * beginning of the message. */
302 res.status = strtol (buffer, &ptr, 0);
303 if ((errno != 0) || (ptr == &buffer[0]))
305 lcc_set_errno (c, errno);
309 /* Skip white spaces after the status number */
310 while ((*ptr == ' ') || (*ptr == '\t'))
313 /* Now copy the message. */
314 strncpy (res.message, ptr, sizeof (res.message));
315 res.message[sizeof (res.message) - 1] = 0;
317 /* Error or no lines follow: We're done. */
320 memcpy (ret_res, &res, sizeof (res));
324 /* Allocate space for the char-pointers */
325 res.lines_num = (size_t) res.status;
327 res.lines = (char **) malloc (res.lines_num * sizeof (char *));
328 if (res.lines == NULL)
330 lcc_set_errno (c, ENOMEM);
334 /* Now receive all the lines */
335 for (i = 0; i < res.lines_num; i++)
337 ptr = fgets (buffer, sizeof (buffer), c->fh);
340 lcc_set_errno (c, errno);
344 LCC_DEBUG ("receive: <-- %s\n", buffer);
346 res.lines[i] = lcc_strdup (buffer);
347 if (res.lines[i] == NULL)
349 lcc_set_errno (c, ENOMEM);
354 /* Check if the for-loop exited with an error. */
355 if (i < res.lines_num)
366 memcpy (ret_res, &res, sizeof (res));
368 } /* }}} int lcc_receive */
370 static int lcc_sendreceive (lcc_connection_t *c, /* {{{ */
371 const char *command, lcc_response_t *ret_res)
378 lcc_set_errno (c, EBADF);
382 status = lcc_send (c, command);
386 memset (&res, 0, sizeof (res));
387 status = lcc_receive (c, &res);
389 memcpy (ret_res, &res, sizeof (*ret_res));
392 } /* }}} int lcc_sendreceive */
394 static int lcc_open_unixsocket (lcc_connection_t *c, const char *path) /* {{{ */
396 struct sockaddr_un sa;
401 assert (c->fh == NULL);
402 assert (path != NULL);
404 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
406 fd = socket (AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
409 lcc_set_errno (c, errno);
413 memset (&sa, 0, sizeof (sa));
414 sa.sun_family = AF_UNIX;
415 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
417 status = connect (fd, (struct sockaddr *) &sa, sizeof (sa));
420 lcc_set_errno (c, errno);
425 c->fh = fdopen (fd, "r+");
428 lcc_set_errno (c, errno);
434 } /* }}} int lcc_open_unixsocket */
436 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
437 const char *addr_orig)
439 struct addrinfo ai_hints;
440 struct addrinfo *ai_res;
441 struct addrinfo *ai_ptr;
442 char addr_copy[NI_MAXHOST];
449 assert (c->fh == NULL);
450 assert (addr_orig != NULL);
452 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
453 addr_copy[sizeof(addr_copy) - 1] = '\0';
456 memset (&ai_hints, 0, sizeof (ai_hints));
457 ai_hints.ai_flags = 0;
459 ai_hints.ai_flags |= AI_ADDRCONFIG;
461 ai_hints.ai_family = AF_UNSPEC;
462 ai_hints.ai_socktype = SOCK_STREAM;
465 if (*addr == '[') /* IPv6+port format */
467 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
470 port = strchr (addr, ']');
473 LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
485 LCC_SET_ERRSTR (c, "garbage after address: %s", port);
488 } /* if (*addr = ']') */
489 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
491 port = strrchr (addr, ':');
500 status = getaddrinfo (addr,
501 port == NULL ? LCC_DEFAULT_PORT : port,
505 LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
509 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
511 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
519 status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
528 c->fh = fdopen (fd, "r+");
537 assert (status == 0);
543 lcc_set_errno (c, status);
548 } /* }}} int lcc_open_netsocket */
550 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
558 assert (c->fh == NULL);
559 assert (addr != NULL);
561 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
562 status = lcc_open_unixsocket (c, addr + strlen ("unix:"));
563 else if (addr[0] == '/')
564 status = lcc_open_unixsocket (c, addr);
566 status = lcc_open_netsocket (c, addr);
569 } /* }}} int lcc_open_socket */
574 unsigned int lcc_version (void) /* {{{ */
576 return (LCC_VERSION);
577 } /* }}} unsigned int lcc_version */
579 const char *lcc_version_string (void) /* {{{ */
581 return (LCC_VERSION_STRING);
582 } /* }}} const char *lcc_version_string */
584 const char *lcc_version_extra (void) /* {{{ */
586 return (LCC_VERSION_EXTRA);
587 } /* }}} const char *lcc_version_extra */
589 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
600 c = (lcc_connection_t *) malloc (sizeof (*c));
603 memset (c, 0, sizeof (*c));
605 status = lcc_open_socket (c, address);
614 } /* }}} int lcc_connect */
616 int lcc_disconnect (lcc_connection_t *c) /* {{{ */
629 } /* }}} int lcc_disconnect */
631 int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
632 size_t *ret_values_num, gauge_t **ret_values, char ***ret_values_names)
634 char ident_str[6 * LCC_NAME_LEN];
635 char ident_esc[12 * LCC_NAME_LEN];
636 char command[14 * LCC_NAME_LEN];
640 gauge_t *values = NULL;
641 char **values_names = NULL;
651 lcc_set_errno (c, EINVAL);
655 /* Build a commend with an escaped version of the identifier string. */
656 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
660 snprintf (command, sizeof (command), "GETVAL %s",
661 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
662 command[sizeof (command) - 1] = 0;
664 /* Send talk to the daemon.. */
665 status = lcc_sendreceive (c, command, &res);
671 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
672 lcc_response_free (&res);
676 values_num = res.lines_num;
678 #define BAIL_OUT(e) do { \
679 lcc_set_errno (c, (e)); \
681 if (values_names != NULL) { \
682 for (i = 0; i < values_num; i++) { \
683 free (values_names[i]); \
686 free (values_names); \
687 lcc_response_free (&res); \
691 /* If neither the values nor the names are requested, return here.. */
692 if ((ret_values == NULL) && (ret_values_names == NULL))
694 if (ret_values_num != NULL)
695 *ret_values_num = values_num;
696 lcc_response_free (&res);
700 /* Allocate space for the values */
701 if (ret_values != NULL)
703 values = (gauge_t *) malloc (values_num * sizeof (*values));
708 if (ret_values_names != NULL)
710 values_names = (char **) calloc (values_num, sizeof (*values_names));
711 if (values_names == NULL)
715 for (i = 0; i < res.lines_num; i++)
722 value = strchr (key, '=');
733 values[i] = strtod (value, &endptr);
735 if ((endptr == value) || (errno != 0))
739 if (values_names != NULL)
741 values_names[i] = lcc_strdup (key);
742 if (values_names[i] == NULL)
745 } /* for (i = 0; i < res.lines_num; i++) */
747 if (ret_values_num != NULL)
748 *ret_values_num = values_num;
749 if (ret_values != NULL)
750 *ret_values = values;
751 if (ret_values_names != NULL)
752 *ret_values_names = values_names;
755 } /* }}} int lcc_getval */
757 int lcc_putval (lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
759 char ident_str[6 * LCC_NAME_LEN];
760 char ident_esc[12 * LCC_NAME_LEN];
761 char command[1024] = "";
766 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
767 || (vl->values == NULL) || (vl->values_types == NULL))
769 lcc_set_errno (c, EINVAL);
773 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
778 SSTRCATF (command, "PUTVAL %s",
779 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
781 if (vl->interval > 0)
782 SSTRCATF (command, " interval=%i", vl->interval);
785 SSTRCATF (command, "%u", (unsigned int) vl->time);
787 SSTRCAT (command, "N");
789 for (i = 0; i < vl->values_len; i++)
791 if (vl->values_types[i] == LCC_TYPE_COUNTER)
792 SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
793 else if (vl->values_types[i] == LCC_TYPE_GAUGE)
795 if (isnan (vl->values[i].gauge))
796 SSTRCPY (command, ":U");
798 SSTRCATF (command, ":%g", vl->values[i].gauge);
800 } /* for (i = 0; i < vl->values_len; i++) */
802 status = lcc_sendreceive (c, command, &res);
808 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
809 lcc_response_free (&res);
813 lcc_response_free (&res);
815 } /* }}} int lcc_putval */
817 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
818 lcc_identifier_t *ident, int timeout)
820 char command[1024] = "";
826 lcc_set_errno (c, EINVAL);
830 SSTRCPY (command, "FLUSH");
833 SSTRCATF (command, " timeout=%i", timeout);
837 char buffer[2 * LCC_NAME_LEN];
838 SSTRCATF (command, " plugin=%s",
839 lcc_strescape (buffer, plugin, sizeof (buffer)));
844 char ident_str[6 * LCC_NAME_LEN];
845 char ident_esc[12 * LCC_NAME_LEN];
847 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
851 SSTRCATF (command, " identifier=%s",
852 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
855 status = lcc_sendreceive (c, command, &res);
861 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
862 lcc_response_free (&res);
866 lcc_response_free (&res);
868 } /* }}} int lcc_flush */
870 /* TODO: Implement lcc_putnotif */
872 int lcc_listval (lcc_connection_t *c, /* {{{ */
873 lcc_identifier_t **ret_ident, size_t *ret_ident_num)
879 lcc_identifier_t *ident;
885 if ((ret_ident == NULL) || (ret_ident_num == NULL))
887 lcc_set_errno (c, EINVAL);
891 status = lcc_sendreceive (c, "LISTVAL", &res);
897 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
898 lcc_response_free (&res);
902 ident_num = res.lines_num;
903 ident = (lcc_identifier_t *) malloc (ident_num * sizeof (*ident));
906 lcc_response_free (&res);
907 lcc_set_errno (c, ENOMEM);
911 for (i = 0; i < res.lines_num; i++)
916 /* First field is the time. */
917 time_str = res.lines[i];
919 /* Set `ident_str' to the beginning of the second field. */
920 ident_str = time_str;
921 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
923 while ((*ident_str == ' ') || (*ident_str == '\t'))
931 lcc_set_errno (c, EILSEQ);
936 status = lcc_string_to_identifier (c, ident + i, ident_str);
941 lcc_response_free (&res);
950 *ret_ident_num = ident_num;
953 } /* }}} int lcc_listval */
955 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
958 return ("Invalid object");
960 } /* }}} const char *lcc_strerror */
962 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
963 char *string, size_t string_size, const lcc_identifier_t *ident)
965 if ((string == NULL) || (string_size < 6) || (ident == NULL))
967 lcc_set_errno (c, EINVAL);
971 if (ident->plugin_instance[0] == 0)
973 if (ident->type_instance[0] == 0)
974 snprintf (string, string_size, "%s/%s/%s",
979 snprintf (string, string_size, "%s/%s/%s-%s",
983 ident->type_instance);
987 if (ident->type_instance[0] == 0)
988 snprintf (string, string_size, "%s/%s-%s/%s",
991 ident->plugin_instance,
994 snprintf (string, string_size, "%s/%s-%s/%s-%s",
997 ident->plugin_instance,
999 ident->type_instance);
1002 string[string_size - 1] = 0;
1004 } /* }}} int lcc_identifier_to_string */
1006 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
1007 lcc_identifier_t *ident, const char *string)
1012 char *plugin_instance;
1014 char *type_instance;
1016 string_copy = lcc_strdup (string);
1017 if (string_copy == NULL)
1019 lcc_set_errno (c, ENOMEM);
1024 plugin = strchr (host, '/');
1027 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1034 type = strchr (plugin, '/');
1037 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
1044 plugin_instance = strchr (plugin, '-');
1045 if (plugin_instance != NULL)
1047 *plugin_instance = 0;
1051 type_instance = strchr (type, '-');
1052 if (type_instance != NULL)
1058 memset (ident, 0, sizeof (*ident));
1060 SSTRCPY (ident->host, host);
1061 SSTRCPY (ident->plugin, plugin);
1062 if (plugin_instance != NULL)
1063 SSTRCPY (ident->plugin_instance, plugin_instance);
1064 SSTRCPY (ident->type, type);
1065 if (type_instance != NULL)
1066 SSTRCPY (ident->type_instance, type_instance);
1070 } /* }}} int lcc_string_to_identifier */
1072 /* vim: set sw=2 sts=2 et fdm=marker : */