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