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
36 /* Disable non-standard extensions */
47 #if !defined(__GNUC__) || !__GNUC__
48 # define __attribute__(x) /**/
58 #include <sys/types.h>
59 #include <sys/socket.h>
69 /* NI_MAXHOST has been obsoleted by RFC 3493 which is a reason for SunOS 5.11
70 * to no longer define it. We'll use the old, RFC 2553 value here. */
72 # define NI_MAXHOST 1025
75 /* Secure/static macros. They work like `strcpy' and `strcat', but assure null
76 * termination. They work for static buffers only, because they use `sizeof'.
77 * The `SSTRCATF' combines the functionality of `snprintf' and `strcat' which
78 * is very useful to add formatted stuff to the end of a buffer. */
79 #define SSTRCPY(d,s) do { \
80 strncpy ((d), (s), sizeof (d)); \
81 (d)[sizeof (d) - 1] = 0; \
84 #define SSTRCAT(d,s) do { \
85 strncat ((d), (s), sizeof (d)); \
86 (d)[sizeof (d) - 1] = 0; \
89 #define SSTRCATF(d, ...) do { \
90 char _b[sizeof (d)]; \
91 snprintf (_b, sizeof (_b), __VA_ARGS__); \
92 _b[sizeof (_b) - 1] = 0; \
97 #define LCC_SET_ERRSTR(c, ...) do { \
98 snprintf ((c)->errbuf, sizeof ((c)->errbuf), __VA_ARGS__); \
99 (c)->errbuf[sizeof ((c)->errbuf) - 1] = 0; \
103 # define LCC_DEBUG(...) printf (__VA_ARGS__)
105 # define LCC_DEBUG(...) /**/
111 struct lcc_connection_s
117 struct lcc_response_s
124 typedef struct lcc_response_s lcc_response_t;
129 static int lcc_set_errno (lcc_connection_t *c, int err) /* {{{ */
134 strerror_r (err, c->errbuf, sizeof (c->errbuf));
135 c->errbuf[sizeof (c->errbuf) - 1] = 0;
138 } /* }}} int lcc_set_errno */
140 /* lcc_strdup: Since `strdup' is an XSI extension, we provide our own version
142 __attribute__((malloc, nonnull (1)))
143 static char *lcc_strdup (const char *str) /* {{{ */
148 strsize = strlen (str) + 1;
149 ret = (char *) malloc (strsize);
151 memcpy (ret, str, strsize);
153 } /* }}} char *lcc_strdup */
155 __attribute__((nonnull (1, 2)))
156 static char *lcc_strescape (char *dest, const char *src, size_t dest_size) /* {{{ */
164 assert (dest_size >= 3);
166 dest[dest_pos] = '"';
171 if ((dest_pos == (dest_size - 2))
172 || (src[src_pos] == 0))
175 if ((src[src_pos] == '"') || (src[src_pos] == '\\'))
177 /* Check if there is enough space for both characters.. */
178 if (dest_pos == (dest_size - 3))
181 dest[dest_pos] = '\\';
185 dest[dest_pos] = src[src_pos];
190 assert (dest_pos <= (dest_size - 2));
192 dest[dest_pos] = '"';
200 } /* }}} char *lcc_strescape */
202 /* lcc_chomp: Removes all control-characters at the end of a string. */
203 static void lcc_chomp (char *str) /* {{{ */
207 str_len = strlen (str);
210 if (str[str_len - 1] >= 32)
212 str[str_len - 1] = 0;
215 } /* }}} void lcc_chomp */
217 static void lcc_response_free (lcc_response_t *res) /* {{{ */
224 for (i = 0; i < res->lines_num; i++)
225 free (res->lines[i]);
228 } /* }}} void lcc_response_free */
230 static int lcc_send (lcc_connection_t *c, const char *command) /* {{{ */
234 LCC_DEBUG ("send: --> %s\n", command);
236 status = fprintf (c->fh, "%s\r\n", command);
239 lcc_set_errno (c, errno);
244 } /* }}} int lcc_send */
246 static int lcc_receive (lcc_connection_t *c, /* {{{ */
247 lcc_response_t *ret_res)
254 memset (&res, 0, sizeof (res));
256 /* Read the first line, containing the status and a message */
257 ptr = fgets (buffer, sizeof (buffer), c->fh);
260 lcc_set_errno (c, errno);
264 LCC_DEBUG ("receive: <-- %s\n", buffer);
266 /* Convert the leading status to an integer and make `ptr' to point to the
267 * beginning of the message. */
270 res.status = strtol (buffer, &ptr, 0);
271 if ((errno != 0) || (ptr == &buffer[0]))
273 lcc_set_errno (c, errno);
277 /* Skip white spaces after the status number */
278 while ((*ptr == ' ') || (*ptr == '\t'))
281 /* Now copy the message. */
282 strncpy (res.message, ptr, sizeof (res.message));
283 res.message[sizeof (res.message) - 1] = 0;
285 /* Error or no lines follow: We're done. */
288 memcpy (ret_res, &res, sizeof (res));
292 /* Allocate space for the char-pointers */
293 res.lines_num = (size_t) res.status;
295 res.lines = (char **) malloc (res.lines_num * sizeof (char *));
296 if (res.lines == NULL)
298 lcc_set_errno (c, ENOMEM);
302 /* Now receive all the lines */
303 for (i = 0; i < res.lines_num; i++)
305 ptr = fgets (buffer, sizeof (buffer), c->fh);
308 lcc_set_errno (c, errno);
312 LCC_DEBUG ("receive: <-- %s\n", buffer);
314 res.lines[i] = lcc_strdup (buffer);
315 if (res.lines[i] == NULL)
317 lcc_set_errno (c, ENOMEM);
322 /* Check if the for-loop exited with an error. */
323 if (i < res.lines_num)
334 memcpy (ret_res, &res, sizeof (res));
336 } /* }}} int lcc_receive */
338 static int lcc_sendreceive (lcc_connection_t *c, /* {{{ */
339 const char *command, lcc_response_t *ret_res)
344 status = lcc_send (c, command);
348 memset (&res, 0, sizeof (res));
349 status = lcc_receive (c, &res);
351 memcpy (ret_res, &res, sizeof (*ret_res));
354 } /* }}} int lcc_sendreceive */
356 static int lcc_open_unixsocket (lcc_connection_t *c, const char *path) /* {{{ */
358 struct sockaddr_un sa;
363 assert (c->fh == NULL);
364 assert (path != NULL);
366 /* Don't use PF_UNIX here, because it's broken on Mac OS X (10.4, possibly
368 fd = socket (AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
371 lcc_set_errno (c, errno);
375 memset (&sa, 0, sizeof (sa));
376 sa.sun_family = AF_UNIX;
377 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
379 status = connect (fd, (struct sockaddr *) &sa, sizeof (sa));
382 lcc_set_errno (c, errno);
387 c->fh = fdopen (fd, "r+");
390 lcc_set_errno (c, errno);
396 } /* }}} int lcc_open_unixsocket */
398 static int lcc_open_netsocket (lcc_connection_t *c, /* {{{ */
399 const char *addr_orig)
401 struct addrinfo ai_hints;
402 struct addrinfo *ai_res;
403 struct addrinfo *ai_ptr;
404 char addr_copy[NI_MAXHOST];
411 assert (c->fh == NULL);
412 assert (addr_orig != NULL);
414 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
415 addr_copy[sizeof(addr_copy) - 1] = '\0';
418 memset (&ai_hints, 0, sizeof (ai_hints));
419 ai_hints.ai_flags = 0;
421 ai_hints.ai_flags |= AI_ADDRCONFIG;
423 ai_hints.ai_family = AF_UNSPEC;
424 ai_hints.ai_socktype = SOCK_STREAM;
427 if (*addr == '[') /* IPv6+port format */
429 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
432 port = strchr (addr, ']');
435 LCC_SET_ERRSTR (c, "malformed address: %s", addr_orig);
447 LCC_SET_ERRSTR (c, "garbage after address: %s", port);
450 } /* if (*addr = ']') */
451 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
453 port = strrchr (addr, ':');
462 status = getaddrinfo (addr,
463 port == NULL ? LCC_DEFAULT_PORT : port,
467 LCC_SET_ERRSTR (c, "getaddrinfo: %s", gai_strerror (status));
471 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
473 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
481 status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
490 c->fh = fdopen (fd, "r+");
499 assert (status == 0);
505 lcc_set_errno (c, status);
510 } /* }}} int lcc_open_netsocket */
512 static int lcc_open_socket (lcc_connection_t *c, const char *addr) /* {{{ */
520 assert (c->fh == NULL);
521 assert (addr != NULL);
523 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
524 status = lcc_open_unixsocket (c, addr + strlen ("unix:"));
525 else if (addr[0] == '/')
526 status = lcc_open_unixsocket (c, addr);
528 status = lcc_open_netsocket (c, addr);
531 } /* }}} int lcc_open_socket */
536 int lcc_connect (const char *address, lcc_connection_t **ret_con) /* {{{ */
546 c = (lcc_connection_t *) malloc (sizeof (*c));
549 memset (c, 0, sizeof (*c));
552 return (lcc_open_socket (c, address));
553 } /* }}} int lcc_connect */
555 int lcc_disconnect (lcc_connection_t *c) /* {{{ */
568 } /* }}} int lcc_disconnect */
570 int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
571 size_t *ret_values_num, gauge_t **ret_values, char ***ret_values_names)
573 char ident_str[6 * LCC_NAME_LEN];
574 char ident_esc[12 * LCC_NAME_LEN];
575 char command[14 * LCC_NAME_LEN];
579 gauge_t *values = NULL;
580 char **values_names = NULL;
590 lcc_set_errno (c, EINVAL);
594 /* Build a commend with an escaped version of the identifier string. */
595 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str), ident);
599 snprintf (command, sizeof (command), "GETVAL %s",
600 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
601 command[sizeof (command) - 1] = 0;
603 /* Send talk to the daemon.. */
604 status = lcc_sendreceive (c, command, &res);
610 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
611 lcc_response_free (&res);
615 values_num = res.lines_num;
617 #define BAIL_OUT(e) do { \
618 lcc_set_errno (c, (e)); \
620 if (values_names != NULL) { \
621 for (i = 0; i < values_num; i++) { \
622 free (values_names[i]); \
625 free (values_names); \
626 lcc_response_free (&res); \
630 /* If neither the values nor the names are requested, return here.. */
631 if ((ret_values == NULL) && (ret_values_names == NULL))
633 if (ret_values_num != NULL)
634 *ret_values_num = values_num;
635 lcc_response_free (&res);
639 /* Allocate space for the values */
640 if (ret_values != NULL)
642 values = (gauge_t *) malloc (values_num * sizeof (*values));
647 if (ret_values_names != NULL)
649 values_names = (char **) calloc (values_num, sizeof (*values_names));
650 if (values_names == NULL)
654 for (i = 0; i < res.lines_num; i++)
661 value = strchr (key, '=');
672 values[i] = strtod (value, &endptr);
674 if ((endptr == value) || (errno != 0))
678 if (values_names != NULL)
680 values_names[i] = lcc_strdup (key);
681 if (values_names[i] == NULL)
684 } /* for (i = 0; i < res.lines_num; i++) */
686 if (ret_values_num != NULL)
687 *ret_values_num = values_num;
688 if (ret_values != NULL)
689 *ret_values = values;
690 if (ret_values_names != NULL)
691 *ret_values_names = values_names;
694 } /* }}} int lcc_getval */
696 int lcc_putval (lcc_connection_t *c, const lcc_value_list_t *vl) /* {{{ */
698 char ident_str[6 * LCC_NAME_LEN];
699 char ident_esc[12 * LCC_NAME_LEN];
700 char command[1024] = "";
705 if ((c == NULL) || (vl == NULL) || (vl->values_len < 1)
706 || (vl->values == NULL) || (vl->values_types == NULL))
708 lcc_set_errno (c, EINVAL);
712 status = lcc_identifier_to_string (c, ident_str, sizeof (ident_str),
717 SSTRCATF (command, "PUTVAL %s",
718 lcc_strescape (ident_esc, ident_str, sizeof (ident_esc)));
720 if (vl->interval > 0)
721 SSTRCATF (command, " interval=%i", vl->interval);
724 SSTRCATF (command, "%u", (unsigned int) vl->time);
726 SSTRCAT (command, "N");
728 for (i = 0; i < vl->values_len; i++)
730 if (vl->values_types[i] == LCC_TYPE_COUNTER)
731 SSTRCATF (command, ":%"PRIu64, vl->values[i].counter);
732 else if (vl->values_types[i] == LCC_TYPE_GAUGE)
734 if (isnan (vl->values[i].gauge))
735 SSTRCPY (command, ":U");
737 SSTRCATF (command, ":%g", vl->values[i].gauge);
739 } /* for (i = 0; i < vl->values_len; i++) */
741 status = lcc_sendreceive (c, command, &res);
747 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
748 lcc_response_free (&res);
752 lcc_response_free (&res);
754 } /* }}} int lcc_putval */
756 int lcc_flush (lcc_connection_t *c, const char *plugin, /* {{{ */
757 lcc_identifier_t *ident, int timeout)
765 lcc_set_errno (c, EINVAL);
769 SSTRCPY (command, "FLUSH");
772 SSTRCATF (command, " timeout=%i", timeout);
776 char buffer[2 * LCC_NAME_LEN];
777 SSTRCATF (command, " plugin=%s",
778 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);
800 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
801 lcc_response_free (&res);
805 lcc_response_free (&res);
807 } /* }}} int lcc_flush */
809 /* TODO: Implement lcc_putnotif */
811 int lcc_listval (lcc_connection_t *c, /* {{{ */
812 lcc_identifier_t **ret_ident, size_t *ret_ident_num)
818 lcc_identifier_t *ident;
824 if ((ret_ident == NULL) || (ret_ident_num == NULL))
826 lcc_set_errno (c, EINVAL);
830 status = lcc_sendreceive (c, "LISTVAL", &res);
836 LCC_SET_ERRSTR (c, "Server error: %s", res.message);
837 lcc_response_free (&res);
841 ident_num = res.lines_num;
842 ident = (lcc_identifier_t *) malloc (ident_num * sizeof (*ident));
845 lcc_response_free (&res);
846 lcc_set_errno (c, ENOMEM);
850 for (i = 0; i < res.lines_num; i++)
855 /* First field is the time. */
856 time_str = res.lines[i];
858 /* Set `ident_str' to the beginning of the second field. */
859 ident_str = time_str;
860 while ((*ident_str != ' ') && (*ident_str != '\t') && (*ident_str != 0))
862 while ((*ident_str == ' ') || (*ident_str == '\t'))
870 lcc_set_errno (c, EPROTO);
875 status = lcc_string_to_identifier (c, ident + i, ident_str);
880 lcc_response_free (&res);
889 *ret_ident_num = ident_num;
892 } /* }}} int lcc_listval */
894 const char *lcc_strerror (lcc_connection_t *c) /* {{{ */
897 return ("Invalid object");
899 } /* }}} const char *lcc_strerror */
901 int lcc_identifier_to_string (lcc_connection_t *c, /* {{{ */
902 char *string, size_t string_size, const lcc_identifier_t *ident)
904 if ((string == NULL) || (string_size < 6) || (ident == NULL))
906 lcc_set_errno (c, EINVAL);
910 if (ident->plugin_instance[0] == 0)
912 if (ident->type_instance[0] == 0)
913 snprintf (string, string_size, "%s/%s/%s",
918 snprintf (string, string_size, "%s/%s/%s-%s",
922 ident->type_instance);
926 if (ident->type_instance[0] == 0)
927 snprintf (string, string_size, "%s/%s-%s/%s",
930 ident->plugin_instance,
933 snprintf (string, string_size, "%s/%s-%s/%s-%s",
936 ident->plugin_instance,
938 ident->type_instance);
941 string[string_size - 1] = 0;
943 } /* }}} int lcc_identifier_to_string */
945 int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
946 lcc_identifier_t *ident, const char *string)
951 char *plugin_instance;
955 string_copy = lcc_strdup (string);
956 if (string_copy == NULL)
958 lcc_set_errno (c, ENOMEM);
963 plugin = strchr (host, '/');
966 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
973 type = strchr (plugin, '/');
976 LCC_SET_ERRSTR (c, "Malformed identifier string: %s", string);
983 plugin_instance = strchr (plugin, '-');
984 if (plugin_instance != NULL)
986 *plugin_instance = 0;
990 type_instance = strchr (type, '-');
991 if (type_instance != NULL)
997 memset (ident, 0, sizeof (*ident));
999 SSTRCPY (ident->host, host);
1000 SSTRCPY (ident->plugin, plugin);
1001 if (plugin_instance != NULL)
1002 SSTRCPY (ident->plugin_instance, plugin_instance);
1003 SSTRCPY (ident->type, type);
1004 if (type_instance != NULL)
1005 SSTRCPY (ident->type_instance, type_instance);
1009 } /* }}} int lcc_string_to_identifier */
1011 /* vim: set sw=2 sts=2 et fdm=marker : */