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