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