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