- core sctp support
[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_SCTP_T:
405                         case FORWARD_UDP_T:
406                         case SEND_T:
407                         case SEND_TCP_T:
408                                         switch(t->val[0].type){
409                                                 case IP_ST:
410                                                         tmp=strdup(ip_addr2a(
411                                                                                 (struct ip_addr*)t->val[0].u.data));
412                                                         if (tmp==0){
413                                                                 LOG(L_CRIT, "ERROR: fix_actions:"
414                                                                                 "memory allocation failure\n");
415                                                                 return E_OUT_OF_MEM;
416                                                         }
417                                                         t->val[0].type=STRING_ST;
418                                                         t->val[0].u.string=tmp;
419                                                         /* no break */
420                                                 case STRING_ST:
421                                                         s.s = t->val[0].u.string;
422                                                         s.len = strlen(s.s);
423                                                         p=add_proxy(&s, t->val[1].u.number, 0); /* FIXME proto*/
424                                                         if (p==0) return E_BAD_ADDRESS;
425                                                         t->val[0].u.data=p;
426                                                         t->val[0].type=PROXY_ST;
427                                                         break;
428                                                 case URIHOST_ST:
429                                                         break;
430                                                 default:
431                                                         LOG(L_CRIT, "BUG: fix_actions: invalid type"
432                                                                         "%d (should be string or number)\n",
433                                                                                 t->type);
434                                                         return E_BUG;
435                                         }
436                                         break;
437                         case IF_T:
438                                 if (t->val[0].type!=EXPR_ST){
439                                         LOG(L_CRIT, "BUG: fix_actions: invalid subtype"
440                                                                 "%d for if (should be expr)\n",
441                                                                 t->val[0].type);
442                                         return E_BUG;
443                                 }else if( (t->val[1].type!=ACTIONS_ST)&&(t->val[1].type!=NOSUBTYPE) ){
444                                         LOG(L_CRIT, "BUG: fix_actions: invalid subtype"
445                                                                 "%d for if() {...} (should be action)\n",
446                                                                 t->val[1].type);
447                                         return E_BUG;
448                                 }else if( (t->val[2].type!=ACTIONS_ST)&&(t->val[2].type!=NOSUBTYPE) ){
449                                         LOG(L_CRIT, "BUG: fix_actions: invalid subtype"
450                                                                 "%d for if() {} else{...}(should be action)\n",
451                                                                 t->val[2].type);
452                                         return E_BUG;
453                                 }
454                                 if (t->val[0].u.data){
455                                         if ((ret=fix_expr((struct expr*)t->val[0].u.data))<0)
456                                                 return ret;
457                                 }
458                                 if ( (t->val[1].type==ACTIONS_ST)&&(t->val[1].u.data) ){
459                                         if ((ret=fix_actions((struct action*)t->val[1].u.data))<0)
460                                                 return ret;
461                                 }
462                                 if ( (t->val[2].type==ACTIONS_ST)&&(t->val[2].u.data) ){
463                                                 if ((ret=fix_actions((struct action*)t->val[2].u.data))<0)
464                                                 return ret;
465                                 }
466                                 break;
467
468                         case ASSIGN_T:
469                         case ADD_T:
470                                 if (t->val[0].type != AVP_ST) {
471                                         LOG(L_CRIT, "BUG: fix_actions: Invalid left side of assignment\n");
472                                         return E_BUG;
473                                 }
474                                 if (t->val[0].u.attr->type & AVP_CLASS_DOMAIN) {
475                                         LOG(L_ERR, "ERROR: You cannot change domain attributes from the script, they are read-only\n");
476                                         return E_BUG;
477                                 } else if (t->val[0].u.attr->type & AVP_CLASS_GLOBAL) {
478                                         LOG(L_ERR, "ERROR: You cannot change global attributes from the script, they are read-only\n");
479                                         return E_BUG;
480                                 }
481
482                                 if (t->val[1].type == ACTION_ST && t->val[1].u.data) {
483                                         if ((ret = fix_actions((struct action*)t->val[1].u.data)) < 0) {
484                                                 return ret;
485                                         }
486                                 } else if (t->val[1].type == EXPR_ST && t->val[1].u.data) {
487                                         if ((ret = fix_expr((struct expr*)t->val[1].u.data)) < 0) {
488                                                 return ret;
489                                         }
490                                 } else if (t->val[1].type == STRING_ST) {
491                                         int len;
492                                         len = strlen(t->val[1].u.data);
493                                         t->val[1].u.str.s = t->val[1].u.data;
494                                         t->val[1].u.str.len = len;
495                                 } else if (t->val[1].type == SELECT_ST) {
496                                         if ((ret=resolve_select(t->val[1].u.select)) < 0) {
497                                                 BUG("Unable to resolve select\n");
498                                                 print_select(t->val[1].u.select);
499                                                 return ret;
500                                         }
501                                 }
502                                 break;
503
504                         case MODULE_T:
505                                 cmd = t->val[0].u.data;
506                                 if (cmd && cmd->fixup) {
507                                         int i;
508                                         DBG("fixing %s()\n", cmd->name);
509                                         /* type cast NUMBER to STRING, old modules may expect all STRING params during fixup */
510                                         for (i=0; i<t->val[1].u.number; i++) {
511                                                 if (t->val[i+2].type == NUMBER_ST) {
512                                                         char buf[30];
513                                                         snprintf(buf, sizeof(buf)-1, "%ld", t->val[i+2].u.number);
514                                                         /* fixup currently requires string pkg_malloc-aed */
515                                                         t->val[i+2].u.string = pkg_malloc(strlen(buf)+1);
516                                                         if (!t->val[i+2].u.string) {
517                                                                 LOG(L_CRIT, "ERROR: cannot translate NUMBER to STRING\n");
518                                                                 return E_OUT_OF_MEM;
519                                                         }
520                                                         strcpy(t->val[i+2].u.string, buf);
521                                                         t->val[i+2].type = STRING_ST;
522                                                 }
523                                         }
524                                         for (i=0; i<t->val[1].u.number; i++) {
525                                                 void *p;
526                                                 p = t->val[i+2].u.data;
527                                                 ret = cmd->fixup(&t->val[i+2].u.data, i+1);
528                                                 if (t->val[i+2].u.data != p)
529                                                         t->val[i+2].type = MODFIXUP_ST;
530                                                 if (ret < 0)
531                                                         return ret;
532                                         }
533                                 }
534                                 break;
535                         case FORCE_SEND_SOCKET_T:
536                                 if (t->val[0].type!=SOCKID_ST){
537                                         LOG(L_CRIT, "BUG: fix_actions: invalid subtype"
538                                                                 "%d for force_send_socket\n",
539                                                                 t->val[0].type);
540                                         return E_BUG;
541                                 }
542                                 he=resolvehost(((struct socket_id*)t->val[0].u.data)->name);
543                                 if (he==0){
544                                         LOG(L_ERR, "ERROR: fix_actions: force_send_socket:"
545                                                                 " could not resolve %s\n",
546                                                         ((struct socket_id*)t->val[0].u.data)->name);
547                                         return E_BAD_ADDRESS;
548                                 }
549                                 hostent2ip_addr(&ip, he, 0);
550                                 si=find_si(&ip, ((struct socket_id*)t->val[0].u.data)->port,
551                                                                 ((struct socket_id*)t->val[0].u.data)->proto);
552                                 if (si==0){
553                                         LOG(L_ERR, "ERROR: fix_actions: bad force_send_socket"
554                                                         " argument: %s:%d (ser doesn't listen on it)\n",
555                                                         ((struct socket_id*)t->val[0].u.data)->name,
556                                                         ((struct socket_id*)t->val[0].u.data)->port);
557                                         return E_BAD_ADDRESS;
558                                 }
559                                 t->val[0].u.data=si;
560                                 t->val[0].type=SOCKETINFO_ST;
561                                 break;
562                 }
563         }
564         return 0;
565 }
566
567
568 /* Compare parameters as ordinary numbers
569  *
570  * Left and right operands can be either numbers or
571  * attributes. If either of the attributes if of string type then the length of
572  * its value will be used.
573  */
574 inline static int comp_num(int op, long left, int rtype, union exp_op* r)
575 {
576         int_str val;
577         avp_t* avp;
578         long right;
579
580         if (rtype == AVP_ST) {
581                 avp = search_avp_by_index(r->attr->type, r->attr->name, &val, r->attr->index);
582                 if (avp && !(avp->flags & AVP_VAL_STR)) right = val.n;
583                 else return (op == DIFF_OP);
584         } else if (rtype == NUMBER_ST) {
585                 right = r->numval;
586         } else {
587                 LOG(L_CRIT, "BUG: comp_num: Invalid right operand (%d)\n", rtype);
588                 return E_BUG;
589         }
590
591         switch (op){
592         case EQUAL_OP: return (long)left == (long)right;
593         case DIFF_OP:  return (long)left != (long)right;
594         case GT_OP:    return (long)left >  (long)right;
595         case LT_OP:    return (long)left <  (long)right;
596         case GTE_OP:   return (long)left >= (long)right;
597         case LTE_OP:   return (long)left <= (long)right;
598         default:
599                 LOG(L_CRIT, "BUG: comp_num: unknown operator: %d\n", op);
600                 return E_BUG;
601         }
602 }
603
604 /*
605  * Compare given string "left" with right side of expression
606  */
607 inline static int comp_str(int op, str* left, int rtype, union exp_op* r, struct sip_msg* msg)
608 {
609         str* right;
610         int_str val;
611         str v;
612         avp_t* avp;
613         int ret;
614         char backup;
615         regex_t* re;
616         unsigned int l;
617         
618         right=0; /* warning fix */
619
620         if (rtype == AVP_ST) {
621                 avp = search_avp_by_index(r->attr->type, r->attr->name, &val, r->attr->index);
622                 if (avp && (avp->flags & AVP_VAL_STR)) right = &val.s;
623                 else return (op == DIFF_OP);
624         } else if (rtype == SELECT_ST) {
625                 ret = run_select(&v, r->select, msg);
626                 if (ret != 0) return (op == DIFF_OP); /* Not found or error */
627                 right = &v;
628         } else if ((op == MATCH_OP && rtype == RE_ST)) {
629         } else if (op != MATCH_OP && rtype == STRING_ST) {
630                 right = &r->str;
631         } else if (rtype == NUMBER_ST) {
632                         /* "123" > 100 is not allowed by cfg.y rules
633                          * but can happen as @select or $avp evaluation
634                          * $test > 10
635                          * the right operator MUST be number to do the conversion
636                          */
637                 if (str2int(left,&l) < 0)
638                         goto error;
639                 return comp_num(op, l, rtype, r);
640         } else {
641                 LOG(L_CRIT, "BUG: comp_str: Bad type %d, "
642                     "string or RE expected\n", rtype);
643                 goto error;
644         }
645
646         ret=-1;
647         switch(op){
648                 case EQUAL_OP:
649                         if (left->len != right->len) return 0;
650                         ret=(strncasecmp(left->s, right->s, left->len)==0);
651                         break;
652                 case DIFF_OP:
653                         if (left->len != right->len) return 1;
654                         ret = (strncasecmp(left->s, right->s, left->len)!=0);
655                         break;
656                 case MATCH_OP:
657                              /* this is really ugly -- we put a temporary zero-terminating
658                               * character in the original string; that's because regexps
659                               * take 0-terminated strings and our messages are not
660                               * zero-terminated; it should not hurt as long as this function
661                               * is applied to content of pkg mem, which is always the case
662                               * with calls from route{}; the same goes for fline in reply_route{};
663                               *
664                               * also, the received function should always give us an extra
665                               * character, into which we can put the 0-terminator now;
666                               * an alternative would be allocating a new piece of memory,
667                               * which might be too slow
668                               * -jiri
669                               *
670                               * janakj: AVPs are zero terminated too so this is not problem either
671                               */
672                         backup=left->s[left->len];
673                         if (backup) left->s[left->len]='\0';
674                         if (rtype == AVP_ST || rtype == SELECT_ST) {
675                                      /* For AVPs we need to compile the RE on the fly */
676                                 re=(regex_t*)pkg_malloc(sizeof(regex_t));
677                                 if (re==0){
678                                         LOG(L_CRIT, "ERROR: comp_strstr: memory allocation"
679                                             " failure\n");
680                                         left->s[left->len] = backup;
681                                         goto error;
682                                 }
683                                 if (regcomp(re, right->s, REG_EXTENDED|REG_NOSUB|REG_ICASE)) {
684                                         pkg_free(re);
685                                         left->s[left->len] = backup;
686                                         goto error;
687                                 }
688                                 ret=(regexec(re, left->s, 0, 0, 0)==0);
689                                 regfree(re);
690                                 pkg_free(re);
691                         } else {
692                                 ret=(regexec(r->re, left->s, 0, 0, 0)==0);
693                         }
694                         if (backup) left->s[left->len] = backup;
695                         break;
696                 default:
697                         LOG(L_CRIT, "BUG: comp_str: unknown op %d\n", op);
698                         goto error;
699         }
700         return ret;
701
702 error:
703         return (op == DIFF_OP) ? 1 : -1;
704 }
705
706
707 /* eval_elem helping function, returns str op param */
708 inline static int comp_string(int op, char* left, int rtype, union exp_op* r)
709 {
710         int ret;
711         int_str val;
712         avp_t* avp;
713         char* right;
714
715         ret=-1;
716         right=0;
717         if (rtype == AVP_ST) {
718                 avp = search_avp_by_index(r->attr->type, r->attr->name, &val, r->attr->index);
719                 if (avp && (avp->flags & AVP_VAL_STR)) right = val.s.s;
720                 else return (op == DIFF_OP);
721         } else if (rtype == STRING_ST) {
722                 right = r->str.s;
723         }
724
725         switch(op){
726                 case EQUAL_OP:
727                         if (rtype!=STRING_ST && rtype!=AVP_ST){
728                                 LOG(L_CRIT, "BUG: comp_string: bad type %d, "
729                                                 "string or attr expected\n", rtype);
730                                 goto error;
731                         }
732                         ret=(strcasecmp(left, right)==0);
733                         break;
734                 case DIFF_OP:
735                         if (rtype!=STRING_ST && rtype!=AVP_ST){
736                                 LOG(L_CRIT, "BUG: comp_string: bad type %d, "
737                                                 "string or attr expected\n", rtype);
738                                 goto error;
739                         }
740                         ret=(strcasecmp(left, right)!=0);
741                         break;
742                 case MATCH_OP:
743                         if (rtype!=RE_ST){
744                                 LOG(L_CRIT, "BUG: comp_string: bad type %d, "
745                                                 " RE expected\n", rtype);
746                                 goto error;
747                         }
748                         ret=(regexec(r->re, left, 0, 0, 0)==0);
749                         break;
750                 default:
751                         LOG(L_CRIT, "BUG: comp_string: unknown op %d\n", op);
752                         goto error;
753         }
754         return ret;
755
756 error:
757         return -1;
758 }
759
760
761 inline static int comp_avp(int op, avp_spec_t* spec, int rtype, union exp_op* r, struct sip_msg* msg)
762 {
763         avp_t* avp;
764         int_str val;
765         union exp_op num_val;
766         str tmp;
767         unsigned int uval;
768
769         if (spec->type & AVP_INDEX_ALL) {
770                 avp = search_first_avp(spec->type & ~AVP_INDEX_ALL, spec->name, NULL, NULL);
771                 return (avp!=0);
772         }
773         avp = search_avp_by_index(spec->type, spec->name, &val, spec->index);
774         if (!avp) return (op == DIFF_OP);
775
776         switch(op) {
777         case NO_OP:
778                 if (avp->flags & AVP_VAL_STR) {
779                         return val.s.len!=0;
780                 } else {
781                         return val.n != 0;
782                 }
783                 break;
784
785         case BINOR_OP:
786                 return (val.n | r->numval)!=0;
787                 break;
788
789         case BINAND_OP:
790                 return (val.n & r->numval)!=0;
791                 break;
792         }
793
794         if (avp->flags & AVP_VAL_STR) {
795                 return comp_str(op, &val.s, rtype, r, msg);
796         } else {
797                 switch(rtype){
798                         case NUMBER_ST:
799                                 return comp_num(op, val.n, rtype, r);
800                         case STRING_ST:
801                                 tmp.s=r->string;
802                                 tmp.len=strlen(r->string);
803                                 if (str2int(&tmp, &uval)<0){
804                                         LOG(L_WARN, "WARNING: comp_avp: cannot convert string value"
805                                                                 " to int (%s)\n", ZSW(r->string));
806                                         goto error;
807                                 }
808                                 num_val.numval=uval;
809                                 return comp_num(op, val.n, NUMBER_ST, &num_val);
810                         case STR_ST:
811                                 if (str2int(&r->str, &uval)<0){
812                                         LOG(L_WARN, "WARNING: comp_avp: cannot convert str value"
813                                                                 " to int (%.*s)\n", r->str.len, ZSW(r->str.s));
814                                         goto error;
815                                 }
816                                 num_val.numval=uval;
817                                 return comp_num(op, val.n, NUMBER_ST, &num_val);
818                         case AVP_ST:
819                                 return comp_num(op, val.n, rtype, r);
820                         default:
821                                 LOG(L_CRIT, "BUG: comp_avp: invalid type for numeric avp "
822                                                         "comparison (%d)\n", rtype);
823                                 goto error;
824                 }
825         }
826 error:
827         return (op == DIFF_OP) ? 1 : -1;
828 }
829
830 /*
831  * Left side of expression was select
832  */
833 inline static int comp_select(int op, select_t* sel, int rtype, union exp_op* r, struct sip_msg* msg)
834 {
835         int ret;
836         str val;
837         char empty_str=0;
838
839         ret = run_select(&val, sel, msg);
840         if (ret != 0) return (op == DIFF_OP);
841
842         switch(op) {
843         case NO_OP: return (val.len>0);
844         case BINOR_OP:
845         case BINAND_OP:
846                 ERR("Binary operators cannot be used with string selects\n");
847                 return -1;
848         }
849         if (val.len==0) {
850                 /* make sure the string pointer uses accessible memory range
851                  * the comp_str function might dereference it
852                  */
853                 val.s=&empty_str;
854         }
855         return comp_str(op, &val, rtype, r, msg);
856 }
857
858 /* check_self wrapper -- it checks also for the op */
859 inline static int check_self_op(int op, str* s, unsigned short p)
860 {
861         int ret;
862
863         ret=check_self(s, p, 0);
864         switch(op){
865                 case EQUAL_OP:
866                         break;
867                 case DIFF_OP:
868                         ret=(ret > 0) ? 0 : 1;
869                         break;
870                 default:
871                         LOG(L_CRIT, "BUG: check_self_op: invalid operator %d\n", op);
872                         ret=-1;
873         }
874         return ret;
875 }
876
877
878 /* eval_elem helping function, returns an op param */
879 inline static int comp_ip(int op, struct ip_addr* ip, int rtype, union exp_op* r)
880 {
881         struct hostent* he;
882         char ** h;
883         int ret;
884         str tmp;
885
886         ret=-1;
887         switch(rtype){
888                 case NET_ST:
889                         switch(op){
890                                 case EQUAL_OP:
891                                         ret=(matchnet(ip, r->net)==1);
892                                         break;
893                                 case DIFF_OP:
894                                         ret=(matchnet(ip, r->net)!=1);
895                                         break;
896                                 default:
897                                         goto error_op;
898                         }
899                         break;
900                 case AVP_ST:
901                 case STRING_ST:
902                 case RE_ST:
903                         switch(op){
904                                 case EQUAL_OP:
905                                 case MATCH_OP:
906                                         /* 1: compare with ip2str*/
907                                         ret=comp_string(op, ip_addr2a(ip), rtype, r);
908                                         if (ret==1) break;
909                                         /* 2: resolve (name) & compare w/ all the ips */
910                                         if (rtype==STRING_ST){
911                                                 he=resolvehost(r->str.s);
912                                                 if (he==0){
913                                                         DBG("comp_ip: could not resolve %s\n",
914                                                             r->str.s);
915                                                 }else if (he->h_addrtype==ip->af){
916                                                         for(h=he->h_addr_list;(ret!=1)&& (*h); h++){
917                                                                 ret=(memcmp(ip->u.addr, *h, ip->len)==0);
918                                                         }
919                                                         if (ret==1) break;
920                                                 }
921                                         }
922                                         /* 3: (slow) rev dns the address
923                                         * and compare with all the aliases
924                                         * !!??!! review: remove this? */
925                                         if (unlikely((received_dns & DO_REV_DNS) && 
926                                                         ((he=rev_resolvehost(ip))!=0) )){
927                                                 /*  compare with primary host name */
928                                                 ret=comp_string(op, he->h_name, rtype, r);
929                                                 /* compare with all the aliases */
930                                                 for(h=he->h_aliases; (ret!=1) && (*h); h++){
931                                                         ret=comp_string(op, *h, rtype, r);
932                                                 }
933                                         }else{
934                                                 ret=0;
935                                         }
936                                         break;
937                                 case DIFF_OP:
938                                         ret=(comp_ip(EQUAL_OP, ip, rtype, r) > 0) ? 0 : 1;
939                                         break;
940                                 default:
941                                         goto error_op;
942                         }
943                         break;
944                 case MYSELF_ST: /* check if it's one of our addresses*/
945                         tmp.s=ip_addr2a(ip);
946                         tmp.len=strlen(tmp.s);
947                         ret=check_self_op(op, &tmp, 0);
948                         break;
949                 default:
950                         LOG(L_CRIT, "BUG: comp_ip: invalid type for "
951                                                 " src_ip or dst_ip (%d)\n", rtype);
952                         ret=-1;
953         }
954         return ret;
955 error_op:
956         LOG(L_CRIT, "BUG: comp_ip: invalid operator %d\n", op);
957         return -1;
958
959 }
960
961
962 /* returns: 0/1 (false/true) or -1 on error */
963 inline static int eval_elem(struct run_act_ctx* h, struct expr* e, 
964                                                                 struct sip_msg* msg)
965 {
966         struct sip_uri uri;
967         int ret;
968         struct onsend_info* snd_inf;
969         struct ip_addr ip;
970         ret=E_BUG;
971
972         if (e->type!=ELEM_T){
973                 LOG(L_CRIT," BUG: eval_elem: invalid type\n");
974                 goto error;
975         }
976         switch(e->l_type){
977         case METHOD_O:
978                 ret=comp_str(e->op, &msg->first_line.u.request.method,
979                              e->r_type, &e->r, msg);
980                 break;
981         case URI_O:
982                 if(msg->new_uri.s) {
983                         if (e->r_type==MYSELF_ST){
984                                 if (parse_sip_msg_uri(msg)<0) ret=-1;
985                                 else ret=check_self_op(e->op, &msg->parsed_uri.host,
986                                                        msg->parsed_uri.port_no?
987                                                        msg->parsed_uri.port_no:SIP_PORT);
988                         }else{
989                                 ret=comp_str(e->op, &msg->new_uri,
990                                              e->r_type, &e->r, msg);
991                         }
992                 }else{
993                         if (e->r_type==MYSELF_ST){
994                                 if (parse_sip_msg_uri(msg)<0) ret=-1;
995                                 else ret=check_self_op(e->op, &msg->parsed_uri.host,
996                                                        msg->parsed_uri.port_no?
997                                                        msg->parsed_uri.port_no:SIP_PORT);
998                         }else{
999                                 ret=comp_str(e->op, &msg->first_line.u.request.uri,
1000                                              e->r_type, &e->r, msg);
1001                         }
1002                 }
1003                 break;
1004
1005         case FROM_URI_O:
1006                 if (parse_from_header(msg)!=0){
1007                         LOG(L_ERR, "ERROR: eval_elem: bad or missing"
1008                             " From: header\n");
1009                         goto error;
1010                 }
1011                 if (e->r_type==MYSELF_ST){
1012                         if (parse_uri(get_from(msg)->uri.s, get_from(msg)->uri.len,
1013                                       &uri) < 0){
1014                                 LOG(L_ERR, "ERROR: eval_elem: bad uri in From:\n");
1015                                 goto error;
1016                         }
1017                         ret=check_self_op(e->op, &uri.host,
1018                                           uri.port_no?uri.port_no:SIP_PORT);
1019                 }else{
1020                         ret=comp_str(e->op, &get_from(msg)->uri,
1021                                      e->r_type, &e->r, msg);
1022                 }
1023                 break;
1024
1025         case TO_URI_O:
1026                 if ((msg->to==0) && ((parse_headers(msg, HDR_TO_F, 0)==-1) ||
1027                                      (msg->to==0))){
1028                         LOG(L_ERR, "ERROR: eval_elem: bad or missing"
1029                             " To: header\n");
1030                         goto error;
1031                 }
1032                      /* to content is parsed automatically */
1033                 if (e->r_type==MYSELF_ST){
1034                         if (parse_uri(get_to(msg)->uri.s, get_to(msg)->uri.len,
1035                                       &uri) < 0){
1036                                 LOG(L_ERR, "ERROR: eval_elem: bad uri in To:\n");
1037                                 goto error;
1038                         }
1039                         ret=check_self_op(e->op, &uri.host,
1040                                           uri.port_no?uri.port_no:SIP_PORT);
1041                 }else{
1042                         ret=comp_str(e->op, &get_to(msg)->uri,
1043                                      e->r_type, &e->r, msg);
1044                 }
1045                 break;
1046
1047         case SRCIP_O:
1048                 ret=comp_ip(e->op, &msg->rcv.src_ip, e->r_type, &e->r);
1049                 break;
1050
1051         case DSTIP_O:
1052                 ret=comp_ip(e->op, &msg->rcv.dst_ip, e->r_type, &e->r);
1053                 break;
1054
1055         case SNDIP_O:
1056                 snd_inf=get_onsend_info();
1057                 if (snd_inf && snd_inf->send_sock){
1058                         ret=comp_ip(e->op, &snd_inf->send_sock->address, e->r_type, &e->r);
1059                 }else{
1060                         BUG("eval_elem: snd_ip unknown (not in a onsend_route?)\n");
1061                 }
1062                 break;
1063
1064         case TOIP_O:
1065                 snd_inf=get_onsend_info();
1066                 if (snd_inf && snd_inf->to){
1067                         su2ip_addr(&ip, snd_inf->to);
1068                         ret=comp_ip(e->op, &ip, e->r_type, &e->r);
1069                 }else{
1070                         BUG("eval_elem: to_ip unknown (not in a onsend_route?)\n");
1071                 }
1072                 break;
1073
1074         case NUMBER_O:
1075                 ret=!(!e->r.numval); /* !! to transform it in {0,1} */
1076                 break;
1077
1078         case ACTION_O:
1079                 ret=run_actions(h, (struct action*)e->r.param, msg);
1080                 if (ret<=0) ret=0;
1081                 else ret=1;
1082                 break;
1083
1084         case SRCPORT_O:
1085                 ret=comp_num(e->op, (int)msg->rcv.src_port,
1086                              e->r_type, &e->r);
1087                 break;
1088
1089         case DSTPORT_O:
1090                 ret=comp_num(e->op, (int)msg->rcv.dst_port,
1091                              e->r_type, &e->r);
1092                 break;
1093
1094         case SNDPORT_O:
1095                 snd_inf=get_onsend_info();
1096                 if (snd_inf && snd_inf->send_sock){
1097                         ret=comp_num(e->op, (int)snd_inf->send_sock->port_no,
1098                                      e->r_type, &e->r);
1099                 }else{
1100                         BUG("eval_elem: snd_port unknown (not in a onsend_route?)\n");
1101                 }
1102                 break;
1103
1104         case TOPORT_O:
1105                 snd_inf=get_onsend_info();
1106                 if (snd_inf && snd_inf->to){
1107                         ret=comp_num(e->op, (int)su_getport(snd_inf->to),
1108                                      e->r_type, &e->r);
1109                 }else{
1110                         BUG("eval_elem: to_port unknown (not in a onsend_route?)\n");
1111                 }
1112                 break;
1113
1114         case PROTO_O:
1115                 ret=comp_num(e->op, msg->rcv.proto,
1116                              e->r_type, &e->r);
1117                 break;
1118
1119         case SNDPROTO_O:
1120                 snd_inf=get_onsend_info();
1121                 if (snd_inf && snd_inf->send_sock){
1122                         ret=comp_num(e->op, snd_inf->send_sock->proto,
1123                                      e->r_type, &e->r);
1124                 }else{
1125                         BUG("eval_elem: snd_proto unknown (not in a onsend_route?)\n");
1126                 }
1127                 break;
1128
1129         case AF_O:
1130                 ret=comp_num(e->op, (int)msg->rcv.src_ip.af,
1131                              e->r_type, &e->r);
1132                 break;
1133
1134         case SNDAF_O:
1135                 snd_inf=get_onsend_info();
1136                 if (snd_inf && snd_inf->send_sock){
1137                         ret=comp_num(e->op, snd_inf->send_sock->address.af,
1138                                                         e->r_type, &e->r);
1139                 }else{
1140                         BUG("eval_elem: snd_af unknown (not in a onsend_route?)\n");
1141                 }
1142                 break;
1143
1144         case MSGLEN_O:
1145                 if ((snd_inf=get_onsend_info())!=0){
1146                         ret=comp_num(e->op, (int)snd_inf->len,
1147                                         e->r_type, &e->r);
1148                 }else{
1149                         ret=comp_num(e->op, (int)msg->len,
1150                                         e->r_type, &e->r);
1151                 }
1152                 break;
1153
1154         case RETCODE_O:
1155                 ret=comp_num(e->op, h->last_retcode, e->r_type, &e->r);
1156                 break;
1157
1158         case AVP_O:
1159                 ret = comp_avp(e->op, e->l.attr, e->r_type, &e->r, msg);
1160                 break;
1161
1162         case SELECT_O:
1163                 ret = comp_select(e->op, e->l.select, e->r_type, &e->r, msg);
1164                 break;
1165
1166         default:
1167                 LOG(L_CRIT, "BUG: eval_elem: invalid operand %d\n",
1168                     e->l_type);
1169         }
1170         return ret;
1171 error:
1172         return (e->op == DIFF_OP) ? 1 : -1;
1173 }
1174
1175
1176
1177 /* ret= 1/0 (true/false) ,  -1 on error (evaluates as false)*/
1178 int eval_expr(struct run_act_ctx* h, struct expr* e, struct sip_msg* msg)
1179 {
1180         int ret;
1181
1182         if (e->type==ELEM_T){
1183                 ret=eval_elem(h, e, msg);
1184         }else if (e->type==EXP_T){
1185                 switch(e->op){
1186                         case LOGAND_OP:
1187                                 ret=eval_expr(h, e->l.expr, msg);
1188                                 /* if error or false stop evaluating the rest */
1189                                 if (ret <= 0) break;
1190                                 ret=eval_expr(h, e->r.expr, msg); /*ret1 is 1*/
1191                                 break;
1192                         case LOGOR_OP:
1193                                 ret=eval_expr(h, e->l.expr, msg);
1194                                 /* if true stop evaluating the rest */
1195                                 if (ret > 0) break;
1196                                 ret=eval_expr(h, e->r.expr, msg); /* ret1 is 0 */
1197                                 break;
1198                         case NOT_OP:
1199                                 ret=eval_expr(h, e->l.expr, msg);
1200                                 ret=(ret > 0) ? 0 : 1;
1201                                 break;
1202                         default:
1203                                 LOG(L_CRIT, "BUG: eval_expr: unknown op %d\n", e->op);
1204                                 ret=-1;
1205                 }
1206         }else{
1207                 LOG(L_CRIT, "BUG: eval_expr: unknown type %d\n", e->type);
1208                 ret=-1;
1209         }
1210         return ret;
1211 }
1212
1213
1214 /* adds an action list to head; a must be null terminated (last a->next=0))*/
1215 void push(struct action* a, struct action** head)
1216 {
1217         struct action *t;
1218         if (*head==0){
1219                 *head=a;
1220                 return;
1221         }
1222         for (t=*head; t->next;t=t->next);
1223         t->next=a;
1224 }
1225
1226
1227
1228
1229 int add_actions(struct action* a, struct action** head)
1230 {
1231         int ret;
1232
1233         LOG(L_DBG, "add_actions: fixing actions...\n");
1234         if ((ret=fix_actions(a))!=0) goto error;
1235         push(a,head);
1236         return 0;
1237
1238 error:
1239         return ret;
1240 }
1241
1242
1243
1244 static int fix_rl(struct route_list* rt)
1245 {
1246         int i;
1247         int ret;
1248         
1249         for(i=0;i<rt->idx; i++){
1250                 if(rt->rlist[i]){
1251                         if ((ret=fix_actions(rt->rlist[i]))!=0){
1252                                 return ret;
1253                         }
1254                 }
1255         }
1256         return 0;
1257 }
1258
1259
1260
1261 /* fixes all action tables */
1262 /* returns 0 if ok , <0 on error */
1263 int fix_rls()
1264 {
1265         int ret;
1266         
1267         if ((ret=fix_rl(&main_rt))!=0)
1268                 return ret;
1269         if ((ret=fix_rl(&onreply_rt))!=0)
1270                 return ret;
1271         if ((ret=fix_rl(&failure_rt))!=0)
1272                 return ret;
1273         if ((ret=fix_rl(&branch_rt))!=0)
1274                 return ret;
1275         if ((ret=fix_rl(&onsend_rt))!=0)
1276                 return ret;
1277
1278         return 0;
1279 }
1280
1281
1282
1283 static void print_rl(struct route_list* rt, char* name)
1284 {
1285         int j;
1286         
1287         for(j=0; j<rt->entries; j++){
1288                 if (rt->rlist[j]==0){
1289                         if ((j==0) && (rt==&main_rt))
1290                                 DBG("WARNING: the main routing table is empty\n");
1291                         continue;
1292                 }
1293                 DBG("%s routing table %d:\n", name, j);
1294                 print_actions(rt->rlist[j]);
1295                 DBG("\n");
1296         }
1297 }
1298
1299
1300 /* debug function, prints routing tables */
1301 void print_rls()
1302 {
1303         print_rl(&main_rt, "");
1304         print_rl(&onreply_rt, "onreply");
1305         print_rl(&failure_rt, "failure");
1306         print_rl(&branch_rt, "branch");
1307         print_rl(&onsend_rt, "onsend");
1308 }