Relicense the RRDCacheD client interface under the MIT license. This
[rrdtool.git] / src / rrd_client.c
1 /**
2  * RRDTool - src/rrd_client.c
3  * Copyright (C) 2008-2010  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy
6  * of this software and associated documentation files (the "Software"), to
7  * deal in the Software without restriction, including without limitation the
8  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9  * sell copies of the Software, and to permit persons to whom the Software is
10  * furnished to do so, subject to the following conditions:
11  * 
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  * 
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 DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at verplant.org>
25  *   Sebastian tokkee Harl <sh at tokkee.org>
26  **/
27
28 #include "rrd.h"
29 #include "rrd_tool.h"
30 #include "rrd_client.h"
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <strings.h>
36 #include <errno.h>
37 #include <assert.h>
38 #include <pthread.h>
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <sys/un.h>
42 #include <netdb.h>
43 #include <limits.h>
44
45 #ifndef ENODATA
46 #define ENODATA ENOENT
47 #endif
48
49 struct rrdc_response_s
50 {
51   int status;
52   char *message;
53   char **lines;
54   size_t lines_num;
55 };
56 typedef struct rrdc_response_s rrdc_response_t;
57
58 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
59 static int sd = -1;
60 static FILE *sh = NULL;
61 static char *sd_path = NULL; /* cache the path for sd */
62
63 /* get_path: Return a path name appropriate to be sent to the daemon.
64  *
65  * When talking to a local daemon (thru a UNIX socket), relative path names
66  * are resolved to absolute path names to allow for transparent integration
67  * into existing solutions (as requested by Tobi). Else, absolute path names
68  * are not allowed, since path name translation is done by the server.
69  *
70  * One must hold `lock' when calling this function. */
71 static const char *get_path (const char *path, char *resolved_path) /* {{{ */
72 {
73   const char *ret = path;
74   int is_unix = 0;
75
76   if ((*sd_path == '/')
77       || (strncmp ("unix:", sd_path, strlen ("unix:")) == 0))
78     is_unix = 1;
79
80   if (*path == '/') /* absolute path */
81   {
82     if (! is_unix)
83     {
84       rrd_set_error ("absolute path names not allowed when talking "
85           "to a remote daemon");
86       return (NULL);
87     }
88     /* else: nothing to do */
89   }
90   else /* relative path */
91   {
92     if (is_unix)
93     {
94       realpath (path, resolved_path);
95       ret = resolved_path;
96     }
97     /* else: nothing to do */
98   }
99   return (ret);
100 } /* }}} char *get_path */
101
102 static size_t strsplit (char *string, char **fields, size_t size) /* {{{ */
103 {
104   size_t i;
105   char *ptr;
106   char *saveptr;
107
108   i = 0;
109   ptr = string;
110   saveptr = NULL;
111   while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
112   {
113     ptr = NULL;
114     i++;
115
116     if (i >= size)
117       break;
118   }
119
120   return (i);
121 } /* }}} size_t strsplit */
122
123 static int parse_header (char *line, /* {{{ */
124     char **ret_key, char **ret_value)
125 {
126   char *tmp;
127
128   *ret_key = line;
129
130   tmp = strchr (line, ':');
131   if (tmp == NULL)
132     return (-1);
133
134   do
135   {
136     *tmp = 0;
137     tmp++;
138   }
139   while ((tmp[0] == ' ') || (tmp[0] == '\t'));
140
141   if (*tmp == 0)
142     return (-1);
143
144   *ret_value = tmp;
145   return (0);
146 } /* }}} int parse_header */
147
148 static int parse_ulong_header (char *line, /* {{{ */
149     char **ret_key, unsigned long *ret_value)
150 {
151   char *str_value;
152   char *endptr;
153   int status;
154
155   str_value = NULL;
156   status = parse_header (line, ret_key, &str_value);
157   if (status != 0)
158     return (status);
159
160   endptr = NULL;
161   errno = 0;
162   *ret_value = (unsigned long) strtol (str_value, &endptr, /* base = */ 0);
163   if ((endptr == str_value) || (errno != 0))
164     return (-1);
165
166   return (0);
167 } /* }}} int parse_ulong_header */
168
169 static int parse_char_array_header (char *line, /* {{{ */
170     char **ret_key, char **array, size_t array_len, int alloc)
171 {
172   char *tmp_array[array_len];
173   char *value;
174   size_t num;
175   int status;
176
177   value = NULL;
178   status = parse_header (line, ret_key, &value);
179   if (status != 0)
180     return (-1);
181
182   num = strsplit (value, tmp_array, array_len);
183   if (num != array_len)
184     return (-1);
185
186   if (alloc == 0)
187   {
188     memcpy (array, tmp_array, sizeof (tmp_array));
189   }
190   else
191   {
192     size_t i;
193
194     for (i = 0; i < array_len; i++)
195       array[i] = strdup (tmp_array[i]);
196   }
197
198   return (0);
199 } /* }}} int parse_char_array_header */
200
201 static int parse_value_array_header (char *line, /* {{{ */
202     time_t *ret_time, rrd_value_t *array, size_t array_len)
203 {
204   char *str_key;
205   char *str_array[array_len];
206   char *endptr;
207   int status;
208   size_t i;
209
210   str_key = NULL;
211   status = parse_char_array_header (line, &str_key,
212       str_array, array_len, /* alloc = */ 0);
213   if (status != 0)
214     return (-1);
215
216   errno = 0;
217   endptr = NULL;
218   *ret_time = (time_t) strtol (str_key, &endptr, /* base = */ 10);
219   if ((endptr == str_key) || (errno != 0))
220     return (-1);
221
222   for (i = 0; i < array_len; i++)
223   {
224     endptr = NULL;
225     array[i] = (rrd_value_t) strtod (str_array[i], &endptr);
226     if ((endptr == str_array[i]) || (errno != 0))
227       return (-1);
228   }
229
230   return (0);
231 } /* }}} int parse_value_array_header */
232
233 /* One must hold `lock' when calling `close_connection'. */
234 static void close_connection (void) /* {{{ */
235 {
236   if (sh != NULL)
237   {
238     fclose (sh);
239     sh = NULL;
240     sd = -1;
241   }
242   else if (sd >= 0)
243   {
244     close (sd);
245     sd = -1;
246   }
247
248   if (sd_path != NULL)
249     free (sd_path);
250   sd_path = NULL;
251 } /* }}} void close_connection */
252
253 static int buffer_add_string (const char *str, /* {{{ */
254     char **buffer_ret, size_t *buffer_size_ret)
255 {
256   char *buffer;
257   size_t buffer_size;
258   size_t buffer_pos;
259   size_t i;
260   int status;
261
262   buffer = *buffer_ret;
263   buffer_size = *buffer_size_ret;
264   buffer_pos = 0;
265
266   i = 0;
267   status = -1;
268   while (buffer_pos < buffer_size)
269   {
270     if (str[i] == 0)
271     {
272       buffer[buffer_pos] = ' ';
273       buffer_pos++;
274       status = 0;
275       break;
276     }
277     else if ((str[i] == ' ') || (str[i] == '\\'))
278     {
279       if (buffer_pos >= (buffer_size - 1))
280         break;
281       buffer[buffer_pos] = '\\';
282       buffer_pos++;
283       buffer[buffer_pos] = str[i];
284       buffer_pos++;
285     }
286     else
287     {
288       buffer[buffer_pos] = str[i];
289       buffer_pos++;
290     }
291     i++;
292   } /* while (buffer_pos < buffer_size) */
293
294   if (status != 0)
295     return (-1);
296
297   *buffer_ret = buffer + buffer_pos;
298   *buffer_size_ret = buffer_size - buffer_pos;
299
300   return (0);
301 } /* }}} int buffer_add_string */
302
303 static int buffer_add_value (const char *value, /* {{{ */
304     char **buffer_ret, size_t *buffer_size_ret)
305 {
306   char temp[4096];
307
308   if (strncmp (value, "N:", 2) == 0)
309     snprintf (temp, sizeof (temp), "%lu:%s",
310         (unsigned long) time (NULL), value + 2);
311   else
312     strncpy (temp, value, sizeof (temp));
313   temp[sizeof (temp) - 1] = 0;
314
315   return (buffer_add_string (temp, buffer_ret, buffer_size_ret));
316 } /* }}} int buffer_add_value */
317
318 /* Remove trailing newline (NL) and carriage return (CR) characters. Similar to
319  * the Perl function `chomp'. Returns the number of characters that have been
320  * removed. */
321 static int chomp (char *str) /* {{{ */
322 {
323   size_t len;
324   int removed;
325
326   if (str == NULL)
327     return (-1);
328
329   len = strlen (str);
330   removed = 0;
331   while ((len > 0) && ((str[len - 1] == '\n') || (str[len - 1] == '\r')))
332   {
333     str[len - 1] = 0;
334     len--;
335     removed++;
336   }
337
338   return (removed);
339 } /* }}} int chomp */
340
341 static void response_free (rrdc_response_t *res) /* {{{ */
342 {
343   if (res == NULL)
344     return;
345
346   if (res->lines != NULL)
347   {
348     size_t i;
349
350     for (i = 0; i < res->lines_num; i++)
351       if (res->lines[i] != NULL)
352         free (res->lines[i]);
353     free (res->lines);
354   }
355
356   free (res);
357 } /* }}} void response_free */
358
359 static int response_read (rrdc_response_t **ret_response) /* {{{ */
360 {
361   rrdc_response_t *ret;
362
363   char buffer[4096];
364   char *buffer_ptr;
365
366   size_t i;
367
368   if (sh == NULL)
369     return (-1);
370
371   ret = (rrdc_response_t *) malloc (sizeof (rrdc_response_t));
372   if (ret == NULL)
373     return (-2);
374   memset (ret, 0, sizeof (*ret));
375   ret->lines = NULL;
376   ret->lines_num = 0;
377
378   buffer_ptr = fgets (buffer, sizeof (buffer), sh);
379   if (buffer_ptr == NULL)
380     return (-3);
381   chomp (buffer);
382
383   ret->status = strtol (buffer, &ret->message, 0);
384   if (buffer == ret->message)
385   {
386     response_free (ret);
387     return (-4);
388   }
389   /* Skip leading whitespace of the status message */
390   ret->message += strspn (ret->message, " \t");
391
392   if (ret->status <= 0)
393   {
394     if (ret->status < 0)
395       rrd_set_error("rrdcached: %s", ret->message);
396     *ret_response = ret;
397     return (0);
398   }
399
400   ret->lines = (char **) malloc (sizeof (char *) * ret->status);
401   if (ret->lines == NULL)
402   {
403     response_free (ret);
404     return (-5);
405   }
406   memset (ret->lines, 0, sizeof (char *) * ret->status);
407   ret->lines_num = (size_t) ret->status;
408
409   for (i = 0; i < ret->lines_num; i++)
410   {
411     buffer_ptr = fgets (buffer, sizeof (buffer), sh);
412     if (buffer_ptr == NULL)
413     {
414       response_free (ret);
415       return (-6);
416     }
417     chomp (buffer);
418
419     ret->lines[i] = strdup (buffer);
420     if (ret->lines[i] == NULL)
421     {
422       response_free (ret);
423       return (-7);
424     }
425   }
426
427   *ret_response = ret;
428   return (0);
429 } /* }}} rrdc_response_t *response_read */
430
431 static int request (const char *buffer, size_t buffer_size, /* {{{ */
432     rrdc_response_t **ret_response)
433 {
434   int status;
435   rrdc_response_t *res;
436
437   if (sh == NULL)
438     return (ENOTCONN);
439
440   status = (int) fwrite (buffer, buffer_size, /* nmemb = */ 1, sh);
441   if (status != 1)
442   {
443     close_connection ();
444     rrd_set_error("request: socket error (%d) while talking to rrdcached",
445                   status);
446     return (-1);
447   }
448   fflush (sh);
449
450   res = NULL;
451   status = response_read (&res);
452
453   if (status != 0)
454   {
455     if (status < 0)
456       rrd_set_error("request: internal error while talking to rrdcached");
457     return (status);
458   }
459
460   *ret_response = res;
461   return (0);
462 } /* }}} int request */
463
464 /* determine whether we are connected to the specified daemon_addr if
465  * NULL, return whether we are connected at all
466  */
467 int rrdc_is_connected(const char *daemon_addr) /* {{{ */
468 {
469   if (sd < 0)
470     return 0;
471   else if (daemon_addr == NULL)
472   {
473     /* here we have to handle the case i.e.
474      *   UPDATE --daemon ...; UPDATEV (no --daemon) ...
475      * In other words: we have a cached connection,
476      * but it is not specified in the current command.
477      * Daemon is only implied in this case if set in ENV
478      */
479     if (getenv(ENV_RRDCACHED_ADDRESS) != NULL)
480       return 1;
481     else
482       return 0;
483   }
484   else if (strcmp(daemon_addr, sd_path) == 0)
485     return 1;
486   else
487     return 0;
488
489 } /* }}} int rrdc_is_connected */
490
491 static int rrdc_connect_unix (const char *path) /* {{{ */
492 {
493   struct sockaddr_un sa;
494   int status;
495
496   assert (path != NULL);
497   assert (sd == -1);
498
499   sd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
500   if (sd < 0)
501   {
502     status = errno;
503     return (status);
504   }
505
506   memset (&sa, 0, sizeof (sa));
507   sa.sun_family = AF_UNIX;
508   strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
509
510   status = connect (sd, (struct sockaddr *) &sa, sizeof (sa));
511   if (status != 0)
512   {
513     status = errno;
514     close_connection ();
515     return (status);
516   }
517
518   sh = fdopen (sd, "r+");
519   if (sh == NULL)
520   {
521     status = errno;
522     close_connection ();
523     return (status);
524   }
525
526   return (0);
527 } /* }}} int rrdc_connect_unix */
528
529 static int rrdc_connect_network (const char *addr_orig) /* {{{ */
530 {
531   struct addrinfo ai_hints;
532   struct addrinfo *ai_res;
533   struct addrinfo *ai_ptr;
534   char addr_copy[NI_MAXHOST];
535   char *addr;
536   char *port;
537
538   assert (addr_orig != NULL);
539   assert (sd == -1);
540
541   strncpy(addr_copy, addr_orig, sizeof(addr_copy));
542   addr_copy[sizeof(addr_copy) - 1] = '\0';
543   addr = addr_copy;
544
545   int status;
546   memset (&ai_hints, 0, sizeof (ai_hints));
547   ai_hints.ai_flags = 0;
548 #ifdef AI_ADDRCONFIG
549   ai_hints.ai_flags |= AI_ADDRCONFIG;
550 #endif
551   ai_hints.ai_family = AF_UNSPEC;
552   ai_hints.ai_socktype = SOCK_STREAM;
553
554   port = NULL;
555   if (*addr == '[') /* IPv6+port format */
556   {
557     /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
558     addr++;
559
560     port = strchr (addr, ']');
561     if (port == NULL)
562     {
563       rrd_set_error("malformed address: %s", addr_orig);
564       return (-1);
565     }
566     *port = 0;
567     port++;
568
569     if (*port == ':')
570       port++;
571     else if (*port == 0)
572       port = NULL;
573     else
574     {
575       rrd_set_error("garbage after address: %s", port);
576       return (-1);
577     }
578   } /* if (*addr == '[') */
579   else
580   {
581     port = rindex(addr, ':');
582     if (port != NULL)
583     {
584       *port = 0;
585       port++;
586     }
587   }
588
589   ai_res = NULL;
590   status = getaddrinfo (addr,
591                         port == NULL ? RRDCACHED_DEFAULT_PORT : port,
592                         &ai_hints, &ai_res);
593   if (status != 0)
594   {
595     rrd_set_error ("failed to resolve address `%s' (port %s): %s",
596         addr, port == NULL ? RRDCACHED_DEFAULT_PORT : port,
597         gai_strerror (status));
598     return (-1);
599   }
600
601   for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
602   {
603     sd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
604     if (sd < 0)
605     {
606       status = errno;
607       sd = -1;
608       continue;
609     }
610
611     status = connect (sd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
612     if (status != 0)
613     {
614       status = errno;
615       close_connection();
616       continue;
617     }
618
619     sh = fdopen (sd, "r+");
620     if (sh == NULL)
621     {
622       status = errno;
623       close_connection ();
624       continue;
625     }
626
627     assert (status == 0);
628     break;
629   } /* for (ai_ptr) */
630
631   return (status);
632 } /* }}} int rrdc_connect_network */
633
634 int rrdc_connect (const char *addr) /* {{{ */
635 {
636   int status = 0;
637
638   if (addr == NULL)
639     addr = getenv (ENV_RRDCACHED_ADDRESS);
640
641   if (addr == NULL)
642     return 0;
643
644   pthread_mutex_lock(&lock);
645
646   if (sd >= 0 && sd_path != NULL && strcmp(addr, sd_path) == 0)
647   {
648     /* connection to the same daemon; use cached connection */
649     pthread_mutex_unlock (&lock);
650     return (0);
651   }
652   else
653   {
654     close_connection();
655   }
656
657   rrd_clear_error ();
658   if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
659     status = rrdc_connect_unix (addr + strlen ("unix:"));
660   else if (addr[0] == '/')
661     status = rrdc_connect_unix (addr);
662   else
663     status = rrdc_connect_network(addr);
664
665   if (status == 0 && sd >= 0)
666     sd_path = strdup(addr);
667   else
668   {
669     char *err = rrd_test_error () ? rrd_get_error () : "Internal error";
670     /* err points the string that gets written to by rrd_set_error(), thus we
671      * cannot pass it to that function */
672     err = strdup (err);
673     rrd_set_error("Unable to connect to rrdcached: %s",
674                   (status < 0)
675                   ? (err ? err : "Internal error")
676                   : rrd_strerror (status));
677     if (err != NULL)
678       free (err);
679   }
680
681   pthread_mutex_unlock (&lock);
682   return (status);
683 } /* }}} int rrdc_connect */
684
685 int rrdc_disconnect (void) /* {{{ */
686 {
687   pthread_mutex_lock (&lock);
688
689   close_connection();
690
691   pthread_mutex_unlock (&lock);
692
693   return (0);
694 } /* }}} int rrdc_disconnect */
695
696 int rrdc_update (const char *filename, int values_num, /* {{{ */
697                 const char * const *values)
698 {
699   char buffer[4096];
700   char *buffer_ptr;
701   size_t buffer_free;
702   size_t buffer_size;
703   rrdc_response_t *res;
704   int status;
705   int i;
706   char file_path[PATH_MAX];
707
708   memset (buffer, 0, sizeof (buffer));
709   buffer_ptr = &buffer[0];
710   buffer_free = sizeof (buffer);
711
712   status = buffer_add_string ("update", &buffer_ptr, &buffer_free);
713   if (status != 0)
714     return (ENOBUFS);
715
716   pthread_mutex_lock (&lock);
717   filename = get_path (filename, file_path);
718   if (filename == NULL)
719   {
720     pthread_mutex_unlock (&lock);
721     return (-1);
722   }
723
724   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
725   if (status != 0)
726   {
727     pthread_mutex_unlock (&lock);
728     return (ENOBUFS);
729   }
730
731   for (i = 0; i < values_num; i++)
732   {
733     status = buffer_add_value (values[i], &buffer_ptr, &buffer_free);
734     if (status != 0)
735     {
736       pthread_mutex_unlock (&lock);
737       return (ENOBUFS);
738     }
739   }
740
741   assert (buffer_free < sizeof (buffer));
742   buffer_size = sizeof (buffer) - buffer_free;
743   assert (buffer[buffer_size - 1] == ' ');
744   buffer[buffer_size - 1] = '\n';
745
746   res = NULL;
747   status = request (buffer, buffer_size, &res);
748   pthread_mutex_unlock (&lock);
749
750   if (status != 0)
751     return (status);
752
753   status = res->status;
754   response_free (res);
755
756   return (status);
757 } /* }}} int rrdc_update */
758
759 int rrdc_flush (const char *filename) /* {{{ */
760 {
761   char buffer[4096];
762   char *buffer_ptr;
763   size_t buffer_free;
764   size_t buffer_size;
765   rrdc_response_t *res;
766   int status;
767   char file_path[PATH_MAX];
768
769   if (filename == NULL)
770     return (-1);
771
772   memset (buffer, 0, sizeof (buffer));
773   buffer_ptr = &buffer[0];
774   buffer_free = sizeof (buffer);
775
776   status = buffer_add_string ("flush", &buffer_ptr, &buffer_free);
777   if (status != 0)
778     return (ENOBUFS);
779
780   pthread_mutex_lock (&lock);
781   filename = get_path (filename, file_path);
782   if (filename == NULL)
783   {
784     pthread_mutex_unlock (&lock);
785     return (-1);
786   }
787
788   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
789   if (status != 0)
790   {
791     pthread_mutex_unlock (&lock);
792     return (ENOBUFS);
793   }
794
795   assert (buffer_free < sizeof (buffer));
796   buffer_size = sizeof (buffer) - buffer_free;
797   assert (buffer[buffer_size - 1] == ' ');
798   buffer[buffer_size - 1] = '\n';
799
800   res = NULL;
801   status = request (buffer, buffer_size, &res);
802   pthread_mutex_unlock (&lock);
803
804   if (status != 0)
805     return (status);
806
807   status = res->status;
808   response_free (res);
809
810   return (status);
811 } /* }}} int rrdc_flush */
812
813 int rrdc_fetch (const char *filename, /* {{{ */
814     const char *cf,
815     time_t *ret_start, time_t *ret_end,
816     unsigned long *ret_step,
817     unsigned long *ret_ds_num,
818     char ***ret_ds_names,
819     rrd_value_t **ret_data)
820 {
821   char buffer[4096];
822   char *buffer_ptr;
823   size_t buffer_free;
824   size_t buffer_size;
825   rrdc_response_t *res;
826   char path_buffer[PATH_MAX];
827   char *path_ptr;
828
829   char *str_tmp;
830   unsigned long flush_version;
831
832   time_t start;
833   time_t end;
834   unsigned long step;
835   unsigned long ds_num;
836   char **ds_names;
837
838   rrd_value_t *data;
839   size_t data_size;
840   size_t data_fill;
841
842   int status;
843   size_t current_line;
844   time_t t;
845
846   if ((filename == NULL) || (cf == NULL))
847     return (-1);
848
849   /* Send request {{{ */
850   memset (buffer, 0, sizeof (buffer));
851   buffer_ptr = &buffer[0];
852   buffer_free = sizeof (buffer);
853
854   status = buffer_add_string ("FETCH", &buffer_ptr, &buffer_free);
855   if (status != 0)
856     return (ENOBUFS);
857
858   /* change to path for rrdcached */
859   path_ptr = get_path (filename, path_buffer);
860   if (path_ptr == NULL)
861     return (EINVAL);
862
863   status = buffer_add_string (path_ptr, &buffer_ptr, &buffer_free);
864   if (status != 0)
865     return (ENOBUFS);
866
867   status = buffer_add_string (cf, &buffer_ptr, &buffer_free);
868   if (status != 0)
869     return (ENOBUFS);
870
871   if ((ret_start != NULL) && (*ret_start > 0))
872   {
873     char tmp[64];
874     snprintf (tmp, sizeof (tmp), "%lu", (unsigned long) *ret_start);
875     tmp[sizeof (tmp) - 1] = 0;
876     status = buffer_add_string (tmp, &buffer_ptr, &buffer_free);
877     if (status != 0)
878       return (ENOBUFS);
879
880     if ((ret_end != NULL) && (*ret_end > 0))
881     {
882       snprintf (tmp, sizeof (tmp), "%lu", (unsigned long) *ret_end);
883       tmp[sizeof (tmp) - 1] = 0;
884       status = buffer_add_string (tmp, &buffer_ptr, &buffer_free);
885       if (status != 0)
886         return (ENOBUFS);
887     }
888   }
889
890   assert (buffer_free < sizeof (buffer));
891   buffer_size = sizeof (buffer) - buffer_free;
892   assert (buffer[buffer_size - 1] == ' ');
893   buffer[buffer_size - 1] = '\n';
894
895   res = NULL;
896   status = request (buffer, buffer_size, &res);
897   if (status != 0)
898     return (status);
899
900   status = res->status;
901   if (status < 0)
902   {
903     rrd_set_error ("rrdcached: %s", res->message);
904     response_free (res);
905     return (status);
906   }
907   /* }}} Send request */
908
909   ds_names = NULL;
910   ds_num = 0;
911   data = NULL;
912   current_line = 0;
913
914   /* Macros to make error handling a little easier (i. e. less to type and
915    * read. `BAIL_OUT' sets the error message, frees all dynamically allocated
916    * variables and returns the provided status code. */
917 #define BAIL_OUT(status, ...) do { \
918     rrd_set_error ("rrdc_fetch: " __VA_ARGS__); \
919     free (data); \
920     if (ds_names != 0) { size_t k; for (k = 0; k < ds_num; k++) free (ds_names[k]); } \
921     free (ds_names); \
922     response_free (res); \
923     return (status); \
924   } while (0)
925
926 #define READ_NUMERIC_FIELD(name,type,var) do { \
927     char *key; \
928     unsigned long value; \
929     assert (current_line < res->lines_num); \
930     status = parse_ulong_header (res->lines[current_line], &key, &value); \
931     if (status != 0) \
932       BAIL_OUT (-1, "Unable to parse header `%s'", name); \
933     if (strcasecmp (key, name) != 0) \
934       BAIL_OUT (-1, "Unexpected header line: Expected `%s', got `%s'", name, key); \
935     var = (type) value; \
936     current_line++; \
937   } while (0)
938
939   if (res->lines_num < 1)
940     BAIL_OUT (-1, "Premature end of response packet");
941
942   /* We're making some very strong assumptions about the fields below. We
943    * therefore check the version of the `flush' command first, so that later
944    * versions can change the order of fields and it's easier to implement
945    * backwards compatibility. */
946   READ_NUMERIC_FIELD ("FlushVersion", unsigned long, flush_version);
947   if (flush_version != 1)
948     BAIL_OUT (-1, "Don't know how to handle flush format version %lu.",
949         flush_version);
950
951   if (res->lines_num < 5)
952     BAIL_OUT (-1, "Premature end of response packet");
953
954   READ_NUMERIC_FIELD ("Start", time_t, start);
955   READ_NUMERIC_FIELD ("End", time_t, end);
956   if (start >= end)
957     BAIL_OUT (-1, "Malformed start and end times: start = %lu; end = %lu;",
958         (unsigned long) start,
959         (unsigned long) end);
960
961   READ_NUMERIC_FIELD ("Step", unsigned long, step);
962   if (step < 1)
963     BAIL_OUT (-1, "Invalid number for Step: %lu", step);
964
965   READ_NUMERIC_FIELD ("DSCount", unsigned long, ds_num);
966   if (ds_num < 1)
967     BAIL_OUT (-1, "Invalid number for DSCount: %lu", ds_num);
968   
969   /* It's time to allocate some memory */
970   ds_names = calloc ((size_t) ds_num, sizeof (*ds_names));
971   if (ds_names == NULL)
972     BAIL_OUT (-1, "Out of memory");
973
974   status = parse_char_array_header (res->lines[current_line],
975       &str_tmp, ds_names, (size_t) ds_num, /* alloc = */ 1);
976   if (status != 0)
977     BAIL_OUT (-1, "Unable to parse header `DSName'");
978   if (strcasecmp ("DSName", str_tmp) != 0)
979     BAIL_OUT (-1, "Unexpected header line: Expected `DSName', got `%s'", str_tmp);
980   current_line++;
981
982   data_size = ds_num * (end - start) / step;
983   if (data_size < 1)
984     BAIL_OUT (-1, "No data returned or headers invalid.");
985
986   if (res->lines_num != (6 + (data_size / ds_num)))
987     BAIL_OUT (-1, "Got %zu lines, expected %zu",
988         res->lines_num, (6 + (data_size / ds_num)));
989
990   data = calloc (data_size, sizeof (*data));
991   if (data == NULL)
992     BAIL_OUT (-1, "Out of memory");
993   
994
995   data_fill = 0;
996   for (t = start + step; t <= end; t += step, current_line++)
997   {
998     time_t tmp;
999
1000     assert (current_line < res->lines_num);
1001
1002     status = parse_value_array_header (res->lines[current_line],
1003         &tmp, data + data_fill, (size_t) ds_num);
1004     if (status != 0)
1005       BAIL_OUT (-1, "Cannot parse value line");
1006
1007     data_fill += (size_t) ds_num;
1008   }
1009
1010   *ret_start = start;
1011   *ret_end = end;
1012   *ret_step = step;
1013   *ret_ds_num = ds_num;
1014   *ret_ds_names = ds_names;
1015   *ret_data = data;
1016
1017   response_free (res);
1018   return (0);
1019 #undef READ_NUMERIC_FIELD
1020 #undef BAIL_OUT
1021 } /* }}} int rrdc_flush */
1022
1023 /* convenience function; if there is a daemon specified, or if we can
1024  * detect one from the environment, then flush the file.  Otherwise, no-op
1025  */
1026 int rrdc_flush_if_daemon (const char *opt_daemon, const char *filename) /* {{{ */
1027 {
1028   int status = 0;
1029
1030   rrdc_connect(opt_daemon);
1031
1032   if (rrdc_is_connected(opt_daemon))
1033   {
1034     rrd_clear_error();
1035     status = rrdc_flush (filename);
1036
1037     if (status != 0 && !rrd_test_error())
1038     {
1039       if (status > 0)
1040       {
1041         rrd_set_error("rrdc_flush (%s) failed: %s",
1042                       filename, rrd_strerror(status));
1043       }
1044       else if (status < 0)
1045       {
1046         rrd_set_error("rrdc_flush (%s) failed with status %i.",
1047                       filename, status);
1048       }
1049     }
1050   } /* if (rrdc_is_connected(..)) */
1051
1052   return status;
1053 } /* }}} int rrdc_flush_if_daemon */
1054
1055
1056 int rrdc_stats_get (rrdc_stats_t **ret_stats) /* {{{ */
1057 {
1058   rrdc_stats_t *head;
1059   rrdc_stats_t *tail;
1060
1061   rrdc_response_t *res;
1062
1063   int status;
1064   size_t i;
1065
1066   /* Protocol example: {{{
1067    * ->  STATS
1068    * <-  5 Statistics follow
1069    * <-  QueueLength: 0
1070    * <-  UpdatesWritten: 0
1071    * <-  DataSetsWritten: 0
1072    * <-  TreeNodesNumber: 0
1073    * <-  TreeDepth: 0
1074    * }}} */
1075
1076   res = NULL;
1077   pthread_mutex_lock (&lock);
1078   status = request ("STATS\n", strlen ("STATS\n"), &res);
1079   pthread_mutex_unlock (&lock);
1080
1081   if (status != 0)
1082     return (status);
1083
1084   if (res->status <= 0)
1085   {
1086     response_free (res);
1087     return (EIO);
1088   }
1089
1090   head = NULL;
1091   tail = NULL;
1092   for (i = 0; i < res->lines_num; i++)
1093   {
1094     char *key;
1095     char *value;
1096     char *endptr;
1097     rrdc_stats_t *s;
1098
1099     key = res->lines[i];
1100     value = strchr (key, ':');
1101     if (value == NULL)
1102       continue;
1103     *value = 0;
1104     value++;
1105
1106     while ((value[0] == ' ') || (value[0] == '\t'))
1107       value++;
1108
1109     s = (rrdc_stats_t *) malloc (sizeof (rrdc_stats_t));
1110     if (s == NULL)
1111       continue;
1112     memset (s, 0, sizeof (*s));
1113
1114     s->name = strdup (key);
1115
1116     endptr = NULL;
1117     if ((strcmp ("QueueLength", key) == 0)
1118         || (strcmp ("TreeDepth", key) == 0)
1119         || (strcmp ("TreeNodesNumber", key) == 0))
1120     {
1121       s->type = RRDC_STATS_TYPE_GAUGE;
1122       s->value.gauge = strtod (value, &endptr);
1123     }
1124     else if ((strcmp ("DataSetsWritten", key) == 0)
1125         || (strcmp ("FlushesReceived", key) == 0)
1126         || (strcmp ("JournalBytes", key) == 0)
1127         || (strcmp ("JournalRotate", key) == 0)
1128         || (strcmp ("UpdatesReceived", key) == 0)
1129         || (strcmp ("UpdatesWritten", key) == 0))
1130     {
1131       s->type = RRDC_STATS_TYPE_COUNTER;
1132       s->value.counter = (uint64_t) strtoll (value, &endptr, /* base = */ 0);
1133     }
1134     else
1135     {
1136       free (s);
1137       continue;
1138     }
1139
1140     /* Conversion failed */
1141     if (endptr == value)
1142     {
1143       free (s);
1144       continue;
1145     }
1146
1147     if (head == NULL)
1148     {
1149       head = s;
1150       tail = s;
1151       s->next = NULL;
1152     }
1153     else
1154     {
1155       tail->next = s;
1156       tail = s;
1157     }
1158   } /* for (i = 0; i < res->lines_num; i++) */
1159
1160   response_free (res);
1161
1162   if (head == NULL)
1163     return (EPROTO);
1164
1165   *ret_stats = head;
1166   return (0);
1167 } /* }}} int rrdc_stats_get */
1168
1169 void rrdc_stats_free (rrdc_stats_t *ret_stats) /* {{{ */
1170 {
1171   rrdc_stats_t *this;
1172
1173   this = ret_stats;
1174   while (this != NULL)
1175   {
1176     rrdc_stats_t *next;
1177
1178     next = this->next;
1179
1180     if (this->name != NULL)
1181     {
1182       free ((char *)this->name);
1183       this->name = NULL;
1184     }
1185     free (this);
1186
1187     this = next;
1188   } /* while (this != NULL) */
1189 } /* }}} void rrdc_stats_free */
1190
1191 /*
1192  * vim: set sw=2 sts=2 ts=8 et fdm=marker :
1193  */