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