Blocked 80689, the fix to ael.y; already in trunk.
[asterisk/asterisk.git] / utils / check_expr.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 #include <stdio.h>
20 #include <stddef.h>
21 #include <stdarg.h>
22 #include <string.h>
23 #include <stdlib.h>
24
25 struct ast_channel 
26 {
27         char x; /* basically empty! */
28 };
29
30 #include <../include/asterisk/compat.h>
31 #include <../include/asterisk/ast_expr.h>
32
33 #define AST_API_MODULE 1
34 #include "asterisk/inline_api.h"
35
36 #define AST_API_MODULE 1
37 #include "asterisk/lock.h"
38
39 #include "asterisk/strings.h"
40
41 /* I included this from utils.c, so as not to have everything in that .c
42    file included */
43 /*!
44  * core handler for dynamic strings.
45  * This is not meant to be called directly, but rather through the
46  * various wrapper macros
47  *      ast_str_set(...)
48  *      ast_str_append(...)
49  *      ast_str_set_va(...)
50  *      ast_str_append_va(...)
51  */
52 int __ast_str_helper(struct ast_str **buf, size_t max_len,
53         int append, const char *fmt, va_list ap)
54 {
55         int res, need;
56         int offset = (append && (*buf)->len) ? (*buf)->used : 0;
57
58         if (max_len < 0)
59                 max_len = (*buf)->len;  /* don't exceed the allocated space */
60         /*
61          * Ask vsnprintf how much space we need. Remember that vsnprintf
62          * does not count the final '\0' so we must add 1.
63          */
64         res = vsnprintf((*buf)->str + offset, (*buf)->len - offset, fmt, ap);
65
66         need = res + offset + 1;
67         /*
68          * If there is not enough space and we are below the max length,
69          * reallocate the buffer and return a message telling to retry.
70          */
71         if (need > (*buf)->len && (max_len == 0 || (*buf)->len < max_len) ) {
72                 if (max_len && max_len < need)  /* truncate as needed */
73                         need = max_len;
74                 else if (max_len == 0)  /* if unbounded, give more room for next time */
75                         need += 16 + need/4;
76                 if (ast_str_make_space(buf, need)) {
77                         return AST_DYNSTR_BUILD_FAILED;
78                 }
79                 (*buf)->str[offset] = '\0';     /* Truncate the partial write. */
80
81                 /* va_end() and va_start() must be done before calling
82                  * vsnprintf() again. */
83                 return AST_DYNSTR_BUILD_RETRY;
84         }
85         /* update space used, keep in mind the truncation */
86         (*buf)->used = (res + offset > (*buf)->len) ? (*buf)->len : res + offset;
87
88         return res;
89 }
90
91 static int global_lineno = 1;
92 static int global_expr_count=0;
93 static int global_expr_max_size=0;
94 static int global_expr_tot_size=0;
95 static int global_warn_count=0;
96 static int global_OK_count=0;
97
98 struct varz
99 {
100         char varname[100]; /* a really ultra-simple, space-wasting linked list of var=val data */
101         char varval[1000]; /* if any varname is bigger than 100 chars, or val greater than 1000, then **CRASH** */
102         struct varz *next;
103 };
104
105 struct varz *global_varlist;
106
107 /* Our own version of ast_log, since the expr parser uses it. */
108
109 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...) __attribute__ ((format (printf,5,6)));
110
111 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
112 {
113         va_list vars;
114         va_start(vars,fmt);
115         
116         printf("LOG: lev:%d file:%s  line:%d func: %s  ",
117                    level, file, line, function);
118         vprintf(fmt, vars);
119         fflush(stdout);
120         va_end(vars);
121 }
122 void ast_register_file_version(const char *file, const char *version);
123 void ast_unregister_file_version(const char *file);
124
125 char *find_var(const char *varname);
126 void set_var(const char *varname, const char *varval);
127 unsigned int check_expr(char* buffer, char* error_report);
128 int check_eval(char *buffer, char *error_report);
129 void parse_file(const char *fname);
130
131 void ast_register_file_version(const char *file, const char *version)
132 {
133 }
134
135 void ast_unregister_file_version(const char *file)
136 {
137 }
138
139 char *find_var(const char *varname) /* the list should be pretty short, if there's any list at all */
140 {
141         struct varz *t;
142         for (t= global_varlist; t; t = t->next) {
143                 if (!strcmp(t->varname, varname)) {
144                         return t->varval;
145                 }
146         }
147         return 0;
148 }
149
150 void set_var(const char *varname, const char *varval);
151
152 void set_var(const char *varname, const char *varval)
153 {
154         struct varz *t = (struct varz*)calloc(1,sizeof(struct varz));
155         if (!t)
156                 return;
157         strcpy(t->varname, varname);
158         strcpy(t->varval, varval);
159         t->next = global_varlist;
160         global_varlist = t;
161 }
162
163 unsigned int check_expr(char* buffer, char* error_report)
164 {
165         char* cp;
166         unsigned int warn_found = 0;
167
168         error_report[0] = 0;
169         
170         for (cp = buffer; *cp; ++cp)
171         {
172                 switch (*cp)
173                 {
174                         case '"':
175                                 /* skip to the other end */
176                                 while (*(++cp) && *cp != '"') ;
177
178                                 if (*cp == 0)
179                                 {
180                                         fprintf(stderr,
181                                                 "Trouble? Unterminated double quote found at line %d\n",
182                                                 global_lineno);
183                                 }
184                                 break;
185                                 
186                         case '>':
187                         case '<':
188                         case '!':
189                                 if (   (*(cp + 1) == '=')
190                                         && ( ( (cp > buffer) && (*(cp - 1) != ' ') ) || (*(cp + 2) != ' ') ) )
191                                 {
192                                         char msg[200];
193                                         snprintf(msg,
194                                                 sizeof(msg),
195                                                 "WARNING: line %d: '%c%c' operator not separated by spaces. This may lead to confusion. You may wish to use double quotes to quote the grouping it is in. Please check!\n",
196                                                 global_lineno, *cp, *(cp + 1));
197                                         strcat(error_report, msg);
198                                         ++global_warn_count;
199                                         ++warn_found;
200                                 }
201                                 break;
202                                 
203                         case '|':
204                         case '&':
205                         case '=':
206                         case '+':
207                         case '-':
208                         case '*':
209                         case '/':
210                         case '%':
211                         case '?':
212                         case ':':
213                                 if ( ( (cp > buffer) && (*(cp - 1) != ' ') ) || (*(cp + 1) != ' ') )
214                                 {
215                                         char msg[200];
216                                         snprintf(msg,
217                                                 sizeof(msg),
218                                                 "WARNING: line %d: '%c' operator not separated by spaces. This may lead to confusion. You may wish to use double quotes to quote the grouping it is in. Please check!\n",
219                                                 global_lineno, *cp );
220                                         strcat(error_report, msg);
221                                         ++global_warn_count;
222                                         ++warn_found;
223                                 }
224                                 break;
225                 }
226         }
227
228         return warn_found;
229 }
230
231 int check_eval(char *buffer, char *error_report);
232
233 struct ast_custom_function *ast_custom_function_find(const char *name);
234
235 struct ast_custom_function *ast_custom_function_find(const char *name)
236 {
237         return 0;
238 }
239
240 int check_eval(char *buffer, char *error_report)
241 {
242         char *cp, *ep;
243         char s[4096];
244         char evalbuf[80000];
245         int result;
246
247         error_report[0] = 0;
248         ep = evalbuf;
249
250         for (cp=buffer;*cp;cp++) {
251                 if (*cp == '$' && *(cp+1) == '{') {
252                         int brack_lev = 1;
253                         char *xp= cp+2;
254                         
255                         while (*xp) {
256                                 if (*xp == '{')
257                                         brack_lev++;
258                                 else if (*xp == '}')
259                                         brack_lev--;
260                                 
261                                 if (brack_lev == 0)
262                                         break;
263                                 xp++;
264                         }
265                         if (*xp == '}') {
266                                 char varname[200];
267                                 char *val;
268                                 
269                                 strncpy(varname,cp+2, xp-cp-2);
270                                 varname[xp-cp-2] = 0;
271                                 cp = xp;
272                                 val = find_var(varname);
273                                 if (val) {
274                                         char *z = val;
275                                         while (*z)
276                                                 *ep++ = *z++;
277                                 }
278                                 else {
279                                         *ep++ = '5';  /* why not */
280                                         *ep++ = '5';
281                                         *ep++ = '5';
282                                 }
283                         }
284                         else {
285                                 printf("Unterminated variable reference at line %d\n", global_lineno);
286                                 *ep++ = *cp;
287                         }
288                 }
289                 else if (*cp == '\\') {
290                         /* braindead simple elim of backslash */
291                         cp++;
292                         *ep++ = *cp;
293                 }
294                 else
295                         *ep++ = *cp;
296         }
297         *ep++ = 0;
298
299         /* now, run the test */
300         result = ast_expr(evalbuf, s, sizeof(s),NULL);
301         if (result) {
302                 sprintf(error_report,"line %d, evaluation of $[ %s ] result: %s\n", global_lineno, evalbuf, s);
303                 return 1;
304         } else {
305                 sprintf(error_report,"line %d, evaluation of $[ %s ] result: ****SYNTAX ERROR****\n", global_lineno, evalbuf);
306                 return 1;
307         }
308 }
309
310
311 void parse_file(const char *fname);
312
313 void parse_file(const char *fname)
314 {
315         FILE *f = fopen(fname,"r");
316         FILE *l = fopen("expr2_log","w");
317         int c1;
318         char last_char= 0;
319         char buffer[30000]; /* I sure hope no expr gets this big! */
320         
321         if (!f) {
322                 fprintf(stderr,"Couldn't open %s for reading... need an extensions.conf file to parse!\n",fname);
323                 exit(20);
324         }
325         if (!l) {
326                 fprintf(stderr,"Couldn't open 'expr2_log' file for writing... please fix and re-run!\n");
327                 exit(21);
328         }
329         
330         global_lineno = 1;
331         
332         while ((c1 = fgetc(f)) != EOF) {
333                 if (c1 == '\n')
334                         global_lineno++;
335                 else if (c1 == '[') {
336                         if (last_char == '$') {
337                                 /* bingo, an expr */
338                                 int bracklev = 1;
339                                 int bufcount = 0;
340                                 int retval;
341                                 char error_report[30000];
342                                 
343                                 while ((c1 = fgetc(f)) != EOF) {
344                                         if (c1 == '[')
345                                                 bracklev++;
346                                         else if (c1 == ']')
347                                                 bracklev--;
348                                         if (c1 == '\n') {
349                                                 fprintf(l, "ERROR-- A newline in an expression? Weird! ...at line %d\n", global_lineno);
350                                                 fclose(f);
351                                                 fclose(l);
352                                                 printf("--- ERROR --- A newline in the middle of an expression at line %d!\n", global_lineno);
353                                         }
354                                         
355                                         if (bracklev == 0)
356                                                 break;
357                                         buffer[bufcount++] = c1;
358                                 }
359                                 if (c1 == EOF) {
360                                         fprintf(l, "ERROR-- End of File Reached in the middle of an Expr at line %d\n", global_lineno);
361                                         fclose(f);
362                                         fclose(l);
363                                         printf("--- ERROR --- EOF reached in middle of an expression at line %d!\n", global_lineno);
364                                         exit(22);
365                                 }
366                                 
367                                 buffer[bufcount] = 0;
368                                 /* update stats */
369                                 global_expr_tot_size += bufcount;
370                                 global_expr_count++;
371                                 if (bufcount > global_expr_max_size)
372                                         global_expr_max_size = bufcount;
373                                 
374                                 retval = check_expr(buffer, error_report); /* check_expr should bump the warning counter */
375                                 if (retval != 0) {
376                                         /* print error report */
377                                         printf("Warning(s) at line %d, expression: $[%s]; see expr2_log file for details\n", 
378                                                    global_lineno, buffer);
379                                         fprintf(l, "%s", error_report);
380                                 }
381                                 else {
382                                         printf("OK -- $[%s] at line %d\n", buffer, global_lineno);
383                                         global_OK_count++;
384                                 }
385                                 error_report[0] = 0;
386                                 retval = check_eval(buffer, error_report);
387                                 fprintf(l, "%s", error_report);
388                         }
389                 }
390                 last_char = c1;
391         }
392         printf("Summary:\n  Expressions detected: %d\n  Expressions OK:  %d\n  Total # Warnings:   %d\n  Longest Expr:   %d chars\n  Ave expr len:  %d chars\n",
393                    global_expr_count,
394                    global_OK_count,
395                    global_warn_count,
396                    global_expr_max_size,
397                    (global_expr_count) ? global_expr_tot_size/global_expr_count : 0);
398         
399         fclose(f);
400         fclose(l);
401 }
402
403
404 int main(int argc,char **argv)
405 {
406         int argc1;
407         char *eq;
408         
409         if (argc < 2) {
410                 printf("check_expr -- a program to look thru extensions.conf files for $[...] expressions,\n");
411                 printf("              and run them thru the parser, looking for problems\n");
412                 printf("Hey-- give me a path to an extensions.conf file!\n");
413                 printf(" You can also follow the file path with a series of variable decls,\n");
414                 printf("     of the form, varname=value, each separated from the next by spaces.\n");
415                 printf("     (this might allow you to avoid division by zero messages, check that math\n");
416                 printf("      is being done correctly, etc.)\n");
417                 printf(" Note that messages about operators not being surrounded by spaces is merely to alert\n");
418                 printf("  you to possible problems where you might be expecting those operators as part of a string.\n");
419         printf("  (to include operators in a string, wrap with double quotes!)\n");
420                 
421                 exit(19);
422         }
423         global_varlist = 0;
424         for (argc1=2;argc1 < argc; argc1++) {
425                 if ((eq = strchr(argv[argc1],'='))) {
426                         *eq = 0;
427                         set_var(argv[argc1],eq+1);
428                 }
429         }
430
431         /* parse command args for x=y and set varz */
432         
433         parse_file(argv[1]);
434         return 0;
435 }