- added disable tcp support (-T or disable_tcp=yes in the cfg)
[sip-router] / modules / tm / t_lookup.c
1 /*
2  * $Id$
3  *
4  * This C-file takes care of matching requests and replies with
5  * existing transactions. Note that we do not do SIP-compliant
6  * request matching as asked by SIP spec. We do bitwise matching of 
7  * all header fields in requests which form a transaction key. 
8  * It is much faster and it worx pretty well -- we haven't 
9  * had any interop issue neither in lab nor in bake-offs. The reason
10  * is that retransmissions do look same as original requests
11  * (it would be really silly if they wuld be mangled). The only
12  * exception is we parse To as To in ACK is compared to To in
13  * reply and both  of them are constructed by different software.
14  * 
15  * As for reply matching, we match based on branch value -- that is
16  * faster too. There are two versions .. with SYNONYMs #define
17  * enabled, the branch includes ordinal number of a transaction
18  * in a synonym list in hash table and is somewhat faster but
19  * not reboot-resilient. SYNONYMs turned off are little slower
20  * but work across reboots as well.
21  *
22  * The branch parameter is formed as follows:
23  * SYNONYMS  on: hash.synonym.branch
24  * SYNONYMS off: hash.md5.branch
25  *
26  * -jiri
27  *
28  *
29  * Copyright (C) 2001-2003 Fhg Fokus
30  *
31  * This file is part of ser, a free SIP server.
32  *
33  * ser is free software; you can redistribute it and/or modify
34  * it under the terms of the GNU General Public License as published by
35  * the Free Software Foundation; either version 2 of the License, or
36  * (at your option) any later version
37  *
38  * For a license to use the ser software under conditions
39  * other than those described here, or to purchase support for this
40  * software, please contact iptel.org by e-mail at the following addresses:
41  *    info@iptel.org
42  *
43  * ser is distributed in the hope that it will be useful,
44  * but WITHOUT ANY WARRANTY; without even the implied warranty of
45  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
46  * GNU General Public License for more details.
47  *
48  * You should have received a copy of the GNU General Public License 
49  * along with this program; if not, write to the Free Software 
50  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
51  *
52  * History:
53  * ----------
54  * 2003-01-23  options for disabling r-uri matching introduced (jiri)
55  *              nameser_compat.h (andrei)
56  * 2003-01-27  next baby-step to removing ZT - PRESERVE_ZT (jiri)
57  * 2003-01-28  scratchpad removed (jiri)
58  * 2003-02-13  init_rb() is proto indep. & it uses struct dest_info (andrei)
59  * 2003-02-24  s/T_NULL/T_NULL_CELL/ to avoid redefinition conflict w/
60  * 2003-02-27  3261 ACK/200 consumption bug removed (jiri)
61  * 2003-02-28 scratchpad compatibility abandoned (jiri)
62  * 2003-03-01  kr set through a function now (jiri)
63  * 2003-03-06  dialog matching introduced for ACKs -- that's important for 
64  *             INVITE UAS (like INVITE) and 200/ACK proxy matching (jiri)
65  * 2003-03-29  optimization: e2e ACK matching only if callback installed
66  *             (jiri)
67  * 2003-03-30  set_kr for requests only (jiri)
68  * 2003-04-04  bug_fix: RESPONSE_IN callback not called for local
69  *             UAC transactions (jiri)
70  * 2003-04-07  new transactions inherit on_negative and on_relpy from script
71  *             variables on instatntiation (jiri)
72  */
73
74
75 #include "defs.h"
76
77
78 #include <assert.h>
79 #include "../../comp_defs.h"
80 #include "../../dprint.h"
81 #include "../../config.h"
82 #include "../../parser/parser_f.h"
83 #include "../../parser/parse_from.h"
84 #include "../../ut.h"
85 #include "../../timer.h"
86 #include "../../hash_func.h"
87 #include "../../globals.h"
88 #include "../../forward.h"
89 #include "t_funcs.h"
90 #include "config.h"
91 #include "sip_msg.h"
92 #include "t_hooks.h"
93 #include "t_lookup.h"
94
95 #define EQ_VIA_LEN(_via)\
96         ( (p_msg->via1->bsize-(p_msg->_via->name.s-(p_msg->_via->hdr.s+p_msg->_via->hdr.len)))==\
97                 (t_msg->via1->bsize-(t_msg->_via->name.s-(t_msg->_via->hdr.s+t_msg->_via->hdr.len))) )
98
99
100
101 #define EQ_LEN(_hf) (t_msg->_hf->body.len==p_msg->_hf->body.len)
102 #define EQ_REQ_URI_LEN\
103         (p_msg->first_line.u.request.uri.len==t_msg->first_line.u.request.uri.len)
104
105 #define EQ_STR(_hf) (memcmp(t_msg->_hf->body.s,\
106         p_msg->_hf->body.s, \
107         p_msg->_hf->body.len)==0)
108 #define EQ_REQ_URI_STR\
109         ( memcmp( t_msg->first_line.u.request.uri.s,\
110         p_msg->first_line.u.request.uri.s,\
111         p_msg->first_line.u.request.uri.len)==0)
112 #define EQ_VIA_STR(_via)\
113         ( memcmp( t_msg->_via->name.s,\
114          p_msg->_via->name.s,\
115          (t_msg->via1->bsize-(t_msg->_via->name.s-(t_msg->_via->hdr.s+t_msg->_via->hdr.len)))\
116         )==0 )
117
118
119
120 #define HF_LEN(_hf) ((_hf)->len)
121
122 /* should be request-uri matching used as a part of pre-3261 
123  * transaction matching, as the standard wants us to do so
124  * (and is reasonable to do so, to be able to distinguish
125  * spirals)? turn only off for better interaction with 
126  * devices that are broken and send different r-uri in
127  * CANCEL/ACK than in original INVITE
128  */
129 int ruri_matching=1;
130
131 /* presumably matching transaction for an e2e ACK */
132 static struct cell *t_ack;
133
134 /* this is a global variable which keeps pointer to
135    transaction currently processed by a process; it it
136    set by t_lookup_request or t_reply_matching; don't
137    dare to change it anywhere else as it would
138    break ref_counting
139 */
140
141 static struct cell *T;
142
143 /* number of currently processed message; good to know
144    to be able to doublecheck whether we are still working
145    on a current transaction or a new message arrived;
146    don't even think of changing it
147 */
148 unsigned int     global_msg_id;
149
150 struct cell *get_t() { return T; }
151 void set_t(struct cell *t) { T=t; }
152 void init_t() {global_msg_id=0; set_t(T_UNDEFINED);}
153
154 static inline int parse_dlg( struct sip_msg *msg )
155 {
156         if (parse_headers(msg, HDR_FROM | HDR_CSEQ | HDR_TO, 0)==-1) {
157                 LOG(L_ERR, "ERROR: tid_matching: From or Cseq or To invalid\n");
158                 return 0;
159         }
160         if (parse_from_header(msg)==-1) {
161                 LOG(L_ERR, "ERROR: tid_matching: From broken\n");
162                 return 0;
163         }
164         /* To is automatically parsed through HDR_TO in parse bitmap,
165          * we don't need to worry about it now
166         if (parse_to_header(msg)==-1) {
167                 LOG(L_ERR, "ERROR: tid_matching: To broken\n");
168                 return 0;
169         }
170         */
171         return 1;
172 }
173
174 /* is the ACK (p_msg) in p_msg dialog-wise equal to the INVITE (t_msg) 
175  * except to-tags? */
176 static inline int partial_dlg_matching(struct sip_msg *t_msg, struct sip_msg *p_msg)
177 {
178         struct to_body *inv_from;
179
180         if (!EQ_LEN(callid)) return 0;
181         if (get_cseq(t_msg)->number.len!=get_cseq(p_msg)->number.len)
182                 return 0;
183         inv_from=get_from(t_msg);
184         if (!inv_from) {
185                 LOG(L_ERR, "ERROR: partial_dlg_matching: INV/From not parsed\n");
186                 return 0;
187         }
188         if (inv_from->tag_value.len!=get_from(p_msg)->tag_value.len)
189                 return 0;
190         if (!EQ_STR(callid)) 
191                 return 0;
192         if (memcmp(get_cseq(t_msg)->number.s, get_cseq(p_msg)->number.s,
193                         get_cseq(p_msg)->number.len)!=0)
194                 return 0;
195         if (memcmp(inv_from->tag_value.s, get_from(p_msg)->tag_value.s,
196                         get_from(p_msg)->tag_value.len)!=0)
197                 return 0;
198         return 1;
199 }
200
201 /* are to-tags in ACK/200 same as those we sent out? */
202 static inline int dlg_matching(struct cell *p_cell, struct sip_msg *ack )
203 {
204         if (get_to(ack)->tag_value.len!=p_cell->uas.local_totag.len)
205                 return 0;
206         if (memcmp(get_to(ack)->tag_value.s,p_cell->uas.local_totag.s,
207                                 p_cell->uas.local_totag.len)!=0)
208                 return 0;
209         return 1;
210 }
211
212 static inline int ack_matching(struct cell *p_cell, struct sip_msg *p_msg) 
213 {
214         /* partial dialog matching -- no to-tag, only from-tag, 
215          * callid, cseq number ; */
216         if (!partial_dlg_matching(p_cell->uas.request, p_msg)) 
217                 return 0;
218
219         /* if this transaction is proxied (as opposed to UAS) we're
220          * done now -- we ignore to-tags; the ACK simply belongs to
221          * this UAS part of dialog, whatever to-tag it gained
222          */
223         if (p_cell->relaied_reply_branch!=-2) {
224                 return 2; /* e2e proxied ACK */
225         }
226         /* it's a local dialog -- we wish to verify to-tags too */
227         if (dlg_matching(p_cell, p_msg)) {
228                 return 1;
229         }
230         return 0;
231 }
232
233 /* branch-based transaction matching */
234 static inline int via_matching( struct via_body *inv_via, 
235                                 struct via_body *ack_via )
236 {
237         if (inv_via->tid.len!=ack_via->tid.len)
238                 return 0;
239         if (memcmp(inv_via->tid.s, ack_via->tid.s,
240                                 ack_via->tid.len)!=0)
241                 return 0;
242         /* ok, tid matches -- now make sure that the
243          * originater matches too to avoid confusion with
244          * different senders generating the same tid
245          */
246         if (inv_via->host.len!=ack_via->host.len)
247                 return 0;;
248         if (memcmp(inv_via->host.s, ack_via->host.s,
249                         ack_via->host.len)!=0)
250                 return 0;
251         if (inv_via->port!=ack_via->port)
252                 return 0;
253         if (inv_via->transport.len!=ack_via->transport.len)
254                 return 0;
255         if (memcmp(inv_via->transport.s, ack_via->transport.s,
256                         ack_via->transport.len)!=0)
257                 return 0;
258         /* everything matched -- we found it */
259         return 1;
260 }
261
262
263 /* transaction matching a-la RFC-3261 using transaction ID in branch
264    (the function assumes there is magic cookie in branch) 
265    It returns:
266          2 if e2e ACK for a proxied transaction found
267      1  if found (covers ACK for local UAS)
268          0  if not found (trans undefined)
269 */
270
271 static int matching_3261( struct sip_msg *p_msg, struct cell **trans,
272                         enum request_method skip_method)
273 {
274         struct cell *p_cell;
275         struct sip_msg  *t_msg;
276         struct via_body *via1;
277         int is_ack;
278         int dlg_parsed;
279         int ret;
280
281         via1=p_msg->via1;
282         is_ack=p_msg->REQ_METHOD==METHOD_ACK;
283         dlg_parsed=0;
284         /* update parsed tid */
285         via1->tid.s=via1->branch->value.s+MCOOKIE_LEN;
286         via1->tid.len=via1->branch->value.len-MCOOKIE_LEN;
287
288         for ( p_cell = get_tm_table()->entrys[p_msg->hash_index].first_cell;
289                 p_cell; p_cell = p_cell->next_cell ) 
290         {
291                 t_msg=p_cell->uas.request;
292                 if (skip_method & t_msg->REQ_METHOD)
293                         continue;
294
295                 /* dialog matching needs to be applied for ACK/200s */
296                 if (is_ack && p_cell->uas.status<300) {
297                         /* make sure we have parsed all things we need for dialog
298                          * matching */
299                         if (!dlg_parsed) {
300                                 dlg_parsed=1;
301                                 if (!parse_dlg(p_msg)) {
302                                         LOG(L_ERR, "ERROR: tid_matching: dlg parsing failed\n");
303                                         return 0;
304                                 }
305                         }
306                         ret=ack_matching(p_cell /* t w/invite */, p_msg /* ack */);
307                         if (ret>0) {
308                                 *trans=p_cell;
309                                 return ret; /* 2: e2e proxied ACK, 1 e2e UAS ACK */
310                         }
311                         /* this ACK is neither local "negative" one, nor a proxied
312                          * end-2-end one, nor an end-2-end one for a UAS transaction
313                          * -- we failed to match */
314                         continue;
315                 }
316                 /* now real tid matching occurs  for negative ACKs and any 
317                  * other requests */
318                 if (!via_matching(t_msg->via1 /* inv via */, via1 /* ack */ ))
319                         continue;
320                 /* all matched -- we found the transaction ! */
321                 DBG("DEBUG: RFC3261 transaction matched, tid=%.*s\n",
322                         via1->tid.len, via1->tid.s);
323
324                 *trans=p_cell;
325                 return 1;
326         }
327         /* :-( ... we didn't find any */
328         DBG("DEBUG: RFC3261 transaction matching failed\n");
329         return 0;
330 }
331
332
333 /* function returns:
334  *      negative - transaction wasn't found
335  *                      (-2 = possibly e2e ACK matched )
336  *      positive - transaction found
337  */
338
339 int t_lookup_request( struct sip_msg* p_msg , int leave_new_locked )
340 {
341         struct cell         *p_cell;
342         unsigned int       isACK;
343         struct sip_msg  *t_msg;
344         int ret;
345         struct via_param *branch;
346         int match_status;
347
348         /* parse all*/
349         if (check_transaction_quadruple(p_msg)==0)
350         {
351                 LOG(L_ERR, "ERROR: TM module: t_lookup_request: too few headers\n");
352                 set_t(0);       
353                 /* stop processing */
354                 return 0;
355         }
356
357         /* start searching into the table */
358         if (!p_msg->hash_index)
359                 p_msg->hash_index=hash( p_msg->callid->body , get_cseq(p_msg)->number ) ;
360         isACK = p_msg->REQ_METHOD==METHOD_ACK;
361         DBG("t_lookup_request: start searching: hash=%d, isACK=%d\n",
362                 p_msg->hash_index,isACK);
363
364
365         /* asume not found */
366         ret=-1;
367
368         /* first of all, look if there is RFC3261 magic cookie in branch; if
369          * so, we can do very quick matching and skip the old-RFC bizzar
370          * comparison of many header fields
371          */
372         if (!p_msg->via1) {
373                 LOG(L_ERR, "ERROR: t_lookup_request: no via\n");
374                 set_t(0);       
375                 return 0;
376         }
377         branch=p_msg->via1->branch;
378         if (branch && branch->value.s && branch->value.len>MCOOKIE_LEN
379                         && memcmp(branch->value.s,MCOOKIE,MCOOKIE_LEN)==0) {
380                 /* huhuhu! the cookie is there -- let's proceed fast */
381                 LOCK_HASH(p_msg->hash_index);
382                 match_status=matching_3261(p_msg,&p_cell, 
383                                 /* skip transactions with different method; otherwise CANCEL would 
384                                  * match the previous INVITE trans.  */
385                                 isACK ? ~METHOD_INVITE: ~p_msg->REQ_METHOD);
386                 switch(match_status) {
387                                 case 0: goto notfound;  /* no match */
388                                 case 1: goto found;     /* match */
389                                 case 2: goto e2e_ack;   /* e2e proxy ACK */
390                 }
391         }
392
393         /* ok -- it's ugly old-fashioned transaction matching -- it is
394          * a bit simplified to be fast -- we don't do all the comparisons
395          * of parsed uri, which was simply too bloated */
396         DBG("DEBUG: proceeding to pre-RFC3261 transaction matching\n");
397
398         /* lock the whole entry*/
399         LOCK_HASH(p_msg->hash_index);
400
401         /* all the transactions from the entry are compared */
402         for ( p_cell = get_tm_table()->entrys[p_msg->hash_index].first_cell;
403                   p_cell; p_cell = p_cell->next_cell ) 
404         {
405                 t_msg = p_cell->uas.request;
406
407                 if (!isACK) {   
408                         /* compare lengths first */ 
409                         if (!EQ_LEN(callid)) continue;
410                         if (!EQ_LEN(cseq)) continue;
411                         if (!EQ_LEN(from)) continue;
412                         if (!EQ_LEN(to)) continue;
413                         if (ruri_matching && !EQ_REQ_URI_LEN) continue;
414                         if (!EQ_VIA_LEN(via1)) continue;
415
416                         /* length ok -- move on */
417                         if (!EQ_STR(callid)) continue;
418                         if (!EQ_STR(cseq)) continue;
419                         if (!EQ_STR(from)) continue;
420                         if (!EQ_STR(to)) continue;
421                         if (ruri_matching && !EQ_REQ_URI_STR) continue;
422                         if (!EQ_VIA_STR(via1)) continue;
423
424                         /* request matched ! */
425                         DBG("DEBUG: non-ACK matched\n");
426                         goto found;
427                 } else { /* it's an ACK request*/
428                         /* ACK's relate only to INVITEs */
429                         if (t_msg->REQ_METHOD!=METHOD_INVITE) continue;
430
431                         /* From|To URI , CallID, CSeq # must be always there */
432                         /* compare lengths now */
433                         if (!EQ_LEN(callid)) continue;
434                         /* CSeq only the number without method ! */
435                         if (get_cseq(t_msg)->number.len!=get_cseq(p_msg)->number.len)
436                                 continue;
437                         if (! EQ_LEN(from)) continue;
438                         /* To only the uri -- to many UACs screw up tags  */
439                         if (get_to(t_msg)->uri.len!=get_to(p_msg)->uri.len)
440                                 continue;
441                         if (!EQ_STR(callid)) continue;
442                         if (memcmp(get_cseq(t_msg)->number.s, get_cseq(p_msg)->number.s,
443                                 get_cseq(p_msg)->number.len)!=0) continue;
444                         if (!EQ_STR(from)) continue;
445                         if (memcmp(get_to(t_msg)->uri.s, get_to(p_msg)->uri.s,
446                                 get_to(t_msg)->uri.len)!=0) continue;
447
448                         /* it is e2e ACK/200 */
449                         if (p_cell->uas.status<300) {
450                                 /* all criteria for proxied ACK are ok */
451                                 if (p_cell->relaied_reply_branch!=-2) 
452                                         goto e2e_ack;
453                                 /* it's a local UAS transaction */
454                                 if (dlg_matching(p_cell, p_msg))
455                                         goto found;
456                                 continue;
457                         }
458
459                         /* it is not an e2e ACK/200 -- perhaps it is 
460                          * local negative case; in which case we will want
461                          * more elements to match: r-uri and via; allow
462                          * mismatching r-uri as an config option for broken
463                          * UACs */
464                         if (ruri_matching && ! EQ_REQ_URI_LEN ) continue;
465                         if (! EQ_VIA_LEN(via1)) continue;
466                         if (ruri_matching && !EQ_REQ_URI_STR) continue;
467                         if (!EQ_VIA_STR(via1)) continue;
468
469                         /* wow -- we survived all the check! we matched! */
470                         DBG("DEBUG: non-2xx ACK matched\n");
471                         goto found;
472                 } /* ACK */
473         } /* synonym loop */
474
475 notfound:
476         /* no transaction found */
477         set_t(0);
478         if (!leave_new_locked) {
479                 UNLOCK_HASH(p_msg->hash_index);
480         }
481         DBG("DEBUG: t_lookup_request: no transaction found\n");
482         return -1;
483
484 e2e_ack:
485         t_ack=p_cell;   /* e2e proxied ACK */
486         set_t(0);
487         if (!leave_new_locked) {
488                 UNLOCK_HASH(p_msg->hash_index);
489         }
490         DBG("DEBUG: t_lookup_request: e2e proxy ACK found\n");
491         return -2;
492
493 found:
494         set_t(p_cell);
495         REF_UNSAFE( T );
496         set_kr(REQ_EXIST);
497         UNLOCK_HASH( p_msg->hash_index );
498         DBG("DEBUG: t_lookup_request: transaction found (T=%p)\n",T);
499         return 1;
500 }
501
502
503
504 /* function lookups transaction being cancelled by CANCEL in p_msg;
505  * it returns:
506  *       0 - transaction wasn't found
507  *       T - transaction found
508  */
509 struct cell* t_lookupOriginalT(  struct sip_msg* p_msg )
510 {
511         struct cell     *p_cell;
512         unsigned int     hash_index;
513         struct sip_msg  *t_msg;
514         struct via_param *branch;
515         int ret;
516
517
518         /* start searching in the table */
519         hash_index = p_msg->hash_index;
520         DBG("DEBUG: t_lookupOriginalT: searching on hash entry %d\n",hash_index );
521
522
523         /* first of all, look if there is RFC3261 magic cookie in branch; if
524          * so, we can do very quick matching and skip the old-RFC bizzar
525          * comparison of many header fields
526          */
527         if (!p_msg->via1) {
528                 LOG(L_ERR, "ERROR: t_lookup_request: no via\n");
529                 set_t(0);
530                 return 0;
531         }
532         branch=p_msg->via1->branch;
533         if (branch && branch->value.s && branch->value.len>MCOOKIE_LEN
534                         && memcmp(branch->value.s,MCOOKIE,MCOOKIE_LEN)==0) {
535                 /* huhuhu! the cookie is there -- let's proceed fast */
536                 LOCK_HASH(hash_index);
537                 ret=matching_3261(p_msg, &p_cell,
538                                 /* we are seeking the original transaction --
539                                  * skip CANCEL transactions during search
540                                  */
541                                 METHOD_CANCEL);
542                 if (ret==1) goto found; else goto notfound;
543         }
544
545         /* no cookies --proceed to old-fashioned pre-3261 t-matching */
546
547         LOCK_HASH(hash_index);
548
549         /* all the transactions from the entry are compared */
550         for (p_cell=get_tm_table()->entrys[hash_index].first_cell;
551                 p_cell; p_cell = p_cell->next_cell )
552         {
553                 t_msg = p_cell->uas.request;
554
555                 /* we don't cancel CANCELs ;-) */
556                 if (p_cell->uas.request->REQ_METHOD==METHOD_CANCEL)
557                         continue;
558
559                 /* check lengths now */ 
560                 if (!EQ_LEN(callid))
561                         continue;
562                 if (get_cseq(t_msg)->number.len!=get_cseq(p_msg)->number.len)
563                         continue;
564                 if (!EQ_LEN(from))
565                         continue;
566 #ifdef CANCEL_TAG
567                 if (!EQ_LEN(to))
568                         continue;
569 #else
570                 /* relaxed matching -- we don't care about to-tags anymore,
571                  * many broken UACs screw them up and ignoring them does not
572                  * actually hurt
573                  */
574                 if (get_to(t_msg)->uri.len!=get_to(p_msg)->uri.len)
575                         continue;
576 #endif
577                 if (ruri_matching && !EQ_REQ_URI_LEN)
578                         continue;
579                 if (!EQ_VIA_LEN(via1))
580                         continue;
581
582                 /* check the content now */
583                 if (!EQ_STR(callid))
584                         continue;
585                 if (memcmp(get_cseq(t_msg)->number.s,
586                         get_cseq(p_msg)->number.s,get_cseq(p_msg)->number.len)!=0)
587                         continue;
588                 if (!EQ_STR(from))
589                         continue;
590 #ifdef CANCEL_TAG
591                 if (!EQ_STR(to))
592                         continue;
593 #else
594                 if (memcmp(get_to(t_msg)->uri.s, get_to(p_msg)->uri.s,
595                                         get_to(t_msg)->uri.len)!=0)
596                         continue;
597 #endif
598                 if (ruri_matching && !EQ_REQ_URI_STR)
599                         continue;
600                 if (!EQ_VIA_STR(via1))
601                         continue;
602
603                 /* found */
604                 goto found;
605         }
606
607 notfound:
608         /* no transaction found */
609         DBG("DEBUG: t_lookupOriginalT: no CANCEL maching found! \n" );
610         UNLOCK_HASH(hash_index);
611         DBG("DEBUG: t_lookupOriginalT completed\n");
612         return 0;
613
614 found:
615         DBG("DEBUG: t_lookupOriginalT: canceled transaction"
616                 " found (%p)! \n",p_cell );
617         REF_UNSAFE( p_cell );
618         UNLOCK_HASH(hash_index);
619         DBG("DEBUG: t_lookupOriginalT completed\n");
620         return p_cell;
621 }
622
623
624
625
626 /* Returns 0 - nothing found
627  *         1  - T found
628  */
629 int t_reply_matching( struct sip_msg *p_msg , int *p_branch )
630 {
631         struct cell*  p_cell;
632         int hash_index   = 0;
633         int entry_label  = 0;
634         int branch_id    = 0;
635         char  *hashi, *branchi, *p, *n;
636         int hashl, branchl;
637         int scan_space;
638         str cseq_method;
639         str req_method;
640
641         char *loopi;
642         int loopl;
643         char *syni;
644         int synl;
645         
646         short is_cancel;
647
648         /* make compiler warnnings happy */
649         loopi=0;
650         loopl=0;
651         syni=0;
652         synl=0;
653
654         /* split the branch into pieces: loop_detection_check(ignored),
655          hash_table_id, synonym_id, branch_id */
656
657         if (!(p_msg->via1 && p_msg->via1->branch && p_msg->via1->branch->value.s))
658                 goto nomatch2;
659
660         /* we do RFC 3261 tid matching and want to see first if there is
661          * magic cookie in branch */
662         if (p_msg->via1->branch->value.len<=MCOOKIE_LEN)
663                 goto nomatch2;
664         if (memcmp(p_msg->via1->branch->value.s, MCOOKIE, MCOOKIE_LEN)!=0)
665                 goto nomatch2;
666
667         p=p_msg->via1->branch->value.s+MCOOKIE_LEN;
668         scan_space=p_msg->via1->branch->value.len-MCOOKIE_LEN;
669
670
671         /* hash_id */
672         n=eat_token2_end( p, p+scan_space, BRANCH_SEPARATOR);
673         hashl=n-p;
674         scan_space-=hashl;
675         if (!hashl || scan_space<2 || *n!=BRANCH_SEPARATOR) goto nomatch2;
676         hashi=p;
677         p=n+1;scan_space--;
678
679         if (!syn_branch) {
680                 /* md5 value */
681                 n=eat_token2_end( p, p+scan_space, BRANCH_SEPARATOR );
682                 loopl = n-p;
683                 scan_space-= loopl;
684                 if (n==p || scan_space<2 || *n!=BRANCH_SEPARATOR) 
685                         goto nomatch2;
686                 loopi=p;
687                 p=n+1; scan_space--;
688         } else {
689                 /* synonym id */
690                 n=eat_token2_end( p, p+scan_space, BRANCH_SEPARATOR);
691                 synl=n-p;
692                 scan_space-=synl;
693                 if (!synl || scan_space<2 || *n!=BRANCH_SEPARATOR) 
694                         goto nomatch2;
695                 syni=p;
696                 p=n+1;scan_space--;
697         }
698
699         /* branch id  -  should exceed the scan_space */
700         n=eat_token_end( p, p+scan_space );
701         branchl=n-p;
702         if (!branchl ) goto nomatch2;
703         branchi=p;
704
705         /* sanity check */
706         if ((hash_index=reverse_hex2int(hashi, hashl))<0
707                 ||hash_index>=TABLE_ENTRIES
708                 || (branch_id=reverse_hex2int(branchi, branchl))<0
709                 ||branch_id>=MAX_BRANCHES
710                 || (syn_branch ? (entry_label=reverse_hex2int(syni, synl))<0 
711                         : loopl!=MD5_LEN )
712         ) {
713                 DBG("DEBUG: t_reply_matching: poor reply lables %d label %d "
714                         "branch %d\n",hash_index, entry_label, branch_id );
715                 goto nomatch2;
716         }
717
718
719         DBG("DEBUG: t_reply_matching: hash %d label %d branch %d\n",
720                 hash_index, entry_label, branch_id );
721
722
723         /* search the hash table list at entry 'hash_index'; lock the
724            entry first 
725         */
726         cseq_method=get_cseq(p_msg)->method;
727         is_cancel=cseq_method.len==CANCEL_LEN 
728                 && memcmp(cseq_method.s, CANCEL, CANCEL_LEN)==0;
729         LOCK_HASH(hash_index);
730         for (p_cell = get_tm_table()->entrys[hash_index].first_cell; p_cell; 
731                 p_cell=p_cell->next_cell) {
732
733                 /* first look if branch matches */
734
735                 if (syn_branch) {
736                         if (p_cell->label != entry_label) 
737                                 continue;
738                 } else {
739                         if ( memcmp(p_cell->md5, loopi,MD5_LEN)!=0)
740                                         continue;
741                 }
742
743                 /* sanity check ... too high branch ? */
744                 if ( branch_id>=p_cell->nr_of_outgoings )
745                         continue;
746
747                 /* does method match ? (remember -- CANCELs have the same branch
748                    as cancelled transactions) */
749                 req_method=p_cell->method;
750                 if ( /* method match */
751                         ! ((cseq_method.len==req_method.len 
752                         && memcmp( cseq_method.s, req_method.s, cseq_method.len )==0)
753                         /* or it is a local cancel */
754                         || (is_cancel && p_cell->is_invite 
755                                 /* commented out -- should_cancel_branch set it to
756                                    BUSY_BUFFER to avoid collisions with repliesl;
757                                    thus, we test here by bbuffer size
758                                 */
759                                 /* && p_cell->uac[branch_id].local_cancel.buffer ))) */
760                                 && p_cell->uac[branch_id].local_cancel.buffer_len ))) 
761                         continue;
762
763
764                 /* we passed all disqualifying factors .... the transaction has been
765                    matched !
766                 */
767                 set_t(p_cell);
768                 *p_branch = branch_id;
769                 REF_UNSAFE( T );
770                 UNLOCK_HASH(hash_index);
771                 DBG("DEBUG: t_reply_matching: reply matched (T=%p)!\n",T);
772                 /* if this is a 200 for INVITE, we will wish to store to-tags to be
773                  * able to distuingish retransmissions later and not to call
774                  * TMCB_RESPONSE_OUT uselessly; we do it only if callbacks are
775                  * enabled -- except callback customers, nobody cares about 
776                  * retransmissions of multiple 200/INV or ACK/200s
777                  */
778                 if (p_cell->is_invite && p_msg->REPLY_STATUS>=200 
779                                 && p_msg->REPLY_STATUS<300 
780                                 && ( (!p_cell->local && 
781                                         (callback_array[TMCB_RESPONSE_OUT]||
782                                                 callback_array[TMCB_E2EACK_IN]))
783                                         || (p_cell->local && callback_array[TMCB_LOCAL_COMPLETED]) )) {
784                         if (parse_headers(p_msg, HDR_TO, 0)==-1) {
785                                 LOG(L_ERR, "ERROR: t_reply_matching: to parsing failed\n");
786                         }
787                 }
788                 if (!p_cell->local) 
789                         callback_event(TMCB_RESPONSE_IN, T, p_msg, p_msg->REPLY_STATUS);
790                 return 1;
791         } /* for cycle */
792
793         /* nothing found */
794         UNLOCK_HASH(hash_index);
795         DBG("DEBUG: t_reply_matching: no matching transaction exists\n");
796
797 nomatch2:
798         DBG("DEBUG: t_reply_matching: failure to match a transaction\n");
799         *p_branch = -1;
800         set_t(0);
801         return -1;
802 }
803
804
805
806
807 /* Determine current transaction
808  *
809  *                   Found      Not Found     Error (e.g. parsing)
810  *  Return Value     1          0             -1
811  *  T                ptr        0             T_UNDEFINED
812  */
813 int t_check( struct sip_msg* p_msg , int *param_branch )
814 {
815         int local_branch;
816
817         /* is T still up-to-date ? */
818         DBG("DEBUG: t_check: msg id=%d global id=%d T start=%p\n", 
819                 p_msg->id,global_msg_id,T);
820         if ( p_msg->id != global_msg_id || T==T_UNDEFINED )
821         {
822                 global_msg_id = p_msg->id;
823                 T = T_UNDEFINED;
824                 /* transaction lookup */
825                 if ( p_msg->first_line.type==SIP_REQUEST ) {
826                         /* force parsing all the needed headers*/
827                         if (parse_headers(p_msg, HDR_EOH, 0 )==-1) {
828                                 LOG(L_ERR, "ERROR: t_check: parsing error\n");
829                                 return -1;
830                         }
831                         /* in case, we act as UAS for INVITE and reply with 200,
832                          * we will need to run dialog-matching for subsequent
833                          * ACK, for which we need From-tag; We also need from-tag
834                          * in case people want to have proxied e2e ACKs accounted
835                          */
836                         if (p_msg->REQ_METHOD==METHOD_INVITE 
837                                                         && parse_from_header(p_msg)==-1) {
838                                 LOG(L_ERR, "ERROR: t_check: from parsing failed\n");
839                                 return -1;
840                         }
841                         t_lookup_request( p_msg , 0 /* unlock before returning */ );
842                 } else {
843                         /* we need Via for branch and Cseq method to distinguish
844                            replies with the same branch/cseqNr (CANCEL)
845                         */
846                         if ( parse_headers(p_msg, HDR_VIA1|HDR_CSEQ, 0 )==-1
847                         || !p_msg->via1 || !p_msg->cseq ) {
848                                 LOG(L_ERR, "ERROR: reply cannot be parsed\n");
849                                 return -1;
850                         }
851
852                         /* if that is an INVITE, we will also need to-tag
853                            for later ACK matching
854                         */
855             if ( get_cseq(p_msg)->method.len==INVITE_LEN 
856                                 && memcmp( get_cseq(p_msg)->method.s, INVITE, INVITE_LEN )==0 ) {
857                                         if (parse_headers(p_msg, HDR_TO, 0)==-1
858                                                 || !p_msg->to)  {
859                                                 LOG(L_ERR, "ERROR: INVITE reply cannot be parsed\n");
860                                                 return -1;
861                                         }
862                         }
863
864                         t_reply_matching( p_msg ,
865                                 param_branch!=0?param_branch:&local_branch );
866
867                 }
868 #ifdef EXTRA_DEBUG
869                 if ( T && T!=T_UNDEFINED && T->damocles) {
870                         LOG( L_ERR, "ERROR: transaction %p scheduled for deletion "
871                                 "and called from t_check\n", T);
872                         abort();
873                 }
874 #endif
875                 DBG("DEBUG: t_check: msg id=%d global id=%d T end=%p\n",
876                         p_msg->id,global_msg_id,T);
877         } else {
878                 if (T)
879                         DBG("DEBUG: t_check: T alredy found!\n");
880                 else
881                         DBG("DEBUG: t_check: T previously sought and not found\n");
882         }
883
884         return T ? (T==T_UNDEFINED ? -1 : 1 ) : 0;
885 }
886
887 int init_rb( struct retr_buf *rb, struct sip_msg *msg)
888 {
889         struct socket_info* send_sock;
890         struct via_body* via;
891         int proto;
892
893         via=msg->via1;
894         if (!reply_to_via) {
895                 update_sock_struct_from_ip( &rb->dst.to, msg );
896                 proto=msg->rcv.proto;
897         } else {
898                 /*init retrans buffer*/
899                 if (update_sock_struct_from_via( &(rb->dst.to), msg, via )==-1) {
900                         LOG(L_ERR, "ERROR: init_rb: cannot lookup reply dst: %.*s\n",
901                                 via->host.len, via->host.s );
902                         ser_error=E_BAD_VIA;
903                         return 0;
904                 }
905                 proto=via->proto;
906         }
907         rb->dst.proto=proto;
908         rb->dst.proto_reserved1=msg->rcv.proto_reserved1;
909         send_sock=get_send_socket(&rb->dst.to, proto);
910         if (send_sock==0) {
911                 LOG(L_ERR, "ERROR: init_rb: cannot fwd to af %d, proto %d "
912                         "no socket\n", rb->dst.to.s.sa_family, proto);
913                 ser_error=E_BAD_VIA;
914                 return 0;
915         }
916         rb->dst.send_sock=send_sock;
917         
918     return 1;
919 }
920
921
922
923 /* atomic "new_tran" construct; it returns:
924
925         <0      on error
926
927         +1      if a request did not match a transaction
928                 - it that was an ack, the calling function
929                   shall forward statelessy
930                 - otherwise it means, a new transaction was
931                   introduced and the calling function
932                   shall reply/relay/whatever_appropriate
933
934         0 on retransmission
935 */
936 int t_newtran( struct sip_msg* p_msg )
937 {
938
939         int ret, lret;
940         struct cell *new_cell;
941         struct sip_msg *shm_msg;
942
943         ret=1;
944
945         /* is T still up-to-date ? */
946         DBG("DEBUG: t_addifnew: msg id=%d , global msg id=%d ,"
947                 " T on entrance=%p\n",p_msg->id,global_msg_id,T);
948
949         if ( T && T!=T_UNDEFINED  ) {
950                 LOG(L_ERR, "ERROR: t_newtran: "
951                         "transaction already in process %p\n", T );
952                 return E_SCRIPT;
953         }
954
955         global_msg_id = p_msg->id;
956         T = T_UNDEFINED;
957         /* first of all, parse everything -- we will store
958            in shared memory and need to have all headers
959            ready for generating potential replies later;
960            parsing later on demand is not an option since
961            the request will be in shmem and applying 
962            parse_headers to it would intermix shmem with
963            pkg_mem
964         */
965         
966         if (parse_headers(p_msg, HDR_EOH, 0 )) {
967                 LOG(L_ERR, "ERROR: t_newtran: parse_headers failed\n");
968                 return E_BAD_REQ;
969         }
970         if ((p_msg->parsed_flag & HDR_EOH)!=HDR_EOH) {
971                         LOG(L_ERR, "ERROR: t_newtran: EoH not parsed\n");
972                         return E_OUT_OF_MEM;
973         }
974         /* t_lookup_requests attmpts to find the transaction; 
975            it also calls check_transaction_quadruple -> it is
976            safe to assume we have from/callid/cseq/to
977         */ 
978         lret = t_lookup_request( p_msg, 1 /* leave locked if not found */ );
979         /* on error, pass the error in the stack ... */
980         if (lret==0) return E_BAD_TUPEL;
981         /* transaction not found, it's a new request;
982            establish a new transaction (unless it is an ACK) */
983         if (lret<0) {
984                 new_cell=0;
985                 if ( p_msg->REQ_METHOD!=METHOD_ACK ) {
986                         /* REVIEW */
987                         /* for ACK-dlw-wise matching, we want From-tags */
988                         if (p_msg->REQ_METHOD==METHOD_INVITE) {
989                                 if (parse_from_header(p_msg)<0) {
990                                         LOG(L_ERR, "ERROR: t_newtran: no valid From\n");
991                                         return E_BAD_REQ;
992                                 }
993                         }
994                         /* REVIEW */
995                         /* make sure uri will be parsed before cloning */
996                         if (parse_sip_msg_uri(p_msg)<0) {
997                                 LOG(L_ERR, "ERROR: t_new_tran: uri invalid\n");
998                                 return E_BAD_REQ;
999                         }
1000                         
1001                         /* add new transaction */
1002                         new_cell = build_cell( p_msg ) ;
1003                         if  ( !new_cell ){
1004                                 LOG(L_ERR, "ERROR: t_addifnew: out of mem:\n");
1005                                 ret = E_OUT_OF_MEM;
1006                         } else {
1007                                 insert_into_hash_table_unsafe( new_cell );
1008                                 set_t(new_cell);
1009                                 INIT_REF_UNSAFE(T);
1010                                 /* init pointers to headers needed to construct local
1011                                    requests such as CANCEL/ACK
1012                                 */
1013
1014                                 shm_msg=new_cell->uas.request;
1015                                 new_cell->from.s=shm_msg->from->name.s;
1016                                 new_cell->from.len=HF_LEN(shm_msg->from);
1017                                 new_cell->to.s=shm_msg->to->name.s;
1018                                 new_cell->to.len=HF_LEN(shm_msg->to);
1019                                 new_cell->callid.s=shm_msg->callid->name.s;
1020                                 new_cell->callid.len=HF_LEN(shm_msg->callid);
1021                                 new_cell->cseq_n.s=shm_msg->cseq->name.s;
1022                                 new_cell->cseq_n.len=get_cseq(shm_msg)->number.s
1023                                         +get_cseq(shm_msg)->number.len
1024                                         -shm_msg->cseq->name.s;
1025
1026                                 new_cell->method=new_cell->uas.request->first_line.u.request.method;
1027                                 new_cell->is_invite=p_msg->REQ_METHOD==METHOD_INVITE;
1028                                 new_cell->on_negative=get_on_negative();
1029                                 new_cell->on_reply=get_on_reply();
1030
1031                         }
1032
1033                 }
1034
1035                 /* was it an e2e ACK ? if so, trigger a callback */
1036                 if (lret==-2) {
1037                                 /* no callbacks? complete quickly */
1038                                 if (!callback_array[TMCB_E2EACK_IN]) {
1039                                         UNLOCK_HASH(p_msg->hash_index);
1040                                 } else {
1041                                         REF_UNSAFE(t_ack);
1042                                         UNLOCK_HASH(p_msg->hash_index);
1043                                         /* we don't call from within REPLY_LOCK -- that introduces
1044                                            a race condition; however, it is so unlikely and the
1045                                            impact is so small (callback called multiple times of
1046                                    multiple ACK/200s received in parallel), that we do not
1047                                             better waste time in locks
1048                                          */
1049                                         if (unmatched_totag(t_ack, p_msg)) {
1050                                                 callback_event( TMCB_E2EACK_IN, t_ack, p_msg, 
1051                                                         p_msg->REQ_METHOD );
1052                                         }
1053                                         UNREF(t_ack);
1054                                 }
1055                 } else { /* not e2e ACK */
1056                         UNLOCK_HASH(p_msg->hash_index);
1057                         /* now, when the transaction state exists, check if
1058                            there is a meaningful Via and calculate it; better
1059                            do it now than later: state is established so that
1060                            subsequent retransmissions will be absorbed and will
1061                            not possibly block during Via DNS resolution; doing
1062                            it later would only burn more CPU as if there is an
1063                            error, we cannot relay later whatever comes out of the
1064                            the transaction 
1065                         */
1066                         if (new_cell && p_msg->REQ_METHOD!=METHOD_ACK) {
1067                                 if (!init_rb( &T->uas.response, p_msg)) {
1068                                         LOG(L_ERR, "ERROR: t_newtran: unresolveable via1\n");
1069                                         put_on_wait( T );
1070                                         t_unref(p_msg);
1071                                         ret=E_BAD_VIA;
1072                                 }
1073                         }
1074                 }
1075
1076                 return ret;
1077         } 
1078
1079         /* transaction found, it's a retransmission  or hbh ACK */
1080         if (p_msg->REQ_METHOD==METHOD_ACK) {
1081                 t_release_transaction(T);
1082         } else {
1083                 t_retransmit_reply(T);
1084         }
1085         /* things are done -- return from script */
1086         return 0;
1087
1088 }
1089
1090
1091 int t_unref( struct sip_msg* p_msg  )
1092 {
1093         enum kill_reason kr;
1094
1095         if (T==T_UNDEFINED || T==T_NULL_CELL)
1096                 return -1;
1097         if (p_msg->first_line.type==SIP_REQUEST){
1098                 kr=get_kr();
1099                 if (kr==0 
1100                                 ||(p_msg->REQ_METHOD==METHOD_ACK && !(kr & REQ_RLSD))) {
1101                         LOG(L_WARN, "WARNING: script writer didn't release transaction\n");
1102                         t_release_transaction(T);
1103                 }
1104         }
1105         UNREF( T );
1106         set_t(T_UNDEFINED);
1107         return 1;
1108 }
1109
1110 int t_get_trans_ident(struct sip_msg* p_msg, unsigned int* hash_index, unsigned int* label)
1111 {
1112     struct cell* t;
1113     if(t_check(p_msg,0) != 1){
1114         LOG(L_ERR,"ERROR: t_get_trans_ident: no transaction found\n");
1115         return -1;
1116     }
1117     t = get_t();
1118     if(!t){
1119         LOG(L_ERR,"ERROR: t_get_trans_ident: transaction found is NULL\n");
1120         return -1;
1121     }
1122     
1123     *hash_index = t->hash_index;
1124     *label = t->label;
1125
1126     return 1;
1127 }
1128
1129 int t_lookup_ident(struct cell ** trans, unsigned int hash_index, unsigned int label)
1130 {
1131     struct cell* p_cell;
1132
1133     if(hash_index >= TABLE_ENTRIES){
1134                 LOG(L_ERR,"ERROR: t_lookup_ident: invalid hash_index=%u\n",hash_index);
1135                 return -1;
1136     }
1137
1138     LOCK_HASH(hash_index);
1139
1140     /* all the transactions from the entry are compared */
1141     for ( p_cell = get_tm_table()->entrys[hash_index].first_cell;
1142           p_cell; p_cell = p_cell->next_cell ) 
1143     {
1144                 if(p_cell->label == label){
1145                         REF_UNSAFE(p_cell);
1146                 UNLOCK_HASH(hash_index);
1147                         set_t(p_cell);
1148                         *trans=p_cell;
1149                         DBG("DEBUG: t_lookup_ident: transaction found\n");
1150                         return 1;
1151                 }
1152     }
1153         
1154         UNLOCK_HASH(hash_index);
1155         set_t(0);
1156         *trans=p_cell;
1157
1158         DBG("DEBUG: t_lookup_ident: transaction not found\n");
1159     
1160     return -1;
1161 }
1162
1163 int t_is_local(struct sip_msg* p_msg)
1164 {
1165     struct cell* t;
1166     if(t_check(p_msg,0) != 1){
1167         LOG(L_ERR,"ERROR: t_is_local: no transaction found\n");
1168         return -1;
1169     }
1170     t = get_t();
1171     if(!t){
1172         LOG(L_ERR,"ERROR: t_is_local: transaction found is NULL\n");
1173         return -1;
1174     }
1175     
1176     return t->local;
1177 }