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