- TM retransmissions disabled for all but UDP
[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-03-01  kr set through a function now (jiri)
55  * 2003-02-28 scratchpad compatibility abandoned (jiri)
56  * 2003-02-27  3261 ACK/200 consumption bug removed (jiri)
57  * 2003-02-24  s/T_NULL/T_NULL_CELL/ to avoid redefinition conflict w/
58  * 2003-02-13  init_rb() is proto indep. & it uses struct dest_info (andrei)
59  * 2003-01-28  scratchpad removed (jiri)
60  * 2003-01-27  next baby-step to removing ZT - PRESERVE_ZT (jiri)
61  * 2003-01-23  options for disabling r-uri matching introduced (jiri)
62  *              nameser_compat.h (andrei)
63  */
64
65
66 #include "defs.h"
67
68
69 #include <assert.h>
70 #include "../../comp_defs.h"
71 #include "../../dprint.h"
72 #include "../../config.h"
73 #include "../../parser/parser_f.h"
74 #include "../../ut.h"
75 #include "../../timer.h"
76 #include "../../hash_func.h"
77 #include "../../globals.h"
78 #include "../../forward.h"
79 #include "t_funcs.h"
80 #include "config.h"
81 #include "sip_msg.h"
82 #include "t_hooks.h"
83 #include "t_lookup.h"
84
85 #define EQ_VIA_LEN(_via)\
86         ( (p_msg->via1->bsize-(p_msg->_via->name.s-(p_msg->_via->hdr.s+p_msg->_via->hdr.len)))==\
87                 (t_msg->via1->bsize-(t_msg->_via->name.s-(t_msg->_via->hdr.s+t_msg->_via->hdr.len))) )
88
89
90
91 #define EQ_LEN(_hf) (t_msg->_hf->body.len==p_msg->_hf->body.len)
92 #define EQ_REQ_URI_LEN\
93         (p_msg->first_line.u.request.uri.len==t_msg->first_line.u.request.uri.len)
94
95 #define EQ_STR(_hf) (memcmp(t_msg->_hf->body.s,\
96         p_msg->_hf->body.s, \
97         p_msg->_hf->body.len)==0)
98 #define EQ_REQ_URI_STR\
99         ( memcmp( t_msg->first_line.u.request.uri.s,\
100         p_msg->first_line.u.request.uri.s,\
101         p_msg->first_line.u.request.uri.len)==0)
102 #define EQ_VIA_STR(_via)\
103         ( memcmp( t_msg->_via->name.s,\
104          p_msg->_via->name.s,\
105          (t_msg->via1->bsize-(t_msg->_via->name.s-(t_msg->_via->hdr.s+t_msg->_via->hdr.len)))\
106         )==0 )
107
108
109
110 #define HF_LEN(_hf) ((_hf)->len)
111
112 /* should be request-uri matching used as a part of pre-3261 
113  * transaction matching, as the standard wants us to do so
114  * (and is reasonable to do so, to be able to distinguish
115  * spirals)? turn only off for better interaction with 
116  * devices that are broken and send different r-uri in
117  * CANCEL/ACK than in original INVITE
118  */
119 int ruri_matching=1;
120
121 /* presumably matching transaction for an e2e ACK */
122 static struct cell *t_ack;
123
124 /* this is a global variable which keeps pointer to
125    transaction currently processed by a process; it it
126    set by t_lookup_request or t_reply_matching; don't
127    dare to change it anywhere else as it would
128    break ref_counting
129 */
130
131 static struct cell *T;
132
133 /* number of currently processed message; good to know
134    to be able to doublecheck whether we are still working
135    on a current transaction or a new message arrived;
136    don't even think of changing it
137 */
138 unsigned int     global_msg_id;
139
140 struct cell *get_t() { return T; }
141 void set_t(struct cell *t) { T=t; }
142 void init_t() {global_msg_id=0; set_t(T_UNDEFINED);}
143
144
145 /* transaction matching a-la RFC-3261 using transaction ID in branch
146  * (the function assumes there is magic cookie in branch) */
147
148 static struct cell *tid_matching( int hash_index, 
149                 struct via_body *via1, 
150                 enum request_method skip_method)
151 {
152         struct cell *p_cell;
153         struct sip_msg  *t_msg;
154
155
156         /* update parsed tid */
157         via1->tid.s=via1->branch->value.s+MCOOKIE_LEN;
158         via1->tid.len=via1->branch->value.len-MCOOKIE_LEN;
159
160         for ( p_cell = get_tm_table()->entrys[hash_index].first_cell;
161                 p_cell; p_cell = p_cell->next_cell ) 
162         {
163                 t_msg=p_cell->uas.request;
164                 if (skip_method & t_msg->REQ_METHOD)
165                         continue;
166                 if (t_msg->via1->tid.len!=via1->tid.len)
167                         continue;
168                 if (memcmp(t_msg->via1->tid.s, via1->tid.s,
169                                 via1->tid.len)!=0)
170                         continue;
171                 /* ok, tid matches -- now make sure that the
172                  * originater matches too to avoid confusion with
173                  * different senders generating the same tid
174                  */
175                 if (via1->host.len!=t_msg->via1->host.len)
176                         continue;
177                 if (memcmp(via1->host.s, t_msg->via1->host.s,
178                                         via1->host.len)!=0)
179                         continue;
180                 if (via1->port!=t_msg->via1->port)
181                         continue;
182                 if (via1->transport.len!=t_msg->via1->transport.len)
183                         continue;
184                 if (memcmp(via1->transport.s, t_msg->via1->transport.s,
185                                         via1->transport.len)!=0)
186                         continue;
187                 /* all matched -- we found the transaction ! */
188                 DBG("DEBUG: RFC3261 transaction matched, tid=%.*s\n",
189                         via1->tid.len, via1->tid.s);
190
191                 return p_cell;
192         }
193         /* :-( ... we didn't find any */
194         DBG("DEBUG: RFC3261 transaction matching failed\n");
195         return 0;
196 }
197
198
199 /* function returns:
200  *      negative - transaction wasn't found
201  *                      (-2 = possibly e2e ACK matched )
202  *      positive - transaction found
203  */
204
205 int t_lookup_request( struct sip_msg* p_msg , int leave_new_locked )
206 {
207         struct cell         *p_cell;
208         unsigned int       isACK;
209         struct sip_msg  *t_msg;
210         int ret;
211         struct via_param *branch;
212
213         /* parse all*/
214         if (check_transaction_quadruple(p_msg)==0)
215         {
216                 LOG(L_ERR, "ERROR: TM module: t_lookup_request: too few headers\n");
217                 set_t(0);       
218                 /* stop processing */
219                 return 0;
220         }
221
222         /* start searching into the table */
223         if (!p_msg->hash_index)
224                 p_msg->hash_index=hash( p_msg->callid->body , 
225                         get_cseq(p_msg)->number ) ;
226         isACK = p_msg->REQ_METHOD==METHOD_ACK;
227         DBG("t_lookup_request: start searching: hash=%d, isACK=%d\n",
228                 p_msg->hash_index,isACK);
229
230
231         /* asume not found */
232         ret=-1;
233
234         /* first of all, look if there is RFC3261 magic cookie in branch; if
235          * so, we can do very quick matching and skip the old-RFC bizzar
236          * comparison of many header fields
237          */
238         if (!p_msg->via1) {
239                 LOG(L_ERR, "ERROR: t_lookup_request: no via\n");
240                 set_t(0);       
241                 return 0;
242         }
243         branch=p_msg->via1->branch;
244         if (branch && branch->value.s && branch->value.len>MCOOKIE_LEN
245                         && memcmp(branch->value.s,MCOOKIE,MCOOKIE_LEN)==0) {
246                 /* huhuhu! the cookie is there -- let's proceed fast */
247                 LOCK_HASH(p_msg->hash_index);
248                 p_cell=tid_matching(p_msg->hash_index, p_msg->via1, 
249                                 /* skip transactions with different
250                                  * method; otherwise CANCEL would 
251                                  * match the previous INVITE trans.
252                                  */
253                                 isACK ? ~METHOD_INVITE: ~p_msg->REQ_METHOD);
254                 if (p_cell) {
255                         /* ACK/200 */
256                         if (isACK && p_cell->uas.status>=200 && p_cell->uas.status<300) {
257                                 /* perhaps there are some spirals on the synonym list, but
258                                    it makes no sense to iterate the list until bitter end */
259                                 t_ack=p_cell;
260                                 ret=-2;
261                                 goto notfound;
262                         }
263                         /* all but 200/ACK */
264                         goto found;
265                 } 
266                 /* new */
267                 goto notfound;
268         }
269
270         /* ok -- it's ugly old-fashioned transaction matching */
271         DBG("DEBUG: proceeding to pre-RFC3261 transaction matching\n");
272
273         /* lock the whole entry*/
274         LOCK_HASH(p_msg->hash_index);
275
276         /* all the transactions from the entry are compared */
277         for ( p_cell = get_tm_table()->entrys[p_msg->hash_index].first_cell;
278                   p_cell; p_cell = p_cell->next_cell ) 
279         {
280                 t_msg = p_cell->uas.request;
281
282                 if (!isACK) {   
283                         /* compare lengths first */ 
284                         if (!EQ_LEN(callid)) continue;
285                         if (!EQ_LEN(cseq)) continue;
286                         if (!EQ_LEN(from)) continue;
287                         if (!EQ_LEN(to)) continue;
288                         if (ruri_matching && !EQ_REQ_URI_LEN) continue;
289                         if (!EQ_VIA_LEN(via1)) continue;
290
291                         /* length ok -- move on */
292                         if (!EQ_STR(callid)) continue;
293                         if (!EQ_STR(cseq)) continue;
294                         if (!EQ_STR(from)) continue;
295                         if (!EQ_STR(to)) continue;
296                         if (ruri_matching && !EQ_REQ_URI_STR) continue;
297                         if (!EQ_VIA_STR(via1)) continue;
298
299                         /* request matched ! */
300                         DBG("DEBUG: non-ACK matched\n");
301                         goto found;
302                 } else { /* it's an ACK request*/
303                         /* ACK's relate only to INVITEs */
304                         if (t_msg->REQ_METHOD!=METHOD_INVITE) continue;
305
306                         /* compare lengths now */
307                         if (!EQ_LEN(callid)) continue;
308                         /* CSeq only the number without method ! */
309                         if (get_cseq(t_msg)->number.len!=get_cseq(p_msg)->number.len)
310                                 continue;
311                         if (! EQ_LEN(from)) continue;
312                         /* To only the uri and ... */
313                         if (get_to(t_msg)->uri.len!=get_to(p_msg)->uri.len)
314                                 continue;
315                         /* don't care about to-tags -- many UAC screw them
316                          * up anyway, and it doesn't hurt if we ignore 
317                          * them */
318 #ifdef ACKTAG
319                         /* ... its to-tag compared to reply's tag */
320                         if (p_cell->uas.to_tag.len!=get_to(p_msg)->tag_value.len)
321                                 continue;
322 #endif
323
324                         /* we first skip r-uri and Via and proceed with
325                            content of other header-fields */
326
327                         if ( memcmp(t_msg->callid->body.s, p_msg->callid->body.s,
328                                 p_msg->callid->body.len)!=0) continue;
329                         if ( memcmp(get_cseq(t_msg)->number.s, get_cseq(p_msg)->number.s,
330                                 get_cseq(p_msg)->number.len)!=0) continue;
331                         if (!EQ_STR(from)) continue;
332                         if (memcmp(get_to(t_msg)->uri.s, get_to(p_msg)->uri.s,
333                                 get_to(t_msg)->uri.len)!=0) continue;
334 #ifdef ACKTAG
335                         if (
336 #ifdef _BUG
337                                 p_cell->uas.to_tag.len!=0 /* to-tags empty */ || 
338 #endif
339                                 memcmp(p_cell->uas.to_tag.s, get_to(p_msg)->tag_value.s,
340                                 p_cell->uas.to_tag.len)!=0) continue;
341 #endif
342         
343                         /* ok, now only r-uri or via can mismatch; they must match
344                            for non-2xx; if it is a 2xx, we don't try to match
345                            (we might have checked that earlier to speed-up, but
346                            we still want to see a diagnosti message telling
347                            "this ACK presumably belongs to this 2xx transaction";
348                            might change in future); the reason is 2xx ACKs are
349                            a separate transaction which may carry different
350                            r-uri/via1 and is thus also impossible to match it
351                            uniquely to a spiraled transaction;
352                         */
353                         if (p_cell->uas.status>=200 && p_cell->uas.status<300) {
354                                 DBG("DEBUG: an ACK hit a 2xx transaction (T=%p); "
355                                         "considered mismatch\n", p_cell );
356                                 /* perhaps there are some spirals on the synonym list, but
357                                    it makes no sense to iterate the list until bitter end */
358                                 t_ack=p_cell;
359                                 ret=-2;
360                                 break;
361                         }
362                         /* its for a >= 300 ... everything must match ! */
363                         if (ruri_matching && ! EQ_REQ_URI_LEN ) continue;
364                         if (! EQ_VIA_LEN(via1)) continue;
365                         if (ruri_matching && !EQ_REQ_URI_STR) continue;
366                         if (!EQ_VIA_STR(via1)) continue;
367
368                         /* wow -- we survived all the check! we matched! */
369                         DBG("DEBUG: non-2xx ACK matched\n");
370                         goto found;
371                 } /* ACK */
372         } /* synonym loop */
373
374 notfound:
375         /* no transaction found */
376         set_t(0);
377         if (!leave_new_locked) {
378                 UNLOCK_HASH(p_msg->hash_index);
379         }
380         DBG("DEBUG: t_lookup_request: no transaction found\n");
381         return ret;
382
383 found:
384         set_t(p_cell);
385         REF_UNSAFE( T );
386         set_kr(T, REQ_EXIST);
387         UNLOCK_HASH( p_msg->hash_index );
388         DBG("DEBUG: t_lookup_request: transaction found (T=%p)\n",T);
389         return 1;
390 }
391
392
393
394 /* function lookups transaction being cancelled by CANCEL in p_msg;
395  * it returns:
396  *       0 - transaction wasn't found
397  *       T - transaction found
398  */
399 struct cell* t_lookupOriginalT(  struct sip_msg* p_msg )
400 {
401         struct cell     *p_cell;
402         unsigned int     hash_index;
403         struct sip_msg  *t_msg;
404         struct via_param *branch;
405
406
407         /* start searching in the table */
408         hash_index = p_msg->hash_index;
409         DBG("DEBUG: t_lookupOriginalT: searching on hash entry %d\n",hash_index );
410
411
412         /* first of all, look if there is RFC3261 magic cookie in branch; if
413          * so, we can do very quick matching and skip the old-RFC bizzar
414          * comparison of many header fields
415          */
416         if (!p_msg->via1) {
417                 LOG(L_ERR, "ERROR: t_lookup_request: no via\n");
418                 set_t(0);
419                 return 0;
420         }
421         branch=p_msg->via1->branch;
422         if (branch && branch->value.s && branch->value.len>MCOOKIE_LEN
423                         && memcmp(branch->value.s,MCOOKIE,MCOOKIE_LEN)==0) {
424                 /* huhuhu! the cookie is there -- let's proceed fast */
425                 LOCK_HASH(hash_index);
426                 p_cell=tid_matching(hash_index, p_msg->via1, 
427                                 /* we are seeking the original transaction --
428                                  * skip CANCEL transactions during search
429                                  */
430                                 METHOD_CANCEL);
431                 if (p_cell) goto found; else goto notfound;
432         }
433
434         /* no cookies --proceed to old-fashioned pre-3261 t-matching */
435
436         LOCK_HASH(hash_index);
437
438         /* all the transactions from the entry are compared */
439         for (p_cell=get_tm_table()->entrys[hash_index].first_cell;
440                 p_cell; p_cell = p_cell->next_cell )
441         {
442                 t_msg = p_cell->uas.request;
443
444                 /* we don't cancel CANCELs ;-) */
445                 if (p_cell->uas.request->REQ_METHOD==METHOD_CANCEL)
446                         continue;
447
448                 /* check lengths now */ 
449                 if (!EQ_LEN(callid))
450                         continue;
451                 if (get_cseq(t_msg)->number.len!=get_cseq(p_msg)->number.len)
452                         continue;
453                 if (!EQ_LEN(from))
454                         continue;
455 #ifdef CANCEL_TAG
456                 if (!EQ_LEN(to))
457                         continue;
458 #else
459                 /* relaxed matching -- we don't care about to-tags anymore,
460                  * many broken UACs screw them up and ignoring them does not
461                  * actually hurt
462                  */
463                 if (get_to(t_msg)->uri.len!=get_to(p_msg)->uri.len)
464                         continue;
465 #endif
466                 if (ruri_matching && !EQ_REQ_URI_LEN)
467                         continue;
468                 if (!EQ_VIA_LEN(via1))
469                         continue;
470
471                 /* check the content now */
472                 if (!EQ_STR(callid))
473                         continue;
474                 if (memcmp(get_cseq(t_msg)->number.s,
475                         get_cseq(p_msg)->number.s,get_cseq(p_msg)->number.len)!=0)
476                         continue;
477                 if (!EQ_STR(from))
478                         continue;
479 #ifdef CANCEL_TAG
480                 if (!EQ_STR(to))
481                         continue;
482 #else
483                 if (memcmp(get_to(t_msg)->uri.s, get_to(p_msg)->uri.s,
484                                         get_to(t_msg)->uri.len)!=0)
485                         continue;
486 #endif
487                 if (ruri_matching && !EQ_REQ_URI_STR)
488                         continue;
489                 if (!EQ_VIA_STR(via1))
490                         continue;
491
492                 /* found */
493                 goto found;
494         }
495
496 notfound:
497         /* no transaction found */
498         DBG("DEBUG: t_lookupOriginalT: no CANCEL maching found! \n" );
499         UNLOCK_HASH(hash_index);
500         DBG("DEBUG: t_lookupOriginalT completed\n");
501         return 0;
502
503 found:
504         DBG("DEBUG: t_lookupOriginalT: canceled transaction"
505                 " found (%p)! \n",p_cell );
506         REF_UNSAFE( p_cell );
507         UNLOCK_HASH(hash_index);
508         DBG("DEBUG: t_lookupOriginalT completed\n");
509         return p_cell;
510 }
511
512
513
514
515 /* Returns 0 - nothing found
516  *         1  - T found
517  */
518 int t_reply_matching( struct sip_msg *p_msg , int *p_branch )
519 {
520         struct cell*  p_cell;
521         int hash_index   = 0;
522         int entry_label  = 0;
523         int branch_id    = 0;
524         char  *hashi, *branchi, *p, *n;
525         int hashl, branchl;
526         int scan_space;
527         str cseq_method;
528         str req_method;
529
530         char *loopi;
531         int loopl;
532         char *syni;
533         int synl;
534         
535         short is_cancel;
536
537         /* make compiler warnnings happy */
538         loopi=0;
539         loopl=0;
540         syni=0;
541         synl=0;
542
543         /* split the branch into pieces: loop_detection_check(ignored),
544          hash_table_id, synonym_id, branch_id */
545
546         if (!(p_msg->via1 && p_msg->via1->branch && p_msg->via1->branch->value.s))
547                 goto nomatch2;
548
549         /* we do RFC 3261 tid matching and want to see first if there is
550          * magic cookie in branch */
551         if (p_msg->via1->branch->value.len<=MCOOKIE_LEN)
552                 goto nomatch2;
553         if (memcmp(p_msg->via1->branch->value.s, MCOOKIE, MCOOKIE_LEN)!=0)
554                 goto nomatch2;
555
556         p=p_msg->via1->branch->value.s+MCOOKIE_LEN;
557         scan_space=p_msg->via1->branch->value.len-MCOOKIE_LEN;
558
559
560         /* hash_id */
561         n=eat_token2_end( p, p+scan_space, BRANCH_SEPARATOR);
562         hashl=n-p;
563         scan_space-=hashl;
564         if (!hashl || scan_space<2 || *n!=BRANCH_SEPARATOR) goto nomatch2;
565         hashi=p;
566         p=n+1;scan_space--;
567
568         if (!syn_branch) {
569                 /* md5 value */
570                 n=eat_token2_end( p, p+scan_space, BRANCH_SEPARATOR );
571                 loopl = n-p;
572                 scan_space-= loopl;
573                 if (n==p || scan_space<2 || *n!=BRANCH_SEPARATOR) 
574                         goto nomatch2;
575                 loopi=p;
576                 p=n+1; scan_space--;
577         } else {
578                 /* synonym id */
579                 n=eat_token2_end( p, p+scan_space, BRANCH_SEPARATOR);
580                 synl=n-p;
581                 scan_space-=synl;
582                 if (!synl || scan_space<2 || *n!=BRANCH_SEPARATOR) 
583                         goto nomatch2;
584                 syni=p;
585                 p=n+1;scan_space--;
586         }
587
588         /* branch id  -  should exceed the scan_space */
589         n=eat_token_end( p, p+scan_space );
590         branchl=n-p;
591         if (!branchl ) goto nomatch2;
592         branchi=p;
593
594         /* sanity check */
595         if ((hash_index=reverse_hex2int(hashi, hashl))<0
596                 ||hash_index>=TABLE_ENTRIES
597                 || (branch_id=reverse_hex2int(branchi, branchl))<0
598                 ||branch_id>=MAX_BRANCHES
599                 || (syn_branch ? (entry_label=reverse_hex2int(syni, synl))<0 
600                         : loopl!=MD5_LEN )
601         ) {
602                 DBG("DEBUG: t_reply_matching: poor reply lables %d label %d "
603                         "branch %d\n",hash_index, entry_label, branch_id );
604                 goto nomatch2;
605         }
606
607
608         DBG("DEBUG: t_reply_matching: hash %d label %d branch %d\n",
609                 hash_index, entry_label, branch_id );
610
611
612         /* search the hash table list at entry 'hash_index'; lock the
613            entry first 
614         */
615         cseq_method=get_cseq(p_msg)->method;
616         is_cancel=cseq_method.len==CANCEL_LEN 
617                 && memcmp(cseq_method.s, CANCEL, CANCEL_LEN)==0;
618         LOCK_HASH(hash_index);
619         for (p_cell = get_tm_table()->entrys[hash_index].first_cell; p_cell; 
620                 p_cell=p_cell->next_cell) {
621
622                 /* first look if branch matches */
623
624                 if (syn_branch) {
625                         if (p_cell->label != entry_label) 
626                                 continue;
627                 } else {
628                         if ( memcmp(p_cell->md5, loopi,MD5_LEN)!=0)
629                                         continue;
630                 }
631
632                 /* sanity check ... too high branch ? */
633                 if ( branch_id>=p_cell->nr_of_outgoings )
634                         continue;
635
636                 /* does method match ? (remember -- CANCELs have the same branch
637                    as cancelled transactions) */
638                 req_method=p_cell->method;
639                 if ( /* method match */
640                         ! ((cseq_method.len==req_method.len 
641                         && memcmp( cseq_method.s, req_method.s, cseq_method.len )==0)
642                         /* or it is a local cancel */
643                         || (is_cancel && p_cell->is_invite 
644                                 /* commented out -- should_cancel_branch set it to
645                                    BUSY_BUFFER to avoid collisions with repliesl;
646                                    thus, we test here by bbuffer size
647                                 */
648                                 /* && p_cell->uac[branch_id].local_cancel.buffer ))) */
649                                 && p_cell->uac[branch_id].local_cancel.buffer_len ))) 
650                         continue;
651
652
653                 /* we passed all disqualifying factors .... the transaction has been
654                    matched !
655                 */
656                 set_t(p_cell);
657                 *p_branch = branch_id;
658                 REF_UNSAFE( T );
659                 UNLOCK_HASH(hash_index);
660                 DBG("DEBUG: t_reply_matching: reply matched (T=%p)!\n",T);
661                 return 1;
662         } /* for cycle */
663
664         /* nothing found */
665         UNLOCK_HASH(hash_index);
666         DBG("DEBUG: t_reply_matching: no matching transaction exists\n");
667
668 nomatch2:
669         DBG("DEBUG: t_reply_matching: failure to match a transaction\n");
670         *p_branch = -1;
671         set_t(0);
672         return -1;
673 }
674
675
676
677
678 /* Functions update T (T gets either a valid pointer in it or it equals zero) if no transaction
679   * for current message exists;
680   * it returns 1 if found, 0 if not found, -1 on error
681   */
682 int t_check( struct sip_msg* p_msg , int *param_branch )
683 {
684         int local_branch;
685
686         /* is T still up-to-date ? */
687         DBG("DEBUG: t_check: msg id=%d global id=%d T start=%p\n", 
688                 p_msg->id,global_msg_id,T);
689         if ( p_msg->id != global_msg_id || T==T_UNDEFINED )
690         {
691                 global_msg_id = p_msg->id;
692                 T = T_UNDEFINED;
693                 /* transaction lookup */
694                 if ( p_msg->first_line.type==SIP_REQUEST ) {
695                         /* force parsing all the needed headers*/
696                         if (parse_headers(p_msg, HDR_EOH, 0 )==-1)
697                                 return -1;
698                         t_lookup_request( p_msg , 0 /* unlock before returning */ );
699                 } else {
700                         /* we need Via for branch and Cseq method to distinguish
701                            replies with the same branch/cseqNr (CANCEL)
702                         */
703                         if ( parse_headers(p_msg, HDR_VIA1|HDR_CSEQ, 0 )==-1
704                         || !p_msg->via1 || !p_msg->cseq ) {
705                                 LOG(L_ERR, "ERROR: reply cannot be parsed\n");
706                                 return -1;
707                         }
708
709                         /* if that is an INVITE, we will also need to-tag
710                            for later ACK matching
711                         */
712             if ( get_cseq(p_msg)->method.len==INVITE_LEN 
713                                 && memcmp( get_cseq(p_msg)->method.s, INVITE, INVITE_LEN )==0 ) {
714                                         if (parse_headers(p_msg, HDR_TO, 0)==-1
715                                                 || !p_msg->to)  {
716                                                 LOG(L_ERR, "ERROR: INVITE reply cannot be parsed\n");
717                                                 return -1;
718                                         }
719                         }
720
721                         t_reply_matching( p_msg ,
722                                 param_branch!=0?param_branch:&local_branch );
723
724                 }
725 #ifdef EXTRA_DEBUG
726                 if ( T && T!=T_UNDEFINED && T->damocles) {
727                         LOG( L_ERR, "ERROR: transaction %p scheduled for deletion "
728                                 "and called from t_check\n", T);
729                         abort();
730                 }
731 #endif
732                 DBG("DEBUG: t_check: msg id=%d global id=%d T end=%p\n",
733                         p_msg->id,global_msg_id,T);
734         } else {
735                 if (T)
736                         DBG("DEBUG: t_check: T alredy found!\n");
737                 else
738                         DBG("DEBUG: t_check: T previously sought and not found\n");
739         }
740
741         return ((T)?1:0) ;
742 }
743
744 int init_rb( struct retr_buf *rb, struct sip_msg *msg)
745 {
746         struct socket_info* send_sock;
747         struct via_body* via;
748         int proto;
749
750         via=msg->via1;
751         if (!reply_to_via) {
752                 update_sock_struct_from_ip( &rb->dst.to, msg );
753                 proto=msg->rcv.proto;
754         } else {
755                 /*init retrans buffer*/
756                 if (update_sock_struct_from_via( &(rb->dst.to),via )==-1) {
757                         LOG(L_ERR, "ERROR: init_rb: cannot lookup reply dst: %.*s\n",
758                                 via->host.len, via->host.s );
759                         ser_error=E_BAD_VIA;
760                         return 0;
761                 }
762                 proto=via->proto;
763         }
764         rb->dst.proto=proto;
765         rb->dst.proto_reserved1=msg->rcv.proto_reserved1;
766         send_sock=get_send_socket(&rb->dst.to, proto);
767         if (send_sock==0) {
768                 LOG(L_ERR, "ERROR: init_rb: cannot fwd to af %d "
769                         "no socket\n", rb->dst.to.s.sa_family);
770                 ser_error=E_BAD_VIA;
771                 return 0;
772         }
773         rb->dst.send_sock=send_sock;
774         
775     return 1;
776 }
777
778
779
780 /* atomic "new_tran" construct; it returns:
781
782         <0      on error
783
784         +1      if a request did not match a transaction
785                 - it that was an ack, the calling function
786                   shall forward statelessy
787                 - otherwise it means, a new transaction was
788                   introduced and the calling function
789                   shall reply/relay/whatever_appropriate
790
791         0 on retransmission
792 */
793 int t_newtran( struct sip_msg* p_msg )
794 {
795
796         int ret, lret;
797         struct cell *new_cell;
798         struct sip_msg *shm_msg;
799
800         ret=1;
801
802         /* is T still up-to-date ? */
803         DBG("DEBUG: t_addifnew: msg id=%d , global msg id=%d ,"
804                 " T on entrance=%p\n",p_msg->id,global_msg_id,T);
805
806         if ( T && T!=T_UNDEFINED  ) {
807                 LOG(L_ERR, "ERROR: t_newtran: "
808                         "transaction already in process %p\n", T );
809                 return E_SCRIPT;
810         }
811
812         global_msg_id = p_msg->id;
813         T = T_UNDEFINED;
814         /* first of all, parse everything -- we will store
815            in shared memory and need to have all headers
816            ready for generating potential replies later;
817            parsing later on demand is not an option since
818            the request will be in shmem and applying 
819            parse_headers to it would intermix shmem with
820            pkg_mem
821         */
822         
823         if (parse_headers(p_msg, HDR_EOH, 0 )) {
824                 LOG(L_ERR, "ERROR: t_newtran: parse_headers failed\n");
825                 return E_BAD_REQ;
826         }
827         if ((p_msg->parsed_flag & HDR_EOH)!=HDR_EOH) {
828                         LOG(L_ERR, "ERROR: t_newtran: EoH not parsed\n");
829                         return E_OUT_OF_MEM;
830         }
831         /* t_lookup_requests attmpts to find the transaction; 
832            it also calls check_transaction_quadruple -> it is
833            safe to assume we have from/callid/cseq/to
834         */ 
835         lret = t_lookup_request( p_msg, 1 /* leave locked if not found */ );
836         /* on error, pass the error in the stack ... */
837         if (lret==0) return E_BAD_TUPEL;
838         /* transaction not found, it's a new request;
839            establish a new transaction (unless it is an ACK) */
840         if (lret<0) {
841                 new_cell=0;
842                 if ( p_msg->REQ_METHOD!=METHOD_ACK ) {
843                         /* add new transaction */
844                         new_cell = build_cell( p_msg ) ;
845                         if  ( !new_cell ){
846                                 LOG(L_ERR, "ERROR: t_addifnew: out of mem:\n");
847                                 ret = E_OUT_OF_MEM;
848                         } else {
849                                 insert_into_hash_table_unsafe( new_cell );
850                                 set_t(new_cell);
851                                 INIT_REF_UNSAFE(T);
852                                 /* init pointers to headers needed to construct local
853                                    requests such as CANCEL/ACK
854                                 */
855
856                                 shm_msg=new_cell->uas.request;
857                                 new_cell->from.s=shm_msg->from->name.s;
858                                 new_cell->from.len=HF_LEN(shm_msg->from);
859                                 new_cell->to.s=shm_msg->to->name.s;
860                                 new_cell->to.len=HF_LEN(shm_msg->to);
861                                 new_cell->callid.s=shm_msg->callid->name.s;
862                                 new_cell->callid.len=HF_LEN(shm_msg->callid);
863                                 new_cell->cseq_n.s=shm_msg->cseq->name.s;
864                                 new_cell->cseq_n.len=get_cseq(shm_msg)->number.s
865                                         +get_cseq(shm_msg)->number.len
866                                         -shm_msg->cseq->name.s;
867
868                                 new_cell->method=new_cell->uas.request->first_line.u.request.method;
869                                 new_cell->is_invite=p_msg->REQ_METHOD==METHOD_INVITE;
870                         }
871
872                 }
873
874                 /* was it an e2e ACK ? if so, trigger a callback */
875                 if (lret==-2) {
876                                 REF_UNSAFE(t_ack);
877                                 UNLOCK_HASH(p_msg->hash_index);
878                                 callback_event( TMCB_E2EACK, t_ack, p_msg, p_msg->REQ_METHOD );
879                                 UNREF(t_ack);
880                 } else { /* not e2e ACK */
881                         UNLOCK_HASH(p_msg->hash_index);
882                         /* now, when the transaction state exists, check if
883                            there is a meaningful Via and calculate it; better
884                            do it now than later: state is established so that
885                            subsequent retransmissions will be absorbed and will
886                            not possibly block during Via DNS resolution; doing
887                            it later would only burn more CPU as if there is an
888                            error, we cannot relay later whatever comes out of the
889                            the transaction 
890                         */
891                         if (new_cell && p_msg->REQ_METHOD!=METHOD_ACK) {
892                                 if (!init_rb( &T->uas.response, p_msg)) {
893                                         LOG(L_ERR, "ERROR: t_newtran: unresolveable via1\n");
894                                         put_on_wait( T );
895                                         t_unref(p_msg);
896                                         ret=E_BAD_VIA;
897                                 }
898                         }
899                 }
900
901                 return ret;
902         } 
903
904         /* transaction found, it's a retransmission  or hbh ACK */
905         if (p_msg->REQ_METHOD==METHOD_ACK) {
906                 t_release_transaction(T);
907         } else {
908                 t_retransmit_reply(T);
909         }
910         /* things are done -- return from script */
911         return 0;
912
913 }
914
915
916 int t_unref( struct sip_msg* p_msg  )
917 {
918         if (T==T_UNDEFINED || T==T_NULL_CELL)
919                 return -1;
920         if (T->kr==0 
921                 ||(p_msg->REQ_METHOD==METHOD_ACK && !(T->kr & REQ_RLSD))) {
922                 LOG(L_WARN, "WARNING: script writer didn't release transaction\n");
923                 t_release_transaction(T);
924         }
925         UNREF( T );
926         set_t(T_UNDEFINED);
927         return 1;
928 }
929
930 #ifdef VOICE_MAIL
931 int t_get_trans_ident(struct sip_msg* p_msg, unsigned int* hash_index, unsigned int* label)
932 {
933     struct cell* t;
934     if(t_check(p_msg,0) != 1){
935         LOG(L_ERR,"ERROR: t_get_trans_ident: no transaction found\n");
936         return -1;
937     }
938     t = get_t();
939     if(!t){
940         LOG(L_ERR,"ERROR: t_get_trans_ident: transaction found is NULL\n");
941         return -1;
942     }
943     
944     *hash_index = t->hash_index;
945     *label = t->label;
946
947     return 1;
948 }
949
950 int t_lookup_ident(struct sip_msg** p_msg, unsigned int hash_index, unsigned int label)
951 {
952     int ret = 0;
953     struct cell* p_cell;
954
955     if(hash_index >= TABLE_ENTRIES){
956         LOG(L_ERR,"ERROR: t_lookup_ident: invalid hash_index=%u\n",hash_index);
957         return -1;
958     }
959
960     LOCK_HASH(hash_index);
961
962     /* all the transactions from the entry are compared */
963     for ( p_cell = get_tm_table()->entrys[hash_index].first_cell;
964           p_cell; p_cell = p_cell->next_cell ) 
965     {
966         if(p_cell->label == label){
967             ret = 1;
968             break;
969         }
970     }
971
972     if(ret==1){
973         DBG("DEBUG: t_lookup_ident: transaction found\n");
974         *p_msg = p_cell->uas.request;
975     }
976     else
977         DBG("DEBUG: t_lookup_ident: transaction not found\n");
978     
979     UNLOCK_HASH(hash_index);
980     return ret;
981 }
982
983 int t_is_local(struct sip_msg* p_msg)
984 {
985     struct cell* t;
986     if(t_check(p_msg,0) != 1){
987         LOG(L_ERR,"ERROR: t_is_local: no transaction found\n");
988         return -1;
989     }
990     t = get_t();
991     if(!t){
992         LOG(L_ERR,"ERROR: t_is_local: transaction found is NULL\n");
993         return -1;
994     }
995     
996     return t->local;
997 }
998
999 #endif
1000
1001
1002