ba561ce52cabbf062589b7facec130b41c461d18
[rrdtool.git] / src / rrd_tool.c
1 /*****************************************************************************
2  * RRDtool 1.2.23  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
436
437 #if HAVE_GETRUSAGE
438                     getrusage(RUSAGE_SELF, &myusage);
439                     gettimeofday(&currenttime, NULL);
440                     printf("OK u:%1.2f s:%1.2f r:%1.2f\n",
441                            (double) myusage.ru_utime.tv_sec +
442                            (double) myusage.ru_utime.tv_usec / 1000000.0,
443                            (double) myusage.ru_stime.tv_sec +
444                            (double) myusage.ru_stime.tv_usec / 1000000.0,
445                            (double) (currenttime.tv_sec - starttime.tv_sec)
446                            + (double) (currenttime.tv_usec -
447                                        starttime.tv_usec)
448                            / 1000000.0);
449 #else
450                     printf("OK\n");
451
452 #endif
453                 }
454             }
455             fflush(stdout); /* this is important for pipes to work */
456             free(aLine);
457         }
458     } else if (argc == 2) {
459         PrintUsage(argv[1]);
460         exit(0);
461     } else if (argc == 3 && !strcmp(argv[1], "help")) {
462         PrintUsage(argv[2]);
463         exit(0);
464     } else {
465         exit(HandleInputLine(argc, argv, stderr));
466     }
467     return 0;
468 }
469
470 /* HandleInputLine is NOT thread safe - due to readdir issues,
471    resolving them portably is not really simple. */
472 int HandleInputLine(
473     int argc,
474     char **argv,
475     FILE * out)
476 {
477 #if defined(HAVE_OPENDIR) && defined (HAVE_READDIR)
478     DIR      *curdir;   /* to read current dir with ls */
479     struct dirent *dent;
480 #endif
481 #if defined(HAVE_SYS_STAT_H)
482     struct stat st;
483 #endif
484     char     *cwd;      /* To hold current working dir on call to pwd */
485
486     /* Reset errno to 0 before we start.
487      */
488     errno = 0;
489
490     if (RemoteMode) {
491         if (argc > 1 && strcmp("quit", argv[1]) == 0) {
492             if (argc > 2) {
493                 printf("ERROR: invalid parameter count for quit\n");
494                 return (1);
495             }
496             exit(0);
497         }
498 #if defined(HAVE_OPENDIR) && defined(HAVE_READDIR) && defined(HAVE_CHDIR)
499         if (argc > 1 && strcmp("cd", argv[1]) == 0) {
500             if (argc > 3) {
501                 printf("ERROR: invalid parameter count for cd\n");
502                 return (1);
503             }
504 #if ! defined(HAVE_CHROOT) || ! defined(HAVE_GETUID)
505             if (getuid() == 0 && !ChangeRoot) {
506                 printf
507                     ("ERROR: chdir security problem - rrdtool is running as "
508                      "root but not chroot!\n");
509                 return (1);
510             }
511 #endif
512             chdir(argv[2]);
513             if (errno != 0) {
514                 printf("ERROR: %s\n", rrd_strerror(errno));
515                 return (1);
516             }
517             return (0);
518         }
519         if (argc > 1 && strcmp("pwd", argv[1]) == 0) {
520             if (argc > 2) {
521                 printf("ERROR: invalid parameter count for pwd\n");
522                 return (1);
523             }
524             cwd = getcwd(NULL, MAXPATH);
525             if (cwd == NULL) {
526                 printf("ERROR: %s\n", rrd_strerror(errno));
527                 return (1);
528             }
529             printf("%s\n", cwd);
530             free(cwd);
531             return (0);
532         }
533         if (argc > 1 && strcmp("mkdir", argv[1]) == 0) {
534             if (argc > 3) {
535                 printf("ERROR: invalid parameter count for mkdir\n");
536                 return (1);
537             }
538 #if ! defined(HAVE_CHROOT) || ! defined(HAVE_GETUID)
539             if (getuid() == 0 && !ChangeRoot) {
540                 printf
541                     ("ERROR: mkdir security problem - rrdtool is running as "
542                      "root but not chroot!\n");
543                 return (1);
544             }
545 #endif
546             mkdir(argv[2], 0777);
547             if (errno != 0) {
548                 printf("ERROR: %s\n", rrd_strerror(errno));
549                 return (1);
550             }
551             return (0);
552         }
553         if (argc > 1 && strcmp("ls", argv[1]) == 0) {
554             if (argc > 2) {
555                 printf("ERROR: invalid parameter count for ls\n");
556                 return (1);
557             }
558             if ((curdir = opendir(".")) != NULL) {
559                 while ((dent = readdir(curdir)) != NULL) {
560                     if (!stat(dent->d_name, &st)) {
561                         if (S_ISDIR(st.st_mode)) {
562                             printf("d %s\n", dent->d_name);
563                         }
564                         if (strlen(dent->d_name) > 4 && S_ISREG(st.st_mode)) {
565                             if (!strcmp
566                                 (dent->d_name + NAMLEN(dent) - 4, ".rrd")
567                                 || !strcmp(dent->d_name + NAMLEN(dent) - 4,
568                                            ".RRD")) {
569                                 printf("- %s\n", dent->d_name);
570                             }
571                         }
572                     }
573                 }
574                 closedir(curdir);
575             } else {
576                 printf("ERROR: %s\n", rrd_strerror(errno));
577                 return (errno);
578             }
579             return (0);
580         }
581 #endif                          /* opendir and readdir */
582
583     }
584     if (argc < 3
585         || strcmp("help", argv[1]) == 0
586         || strcmp("--help", argv[1]) == 0
587         || strcmp("-help", argv[1]) == 0
588         || strcmp("-?", argv[1]) == 0 || strcmp("-h", argv[1]) == 0) {
589         PrintUsage("");
590         return 0;
591     }
592
593     if (strcmp("create", argv[1]) == 0)
594         rrd_create(argc - 1, &argv[1]);
595     else if (strcmp("dump", argv[1]) == 0)
596         rrd_dump(argc - 1, &argv[1]);
597     else if (strcmp("info", argv[1]) == 0 || strcmp("updatev", argv[1]) == 0) {
598         info_t   *data, *save;
599
600         if (strcmp("info", argv[1]) == 0)
601             data = rrd_info(argc - 1, &argv[1]);
602         else
603             data = rrd_update_v(argc - 1, &argv[1]);
604         while (data) {
605             save = data;
606             printf("%s = ", data->key);
607             free(data->key);
608
609             switch (data->type) {
610             case RD_I_VAL:
611                 if (isnan(data->value.u_val))
612                     printf("NaN");
613                 else
614                     printf("%0.10e", data->value.u_val);
615                 break;
616             case RD_I_CNT:
617                 printf("%lu", data->value.u_cnt);
618                 break;
619             case RD_I_INT:
620                 printf("%d", data->value.u_int);
621                 break;
622             case RD_I_STR:
623                 printf("\"%s\"", data->value.u_str);
624                 free(data->value.u_str);
625                 break;
626             }
627             data = data->next;
628             free(save);
629             printf("\n");
630         }
631         free(data);
632     }
633
634     else if (strcmp("--version", argv[1]) == 0 ||
635              strcmp("version", argv[1]) == 0 ||
636              strcmp("v", argv[1]) == 0 ||
637              strcmp("-v", argv[1]) == 0 || strcmp("-version", argv[1]) == 0)
638         printf("RRDtool " PACKAGE_VERSION
639                "  Copyright by Tobi Oetiker, 1997-2005 (%f)\n",
640                rrd_version());
641     else if (strcmp("restore", argv[1]) == 0)
642         rrd_restore(argc - 1, &argv[1]);
643     else if (strcmp("resize", argv[1]) == 0)
644         rrd_resize(argc - 1, &argv[1]);
645     else if (strcmp("last", argv[1]) == 0)
646         printf("%ld\n", rrd_last(argc - 1, &argv[1]));
647     else if (strcmp("lastupdate", argv[1]) == 0) {
648         time_t    last_update;
649         char    **ds_namv;
650         char    **last_ds;
651         unsigned long ds_cnt, i;
652
653         if (rrd_lastupdate(argc - 1, &argv[1], &last_update,
654                            &ds_cnt, &ds_namv, &last_ds) == 0) {
655             for (i = 0; i < ds_cnt; i++)
656                 printf(" %s", ds_namv[i]);
657             printf("\n\n");
658             printf("%10lu:", last_update);
659             for (i = 0; i < ds_cnt; i++) {
660                 printf(" %s", last_ds[i]);
661                 free(last_ds[i]);
662                 free(ds_namv[i]);
663             }
664             printf("\n");
665             free(last_ds);
666             free(ds_namv);
667         }
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, start + step,
724                    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, end, META_END_TAG);
727             printf("    <%s>%lu</%s>\n", META_ROWS_TAG, row_cnt,
728                    META_ROWS_TAG);
729             printf("    <%s>%lu</%s>\n", META_COLS_TAG, col_cnt,
730                    META_COLS_TAG);
731             printf("    <%s>\n", LEGEND_TAG);
732             for (j = 0; j < col_cnt; j++) {
733                 char     *entry = NULL;
734
735                 entry = legend_v[j];
736                 printf("      <%s>%s</%s>\n", LEGEND_ENTRY_TAG, entry,
737                        LEGEND_ENTRY_TAG);
738                 free(entry);
739             }
740             free(legend_v);
741             printf("    </%s>\n", LEGEND_TAG);
742             printf("  </%s>\n", META_TAG);
743             printf("  <%s>\n", DATA_TAG);
744             for (ti = start + step; ti <= end; ti += step) {
745                 printf("    <%s>", DATA_ROW_TAG);
746                 printf("<%s>%lu</%s>", COL_TIME_TAG, ti, COL_TIME_TAG);
747                 for (j = 0; j < col_cnt; j++) {
748                     rrd_value_t newval = DNAN;
749
750                     if (enumds == 1)
751                         snprintf(vtag, vtag_s, "%s%lu", COL_DATA_TAG, j);
752                     else
753                         snprintf(vtag, vtag_s, "%s", COL_DATA_TAG);
754
755                     newval = *ptr;
756                     if (isnan(newval)) {
757                         printf("<%s>NaN</%s>", vtag, vtag);
758                     } else {
759                         printf("<%s>%0.10e</%s>", vtag, newval, vtag);
760                     };
761                     ptr++;
762                 }
763                 printf("</%s>\n", DATA_ROW_TAG);
764             }
765             free(data);
766             printf("  </%s>\n", DATA_TAG);
767             printf("</%s>\n", ROOT_TAG);
768         }
769         free(vtag);
770     } else if (strcmp("graph", argv[1]) == 0) {
771         char    **calcpr;
772
773 #ifdef notused /*XXX*/
774         const char *imgfile = argv[2];  /* rrd_graph changes argv pointer */
775 #endif
776         int       xsize, ysize;
777         double    ymin, ymax;
778         int       i;
779         int       tostdout = (strcmp(argv[2], "-") == 0);
780         int       imginfo = 0;
781
782         for (i = 2; i < argc; i++) {
783             if (strcmp(argv[i], "--imginfo") == 0
784                 || strcmp(argv[i], "-f") == 0) {
785                 imginfo = 1;
786                 break;
787             }
788         }
789         if (rrd_graph
790             (argc - 1, &argv[1], &calcpr, &xsize, &ysize, NULL, &ymin,
791              &ymax) != -1) {
792             if (!tostdout && !imginfo)
793                 printf("%dx%d\n", xsize, ysize);
794             if (calcpr) {
795                 for (i = 0; calcpr[i]; i++) {
796                     if (!tostdout)
797                         printf("%s\n", calcpr[i]);
798                     free(calcpr[i]);
799                 }
800                 free(calcpr);
801             }
802         }
803
804     } else if (strcmp("tune", argv[1]) == 0)
805         rrd_tune(argc - 1, &argv[1]);
806     else {
807         rrd_set_error("unknown function '%s'", argv[1]);
808     }
809     if (rrd_test_error()) {
810         fprintf(out, "ERROR: %s\n", rrd_get_error());
811         rrd_clear_error();
812         return 1;
813     }
814     return (0);
815 }
816
817 int CountArgs(
818     char *aLine)
819 {
820     int       i = 0;
821     int       aCount = 0;
822     int       inarg = 0;
823
824     while (aLine[i] == ' ')
825         i++;
826     while (aLine[i] != 0) {
827         if ((aLine[i] == ' ') && inarg) {
828             inarg = 0;
829         }
830         if ((aLine[i] != ' ') && !inarg) {
831             inarg = 1;
832             aCount++;
833         }
834         i++;
835     }
836     return aCount;
837 }
838
839 /*
840  * CreateArgs - take a string (aLine) and tokenize
841  */
842 int CreateArgs(
843     char *pName,
844     char *aLine,
845     int argc,
846     char **argv)
847 {
848     char     *getP, *putP;
849     char    **pargv = argv;
850     char      Quote = 0;
851     int       inArg = 0;
852     int       len;
853
854     len = strlen(aLine);
855     /* remove trailing space and newlines */
856     while (len && aLine[len] <= ' ') {
857         aLine[len] = 0;
858         len--;
859     }
860     /* sikp leading blanks */
861     while (*aLine && *aLine <= ' ')
862         aLine++;
863
864     pargv[0] = pName;
865     argc = 1;
866     getP = aLine;
867     putP = aLine;
868     while (*getP) {
869         switch (*getP) {
870         case ' ':
871             if (Quote) {
872                 *(putP++) = *getP;
873             } else if (inArg) {
874                 *(putP++) = 0;
875                 inArg = 0;
876             }
877             break;
878         case '"':
879         case '\'':
880             if (Quote != 0) {
881                 if (Quote == *getP)
882                     Quote = 0;
883                 else {
884                     *(putP++) = *getP;
885                 }
886             } else {
887                 if (!inArg) {
888                     pargv[argc++] = putP;
889                     inArg = 1;
890                 }
891                 Quote = *getP;
892             }
893             break;
894         default:
895             if (!inArg) {
896                 pargv[argc++] = putP;
897                 inArg = 1;
898             }
899             *(putP++) = *getP;
900             break;
901         }
902         getP++;
903     }
904
905     *putP = '\0';
906
907     if (Quote)
908         return -1;
909     else
910         return argc;
911 }