register(k): pack contact info based on header for searching existing ul records
[sip-router] / select.c
1 /*
2  * $Id$
3  *
4  * Copyright (C) 2005-2006 iptelorg GmbH
5  *
6  * This file is part of ser, a free SIP server.
7  *
8  * ser is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version
12  *
13  * For a license to use the ser software under conditions
14  * other than those described here, or to purchase support for this
15  * software, please contact iptel.org by e-mail at the following addresses:
16  *    info@iptel.org
17  *
18  * ser is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26  *
27  * History:
28  * --------
29  *  2005-12-19  select framework (mma)
30  *  2006-01-19  multiple nested calls, IS_ALIAS -> NESTED flag renamed (mma)
31  *              DIVERSION flag checked
32  *  2006-02-26  don't free str when changing type STR -> DIVERSION (mma)
33  *                              it can't be freeable sometimes (e.g. xlog's select)
34  *      2006-05-30  parse_select (mma)
35  *      2006-06-02  shm_parse_select (mma)
36  *
37  */
38
39 /*!
40  * \file
41  * \brief SIP-router core :: 
42  * \ingroup core
43  * Module: \ref core
44  */
45
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 #include <ctype.h>
51
52 #include "select.h"
53 #include "dprint.h"
54 #include "select_core.h"
55 #include "mem/mem.h"
56 #include "mem/shm_mem.h"
57
58 /*
59  * The main parser table list placeholder
60  * at startup use core table, modules can
61  * add their own via register_select_table call
62  */
63 static select_table_t *select_list = &select_core_table;
64
65 /* the level of the select call that is beeing evaluated
66  * by the child process
67  */
68 int select_level = 0;
69
70 /* pointer to the SIP uri beeing processed.
71  * Nested function calls can pass information to each
72  * other using this pointer. Only for performace reasons.
73  * (Miklos)
74  */
75 struct sip_uri  *select_uri_p = NULL;
76
77 /** parse a select identifier (internal version)
78  * Parse select string into select structure s
79  * moves pointer p to the first unused char.
80  *
81  * The select identifier must be of the form:
82 \verbatim
83  *   [@] <sel_id> [ '.' <sel_id> ...]
84  *   
85  * Where 
86  *       <sel_id> = <id> |
87  *                  <id> '[' <idx> ']'
88  *       <id> = [a-zA-Z0-9_]+
89  *       <idx> = <number> | <string>
90  *       <string> = '"' <ascii> '"' | 
91  *                  '\"' <ascii> '\"'
92  *
93  * Examples:
94  *     @to.tag
95  *     @hf_value["contact"]
96  *     @msg.header["SER-Server-ID"]
97  *     @eval.pop[-1]
98  *     contact.uri.params.maddr
99  *     cfg_get.rtp_proxy.enabled 
100 \endverbatim
101  *
102  * @return -1 error
103  *                        p points to the first unconsumed char
104  *          0 success
105  *                        p points to the first unconsumed char
106  *                        s points to the select structure
107  */
108
109 int w_parse_select(char**p, select_t* sel)
110 {
111         str name;
112         char* select_name;
113         
114         if (**p=='@') (*p)++;
115         select_name=*p;
116         sel->n=0;
117         while (isalpha((unsigned char)*(*p))) {
118                 if (sel->n > MAX_SELECT_PARAMS -2) {
119                         ERR("parse_select: select depth exceeds max\n");
120                         goto error;
121                 }
122                 name.s=(*p);
123                 while (isalpha((unsigned char)*(*p)) || 
124                                 isdigit((unsigned char)*(*p)) || (*(*p)=='_')) (*p)++;
125                 name.len=(*p)-name.s;
126                 sel->params[sel->n].type=SEL_PARAM_STR;
127                 sel->params[sel->n].v.s=name;
128                 DBG("parse_select: part %d: %.*s\n", sel->n, sel->params[sel->n].v.s.len, sel->params[sel->n].v.s.s);
129                 sel->n++;
130                 if (*(*p)=='[') {
131                         (*p)++; 
132                         if (*(*p)=='\\') (*p)++;
133                         if (*(*p)=='"') {
134                                 (*p)++; 
135                                 name.s=(*p);
136                                 while ((*(*p)!='\0') && (*(*p)!='"')) (*p)++;
137                                 if (*(*p)!='"') {
138                                         ERR("parse_select: end of string is missing\n");
139                                         goto error;
140                                 }
141                                 name.len=(*p)-name.s;
142                                 if (*((*p)-1)=='\\') name.len--;
143                                 (*p)++;
144                                 if (*(*p)!=']') {
145                                         ERR("parse_select: invalid string index, no closing ]\n");
146                                         goto error;
147                                 };
148                                 (*p)++;
149                                 sel->params[sel->n].type=SEL_PARAM_STR;
150                                 sel->params[sel->n].v.s=name;
151                                 DBG("parse_select: part %d: [\"%.*s\"]\n", sel->n, sel->params[sel->n].v.s.len, sel->params[sel->n].v.s.s);
152                         } else {
153                                 name.s=(*p);
154                                 if (*(*p)=='-') (*p)++;
155                                 while (isdigit((unsigned char)*(*p))) (*p)++;
156                                 name.len=(*p)-name.s;
157                                 if (*(*p)!=']') {
158                                         ERR("parse_select: invalid index, no closing ]\n");
159                                         goto error;
160                                 };
161                                 (*p)++;
162                                 sel->params[sel->n].type=SEL_PARAM_INT;
163                                 sel->params[sel->n].v.i=atoi(name.s);
164                                 DBG("parse_select: part %d: [%d]\n", sel->n, sel->params[sel->n].v.i);
165                         }
166                         sel->n++;
167                 }
168                 if (*(*p)!='.') break;
169                 (*p)++;
170         };
171         if (sel->n==0) {
172                 ERR("parse_select: invalid select '%.*s'\n", (int)(*p - select_name), select_name);
173                 goto error;
174         };
175         DBG("parse_select: end, total elements: %d, calling resolve_select\n", sel->n);
176         if (resolve_select(sel)<0) {
177                 ERR("parse_select: error while resolve_select '%.*s'\n", (int)(*p - select_name), select_name);
178                 goto error;
179         }
180         return 0;
181         
182 error:
183         return -1;
184 }
185
186
187 /** parse a select identifier.
188  * Parse select string into select structure s and
189  * moves pointer p to the first unused char.
190  * 
191 \verbatim
192  * The select identifier must be of the form:
193  *   [@] <sel_id> [ '.' <sel_id> ...]
194  *   
195  * Where 
196  *       <sel_id> = <id> |
197  *                  <id> '[' <idx> ']'
198  *       <id> = [a-zA-Z0-9_]+
199  *       <idx> = <number>  | '-' <number> | <string>
200  *       <string> = '"' <ascii> '"' | 
201  *                  '\"' <ascii> '\"'
202  *
203  * Examples:
204  *     @to.tag
205  *     @hf_value["contact"]
206  *     @msg.header["SER-Server-ID"]
207  *     @eval.pop[-1]
208  *     contact.uri.params.maddr
209  *     cfg_get.rtp_proxy.enabled 
210 \endverbatim
211   *
212   * @param p - double string (asciiz) pointer, *p is moved to the first char
213   *            after the select identifier
214   * @param s - the result will be stored here
215   * @return  < 0 on error, 0 on success
216   */
217 int parse_select (char** p, select_t** s)
218 {
219         select_t* sel;
220         
221         sel=(select_t*)pkg_malloc(sizeof(select_t));
222         if (!sel) {
223                 ERR("parse_select: no free memory\n");
224                 return -1;
225         }
226         memset(sel, 0, sizeof(select_t));
227         if (w_parse_select(p, sel)<0) {
228                 pkg_free(sel);
229                 return -2;
230         }
231         *s=sel;
232         return 0;
233 }
234
235 void free_select(select_t *s)
236 {
237         if (s)
238                 pkg_free(s);
239 }
240
241 void shm_free_select(select_t *s)
242 {
243         if (s)
244                 shm_free(s);
245 }
246
247 int shm_parse_select (char** p, select_t** s)
248 {
249         select_t* sel;
250         
251         sel=(select_t*)shm_malloc(sizeof(select_t));
252         if (!sel) {
253                 ERR("parse_select: no free shared memory\n");
254                 return -1;
255         }
256         if (w_parse_select(p, sel)<0) {
257                 shm_free(sel);
258                 return -2;
259         }
260         *s=sel;
261         return 0;
262 }
263
264 int resolve_select(select_t* s)
265 {
266         select_f f;
267         int nested;
268         int param_idx = 0;
269         int table_idx = 0;
270         select_table_t* t = NULL;
271         int accept = 0;
272
273         f = NULL;
274         nested = 0;
275         memset (s->f, 0, sizeof(s->f));
276         while (param_idx<s->n) {
277                 accept = 0;
278                 switch (s->params[param_idx].type) {
279                 case SEL_PARAM_STR:
280                         DBG("resolve_select: '%.*s'\n", s->params[param_idx].v.s.len, s->params[param_idx].v.s.s);
281                         break;
282                 case SEL_PARAM_INT:
283                         DBG("resolve_select: [%d]\n", s->params[param_idx].v.i);
284                         break;
285                 default:
286                         /* just to avoid the warning */
287                         break;
288                 }
289                 for (t=select_list; t; t=t->next) {
290                         table_idx = 0;
291                         if (!t->table) continue;
292                         while (t->table[table_idx].curr_f || t->table[table_idx].new_f) {
293                                 if (t->table[table_idx].curr_f == f) {
294                                         if ((t->table[table_idx].flags & (NESTED | CONSUME_NEXT_INT | CONSUME_NEXT_STR)) == NESTED) {
295                                                 accept = 1;
296                                         } else if (t->table[table_idx].type == s->params[param_idx].type) {
297                                                 switch (t->table[table_idx].type) {
298                                                 case SEL_PARAM_INT:
299                                                         accept = 1;
300                                                         break;
301                                                 case SEL_PARAM_STR:
302                                                         accept = (((t->table[table_idx].name.len == s->params[param_idx].v.s.len) || !t->table[table_idx].name.len)
303                                                                    && (!t->table[table_idx].name.s || !strncasecmp(t->table[table_idx].name.s, s->params[param_idx].v.s.s, s->params[param_idx].v.s.len)));
304                                                         break;
305                                                 default:
306                                                         break;
307                                                 }
308                                         };
309                                 }
310                                 if (accept) goto accepted;
311                                 table_idx++;
312                         }
313                 }
314                 switch (s->params[param_idx].type) {
315                         case SEL_PARAM_STR:
316                                 LOG(L_ERR, "Unable to resolve select '%.*s' at level %d\n", s->params[param_idx].v.s.len, s->params[param_idx].v.s.s, param_idx);
317                                 break;
318                         case SEL_PARAM_INT:
319                                 LOG(L_ERR, "Unable to resolve select [%d] at level %d\n", s->params[param_idx].v.i, param_idx);
320                                 break;
321                         default:
322                                 BUG ("Unable to resolve select at level %d\n", param_idx);
323                                 break;
324                         break;
325                 }
326                 goto not_found;
327
328                 accepted:
329                 if (t->table[table_idx].flags & DIVERSION) {
330                         /* if (s->params[param_idx].type == SEL_PARAM_STR) pkg_free(s->params[param_idx].v.s.s); */
331                         /* don't free it (the mem can leak only once at startup)
332                          * the parsed string can live inside larger string block
333                          * e.g. when xlog's select is parsed
334                          */
335                         s->params[param_idx].type = SEL_PARAM_DIV;
336                         s->params[param_idx].v.i = t->table[table_idx].flags & DIVERSION_MASK;
337
338                 }
339                 if (t->table[table_idx].flags & CONSUME_NEXT_STR) {
340                         if ((param_idx<s->n-1) && (s->params[param_idx+1].type == SEL_PARAM_STR)) {
341                                 param_idx++;
342                         } else if (!(t->table[table_idx].flags & OPTIONAL)) {
343                                 BUG ("Mandatory STR parameter not found\n");
344                                 goto not_found;
345                         }
346                 }
347                 if (t->table[table_idx].flags & CONSUME_NEXT_INT) {
348                         if ((param_idx<s->n-1) && (s->params[param_idx+1].type == SEL_PARAM_INT)) {
349                                 param_idx++;
350                         } else if (!(t->table[table_idx].flags & OPTIONAL)) {
351                                 BUG ("Mandatory INT parameter not found\n");
352                                 goto not_found;
353                         }
354                 }
355
356                 if (t->table[table_idx].flags & NESTED) {
357                         if (nested < MAX_NESTED_CALLS-1) { /* need space for final function */
358                                 s->f[nested++] = f;
359                                 s->param_offset[nested] = param_idx;
360                         } else {
361                                 BUG("MAX_NESTED_CALLS too small to resolve select\n");
362                                 goto not_found;
363                         }
364                 } else {
365                         param_idx++;
366                 }
367
368                 if (t->table[table_idx].flags & FIXUP_CALL) {
369                         select_level = nested;
370                         s->param_offset[nested+1] = param_idx;
371                         if (t->table[table_idx].new_f(NULL, s, NULL)<0) goto not_found;
372                 }
373
374                 f = t->table[table_idx].new_f;
375
376                 if (t->table[table_idx].flags & CONSUME_ALL) {
377                         /* sanity checks */
378                         if (t->table[table_idx].flags & NESTED)
379                                 WARN("resolve_select: CONSUME_ALL should not be set "
380                                         "together with NESTED flag!\n");
381                         if ((t->table[table_idx].flags & FIXUP_CALL) == 0)
382                                 WARN("resolve_select: FIXUP_CALL should be defined "
383                                         "if CONSUME_ALL flag is set!\n");
384                         break;
385                 }
386         }
387
388         if (t->table[table_idx].flags & SEL_PARAM_EXPECTED) {
389                 BUG ("final node has SEL_PARAM_EXPECTED set (no more parameters available)\n");
390                 goto not_found;
391         }
392         if (nested >= MAX_NESTED_CALLS) {
393                 BUG("MAX_NESTED_CALLS too small, no space for finally resolved function\n");
394                 goto not_found;
395         }
396         if ((nested>0) && (s->f[nested-1] == f)) {
397                 BUG("Topmost nested function equals to final function, won't call it twice\n");
398         } else {
399                 s->f[nested++] = f;
400         }
401         s->param_offset[nested] = s->n;
402
403         return 0;
404
405 not_found:
406         return -1;
407 }
408
409 int run_select(str* res, select_t* s, struct sip_msg* msg)
410 {
411         int ret, orig_level;
412
413         if (res == NULL) {
414                 BUG("Select unprepared result space\n");
415                 return -1;
416         }
417         if (s == 0) {
418                 BUG("Select structure is NULL\n");
419                 return -1;
420         }
421         if (s->f[0] == 0) {
422                 BUG("Select structure has not been resolved\n");
423                 return -1;
424         }
425         DBG("Calling SELECT %p \n", s->f);
426
427         /* reset the uri pointer */
428         select_uri_p = NULL;
429
430         /* save and restore the original select_level
431          * because of the nested selects */
432         orig_level = select_level;
433         ret = 0;
434         for (   select_level=0;
435                 (ret == 0) && (s->f[select_level] !=0 ) && (select_level<MAX_NESTED_CALLS);
436                 select_level++
437         ) {
438                 ret = s->f[select_level](res, s, msg);
439         }
440         select_level = orig_level;
441         return ret;
442 }
443
444 void print_select(select_t* s)
445 {
446         int i;
447         DBG("select(");
448         for(i = 0; i < s->n; i++) {
449                 if (s->params[i].type == SEL_PARAM_INT) {
450                         DBG("%d,", s->params[i].v.i);
451                 } else {
452                         DBG("%.*s,", s->params[i].v.s.len, s->params[i].v.s.s);
453                 }
454         }
455         DBG(")\n");
456 }
457
458 int register_select_table(select_row_t* mod_tab)
459 {
460         select_table_t* t;
461         t=(select_table_t*)pkg_malloc(sizeof(select_table_t));
462         if (!t) {
463                 ERR("No memory for new select_table structure\n");
464                 return -1;
465         }
466
467         t->table=mod_tab;
468         t->next=select_list;
469         select_list=t;
470         return 0;
471 }