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