fix memory handling when argument separation in pipe mode fails. fix for #230
[rrdtool.git] / src / rrd_tool.c
1 /*****************************************************************************
2  * RRDtool 1.3.2  Copyright by Tobi Oetiker, 1997-2008
3  *****************************************************************************
4  * rrd_tool.c  Startup wrapper
5  *****************************************************************************/
6
7 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__) && !defined(HAVE_CONFIG_H)
8 #include "../win32/config.h"
9 #include <stdlib.h>
10 #include <sys/stat.h>
11 #else
12 #ifdef HAVE_CONFIG_H
13 #include "../rrd_config.h"
14 #endif
15 #endif
16
17 #include "rrd_tool.h"
18 #include "rrd_xport.h"
19 #include "rrd_i18n.h"
20
21 #ifdef HAVE_LOCALE_H
22 #include <locale.h>
23 #endif
24
25 void      PrintUsage(
26     char *cmd);
27 int       CountArgs(
28     char *aLine);
29 int       CreateArgs(
30     char *,
31     char *,
32     char **);
33 int       HandleInputLine(
34     int,
35     char **,
36     FILE *);
37 int       RemoteMode = 0;
38 int       ChangeRoot = 0;
39
40 #define TRUE            1
41 #define FALSE           0
42 #define MAX_LENGTH      10000
43
44
45 void PrintUsage(
46     char *cmd)
47 {
48
49     const char *help_main =
50         N_("RRDtool %s"
51            "  Copyright 1997-2008 by Tobias Oetiker <tobi@oetiker.ch>\n"
52            "               Compiled %s %s\n\n"
53            "Usage: rrdtool [options] command command_options\n\n");
54
55     const char *help_list =
56         N_
57         ("Valid commands: create, update, updatev, graph, graphv,  dump, restore,\n"
58          "\t\tlast, lastupdate, first, info, fetch, tune,\n"
59          "\t\tresize, xport, flushcached\n\n");
60
61     const char *help_listremote =
62         N_("Valid remote commands: quit, ls, cd, mkdir, pwd\n\n");
63
64
65     const char *help_create =
66         N_("* create - create a new RRD\n\n"
67            "\trrdtool create filename [--start|-b start time]\n"
68            "\t\t[--step|-s step]\n"
69            "\t\t[DS:ds-name:DST:dst arguments]\n"
70            "\t\t[RRA:CF:cf arguments]\n\n");
71
72     const char *help_dump =
73         N_("* dump - dump an RRD to XML\n\n"
74            "\trrdtool dump filename.rrd >filename.xml\n\n");
75
76     const char *help_info =
77         N_("* info - returns the configuration and status of the RRD\n\n"
78            "\trrdtool info filename.rrd\n\n");
79
80     const char *help_restore =
81         N_("* restore - restore an RRD file from its XML form\n\n"
82            "\trrdtool restore [--range-check|-r] [--force-overwrite|-f] filename.xml filename.rrd\n\n");
83
84     const char *help_last =
85         N_("* last - show last update time for RRD\n\n"
86            "\trrdtool last filename.rrd\n\n");
87
88     const char *help_lastupdate =
89         N_("* lastupdate - returns the most recent datum stored for\n"
90            "  each DS in an RRD\n\n" "\trrdtool lastupdate filename.rrd\n\n");
91
92     const char *help_first =
93         N_("* first - show first update time for RRA within an RRD\n\n"
94            "\trrdtool first filename.rrd [--rraindex number]\n\n");
95
96     const char *help_update =
97         N_("* update - update an RRD\n\n"
98            "\trrdtool update filename\n"
99            "\t\t[--template|-t ds-name:ds-name:...]\n"
100            "\t\t[--daemon <address>]\n"
101            "\t\ttime|N:value[:value...]\n\n"
102            "\t\tat-time@value[:value...]\n\n"
103            "\t\t[ time:value[:value...] ..]\n\n");
104
105     const char *help_updatev =
106         N_("* updatev - a verbose version of update\n"
107            "\treturns information about values, RRAs, and datasources updated\n\n"
108            "\trrdtool updatev filename\n"
109            "\t\t[--template|-t ds-name:ds-name:...]\n"
110            "\t\ttime|N:value[:value...]\n\n"
111            "\t\tat-time@value[:value...]\n\n"
112            "\t\t[ time:value[:value...] ..]\n\n");
113
114     const char *help_fetch =
115         N_("* fetch - fetch data out of an RRD\n\n"
116            "\trrdtool fetch filename.rrd CF\n"
117            "\t\t[-r|--resolution resolution]\n"
118            "\t\t[-s|--start start] [-e|--end end]\n"
119            "\t\t[--daemon <address>]\n\n");
120
121     const char *help_flushcached =
122         N_("* flushcached - flush cached data out to an RRD file\n\n"
123            "\trrdtool flushcached filename.rrd\n"
124            "\t\t[--daemon <address>]\n\n");
125
126 /* break up very large strings (help_graph, help_tune) for ISO C89 compliance*/
127
128     const char *help_graph0 =
129         N_("* graph - generate a graph from one or several RRD\n\n"
130            "\trrdtool graph filename [-s|--start seconds] [-e|--end seconds]\n");
131     const char *help_graphv0 =
132         N_("* graphv - generate a graph from one or several RRD\n"
133            "           with meta data printed before the graph\n\n"
134            "\trrdtool graphv filename [-s|--start seconds] [-e|--end seconds]\n");
135     const char *help_graph1 =
136         N_("\t\t[-x|--x-grid x-axis grid and label]\n"
137            "\t\t[-Y|--alt-y-grid] [--full-size-mode]\n"
138            "\t\t[-y|--y-grid y-axis grid and label]\n"
139            "\t\t[-v|--vertical-label string] [-w|--width pixels]\n"
140            "\t\t[--right-axis scale:shift] [--right-axis-label label]\n"
141            "\t\t[--right-axis-format format]\n"
142            "\t\t[-h|--height pixels] [-o|--logarithmic]\n"
143            "\t\t[-u|--upper-limit value] [-z|--lazy]\n"
144            "\t\t[-l|--lower-limit value] [-r|--rigid]\n"
145            "\t\t[-g|--no-legend] [--daemon <address>]\n"
146            "\t\t[-F|--force-rules-legend]\n" "\t\t[-j|--only-graph]\n");
147     const char *help_graph2 =
148         N_("\t\t[-n|--font FONTTAG:size:font]\n"
149            "\t\t[-m|--zoom factor]\n"
150            "\t\t[-A|--alt-autoscale]\n"
151            "\t\t[-M|--alt-autoscale-max]\n"
152            "\t\t[-G|--graph-render-mode {normal,mono}]\n"
153            "\t\t[-R|--font-render-mode {normal,light,mono}]\n"
154            "\t\t[-B|--font-smoothing-threshold size]\n"
155            "\t\t[-T|--tabwidth width]\n"
156            "\t\t[-E|--slope-mode]\n"
157            "\t\t[-N|--no-gridfit]\n"
158            "\t\t[-X|--units-exponent value]\n"
159            "\t\t[-L|--units-length value]\n"
160            "\t\t[-S|--step seconds]\n"
161            "\t\t[-f|--imginfo printfstr]\n"
162            "\t\t[-a|--imgformat PNG]\n"
163            "\t\t[-c|--color COLORTAG#rrggbb[aa]]\n"
164            "\t\t[--border width\n"
165            "\t\t[-t|--title string]\n"
166            "\t\t[-W|--watermark string]\n"
167            "\t\t[DEF:vname=rrd:ds-name:CF]\n");
168     const char *help_graph3 =
169         N_("\t\t[CDEF:vname=rpn-expression]\n"
170            "\t\t[VDEF:vdefname=rpn-expression]\n"
171            "\t\t[PRINT:vdefname:format]\n"
172            "\t\t[GPRINT:vdefname:format]\n" "\t\t[COMMENT:text]\n"
173            "\t\t[SHIFT:vname:offset]\n"
174            "\t\t[TICK:vname#rrggbb[aa][:[fraction][:legend]]]\n"
175            "\t\t[HRULE:value#rrggbb[aa][:legend]]\n"
176            "\t\t[VRULE:value#rrggbb[aa][:legend]]\n"
177            "\t\t[LINE[width]:vname[#rrggbb[aa][:[legend][:STACK]]]]\n"
178            "\t\t[AREA:vname[#rrggbb[aa][:[legend][:STACK]]]]\n"
179            "\t\t[PRINT:vname:CF:format] (deprecated)\n"
180            "\t\t[GPRINT:vname:CF:format] (deprecated)\n"
181            "\t\t[STACK:vname[#rrggbb[aa][:legend]]] (deprecated)\n\n");
182     const char *help_tune1 =
183         N_(" * tune -  Modify some basic properties of an RRD\n\n"
184            "\trrdtool tune filename\n"
185            "\t\t[--heartbeat|-h ds-name:heartbeat]\n"
186            "\t\t[--data-source-type|-d ds-name:DST]\n"
187            "\t\t[--data-source-rename|-r old-name:new-name]\n"
188            "\t\t[--minimum|-i ds-name:min] [--maximum|-a ds-name:max]\n"
189            "\t\t[--deltapos scale-value] [--deltaneg scale-value]\n"
190            "\t\t[--failure-threshold integer]\n"
191            "\t\t[--window-length integer]\n"
192            "\t\t[--alpha adaptation-parameter]\n");
193     const char *help_tune2 =
194         N_(" * tune -  Modify some basic properties of an RRD\n\n"
195            "\t\t[--beta adaptation-parameter]\n"
196            "\t\t[--gamma adaptation-parameter]\n"
197            "\t\t[--gamma-deviation adaptation-parameter]\n"
198            "\t\t[--aberrant-reset ds-name]\n\n");
199     const char *help_resize =
200         N_
201         (" * resize - alter the length of one of the RRAs in an RRD\n\n"
202          "\trrdtool resize filename rranum GROW|SHRINK rows\n\n");
203     const char *help_xport =
204         N_("* xport - generate XML dump from one or several RRD\n\n"
205            "\trrdtool xport [-s|--start seconds] [-e|--end seconds]\n"
206            "\t\t[-m|--maxrows rows]\n" "\t\t[--step seconds]\n"
207            "\t\t[--enumds]\n" "\t\t[DEF:vname=rrd:ds-name:CF]\n"
208            "\t\t[CDEF:vname=rpn-expression]\n"
209            "\t\t[XPORT:vname:legend]\n\n");
210     const char *help_quit =
211         N_(" * quit - closing a session in remote mode\n\n"
212            "\trrdtool quit\n\n");
213     const char *help_ls =
214         N_(" * ls - lists all *.rrd files in current directory\n\n"
215            "\trrdtool ls\n\n");
216     const char *help_cd =
217         N_(" * cd - changes the current directory\n\n"
218            "\trrdtool cd new directory\n\n");
219     const char *help_mkdir =
220         N_(" * mkdir - creates a new directory\n\n"
221            "\trrdtool mkdir newdirectoryname\n\n");
222     const char *help_pwd =
223         N_(" * pwd - returns the current working directory\n\n"
224            "\trrdtool pwd\n\n");
225     const char *help_lic =
226         N_("RRDtool is distributed under the Terms of the GNU General\n"
227            "Public License Version 2. (www.gnu.org/copyleft/gpl.html)\n\n"
228            "For more information read the RRD manpages\n\n");
229     enum { C_NONE, C_CREATE, C_DUMP, C_INFO, C_RESTORE, C_LAST,
230         C_LASTUPDATE, C_FIRST, C_UPDATE, C_FETCH, C_GRAPH, C_GRAPHV,
231         C_TUNE,
232         C_RESIZE, C_XPORT, C_QUIT, C_LS, C_CD, C_MKDIR, C_PWD,
233         C_UPDATEV, C_FLUSHCACHED
234     };
235     int       help_cmd = C_NONE;
236
237     if (cmd) {
238         if (!strcmp(cmd, "create"))
239             help_cmd = C_CREATE;
240         else if (!strcmp(cmd, "dump"))
241             help_cmd = C_DUMP;
242         else if (!strcmp(cmd, "info"))
243             help_cmd = C_INFO;
244         else if (!strcmp(cmd, "restore"))
245             help_cmd = C_RESTORE;
246         else if (!strcmp(cmd, "last"))
247             help_cmd = C_LAST;
248         else if (!strcmp(cmd, "lastupdate"))
249             help_cmd = C_LASTUPDATE;
250         else if (!strcmp(cmd, "first"))
251             help_cmd = C_FIRST;
252         else if (!strcmp(cmd, "update"))
253             help_cmd = C_UPDATE;
254         else if (!strcmp(cmd, "updatev"))
255             help_cmd = C_UPDATEV;
256         else if (!strcmp(cmd, "fetch"))
257             help_cmd = C_FETCH;
258         else if (!strcmp(cmd, "flushcached"))
259             help_cmd = C_FLUSHCACHED;
260         else if (!strcmp(cmd, "graph"))
261             help_cmd = C_GRAPH;
262         else if (!strcmp(cmd, "graphv"))
263             help_cmd = C_GRAPHV;
264         else if (!strcmp(cmd, "tune"))
265             help_cmd = C_TUNE;
266         else if (!strcmp(cmd, "resize"))
267             help_cmd = C_RESIZE;
268         else if (!strcmp(cmd, "xport"))
269             help_cmd = C_XPORT;
270         else if (!strcmp(cmd, "quit"))
271             help_cmd = C_QUIT;
272         else if (!strcmp(cmd, "ls"))
273             help_cmd = C_LS;
274         else if (!strcmp(cmd, "cd"))
275             help_cmd = C_CD;
276         else if (!strcmp(cmd, "mkdir"))
277             help_cmd = C_MKDIR;
278         else if (!strcmp(cmd, "pwd"))
279             help_cmd = C_PWD;
280     }
281     fprintf(stdout, _(help_main), PACKAGE_VERSION, __DATE__, __TIME__);
282     fflush(stdout);
283     switch (help_cmd) {
284     case C_NONE:
285         fputs(_(help_list), stdout);
286         if (RemoteMode) {
287             fputs(_(help_listremote), stdout);
288         }
289         break;
290     case C_CREATE:
291         fputs(_(help_create), stdout);
292         break;
293     case C_DUMP:
294         fputs(_(help_dump), stdout);
295         break;
296     case C_INFO:
297         fputs(_(help_info), stdout);
298         break;
299     case C_RESTORE:
300         fputs(_(help_restore), stdout);
301         break;
302     case C_LAST:
303         fputs(_(help_last), stdout);
304         break;
305     case C_LASTUPDATE:
306         fputs(_(help_lastupdate), stdout);
307         break;
308     case C_FIRST:
309         fputs(_(help_first), stdout);
310         break;
311     case C_UPDATE:
312         fputs(_(help_update), stdout);
313         break;
314     case C_UPDATEV:
315         fputs(_(help_updatev), stdout);
316         break;
317     case C_FETCH:
318         fputs(_(help_fetch), stdout);
319         break;
320     case C_FLUSHCACHED:
321         fputs(_(help_flushcached), stdout);
322         break;
323     case C_GRAPH:
324         fputs(_(help_graph0), stdout);
325         fputs(_(help_graph1), stdout);
326         fputs(_(help_graph2), stdout);
327         fputs(_(help_graph3), stdout);
328         break;
329     case C_GRAPHV:
330         fputs(_(help_graphv0), stdout);
331         fputs(_(help_graph1), stdout);
332         fputs(_(help_graph2), stdout);
333         fputs(_(help_graph3), stdout);
334         break;
335     case C_TUNE:
336         fputs(_(help_tune1), stdout);
337         fputs(_(help_tune2), stdout);
338         break;
339     case C_RESIZE:
340         fputs(_(help_resize), stdout);
341         break;
342     case C_XPORT:
343         fputs(_(help_xport), stdout);
344         break;
345     case C_QUIT:
346         fputs(_(help_quit), stdout);
347         break;
348     case C_LS:
349         fputs(_(help_ls), stdout);
350         break;
351     case C_CD:
352         fputs(_(help_cd), stdout);
353         break;
354     case C_MKDIR:
355         fputs(_(help_mkdir), stdout);
356         break;
357     case C_PWD:
358         fputs(_(help_pwd), stdout);
359         break;
360     }
361     fputs(_(help_lic), stdout);
362 }
363
364 static char *fgetslong(
365     char **aLinePtr,
366     FILE * stream)
367 {
368     char     *linebuf;
369     size_t    bufsize = MAX_LENGTH;
370     int       eolpos = 0;
371
372     if (feof(stream))
373         return *aLinePtr = 0;
374     if (!(linebuf = malloc(bufsize))) {
375         perror("fgetslong: malloc");
376         exit(1);
377     }
378     linebuf[0] = '\0';
379     while (fgets(linebuf + eolpos, MAX_LENGTH, stream)) {
380         eolpos += strlen(linebuf + eolpos);
381         if (linebuf[eolpos - 1] == '\n')
382             return *aLinePtr = linebuf;
383         bufsize += MAX_LENGTH;
384         if (!(linebuf = realloc(linebuf, bufsize))) {
385             free(linebuf);
386             perror("fgetslong: realloc");
387             exit(1);
388         }
389     }
390     if (linebuf[0]){
391         return  *aLinePtr = linebuf;
392     }
393     free(linebuf);
394     return *aLinePtr = 0;
395 }
396
397 int main(
398     int argc,
399     char *argv[])
400 {
401     char    **myargv;
402     char     *aLine;
403     char     *firstdir = "";
404
405 #ifdef MUST_DISABLE_SIGFPE
406     signal(SIGFPE, SIG_IGN);
407 #endif
408 #ifdef MUST_DISABLE_FPMASK
409     fpsetmask(0);
410 #endif
411 #ifdef HAVE_LOCALE_H
412     /* initialize locale settings
413        according to localeconv(3) */       
414     setlocale(LC_ALL, "");
415 #endif
416
417 #if defined(HAVE_LIBINTL_H) && defined(BUILD_LIBINTL)
418     bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
419     textdomain(GETTEXT_PACKAGE);
420 #endif
421     if (argc == 1) {
422         PrintUsage("");
423         return 0;
424     }
425
426     if (((argc == 2) || (argc == 3)) && !strcmp("-", argv[1])) {
427 #if HAVE_GETRUSAGE
428         struct rusage myusage;
429         struct timeval starttime;
430         struct timeval currenttime;
431
432         gettimeofday(&starttime, NULL);
433 #endif
434         RemoteMode = 1;
435         if ((argc == 3) && strcmp("", argv[2])) {
436
437             if (
438 #ifdef HAVE_GETUID
439                    getuid()
440 #else
441                    1
442 #endif
443                    == 0) {
444
445 #ifdef HAVE_CHROOT
446                 if (chroot(argv[2]) != 0){
447                     fprintf(stderr, "ERROR: chroot %s: %s\n", argv[2],rrd_strerror(errno));
448                     exit(errno);
449                 }
450                 ChangeRoot = 1;
451                 firstdir = "/";
452 #else
453                 fprintf(stderr,
454                         "ERROR: change root is not supported by your OS "
455                         "or at least by this copy of rrdtool\n");
456                 exit(1);
457 #endif
458             } else {
459                 firstdir = argv[2];
460             }
461         }
462         if (strcmp(firstdir, "")) {
463             if (chdir(firstdir) != 0){
464                 fprintf(stderr, "ERROR: chdir %s %s\n", firstdir,rrd_strerror(errno));
465                 exit(errno);
466             }
467         }
468
469         while (fgetslong(&aLine, stdin)) {
470             char *aLineOrig = aLine;
471             if ((argc = CountArgs(aLine)) == 0) {
472                 free(aLine);
473                 printf("ERROR: not enough arguments\n");
474                 continue;                
475             }
476             if ((myargv = (char **) malloc((argc + 1) *
477                                            sizeof(char *))) == NULL) {
478                 perror("malloc");
479                 exit(1);
480             }
481             if ((argc = CreateArgs(argv[0], aLine, myargv)) < 0) {
482                 printf("ERROR: creating arguments\n");
483             } else {
484                 if ( HandleInputLine(argc, myargv, stdout) == 0 ){
485 #if HAVE_GETRUSAGE
486                     getrusage(RUSAGE_SELF, &myusage);
487                     gettimeofday(&currenttime, NULL);
488                     printf("OK u:%1.2f s:%1.2f r:%1.2f\n",
489                            (double) myusage.ru_utime.tv_sec +
490                            (double) myusage.ru_utime.tv_usec / 1000000.0,
491                            (double) myusage.ru_stime.tv_sec +
492                            (double) myusage.ru_stime.tv_usec / 1000000.0,
493                            (double) (currenttime.tv_sec - starttime.tv_sec)
494                            + (double) (currenttime.tv_usec -
495                                        starttime.tv_usec)
496                            / 1000000.0);
497 #else
498                     printf("OK\n");
499 #endif
500                 }
501             }
502             fflush(stdout); /* this is important for pipes to work */
503             free(myargv);
504             free(aLineOrig);
505         }
506     } else if (argc == 2) {
507         PrintUsage(argv[1]);
508         exit(0);
509     } else if (argc == 3 && !strcmp(argv[1], "help")) {
510         PrintUsage(argv[2]);
511         exit(0);
512     } else {
513         exit(HandleInputLine(argc, argv, stderr));
514     }
515     return 0;
516 }
517
518 /* HandleInputLine is NOT thread safe - due to readdir issues,
519    resolving them portably is not really simple. */
520 int HandleInputLine(
521     int argc,
522     char **argv,
523     FILE * out)
524 {
525 #if defined(HAVE_OPENDIR) && defined (HAVE_READDIR)
526     DIR      *curdir;   /* to read current dir with ls */
527     struct dirent *dent;
528 #endif
529 #if defined(HAVE_SYS_STAT_H)
530     struct stat st;
531 #endif
532
533     /* Reset errno to 0 before we start.
534      */
535     if (RemoteMode) {
536         if (argc > 1 && strcmp("quit", argv[1]) == 0) {
537             if (argc > 2) {
538                 printf("ERROR: invalid parameter count for quit\n");
539                 return (1);
540             }
541             exit(0);
542         }
543 #if defined(HAVE_OPENDIR) && defined(HAVE_READDIR) && defined(HAVE_CHDIR)
544         if (argc > 1 && strcmp("cd", argv[1]) == 0) {
545             if (argc > 3) {
546                 printf("ERROR: invalid parameter count for cd\n");
547                 return (1);
548             }
549 #if ! defined(HAVE_CHROOT) || ! defined(HAVE_GETUID)
550             if (getuid() == 0 && !ChangeRoot) {
551                 printf
552                     ("ERROR: chdir security problem - rrdtool is running as "
553                      "root but not chroot!\n");
554                 return (1);
555             }
556 #endif
557             if (chdir(argv[2]) != 0){
558                 printf("ERROR: chdir %s %s\n", argv[2], rrd_strerror(errno));
559                 return (1);
560             }
561             return (0);
562         }
563         if (argc > 1 && strcmp("pwd", argv[1]) == 0) {
564             char     *cwd;      /* To hold current working dir on call to pwd */
565             if (argc > 2) {
566                 printf("ERROR: invalid parameter count for pwd\n");
567                 return (1);
568             }
569             cwd = getcwd(NULL, MAXPATH);
570             if (cwd == NULL) {
571                 printf("ERROR: getcwd %s\n", rrd_strerror(errno));
572                 return (1);
573             }
574             printf("%s\n", cwd);
575             free(cwd);
576             return (0);
577         }
578         if (argc > 1 && strcmp("mkdir", argv[1]) == 0) {
579             if (argc > 3) {
580                 printf("ERROR: invalid parameter count for mkdir\n");
581                 return (1);
582             }
583 #if ! defined(HAVE_CHROOT) || ! defined(HAVE_GETUID)
584             if (getuid() == 0 && !ChangeRoot) {
585                 printf
586                     ("ERROR: mkdir security problem - rrdtool is running as "
587                      "root but not chroot!\n");
588                 return (1);
589             }
590 #endif
591             if(mkdir(argv[2], 0777)!=0){
592                 printf("ERROR: mkdir %s: %s\n", argv[2],rrd_strerror(errno));
593                 return (1);
594             }
595             return (0);
596         }
597         if (argc > 1 && strcmp("ls", argv[1]) == 0) {
598             if (argc > 2) {
599                 printf("ERROR: invalid parameter count for ls\n");
600                 return (1);
601             }
602             if ((curdir = opendir(".")) != NULL) {
603                 while ((dent = readdir(curdir)) != NULL) {
604                     if (!stat(dent->d_name, &st)) {
605                         if (S_ISDIR(st.st_mode)) {
606                             printf("d %s\n", dent->d_name);
607                         }
608                         if (strlen(dent->d_name) > 4 && S_ISREG(st.st_mode)) {
609                             if (!strcmp
610                                 (dent->d_name + NAMLEN(dent) - 4, ".rrd")
611                                 || !strcmp(dent->d_name + NAMLEN(dent) - 4,
612                                            ".RRD")) {
613                                 printf("- %s\n", dent->d_name);
614                             }
615                         }
616                     }
617                 }
618                 closedir(curdir);
619             } else {
620                 printf("ERROR: opendir .: %s\n", rrd_strerror(errno));
621                 return (errno);
622             }
623             return (0);
624         }
625 #endif                          /* opendir and readdir */
626
627     }
628     if (argc < 3
629         || strcmp("help", argv[1]) == 0
630         || strcmp("--help", argv[1]) == 0
631         || strcmp("-help", argv[1]) == 0
632         || strcmp("-?", argv[1]) == 0 || strcmp("-h", argv[1]) == 0) {
633         PrintUsage("");
634         return 0;
635     }
636
637     if (strcmp("create", argv[1]) == 0)
638         rrd_create(argc - 1, &argv[1]);
639     else if (strcmp("dump", argv[1]) == 0)
640         rrd_dump(argc - 1, &argv[1]);
641     else if (strcmp("info", argv[1]) == 0 || strcmp("updatev", argv[1]) == 0) {
642         rrd_info_t *data;
643
644         if (strcmp("info", argv[1]) == 0)
645
646             data = rrd_info(argc - 1, &argv[1]);
647         else
648             data = rrd_update_v(argc - 1, &argv[1]);
649         rrd_info_print(data);
650         rrd_info_free(data);
651     }
652
653     else if (strcmp("--version", argv[1]) == 0 ||
654              strcmp("version", argv[1]) == 0 ||
655              strcmp("v", argv[1]) == 0 ||
656              strcmp("-v", argv[1]) == 0 || strcmp("-version", argv[1]) == 0)
657         printf("RRDtool " PACKAGE_VERSION
658                "  Copyright by Tobi Oetiker, 1997-2008 (%f)\n",
659                rrd_version());
660     else if (strcmp("restore", argv[1]) == 0)
661         rrd_restore(argc - 1, &argv[1]);
662     else if (strcmp("resize", argv[1]) == 0)
663         rrd_resize(argc - 1, &argv[1]);
664     else if (strcmp("last", argv[1]) == 0)
665         printf("%ld\n", rrd_last(argc - 1, &argv[1]));
666     else if (strcmp("lastupdate", argv[1]) == 0) {
667         rrd_lastupdate(argc - 1, &argv[1]);
668     } else if (strcmp("first", argv[1]) == 0)
669         printf("%ld\n", rrd_first(argc - 1, &argv[1]));
670     else if (strcmp("update", argv[1]) == 0)
671         rrd_update(argc - 1, &argv[1]);
672     else if (strcmp("fetch", argv[1]) == 0) {
673         time_t    start, end, ti;
674         unsigned long step, ds_cnt, i, ii;
675         rrd_value_t *data, *datai;
676         char    **ds_namv;
677
678         if (rrd_fetch
679             (argc - 1, &argv[1], &start, &end, &step, &ds_cnt, &ds_namv,
680              &data) != -1) {
681             datai = data;
682             printf("           ");
683             for (i = 0; i < ds_cnt; i++)
684                 printf("%20s", ds_namv[i]);
685             printf("\n\n");
686             for (ti = start + step; ti <= end; ti += step) {
687                 printf("%10lu:", ti);
688                 for (ii = 0; ii < ds_cnt; ii++)
689                     printf(" %0.10e", *(datai++));
690                 printf("\n");
691             }
692             for (i = 0; i < ds_cnt; i++)
693                 free(ds_namv[i]);
694             free(ds_namv);
695             free(data);
696         }
697     } else if (strcmp("xport", argv[1]) == 0) {
698         int       xxsize;
699         unsigned long int j = 0;
700         time_t    start, end, ti;
701         unsigned long step, col_cnt, row_cnt;
702         rrd_value_t *data, *ptr;
703         char    **legend_v;
704         int       enumds = 0;
705         int       i;
706         size_t    vtag_s = strlen(COL_DATA_TAG) + 10;
707         char     *vtag = malloc(vtag_s);
708
709         for (i = 2; i < argc; i++) {
710             if (strcmp("--enumds", argv[i]) == 0)
711                 enumds = 1;
712         }
713
714         if (rrd_xport
715             (argc - 1, &argv[1], &xxsize, &start, &end, &step, &col_cnt,
716              &legend_v, &data) != -1) {
717             row_cnt = (end - start) / step;
718             ptr = data;
719             printf("<?xml version=\"1.0\" encoding=\"%s\"?>\n\n",
720                    XML_ENCODING);
721             printf("<%s>\n", ROOT_TAG);
722             printf("  <%s>\n", META_TAG);
723             printf("    <%s>%lu</%s>\n", META_START_TAG,
724                    (unsigned long) start + step, META_START_TAG);
725             printf("    <%s>%lu</%s>\n", META_STEP_TAG, step, META_STEP_TAG);
726             printf("    <%s>%lu</%s>\n", META_END_TAG, (unsigned long) end,
727                    META_END_TAG);
728             printf("    <%s>%lu</%s>\n", META_ROWS_TAG, row_cnt,
729                    META_ROWS_TAG);
730             printf("    <%s>%lu</%s>\n", META_COLS_TAG, col_cnt,
731                    META_COLS_TAG);
732             printf("    <%s>\n", LEGEND_TAG);
733             for (j = 0; j < col_cnt; j++) {
734                 char     *entry = NULL;
735
736                 entry = legend_v[j];
737                 printf("      <%s>%s</%s>\n", LEGEND_ENTRY_TAG, entry,
738                        LEGEND_ENTRY_TAG);
739                 free(entry);
740             }
741             free(legend_v);
742             printf("    </%s>\n", LEGEND_TAG);
743             printf("  </%s>\n", META_TAG);
744             printf("  <%s>\n", DATA_TAG);
745             for (ti = start + step; ti <= end; ti += step) {
746                 printf("    <%s>", DATA_ROW_TAG);
747                 printf("<%s>%lu</%s>", COL_TIME_TAG, ti, COL_TIME_TAG);
748                 for (j = 0; j < col_cnt; j++) {
749                     rrd_value_t newval = DNAN;
750
751                     if (enumds == 1)
752
753                         snprintf(vtag, vtag_s, "%s%lu", COL_DATA_TAG, j);
754                     else
755                         snprintf(vtag, vtag_s, "%s", COL_DATA_TAG);
756                     newval = *ptr;
757                     if (isnan(newval)) {
758                         printf("<%s>NaN</%s>", vtag, vtag);
759                     } else {
760                         printf("<%s>%0.10e</%s>", vtag, newval, vtag);
761                     };
762                     ptr++;
763                 }
764                 printf("</%s>\n", DATA_ROW_TAG);
765             }
766             free(data);
767             printf("  </%s>\n", DATA_TAG);
768             printf("</%s>\n", ROOT_TAG);
769         }
770         free(vtag);
771     } else if (strcmp("graph", argv[1]) == 0) {
772         char    **calcpr;
773
774 #ifdef notused /*XXX*/
775         const char *imgfile = argv[2];  /* rrd_graph changes argv pointer */
776 #endif
777         int       xsize, ysize;
778         double    ymin, ymax;
779         int       i;
780         int       tostdout = (strcmp(argv[2], "-") == 0);
781         int       imginfo = 0;
782
783         for (i = 2; i < argc; i++) {
784             if (strcmp(argv[i], "--imginfo") == 0
785                 || strcmp(argv[i], "-f") == 0) {
786                 imginfo = 1;
787                 break;
788             }
789         }
790         if (rrd_graph
791             (argc - 1, &argv[1], &calcpr, &xsize, &ysize, NULL, &ymin,
792              &ymax) != -1) {
793             if (!tostdout && !imginfo)
794                 printf("%dx%d\n", xsize, ysize);
795             if (calcpr) {
796                 for (i = 0; calcpr[i]; i++) {
797                     if (!tostdout)
798                         printf("%s\n", calcpr[i]);
799                     free(calcpr[i]);
800                 }
801                 free(calcpr);
802             }
803         }
804
805     } else if (strcmp("graphv", argv[1]) == 0) {
806         rrd_info_t *grinfo = NULL;  /* 1 to distinguish it from the NULL that rrd_graph sends in */
807
808         grinfo = rrd_graph_v(argc - 1, &argv[1]);
809         if (grinfo) {
810             rrd_info_print(grinfo);
811             rrd_info_free(grinfo);
812         }
813
814     } else if (strcmp("tune", argv[1]) == 0)
815         rrd_tune(argc - 1, &argv[1]);
816     else if (strcmp("flushcached", argv[1]) == 0)
817         rrd_flushcached(argc - 1, &argv[1]);
818     else {
819         rrd_set_error("unknown function '%s'", argv[1]);
820     }
821     if (rrd_test_error()) {
822         fprintf(out, "ERROR: %s\n", rrd_get_error());
823         rrd_clear_error();
824         return 1;
825     }
826     return (0);
827 }
828
829 int CountArgs(
830     char *aLine)
831 {
832     int       i = 0;
833     int       aCount = 0;
834     int       inarg = 0;
835
836     while (aLine[i] == ' ')
837         i++;
838     while (aLine[i] != 0) {
839         if ((aLine[i] == ' ') && inarg) {
840             inarg = 0;
841         }
842         if ((aLine[i] != ' ') && !inarg) {
843             inarg = 1;
844             aCount++;
845         }
846         i++;
847     }
848     return aCount;
849 }
850
851 /*
852  * CreateArgs - take a string (aLine) and tokenize
853  */
854 int CreateArgs(
855     char *pName,
856     char *aLine,
857     char **argv)
858 {
859     char     *getP, *putP;
860     char    **pargv = argv;
861     char      Quote = 0;
862     int       inArg = 0;
863     int       len;
864     int       argc = 1;
865
866     len = strlen(aLine);
867     /* remove trailing space and newlines */
868     while (len && aLine[len] <= ' ') {
869         aLine[len] = 0;
870         len--;
871     }
872     /* sikp leading blanks */
873     while (*aLine && *aLine <= ' ')
874         aLine++;
875     pargv[0] = pName;
876     argc = 1;
877     getP = aLine;
878     putP = aLine;
879     while (*getP) {
880         switch (*getP) {
881         case ' ':
882             if (Quote) {
883                 *(putP++) = *getP;
884             } else if (inArg) {
885                 *(putP++) = 0;
886                 inArg = 0;
887             }
888             break;
889         case '"':
890         case '\'':
891             if (Quote != 0) {
892                 if (Quote == *getP)
893                     Quote = 0;
894                 else {
895                     *(putP++) = *getP;
896                 }
897             } else {
898                 if (!inArg) {
899                     pargv[argc++] = putP;
900                     inArg = 1;
901                 }
902                 Quote = *getP;
903             }
904             break;
905         default:
906             if (!inArg) {
907                 pargv[argc++] = putP;
908                 inArg = 1;
909             }
910             *(putP++) = *getP;
911             break;
912         }
913         getP++;
914     }
915
916     *putP = '\0';
917     if (Quote)
918         return -1;
919     else
920         return argc;
921 }