rrd_client: Do not rewrite path names when accessing remote daemons.
[rrdtool.git] / src / rrd_client.c
1 /**
2  * RRDTool - src/rrd_client.c
3  * Copyright (C) 2008 Florian octo Forster
4  *
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.
8  *
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.
13  *
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
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  *   Sebastian tokkee Harl <sh at tokkee.org>
21  **/
22
23 #include "rrd.h"
24 #include "rrd_client.h"
25 #include "rrd_tool.h"
26
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <assert.h>
31 #include <pthread.h>
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <sys/un.h>
35 #include <netdb.h>
36
37 #ifndef ENODATA
38 #define ENODATA ENOENT
39 #endif
40
41 struct rrdc_response_s
42 {
43   int status;
44   char *message;
45   char **lines;
46   size_t lines_num;
47 };
48 typedef struct rrdc_response_s rrdc_response_t;
49
50 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
51 static int sd = -1;
52 static FILE *sh = NULL;
53 static char *sd_path = NULL; /* cache the path for sd */
54
55 /* get_path: Return a path name appropriate to be sent to the daemon.
56  *
57  * When talking to a local daemon (thru a UNIX socket), relative path names
58  * are resolved to absolute path names to allow for transparent integration
59  * into existing solutions (as requested by Tobi). Else, absolute path names
60  * are not allowed, since path name translation is done by the server.
61  *
62  * One must hold `lock' when calling this function. */
63 static const char *get_path (const char *path, char *resolved_path) /* {{{ */
64 {
65   const char *ret = path;
66   int is_unix = 0;
67
68   if ((*sd_path == '/')
69       || (strncmp ("unix:", sd_path, strlen ("unix:")) == 0))
70     is_unix = 1;
71
72   if (*path == '/') /* absolute path */
73   {
74     if (! is_unix)
75     {
76       rrd_set_error ("absolute path names not allowed when talking "
77           "to a remote daemon");
78       return (NULL);
79     }
80     /* else: nothing to do */
81   }
82   else /* relative path */
83   {
84     if (is_unix)
85     {
86       realpath (path, resolved_path);
87       ret = resolved_path;
88     }
89     /* else: nothing to do */
90   }
91   return (ret);
92 } /* }}} char *get_path */
93
94 /* One must hold `lock' when calling `close_connection'. */
95 static void close_connection (void) /* {{{ */
96 {
97   if (sh != NULL)
98   {
99     fclose (sh);
100     sh = NULL;
101     sd = -1;
102   }
103   else if (sd >= 0)
104   {
105     close (sd);
106     sd = -1;
107   }
108
109   if (sd_path != NULL)
110     free (sd_path);
111   sd_path = NULL;
112 } /* }}} void close_connection */
113
114 static int buffer_add_string (const char *str, /* {{{ */
115     char **buffer_ret, size_t *buffer_size_ret)
116 {
117   char *buffer;
118   size_t buffer_size;
119   size_t buffer_pos;
120   size_t i;
121   int status;
122
123   buffer = *buffer_ret;
124   buffer_size = *buffer_size_ret;
125   buffer_pos = 0;
126
127   i = 0;
128   status = -1;
129   while (buffer_pos < buffer_size)
130   {
131     if (str[i] == 0)
132     {
133       buffer[buffer_pos] = ' ';
134       buffer_pos++;
135       status = 0;
136       break;
137     }
138     else if ((str[i] == ' ') || (str[i] == '\\'))
139     {
140       if (buffer_pos >= (buffer_size - 1))
141         break;
142       buffer[buffer_pos] = '\\';
143       buffer_pos++;
144       buffer[buffer_pos] = str[i];
145       buffer_pos++;
146     }
147     else
148     {
149       buffer[buffer_pos] = str[i];
150       buffer_pos++;
151     }
152     i++;
153   } /* while (buffer_pos < buffer_size) */
154
155   if (status != 0)
156     return (-1);
157
158   *buffer_ret = buffer + buffer_pos;
159   *buffer_size_ret = buffer_size - buffer_pos;
160
161   return (0);
162 } /* }}} int buffer_add_string */
163
164 static int buffer_add_value (const char *value, /* {{{ */
165     char **buffer_ret, size_t *buffer_size_ret)
166 {
167   char temp[4096];
168
169   if (strncmp (value, "N:", 2) == 0)
170     snprintf (temp, sizeof (temp), "%lu:%s",
171         (unsigned long) time (NULL), value + 2);
172   else
173     strncpy (temp, value, sizeof (temp));
174   temp[sizeof (temp) - 1] = 0;
175
176   return (buffer_add_string (temp, buffer_ret, buffer_size_ret));
177 } /* }}} int buffer_add_value */
178
179 /* Remove trailing newline (NL) and carriage return (CR) characters. Similar to
180  * the Perl function `chomp'. Returns the number of characters that have been
181  * removed. */
182 static int chomp (char *str) /* {{{ */
183 {
184   size_t len;
185   int removed;
186
187   if (str == NULL)
188     return (-1);
189
190   len = strlen (str);
191   removed = 0;
192   while ((len > 0) && ((str[len - 1] == '\n') || (str[len - 1] == '\r')))
193   {
194     str[len - 1] = 0;
195     len--;
196     removed++;
197   }
198
199   return (removed);
200 } /* }}} int chomp */
201
202 static void response_free (rrdc_response_t *res) /* {{{ */
203 {
204   if (res == NULL)
205     return;
206
207   if (res->lines != NULL)
208   {
209     size_t i;
210
211     for (i = 0; i < res->lines_num; i++)
212       if (res->lines[i] != NULL)
213         free (res->lines[i]);
214     free (res->lines);
215   }
216
217   free (res);
218 } /* }}} void response_free */
219
220 static int response_read (rrdc_response_t **ret_response) /* {{{ */
221 {
222   rrdc_response_t *ret;
223
224   char buffer[4096];
225   char *buffer_ptr;
226
227   size_t i;
228
229   if (sh == NULL)
230     return (-1);
231
232   ret = (rrdc_response_t *) malloc (sizeof (rrdc_response_t));
233   if (ret == NULL)
234     return (-2);
235   memset (ret, 0, sizeof (*ret));
236   ret->lines = NULL;
237   ret->lines_num = 0;
238
239   buffer_ptr = fgets (buffer, sizeof (buffer), sh);
240   if (buffer_ptr == NULL)
241     return (-3);
242   chomp (buffer);
243
244   ret->status = strtol (buffer, &ret->message, 0);
245   if (buffer == ret->message)
246   {
247     response_free (ret);
248     return (-4);
249   }
250   /* Skip leading whitespace of the status message */
251   ret->message += strspn (ret->message, " \t");
252
253   if (ret->status <= 0)
254   {
255     if (ret->status < 0)
256       rrd_set_error("rrdcached: %s", ret->message);
257     *ret_response = ret;
258     return (0);
259   }
260
261   ret->lines = (char **) malloc (sizeof (char *) * ret->status);
262   if (ret->lines == NULL)
263   {
264     response_free (ret);
265     return (-5);
266   }
267   memset (ret->lines, 0, sizeof (char *) * ret->status);
268   ret->lines_num = (size_t) ret->status;
269
270   for (i = 0; i < ret->lines_num; i++)
271   {
272     buffer_ptr = fgets (buffer, sizeof (buffer), sh);
273     if (buffer_ptr == NULL)
274     {
275       response_free (ret);
276       return (-6);
277     }
278     chomp (buffer);
279
280     ret->lines[i] = strdup (buffer);
281     if (ret->lines[i] == NULL)
282     {
283       response_free (ret);
284       return (-7);
285     }
286   }
287
288   *ret_response = ret;
289   return (0);
290 } /* }}} rrdc_response_t *response_read */
291
292 static int request (const char *buffer, size_t buffer_size, /* {{{ */
293     rrdc_response_t **ret_response)
294 {
295   int status;
296   rrdc_response_t *res;
297
298   if (sh == NULL)
299     return (ENOTCONN);
300
301   status = (int) fwrite (buffer, buffer_size, /* nmemb = */ 1, sh);
302   if (status != 1)
303   {
304     close_connection ();
305     rrd_set_error("request: socket error (%d) while talking to rrdcached",
306                   status);
307     return (-1);
308   }
309   fflush (sh);
310
311   res = NULL;
312   status = response_read (&res);
313
314   if (status != 0)
315   {
316     if (status < 0)
317       rrd_set_error("request: internal error while talking to rrdcached");
318     return (status);
319   }
320
321   *ret_response = res;
322   return (0);
323 } /* }}} int request */
324
325 /* determine whether we are connected to the specified daemon_addr if
326  * NULL, return whether we are connected at all
327  */
328 int rrdc_is_connected(const char *daemon_addr) /* {{{ */
329 {
330   if (sd < 0)
331     return 0;
332   else if (daemon_addr == NULL)
333   {
334     /* here we have to handle the case i.e.
335      *   UPDATE --daemon ...; UPDATEV (no --daemon) ...
336      * In other words: we have a cached connection,
337      * but it is not specified in the current command.
338      * Daemon is only implied in this case if set in ENV
339      */
340     if (getenv(ENV_RRDCACHED_ADDRESS) != NULL)
341       return 1;
342     else
343       return 0;
344   }
345   else if (strcmp(daemon_addr, sd_path) == 0)
346     return 1;
347   else
348     return 0;
349
350 } /* }}} int rrdc_is_connected */
351
352 static int rrdc_connect_unix (const char *path) /* {{{ */
353 {
354   struct sockaddr_un sa;
355   int status;
356
357   assert (path != NULL);
358   assert (sd == -1);
359
360   sd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
361   if (sd < 0)
362   {
363     status = errno;
364     return (status);
365   }
366
367   memset (&sa, 0, sizeof (sa));
368   sa.sun_family = AF_UNIX;
369   strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
370
371   status = connect (sd, (struct sockaddr *) &sa, sizeof (sa));
372   if (status != 0)
373   {
374     status = errno;
375     close_connection ();
376     return (status);
377   }
378
379   sh = fdopen (sd, "r+");
380   if (sh == NULL)
381   {
382     status = errno;
383     close_connection ();
384     return (status);
385   }
386
387   return (0);
388 } /* }}} int rrdc_connect_unix */
389
390 static int rrdc_connect_network (const char *addr_orig) /* {{{ */
391 {
392   struct addrinfo ai_hints;
393   struct addrinfo *ai_res;
394   struct addrinfo *ai_ptr;
395   char addr_copy[NI_MAXHOST];
396   char *addr;
397   char *port;
398
399   assert (addr_orig != NULL);
400   assert (sd == -1);
401
402   strncpy(addr_copy, addr_orig, sizeof(addr_copy));
403   addr_copy[sizeof(addr_copy) - 1] = '\0';
404   addr = addr_copy;
405
406   int status;
407   memset (&ai_hints, 0, sizeof (ai_hints));
408   ai_hints.ai_flags = 0;
409 #ifdef AI_ADDRCONFIG
410   ai_hints.ai_flags |= AI_ADDRCONFIG;
411 #endif
412   ai_hints.ai_family = AF_UNSPEC;
413   ai_hints.ai_socktype = SOCK_STREAM;
414
415   port = NULL;
416   if (*addr == '[') /* IPv6+port format */
417   {
418     /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
419     addr++;
420
421     port = strchr (addr, ']');
422     if (port == NULL)
423     {
424       rrd_set_error("malformed address: %s", addr_orig);
425       return (-1);
426     }
427     *port = 0;
428     port++;
429
430     if (*port == ':')
431       port++;
432     else if (*port == 0)
433       port = NULL;
434     else
435     {
436       rrd_set_error("garbage after address: %s", port);
437       return (-1);
438     }
439   } /* if (*addr = ']') */
440   else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
441   {
442     port = rindex(addr, ':');
443     if (port != NULL)
444     {
445       *port = 0;
446       port++;
447     }
448   }
449
450   ai_res = NULL;
451   status = getaddrinfo (addr,
452                         port == NULL ? RRDCACHED_DEFAULT_PORT : port,
453                         &ai_hints, &ai_res);
454   if (status != 0)
455     return (status);
456
457   for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
458   {
459     sd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
460     if (sd < 0)
461     {
462       status = errno;
463       sd = -1;
464       continue;
465     }
466
467     status = connect (sd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
468     if (status != 0)
469     {
470       status = errno;
471       close_connection();
472       continue;
473     }
474
475     sh = fdopen (sd, "r+");
476     if (sh == NULL)
477     {
478       status = errno;
479       close_connection ();
480       continue;
481     }
482
483     assert (status == 0);
484     break;
485   } /* for (ai_ptr) */
486
487   return (status);
488 } /* }}} int rrdc_connect_network */
489
490 int rrdc_connect (const char *addr) /* {{{ */
491 {
492   int status = 0;
493
494   if (addr == NULL)
495     addr = getenv (ENV_RRDCACHED_ADDRESS);
496
497   if (addr == NULL)
498     return 0;
499
500   pthread_mutex_lock(&lock);
501
502   if (sd >= 0 && sd_path != NULL && strcmp(addr, sd_path) == 0)
503   {
504     /* connection to the same daemon; use cached connection */
505     pthread_mutex_unlock (&lock);
506     return (0);
507   }
508   else
509   {
510     close_connection();
511   }
512
513   if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
514     status = rrdc_connect_unix (addr + strlen ("unix:"));
515   else if (addr[0] == '/')
516     status = rrdc_connect_unix (addr);
517   else
518     status = rrdc_connect_network(addr);
519
520   if (status == 0 && sd >= 0)
521     sd_path = strdup(addr);
522   else
523     rrd_set_error("Unable to connect to rrdcached: %s",
524                   (status < 0)
525                   ? "Internal error"
526                   : rrd_strerror (status));
527
528   pthread_mutex_unlock (&lock);
529   return (status);
530 } /* }}} int rrdc_connect */
531
532 int rrdc_disconnect (void) /* {{{ */
533 {
534   pthread_mutex_lock (&lock);
535
536   close_connection();
537
538   pthread_mutex_unlock (&lock);
539
540   return (0);
541 } /* }}} int rrdc_disconnect */
542
543 int rrdc_update (const char *filename, int values_num, /* {{{ */
544                 const char * const *values)
545 {
546   char buffer[4096];
547   char *buffer_ptr;
548   size_t buffer_free;
549   size_t buffer_size;
550   rrdc_response_t *res;
551   int status;
552   int i;
553   char file_path[PATH_MAX];
554
555   memset (buffer, 0, sizeof (buffer));
556   buffer_ptr = &buffer[0];
557   buffer_free = sizeof (buffer);
558
559   status = buffer_add_string ("update", &buffer_ptr, &buffer_free);
560   if (status != 0)
561     return (ENOBUFS);
562
563   pthread_mutex_lock (&lock);
564   filename = get_path (filename, file_path);
565   if (filename == NULL)
566   {
567     pthread_mutex_unlock (&lock);
568     return (-1);
569   }
570
571   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
572   if (status != 0)
573   {
574     pthread_mutex_unlock (&lock);
575     return (ENOBUFS);
576   }
577
578   for (i = 0; i < values_num; i++)
579   {
580     status = buffer_add_value (values[i], &buffer_ptr, &buffer_free);
581     if (status != 0)
582     {
583       pthread_mutex_unlock (&lock);
584       return (ENOBUFS);
585     }
586   }
587
588   assert (buffer_free < sizeof (buffer));
589   buffer_size = sizeof (buffer) - buffer_free;
590   assert (buffer[buffer_size - 1] == ' ');
591   buffer[buffer_size - 1] = '\n';
592
593   res = NULL;
594   status = request (buffer, buffer_size, &res);
595   pthread_mutex_unlock (&lock);
596
597   if (status != 0)
598     return (status);
599
600   status = res->status;
601   response_free (res);
602
603   return (status);
604 } /* }}} int rrdc_update */
605
606 int rrdc_flush (const char *filename) /* {{{ */
607 {
608   char buffer[4096];
609   char *buffer_ptr;
610   size_t buffer_free;
611   size_t buffer_size;
612   rrdc_response_t *res;
613   int status;
614   char file_path[PATH_MAX];
615
616   if (filename == NULL)
617     return (-1);
618
619   memset (buffer, 0, sizeof (buffer));
620   buffer_ptr = &buffer[0];
621   buffer_free = sizeof (buffer);
622
623   status = buffer_add_string ("flush", &buffer_ptr, &buffer_free);
624   if (status != 0)
625     return (ENOBUFS);
626
627   pthread_mutex_lock (&lock);
628   filename = get_path (filename, file_path);
629   if (filename == NULL)
630   {
631     pthread_mutex_unlock (&lock);
632     return (-1);
633   }
634
635   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
636   if (status != 0)
637   {
638     pthread_mutex_unlock (&lock);
639     return (ENOBUFS);
640   }
641
642   assert (buffer_free < sizeof (buffer));
643   buffer_size = sizeof (buffer) - buffer_free;
644   assert (buffer[buffer_size - 1] == ' ');
645   buffer[buffer_size - 1] = '\n';
646
647   res = NULL;
648   status = request (buffer, buffer_size, &res);
649   pthread_mutex_unlock (&lock);
650
651   if (status != 0)
652     return (status);
653
654   status = res->status;
655   response_free (res);
656
657   return (status);
658 } /* }}} int rrdc_flush */
659
660
661 /* convenience function; if there is a daemon specified, or if we can
662  * detect one from the environment, then flush the file.  Otherwise, no-op
663  */
664 int rrdc_flush_if_daemon (const char *opt_daemon, const char *filename) /* {{{ */
665 {
666   int status = 0;
667
668   rrdc_connect(opt_daemon);
669
670   if (rrdc_is_connected(opt_daemon))
671   {
672     rrd_clear_error();
673     status = rrdc_flush (filename);
674
675     if (status != 0 && !rrd_test_error())
676     {
677       if (status > 0)
678       {
679         rrd_set_error("rrdc_flush (%s) failed: %s",
680                       filename, rrd_strerror(status));
681       }
682       else if (status < 0)
683       {
684         rrd_set_error("rrdc_flush (%s) failed with status %i.",
685                       filename, status);
686       }
687     }
688   } /* if (rrdc_is_connected(..)) */
689
690   return status;
691 } /* }}} int rrdc_flush_if_daemon */
692
693
694 int rrdc_stats_get (rrdc_stats_t **ret_stats) /* {{{ */
695 {
696   rrdc_stats_t *head;
697   rrdc_stats_t *tail;
698
699   rrdc_response_t *res;
700
701   int status;
702   size_t i;
703
704   /* Protocol example: {{{
705    * ->  STATS
706    * <-  5 Statistics follow
707    * <-  QueueLength: 0
708    * <-  UpdatesWritten: 0
709    * <-  DataSetsWritten: 0
710    * <-  TreeNodesNumber: 0
711    * <-  TreeDepth: 0
712    * }}} */
713
714   res = NULL;
715   pthread_mutex_lock (&lock);
716   status = request ("STATS\n", strlen ("STATS\n"), &res);
717   pthread_mutex_unlock (&lock);
718
719   if (status != 0)
720     return (status);
721
722   if (res->status <= 0)
723   {
724     response_free (res);
725     return (EIO);
726   }
727
728   head = NULL;
729   tail = NULL;
730   for (i = 0; i < res->lines_num; i++)
731   {
732     char *key;
733     char *value;
734     char *endptr;
735     rrdc_stats_t *s;
736
737     key = res->lines[i];
738     value = strchr (key, ':');
739     if (value == NULL)
740       continue;
741     *value = 0;
742     value++;
743
744     while ((value[0] == ' ') || (value[0] == '\t'))
745       value++;
746
747     s = (rrdc_stats_t *) malloc (sizeof (rrdc_stats_t));
748     if (s == NULL)
749       continue;
750     memset (s, 0, sizeof (*s));
751
752     s->name = strdup (key);
753
754     endptr = NULL;
755     if ((strcmp ("QueueLength", key) == 0)
756         || (strcmp ("TreeDepth", key) == 0)
757         || (strcmp ("TreeNodesNumber", key) == 0))
758     {
759       s->type = RRDC_STATS_TYPE_GAUGE;
760       s->value.gauge = strtod (value, &endptr);
761     }
762     else if ((strcmp ("DataSetsWritten", key) == 0)
763         || (strcmp ("FlushesReceived", key) == 0)
764         || (strcmp ("JournalBytes", key) == 0)
765         || (strcmp ("JournalRotate", key) == 0)
766         || (strcmp ("UpdatesReceived", key) == 0)
767         || (strcmp ("UpdatesWritten", key) == 0))
768     {
769       s->type = RRDC_STATS_TYPE_COUNTER;
770       s->value.counter = (uint64_t) strtoll (value, &endptr, /* base = */ 0);
771     }
772     else
773     {
774       free (s);
775       continue;
776     }
777
778     /* Conversion failed */
779     if (endptr == value)
780     {
781       free (s);
782       continue;
783     }
784
785     if (head == NULL)
786     {
787       head = s;
788       tail = s;
789       s->next = NULL;
790     }
791     else
792     {
793       tail->next = s;
794       tail = s;
795     }
796   } /* for (i = 0; i < res->lines_num; i++) */
797
798   response_free (res);
799
800   if (head == NULL)
801     return (EPROTO);
802
803   *ret_stats = head;
804   return (0);
805 } /* }}} int rrdc_stats_get */
806
807 void rrdc_stats_free (rrdc_stats_t *ret_stats) /* {{{ */
808 {
809   rrdc_stats_t *this;
810
811   this = ret_stats;
812   while (this != NULL)
813   {
814     rrdc_stats_t *next;
815
816     next = this->next;
817
818     if (this->name != NULL)
819     {
820       free ((char *)this->name);
821       this->name = NULL;
822     }
823     free (this);
824
825     this = next;
826   } /* while (this != NULL) */
827 } /* }}} void rrdc_stats_free */
828
829 /*
830  * vim: set sw=2 sts=2 ts=8 et fdm=marker :
831  */