fix off by 1 error
[rrdtool.git] / src / rrd_xport.c
1 /****************************************************************************
2  * RRDtool 1.4.3  Copyright by Tobi Oetiker, 1997-2010
3  ****************************************************************************
4  * rrd_xport.c  export RRD data 
5  ****************************************************************************/
6
7 #include <sys/stat.h>
8 #include <locale.h>
9
10 #include "rrd_tool.h"
11 #include "rrd_graph.h"
12 #include "rrd_xport.h"
13 #include "unused.h"
14 #include "rrd_client.h"
15
16 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
17 #include <io.h>
18 #include <fcntl.h>
19 #endif
20
21 int       rrd_xport(
22     int,
23     char **,
24     int *,
25     time_t *,
26     time_t *,
27     unsigned long *,
28     unsigned long *,
29     char ***,
30     rrd_value_t **);
31
32 int       rrd_xport_fn(
33     image_desc_t *,
34     time_t *,
35     time_t *,
36     unsigned long *,
37     unsigned long *,
38     char ***,
39     rrd_value_t **,
40     int);
41
42 /* helper function for buffer handling */
43 typedef struct stringbuffer_t {
44   size_t allocated;
45   size_t len;
46   unsigned char* data;
47   FILE *file;
48 } stringbuffer_t;
49 int addToBuffer(stringbuffer_t *,char*,size_t);
50 void escapeJSON(char*,size_t);
51
52 int rrd_graph_xport(image_desc_t *);
53 int rrd_xport_format_xmljson(int,stringbuffer_t *,image_desc_t*,time_t, time_t, unsigned long, unsigned long, char**, rrd_value_t*);
54 int rrd_xport_format_sv(char,stringbuffer_t *,image_desc_t*,time_t, time_t, unsigned long, unsigned long, char**, rrd_value_t*);
55 int rrd_xport_format_addprints(int,stringbuffer_t *,image_desc_t *);
56
57 int rrd_xport(
58     int argc,
59     char **argv,
60     int UNUSED(*xsize),
61     time_t *start,
62     time_t *end,        /* which time frame do you want ?
63                          * will be changed to represent reality */
64     unsigned long *step,    /* which stepsize do you want? 
65                              * will be changed to represent reality */
66     unsigned long *col_cnt, /* number of data columns in the result */
67     char ***legend_v,   /* legend entries */
68     rrd_value_t **data)
69 {                       /* two dimensional array containing the data */
70     image_desc_t im;
71     time_t    start_tmp = 0, end_tmp = 0;
72     rrd_time_value_t start_tv, end_tv;
73     char     *parsetime_error = NULL;
74
75     struct option long_options[] = {
76         {"start", required_argument, 0, 's'},
77         {"end", required_argument, 0, 'e'},
78         {"maxrows", required_argument, 0, 'm'},
79         {"step", required_argument, 0, 261},
80         {"enumds", no_argument, 0, 262},    /* these are handled in the frontend ... */
81         {"json", no_argument, 0, 263},    /* these are handled in the frontend ... */
82         {"daemon", required_argument, 0, 'd'},
83         {0, 0, 0, 0}
84     };
85
86     optind = 0;
87     opterr = 0;         /* initialize getopt */
88
89     rrd_graph_init(&im);
90
91     rrd_parsetime("end-24h", &start_tv);
92     rrd_parsetime("now", &end_tv);
93
94     int enumds=0;
95     int json=0;
96
97     while (1) {
98         int       option_index = 0;
99         int       opt;
100
101         opt = getopt_long(argc, argv, "s:e:m:d:", long_options, &option_index);
102
103         if (opt == EOF)
104             break;
105
106         switch (opt) {
107         case 261:
108             im.step = atoi(optarg);
109             break;
110         case 262:
111             enumds=1;
112             break;
113         case 263:
114             json=1;
115             break;
116         case 's':
117             if ((parsetime_error = rrd_parsetime(optarg, &start_tv))) {
118                 rrd_set_error("start time: %s", parsetime_error);
119                 return -1;
120             }
121             break;
122         case 'e':
123             if ((parsetime_error = rrd_parsetime(optarg, &end_tv))) {
124                 rrd_set_error("end time: %s", parsetime_error);
125                 return -1;
126             }
127             break;
128         case 'm':
129             im.xsize = atol(optarg);
130             if (im.xsize < 10) {
131                 rrd_set_error("maxrows below 10 rows");
132                 return -1;
133             }
134             break;
135         case 'd':
136         {
137             if (im.daemon_addr != NULL)
138             {
139                 rrd_set_error ("You cannot specify --daemon "
140                         "more than once.");
141                 return (-1);
142             }
143
144             im.daemon_addr = strdup(optarg);
145             if (im.daemon_addr == NULL)
146             {
147                 rrd_set_error("strdup error");
148                 return -1;
149             }
150             break;
151         }
152
153         case '?':
154             rrd_set_error("unknown option '%s'", argv[optind - 1]);
155             return -1;
156         }
157     }
158
159     if (rrd_proc_start_end(&start_tv, &end_tv, &start_tmp, &end_tmp) == -1) {
160         return -1;
161     }
162
163     if (start_tmp < 3600 * 24 * 365 * 10) {
164         rrd_set_error("the first entry to fetch should be after 1980 (%ld)",
165                       start_tmp);
166         return -1;
167     }
168
169     if (end_tmp < start_tmp) {
170         rrd_set_error("start (%ld) should be less than end (%ld)",
171                       start_tmp, end_tmp);
172         return -1;
173     }
174
175     im.start = start_tmp;
176     im.end = end_tmp;
177     im.step = max((long) im.step, (im.end - im.start) / im.xsize);
178
179     rrd_graph_script(argc, argv, &im, 0);
180     if (rrd_test_error()) {
181         im_free(&im);
182         return -1;
183     }
184
185     if (im.gdes_c == 0) {
186         rrd_set_error("can't make an xport without contents");
187         im_free(&im);
188         return (-1);
189     }
190
191     {   /* try to connect to rrdcached */
192         int status = rrdc_connect(im.daemon_addr);
193         if (status != 0) return status;
194     }
195
196     if (rrd_xport_fn(&im, start, end, step, col_cnt, legend_v, data,0) == -1) {
197         im_free(&im);
198         return -1;
199     }
200
201     /* and create the export */
202     if (!xsize) {
203       int flags=0;
204       if (json) { flags|=1; }
205       if (enumds) { flags|=4; }
206       stringbuffer_t buffer={0,0,NULL,stdout};
207       rrd_xport_format_xmljson(flags,&buffer,&im, 
208                                *start, *end, *step,
209                                *col_cnt, *legend_v,
210                                *data);
211     }
212
213     im_free(&im);
214     return 0;
215 }
216
217
218
219 int rrd_xport_fn(
220     image_desc_t *im,
221     time_t *start,
222     time_t *end,        /* which time frame do you want ?
223                          * will be changed to represent reality */
224     unsigned long *step,    /* which stepsize do you want? 
225                              * will be changed to represent reality */
226     unsigned long *col_cnt, /* number of data columns in the result */
227     char ***legend_v,   /* legend entries */
228     rrd_value_t **data,
229     int dolines)
230 {                       /* two dimensional array containing the data */
231
232     int       i = 0, j = 0;
233     unsigned long dst_row, row_cnt;
234     rrd_value_t  *dstptr;
235
236     unsigned long xport_counter = 0;
237     int      *ref_list;
238     long     *step_list;
239     long     *step_list_ptr;    
240     char    **legend_list;
241
242
243     /* pull the data from the rrd files ... */
244     if (data_fetch(im) == -1)
245         return -1;
246
247     /* evaluate CDEF  operations ... */
248     if (data_calc(im) == -1)
249         return -1;
250
251     /* how many xports or lines/AREA/STACK ? */
252     *col_cnt = 0;
253     for (i = 0; i < im->gdes_c; i++) {
254         switch (im->gdes[i].gf) {
255         case GF_LINE:
256         case GF_AREA:
257         case GF_STACK:
258           (*col_cnt)+=dolines;
259           break;
260         case GF_XPORT:
261           (*col_cnt)++;
262             break;
263         default:
264             break;
265         }
266     }
267     if ((*col_cnt) == 0) {
268         rrd_set_error("no XPORT found, nothing to do");
269         return -1;
270     }
271
272     /* a list of referenced gdes */
273     ref_list = (int*)malloc(sizeof(int) * (*col_cnt));
274     if (ref_list == NULL)
275         return -1;
276
277     /* a list to save pointers to the column's legend entry */
278     /* this is a return value! */
279     legend_list = (char**)malloc(sizeof(char *) * (*col_cnt));
280     if (legend_list == NULL) {
281         free(ref_list);
282         return -1;
283     }
284
285     /* lets find the step size we have to use for xport */
286     step_list = (long*)malloc(sizeof(long)*((*col_cnt)+1));
287     step_list_ptr = step_list;
288     j = 0;
289     for (i = 0; i < im->gdes_c; i++) {
290       /* decide if we need to handle the output */
291         int handle=0;
292         switch (im->gdes[i].gf) {
293         case GF_LINE:
294         case GF_AREA:
295         case GF_STACK:
296           handle=dolines;
297           break;
298         case GF_XPORT:
299           handle=1;
300           break;
301         default:
302           handle=0;
303           break;
304         }
305         /* and now do the real work */
306         if (handle) {
307             ref_list[xport_counter++] = i;
308             *step_list_ptr = im->gdes[im->gdes[i].vidx].step;
309             /* printf("%s:%lu\n",im->gdes[i].legend,*step_list_ptr); */
310             step_list_ptr++;
311
312             /* reserve room for one legend entry */
313             if ((legend_list[j] = strdup(im->gdes[i].legend)) == NULL) {
314                 free(ref_list);
315                 *data = NULL;
316                 while (--j > -1)
317                     free(legend_list[j]);
318                 free(legend_list);
319                 free(step_list);
320                 rrd_set_error("malloc xport legend entry");
321                 return (-1);
322             }
323
324             if (im->gdes[i].legend == 0)
325                 legend_list[j][0] = '\0';
326             ++j;
327         }
328     }
329     *step_list_ptr=0;    
330     /* find a common step */
331     *step = lcd(step_list);
332     /* printf("step: %lu\n",*step); */
333     free(step_list);
334     
335     *start =  im->start - im->start % (*step);
336     *end = im->end - im->end % (*step) + (*step);
337     
338
339     /* room for rearranged data */
340     /* this is a return value! */
341     row_cnt = ((*end) - (*start)) / (*step);
342     if (((*data) =
343         (rrd_value_t*)malloc((*col_cnt) * row_cnt * sizeof(rrd_value_t))) == NULL) {
344         free(ref_list);
345         free(legend_list);
346         rrd_set_error("malloc xport data area");
347         return (-1);
348     }
349     dstptr = (*data);
350
351     /* fill data structure */
352     for (dst_row = 0; (int) dst_row < (int) row_cnt; dst_row++) {
353         for (i = 0; i < (int) (*col_cnt); i++) {
354             long vidx = im->gdes[ref_list[i]].vidx;
355             time_t now = *start + dst_row * *step;
356             (*dstptr++) = im->gdes[vidx].data[(unsigned long)
357                                               floor((double)
358                                                     (now - im->gdes[vidx].start)
359                                                     /im->gdes[vidx].step)
360                                               * im->gdes[vidx].ds_cnt +
361                                               im->gdes[vidx].ds];
362
363         }
364     }
365
366     *legend_v = legend_list;
367     free(ref_list);
368     return 0;
369
370 }
371
372 int rrd_graph_xport(image_desc_t *im) {
373   /* prepare the data for processing */
374   unsigned long col_cnt=0;
375   time_t start=im->start;
376   time_t end=im->end;
377   unsigned long step=im->step;
378   char **legend_v=NULL;
379   rrd_value_t *data=NULL;
380   /* initialize buffer */
381   stringbuffer_t buffer={0,0,NULL,NULL}; 
382
383   /* check if we have a supported ggraph format */
384   switch (im->graph_type) {
385     /* allow the following to pass */
386   case GTYPE_TIME:
387   case GTYPE_XY:
388     break;
389   default:
390     rrd_set_error("Not supported graph type");
391     return -1;
392   }
393
394   /* if we write a file, then open it */
395   if (strlen(im->graphfile)) {
396     buffer.file=fopen(im->graphfile,"w");
397   }
398
399   /* do the data processing */
400   if (rrd_xport_fn(im,&start,&end,&step,&col_cnt,&legend_v,&data,1)) { return -1;}
401
402   /* fill in some data */
403   rrd_infoval_t info;
404   info.u_cnt = start;
405   grinfo_push(im, sprintf_alloc("graph_start"), RD_I_CNT, info);
406   info.u_cnt = end;
407   grinfo_push(im, sprintf_alloc("graph_end"), RD_I_CNT, info);
408   info.u_cnt = step;
409   grinfo_push(im, sprintf_alloc("graph_step"), RD_I_CNT, info);
410
411   /* set locale */
412   char *old_locale = setlocale(LC_NUMERIC,NULL);
413   setlocale(LC_NUMERIC, "C");
414
415   /* format it for output */
416   int r=0;
417   switch(im->imgformat) {
418   case IF_XML:
419     r=rrd_xport_format_xmljson(2,&buffer,im, start, end, step, col_cnt, legend_v, data);
420     break;
421   case IF_XMLENUM:
422     r=rrd_xport_format_xmljson(6,&buffer,im, start, end, step, col_cnt, legend_v, data);
423     break;
424   case IF_JSON:
425     r=rrd_xport_format_xmljson(1,&buffer,im, start, end, step, col_cnt, legend_v, data);
426     break;
427   case IF_JSONTIME:
428     r=rrd_xport_format_xmljson(3,&buffer,im, start, end, step, col_cnt, legend_v, data);
429     break;
430   case IF_CSV:
431     r=rrd_xport_format_sv(',',&buffer,im, start, end, step, col_cnt, legend_v, data);
432     break;
433   case IF_TSV:
434     r=rrd_xport_format_sv('\t',&buffer,im, start, end, step, col_cnt, legend_v, data);
435     break;
436   case IF_SSV:
437     r=rrd_xport_format_sv(';',&buffer,im, start, end, step, col_cnt, legend_v, data);
438     break;
439   default:
440     break;
441   }
442   /* restore locale */
443   setlocale(LC_NUMERIC, old_locale);
444   /* handle errors */
445   if (r) {
446     /* free legend */
447     for (unsigned long j = 0; j < col_cnt; j++) {
448       free(legend_v[j]);
449     }
450     free(legend_v);
451     /* free data */
452     free(data);
453     /* free the bufer */
454     if (buffer.data) {free(buffer.data);}
455     /* close the file */
456     if (buffer.file) {fclose(buffer.file);}
457     /* and return with error */
458     return r;
459   }
460
461   /* now do the cleanup */
462   if (buffer.file) {
463     fclose(buffer.file); buffer.file=NULL; 
464     im->rendered_image_size=0;
465     im->rendered_image=NULL;
466   } else {
467     im->rendered_image_size=buffer.len;
468     im->rendered_image=buffer.data;    
469   }
470
471   /* and print stuff */
472   return print_calc(im);
473 }
474
475 int addToBuffer(stringbuffer_t * sb,char* data,size_t len) {
476   /* if len <= 0  we assume a string and calculate the length ourself */
477   if (len<=0) { len=strlen(data); }
478   /* if we have got a file, then take the shortcut */
479   if (sb->file) { 
480     sb->len+=len;
481     fwrite(data,len,1,sb->file); 
482     return 0; 
483   }
484   /* if buffer is 0, then initialize */
485   if (! sb->data) { 
486     /* make buffer a multiple of 8192 */
487     sb->allocated+=8192;
488     sb->allocated-=(sb->allocated%8192);    
489     /* and allocate it */
490     sb->data=malloc(sb->allocated); 
491     if (! sb->data) { 
492       rrd_set_error("malloc issue");
493       return 1;
494     }
495     /* and initialize the buffer */
496     sb->len=0;
497     sb->data[0]=0;
498   }
499   /* and figure out if we need to extend the buffer */
500   if (sb->len+len+1>=sb->allocated) {
501     /* add so many pages until we have a buffer big enough */
502     while(sb->len+len+1>=sb->allocated) {
503       sb->allocated+=8192;
504     }
505     /* try to resize it */
506     unsigned char* resized=(unsigned char*)realloc(sb->data,sb->allocated);
507     if (resized) {
508       sb->data=resized;
509     } else {
510       free(sb->data);
511       sb->data=NULL;
512       sb->allocated=0;
513       rrd_set_error("realloc issue");
514       return -1;
515     }
516   }
517   /* and finally add to the buffer */
518   memcpy(sb->data+sb->len,data,len);
519   sb->len+=len;
520   /* and 0 terminate it */
521   sb->data[sb->len]=0;
522   /* and return */
523   return 0;
524 }
525
526 int rrd_xport_format_sv(char sep, stringbuffer_t *buffer,image_desc_t *im,time_t start, time_t end, unsigned long step, unsigned long col_cnt, char **legend_v, rrd_value_t* data) {
527   /* define the time format */
528   char* timefmt=NULL;
529   if (im->xlab_user.minsec!=-1) { timefmt=im->xlab_user.stst; }
530
531   /* row count */
532   unsigned long row_cnt=(end-start)/step;
533
534   /* estimate buffer size (to avoid multiple allocations) */
535   buffer->allocated=
536     1024 /* bytes of overhead /header/footer */
537     +(12+19*col_cnt) /* 12 bytes overhead/line plus 19 bytes per column*/
538     *(1+row_cnt) /* number of columns + 1 (for header) */
539     ;
540
541   char buf[256];
542
543   /* now start writing the header*/
544   if (addToBuffer(buffer,"\"time\"",6)) { return 1; }
545   for(unsigned long i=0;i<col_cnt;i++) {
546     /* strip leading spaces */
547     char *t=legend_v[i]; while (isspace(*t)) { t++;}
548     /* and print it */
549     snprintf(buf,255,"%c\"%s\"",sep,t);
550     if (addToBuffer(buffer,buf,0)) { return 1;}
551   }
552   if (addToBuffer(buffer,"\r\n",2)) { return 1; }
553   /* and now write the data */
554   rrd_value_t *ptr=data;
555   for(time_t ti=start+step;ti<end;ti+=step) {
556     /* write time */
557     if (timefmt) {
558       struct tm loc;
559       localtime_r(&ti,&loc);
560       strftime(buf,254,timefmt,&loc);
561     } else {
562       snprintf(buf,254,"%lld",(long long int)ti);
563     }
564     if (addToBuffer(buffer,buf,0)) { return 1; }
565     /* write the columns */
566     for(unsigned long i=0;i<col_cnt;i++) {
567       /* get the value */
568       rrd_value_t v=*ptr;ptr++;
569       /* and print it */
570       if (isnan(v)) {
571         snprintf(buf,255,"%c\"NaN\"",sep);
572       } else {
573         snprintf(buf,255,"%c\"%0.10e\"",sep,v);
574       }
575       if (addToBuffer(buffer,buf,0)) { return 1;}
576     }
577     /* and add a newline */
578     if (addToBuffer(buffer,"\r\n",2)) { return 1; }
579   }
580
581   /* and return OK */
582   return 0;
583 }
584
585 int rrd_xport_format_xmljson(int flags,stringbuffer_t *buffer,image_desc_t *im,time_t start, time_t end, unsigned long step, unsigned long col_cnt, char **legend_v, rrd_value_t* data) {
586
587   /* define some other stuff based on flags */
588   int json=0;
589   if (flags &1) { json=1; }
590   int showtime=0;
591   if (flags &2) { showtime=1;}
592   int enumds=0;
593   if (flags &4) { enumds=1;}
594
595   /* define the time format */
596   char* timefmt=NULL;
597   /* unfortunatley we have to do it this way, 
598      as when no --x-graph argument is given,
599      then the xlab_user is not in a clean state (e.g. zero-filled) */
600   if (im->xlab_user.minsec!=-1) { timefmt=im->xlab_user.stst; }
601
602   /* row count */
603   unsigned long row_cnt=(end-start)/step;
604
605   /* estimate buffer size (to avoid multiple allocations) */
606   /* better estimates are needed here */
607   buffer->allocated=
608     1024 /* bytes of overhead /header/footer */
609     +(12+19*col_cnt) /* 12 bytes overhead/line plus 19 bytes per column*/
610     *(1+row_cnt) /* number of columns + 1 (for header) */
611     ;
612   char buf[256];
613   char dbuf[1024];
614
615   rrd_value_t *ptr = data;
616   if (json == 0){
617     snprintf(buf,sizeof(buf),
618              "<?xml version=\"1.0\" encoding=\"%s\"?>\n\n<%s>\n  <%s>\n",
619              XML_ENCODING,ROOT_TAG,META_TAG);
620     addToBuffer(buffer,buf,0);
621   }
622   else {
623     addToBuffer(buffer,"{ \"about\": \"RRDtool graph JSON output\",\n  \"meta\": {\n",0);
624   }
625   
626   /* calculate start time */
627   if (timefmt) {
628     struct tm loc;
629     time_t ti=start+step;
630     localtime_r(&ti,&loc);
631     strftime(dbuf,sizeof(dbuf),timefmt,&loc);
632     if (json) {
633       snprintf(buf,sizeof(buf),"    \"%s\": \"%s\",\n",META_START_TAG,dbuf);
634     } else {
635       snprintf(buf,sizeof(buf),"    <%s>%s</%s>\n",META_START_TAG,dbuf,META_START_TAG);
636     }
637   } else {
638     if (json) {
639       snprintf(buf,sizeof(buf),"    \"%s\": %lld,\n",META_START_TAG,(long long int)start+step);
640     } else {
641       snprintf(buf,sizeof(buf),"    <%s>%lld</%s>\n",META_START_TAG,(long long int)start+step,META_START_TAG);
642     }
643   }
644   addToBuffer(buffer,buf,0);
645
646   /* calculate end time */
647   if (timefmt) {
648     struct tm loc;
649     time_t ti=end;
650     localtime_r(&ti,&loc);
651     strftime(dbuf,sizeof(dbuf),timefmt,&loc);
652     if (json) {
653       snprintf(buf,sizeof(buf),"    \"%s\": \"%s\",\n",META_END_TAG,dbuf);
654     } else {
655       snprintf(buf,sizeof(buf),"    <%s>%s</%s>\n",META_END_TAG,dbuf,META_END_TAG);
656     }
657   } else {
658     if (json) {
659       snprintf(buf,sizeof(buf),"    \"%s\": %lld,\n",META_END_TAG,(long long int)end);
660     } else {
661       snprintf(buf,sizeof(buf),"    <%s>%lld</%s>\n",META_END_TAG,(long long int)end,META_END_TAG);
662     }
663   }
664   addToBuffer(buffer,buf,0);
665   /* print other info */
666   if (json) {
667     snprintf(buf,sizeof(buf),"    \"%s\": %lld,\n",META_STEP_TAG,(long long int)step);
668     addToBuffer(buffer,buf,0);
669   } else {
670     snprintf(buf,sizeof(buf),"    <%s>%lld</%s>\n",META_STEP_TAG,(long long int)step,META_STEP_TAG); 
671     addToBuffer(buffer,buf,0);
672     snprintf(buf,sizeof(buf),"    <%s>%lu</%s>\n",META_ROWS_TAG,row_cnt,META_ROWS_TAG); 
673     addToBuffer(buffer,buf,0);
674     snprintf(buf,sizeof(buf),"    <%s>%lu</%s>\n",META_COLS_TAG,col_cnt,META_COLS_TAG); 
675     addToBuffer(buffer,buf,0);
676   }
677   
678   /* start legend */
679   if (json){
680     snprintf(buf,sizeof(buf),"    \"%s\": [\n", LEGEND_TAG);
681   }
682   else {
683     snprintf(buf,sizeof(buf),"    <%s>\n", LEGEND_TAG);
684   }
685   addToBuffer(buffer,buf,0);
686   /* add legend entries */
687   for (unsigned long j = 0; j < col_cnt; j++) {
688     char *entry = legend_v[j];
689     /* I do not know why the legend is "spaced", but let us skip it */
690     while(isspace(*entry)){entry++;}
691     /* now output it */
692     if (json){
693       snprintf(buf,sizeof(buf),"      \"%s\"", entry);
694       addToBuffer(buffer,buf,0);
695       if (j < col_cnt -1){
696         addToBuffer(buffer,",",1);
697       }
698       addToBuffer(buffer,"\n",1);
699     }
700     else {
701       snprintf(buf,sizeof(buf),"      <%s>%s</%s>\n", LEGEND_ENTRY_TAG, entry,LEGEND_ENTRY_TAG);
702       addToBuffer(buffer,buf,0);
703     }
704   }
705   /* end legend */
706   if (json){
707     snprintf(buf,sizeof(buf),"          ],\n");
708   }
709   else {
710     snprintf(buf,sizeof(buf),"    </%s>\n", LEGEND_TAG);
711   }
712   addToBuffer(buffer,buf,0);
713   
714   /* add graphs and prints */
715   if (rrd_xport_format_addprints(json,buffer,im)) {return -1;}
716
717   /* if we have got a trailing , then kill it */
718   if (buffer->data) {
719     if (buffer->data[buffer->len-2]==',') { 
720       buffer->data[buffer->len-2]=buffer->data[buffer->len-1];
721       buffer->len--;
722     }
723   }
724
725   /* end meta */
726   if (json){
727     snprintf(buf,sizeof(buf),"     },\n");
728   } else {
729     snprintf(buf,sizeof(buf),"  </%s>\n", META_TAG);
730   }
731   addToBuffer(buffer,buf,0);
732
733   
734   /* start data */
735   if (json){
736     snprintf(buf,sizeof(buf),"  \"%s\": [\n",DATA_TAG);
737   } else {
738     snprintf(buf,sizeof(buf),"  <%s>\n", DATA_TAG);
739   }
740   addToBuffer(buffer,buf,0);
741   /* iterate over data */
742   for (time_t ti = start + step; ti <= end; ti += step) {
743     if (timefmt) {
744       struct tm loc;
745       localtime_r(&ti,&loc);
746       strftime(dbuf,sizeof(dbuf),timefmt,&loc);
747     } else {
748       snprintf(dbuf,sizeof(dbuf),"%lld",(long long int)ti);
749     }
750     if (json){
751       addToBuffer(buffer,"    [ ",0);
752       if(showtime){
753         addToBuffer(buffer,"\"",1);
754         addToBuffer(buffer,dbuf,0);
755         addToBuffer(buffer,"\",",2);
756       }
757     }
758     else {
759       if (showtime) {
760         snprintf(buf,sizeof(buf),
761                  "    <%s><%s>%s</%s>", DATA_ROW_TAG,COL_TIME_TAG, dbuf, COL_TIME_TAG);
762       } else {
763         snprintf(buf,sizeof(buf),
764                  "    <%s>", DATA_ROW_TAG);
765       }
766       addToBuffer(buffer,buf,0);
767     }
768     for (unsigned long j = 0; j < col_cnt; j++) {
769       rrd_value_t newval = DNAN;
770       newval = *ptr;
771       if (json){
772         if (isnan(newval)){
773           addToBuffer(buffer,"null",0);                        
774         } else {
775           snprintf(buf,sizeof(buf),"%0.10e",newval);
776           addToBuffer(buffer,buf,0);
777         }
778         if (j < col_cnt -1){
779           addToBuffer(buffer,", ",0);
780         }
781       }
782       else {
783         if (isnan(newval)) {
784           if (enumds) {
785             snprintf(buf,sizeof(buf),"<%s%lu>NaN</%s%lu>", COL_DATA_TAG,j,COL_DATA_TAG,j);
786           } else {
787             snprintf(buf,sizeof(buf),"<%s>NaN</%s>", COL_DATA_TAG,COL_DATA_TAG);
788           }
789         } else {
790           if (enumds) {
791             snprintf(buf,sizeof(buf),"<%s%lu>%0.10e</%s%lu>", COL_DATA_TAG,j,newval,COL_DATA_TAG,j);
792           } else {
793             snprintf(buf,sizeof(buf),"<%s>%0.10e</%s>", COL_DATA_TAG,newval,COL_DATA_TAG);
794           }
795         }
796         addToBuffer(buffer,buf,0);
797       }
798       ptr++;
799     }                
800     if (json){
801       addToBuffer(buffer,(ti < end ? " ],\n" : " ]\n"),0);
802     }
803     else {                
804       snprintf(buf,sizeof(buf),"</%s>\n", DATA_ROW_TAG);
805       addToBuffer(buffer,buf,0);
806     }
807   }
808   /* end data */
809   if (json){
810     addToBuffer(buffer,"  ]\n",0);
811   }
812   else {
813     snprintf(buf,sizeof(buf),"  </%s>\n",DATA_TAG);
814     addToBuffer(buffer,buf,0);
815   }
816
817   /* end all */
818   if (json){
819     addToBuffer(buffer,"}\n",0);
820   } else {
821     snprintf(buf,sizeof(buf),"</%s>\n", ROOT_TAG);
822     addToBuffer(buffer,buf,0);
823   }
824   return 0;
825 }
826
827 void escapeJSON(char* txt,size_t len) {
828   char *tmp=(char*)malloc(len+2);
829   size_t l=strlen(txt);
830   size_t pos=0;
831   /* now iterate over the chars */
832   for(size_t i=0;(i<l)&&(pos<len);i++,pos++) {
833     switch (txt[i]) {
834       case '"':
835       case '\\':
836         tmp[pos]='\\';pos++;
837         tmp[pos]=txt[i];
838         break;
839     default:
840       tmp[pos]=txt[i];
841       break;
842     }
843   }
844   /* 0 terminate it */
845   tmp[pos]=0;
846   /* and copy back over txt */
847   strncpy(txt,tmp,len);
848   /* and release tmp */
849   free(tmp);
850 }
851
852 int rrd_xport_format_addprints(int flags,stringbuffer_t *buffer,image_desc_t *im) {
853   /* initialize buffer */
854   stringbuffer_t prints={1024,0,NULL,NULL}; 
855   stringbuffer_t rules={1024,0,NULL,NULL}; 
856   stringbuffer_t gprints={4096,0,NULL,NULL}; 
857   char buf[256];
858   char dbuf[1024];
859   char* val;
860   char* timefmt=NULL;
861   if (im->xlab_user.minsec!=-1) { timefmt=im->xlab_user.stst; }
862
863   /* define some other stuff based on flags */
864   int json=0;
865   if (flags &1) { json=1; }
866   int showtime=0;
867   if (flags &2) { showtime=1;}
868   int enumds=0;
869   if (flags &4) { enumds=1;}
870
871   /* define some values */
872   time_t    now = time(NULL);
873   struct tm tmvdef;
874   localtime_r(&now, &tmvdef);
875   double printval=DNAN;
876
877   /* iterate over all fields and start the work writing to the correct buffers */
878   for (long i = 0; i < im->gdes_c; i++) {
879     long vidx = im->gdes[i].vidx;
880     char* entry;
881     switch (im->gdes[i].gf) {
882     case GF_PRINT:
883     case GF_GPRINT:
884       /* PRINT and GPRINT can now print VDEF generated values.
885        * There's no need to do any calculations on them as these
886        * calculations were already made.
887        * we do not support the depreciated version here
888        */
889       printval=DNAN;
890       /* decide to which buffer we print to*/
891       stringbuffer_t *usebuffer=&gprints;
892       char* usetag="gprint";
893       if (im->gdes[i].gf==GF_PRINT) { 
894         usebuffer=&prints;
895         usetag="print";
896       }
897       /* get the value */
898       if (im->gdes[vidx].gf == GF_VDEF) { /* simply use vals */
899         printval = im->gdes[vidx].vf.val;
900         localtime_r(&im->gdes[vidx].vf.when, &tmvdef);
901       } else {
902         int max_ii = ((im->gdes[vidx].end - im->gdes[vidx].start)
903                       / im->gdes[vidx].step * im->gdes[vidx].ds_cnt);
904         printval = DNAN;
905         long validsteps = 0;
906         for (long ii = im->gdes[vidx].ds;
907              ii < max_ii; ii += im->gdes[vidx].ds_cnt) {
908           if (!finite(im->gdes[vidx].data[ii]))
909             continue;
910           if (isnan(printval)) {
911             printval = im->gdes[vidx].data[ii];
912             validsteps++;
913             continue;
914           }
915           
916           switch (im->gdes[i].cf) {
917           case CF_HWPREDICT:
918           case CF_MHWPREDICT:
919           case CF_DEVPREDICT:
920           case CF_DEVSEASONAL:
921           case CF_SEASONAL:
922           case CF_AVERAGE:
923             validsteps++;
924             printval += im->gdes[vidx].data[ii];
925             break;
926           case CF_MINIMUM:
927             printval = min(printval, im->gdes[vidx].data[ii]);
928             break;
929           case CF_FAILURES:
930           case CF_MAXIMUM:
931             printval = max(printval, im->gdes[vidx].data[ii]);
932             break;
933           case CF_LAST:
934             printval = im->gdes[vidx].data[ii];
935           }
936         }
937         if (im->gdes[i].cf == CF_AVERAGE || im->gdes[i].cf > CF_LAST) {
938           if (validsteps > 1) {
939             printval = (printval / validsteps);
940           }
941         }
942       }
943       /* we handle PRINT and GPRINT the same - format now*/
944       if (im->gdes[i].strftm) {
945         if (im->gdes[vidx].vf.never == 1) {
946           time_clean(buf, im->gdes[i].format);
947         } else {
948           strftime(dbuf,sizeof(dbuf), im->gdes[i].format, &tmvdef);
949         }
950       } else if (bad_format(im->gdes[i].format)) {
951         rrd_set_error
952           ("bad format for PRINT in \"%s'", im->gdes[i].format);
953         return -1;
954       } else {
955         snprintf(dbuf,sizeof(dbuf), im->gdes[i].format, printval,"");
956       }
957       /* print */
958       if (json) {
959         escapeJSON(dbuf,sizeof(dbuf));
960         snprintf(buf,sizeof(buf),",\n        { \"%s\": \"%s\" }",usetag,dbuf);
961       } else {
962         snprintf(buf,sizeof(buf),"        <%s>%s</%s>\n",usetag,dbuf,usetag);
963       }
964       addToBuffer(usebuffer,buf,0);
965       break;
966     case GF_COMMENT:
967       if (json) {
968         strncpy(dbuf,im->gdes[i].legend,sizeof(dbuf));
969         escapeJSON(dbuf,sizeof(dbuf));
970         snprintf(buf,sizeof(buf),",\n        { \"comment\": \"%s\" }",dbuf);
971       } else {
972         snprintf(buf,sizeof(buf),"        <comment>%s</comment>\n",im->gdes[i].legend);
973       }
974       addToBuffer(&gprints,buf,0);
975       break;
976     case GF_LINE:
977       entry = im->gdes[i].legend;
978       /* I do not know why the legend is "spaced", but let us skip it */
979       while(isspace(*entry)){entry++;}
980       if (json) {
981         snprintf(buf,sizeof(buf),",\n        { \"line\": \"%s\" }",entry);
982       } else {
983         snprintf(buf,sizeof(buf),"        <line>%s</line>\n",entry);
984       }
985       addToBuffer(&gprints,buf,0);
986       break;
987     case GF_AREA:
988       if (json) {
989         snprintf(buf,sizeof(buf),",\n        { \"area\": \"%s\" }",im->gdes[i].legend);
990       } else {
991         snprintf(buf,sizeof(buf),"        <area>%s</area>\n",im->gdes[i].legend);
992       }
993       addToBuffer(&gprints,buf,0);
994       break;
995     case GF_STACK:
996       if (json) {
997         snprintf(buf,sizeof(buf),",\n        { \"stack\": \"%s\" }",im->gdes[i].legend);
998       } else {
999         snprintf(buf,sizeof(buf),"        <stack>%s</stack>\n",im->gdes[i].legend);
1000       }
1001       addToBuffer(&gprints,buf,0);
1002       break;
1003     case GF_TEXTALIGN:
1004       val="";
1005       switch (im->gdes[i].txtalign) {
1006       case TXA_LEFT: val="left"; break;
1007       case TXA_RIGHT: val="right"; break;
1008       case TXA_CENTER: val="center"; break;
1009       case TXA_JUSTIFIED: val="justified"; break;
1010       }
1011       if (json) {
1012         snprintf(buf,sizeof(buf),",\n        { \"align\": \"%s\" }",val);
1013       } else {
1014         snprintf(buf,sizeof(buf),"        <align>%s</align>\n",val);
1015       }
1016       addToBuffer(&gprints,buf,0);
1017       break;
1018     case GF_HRULE:
1019       /* This does not work as expected - Tobi please help!!! */
1020       snprintf(dbuf,sizeof(dbuf),"%0.10e",im->gdes[i].vf.val);
1021       /* and output it */
1022       if (json) {
1023         snprintf(buf,sizeof(buf),",\n        { \"hrule\": \"%s\" }",dbuf);
1024       } else {
1025         snprintf(buf,sizeof(buf),"        <hrule>%s</hrule>\n",dbuf);
1026       }
1027       addToBuffer(&rules,buf,0);
1028       break;
1029     case GF_VRULE:
1030       if (timefmt) {
1031         struct tm loc;
1032         localtime_r(&im->gdes[i].xrule,&loc);
1033         strftime(dbuf,254,timefmt,&loc);
1034       } else {
1035         snprintf(dbuf,254,"%lld",(long long int)im->gdes[i].vf.when);
1036       }
1037       /* and output it */
1038       if (json) {
1039         snprintf(buf,sizeof(buf),",\n        { \"vrule\": \"%s\" }",dbuf);
1040       } else {
1041         snprintf(buf,sizeof(buf),"        <vrule>%s</vrule>\n",dbuf);
1042       }
1043       addToBuffer(&rules,buf,0);
1044       break;
1045     default: 
1046       break;
1047     }
1048   }
1049   /* now add prints */
1050   if (prints.len) {
1051     if (json){
1052       snprintf(buf,sizeof(buf),"    \"%s\": [\n","prints");
1053       addToBuffer(buffer,buf,0);
1054       addToBuffer(buffer,(char*)prints.data+2,prints.len-2);
1055       addToBuffer(buffer,"\n        ],\n",0);
1056     } else {
1057       snprintf(buf,sizeof(buf),"    <%s>\n", "prints");
1058       addToBuffer(buffer,buf,0);
1059       addToBuffer(buffer,(char*)prints.data,prints.len);
1060       snprintf(buf,sizeof(buf),"    </%s>\n", "prints");
1061       addToBuffer(buffer,buf,0);
1062     }
1063     free(prints.data);
1064   }
1065   /* now add gprints */
1066   if (gprints.len) {
1067     if (json){
1068       snprintf(buf,sizeof(buf),"    \"%s\": [\n","gprints");
1069       addToBuffer(buffer,buf,0);
1070       addToBuffer(buffer,(char*)gprints.data+2,gprints.len-2);
1071       addToBuffer(buffer,"\n        ],\n",0);
1072     } else {
1073       snprintf(buf,sizeof(buf),"    <%s>\n", "gprints");
1074       addToBuffer(buffer,buf,0);
1075       addToBuffer(buffer,(char*)gprints.data,gprints.len);
1076       snprintf(buf,sizeof(buf),"    </%s>\n", "gprints");
1077       addToBuffer(buffer,buf,0);
1078     }
1079     free(gprints.data);
1080   }
1081   /* now add rules */
1082   if (rules.len) {
1083     if (json){
1084       snprintf(buf,sizeof(buf),"    \"%s\": [\n","rules");
1085       addToBuffer(buffer,buf,0);
1086       addToBuffer(buffer,(char*)rules.data+2,rules.len-2);
1087       addToBuffer(buffer,"\n        ],\n",0);
1088     } else {
1089       snprintf(buf,sizeof(buf),"    <%s>\n", "rules");
1090       addToBuffer(buffer,buf,0);
1091       addToBuffer(buffer,(char*)rules.data,rules.len);
1092       snprintf(buf,sizeof(buf),"    </%s>\n", "rules");
1093       addToBuffer(buffer,buf,0);
1094     }
1095     free(rules.data);
1096   }
1097   /* and return */
1098   return 0;
1099 }