fix use of setlocale all over the place ...
[rrdtool.git] / src / rrd_rpncalc.c
1 /****************************************************************************
2  * RRDtool 1.4.3  Copyright by Tobi Oetiker, 1997-2010
3  ****************************************************************************
4  * rrd_rpncalc.c  RPN calculator functions
5  ****************************************************************************/
6
7 #include <limits.h>
8 #include <locale.h>
9 #include <stdlib.h>
10
11 #include "rrd_tool.h"
12 #include "rrd_rpncalc.h"
13 // #include "rrd_graph.h"
14
15 short     addop2str(
16     enum op_en op,
17     enum op_en op_type,
18     char *op_str,
19     char **result_str,
20     unsigned short *offset);
21 int       tzoffset(
22     time_t);            /* used to implement LTIME */
23
24 short rpn_compact(
25     rpnp_t *rpnp,
26     rpn_cdefds_t **rpnc,
27     short *count)
28 {
29     short     i;
30
31     *count = 0;
32     /* count the number of rpn nodes */
33     while (rpnp[*count].op != OP_END)
34         (*count)++;
35     if (++(*count) > DS_CDEF_MAX_RPN_NODES) {
36         rrd_set_error("Maximum %d RPN nodes permitted",
37                       DS_CDEF_MAX_RPN_NODES);
38         return -1;
39     }
40
41     /* allocate memory */
42     *rpnc = (rpn_cdefds_t *) calloc(*count, sizeof(rpn_cdefds_t));
43     for (i = 0; rpnp[i].op != OP_END; i++) {
44         (*rpnc)[i].op = (char) rpnp[i].op;
45         if (rpnp[i].op == OP_NUMBER) {
46             /* rpnp.val is a double, rpnc.val is a short */
47             double    temp = floor(rpnp[i].val);
48
49             if (temp < SHRT_MIN || temp > SHRT_MAX) {
50                 rrd_set_error
51                     ("constants must be integers in the interval (%d, %d)",
52                      SHRT_MIN, SHRT_MAX);
53                 free(*rpnc);
54                 return -1;
55             }
56             (*rpnc)[i].val = (short) temp;
57         } else if (rpnp[i].op == OP_VARIABLE || rpnp[i].op == OP_PREV_OTHER) {
58             (*rpnc)[i].val = (short) rpnp[i].ptr;
59         }
60     }
61     /* terminate the sequence */
62     (*rpnc)[(*count) - 1].op = OP_END;
63     return 0;
64 }
65
66 rpnp_t   *rpn_expand(
67     rpn_cdefds_t *rpnc)
68 {
69     short     i;
70     rpnp_t   *rpnp;
71
72     /* DS_CDEF_MAX_RPN_NODES is small, so at the expense of some wasted
73      * memory we avoid any reallocs */
74     rpnp = (rpnp_t *) calloc(DS_CDEF_MAX_RPN_NODES, sizeof(rpnp_t));
75     if (rpnp == NULL) {
76         rrd_set_error("failed allocating rpnp array");
77         return NULL;
78     }
79     for (i = 0; rpnc[i].op != OP_END; ++i) {
80         rpnp[i].op = (enum op_en)rpnc[i].op;
81         if (rpnp[i].op == OP_NUMBER) {
82             rpnp[i].val = (double) rpnc[i].val;
83         } else if (rpnp[i].op == OP_VARIABLE || rpnp[i].op == OP_PREV_OTHER) {
84             rpnp[i].ptr = (long) rpnc[i].val;
85         }
86     }
87     /* terminate the sequence */
88     rpnp[i].op = OP_END;
89     return rpnp;
90 }
91
92 /* rpn_compact2str: convert a compact sequence of RPN operator nodes back
93  * into a CDEF string. This function is used by rrd_dump.
94  * arguments:
95  *  rpnc: an array of compact RPN operator nodes
96  *  ds_def: a pointer to the data source definition section of an RRD header
97  *   for lookup of data source names by index
98  *  str: out string, memory is allocated by the function, must be freed by the
99  *   the caller */
100 void rpn_compact2str(
101     rpn_cdefds_t *rpnc,
102     ds_def_t *ds_def,
103     char **str)
104 {
105     unsigned short i, offset = 0;
106     char      buffer[7];    /* short as a string */
107
108     for (i = 0; rpnc[i].op != OP_END; i++) {
109         if (i > 0)
110             (*str)[offset++] = ',';
111
112 #define add_op(VV,VVV) \
113           if (addop2str((enum op_en)(rpnc[i].op), VV, VVV, str, &offset) == 1) continue;
114
115         if (rpnc[i].op == OP_NUMBER) {
116             /* convert a short into a string */
117 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
118             _itoa(rpnc[i].val, buffer, 10);
119 #else
120             sprintf(buffer, "%d", rpnc[i].val);
121 #endif
122             add_op(OP_NUMBER, buffer)
123         }
124
125         if (rpnc[i].op == OP_VARIABLE) {
126             char     *ds_name = ds_def[rpnc[i].val].ds_nam;
127
128             add_op(OP_VARIABLE, ds_name)
129         }
130
131         if (rpnc[i].op == OP_PREV_OTHER) {
132             char     *ds_name = ds_def[rpnc[i].val].ds_nam;
133
134             add_op(OP_VARIABLE, ds_name)
135         }
136 #undef add_op
137
138 #define add_op(VV,VVV) \
139           if (addop2str((enum op_en)rpnc[i].op, VV, #VVV, str, &offset) == 1) continue;
140
141         add_op(OP_ADD, +)
142             add_op(OP_SUB, -)
143             add_op(OP_MUL, *)
144             add_op(OP_DIV, /)
145             add_op(OP_MOD, %)
146             add_op(OP_SIN, SIN)
147             add_op(OP_COS, COS)
148             add_op(OP_LOG, LOG)
149             add_op(OP_FLOOR, FLOOR)
150             add_op(OP_CEIL, CEIL)
151             add_op(OP_EXP, EXP)
152             add_op(OP_DUP, DUP)
153             add_op(OP_EXC, EXC)
154             add_op(OP_POP, POP)
155             add_op(OP_LT, LT)
156             add_op(OP_LE, LE)
157             add_op(OP_GT, GT)
158             add_op(OP_GE, GE)
159             add_op(OP_EQ, EQ)
160             add_op(OP_IF, IF)
161             add_op(OP_MIN, MIN)
162             add_op(OP_MAX, MAX)
163             add_op(OP_LIMIT, LIMIT)
164             add_op(OP_UNKN, UNKN)
165             add_op(OP_UN, UN)
166             add_op(OP_NEGINF, NEGINF)
167             add_op(OP_NE, NE)
168             add_op(OP_PREV, PREV)
169             add_op(OP_INF, INF)
170             add_op(OP_ISINF, ISINF)
171             add_op(OP_NOW, NOW)
172             add_op(OP_LTIME, LTIME)
173             add_op(OP_TIME, TIME)
174             add_op(OP_ATAN2, ATAN2)
175             add_op(OP_ATAN, ATAN)
176             add_op(OP_SQRT, SQRT)
177             add_op(OP_SORT, SORT)
178             add_op(OP_REV, REV)
179             add_op(OP_TREND, TREND)
180             add_op(OP_TRENDNAN, TRENDNAN)
181             add_op(OP_PREDICT, PREDICT)
182             add_op(OP_PREDICTSIGMA, PREDICTSIGMA)
183             add_op(OP_RAD2DEG, RAD2DEG)
184             add_op(OP_DEG2RAD, DEG2RAD)
185             add_op(OP_AVG, AVG)
186             add_op(OP_ABS, ABS)
187             add_op(OP_ADDNAN, ADDNAN)
188 #undef add_op
189     }
190     (*str)[offset] = '\0';
191
192 }
193
194 short addop2str(
195     enum op_en op,
196     enum op_en op_type,
197     char *op_str,
198     char **result_str,
199     unsigned short *offset)
200 {
201     if (op == op_type) {
202         short     op_len;
203
204         op_len = strlen(op_str);
205         *result_str = (char *) rrd_realloc(*result_str,
206                                            (op_len + 1 +
207                                             *offset) * sizeof(char));
208         if (*result_str == NULL) {
209             rrd_set_error("failed to alloc memory in addop2str");
210             return -1;
211         }
212         strncpy(&((*result_str)[*offset]), op_str, op_len);
213         *offset += op_len;
214         return 1;
215     }
216     return 0;
217 }
218
219 void parseCDEF_DS(
220     const char *def,
221     rrd_t *rrd,
222     int ds_idx)
223 {
224     rpnp_t   *rpnp = NULL;
225     rpn_cdefds_t *rpnc = NULL;
226     short     count, i;
227
228     rpnp = rpn_parse((void *) rrd, def, &lookup_DS);
229     if (rpnp == NULL) {
230         rrd_set_error("failed to parse computed data source");
231         return;
232     }
233     /* Check for OP nodes not permitted in COMPUTE DS.
234      * Moved this check from within rpn_compact() because it really is
235      * COMPUTE DS specific. This is less efficient, but creation doesn't
236      * occur too often. */
237     for (i = 0; rpnp[i].op != OP_END; i++) {
238         if (rpnp[i].op == OP_TIME || rpnp[i].op == OP_LTIME ||
239             rpnp[i].op == OP_PREV || rpnp[i].op == OP_COUNT) {
240             rrd_set_error
241                 ("operators time, ltime, prev and count not supported with DS COMPUTE");
242             free(rpnp);
243             return;
244         }
245     }
246     if (rpn_compact(rpnp, &rpnc, &count) == -1) {
247         free(rpnp);
248         return;
249     }
250     /* copy the compact rpn representation over the ds_def par array */
251     memcpy((void *) &(rrd->ds_def[ds_idx].par[DS_cdef]),
252            (void *) rpnc, count * sizeof(rpn_cdefds_t));
253     free(rpnp);
254     free(rpnc);
255 }
256
257 /* lookup a data source name in the rrd struct and return the index,
258  * should use ds_match() here except:
259  * (1) need a void * pointer to the rrd
260  * (2) error handling is left to the caller
261  */
262 long lookup_DS(
263     void *rrd_vptr,
264     char *ds_name)
265 {
266     unsigned int i;
267     rrd_t    *rrd;
268
269     rrd = (rrd_t *) rrd_vptr;
270
271     for (i = 0; i < rrd->stat_head->ds_cnt; ++i) {
272         if (strcmp(ds_name, rrd->ds_def[i].ds_nam) == 0)
273             return i;
274     }
275     /* the caller handles a bad data source name in the rpn string */
276     return -1;
277 }
278
279 /* rpn_parse : parse a string and generate a rpnp array; modified
280  * str2rpn() originally included in rrd_graph.c
281  * arguments:
282  * key_hash: a transparent argument passed to lookup(); conceptually this
283  *    is a hash object for lookup of a numeric key given a variable name
284  * expr: the string RPN expression, including variable names
285  * lookup(): a function that retrieves a numeric key given a variable name
286  */
287 rpnp_t   *rpn_parse(
288     void *key_hash,
289     const char *const expr_const,
290     long      (*lookup) (void *,
291                          char *))
292 {
293     int       pos = 0;
294     char     *expr;
295     long      steps = -1;
296     rpnp_t   *rpnp;
297     char      vname[MAX_VNAME_LEN + 10];
298     char     *old_locale;
299
300     old_locale = setlocale(LC_NUMERIC, NULL);
301     setlocale(LC_NUMERIC, "C");
302
303     rpnp = NULL;
304     expr = (char *) expr_const;
305
306     while (*expr) {
307         if ((rpnp = (rpnp_t *) rrd_realloc(rpnp, (++steps + 2) *
308                                            sizeof(rpnp_t))) == NULL) {
309             setlocale(LC_NUMERIC, old_locale);
310             return NULL;
311         }
312
313         else if ((sscanf(expr, "%lf%n", &rpnp[steps].val, &pos) == 1)
314                  && (expr[pos] == ',')) {
315             rpnp[steps].op = OP_NUMBER;
316             expr += pos;
317         }
318 #define match_op(VV,VVV) \
319         else if (strncmp(expr, #VVV, strlen(#VVV))==0 && ( expr[strlen(#VVV)] == ',' || expr[strlen(#VVV)] == '\0' )){ \
320             rpnp[steps].op = VV; \
321             expr+=strlen(#VVV); \
322         }
323
324 #define match_op_param(VV,VVV) \
325         else if (sscanf(expr, #VVV "(" DEF_NAM_FMT ")",vname) == 1) { \
326           int length = 0; \
327           if ((length = strlen(#VVV)+strlen(vname)+2, \
328               expr[length] == ',' || expr[length] == '\0') ) { \
329              rpnp[steps].op = VV; \
330              rpnp[steps].ptr = (*lookup)(key_hash,vname); \
331              if (rpnp[steps].ptr < 0) { \
332                            free(rpnp); \
333                            return NULL; \
334                          } else expr+=length; \
335           } \
336         }
337
338         match_op(OP_ADD, +)
339             match_op(OP_SUB, -)
340             match_op(OP_MUL, *)
341             match_op(OP_DIV, /)
342             match_op(OP_MOD, %)
343             match_op(OP_SIN, SIN)
344             match_op(OP_COS, COS)
345             match_op(OP_LOG, LOG)
346             match_op(OP_FLOOR, FLOOR)
347             match_op(OP_CEIL, CEIL)
348             match_op(OP_EXP, EXP)
349             match_op(OP_DUP, DUP)
350             match_op(OP_EXC, EXC)
351             match_op(OP_POP, POP)
352             match_op(OP_LTIME, LTIME)
353             match_op(OP_LT, LT)
354             match_op(OP_LE, LE)
355             match_op(OP_GT, GT)
356             match_op(OP_GE, GE)
357             match_op(OP_EQ, EQ)
358             match_op(OP_IF, IF)
359             match_op(OP_MIN, MIN)
360             match_op(OP_MAX, MAX)
361             match_op(OP_LIMIT, LIMIT)
362             /* order is important here ! .. match longest first */
363             match_op(OP_UNKN, UNKN)
364             match_op(OP_UN, UN)
365             match_op(OP_NEGINF, NEGINF)
366             match_op(OP_NE, NE)
367             match_op(OP_COUNT, COUNT)
368             match_op_param(OP_PREV_OTHER, PREV)
369             match_op(OP_PREV, PREV)
370             match_op(OP_INF, INF)
371             match_op(OP_ISINF, ISINF)
372             match_op(OP_NOW, NOW)
373             match_op(OP_TIME, TIME)
374             match_op(OP_ATAN2, ATAN2)
375             match_op(OP_ATAN, ATAN)
376             match_op(OP_SQRT, SQRT)
377             match_op(OP_SORT, SORT)
378             match_op(OP_REV, REV)
379             match_op(OP_TREND, TREND)
380             match_op(OP_TRENDNAN, TRENDNAN)
381             match_op(OP_PREDICT, PREDICT)
382             match_op(OP_PREDICTSIGMA, PREDICTSIGMA)
383             match_op(OP_RAD2DEG, RAD2DEG)
384             match_op(OP_DEG2RAD, DEG2RAD)
385             match_op(OP_AVG, AVG)
386             match_op(OP_ABS, ABS)
387             match_op(OP_ADDNAN, ADDNAN)
388 #undef match_op
389             else if ((sscanf(expr, DEF_NAM_FMT "%n", vname, &pos) == 1)
390                      && ((rpnp[steps].ptr = (*lookup) (key_hash, vname)) !=
391                          -1)) {
392             rpnp[steps].op = OP_VARIABLE;
393             expr += pos;
394         }
395
396         else {
397             setlocale(LC_NUMERIC, old_locale);
398             free(rpnp);
399             return NULL;
400         }
401
402         if (*expr == 0)
403             break;
404         if (*expr == ',')
405             expr++;
406         else {
407             setlocale(LC_NUMERIC, old_locale);
408             free(rpnp);
409             return NULL;
410         }
411     }
412     rpnp[steps + 1].op = OP_END;
413     setlocale(LC_NUMERIC, old_locale);
414     return rpnp;
415 }
416
417 void rpnstack_init(
418     rpnstack_t *rpnstack)
419 {
420     rpnstack->s = NULL;
421     rpnstack->dc_stacksize = 0;
422     rpnstack->dc_stackblock = 100;
423 }
424
425 void rpnstack_free(
426     rpnstack_t *rpnstack)
427 {
428     if (rpnstack->s != NULL)
429         free(rpnstack->s);
430     rpnstack->dc_stacksize = 0;
431 }
432
433 static int rpn_compare_double(
434     const void *x,
435     const void *y)
436 {
437     double    diff = *((const double *) x) - *((const double *) y);
438
439     return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
440 }
441
442 /* rpn_calc: run the RPN calculator; also performs variable substitution;
443  * moved and modified from data_calc() originally included in rrd_graph.c 
444  * arguments:
445  * rpnp : an array of RPN operators (including variable references)
446  * rpnstack : the initialized stack
447  * data_idx : when data_idx is a multiple of rpnp.step, the rpnp.data pointer
448  *   is advanced by rpnp.ds_cnt; used only for variable substitution
449  * output : an array of output values; OP_PREV assumes this array contains
450  *   the "previous" value at index position output_idx-1; the definition of
451  *   "previous" depends on the calling environment
452  * output_idx : an index into the output array in which to store the output
453  *   of the RPN calculator
454  * returns: -1 if the computation failed (also calls rrd_set_error)
455  *           0 on success
456  */
457 short rpn_calc(
458     rpnp_t *rpnp,
459     rpnstack_t *rpnstack,
460     long data_idx,
461     rrd_value_t *output,
462     int output_idx)
463 {
464     int       rpi;
465     long      stptr = -1;
466
467     /* process each op from the rpn in turn */
468     for (rpi = 0; rpnp[rpi].op != OP_END; rpi++) {
469         /* allocate or grow the stack */
470         if (stptr + 5 > rpnstack->dc_stacksize) {
471             /* could move this to a separate function */
472             rpnstack->dc_stacksize += rpnstack->dc_stackblock;
473             rpnstack->s = (double*)rrd_realloc(rpnstack->s,
474                                       (rpnstack->dc_stacksize) *
475                                       sizeof(*(rpnstack->s)));
476             if (rpnstack->s == NULL) {
477                 rrd_set_error("RPN stack overflow");
478                 return -1;
479             }
480         }
481 #define stackunderflow(MINSIZE)                         \
482         if(stptr<MINSIZE){                              \
483             rrd_set_error("RPN stack underflow");       \
484             return -1;                                  \
485         }
486
487         switch (rpnp[rpi].op) {
488         case OP_NUMBER:
489             rpnstack->s[++stptr] = rpnp[rpi].val;
490             break;
491         case OP_VARIABLE:
492         case OP_PREV_OTHER:
493             /* Sanity check: VDEFs shouldn't make it here */
494             if (rpnp[rpi].ds_cnt == 0) {
495                 rrd_set_error("VDEF made it into rpn_calc... aborting");
496                 return -1;
497             } else {
498                 /* make sure we pull the correct value from
499                  * the *.data array. Adjust the pointer into
500                  * the array acordingly. Advance the ptr one
501                  * row in the rra (skip over non-relevant
502                  * data sources)
503                  */
504                 if (rpnp[rpi].op == OP_VARIABLE) {
505                     rpnstack->s[++stptr] = *(rpnp[rpi].data);
506                 } else {
507                     if ((output_idx) <= 0) {
508                         rpnstack->s[++stptr] = DNAN;
509                     } else {
510                         rpnstack->s[++stptr] =
511                             *(rpnp[rpi].data - rpnp[rpi].ds_cnt);
512                     }
513
514                 }
515                 if (data_idx % rpnp[rpi].step == 0) {
516                     rpnp[rpi].data += rpnp[rpi].ds_cnt;
517                 }
518             }
519             break;
520         case OP_COUNT:
521             rpnstack->s[++stptr] = (output_idx + 1);    /* Note: Counter starts at 1 */
522             break;
523         case OP_PREV:
524             if ((output_idx) <= 0) {
525                 rpnstack->s[++stptr] = DNAN;
526             } else {
527                 rpnstack->s[++stptr] = output[output_idx - 1];
528             }
529             break;
530         case OP_UNKN:
531             rpnstack->s[++stptr] = DNAN;
532             break;
533         case OP_INF:
534             rpnstack->s[++stptr] = DINF;
535             break;
536         case OP_NEGINF:
537             rpnstack->s[++stptr] = -DINF;
538             break;
539         case OP_NOW:
540             rpnstack->s[++stptr] = (double) time(NULL);
541             break;
542         case OP_TIME:
543             /* HACK: this relies on the data_idx being the time,
544              ** which the within-function scope is unaware of */
545             rpnstack->s[++stptr] = (double) data_idx;
546             break;
547         case OP_LTIME:
548             rpnstack->s[++stptr] =
549                 (double) tzoffset(data_idx) + (double) data_idx;
550             break;
551         case OP_ADD:
552             stackunderflow(1);
553             rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
554                 + rpnstack->s[stptr];
555             stptr--;
556             break;
557         case OP_ADDNAN:
558             stackunderflow(1);
559             if (isnan(rpnstack->s[stptr - 1])) {
560                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
561             } else if (isnan(rpnstack->s[stptr])) {
562                 /* NOOP */
563                 /* rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]; */
564             } else {
565                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
566                     + rpnstack->s[stptr];
567             }
568
569             stptr--;
570             break;
571         case OP_SUB:
572             stackunderflow(1);
573             rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
574                 - rpnstack->s[stptr];
575             stptr--;
576             break;
577         case OP_MUL:
578             stackunderflow(1);
579             rpnstack->s[stptr - 1] = (rpnstack->s[stptr - 1])
580                 * (rpnstack->s[stptr]);
581             stptr--;
582             break;
583         case OP_DIV:
584             stackunderflow(1);
585             rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
586                 / rpnstack->s[stptr];
587             stptr--;
588             break;
589         case OP_MOD:
590             stackunderflow(1);
591             rpnstack->s[stptr - 1] = fmod(rpnstack->s[stptr - 1]
592                                           , rpnstack->s[stptr]);
593             stptr--;
594             break;
595         case OP_SIN:
596             stackunderflow(0);
597             rpnstack->s[stptr] = sin(rpnstack->s[stptr]);
598             break;
599         case OP_ATAN:
600             stackunderflow(0);
601             rpnstack->s[stptr] = atan(rpnstack->s[stptr]);
602             break;
603         case OP_RAD2DEG:
604             stackunderflow(0);
605             rpnstack->s[stptr] = 57.29577951 * rpnstack->s[stptr];
606             break;
607         case OP_DEG2RAD:
608             stackunderflow(0);
609             rpnstack->s[stptr] = 0.0174532952 * rpnstack->s[stptr];
610             break;
611         case OP_ATAN2:
612             stackunderflow(1);
613             rpnstack->s[stptr - 1] = atan2(rpnstack->s[stptr - 1],
614                                            rpnstack->s[stptr]);
615             stptr--;
616             break;
617         case OP_COS:
618             stackunderflow(0);
619             rpnstack->s[stptr] = cos(rpnstack->s[stptr]);
620             break;
621         case OP_CEIL:
622             stackunderflow(0);
623             rpnstack->s[stptr] = ceil(rpnstack->s[stptr]);
624             break;
625         case OP_FLOOR:
626             stackunderflow(0);
627             rpnstack->s[stptr] = floor(rpnstack->s[stptr]);
628             break;
629         case OP_LOG:
630             stackunderflow(0);
631             rpnstack->s[stptr] = log(rpnstack->s[stptr]);
632             break;
633         case OP_DUP:
634             stackunderflow(0);
635             rpnstack->s[stptr + 1] = rpnstack->s[stptr];
636             stptr++;
637             break;
638         case OP_POP:
639             stackunderflow(0);
640             stptr--;
641             break;
642         case OP_EXC:
643             stackunderflow(1);
644             {
645                 double    dummy;
646
647                 dummy = rpnstack->s[stptr];
648                 rpnstack->s[stptr] = rpnstack->s[stptr - 1];
649                 rpnstack->s[stptr - 1] = dummy;
650             }
651             break;
652         case OP_EXP:
653             stackunderflow(0);
654             rpnstack->s[stptr] = exp(rpnstack->s[stptr]);
655             break;
656         case OP_LT:
657             stackunderflow(1);
658             if (isnan(rpnstack->s[stptr - 1]));
659             else if (isnan(rpnstack->s[stptr]))
660                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
661             else
662                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] <
663                     rpnstack->s[stptr] ? 1.0 : 0.0;
664             stptr--;
665             break;
666         case OP_LE:
667             stackunderflow(1);
668             if (isnan(rpnstack->s[stptr - 1]));
669             else if (isnan(rpnstack->s[stptr]))
670                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
671             else
672                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] <=
673                     rpnstack->s[stptr] ? 1.0 : 0.0;
674             stptr--;
675             break;
676         case OP_GT:
677             stackunderflow(1);
678             if (isnan(rpnstack->s[stptr - 1]));
679             else if (isnan(rpnstack->s[stptr]))
680                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
681             else
682                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] >
683                     rpnstack->s[stptr] ? 1.0 : 0.0;
684             stptr--;
685             break;
686         case OP_GE:
687             stackunderflow(1);
688             if (isnan(rpnstack->s[stptr - 1]));
689             else if (isnan(rpnstack->s[stptr]))
690                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
691             else
692                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] >=
693                     rpnstack->s[stptr] ? 1.0 : 0.0;
694             stptr--;
695             break;
696         case OP_NE:
697             stackunderflow(1);
698             if (isnan(rpnstack->s[stptr - 1]));
699             else if (isnan(rpnstack->s[stptr]))
700                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
701             else
702                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] ==
703                     rpnstack->s[stptr] ? 0.0 : 1.0;
704             stptr--;
705             break;
706         case OP_EQ:
707             stackunderflow(1);
708             if (isnan(rpnstack->s[stptr - 1]));
709             else if (isnan(rpnstack->s[stptr]))
710                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
711             else
712                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] ==
713                     rpnstack->s[stptr] ? 1.0 : 0.0;
714             stptr--;
715             break;
716         case OP_IF:
717             stackunderflow(2);
718             rpnstack->s[stptr - 2] = (isnan(rpnstack->s[stptr - 2])
719                                       || rpnstack->s[stptr - 2] ==
720                                       0.0) ? rpnstack->s[stptr] : rpnstack->
721                 s[stptr - 1];
722             stptr--;
723             stptr--;
724             break;
725         case OP_MIN:
726             stackunderflow(1);
727             if (isnan(rpnstack->s[stptr - 1]));
728             else if (isnan(rpnstack->s[stptr]))
729                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
730             else if (rpnstack->s[stptr - 1] > rpnstack->s[stptr])
731                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
732             stptr--;
733             break;
734         case OP_MAX:
735             stackunderflow(1);
736             if (isnan(rpnstack->s[stptr - 1]));
737             else if (isnan(rpnstack->s[stptr]))
738                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
739             else if (rpnstack->s[stptr - 1] < rpnstack->s[stptr])
740                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
741             stptr--;
742             break;
743         case OP_LIMIT:
744             stackunderflow(2);
745             if (isnan(rpnstack->s[stptr - 2]));
746             else if (isnan(rpnstack->s[stptr - 1]))
747                 rpnstack->s[stptr - 2] = rpnstack->s[stptr - 1];
748             else if (isnan(rpnstack->s[stptr]))
749                 rpnstack->s[stptr - 2] = rpnstack->s[stptr];
750             else if (rpnstack->s[stptr - 2] < rpnstack->s[stptr - 1])
751                 rpnstack->s[stptr - 2] = DNAN;
752             else if (rpnstack->s[stptr - 2] > rpnstack->s[stptr])
753                 rpnstack->s[stptr - 2] = DNAN;
754             stptr -= 2;
755             break;
756         case OP_UN:
757             stackunderflow(0);
758             rpnstack->s[stptr] = isnan(rpnstack->s[stptr]) ? 1.0 : 0.0;
759             break;
760         case OP_ISINF:
761             stackunderflow(0);
762             rpnstack->s[stptr] = isinf(rpnstack->s[stptr]) ? 1.0 : 0.0;
763             break;
764         case OP_SQRT:
765             stackunderflow(0);
766             rpnstack->s[stptr] = sqrt(rpnstack->s[stptr]);
767             break;
768         case OP_SORT:
769             stackunderflow(0);
770             {
771                 int       spn = (int) rpnstack->s[stptr--];
772
773                 stackunderflow(spn - 1);
774                 qsort(rpnstack->s + stptr - spn + 1, spn, sizeof(double),
775                       rpn_compare_double);
776             }
777             break;
778         case OP_REV:
779             stackunderflow(0);
780             {
781                 int       spn = (int) rpnstack->s[stptr--];
782                 double   *p, *q;
783
784                 stackunderflow(spn - 1);
785
786                 p = rpnstack->s + stptr - spn + 1;
787                 q = rpnstack->s + stptr;
788                 while (p < q) {
789                     double    x = *q;
790
791                     *q-- = *p;
792                     *p++ = x;
793                 }
794             }
795             break;
796         case OP_PREDICT:
797         case OP_PREDICTSIGMA:
798             stackunderflow(2);
799             {
800                 /* the local averaging window (similar to trend, but better here, as we get better statistics thru numbers)*/
801                 int   locstepsize = rpnstack->s[--stptr];
802                 /* the number of shifts and range-checking*/
803                 int     shifts = rpnstack->s[--stptr];
804                 stackunderflow(shifts);
805                 // handle negative shifts special
806                 if (shifts<0) {
807                     stptr--;
808                 } else {
809                     stptr-=shifts;
810                 }
811                 /* the real calculation */
812                 double val=DNAN;
813                 /* the info on the datasource */
814                 time_t  dsstep = (time_t) rpnp[rpi - 1].step;
815                 int    dscount = rpnp[rpi - 1].ds_cnt;
816                 int   locstep = (int)ceil((float)locstepsize/(float)dsstep);
817
818                 /* the sums */
819                 double    sum = 0;
820                 double    sum2 = 0;
821                 int       count = 0;
822                 /* now loop for each position */
823                 int doshifts=shifts;
824                 if (shifts<0) { doshifts=-shifts; }
825                 for(int loop=0;loop<doshifts;loop++) {
826                     /* calculate shift step */
827                     int shiftstep=1;
828                     if (shifts<0) {
829                         shiftstep = loop*rpnstack->s[stptr];
830                     } else { 
831                         shiftstep = rpnstack->s[stptr+loop]; 
832                     }
833                     if(shiftstep <0) {
834                         rrd_set_error("negative shift step not allowed: %i",shiftstep);
835                         return -1;
836                     }
837                     shiftstep=(int)ceil((float)shiftstep/(float)dsstep);
838                     /* loop all local shifts */
839                     for(int i=0;i<=locstep;i++) {
840                         /* now calculate offset into data-array - relative to output_idx*/
841                         int offset=shiftstep+i;
842                         /* and process if we have index 0 of above */
843                         if ((offset>=0)&&(offset<output_idx)) {
844                             /* get the value */
845                             val =rpnp[rpi - 1].data[-dscount * offset];
846                             /* and handle the non NAN case only*/
847                             if (! isnan(val)) {
848                                 sum+=val;
849                                 sum2+=val*val;
850                                 count++;
851                             }
852                         }
853                     }
854                 }
855                 /* do the final calculations */
856                 val=DNAN;
857                 if (rpnp[rpi].op == OP_PREDICT) {  /* the average */
858                     if (count>0) {
859                         val = sum/(double)count;
860                     } 
861                 } else {
862                     if (count>1) { /* the sigma case */
863                         val=count*sum2-sum*sum;
864                         if (val<0) {
865                             val=DNAN;
866                         } else {
867                             val=sqrt(val/((float)count*((float)count-1.0)));
868                         }
869                     }
870                 }
871                 rpnstack->s[stptr] = val;
872             }
873             break;
874         case OP_TREND:
875         case OP_TRENDNAN:
876             stackunderflow(1);
877             if ((rpi < 2) || (rpnp[rpi - 2].op != OP_VARIABLE)) {
878                 rrd_set_error("malformed trend arguments");
879                 return -1;
880             } else {
881                 time_t    dur = (time_t) rpnstack->s[stptr];
882                 time_t    step = (time_t) rpnp[rpi - 2].step;
883
884                 if (output_idx > (int) ceil((float) dur / (float) step)) {
885                     int       ignorenan = (rpnp[rpi].op == OP_TREND);
886                     double    accum = 0.0;
887                     int       i = 0;
888                     int       count = 0;
889
890                     do {
891                         double    val =
892                             rpnp[rpi - 2].data[rpnp[rpi - 2].ds_cnt * i--];
893                         if (ignorenan || !isnan(val)) {
894                             accum += val;
895                             ++count;
896                         }
897
898                         dur -= step;
899                     } while (dur > 0);
900
901                     rpnstack->s[--stptr] =
902                         (count == 0) ? DNAN : (accum / count);
903                 } else
904                     rpnstack->s[--stptr] = DNAN;
905             }
906             break;
907         case OP_AVG:
908             stackunderflow(0);
909             {
910                 int       i = (int) rpnstack->s[stptr--];
911                 double    sum = 0;
912                 int       count = 0;
913
914                 stackunderflow(i - 1);
915                 while (i > 0) {
916                     double    val = rpnstack->s[stptr--];
917
918                     i--;
919                     if (isnan(val)) {
920                         continue;
921                     }
922                     count++;
923                     sum += val;
924                 }
925                 /* now push the result back on stack */
926                 if (count > 0) {
927                     rpnstack->s[++stptr] = sum / count;
928                 } else {
929                     rpnstack->s[++stptr] = DNAN;
930                 }
931             }
932             break;
933         case OP_ABS:
934             stackunderflow(0);
935             rpnstack->s[stptr] = fabs(rpnstack->s[stptr]);
936             break;
937         case OP_END:
938             break;
939         }
940 #undef stackunderflow
941     }
942     if (stptr != 0) {
943         rrd_set_error("RPN final stack size != 1");
944         return -1;
945     }
946
947     output[output_idx] = rpnstack->s[0];
948     return 0;
949 }
950
951 /* figure out what the local timezone offset for any point in
952    time was. Return it in seconds */
953 int tzoffset(
954     time_t now)
955 {
956     int       gm_sec, gm_min, gm_hour, gm_yday, gm_year,
957         l_sec, l_min, l_hour, l_yday, l_year;
958     struct tm t;
959     int       off;
960
961     gmtime_r(&now, &t);
962     gm_sec = t.tm_sec;
963     gm_min = t.tm_min;
964     gm_hour = t.tm_hour;
965     gm_yday = t.tm_yday;
966     gm_year = t.tm_year;
967     localtime_r(&now, &t);
968     l_sec = t.tm_sec;
969     l_min = t.tm_min;
970     l_hour = t.tm_hour;
971     l_yday = t.tm_yday;
972     l_year = t.tm_year;
973     off =
974         (l_sec - gm_sec) + (l_min - gm_min) * 60 + (l_hour - gm_hour) * 3600;
975     if (l_yday > gm_yday || l_year > gm_year) {
976         off += 24 * 3600;
977     } else if (l_yday < gm_yday || l_year < gm_year) {
978         off -= 24 * 3600;
979     }
980     return off;
981 }