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