Errors are treated as false during the expression evaluation
[sip-router] / route.c
1 /*
2  * $Id$
3  *
4  * SIP routing engine
5  *
6  *
7  * Copyright (C) 2001-2003 FhG Fokus
8  *
9  * This file is part of ser, a free SIP server.
10  *
11  * ser is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version
15  *
16  * For a license to use the ser software under conditions
17  * other than those described here, or to purchase support for this
18  * software, please contact iptel.org by e-mail at the following addresses:
19  *    info@iptel.org
20  *
21  * ser is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program; if not, write to the Free Software
28  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29  *
30  * History:
31  * --------
32  *  2003-01-28  scratchpad removed, src_port introduced (jiri)
33  *  2003-02-28  scratchpad compatibility abandoned (jiri)
34  *  2003-03-10  updated to the new module exports format (andrei)
35  *  2003-03-19  replaced all mallocs/frees w/ pkg_malloc/pkg_free (andrei)
36  *  2003-04-01  added dst_port, proto, af; renamed comp_port to comp_no,
37  *               inlined all the comp_* functions (andrei)
38  *  2003-04-05  s/reply_route/failure_route, onreply_route introduced (jiri)
39  *  2003-05-23  comp_ip fixed, now it will resolve its operand and compare
40  *              the ip with all the addresses (andrei)
41  *  2003-10-10  added more operators support to comp_* (<,>,<=,>=,!=) (andrei)
42  *  2004-10-19  added from_uri & to_uri (andrei)
43  *  2005-12-12  added retcode support (anrei)
44  *  2005-12-19  select framework (mma)
45  *  2006-01-30  removed rec. protection from eval_expr (andrei)
46  *  2006-02-06  added named route tables (andrei)
47  *  2008-04-14  (expr1 != expr2) is evaluated true if at least one of
48  *              the expressions does not exist (Miklos)
49  *  2008-04-23  errors are treated as false during expression evaluation
50  *              unless the operator is DIFF_OP (Miklos)
51  */
52
53
54 #include <stdlib.h>
55 #include <sys/types.h>
56 #include <regex.h>
57 #include <netdb.h>
58 #include <string.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <arpa/inet.h>
62 #include <netdb.h>
63
64 #include "route.h"
65 #include "forward.h"
66 #include "dprint.h"
67 #include "proxy.h"
68 #include "action.h"
69 #include "sr_module.h"
70 #include "ip_addr.h"
71 #include "resolve.h"
72 #include "socket_info.h"
73 #include "parser/parse_uri.h"
74 #include "parser/parse_from.h"
75 #include "parser/parse_to.h"
76 #include "mem/mem.h"
77 #include "select.h"
78 #include "onsend.h"
79 #include "str_hash.h"
80 #include "ut.h"
81
82 #define RT_HASH_SIZE    8 /* route names hash */
83
84 /* main routing script table  */
85 struct route_list main_rt;
86 struct route_list onreply_rt;
87 struct route_list failure_rt;
88 struct route_list branch_rt;
89 struct route_list onsend_rt;
90
91
92
93 inline static void destroy_rlist(struct route_list* rt)
94 {
95         struct str_hash_entry* e;
96         struct str_hash_entry* tmp;
97
98         if (rt->rlist){
99                 pkg_free(rt->rlist);
100                 rt->rlist=0;
101                 rt->entries=0;
102         }
103         if (rt->names.table){
104                 clist_foreach_safe(rt->names.table, e, tmp, next){
105                         pkg_free(e);
106                 }
107                 pkg_free(rt->names.table);
108                 rt->names.table=0;
109                 rt->names.size=0;
110         }
111 }
112
113
114
115 void destroy_routes()
116 {
117         destroy_rlist(&main_rt);
118         destroy_rlist(&onreply_rt);
119         destroy_rlist(&failure_rt);
120         destroy_rlist(&branch_rt);
121 }
122
123
124
125 /* adds route name -> i mapping
126  * WARNING: it doesn't check for pre-existing routes 
127  * return -1 on error, route index on success
128  */
129 static int route_add(struct route_list* rt, char* name, int i)
130 {
131         struct str_hash_entry* e;
132         
133         e=pkg_malloc(sizeof(struct str_hash_entry));
134         if (e==0){
135                 LOG(L_CRIT, "ERROR: route_add: out of memory\n");
136                 goto error;
137         }
138         e->key.s=name;
139         e->key.len=strlen(name);
140         e->flags=0;
141         e->u.n=i;
142         str_hash_add(&rt->names, e);
143         return 0;
144 error:
145         return -1;
146 }
147
148
149
150 /* returns -1 on error, 0 on success */
151 inline  static int init_rlist(char* r_name, struct route_list* rt,
152                                                                 int n_entries, int hash_size)
153 {
154                 rt->rlist=pkg_malloc(sizeof(struct action*)*n_entries);
155                 if (rt->rlist==0){ 
156                         LOG(L_CRIT, "ERROR: failed to allocate \"%s\" route tables: " 
157                                         "out of memory\n", r_name); 
158                         goto error; 
159                 }
160                 memset(rt->rlist, 0 , sizeof(struct action*)*n_entries);
161                 rt->idx=1; /* idx=0 == default == reserved */
162                 rt->entries=n_entries;
163                 if (str_hash_alloc(&rt->names, hash_size)<0){
164                         LOG(L_CRIT, "ERROR: \"%s\" route table: failed to alloc hash\n",
165                                         r_name);
166                         goto error;
167                 }
168                 str_hash_init(&rt->names);
169                 route_add(rt, "0", 0);  /* default route */
170                 
171                 return 0;
172 error:
173                 return -1;
174 }
175
176
177
178 /* init route tables */
179 int init_routes()
180 {
181         if (init_rlist("main", &main_rt, RT_NO, RT_HASH_SIZE)<0)
182                 goto error;
183         if (init_rlist("on_reply", &onreply_rt, ONREPLY_RT_NO, RT_HASH_SIZE)<0)
184                 goto error;
185         if (init_rlist("failure", &failure_rt, FAILURE_RT_NO, RT_HASH_SIZE)<0)
186                 goto error;
187         if (init_rlist("branch", &branch_rt, BRANCH_RT_NO, RT_HASH_SIZE)<0)
188                 goto error;
189         if (init_rlist("on_send", &onsend_rt, ONSEND_RT_NO, RT_HASH_SIZE)<0)
190                 goto error;
191         return 0;
192 error:
193         destroy_routes();
194         return -1;
195 }
196
197
198
199 static inline int route_new_list(struct route_list* rt)
200 {
201         int ret;
202         struct action** tmp;
203         
204         ret=-1;
205         if (rt->idx >= rt->entries){
206                 tmp=pkg_realloc(rt->rlist, 2*rt->entries*sizeof(struct action*));
207                 if (tmp==0){
208                         LOG(L_CRIT, "ERROR: route_new_list: out of memory\n");
209                         goto end;
210                 }
211                 /* init the newly allocated memory chunk */
212                 memset(&tmp[rt->entries], 0, rt->entries*sizeof(struct action*));
213                 rt->rlist=tmp;
214                 rt->entries*=2;
215         }
216         if (rt->idx<rt->entries){
217                 ret=rt->idx;
218                 rt->idx++;
219         }
220 end:
221         return ret;
222 }
223
224
225
226
227 /* 
228  * if the "name" route already exists, return its index, else
229  * create a new empty route
230  * return route index in rt->rlist or -1 on error
231  */
232 int route_get(struct route_list* rt, char* name)
233 {
234         int len;
235         struct str_hash_entry* e;
236         int i;
237         
238         len=strlen(name);
239         /* check if exists an non empty*/
240         e=str_hash_get(&rt->names, name, len);
241         if (e){
242                 i=e->u.n;
243         }else{
244                 i=route_new_list(rt);
245                 if (i==-1) goto error;
246                 if (route_add(rt, name, i)<0){
247                         goto error;
248                 }
249         }
250         return i;
251 error:
252         return -1;
253 }
254
255
256
257 /* 
258  * if the "name" route already exists, return its index, else
259  * return error
260  * return route index in rt->rlist or -1 on error
261  */
262 int route_lookup(struct route_list* rt, char* name)
263 {
264         int len;
265         struct str_hash_entry* e;
266         
267         len=strlen(name);
268         /* check if exists an non empty*/
269         e=str_hash_get(&rt->names, name, len);
270         if (e){
271                 return e->u.n;
272         }else{
273                 return -1;
274         }
275 }
276
277
278
279 static int fix_actions(struct action* a); /*fwd declaration*/
280
281
282 /* traverses an expr tree and compiles the REs where necessary)
283  * returns: 0 for ok, <0 if errors */
284 static int fix_expr(struct expr* exp)
285 {
286         regex_t* re;
287         int ret;
288
289         ret=E_BUG;
290         if (exp==0){
291                 LOG(L_CRIT, "BUG: fix_expr: null pointer\n");
292                 return E_BUG;
293         }
294         if (exp->type==EXP_T){
295                 switch(exp->op){
296                         case LOGAND_OP:
297                         case LOGOR_OP:
298                                                 if ((ret=fix_expr(exp->l.expr))!=0)
299                                                         return ret;
300                                                 ret=fix_expr(exp->r.expr);
301                                                 break;
302                         case NOT_OP:
303                                                 ret=fix_expr(exp->l.expr);
304                                                 break;
305                         default:
306                                                 LOG(L_CRIT, "BUG: fix_expr: unknown op %d\n",
307                                                                 exp->op);
308                 }
309         }else if (exp->type==ELEM_T){
310                         if (exp->op==MATCH_OP){
311                                      /* right side either has to be string, in which case
312                                       * we turn it into regular expression, or it is regular
313                                       * expression already. In that case we do nothing
314                                       */
315                                 if (exp->r_type==STRING_ST){
316                                         re=(regex_t*)pkg_malloc(sizeof(regex_t));
317                                         if (re==0){
318                                                 LOG(L_CRIT, "ERROR: fix_expr: memory allocation"
319                                                                 " failure\n");
320                                                 return E_OUT_OF_MEM;
321                                         }
322                                         if (regcomp(re, (char*) exp->r.param,
323                                                                 REG_EXTENDED|REG_NOSUB|REG_ICASE) ){
324                                                 LOG(L_CRIT, "ERROR: fix_expr : bad re \"%s\"\n",
325                                                                         (char*) exp->r.param);
326                                                 pkg_free(re);
327                                                 return E_BAD_RE;
328                                         }
329                                         /* replace the string with the re */
330                                         pkg_free(exp->r.param);
331                                         exp->r.re=re;
332                                         exp->r_type=RE_ST;
333                                 }else if (exp->r_type!=RE_ST && exp->r_type != AVP_ST && exp->r_type != SELECT_ST){
334                                         LOG(L_CRIT, "BUG: fix_expr : invalid type for match\n");
335                                         return E_BUG;
336                                 }
337                         }
338                         if (exp->l_type==ACTION_O){
339                                 ret=fix_actions((struct action*)exp->r.param);
340                                 if (ret!=0){
341                                         LOG(L_CRIT, "ERROR: fix_expr : fix_actions error\n");
342                                         return ret;
343                                 }
344                         }
345                              /* Calculate lengths of strings */
346                         if (exp->l_type==STRING_ST) {
347                                 int len;
348                                 if (exp->l.string) len = strlen(exp->l.string);
349                                 else len = 0;
350                                 exp->l.str.s = exp->l.string;
351                                 exp->l.str.len = len;
352                         }
353                         if (exp->r_type==STRING_ST) {
354                                 int len;
355                                 if (exp->r.string) len = strlen(exp->r.string);
356                                 else len = 0;
357                                 exp->r.str.s = exp->r.string;
358                                 exp->r.str.len = len;
359                         }
360                         if (exp->l_type==SELECT_O) {
361                                 if ((ret=resolve_select(exp->l.select)) < 0) {
362                                         BUG("Unable to resolve select\n");
363                                         print_select(exp->l.select);
364                                         return ret;
365                                 }
366                         }
367                         if ((exp->r_type==SELECT_O)||(exp->r_type==SELECT_ST)) {
368                                 if ((ret=resolve_select(exp->r.select)) < 0) {
369                                         BUG("Unable to resolve select\n");
370                                         print_select(exp->l.select);
371                                         return ret;
372                                 }
373                         }
374                         ret=0;
375         }
376         return ret;
377 }
378
379
380
381 /* adds the proxies in the proxy list & resolves the hostnames */
382 /* returns 0 if ok, <0 on error */
383 static int fix_actions(struct action* a)
384 {
385         struct action *t;
386         struct proxy_l* p;
387         char *tmp;
388         int ret;
389         cmd_export_t* cmd;
390         str s;
391         struct hostent* he;
392         struct ip_addr ip;
393         struct socket_info* si;
394
395         if (a==0){
396                 LOG(L_CRIT,"BUG: fix_actions: null pointer\n");
397                 return E_BUG;
398         }
399         for(t=a; t!=0; t=t->next){
400                 switch(t->type){
401                         case FORWARD_T:
402                         case FORWARD_TLS_T:
403                         case FORWARD_TCP_T:
404                         case FORWARD_UDP_T:
405                         case SEND_T:
406                         case SEND_TCP_T:
407                                         switch(t->val[0].type){
408                                                 case IP_ST:
409                                                         tmp=strdup(ip_addr2a(
410                                                                                 (struct ip_addr*)t->val[0].u.data));
411                                                         if (tmp==0){
412                                                                 LOG(L_CRIT, "ERROR: fix_actions:"
413                                                                                 "memory allocation failure\n");
414                                                                 return E_OUT_OF_MEM;
415                                                         }
416                                                         t->val[0].type=STRING_ST;
417                                                         t->val[0].u.string=tmp;
418                                                         /* no break */
419                                                 case STRING_ST:
420                                                         s.s = t->val[0].u.string;
421                                                         s.len = strlen(s.s);
422                                                         p=add_proxy(&s, t->val[1].u.number, 0); /* FIXME proto*/
423                                                         if (p==0) return E_BAD_ADDRESS;
424                                                         t->val[0].u.data=p;
425                                                         t->val[0].type=PROXY_ST;
426                                                         break;
427                                                 case URIHOST_ST:
428                                                         break;
429                                                 default:
430                                                         LOG(L_CRIT, "BUG: fix_actions: invalid type"
431                                                                         "%d (should be string or number)\n",
432                                                                                 t->type);
433                                                         return E_BUG;
434                                         }
435                                         break;
436                         case IF_T:
437                                 if (t->val[0].type!=EXPR_ST){
438                                         LOG(L_CRIT, "BUG: fix_actions: invalid subtype"
439                                                                 "%d for if (should be expr)\n",
440                                                                 t->val[0].type);
441                                         return E_BUG;
442                                 }else if( (t->val[1].type!=ACTIONS_ST)&&(t->val[1].type!=NOSUBTYPE) ){
443                                         LOG(L_CRIT, "BUG: fix_actions: invalid subtype"
444                                                                 "%d for if() {...} (should be action)\n",
445                                                                 t->val[1].type);
446                                         return E_BUG;
447                                 }else if( (t->val[2].type!=ACTIONS_ST)&&(t->val[2].type!=NOSUBTYPE) ){
448                                         LOG(L_CRIT, "BUG: fix_actions: invalid subtype"
449                                                                 "%d for if() {} else{...}(should be action)\n",
450                                                                 t->val[2].type);
451                                         return E_BUG;
452                                 }
453                                 if (t->val[0].u.data){
454                                         if ((ret=fix_expr((struct expr*)t->val[0].u.data))<0)
455                                                 return ret;
456                                 }
457                                 if ( (t->val[1].type==ACTIONS_ST)&&(t->val[1].u.data) ){
458                                         if ((ret=fix_actions((struct action*)t->val[1].u.data))<0)
459                                                 return ret;
460                                 }
461                                 if ( (t->val[2].type==ACTIONS_ST)&&(t->val[2].u.data) ){
462                                                 if ((ret=fix_actions((struct action*)t->val[2].u.data))<0)
463                                                 return ret;
464                                 }
465                                 break;
466
467                         case ASSIGN_T:
468                         case ADD_T:
469                                 if (t->val[0].type != AVP_ST) {
470                                         LOG(L_CRIT, "BUG: fix_actions: Invalid left side of assignment\n");
471                                         return E_BUG;
472                                 }
473                                 if (t->val[0].u.attr->type & AVP_CLASS_DOMAIN) {
474                                         LOG(L_ERR, "ERROR: You cannot change domain attributes from the script, they are read-only\n");
475                                         return E_BUG;
476                                 } else if (t->val[0].u.attr->type & AVP_CLASS_GLOBAL) {
477                                         LOG(L_ERR, "ERROR: You cannot change global attributes from the script, they are read-only\n");
478                                         return E_BUG;
479                                 }
480
481                                 if (t->val[1].type == ACTION_ST && t->val[1].u.data) {
482                                         if ((ret = fix_actions((struct action*)t->val[1].u.data)) < 0) {
483                                                 return ret;
484                                         }
485                                 } else if (t->val[1].type == EXPR_ST && t->val[1].u.data) {
486                                         if ((ret = fix_expr((struct expr*)t->val[1].u.data)) < 0) {
487                                                 return ret;
488                                         }
489                                 } else if (t->val[1].type == STRING_ST) {
490                                         int len;
491                                         len = strlen(t->val[1].u.data);
492                                         t->val[1].u.str.s = t->val[1].u.data;
493                                         t->val[1].u.str.len = len;
494                                 } else if (t->val[1].type == SELECT_ST) {
495                                         if ((ret=resolve_select(t->val[1].u.select)) < 0) {
496                                                 BUG("Unable to resolve select\n");
497                                                 print_select(t->val[1].u.select);
498                                                 return ret;
499                                         }
500                                 }
501                                 break;
502
503                         case MODULE_T:
504                                 cmd = t->val[0].u.data;
505                                 if (cmd && cmd->fixup) {
506                                         int i;
507                                         DBG("fixing %s()\n", cmd->name);
508                                         /* type cast NUMBER to STRING, old modules may expect all STRING params during fixup */
509                                         for (i=0; i<t->val[1].u.number; i++) {
510                                                 if (t->val[i+2].type == NUMBER_ST) {
511                                                         char buf[30];
512                                                         snprintf(buf, sizeof(buf)-1, "%ld", t->val[i+2].u.number);
513                                                         /* fixup currently requires string pkg_malloc-aed */
514                                                         t->val[i+2].u.string = pkg_malloc(strlen(buf)+1);
515                                                         if (!t->val[i+2].u.string) {
516                                                                 LOG(L_CRIT, "ERROR: cannot translate NUMBER to STRING\n");
517                                                                 return E_OUT_OF_MEM;
518                                                         }
519                                                         strcpy(t->val[i+2].u.string, buf);
520                                                         t->val[i+2].type = STRING_ST;
521                                                 }
522                                         }
523                                         for (i=0; i<t->val[1].u.number; i++) {
524                                                 void *p;
525                                                 p = t->val[i+2].u.data;
526                                                 ret = cmd->fixup(&t->val[i+2].u.data, i+1);
527                                                 if (t->val[i+2].u.data != p)
528                                                         t->val[i+2].type = MODFIXUP_ST;
529                                                 if (ret < 0)
530                                                         return ret;
531                                         }
532                                 }
533                                 break;
534                         case FORCE_SEND_SOCKET_T:
535                                 if (t->val[0].type!=SOCKID_ST){
536                                         LOG(L_CRIT, "BUG: fix_actions: invalid subtype"
537                                                                 "%d for force_send_socket\n",
538                                                                 t->val[0].type);
539                                         return E_BUG;
540                                 }
541                                 he=resolvehost(((struct socket_id*)t->val[0].u.data)->name);
542                                 if (he==0){
543                                         LOG(L_ERR, "ERROR: fix_actions: force_send_socket:"
544                                                                 " could not resolve %s\n",
545                                                         ((struct socket_id*)t->val[0].u.data)->name);
546                                         return E_BAD_ADDRESS;
547                                 }
548                                 hostent2ip_addr(&ip, he, 0);
549                                 si=find_si(&ip, ((struct socket_id*)t->val[0].u.data)->port,
550                                                                 ((struct socket_id*)t->val[0].u.data)->proto);
551                                 if (si==0){
552                                         LOG(L_ERR, "ERROR: fix_actions: bad force_send_socket"
553                                                         " argument: %s:%d (ser doesn't listen on it)\n",
554                                                         ((struct socket_id*)t->val[0].u.data)->name,
555                                                         ((struct socket_id*)t->val[0].u.data)->port);
556                                         return E_BAD_ADDRESS;
557                                 }
558                                 t->val[0].u.data=si;
559                                 t->val[0].type=SOCKETINFO_ST;
560                                 break;
561                 }
562         }
563         return 0;
564 }
565
566
567 /* Compare parameters as ordinary numbers
568  *
569  * Left and right operands can be either numbers or
570  * attributes. If either of the attributes if of string type then the length of
571  * its value will be used.
572  */
573 inline static int comp_num(int op, long left, int rtype, union exp_op* r)
574 {
575         int_str val;
576         avp_t* avp;
577         long right;
578
579         if (rtype == AVP_ST) {
580                 avp = search_avp_by_index(r->attr->type, r->attr->name, &val, r->attr->index);
581                 if (avp && !(avp->flags & AVP_VAL_STR)) right = val.n;
582                 else return (op == DIFF_OP);
583         } else if (rtype == NUMBER_ST) {
584                 right = r->numval;
585         } else {
586                 LOG(L_CRIT, "BUG: comp_num: Invalid right operand (%d)\n", rtype);
587                 return E_BUG;
588         }
589
590         switch (op){
591         case EQUAL_OP: return (long)left == (long)right;
592         case DIFF_OP:  return (long)left != (long)right;
593         case GT_OP:    return (long)left >  (long)right;
594         case LT_OP:    return (long)left <  (long)right;
595         case GTE_OP:   return (long)left >= (long)right;
596         case LTE_OP:   return (long)left <= (long)right;
597         default:
598                 LOG(L_CRIT, "BUG: comp_num: unknown operator: %d\n", op);
599                 return E_BUG;
600         }
601 }
602
603 /*
604  * Compare given string "left" with right side of expression
605  */
606 inline static int comp_str(int op, str* left, int rtype, union exp_op* r, struct sip_msg* msg)
607 {
608         str* right;
609         int_str val;
610         str v;
611         avp_t* avp;
612         int ret;
613         char backup;
614         regex_t* re;
615         unsigned int l;
616         
617         right=0; /* warning fix */
618
619         if (rtype == AVP_ST) {
620                 avp = search_avp_by_index(r->attr->type, r->attr->name, &val, r->attr->index);
621                 if (avp && (avp->flags & AVP_VAL_STR)) right = &val.s;
622                 else return (op == DIFF_OP);
623         } else if (rtype == SELECT_ST) {
624                 ret = run_select(&v, r->select, msg);
625                 if (ret != 0) return (op == DIFF_OP); /* Not found or error */
626                 right = &v;
627         } else if ((op == MATCH_OP && rtype == RE_ST)) {
628         } else if (op != MATCH_OP && rtype == STRING_ST) {
629                 right = &r->str;
630         } else if (rtype == NUMBER_ST) {
631                         /* "123" > 100 is not allowed by cfg.y rules
632                          * but can happen as @select or $avp evaluation
633                          * $test > 10
634                          * the right operator MUST be number to do the conversion
635                          */
636                 if (str2int(left,&l) < 0)
637                         goto error;
638                 return comp_num(op, l, rtype, r);
639         } else {
640                 LOG(L_CRIT, "BUG: comp_str: Bad type %d, "
641                     "string or RE expected\n", rtype);
642                 goto error;
643         }
644
645         ret=-1;
646         switch(op){
647                 case EQUAL_OP:
648                         if (left->len != right->len) return 0;
649                         ret=(strncasecmp(left->s, right->s, left->len)==0);
650                         break;
651                 case DIFF_OP:
652                         if (left->len != right->len) return 1;
653                         ret = (strncasecmp(left->s, right->s, left->len)!=0);
654                         break;
655                 case MATCH_OP:
656                              /* this is really ugly -- we put a temporary zero-terminating
657                               * character in the original string; that's because regexps
658                               * take 0-terminated strings and our messages are not
659                               * zero-terminated; it should not hurt as long as this function
660                               * is applied to content of pkg mem, which is always the case
661                               * with calls from route{}; the same goes for fline in reply_route{};
662                               *
663                               * also, the received function should always give us an extra
664                               * character, into which we can put the 0-terminator now;
665                               * an alternative would be allocating a new piece of memory,
666                               * which might be too slow
667                               * -jiri
668                               *
669                               * janakj: AVPs are zero terminated too so this is not problem either
670                               */
671                         backup=left->s[left->len];
672                         if (backup) left->s[left->len]='\0';
673                         if (rtype == AVP_ST || rtype == SELECT_ST) {
674                                      /* For AVPs we need to compile the RE on the fly */
675                                 re=(regex_t*)pkg_malloc(sizeof(regex_t));
676                                 if (re==0){
677                                         LOG(L_CRIT, "ERROR: comp_strstr: memory allocation"
678                                             " failure\n");
679                                         left->s[left->len] = backup;
680                                         goto error;
681                                 }
682                                 if (regcomp(re, right->s, REG_EXTENDED|REG_NOSUB|REG_ICASE)) {
683                                         pkg_free(re);
684                                         left->s[left->len] = backup;
685                                         goto error;
686                                 }
687                                 ret=(regexec(re, left->s, 0, 0, 0)==0);
688                                 regfree(re);
689                                 pkg_free(re);
690                         } else {
691                                 ret=(regexec(r->re, left->s, 0, 0, 0)==0);
692                         }
693                         if (backup) left->s[left->len] = backup;
694                         break;
695                 default:
696                         LOG(L_CRIT, "BUG: comp_str: unknown op %d\n", op);
697                         goto error;
698         }
699         return ret;
700
701 error:
702         return (op == DIFF_OP) ? 1 : -1;
703 }
704
705
706 /* eval_elem helping function, returns str op param */
707 inline static int comp_string(int op, char* left, int rtype, union exp_op* r)
708 {
709         int ret;
710         int_str val;
711         avp_t* avp;
712         char* right;
713
714         ret=-1;
715         right=0;
716         if (rtype == AVP_ST) {
717                 avp = search_avp_by_index(r->attr->type, r->attr->name, &val, r->attr->index);
718                 if (avp && (avp->flags & AVP_VAL_STR)) right = val.s.s;
719                 else return (op == DIFF_OP);
720         } else if (rtype == STRING_ST) {
721                 right = r->str.s;
722         }
723
724         switch(op){
725                 case EQUAL_OP:
726                         if (rtype!=STRING_ST && rtype!=AVP_ST){
727                                 LOG(L_CRIT, "BUG: comp_string: bad type %d, "
728                                                 "string or attr expected\n", rtype);
729                                 goto error;
730                         }
731                         ret=(strcasecmp(left, right)==0);
732                         break;
733                 case DIFF_OP:
734                         if (rtype!=STRING_ST && rtype!=AVP_ST){
735                                 LOG(L_CRIT, "BUG: comp_string: bad type %d, "
736                                                 "string or attr expected\n", rtype);
737                                 goto error;
738                         }
739                         ret=(strcasecmp(left, right)!=0);
740                         break;
741                 case MATCH_OP:
742                         if (rtype!=RE_ST){
743                                 LOG(L_CRIT, "BUG: comp_string: bad type %d, "
744                                                 " RE expected\n", rtype);
745                                 goto error;
746                         }
747                         ret=(regexec(r->re, left, 0, 0, 0)==0);
748                         break;
749                 default:
750                         LOG(L_CRIT, "BUG: comp_string: unknown op %d\n", op);
751                         goto error;
752         }
753         return ret;
754
755 error:
756         return -1;
757 }
758
759
760 inline static int comp_avp(int op, avp_spec_t* spec, int rtype, union exp_op* r, struct sip_msg* msg)
761 {
762         avp_t* avp;
763         int_str val;
764         union exp_op num_val;
765         str tmp;
766         unsigned int uval;
767
768         if (spec->type & AVP_INDEX_ALL) {
769                 avp = search_first_avp(spec->type & ~AVP_INDEX_ALL, spec->name, NULL, NULL);
770                 return (avp!=0);
771         }
772         avp = search_avp_by_index(spec->type, spec->name, &val, spec->index);
773         if (!avp) return (op == DIFF_OP);
774
775         switch(op) {
776         case NO_OP:
777                 if (avp->flags & AVP_VAL_STR) {
778                         return val.s.len!=0;
779                 } else {
780                         return val.n != 0;
781                 }
782                 break;
783
784         case BINOR_OP:
785                 return (val.n | r->numval)!=0;
786                 break;
787
788         case BINAND_OP:
789                 return (val.n & r->numval)!=0;
790                 break;
791         }
792
793         if (avp->flags & AVP_VAL_STR) {
794                 return comp_str(op, &val.s, rtype, r, msg);
795         } else {
796                 switch(rtype){
797                         case NUMBER_ST:
798                                 return comp_num(op, val.n, rtype, r);
799                         case STRING_ST:
800                                 tmp.s=r->string;
801                                 tmp.len=strlen(r->string);
802                                 if (str2int(&tmp, &uval)<0){
803                                         LOG(L_WARN, "WARNING: comp_avp: cannot convert string value"
804                                                                 " to int (%s)\n", ZSW(r->string));
805                                         goto error;
806                                 }
807                                 num_val.numval=uval;
808                                 return comp_num(op, val.n, NUMBER_ST, &num_val);
809                         case STR_ST:
810                                 if (str2int(&r->str, &uval)<0){
811                                         LOG(L_WARN, "WARNING: comp_avp: cannot convert str value"
812                                                                 " to int (%.*s)\n", r->str.len, ZSW(r->str.s));
813                                         goto error;
814                                 }
815                                 num_val.numval=uval;
816                                 return comp_num(op, val.n, NUMBER_ST, &num_val);
817                         default:
818                                 LOG(L_CRIT, "BUG: comp_avp: invalid type for numeric avp "
819                                                         "comparison (%d)\n", rtype);
820                                 goto error;
821                 }
822         }
823 error:
824         return (op == DIFF_OP) ? 1 : -1;
825 }
826
827 /*
828  * Left side of expression was select
829  */
830 inline static int comp_select(int op, select_t* sel, int rtype, union exp_op* r, struct sip_msg* msg)
831 {
832         int ret;
833         str val;
834         char empty_str=0;
835
836         ret = run_select(&val, sel, msg);
837         if (ret != 0) return (op == DIFF_OP);
838
839         switch(op) {
840         case NO_OP: return (val.len>0);
841         case BINOR_OP:
842         case BINAND_OP:
843                 ERR("Binary operators cannot be used with string selects\n");
844                 return -1;
845         }
846         if (val.len==0) {
847                 /* make sure the string pointer uses accessible memory range
848                  * the comp_str function might dereference it
849                  */
850                 val.s=&empty_str;
851         }
852         return comp_str(op, &val, rtype, r, msg);
853 }
854
855 /* check_self wrapper -- it checks also for the op */
856 inline static int check_self_op(int op, str* s, unsigned short p)
857 {
858         int ret;
859
860         ret=check_self(s, p, 0);
861         switch(op){
862                 case EQUAL_OP:
863                         break;
864                 case DIFF_OP:
865                         ret=(ret > 0) ? 0 : 1;
866                         break;
867                 default:
868                         LOG(L_CRIT, "BUG: check_self_op: invalid operator %d\n", op);
869                         ret=-1;
870         }
871         return ret;
872 }
873
874
875 /* eval_elem helping function, returns an op param */
876 inline static int comp_ip(int op, struct ip_addr* ip, int rtype, union exp_op* r)
877 {
878         struct hostent* he;
879         char ** h;
880         int ret;
881         str tmp;
882
883         ret=-1;
884         switch(rtype){
885                 case NET_ST:
886                         switch(op){
887                                 case EQUAL_OP:
888                                         ret=(matchnet(ip, r->net)==1);
889                                         break;
890                                 case DIFF_OP:
891                                         ret=(matchnet(ip, r->net)!=1);
892                                         break;
893                                 default:
894                                         goto error_op;
895                         }
896                         break;
897                 case AVP_ST:
898                 case STRING_ST:
899                 case RE_ST:
900                         switch(op){
901                                 case EQUAL_OP:
902                                 case MATCH_OP:
903                                         /* 1: compare with ip2str*/
904                                         ret=comp_string(op, ip_addr2a(ip), rtype, r);
905                                         if (ret==1) break;
906                                         /* 2: resolve (name) & compare w/ all the ips */
907                                         if (rtype==STRING_ST){
908                                                 he=resolvehost(r->str.s);
909                                                 if (he==0){
910                                                         DBG("comp_ip: could not resolve %s\n",
911                                                             r->str.s);
912                                                 }else if (he->h_addrtype==ip->af){
913                                                         for(h=he->h_addr_list;(ret!=1)&& (*h); h++){
914                                                                 ret=(memcmp(ip->u.addr, *h, ip->len)==0);
915                                                         }
916                                                         if (ret==1) break;
917                                                 }
918                                         }
919                                         /* 3: (slow) rev dns the address
920                                         * and compare with all the aliases
921                                         * !!??!! review: remove this? */
922                                         if (unlikely((received_dns & DO_REV_DNS) && 
923                                                         ((he=rev_resolvehost(ip))!=0) )){
924                                                 /*  compare with primary host name */
925                                                 ret=comp_string(op, he->h_name, rtype, r);
926                                                 /* compare with all the aliases */
927                                                 for(h=he->h_aliases; (ret!=1) && (*h); h++){
928                                                         ret=comp_string(op, *h, rtype, r);
929                                                 }
930                                         }else{
931                                                 ret=0;
932                                         }
933                                         break;
934                                 case DIFF_OP:
935                                         ret=(comp_ip(EQUAL_OP, ip, rtype, r) > 0) ? 0 : 1;
936                                         break;
937                                 default:
938                                         goto error_op;
939                         }
940                         break;
941                 case MYSELF_ST: /* check if it's one of our addresses*/
942                         tmp.s=ip_addr2a(ip);
943                         tmp.len=strlen(tmp.s);
944                         ret=check_self_op(op, &tmp, 0);
945                         break;
946                 default:
947                         LOG(L_CRIT, "BUG: comp_ip: invalid type for "
948                                                 " src_ip or dst_ip (%d)\n", rtype);
949                         ret=-1;
950         }
951         return ret;
952 error_op:
953         LOG(L_CRIT, "BUG: comp_ip: invalid operator %d\n", op);
954         return -1;
955
956 }
957
958
959 /* returns: 0/1 (false/true) or -1 on error */
960 inline static int eval_elem(struct run_act_ctx* h, struct expr* e, 
961                                                                 struct sip_msg* msg)
962 {
963         struct sip_uri uri;
964         int ret;
965         struct onsend_info* snd_inf;
966         struct ip_addr ip;
967         ret=E_BUG;
968
969         if (e->type!=ELEM_T){
970                 LOG(L_CRIT," BUG: eval_elem: invalid type\n");
971                 goto error;
972         }
973         switch(e->l_type){
974         case METHOD_O:
975                 ret=comp_str(e->op, &msg->first_line.u.request.method,
976                              e->r_type, &e->r, msg);
977                 break;
978         case URI_O:
979                 if(msg->new_uri.s) {
980                         if (e->r_type==MYSELF_ST){
981                                 if (parse_sip_msg_uri(msg)<0) ret=-1;
982                                 else ret=check_self_op(e->op, &msg->parsed_uri.host,
983                                                        msg->parsed_uri.port_no?
984                                                        msg->parsed_uri.port_no:SIP_PORT);
985                         }else{
986                                 ret=comp_str(e->op, &msg->new_uri,
987                                              e->r_type, &e->r, msg);
988                         }
989                 }else{
990                         if (e->r_type==MYSELF_ST){
991                                 if (parse_sip_msg_uri(msg)<0) ret=-1;
992                                 else ret=check_self_op(e->op, &msg->parsed_uri.host,
993                                                        msg->parsed_uri.port_no?
994                                                        msg->parsed_uri.port_no:SIP_PORT);
995                         }else{
996                                 ret=comp_str(e->op, &msg->first_line.u.request.uri,
997                                              e->r_type, &e->r, msg);
998                         }
999                 }
1000                 break;
1001
1002         case FROM_URI_O:
1003                 if (parse_from_header(msg)!=0){
1004                         LOG(L_ERR, "ERROR: eval_elem: bad or missing"
1005                             " From: header\n");
1006                         goto error;
1007                 }
1008                 if (e->r_type==MYSELF_ST){
1009                         if (parse_uri(get_from(msg)->uri.s, get_from(msg)->uri.len,
1010                                       &uri) < 0){
1011                                 LOG(L_ERR, "ERROR: eval_elem: bad uri in From:\n");
1012                                 goto error;
1013                         }
1014                         ret=check_self_op(e->op, &uri.host,
1015                                           uri.port_no?uri.port_no:SIP_PORT);
1016                 }else{
1017                         ret=comp_str(e->op, &get_from(msg)->uri,
1018                                      e->r_type, &e->r, msg);
1019                 }
1020                 break;
1021
1022         case TO_URI_O:
1023                 if ((msg->to==0) && ((parse_headers(msg, HDR_TO_F, 0)==-1) ||
1024                                      (msg->to==0))){
1025                         LOG(L_ERR, "ERROR: eval_elem: bad or missing"
1026                             " To: header\n");
1027                         goto error;
1028                 }
1029                      /* to content is parsed automatically */
1030                 if (e->r_type==MYSELF_ST){
1031                         if (parse_uri(get_to(msg)->uri.s, get_to(msg)->uri.len,
1032                                       &uri) < 0){
1033                                 LOG(L_ERR, "ERROR: eval_elem: bad uri in To:\n");
1034                                 goto error;
1035                         }
1036                         ret=check_self_op(e->op, &uri.host,
1037                                           uri.port_no?uri.port_no:SIP_PORT);
1038                 }else{
1039                         ret=comp_str(e->op, &get_to(msg)->uri,
1040                                      e->r_type, &e->r, msg);
1041                 }
1042                 break;
1043
1044         case SRCIP_O:
1045                 ret=comp_ip(e->op, &msg->rcv.src_ip, e->r_type, &e->r);
1046                 break;
1047
1048         case DSTIP_O:
1049                 ret=comp_ip(e->op, &msg->rcv.dst_ip, e->r_type, &e->r);
1050                 break;
1051
1052         case SNDIP_O:
1053                 snd_inf=get_onsend_info();
1054                 if (snd_inf && snd_inf->send_sock){
1055                         ret=comp_ip(e->op, &snd_inf->send_sock->address, e->r_type, &e->r);
1056                 }else{
1057                         BUG("eval_elem: snd_ip unknown (not in a onsend_route?)\n");
1058                 }
1059                 break;
1060
1061         case TOIP_O:
1062                 snd_inf=get_onsend_info();
1063                 if (snd_inf && snd_inf->to){
1064                         su2ip_addr(&ip, snd_inf->to);
1065                         ret=comp_ip(e->op, &ip, e->r_type, &e->r);
1066                 }else{
1067                         BUG("eval_elem: to_ip unknown (not in a onsend_route?)\n");
1068                 }
1069                 break;
1070
1071         case NUMBER_O:
1072                 ret=!(!e->r.numval); /* !! to transform it in {0,1} */
1073                 break;
1074
1075         case ACTION_O:
1076                 ret=run_actions(h, (struct action*)e->r.param, msg);
1077                 if (ret<=0) ret=0;
1078                 else ret=1;
1079                 break;
1080
1081         case SRCPORT_O:
1082                 ret=comp_num(e->op, (int)msg->rcv.src_port,
1083                              e->r_type, &e->r);
1084                 break;
1085
1086         case DSTPORT_O:
1087                 ret=comp_num(e->op, (int)msg->rcv.dst_port,
1088                              e->r_type, &e->r);
1089                 break;
1090
1091         case SNDPORT_O:
1092                 snd_inf=get_onsend_info();
1093                 if (snd_inf && snd_inf->send_sock){
1094                         ret=comp_num(e->op, (int)snd_inf->send_sock->port_no,
1095                                      e->r_type, &e->r);
1096                 }else{
1097                         BUG("eval_elem: snd_port unknown (not in a onsend_route?)\n");
1098                 }
1099                 break;
1100
1101         case TOPORT_O:
1102                 snd_inf=get_onsend_info();
1103                 if (snd_inf && snd_inf->to){
1104                         ret=comp_num(e->op, (int)su_getport(snd_inf->to),
1105                                      e->r_type, &e->r);
1106                 }else{
1107                         BUG("eval_elem: to_port unknown (not in a onsend_route?)\n");
1108                 }
1109                 break;
1110
1111         case PROTO_O:
1112                 ret=comp_num(e->op, msg->rcv.proto,
1113                              e->r_type, &e->r);
1114                 break;
1115
1116         case SNDPROTO_O:
1117                 snd_inf=get_onsend_info();
1118                 if (snd_inf && snd_inf->send_sock){
1119                         ret=comp_num(e->op, snd_inf->send_sock->proto,
1120                                      e->r_type, &e->r);
1121                 }else{
1122                         BUG("eval_elem: snd_proto unknown (not in a onsend_route?)\n");
1123                 }
1124                 break;
1125
1126         case AF_O:
1127                 ret=comp_num(e->op, (int)msg->rcv.src_ip.af,
1128                              e->r_type, &e->r);
1129                 break;
1130
1131         case SNDAF_O:
1132                 snd_inf=get_onsend_info();
1133                 if (snd_inf && snd_inf->send_sock){
1134                         ret=comp_num(e->op, snd_inf->send_sock->address.af,
1135                                                         e->r_type, &e->r);
1136                 }else{
1137                         BUG("eval_elem: snd_af unknown (not in a onsend_route?)\n");
1138                 }
1139                 break;
1140
1141         case MSGLEN_O:
1142                 if ((snd_inf=get_onsend_info())!=0){
1143                         ret=comp_num(e->op, (int)snd_inf->len,
1144                                         e->r_type, &e->r);
1145                 }else{
1146                         ret=comp_num(e->op, (int)msg->len,
1147                                         e->r_type, &e->r);
1148                 }
1149                 break;
1150
1151         case RETCODE_O:
1152                 ret=comp_num(e->op, h->last_retcode, e->r_type, &e->r);
1153                 break;
1154
1155         case AVP_O:
1156                 ret = comp_avp(e->op, e->l.attr, e->r_type, &e->r, msg);
1157                 break;
1158
1159         case SELECT_O:
1160                 ret = comp_select(e->op, e->l.select, e->r_type, &e->r, msg);
1161                 break;
1162
1163         default:
1164                 LOG(L_CRIT, "BUG: eval_elem: invalid operand %d\n",
1165                     e->l_type);
1166         }
1167         return ret;
1168 error:
1169         return (e->op == DIFF_OP) ? 1 : -1;
1170 }
1171
1172
1173
1174 /* ret= 1/0 (true/false) ,  -1 on error (evaluates as false)*/
1175 int eval_expr(struct run_act_ctx* h, struct expr* e, struct sip_msg* msg)
1176 {
1177         int ret;
1178
1179         if (e->type==ELEM_T){
1180                 ret=eval_elem(h, e, msg);
1181         }else if (e->type==EXP_T){
1182                 switch(e->op){
1183                         case LOGAND_OP:
1184                                 ret=eval_expr(h, e->l.expr, msg);
1185                                 /* if error or false stop evaluating the rest */
1186                                 if (ret <= 0) break;
1187                                 ret=eval_expr(h, e->r.expr, msg); /*ret1 is 1*/
1188                                 break;
1189                         case LOGOR_OP:
1190                                 ret=eval_expr(h, e->l.expr, msg);
1191                                 /* if true stop evaluating the rest */
1192                                 if (ret > 0) break;
1193                                 ret=eval_expr(h, e->r.expr, msg); /* ret1 is 0 */
1194                                 break;
1195                         case NOT_OP:
1196                                 ret=eval_expr(h, e->l.expr, msg);
1197                                 ret=(ret > 0) ? 0 : 1;
1198                                 break;
1199                         default:
1200                                 LOG(L_CRIT, "BUG: eval_expr: unknown op %d\n", e->op);
1201                                 ret=-1;
1202                 }
1203         }else{
1204                 LOG(L_CRIT, "BUG: eval_expr: unknown type %d\n", e->type);
1205                 ret=-1;
1206         }
1207         return ret;
1208 }
1209
1210
1211 /* adds an action list to head; a must be null terminated (last a->next=0))*/
1212 void push(struct action* a, struct action** head)
1213 {
1214         struct action *t;
1215         if (*head==0){
1216                 *head=a;
1217                 return;
1218         }
1219         for (t=*head; t->next;t=t->next);
1220         t->next=a;
1221 }
1222
1223
1224
1225
1226 int add_actions(struct action* a, struct action** head)
1227 {
1228         int ret;
1229
1230         LOG(L_DBG, "add_actions: fixing actions...\n");
1231         if ((ret=fix_actions(a))!=0) goto error;
1232         push(a,head);
1233         return 0;
1234
1235 error:
1236         return ret;
1237 }
1238
1239
1240
1241 static int fix_rl(struct route_list* rt)
1242 {
1243         int i;
1244         int ret;
1245         
1246         for(i=0;i<rt->idx; i++){
1247                 if(rt->rlist[i]){
1248                         if ((ret=fix_actions(rt->rlist[i]))!=0){
1249                                 return ret;
1250                         }
1251                 }
1252         }
1253         return 0;
1254 }
1255
1256
1257
1258 /* fixes all action tables */
1259 /* returns 0 if ok , <0 on error */
1260 int fix_rls()
1261 {
1262         int ret;
1263         
1264         if ((ret=fix_rl(&main_rt))!=0)
1265                 return ret;
1266         if ((ret=fix_rl(&onreply_rt))!=0)
1267                 return ret;
1268         if ((ret=fix_rl(&failure_rt))!=0)
1269                 return ret;
1270         if ((ret=fix_rl(&branch_rt))!=0)
1271                 return ret;
1272         if ((ret=fix_rl(&onsend_rt))!=0)
1273                 return ret;
1274
1275         return 0;
1276 }
1277
1278
1279
1280 static void print_rl(struct route_list* rt, char* name)
1281 {
1282         int j;
1283         
1284         for(j=0; j<rt->entries; j++){
1285                 if (rt->rlist[j]==0){
1286                         if ((j==0) && (rt==&main_rt))
1287                                 DBG("WARNING: the main routing table is empty\n");
1288                         continue;
1289                 }
1290                 DBG("%s routing table %d:\n", name, j);
1291                 print_actions(rt->rlist[j]);
1292                 DBG("\n");
1293         }
1294 }
1295
1296
1297 /* debug function, prints routing tables */
1298 void print_rls()
1299 {
1300         print_rl(&main_rt, "");
1301         print_rl(&onreply_rt, "onreply");
1302         print_rl(&failure_rt, "failure");
1303         print_rl(&branch_rt, "branch");
1304         print_rl(&onsend_rt, "onsend");
1305 }