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