tm: keep internal retr. intervals in ms
[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 works 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 would 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 instantiation (jiri)
72  * 2003-04-30  t_newtran clean up (jiri)
73  * 2003-08-21  request lookups fixed to skip UAC transactions, 
74  *             thanks Ed (jiri)
75  * 2003-12-04  global TM callbacks switched to per transaction callbacks
76  *             (bogdan)
77  * 2004-02-11  FIFO/CANCEL + alignments (hash=f(callid,cseq)) (uli+jiri)
78  * 2004-02-13: t->is_invite and t->local replaced with flags (bogdan)
79  * 2004-10-10: use of mhomed disabled for replies (jiri)
80  * 2005-02-01: use the incoming request interface for sending the replies
81  *             - changes in init_rb() (bogdan)
82  * 2005-12-09  added t_set_fr()  (andrei)
83  * 2006-01-27  transaction lookup function will set up a cancel flag
84  *             if the searched transaction was pre-canceled (andrei)
85  * 2006-10-16  401 & 407 replies are completely parsed if tm_aggregate_auth is
86  *              set (andrei)
87  * 2006-11-10  a valid msg->hash_index is now marked by FL_HASH_INDEX in 
88  *              msg_flags
89  *             t_lookupOriginalT computes the hash_index by itself  if 
90  *               needed (andrei)
91  * 2007-03-17  added callbacks for retransmitted request, ack to negative 
92  *              replies and replies to local transactions (andrei)
93  * 2007-06-01  support for different retransmissions intervals per transaction;
94  *             added maximum inv. and non-inv. transaction life time (andrei)
95  * 2007-06-05  added delayed error reply support in t_unref;
96 *              added support for turning off 100 repl. sending on inv. (andrei)
97  * 2007-06-01  support for different retransmissions intervals per transaction;
98  *             added maximum inv. and non-inv. transaction life time (andrei)
99  * 2007-06-06  switched tm bucket list to a simpler and faster clist;
100  * 2008-02-28  try matching e2e acks in t_lookup() only for transactions
101  *               which have E2EACK callbacks registered (andrei)
102  * 2008-03-31  message flags are updated in shared memory even if they are set
103  *             after t_newtran() (Miklos)
104  * 2009-06-24  added T_branch and changed set_t() to take also a branch
105  *              parameter (andrei)
106  */
107
108 #include "defs.h"
109
110
111 #include "../../comp_defs.h"
112 #include "../../compiler_opt.h"
113 #include "../../dprint.h"
114 #include "../../config.h"
115 #include "../../parser/parser_f.h"
116 #include "../../parser/parse_from.h"
117 #include "../../ut.h"
118 #include "../../timer.h"
119 #include "../../timer_ticks.h"
120 #include "../../hash_func.h"
121 #include "../../globals.h"
122 #include "../../forward.h"
123 #include "t_funcs.h"
124 #include "config.h"
125 #include "sip_msg.h"
126 #include "t_hooks.h"
127 #include "t_fwd.h"
128 #include "t_lookup.h"
129 #include "dlg.h" /* for t_lookup_callid */
130 #include "t_msgbuilder.h" /* for t_lookup_callid */
131
132 #define EQ_VIA_LEN(_via)\
133         ( (p_msg->via1->bsize-(p_msg->_via->name.s-(p_msg->_via->hdr.s+p_msg->_via->hdr.len)))==\
134                 (t_msg->via1->bsize-(t_msg->_via->name.s-(t_msg->_via->hdr.s+t_msg->_via->hdr.len))) )
135
136
137
138 #define EQ_LEN(_hf) (t_msg->_hf->body.len==p_msg->_hf->body.len)
139 #define EQ_REQ_URI_LEN\
140         (p_msg->first_line.u.request.uri.len==t_msg->first_line.u.request.uri.len)
141
142 #define EQ_STR(_hf) (memcmp(t_msg->_hf->body.s,\
143         p_msg->_hf->body.s, \
144         p_msg->_hf->body.len)==0)
145 #define EQ_REQ_URI_STR\
146         ( memcmp( t_msg->first_line.u.request.uri.s,\
147         p_msg->first_line.u.request.uri.s,\
148         p_msg->first_line.u.request.uri.len)==0)
149 #define EQ_VIA_STR(_via)\
150         ( memcmp( t_msg->_via->name.s,\
151          p_msg->_via->name.s,\
152          (t_msg->via1->bsize-(t_msg->_via->name.s-(t_msg->_via->hdr.s+t_msg->_via->hdr.len)))\
153         )==0 )
154
155
156
157 #define HF_LEN(_hf) ((_hf)->len)
158
159 /* presumably matching transaction for an e2e ACK */
160 static struct cell *t_ack;
161
162 /* this is a global variable which keeps pointer to
163    transaction currently processed by a process; it it
164    set by t_lookup_request or t_reply_matching; don't
165    dare to change it anywhere else as it would
166    break ref_counting.
167    It has a valid value only if:
168     - it's checked inside a failure or tm on_reply route (not core 
169       on_reply[0]!)
170     - global_msg_id == msg->id in all the other kinds of routes
171       Note that this is the safest check and is valid also for
172       failure routes (because fake_env() sets global_msg_id) or tm
173       tm onreply routes (the internal reply_received() t_check() will set
174       T and global_msg_id).
175 */
176 static struct cell *T;
177
178 /* this is a global variable which keeps the current branch
179    for the transaction currently processed.
180    It has a valid value only if T is valid (global_msg_id==msg->id -- see
181    above, and T!=0 and T!=T_UNDEFINED).
182    For a request it's value is T_BR_UNDEFINED (it can have valid values only
183    for replies).
184 */
185 static int T_branch;
186
187 /* number of currently processed message; good to know
188    to be able to doublecheck whether we are still working
189    on a current transaction or a new message arrived;
190    don't even think of changing it.
191 */
192 unsigned int     global_msg_id;
193
194
195
196 struct cell *get_t() { return T; }
197 void set_t(struct cell *t, int branch) { T=t; T_branch=branch; }
198 void init_t() {global_msg_id=0; set_t(T_UNDEFINED, T_BR_UNDEFINED);}
199 int get_t_branch() { return T_branch; }
200
201 static inline int parse_dlg( struct sip_msg *msg )
202 {
203         if (parse_headers(msg, HDR_FROM_F | HDR_CSEQ_F | HDR_TO_F, 0)==-1) {
204                 LOG(L_ERR, "ERROR: parse_dlg: From or Cseq or To invalid\n");
205                 return 0;
206         }
207         if ((msg->from==0)||(msg->cseq==0)||(msg->to==0)) {
208                 LOG(L_ERR, "ERROR: parse_dlg: missing From or Cseq or To\n");
209                 return 0;
210         }
211
212         if (parse_from_header(msg)==-1) {
213                 LOG(L_ERR, "ERROR: parse_dlg: From broken\n");
214                 return 0;
215         }
216         /* To is automatically parsed through HDR_TO in parse bitmap,
217          * we don't need to worry about it now
218         if (parse_to_header(msg)==-1) {
219                 LOG(L_ERR, "ERROR: tid_matching: To broken\n");
220                 return 0;
221         }
222         */
223         return 1;
224 }
225
226 /* is the ACK (p_msg) in p_msg dialog-wise equal to the INVITE (t_msg) 
227  * except to-tags? */
228 static inline int partial_dlg_matching(struct sip_msg *t_msg, struct sip_msg *p_msg)
229 {
230         struct to_body *inv_from;
231
232         if (!EQ_LEN(callid)) return 0;
233         if (get_cseq(t_msg)->number.len!=get_cseq(p_msg)->number.len)
234                 return 0;
235         inv_from=get_from(t_msg);
236         if (!inv_from) {
237                 LOG(L_ERR, "ERROR: partial_dlg_matching: INV/From not parsed\n");
238                 return 0;
239         }
240         if (inv_from->tag_value.len!=get_from(p_msg)->tag_value.len)
241                 return 0;
242         if (!EQ_STR(callid)) 
243                 return 0;
244         if (memcmp(get_cseq(t_msg)->number.s, get_cseq(p_msg)->number.s,
245                         get_cseq(p_msg)->number.len)!=0)
246                 return 0;
247         if (memcmp(inv_from->tag_value.s, get_from(p_msg)->tag_value.s,
248                         get_from(p_msg)->tag_value.len)!=0)
249                 return 0;
250         return 1;
251 }
252
253 /* are to-tags in ACK/200 same as those we sent out? */
254 static inline int dlg_matching(struct cell *p_cell, struct sip_msg *ack )
255 {
256         if (get_to(ack)->tag_value.len!=p_cell->uas.local_totag.len)
257                 return 0;
258         if (memcmp(get_to(ack)->tag_value.s,p_cell->uas.local_totag.s,
259                                 p_cell->uas.local_totag.len)!=0)
260                 return 0;
261         return 1;
262 }
263
264
265
266 /* returns 2 if one of the save totags matches the totag in the current
267  * message (which should be an ACK) and 0 if not */
268 static inline int totag_e2e_ack_matching(struct cell* p_cell, 
269                                                                                                 struct sip_msg *ack)
270 {
271         struct totag_elem *i;
272         str *tag;
273         
274         tag=&get_to(ack)->tag_value;
275         /* no locking needed for reading/searching, see update_totag_set() */
276         for (i=p_cell->fwded_totags; i; i=i->next){
277                 membar_depends(); /* make sure we don't see some old i content
278                                                         (needed on CPUs like Alpha) */
279                 if (i->tag.len==tag->len && memcmp(i->tag.s, tag->s, tag->len)==0) {
280                         return 2;
281                 }
282         }
283         return 0;
284 }
285
286
287
288 /* returns: 0 - no match
289  *          1 - full match to a local transaction
290  *          2 - full match to a proxied transaction
291  *          3 - partial match to a proxied transaction (totag not checked) =>
292  *          care must be taken not to falsely match an ACK for a negative
293  *          reply to a "fork" of the transaction
294  */
295 static inline int ack_matching(struct cell *p_cell, struct sip_msg *p_msg) 
296 {
297         /* partial dialog matching -- no to-tag, only from-tag, 
298          * callid, cseq number ; */
299         if (!partial_dlg_matching(p_cell->uas.request, p_msg)) 
300                 return 0;
301
302         /* if this transaction is proxied (as opposed to UAS) we're
303          * done now -- we ignore to-tags; the ACK simply belongs to
304          * this UAS part of dialog, whatever to-tag it gained
305          */
306         if (likely(p_cell->relayed_reply_branch!=-2)) {
307                 if (likely(has_tran_tmcbs(p_cell, 
308                                                         TMCB_E2EACK_IN|TMCB_E2EACK_RETR_IN)))
309                         return totag_e2e_ack_matching(p_cell, p_msg); /* 2 or 0 */
310                 else
311                         LOG(L_WARN, "WARNING: ack_matching() attempted on"
312                                         " a transaction with no E2EACK callbacks => the results"
313                                         " are not completely reliable when forking is involved\n");
314                 return 3; /* e2e proxied ACK partial match */
315         }
316         /* it's a local dialog -- we wish to verify to-tags too */
317         if (dlg_matching(p_cell, p_msg)) {
318                 return 1;
319         }
320         return 0;
321 }
322
323 /* branch-based transaction matching */
324 static inline int via_matching( struct via_body *inv_via, 
325                                 struct via_body *ack_via )
326 {
327         if (inv_via->tid.len!=ack_via->tid.len)
328                 return 0;
329         if (memcmp(inv_via->tid.s, ack_via->tid.s,
330                                 ack_via->tid.len)!=0)
331                 return 0;
332         /* ok, tid matches -- now make sure that the
333          * originator matches too to avoid confusion with
334          * different senders generating the same tid
335          */
336         if (inv_via->host.len!=ack_via->host.len)
337                 return 0;;
338         if (memcmp(inv_via->host.s, ack_via->host.s,
339                         ack_via->host.len)!=0)
340                 return 0;
341         if (inv_via->port!=ack_via->port)
342                 return 0;
343         if (inv_via->transport.len!=ack_via->transport.len)
344                 return 0;
345         if (memcmp(inv_via->transport.s, ack_via->transport.s,
346                         ack_via->transport.len)!=0)
347                 return 0;
348         /* everything matched -- we found it */
349         return 1;
350 }
351
352
353 /* transaction matching a-la RFC-3261 using transaction ID in branch
354    (the function assumes there is magic cookie in branch) 
355    It returns:
356          2 if e2e ACK for a proxied transaction found
357      1  if found (covers ACK for local UAS)
358          0  if not found (trans undefined)
359         It also sets *cancel if a cancel was found for the searched transaction
360 */
361
362 static int matching_3261( struct sip_msg *p_msg, struct cell **trans,
363                         enum request_method skip_method, int* cancel)
364 {
365         struct cell *p_cell;
366         struct cell *e2e_ack_trans;
367         struct sip_msg  *t_msg;
368         struct via_body *via1;
369         int is_ack;
370         int dlg_parsed;
371         int ret = 0;
372         struct entry* hash_bucket;
373
374         *cancel=0;
375         e2e_ack_trans=0;
376         via1=p_msg->via1;
377         is_ack=p_msg->REQ_METHOD==METHOD_ACK;
378         dlg_parsed=0;
379         /* update parsed tid */
380         via1->tid.s=via1->branch->value.s+MCOOKIE_LEN;
381         via1->tid.len=via1->branch->value.len-MCOOKIE_LEN;
382
383         hash_bucket=&(get_tm_table()->entries[p_msg->hash_index]);
384         clist_foreach(hash_bucket, p_cell, next_c){
385                 prefetch_loc_r(p_cell->next_c, 1);
386                 t_msg=p_cell->uas.request;
387                 if (unlikely(!t_msg)) continue;/*don't try matching UAC transactions */
388                 /* we want to set *cancel for transaction for which there is
389                  * already a canceled transaction (e.g. re-ordered INV-CANCEL, or
390                  *  INV blocked in dns lookup); we don't care about ACKs */
391                 if ((is_ack || (t_msg->REQ_METHOD!=METHOD_CANCEL)) && 
392                                 (skip_method & t_msg->REQ_METHOD)) 
393                         continue;
394
395                 /* here we do an exercise which will be removed from future code
396                    versions: we try to match end-2-end ACKs if they appear at our
397                    server. This allows some applications bound to TM via callbacks
398                    to correlate the e2e ACKs with transaction context, e.g., for
399                    purpose of accounting. We think it is a bad place here, among
400                    other things because it is not reliable. If a transaction loops
401                    via SER the ACK can't be matched to proper INVITE transaction
402                    (it is a separate transactino with its own branch ID) and it
403                    matches all transaction instances in the loop dialog-wise.
404                    Eventually, regardless to which transaction in the loop the
405                    ACK belongs, only the first one will match.
406                 */
407
408                 /* dialog matching needs to be applied for ACK/200s but only if
409                  * this is a local transaction or its a proxied transaction interested
410                  *  in e2e ACKs (has E2EACK* callbacks installed) */
411                 if (unlikely(is_ack && p_cell->uas.status<300)) {
412                         if (unlikely(has_tran_tmcbs(p_cell, 
413                                                         TMCB_E2EACK_IN|TMCB_E2EACK_RETR_IN) ||
414                                                         (p_cell->relayed_reply_branch==-2)  )) {
415                                 /* make sure we have parsed all things we need for dialog
416                                  * matching */
417                                 if (!dlg_parsed) {
418                                         dlg_parsed=1;
419                                         if (unlikely(!parse_dlg(p_msg))) {
420                                                 LOG(L_INFO, "ERROR: matching_3261: dlg parsing "
421                                                                 "failed\n");
422                                                 return 0;
423                                         }
424                                 }
425                                 ret=ack_matching(p_cell /* t w/invite */, p_msg /* ack */);
426                                 if (unlikely(ret>0)) {
427                                         /* if ret==1 => fully matching e2e ack for local trans 
428                                          * if ret==2 => matching e2e ack for proxied  transaction.
429                                          *  which is interested in it (E2EACK* callbacks)
430                                          * if ret==3 => partial match => we should at least
431                                          *  make sure the ACK is not for a negative reply
432                                          *  (FIXME: ret==3 should never happen, it's a bug catch
433                                          *    case)*/
434                                         if (unlikely(ret==1)) goto found;
435                                         if (unlikely(ret==3)){
436                                                 if (e2e_ack_trans==0)
437                                                         e2e_ack_trans=p_cell;
438                                                 continue; /* maybe we get a better 
439                                                                                                            match for a neg. 
440                                                                                                            replied trans. */
441                                         }
442                                         e2e_ack_trans=p_cell;
443                                         goto e2eack_found;
444                                 }
445                                 /* this ACK is neither local "negative" one, nor a proxied
446                                 * end-2-end one, nor an end-2-end one for a UAS transaction
447                                 * -- we failed to match */
448                                 continue;
449                         }
450                         /* not interested, it's an ack and a 2xx replied
451                           transaction but the transaction is not local and
452                           the transaction is not interested in e2eacks (no e2e callbacks)*/
453                         continue;
454                 }
455                 /* now real tid matching occurs  for negative ACKs and any 
456                  * other requests */
457                 if (!via_matching(t_msg->via1 /* inv via */, via1 /* ack */ ))
458                         continue;
459                 if (t_msg->REQ_METHOD==METHOD_CANCEL){
460                         if ((p_msg->REQ_METHOD!=METHOD_CANCEL) && !is_ack){
461                         /* found an existing cancel for the searched transaction */
462                                 *cancel=1;
463                         }
464                         if (skip_method & t_msg->REQ_METHOD) continue;
465                 }
466 found:
467                 prefetch_w(p_cell); /* great chance of modifiying it */
468                 /* all matched -- we found the transaction ! */
469                 DBG("DEBUG: RFC3261 transaction matched, tid=%.*s\n",
470                         via1->tid.len, via1->tid.s);
471                 *trans=p_cell;
472                 return 1;
473         }
474         /* :-( ... we didn't find any */
475         
476         /* just check if it we found an e2e ACK previously
477          * (Note: this is not very reliable, since we match e2e proxy ACKs
478          *  w/o totag => for a pre-forked invite it might match the wrong
479          *  transaction) */
480         if (e2e_ack_trans) {
481 e2eack_found:
482                 *trans=e2e_ack_trans;
483                 return 2;
484         }
485         DBG("DEBUG: RFC3261 transaction matching failed\n");
486         return 0;
487 }
488
489
490 /** find the transaction corresponding to a request.
491  *  @return - negative - transaction wasn't found (-1) or
492  *                        possible e2eACK match (-2).
493  *            1        - transaction found
494  *            0        - parse error
495  * It also sets *cancel if there is already a cancel transaction.
496  * Side-effects: sets T and T_branch 
497  * (T_branch is always set to T_BR_UNDEFINED).
498  */
499
500 int t_lookup_request( struct sip_msg* p_msg , int leave_new_locked,
501                                                 int* cancel)
502 {
503         struct cell         *p_cell;
504         unsigned int       isACK;
505         struct sip_msg  *t_msg;
506         struct via_param *branch;
507         int match_status;
508         struct cell *e2e_ack_trans;
509         struct entry* hash_bucket;
510
511         /* parse all*/
512         if (unlikely(check_transaction_quadruple(p_msg)==0))
513         {
514                 LOG(L_ERR, "ERROR: TM module: t_lookup_request: too few headers\n");
515                 set_t(0, T_BR_UNDEFINED);
516                 /* stop processing */
517                 return 0;
518         }
519
520         /* start searching into the table */
521         if (!(p_msg->msg_flags & FL_HASH_INDEX)){
522                 p_msg->hash_index=hash( p_msg->callid->body , get_cseq(p_msg)->number);
523                 p_msg->msg_flags|=FL_HASH_INDEX;
524         }
525         isACK = p_msg->REQ_METHOD==METHOD_ACK;
526         DBG("t_lookup_request: start searching: hash=%d, isACK=%d\n",
527                 p_msg->hash_index,isACK);
528
529
530         /* assume not found */
531         e2e_ack_trans = 0;
532
533         /* first of all, look if there is RFC3261 magic cookie in branch; if
534          * so, we can do very quick matching and skip the old-RFC bizzar
535          * comparison of many header fields
536          */
537         if (!p_msg->via1) {
538                 LOG(L_ERR, "ERROR: t_lookup_request: no via\n");
539                 set_t(0, T_BR_UNDEFINED);
540                 return 0;
541         }
542         branch=p_msg->via1->branch;
543         if (branch && branch->value.s && branch->value.len>MCOOKIE_LEN
544                         && memcmp(branch->value.s,MCOOKIE,MCOOKIE_LEN)==0) {
545                 /* huhuhu! the cookie is there -- let's proceed fast */
546                 LOCK_HASH(p_msg->hash_index);
547                 match_status=matching_3261(p_msg,&p_cell, 
548                                 /* skip transactions with different method; otherwise CANCEL 
549                                  * would  match the previous INVITE trans.  */
550                                 isACK ? ~METHOD_INVITE: ~p_msg->REQ_METHOD, 
551                                 cancel);
552                 switch(match_status) {
553                                 case 0: goto notfound;  /* no match */
554                                 case 1:  goto found;    /* match */
555                                 case 2: goto e2e_ack;   /* e2e proxy ACK */
556                 }
557         }
558
559         /* ok -- it's ugly old-fashioned transaction matching -- it is
560          * a bit simplified to be fast -- we don't do all the comparisons
561          * of parsed uri, which was simply too bloated */
562         DBG("DEBUG: proceeding to pre-RFC3261 transaction matching\n");
563         *cancel=0;
564         /* lock the whole entry*/
565         LOCK_HASH(p_msg->hash_index);
566
567         hash_bucket=&(get_tm_table()->entries[p_msg->hash_index]);
568         
569         if (likely(!isACK)) {   
570                 /* all the transactions from the entry are compared */
571                 clist_foreach(hash_bucket, p_cell, next_c){
572                         prefetch_loc_r(p_cell->next_c, 1);
573                         t_msg = p_cell->uas.request;
574                         if (!t_msg) continue; /* skip UAC transactions */
575                         /* for non-ACKs we want same method matching, we 
576                          * make an exception for pre-exisiting CANCELs because we
577                          * want to set *cancel */
578                         if ((t_msg->REQ_METHOD!=p_msg->REQ_METHOD) &&
579                                         (t_msg->REQ_METHOD!=METHOD_CANCEL))
580                                         continue;
581                         /* compare lengths first */ 
582                         if (!EQ_LEN(callid)) continue;
583                         /* CSeq only the number without method ! */
584                         if (get_cseq(t_msg)->number.len!=get_cseq(p_msg)->number.len)
585                                 continue;
586                         if (!EQ_LEN(from)) continue;
587                         if (!EQ_LEN(to)) continue;
588                         if (cfg_get(tm, tm_cfg, ruri_matching) && !EQ_REQ_URI_LEN) 
589                                 continue;
590                         if (cfg_get(tm, tm_cfg, via1_matching) && !EQ_VIA_LEN(via1))
591                                 continue;
592                         /* length ok -- move on */
593                         if (!EQ_STR(callid)) continue;
594                         if (memcmp(get_cseq(t_msg)->number.s, get_cseq(p_msg)->number.s,
595                                 get_cseq(p_msg)->number.len)!=0) continue;
596                         if (!EQ_STR(from)) continue;
597                         if (!EQ_STR(to)) continue;
598                         if (cfg_get(tm, tm_cfg, ruri_matching) && !EQ_REQ_URI_STR)
599                                 continue;
600                         if (cfg_get(tm, tm_cfg, via1_matching) && !EQ_VIA_STR(via1))
601                                 continue;
602                         
603                         if ((t_msg->REQ_METHOD==METHOD_CANCEL) &&
604                                 (p_msg->REQ_METHOD!=METHOD_CANCEL)){
605                                 /* we've matched an existing CANCEL */
606                                 *cancel=1;
607                                 continue;
608                         }
609                         
610                         /* request matched ! */
611                         DBG("DEBUG: non-ACK matched\n");
612                         goto found;
613                 } /* synonym loop */
614         } else { /* it's an ACK request*/
615                 /* all the transactions from the entry are compared */
616                 clist_foreach(hash_bucket, p_cell, next_c){
617                         prefetch_loc_r(p_cell->next_c, 1);
618                         t_msg = p_cell->uas.request;
619                         if (!t_msg) continue; /* skip UAC transactions */
620                         /* ACK's relate only to INVITEs */
621                         if (t_msg->REQ_METHOD!=METHOD_INVITE) continue;
622                         /* From|To URI , CallID, CSeq # must be always there */
623                         /* compare lengths now */
624                         if (!EQ_LEN(callid)) continue;
625                         /* CSeq only the number without method ! */
626                         if (get_cseq(t_msg)->number.len!=get_cseq(p_msg)->number.len)
627                                 continue;
628                         /* To only the uri -- to many UACs screw up tags  */
629                         if (get_to(t_msg)->uri.len!=get_to(p_msg)->uri.len)
630                                 continue;
631                         if (!EQ_STR(callid)) continue;
632                         if (memcmp(get_cseq(t_msg)->number.s, get_cseq(p_msg)->number.s,
633                                 get_cseq(p_msg)->number.len)!=0) continue;
634                         if (memcmp(get_to(t_msg)->uri.s, get_to(p_msg)->uri.s,
635                                 get_to(t_msg)->uri.len)!=0) continue;
636                         
637                         /* it is e2e ACK/200 */
638                         if (p_cell->uas.status<300) {
639                                 /* For e2e ACKs, From's tag 'MUST' equal INVITE's, while use
640                                  * of the URI in this case is to be deprecated (Sec. 12.2.1.1).
641                                  * Comparing entire From body is dangerous, since some UAs
642                                  * screw the display name up. */
643                                 if (parse_from_header(p_msg) < 0) {
644                                         ERR("failed to parse From HF; ACK might not match.\n");
645                                         continue;
646                                 }
647                                 if (! STR_EQ(get_from(t_msg)->tag_value, 
648                                                 get_from(p_msg)->tag_value))
649                                         continue;
650 #ifdef TM_E2E_ACK_CHECK_FROM_URI
651                                 if (! STR_EQ(get_from(t_msg)->uri, 
652                                                 get_from(p_msg)->uri))
653                                         continue;
654 #endif
655
656                                 /* all criteria for proxied ACK are ok */
657                                 if (likely(p_cell->relayed_reply_branch!=-2)) {
658                                         if (unlikely(has_tran_tmcbs(p_cell, 
659                                                                         TMCB_E2EACK_IN|TMCB_E2EACK_RETR_IN))){
660                                                 if (likely(totag_e2e_ack_matching(p_cell, p_msg)==2))
661                                                         goto e2e_ack;
662                                                 else if (e2e_ack_trans==0)
663                                                         e2e_ack_trans=p_cell;
664                                         }
665                                         continue;
666                                 }
667                                 /* it's a local UAS transaction */
668                                 if (dlg_matching(p_cell, p_msg))
669                                         goto found;
670                                 continue;
671                         } else {
672                                 /* for hbh ACKs, From HF 'MUST' equal INVITE's one */
673                                 if (! EQ_LEN(from)) continue;
674                                 if (! EQ_STR(from)) continue;
675                         }
676                         
677                         /* it is not an e2e ACK/200 -- perhaps it is 
678                          * local negative case; in which case we will want
679                          * more elements to match: r-uri and via; allow
680                          * mismatching r-uri as an config option for broken
681                          * UACs */
682                         if (cfg_get(tm, tm_cfg, ruri_matching) && !EQ_REQ_URI_LEN )
683                                 continue;
684                         if (cfg_get(tm, tm_cfg, via1_matching) && !EQ_VIA_LEN(via1))
685                                 continue;
686                         if (cfg_get(tm, tm_cfg, ruri_matching) && !EQ_REQ_URI_STR)
687                                 continue;
688                         if (cfg_get(tm, tm_cfg, via1_matching) && !EQ_VIA_STR(via1))
689                                 continue;
690                         
691                         /* wow -- we survived all the check! we matched! */
692                         DBG("DEBUG: non-2xx ACK matched\n");
693                         goto found;
694                 } /* synonym loop */
695         } /* ACK */
696
697 notfound:
698
699         if (e2e_ack_trans) {
700                 p_cell=e2e_ack_trans;
701                 goto e2e_ack;
702         }
703                 
704         /* no transaction found */
705         set_t(0, T_BR_UNDEFINED);
706         if (!leave_new_locked) {
707                 UNLOCK_HASH(p_msg->hash_index);
708         }
709         DBG("DEBUG: t_lookup_request: no transaction found\n");
710         return -1;
711
712 e2e_ack:
713         t_ack=p_cell;   /* e2e proxied ACK */
714         set_t(0, T_BR_UNDEFINED);
715         if (!leave_new_locked) {
716                 UNLOCK_HASH(p_msg->hash_index);
717         }
718         DBG("DEBUG: t_lookup_request: e2e proxy ACK found\n");
719         return -2;
720
721 found:
722         set_t(p_cell, T_BR_UNDEFINED);
723         REF_UNSAFE( T );
724         set_kr(REQ_EXIST);
725         UNLOCK_HASH( p_msg->hash_index );
726         DBG("DEBUG: t_lookup_request: transaction found (T=%p)\n",T);
727         return 1;
728 }
729
730
731
732 /* function lookups transaction being canceled by CANCEL in p_msg;
733  * it returns:
734  *       0 - transaction wasn't found
735  *       T - transaction found
736  */
737 struct cell* t_lookupOriginalT(  struct sip_msg* p_msg )
738 {
739         struct cell     *p_cell;
740         unsigned int     hash_index;
741         struct sip_msg  *t_msg;
742         struct via_param *branch;
743         struct entry* hash_bucket;
744         int foo;
745         int ret;
746
747
748         /* start searching in the table */
749         if (!(p_msg->msg_flags & FL_HASH_INDEX)){
750                 /* parse all*/
751                 if (check_transaction_quadruple(p_msg)==0)
752                 {
753                         LOG(L_ERR, "ERROR: TM module: t_lookupOriginalT:"
754                                         " too few headers\n");
755                         /* stop processing */
756                         return 0;
757                 }
758                 p_msg->hash_index=hash( p_msg->callid->body , get_cseq(p_msg)->number);
759                 p_msg->msg_flags|=FL_HASH_INDEX;
760         }
761         hash_index = p_msg->hash_index;
762         DBG("DEBUG: t_lookupOriginalT: searching on hash entry %d\n",hash_index );
763
764
765         /* first of all, look if there is RFC3261 magic cookie in branch; if
766          * so, we can do very quick matching and skip the old-RFC bizzar
767          * comparison of many header fields
768          */
769         if (!p_msg->via1) {
770                 LOG(L_ERR, "ERROR: t_lookupOriginalT: no via\n");
771                 return 0;
772         }
773         branch=p_msg->via1->branch;
774         if (branch && branch->value.s && branch->value.len>MCOOKIE_LEN
775                         && memcmp(branch->value.s,MCOOKIE,MCOOKIE_LEN)==0) {
776                 /* huhuhu! the cookie is there -- let's proceed fast */
777                 LOCK_HASH(hash_index);
778                 ret=matching_3261(p_msg, &p_cell,
779                                 /* we are seeking the original transaction --
780                                  * skip CANCEL transactions during search
781                                  */
782                                 METHOD_CANCEL, &foo);
783                 if (ret==1) goto found; else goto notfound;
784         }
785
786         /* no cookies --proceed to old-fashioned pre-3261 t-matching */
787
788         LOCK_HASH(hash_index);
789
790         hash_bucket=&(get_tm_table()->entries[hash_index]);
791         /* all the transactions from the entry are compared */
792         clist_foreach(hash_bucket, p_cell, next_c){
793                 prefetch_loc_r(p_cell->next_c, 1);
794                 t_msg = p_cell->uas.request;
795
796                 if (!t_msg) continue; /* skip UAC transactions */
797
798                 /* we don't cancel CANCELs ;-) */
799                 if (unlikely(t_msg->REQ_METHOD==METHOD_CANCEL))
800                         continue;
801
802                 /* check lengths now */ 
803                 if (!EQ_LEN(callid))
804                         continue;
805                 if (get_cseq(t_msg)->number.len!=get_cseq(p_msg)->number.len)
806                         continue;
807                 if (!EQ_LEN(from))
808                         continue;
809 #ifdef CANCEL_TAG
810                 if (!EQ_LEN(to))
811                         continue;
812 #else
813                 /* relaxed matching -- we don't care about to-tags anymore,
814                  * many broken UACs screw them up and ignoring them does not
815                  * actually hurt
816                  */
817                 if (get_to(t_msg)->uri.len!=get_to(p_msg)->uri.len)
818                         continue;
819 #endif
820                 if (cfg_get(tm, tm_cfg, ruri_matching) && !EQ_REQ_URI_LEN)
821                         continue;
822                 if (cfg_get(tm, tm_cfg, via1_matching) && !EQ_VIA_LEN(via1))
823                         continue;
824
825                 /* check the content now */
826                 if (!EQ_STR(callid))
827                         continue;
828                 if (memcmp(get_cseq(t_msg)->number.s,
829                         get_cseq(p_msg)->number.s,get_cseq(p_msg)->number.len)!=0)
830                         continue;
831                 if (!EQ_STR(from))
832                         continue;
833 #ifdef CANCEL_TAG
834                 if (!EQ_STR(to))
835                         continue;
836 #else
837                 if (memcmp(get_to(t_msg)->uri.s, get_to(p_msg)->uri.s,
838                                         get_to(t_msg)->uri.len)!=0)
839                         continue;
840 #endif
841                 if (cfg_get(tm, tm_cfg, ruri_matching) && !EQ_REQ_URI_STR)
842                         continue;
843                 if (cfg_get(tm, tm_cfg, via1_matching) && !EQ_VIA_STR(via1))
844                         continue;
845
846                 /* found */
847                 goto found;
848         }
849
850 notfound:
851         /* no transaction found */
852         DBG("DEBUG: t_lookupOriginalT: no CANCEL matching found! \n" );
853         UNLOCK_HASH(hash_index);
854         DBG("DEBUG: t_lookupOriginalT completed\n");
855         return 0;
856
857 found:
858         DBG("DEBUG: t_lookupOriginalT: canceled transaction"
859                 " found (%p)! \n",p_cell );
860         REF_UNSAFE( p_cell );
861         UNLOCK_HASH(hash_index);
862         DBG("DEBUG: t_lookupOriginalT completed\n");
863         return p_cell;
864 }
865
866
867
868
869 /** get the transaction corresponding to a reply.
870  * @return -1 - nothing found,  1  - T found
871  * Side-effects: sets T and T_branch on success.
872  */
873 int t_reply_matching( struct sip_msg *p_msg , int *p_branch )
874 {
875         struct cell*  p_cell;
876         unsigned int hash_index   = 0;
877         unsigned int entry_label  = 0;
878         unsigned int branch_id    = 0;
879         char  *hashi, *branchi, *p, *n;
880         struct entry* hash_bucket;
881         int hashl, branchl;
882         int scan_space;
883         str cseq_method;
884         str req_method;
885
886         char *loopi;
887         int loopl;
888         char *syni;
889         int synl;
890         
891         short is_cancel;
892
893         /* make compiler warnings happy */
894         loopi=0;
895         loopl=0;
896         syni=0;
897         synl=0;
898
899         /* split the branch into pieces: loop_detection_check(ignored),
900          hash_table_id, synonym_id, branch_id */
901
902         if (!(p_msg->via1 && p_msg->via1->branch && p_msg->via1->branch->value.s))
903                 goto nomatch2;
904
905         /* we do RFC 3261 tid matching and want to see first if there is
906          * magic cookie in branch */
907         if (p_msg->via1->branch->value.len<=MCOOKIE_LEN)
908                 goto nomatch2;
909         if (memcmp(p_msg->via1->branch->value.s, MCOOKIE, MCOOKIE_LEN)!=0)
910                 goto nomatch2;
911
912         p=p_msg->via1->branch->value.s+MCOOKIE_LEN;
913         scan_space=p_msg->via1->branch->value.len-MCOOKIE_LEN;
914
915
916         /* hash_id */
917         n=eat_token2_end( p, p+scan_space, BRANCH_SEPARATOR);
918         hashl=n-p;
919         scan_space-=hashl;
920         if (!hashl || scan_space<2 || *n!=BRANCH_SEPARATOR) goto nomatch2;
921         hashi=p;
922         p=n+1;scan_space--;
923
924         if (!syn_branch) {
925                 /* md5 value */
926                 n=eat_token2_end( p, p+scan_space, BRANCH_SEPARATOR );
927                 loopl = n-p;
928                 scan_space-= loopl;
929                 if (n==p || scan_space<2 || *n!=BRANCH_SEPARATOR) 
930                         goto nomatch2;
931                 loopi=p;
932                 p=n+1; scan_space--;
933         } else {
934                 /* synonym id */
935                 n=eat_token2_end( p, p+scan_space, BRANCH_SEPARATOR);
936                 synl=n-p;
937                 scan_space-=synl;
938                 if (!synl || scan_space<2 || *n!=BRANCH_SEPARATOR) 
939                         goto nomatch2;
940                 syni=p;
941                 p=n+1;scan_space--;
942         }
943
944         /* branch id  -  should exceed the scan_space */
945         n=eat_token_end( p, p+scan_space );
946         branchl=n-p;
947         if (!branchl ) goto nomatch2;
948         branchi=p;
949
950         /* sanity check */
951         if (unlikely(reverse_hex2int(hashi, hashl, &hash_index)<0
952                 ||hash_index>=TABLE_ENTRIES
953                 || reverse_hex2int(branchi, branchl, &branch_id)<0
954                 ||branch_id>=MAX_BRANCHES
955                 || (syn_branch ? (reverse_hex2int(syni, synl, &entry_label))<0 
956                         : loopl!=MD5_LEN ))
957         ) {
958                 DBG("DEBUG: t_reply_matching: poor reply labels %d label %d "
959                         "branch %d\n", hash_index, entry_label, branch_id );
960                 goto nomatch2;
961         }
962
963
964         DBG("DEBUG: t_reply_matching: hash %d label %d branch %d\n",
965                 hash_index, entry_label, branch_id );
966
967
968         /* search the hash table list at entry 'hash_index'; lock the
969            entry first 
970         */
971         cseq_method=get_cseq(p_msg)->method;
972         is_cancel=cseq_method.len==CANCEL_LEN 
973                 && memcmp(cseq_method.s, CANCEL, CANCEL_LEN)==0;
974         LOCK_HASH(hash_index);
975         hash_bucket=&(get_tm_table()->entries[hash_index]);
976         /* all the transactions from the entry are compared */
977         clist_foreach(hash_bucket, p_cell, next_c){
978                 prefetch_loc_r(p_cell->next_c, 1);
979                 /* first look if branch matches */
980                 if (likely(syn_branch)) {
981                         if (p_cell->label != entry_label) 
982                                 continue;
983                 } else {
984                         if ( memcmp(p_cell->md5, loopi,MD5_LEN)!=0)
985                                         continue;
986                 }
987
988                 /* sanity check ... too high branch ? */
989                 if (unlikely(branch_id>=p_cell->nr_of_outgoings))
990                         continue;
991
992                 /* does method match ? (remember -- CANCELs have the same branch
993                    as canceled transactions) */
994                 req_method=p_cell->method;
995                 if ( /* method match */
996                         ! ((cseq_method.len==req_method.len 
997                         && memcmp( cseq_method.s, req_method.s, cseq_method.len )==0)
998                         /* or it is a local cancel */
999                         || (is_cancel && is_invite(p_cell)
1000                                 /* commented out -- should_cancel_branch set it to
1001                                    BUSY_BUFFER to avoid collisions with replies;
1002                                    thus, we test here by buffer size
1003                                 */
1004                                 /* && p_cell->uac[branch_id].local_cancel.buffer ))) */
1005                                 && p_cell->uac[branch_id].local_cancel.buffer_len ))) 
1006                         continue;
1007
1008
1009                 /* we passed all disqualifying factors .... the transaction has been
1010                    matched !
1011                 */
1012                 set_t(p_cell, (int)branch_id);
1013                 *p_branch =(int) branch_id;
1014                 REF_UNSAFE( T );
1015                 UNLOCK_HASH(hash_index);
1016                 DBG("DEBUG: t_reply_matching: reply matched (T=%p)!\n",T);
1017                 /* if this is a 200 for INVITE, we will wish to store to-tags to be
1018                  * able to distinguish retransmissions later and not to call
1019                  * TMCB_RESPONSE_OUT uselessly; we do it only if callbacks are
1020                  * enabled -- except callback customers, nobody cares about 
1021                  * retransmissions of multiple 200/INV or ACK/200s
1022                  */
1023                 if (unlikely( is_invite(p_cell) && p_msg->REPLY_STATUS>=200 
1024                         && p_msg->REPLY_STATUS<300 
1025                         && ((!is_local(p_cell) &&
1026                                 has_tran_tmcbs(p_cell, 
1027                                         TMCB_RESPONSE_OUT|TMCB_RESPONSE_READY
1028                                         |TMCB_E2EACK_IN|TMCB_E2EACK_RETR_IN) )
1029                         || (is_local(p_cell)&&has_tran_tmcbs(p_cell, TMCB_LOCAL_COMPLETED))
1030                 )) ) {
1031                         if (parse_headers(p_msg, HDR_TO_F, 0)==-1) {
1032                                 LOG(L_ERR, "ERROR: t_reply_matching: to parsing failed\n");
1033                         }
1034                 }
1035                 if (unlikely(has_tran_tmcbs(T, TMCB_RESPONSE_IN |
1036                                                                                 TMCB_LOCAL_RESPONSE_IN))){
1037                         if (!is_local(p_cell)) {
1038                                 run_trans_callbacks( TMCB_RESPONSE_IN, T, T->uas.request,
1039                                                                                 p_msg, p_msg->REPLY_STATUS);
1040                         }else{
1041                                 run_trans_callbacks( TMCB_LOCAL_RESPONSE_IN, T, T->uas.request,
1042                                                                                 p_msg, p_msg->REPLY_STATUS);
1043                         }
1044                 }
1045                 return 1;
1046         } /* for cycle */
1047
1048         /* nothing found */
1049         UNLOCK_HASH(hash_index);
1050         DBG("DEBUG: t_reply_matching: no matching transaction exists\n");
1051
1052 nomatch2:
1053         DBG("DEBUG: t_reply_matching: failure to match a transaction\n");
1054         *p_branch = -1;
1055         set_t(0, T_BR_UNDEFINED);
1056         return -1;
1057 }
1058
1059
1060
1061
1062 /** Determine current transaction (w/ e2eack support).
1063  *
1064  * script/t_lookup_request  return convention:
1065  *                   Found      Not Found     Error (e.g. parsing) E2E ACK
1066  *  @return          1         -1              0                  -2
1067  *  T                ptr        0              T_UNDEFINED| 0      0
1068  * Side-effects: sets T and T_branch.
1069  */
1070 int t_check_msg( struct sip_msg* p_msg , int *param_branch )
1071 {
1072         int local_branch;
1073         int canceled;
1074         int ret;
1075         
1076         ret=0;
1077         /* is T still up-to-date ? */
1078         DBG("DEBUG: t_check_msg: msg id=%d global id=%d T start=%p\n", 
1079                 p_msg->id,global_msg_id,T);
1080         if ( p_msg->id != global_msg_id || T==T_UNDEFINED )
1081         {
1082                 global_msg_id = p_msg->id;
1083                 set_t(T_UNDEFINED, T_BR_UNDEFINED);
1084                 /* transaction lookup */
1085                 if ( p_msg->first_line.type==SIP_REQUEST ) {
1086                         /* force parsing all the needed headers*/
1087                         prefetch_loc_r(p_msg->unparsed+64, 1);
1088                         if (parse_headers(p_msg, HDR_EOH_F, 0 )==-1) {
1089                                 LOG(L_ERR, "ERROR: t_check_msg: parsing error\n");
1090                                 goto error;
1091                         }
1092                         /* in case, we act as UAS for INVITE and reply with 200,
1093                          * we will need to run dialog-matching for subsequent
1094                          * ACK, for which we need From-tag; We also need from-tag
1095                          * in case people want to have proxied e2e ACKs accounted
1096                          */
1097                         if (p_msg->REQ_METHOD==METHOD_INVITE 
1098                                                         && parse_from_header(p_msg)==-1) {
1099                                 LOG(L_ERR, "ERROR: t_check_msg: from parsing failed\n");
1100                                 goto error;
1101                         }
1102                         ret=t_lookup_request( p_msg , 0 /* unlock before returning */,
1103                                                                         &canceled);
1104                 } else {
1105                         /* we need Via for branch and Cseq method to distinguish
1106                            replies with the same branch/cseqNr (CANCEL)
1107                            and we need all the WWW/Proxy Authenticate headers for
1108                            401 & 407 replies
1109                         */
1110                         if (cfg_get(tm, tm_cfg, tm_aggregate_auth) && 
1111                                         (p_msg->REPLY_STATUS==401 || p_msg->REPLY_STATUS==407)){
1112                                 if (parse_headers(p_msg, HDR_EOH_F,0)==-1){
1113                                         LOG(L_WARN, "WARNING: the reply cannot be "
1114                                                                 "completely parsed\n");
1115                                         /* try to continue, via1 & cseq are checked below */
1116                                 }
1117                         }else if ( parse_headers(p_msg, HDR_VIA1_F|HDR_CSEQ_F, 0 )==-1) {
1118                                 LOG(L_ERR, "ERROR: reply cannot be parsed\n");
1119                                 goto error;
1120                         }
1121                         if ((p_msg->via1==0) || (p_msg->cseq==0)){
1122                                 LOG(L_ERR, "ERROR: reply doesn't have a via or cseq"
1123                                                         " header\n");
1124                                 goto error;
1125                         }
1126                         /* if that is an INVITE, we will also need to-tag
1127                            for later ACK matching
1128                         */
1129                         if ( get_cseq(p_msg)->method.len==INVITE_LEN 
1130                                 && memcmp( get_cseq(p_msg)->method.s, INVITE, INVITE_LEN )==0)
1131                         {
1132                                 if (parse_headers(p_msg, HDR_TO_F, 0)==-1 || !p_msg->to) {
1133                                         LOG(L_ERR, "ERROR: INVITE reply cannot be parsed\n");
1134                                         goto error;
1135                                 }
1136                         }
1137                         ret=t_reply_matching( p_msg ,
1138                                                         param_branch!=0?param_branch:&local_branch );
1139                 }
1140 #ifdef EXTRA_DEBUG
1141                 if ( T && T!=T_UNDEFINED && T->flags & (T_IN_AGONY)) {
1142                         LOG( L_WARN, "WARNING: transaction %p scheduled for deletion "
1143                                 "and called from t_check_msg (flags=%x) (but it might be ok)"
1144                                 "\n", T, T->flags);
1145                 }
1146 #endif
1147                 DBG("DEBUG: t_check_msg: msg id=%d global id=%d T end=%p\n",
1148                         p_msg->id,global_msg_id,T);
1149         } else { /*  ( p_msg->id == global_msg_id && T!=T_UNDEFINED ) */
1150                 if (T){
1151                         DBG("DEBUG: t_check_msg: T already found!\n");
1152                         ret=1;
1153                 }else{
1154                         DBG("DEBUG: t_check_msg: T previously sought and not found\n");
1155                         ret=-1;
1156                 }
1157                 if (likely(param_branch))
1158                         *param_branch=T_branch;
1159         }
1160         return ret;
1161 error:
1162         return 0;
1163 }
1164
1165
1166
1167 /** Determine current transaction (old version).
1168  *
1169  *                   Found      Not Found     Error (e.g. parsing)
1170  *  @return          1          0             -1
1171  *  T                ptr        0             T_UNDEFINED | 0
1172  *
1173  * Side-effects: sets T and T_branch.
1174  */
1175 int t_check( struct sip_msg* p_msg , int *param_branch )
1176 {
1177         int ret;
1178
1179         ret=t_check_msg(p_msg, param_branch);
1180         /* fix t_check_msg return */
1181         switch(ret){
1182                 case -2: /* e2e ack */     return 0;  /* => not found */
1183                 case -1: /* not found */   return 0;  /* => not found */
1184                 case  0: /* parse error */ return -1; /* => error */
1185                 case  1: /* found */       return ret; /* =>  found */
1186         };
1187         return ret;
1188 }
1189
1190
1191
1192 int init_rb( struct retr_buf *rb, struct sip_msg *msg)
1193 {
1194         /*struct socket_info* send_sock;*/
1195         struct via_body* via;
1196         int proto;
1197
1198         /* rb. timers are init. init_t()/new_cell() */
1199         via=msg->via1;
1200         /* rb->dst is already init (0) by new_t()/build_cell() */
1201         if (!reply_to_via) {
1202                 update_sock_struct_from_ip( &rb->dst.to, msg );
1203                 proto=msg->rcv.proto;
1204         } else {
1205                 /*init retrans buffer*/
1206                 if (update_sock_struct_from_via( &(rb->dst.to), msg, via )==-1) {
1207                         LOG(L_ERR, "ERROR: init_rb: cannot lookup reply dst: %.*s\n",
1208                                 via->host.len, via->host.s );
1209                         ser_error=E_BAD_VIA;
1210                         return 0;
1211                 }
1212                 proto=via->proto;
1213         }
1214         rb->dst.proto=proto;
1215         rb->dst.id=msg->rcv.proto_reserved1;
1216 #ifdef USE_COMP
1217         rb->dst.comp=via->comp_no;
1218 #endif
1219         rb->dst.send_flags=msg->rpl_send_flags;
1220         
1221         membar_write();
1222         rb->dst.send_sock=msg->rcv.bind_address;
1223         return 1;
1224 }
1225
1226
1227 static inline void init_new_t(struct cell *new_cell, struct sip_msg *p_msg)
1228 {
1229         struct sip_msg *shm_msg;
1230         unsigned int timeout; /* avp timeout gets stored here (in s) */
1231         ticks_t lifetime;
1232
1233         shm_msg=new_cell->uas.request;
1234         new_cell->from.s=shm_msg->from->name.s;
1235         new_cell->from.len=HF_LEN(shm_msg->from);
1236         new_cell->to.s=shm_msg->to->name.s;
1237         new_cell->to.len=HF_LEN(shm_msg->to);
1238         new_cell->callid.s=shm_msg->callid->name.s;
1239         new_cell->callid.len=HF_LEN(shm_msg->callid);
1240         new_cell->cseq_n.s=shm_msg->cseq->name.s;
1241         new_cell->cseq_n.len=get_cseq(shm_msg)->number.s
1242                 +get_cseq(shm_msg)->number.len
1243                 -shm_msg->cseq->name.s;
1244
1245         new_cell->method=new_cell->uas.request->first_line.u.request.method;
1246         if (p_msg->REQ_METHOD==METHOD_INVITE){
1247                 /* set flags */
1248                 new_cell->flags |= T_IS_INVITE_FLAG |
1249                         get_msgid_val(user_cell_set_flags, p_msg->id, int);
1250                 new_cell->flags|=T_AUTO_INV_100 &
1251                                         (!cfg_get(tm, tm_cfg, tm_auto_inv_100) -1);
1252                 new_cell->flags|=T_DISABLE_6xx &
1253                                         (!cfg_get(tm, tm_cfg, disable_6xx) -1);
1254 #ifdef CANCEL_REASON_SUPPORT
1255                 new_cell->flags|=T_NO_E2E_CANCEL_REASON &
1256                                         (!!cfg_get(tm, tm_cfg, e2e_cancel_reason) -1);
1257 #endif /* CANCEL_REASON_SUPPORT */
1258                 /* reset flags */
1259                 new_cell->flags &=
1260                         (~ get_msgid_val(user_cell_reset_flags, p_msg->id, int));
1261                 
1262                 lifetime=(ticks_t)get_msgid_val(user_inv_max_lifetime,
1263                                                                                                 p_msg->id, int);
1264                 if (likely(lifetime==0))
1265                         lifetime=cfg_get(tm, tm_cfg, tm_max_inv_lifetime);
1266         }else{
1267                 lifetime=(ticks_t)get_msgid_val(user_noninv_max_lifetime, 
1268                                                                                         p_msg->id, int);
1269                 if (likely(lifetime==0))
1270                         lifetime=cfg_get(tm, tm_cfg, tm_max_noninv_lifetime);
1271         }
1272         new_cell->on_negative=get_on_negative();
1273         new_cell->on_reply=get_on_reply();
1274         new_cell->end_of_life=get_ticks_raw()+lifetime;;
1275         new_cell->fr_timeout=(ticks_t)get_msgid_val(user_fr_timeout,
1276                                                                                                 p_msg->id, int);
1277         new_cell->fr_inv_timeout=(ticks_t)get_msgid_val(user_fr_inv_timeout,
1278                                                                                                 p_msg->id, int);
1279         if (likely(new_cell->fr_timeout==0)){
1280                 if (unlikely(!fr_avp2timer(&timeout))) {
1281                         DBG("init_new_t: FR__TIMER = %d s\n", timeout);
1282                         new_cell->fr_timeout=S_TO_TICKS((ticks_t)timeout);
1283                 }else{
1284                         new_cell->fr_timeout=cfg_get(tm, tm_cfg, fr_timeout);
1285                 }
1286         }
1287         if (likely(new_cell->fr_inv_timeout==0)){
1288                 if (unlikely(!fr_inv_avp2timer(&timeout))) {
1289                         DBG("init_new_t: FR_INV_TIMER = %d s\n", timeout);
1290                         new_cell->fr_inv_timeout=S_TO_TICKS((ticks_t)timeout);
1291                         new_cell->flags |= T_NOISY_CTIMER_FLAG;
1292                 }else{
1293                         new_cell->fr_inv_timeout=cfg_get(tm, tm_cfg, fr_inv_timeout);
1294                 }
1295         }
1296 #ifdef TM_DIFF_RT_TIMEOUT
1297         new_cell->rt_t1_timeout_ms = (retr_timeout_t) get_msgid_val(
1298                                                                                                                 user_rt_t1_timeout_ms,
1299                                                                                                                 p_msg->id, int);
1300         if (likely(new_cell->rt_t1_timeout_ms == 0))
1301                 new_cell->rt_t1_timeout_ms = cfg_get(tm, tm_cfg, rt_t1_timeout_ms);
1302         new_cell->rt_t2_timeout_ms = (retr_timeout_t) get_msgid_val(
1303                                                                                                                 user_rt_t2_timeout_ms,
1304                                                                                                                 p_msg->id, int);
1305         if (likely(new_cell->rt_t2_timeout_ms == 0))
1306                 new_cell->rt_t2_timeout_ms = cfg_get(tm, tm_cfg, rt_t2_timeout_ms);
1307 #endif
1308         new_cell->on_branch=get_on_branch();
1309 }
1310
1311
1312
1313 /** creates a new transaction from a message.
1314  * No checks are made if the transaction exists. It is created and
1315  * added to the tm hashes. T is set to the new transaction.
1316  * @param p_msg - pointer to sip message
1317  * @return  >0 on success, <0 on error (an E_* error code, see error.h)
1318  * Side-effects: sets T and T_branch (T_branch always to T_BR_UNDEFINED).
1319  */
1320 static inline int new_t(struct sip_msg *p_msg)
1321 {
1322         struct cell *new_cell;
1323
1324         /* for ACK-dlw-wise matching, we want From-tags */
1325         if (p_msg->REQ_METHOD==METHOD_INVITE && parse_from_header(p_msg)<0) {
1326                         LOG(L_ERR, "ERROR: new_t: no valid From in INVITE\n");
1327                         return E_BAD_REQ;
1328         }
1329         /* make sure uri will be parsed before cloning */
1330         if (parse_sip_msg_uri(p_msg)<0) {
1331                 LOG(L_ERR, "ERROR: new_t: uri invalid\n");
1332                 return E_BAD_REQ;
1333         }
1334                         
1335         /* add new transaction */
1336         new_cell = build_cell( p_msg ) ;
1337         if  ( !new_cell ){
1338                 LOG(L_ERR, "ERROR: new_t: out of mem:\n");
1339                 return E_OUT_OF_MEM;
1340         } 
1341
1342 #ifdef TM_DEL_UNREF
1343         INIT_REF(new_cell, 2); /* 1 because it will be ref'ed from the
1344                                                                            hash and +1 because we set T to it */
1345 #endif
1346         insert_into_hash_table_unsafe( new_cell, p_msg->hash_index );
1347         set_t(new_cell, T_BR_UNDEFINED);
1348 #ifndef TM_DEL_UNREF
1349         INIT_REF_UNSAFE(T);
1350 #endif
1351         /* init pointers to headers needed to construct local
1352            requests such as CANCEL/ACK
1353         */
1354         init_new_t(new_cell, p_msg);
1355         return 1;
1356 }
1357
1358
1359
1360 /** if no transaction already exists for the message, create a new one.
1361  * atomic "new_tran" construct; it returns:
1362  *
1363  * @return <0   on error
1364  *          +1  if a request did not match a transaction
1365  *           0  on retransmission
1366  * On success, if the request was an ack, the calling function shall
1367  * forward statelessly. Otherwise it means, a new transaction was
1368  * introduced and the calling function shall reply/relay/whatever_appropriate.
1369  * Side-effects: sets T and T_branch (T_branch always to T_BR_UNDEFINED).
1370 */
1371 int t_newtran( struct sip_msg* p_msg )
1372 {
1373         int lret, my_err;
1374         int canceled;
1375
1376
1377         /* is T still up-to-date ? */
1378         DBG("DEBUG: t_newtran: msg id=%d , global msg id=%d ,"
1379                 " T on entrance=%p\n",p_msg->id,global_msg_id,T);
1380
1381         if ( T && T!=T_UNDEFINED  ) {
1382                 /* ERROR message moved to w_t_newtran */
1383                 DBG("DEBUG: t_newtran: "
1384                         "transaction already in process %p\n", T );
1385
1386                 /* t_newtran() has been already called, and the script
1387                 might changed the flags after it, so we must update the flags
1388                 in shm memory -- Miklos */
1389                 if (T->uas.request)
1390                         T->uas.request->flags = p_msg->flags;
1391
1392                 return E_SCRIPT;
1393         }
1394
1395         global_msg_id = p_msg->id;
1396         set_t(T_UNDEFINED, T_BR_UNDEFINED);
1397         /* first of all, parse everything -- we will store in shared memory 
1398            and need to have all headers ready for generating potential replies 
1399            later; parsing later on demand is not an option since the request 
1400            will be in shmem and applying parse_headers to it would intermix 
1401            shmem with pkg_mem
1402         */
1403         
1404         if (parse_headers(p_msg, HDR_EOH_F, 0 )) {
1405                 LOG(L_ERR, "ERROR: t_newtran: parse_headers failed\n");
1406                 return E_BAD_REQ;
1407         }
1408         if ((p_msg->parsed_flag & HDR_EOH_F)!=HDR_EOH_F) {
1409                         LOG(L_ERR, "ERROR: t_newtran: EoH not parsed\n");
1410                         return E_OUT_OF_MEM;
1411         }
1412         /* t_lookup_requests attempts to find the transaction; 
1413            it also calls check_transaction_quadruple -> it is
1414            safe to assume we have from/callid/cseq/to
1415         */ 
1416         lret = t_lookup_request( p_msg, 1 /* leave locked if not found */,
1417                                                                 &canceled );
1418
1419         /* on error, pass the error in the stack ... nothing is locked yet
1420            if 0 is returned */
1421         if (lret==0) return E_BAD_TUPEL;
1422
1423         /* transaction found, it's a retransmission  */
1424         if (lret>0) {
1425                 if (p_msg->REQ_METHOD==METHOD_ACK) {
1426                         if (unlikely(has_tran_tmcbs(T, TMCB_ACK_NEG_IN)))
1427                                 run_trans_callbacks(TMCB_ACK_NEG_IN, T, p_msg, 0, 
1428                                                                                 p_msg->REQ_METHOD);
1429                         t_release_transaction(T);
1430                 } else {
1431                         if (unlikely(has_tran_tmcbs(T, TMCB_REQ_RETR_IN)))
1432                                 run_trans_callbacks(TMCB_REQ_RETR_IN, T, p_msg, 0,
1433                                                                                 p_msg->REQ_METHOD);
1434                         t_retransmit_reply(T);
1435                 }
1436                 /* things are done -- return from script */
1437                 return 0;
1438         }
1439
1440         /* from now on, be careful -- hash table is locked */
1441
1442         if (lret==-2) { /* was it an e2e ACK ? if so, trigger a callback */
1443                 /* no callbacks? complete quickly */
1444                 if (likely( !has_tran_tmcbs(t_ack, 
1445                                                 TMCB_E2EACK_IN|TMCB_E2EACK_RETR_IN) )) {
1446                         UNLOCK_HASH(p_msg->hash_index);
1447                         return 1;
1448                 } 
1449                 REF_UNSAFE(t_ack);
1450                 UNLOCK_HASH(p_msg->hash_index);
1451                 /* we don't call from within REPLY_LOCK -- that introduces
1452                  * a race condition; however, it is so unlikely and the
1453                  * impact is so small (callback called multiple times of
1454                  * multiple ACK/200s received in parallel), that we do not
1455                  * better waste time in locks  */
1456                 if (unmatched_totag(t_ack, p_msg)) {
1457                         if (likely (has_tran_tmcbs(t_ack, TMCB_E2EACK_IN)))
1458                                 run_trans_callbacks( TMCB_E2EACK_IN , t_ack, p_msg, 0,
1459                                                                                 -p_msg->REQ_METHOD );
1460                 }else if (unlikely(has_tran_tmcbs(t_ack, TMCB_E2EACK_RETR_IN))){
1461                         run_trans_callbacks( TMCB_E2EACK_RETR_IN , t_ack, p_msg, 0,
1462                                                                         -p_msg->REQ_METHOD );
1463                 }
1464                 UNREF(t_ack);
1465                 return 1;
1466         }
1467
1468
1469         /* transaction not found, it's a new request (lret<0, lret!=-2);
1470            establish a new transaction ... */
1471         if (p_msg->REQ_METHOD==METHOD_ACK) { /* ... unless it is in ACK */
1472                 my_err=1;
1473                 goto new_err;
1474         }
1475
1476         my_err=new_t(p_msg);
1477         if (my_err<0) {
1478                 LOG(L_ERR, "ERROR: t_newtran: new_t failed\n");
1479                 goto new_err;
1480         }
1481         if (canceled) T->flags|=T_CANCELED; /* mark it for future ref. */
1482
1483
1484         UNLOCK_HASH(p_msg->hash_index);
1485         /* now, when the transaction state exists, check if
1486            there is a meaningful Via and calculate it; better
1487            do it now than later: state is established so that
1488            subsequent retransmissions will be absorbed and will
1489           not possibly block during Via DNS resolution; doing
1490            it later would only burn more CPU as if there is an
1491            error, we cannot relay later whatever comes out of the
1492            the transaction 
1493         */
1494         if (!init_rb( &T->uas.response, p_msg)) {
1495                 LOG(L_ERR, "ERROR: t_newtran: unresolvable via1\n");
1496                 put_on_wait( T );
1497                 t_unref(p_msg);
1498                 return E_BAD_VIA;
1499         }
1500
1501         return 1;
1502
1503
1504 new_err:
1505         UNLOCK_HASH(p_msg->hash_index);
1506         return my_err;
1507
1508 }
1509
1510
1511
1512 /** releases the current transaction (corresp. to p_msg).
1513  * The current transaction (T) corresponding to the sip message being
1514  * processed is released. Delayed replies are sent (if no other reply
1515  * was sent in the script). Extra checks are made to see if the transaction
1516  * was forwarded, explicitly replied or explicitly released. If not the
1517  * transaction * is force-killed and a warning is logged (script error).
1518  * @param p_msg - sip message being processed
1519  * @return -1 on error, 1 on success.
1520  * Side-effects: resets T and T_branch to T_UNDEFINED, T_BR_UNDEFINED,
1521  *  resets tm_error.
1522  */
1523 int t_unref( struct sip_msg* p_msg  )
1524 {
1525         enum kill_reason kr;
1526
1527         if (T==T_UNDEFINED || T==T_NULL_CELL)
1528                 return -1;
1529         if (p_msg->first_line.type==SIP_REQUEST){
1530                 kr=get_kr();
1531                 if (unlikely(kr == REQ_ERR_DELAYED)){
1532                         DBG("t_unref: delayed error reply generation(%d)\n", tm_error);
1533                         if (unlikely(is_route_type(FAILURE_ROUTE))){
1534                                 BUG("tm: t_unref: called w/ kr=REQ_ERR_DELAYED in failure"
1535                                                 " route for %p\n", T);
1536                         }else if (unlikely( kill_transaction(T, tm_error)<=0 )){
1537                                 ERR("ERROR: t_unref: generation of a delayed stateful reply"
1538                                                 " failed\n");
1539                                 t_release_transaction(T);
1540                         }
1541                 }else if ( unlikely (kr==0 ||(p_msg->REQ_METHOD==METHOD_ACK && 
1542                                                                 !(kr & REQ_RLSD)))) {
1543                         LOG(L_WARN, "WARNING: script writer didn't release transaction\n");
1544                         t_release_transaction(T);
1545                 }else if (unlikely((kr & REQ_ERR_DELAYED) &&
1546                                          (kr & ~(REQ_RLSD|REQ_RPLD|REQ_ERR_DELAYED|REQ_FWDED)))){
1547                         BUG("tm: t_unref: REQ_ERR DELAYED should have been caught much"
1548                                         " earlier for %p: %d (hex %x)\n",T, kr, kr);
1549                         t_release_transaction(T);
1550                 }
1551         }
1552         tm_error=0; /* clear it */
1553         UNREF( T );
1554         set_t(T_UNDEFINED, T_BR_UNDEFINED);
1555         return 1;
1556 }
1557
1558
1559
1560 int t_get_trans_ident(struct sip_msg* p_msg, unsigned int* hash_index, unsigned int* label)
1561 {
1562     struct cell* t;
1563     if(t_check(p_msg,0) != 1){
1564         LOG(L_ERR,"ERROR: t_get_trans_ident: no transaction found\n");
1565         return -1;
1566     }
1567     t = get_t();
1568     if(!t){
1569         LOG(L_ERR,"ERROR: t_get_trans_ident: transaction found is NULL\n");
1570         return -1;
1571     }
1572     
1573     *hash_index = t->hash_index;
1574     *label = t->label;
1575
1576     return 1;
1577 }
1578
1579 #ifdef WITH_AS_SUPPORT
1580 /**
1581  * Returns the hash coordinates of the transaction current CANCEL is targeting.
1582  */
1583 int t_get_canceled_ident(struct sip_msg* msg, unsigned int* hash_index, 
1584                 unsigned int* label)
1585 {
1586         struct cell *orig;
1587         if (msg->REQ_METHOD != METHOD_CANCEL) {
1588                 WARN("looking up original transaction for non-CANCEL method (%d).\n",
1589                                 msg->REQ_METHOD);
1590                 return -1;
1591         }
1592         orig = t_lookupOriginalT(msg);
1593         if ((orig == T_NULL_CELL) || (orig == T_UNDEFINED))
1594                 return -1;
1595         *hash_index = orig->hash_index;
1596         *label = orig->label;
1597         DEBUG("original T found @%p, %d:%d.\n", orig, *hash_index, *label);
1598         /* TODO: why's w_t_lookup_cancel setting T to 'undefined'?? */
1599         UNREF(orig);
1600         return 1;
1601 }
1602 #endif /* WITH_AS_SUPPORT */
1603
1604
1605
1606 /** lookup a transaction based on its identifier (hash_index:label).
1607  * @param trans - double pointer to cell structure, that will be filled
1608  *                with the result (a pointer to an existing transaction or
1609  *                0).
1610  * @param hash_index - searched transaction hash_index (part of the ident).
1611  * @param label - searched transaction label (part of the ident).
1612  * @return -1 on error/not found, 1 on success (found)
1613  * Side-effects: sets T and T_branch (T_branch always to T_BR_UNDEFINED).
1614  */
1615 int t_lookup_ident(struct cell ** trans, unsigned int hash_index, 
1616                                         unsigned int label)
1617 {
1618         struct cell* p_cell;
1619         struct entry* hash_bucket;
1620
1621         if(unlikely(hash_index >= TABLE_ENTRIES)){
1622                 LOG(L_ERR,"ERROR: t_lookup_ident: invalid hash_index=%u\n",hash_index);
1623                 return -1;
1624         }
1625         
1626         LOCK_HASH(hash_index);
1627
1628 #ifndef E2E_CANCEL_HOP_BY_HOP
1629 #warning "t_lookup_ident() can only reliably match INVITE transactions in " \
1630                 "E2E_CANCEL_HOP_BY_HOP mode"
1631 #endif
1632         hash_bucket=&(get_tm_table()->entries[hash_index]);
1633         /* all the transactions from the entry are compared */
1634         clist_foreach(hash_bucket, p_cell, next_c){
1635                 prefetch_loc_r(p_cell->next_c, 1);
1636                 if(p_cell->label == label){
1637                         REF_UNSAFE(p_cell);
1638                         UNLOCK_HASH(hash_index);
1639                         set_t(p_cell, T_BR_UNDEFINED);
1640                         *trans=p_cell;
1641                         DBG("DEBUG: t_lookup_ident: transaction found\n");
1642                         return 1;
1643                 }
1644     }
1645         
1646         UNLOCK_HASH(hash_index);
1647         set_t(0, T_BR_UNDEFINED);
1648         *trans=p_cell;
1649
1650         DBG("DEBUG: t_lookup_ident: transaction not found\n");
1651     
1652     return -1;
1653 }
1654
1655
1656
1657 /** check if a transaction is local or not.
1658  * Check if the transaction corresponding to the current message
1659  * is local or not.
1660  * @param p_msg - pointer to sip_msg
1661  * @return -1 on error, 0 if the transaction is not local, 1 if it is local.
1662  * Side-effects: sets T and T_branch.
1663  */
1664 int t_is_local(struct sip_msg* p_msg)
1665 {
1666     struct cell* t;
1667     if(t_check(p_msg,0) != 1){
1668         LOG(L_ERR,"ERROR: t_is_local: no transaction found\n");
1669         return -1;
1670     }
1671     t = get_t();
1672     if(!t){
1673         LOG(L_ERR,"ERROR: t_is_local: transaction found is NULL\n");
1674         return -1;
1675     }
1676     
1677     return is_local(t);
1678 }
1679
1680 /** lookup a transaction based on callid and cseq.
1681  * The parameters are pure header field content only,
1682  * e.g. "123@10.0.0.1" and "11"
1683  * @param trans - double pointer to the transaction, filled with a pointer
1684  *                to the found transaction on success and with 0 if the
1685  *                transaction was not found.
1686  * @param callid - callid for the searched transaction.
1687  * @param cseq - cseq for the searched transaction.
1688  * @return -1 on error/not found, 1 if found.
1689  * Side-effects: sets T and T_branch (T_branch always to T_BR_UNDEFINED).
1690  */
1691 int t_lookup_callid(struct cell ** trans, str callid, str cseq) {
1692         struct cell* p_cell;
1693         unsigned hash_index;
1694         struct entry* hash_bucket;
1695
1696         /* I use MAX_HEADER, not sure if this is a good choice... */
1697         char callid_header[MAX_HEADER];
1698         char cseq_header[MAX_HEADER];
1699         /* save return value of print_* functions here */
1700         char* endpos;
1701
1702         /* need method, which is always INVITE in our case */
1703         /* CANCEL is only useful after INVITE */
1704         str invite_method;
1705         char* invite_string = INVITE;
1706         
1707         invite_method.s = invite_string;
1708         invite_method.len = INVITE_LEN;
1709         
1710         /* lookup the hash index where the transaction is stored */
1711         hash_index=hash(callid, cseq);
1712
1713         if(unlikely(hash_index >= TABLE_ENTRIES)){
1714                 LOG(L_ERR,"ERROR: t_lookup_callid: invalid hash_index=%u\n",hash_index);
1715                 return -1;
1716         }
1717
1718         /* create header fields the same way tm does itself, then compare headers */
1719         endpos = print_callid_mini(callid_header, callid);
1720         DBG("created comparable call_id header field: >%.*s<\n", 
1721                         (int)(endpos - callid_header), callid_header); 
1722
1723         endpos = print_cseq_mini(cseq_header, &cseq, &invite_method);
1724         DBG("created comparable cseq header field: >%.*s<\n", 
1725                         (int)(endpos - cseq_header), cseq_header); 
1726
1727         LOCK_HASH(hash_index);
1728         DBG("just locked hash index %u, looking for transactions there:\n", hash_index);
1729
1730         hash_bucket=&(get_tm_table()->entries[hash_index]);
1731         /* all the transactions from the entry are compared */
1732         clist_foreach(hash_bucket, p_cell, next_c){
1733                 
1734                 prefetch_loc_r(p_cell->next_c, 1);
1735                 /* compare complete header fields, casecmp to make sure invite=INVITE*/
1736                 if ((strncmp(callid_header, p_cell->callid.s, p_cell->callid.len) == 0)
1737                         && (strncasecmp(cseq_header, p_cell->cseq_n.s, p_cell->cseq_n.len)
1738                                 == 0)) {
1739                         DBG("we have a match: callid=>>%.*s<< cseq=>>%.*s<<\n",
1740                                         p_cell->callid.len, p_cell->callid.s, p_cell->cseq_n.len,
1741                                         p_cell->cseq_n.s);
1742                         REF_UNSAFE(p_cell);
1743                         UNLOCK_HASH(hash_index);
1744                         set_t(p_cell, T_BR_UNDEFINED);
1745                         *trans=p_cell;
1746                         DBG("DEBUG: t_lookup_callid: transaction found.\n");
1747                         return 1;
1748                 }
1749                 DBG("NO match: callid=%.*s cseq=%.*s\n", p_cell->callid.len, 
1750                         p_cell->callid.s, p_cell->cseq_n.len, p_cell->cseq_n.s);
1751                         
1752         }
1753
1754         UNLOCK_HASH(hash_index);
1755         DBG("DEBUG: t_lookup_callid: transaction not found.\n");
1756     
1757         return -1;
1758 }
1759
1760
1761
1762 /* params: fr_inv & fr value in ms, 0 means "do not touch"
1763  * ret: 1 on success, -1 on error (script safe)*/
1764 int t_set_fr(struct sip_msg* msg, unsigned int fr_inv_to, unsigned int fr_to)
1765 {
1766         struct cell *t;
1767         ticks_t fr_inv, fr;
1768         
1769         
1770         fr_inv=MS_TO_TICKS((ticks_t)fr_inv_to);
1771         if ((fr_inv==0) && (fr_inv_to!=0)){
1772                 ERR("t_set_fr_inv: fr_inv_timeout too small (%d)\n", fr_inv_to);
1773                 return -1;
1774         }
1775         fr=MS_TO_TICKS((ticks_t)fr_to);
1776         if ((fr==0) && (fr_to!=0)){
1777                 ERR("t_set_fr_inv: fr_timeout too small (%d)\n", fr_to);
1778                 return -1;
1779         }
1780         
1781         t=get_t();
1782         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
1783          * in REQUEST_ROUTE T will be set only if the transaction was already
1784          * created; if not -> use the static variables */
1785         if (!t || t==T_UNDEFINED ){
1786                 set_msgid_val(user_fr_inv_timeout, msg->id, int, (int)fr_inv);
1787                 set_msgid_val(user_fr_timeout, msg->id, int, (int)fr);
1788         }else{
1789                 change_fr(t, fr_inv, fr); /* change running uac timers */
1790         }
1791         return 1;
1792 }
1793
1794 /* reset fr_timer and fr_inv_timer to the default values */
1795 int t_reset_fr()
1796 {
1797         struct cell *t;
1798
1799         t=get_t();
1800         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
1801          * in REQUEST_ROUTE T will be set only if the transaction was already
1802          * created; if not -> use the static variables */
1803         if (!t || t==T_UNDEFINED ){
1804                 memset(&user_fr_inv_timeout, 0, sizeof(user_fr_inv_timeout));
1805                 memset(&user_fr_timeout, 0, sizeof(user_fr_timeout));
1806         }else{
1807                 change_fr(t,
1808                         cfg_get(tm, tm_cfg, fr_inv_timeout),
1809                         cfg_get(tm, tm_cfg, fr_timeout)); /* change running uac timers */
1810         }
1811         return 1;
1812 }
1813
1814 #ifdef TM_DIFF_RT_TIMEOUT
1815
1816 /* params: retr. t1 & retr. t2 value in ms, 0 means "do not touch"
1817  * ret: 1 on success, -1 on error (script safe)*/
1818 int t_set_retr(struct sip_msg* msg, unsigned int t1_ms, unsigned int t2_ms)
1819 {
1820         struct cell *t;
1821         ticks_t retr_t1, retr_t2;
1822         
1823         
1824         retr_t1=MS_TO_TICKS((ticks_t)t1_ms);
1825         if (unlikely((retr_t1==0) && (t1_ms!=0))){
1826                 ERR("t_set_retr: retr. t1 interval too small (%u)\n", t1_ms);
1827                 return -1;
1828         }
1829         if (unlikely(MAX_UVAR_VALUE(t->rt_t1_timeout_ms) < t1_ms)){
1830                 ERR("t_set_retr: retr. t1 interval too big: %d (max %lu)\n",
1831                                 t1_ms, MAX_UVAR_VALUE(t->rt_t1_timeout_ms)); 
1832                 return -1;
1833         } 
1834         retr_t2=MS_TO_TICKS((ticks_t)t2_ms);
1835         if (unlikely((retr_t2==0) && (t2_ms!=0))){
1836                 ERR("t_set_retr: retr. t2 interval too small (%d)\n", t2_ms);
1837                 return -1;
1838         }
1839         if (unlikely(MAX_UVAR_VALUE(t->rt_t2_timeout_ms) < t2_ms)){
1840                 ERR("t_set_retr: retr. t2 interval too big: %u (max %lu)\n",
1841                                 t2_ms, MAX_UVAR_VALUE(t->rt_t2_timeout_ms)); 
1842                 return -1;
1843         } 
1844         
1845         t=get_t();
1846         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
1847          * in REQUEST_ROUTE T will be set only if the transaction was already
1848          * created; if not -> use the static variables */
1849         if (!t || t==T_UNDEFINED ){
1850                 set_msgid_val(user_rt_t1_timeout_ms, msg->id, int, (int)t1_ms);
1851                 set_msgid_val(user_rt_t2_timeout_ms, msg->id, int, (int)t2_ms);
1852         }else{
1853                 change_retr(t, 1, t1_ms, t2_ms); /* change running uac timers */
1854         }
1855         return 1;
1856 }
1857
1858 /* reset retr. t1 and t2 to the default values */
1859 int t_reset_retr()
1860 {
1861         struct cell *t;
1862
1863         t=get_t();
1864         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
1865          * in REQUEST_ROUTE T will be set only if the transaction was already
1866          * created; if not -> use the static variables */
1867         if (!t || t==T_UNDEFINED ){
1868                 memset(&user_rt_t1_timeout_ms, 0, sizeof(user_rt_t1_timeout_ms));
1869                 memset(&user_rt_t2_timeout_ms, 0, sizeof(user_rt_t2_timeout_ms));
1870         }else{
1871                  /* change running uac timers */
1872                 change_retr(t,
1873                         1,
1874                         cfg_get(tm, tm_cfg, rt_t1_timeout_ms),
1875                         cfg_get(tm, tm_cfg, rt_t2_timeout_ms));
1876         }
1877         return 1;
1878 }
1879 #endif
1880
1881
1882 /* params: maximum transaction lifetime for inv and non-inv
1883  *         0 means do not touch"
1884  * ret: 1 on success, -1 on error (script safe)*/
1885 int t_set_max_lifetime(struct sip_msg* msg,
1886                                                 unsigned int lifetime_inv_to,
1887                                                 unsigned int lifetime_noninv_to)
1888 {
1889         struct cell *t;
1890         ticks_t max_inv_lifetime, max_noninv_lifetime;
1891         
1892         
1893         max_noninv_lifetime=MS_TO_TICKS((ticks_t)lifetime_noninv_to);
1894         max_inv_lifetime=MS_TO_TICKS((ticks_t)lifetime_inv_to);
1895         if (unlikely((max_noninv_lifetime==0) && (lifetime_noninv_to!=0))){
1896                 ERR("t_set_max_lifetime: non-inv. interval too small (%d)\n",
1897                                 lifetime_noninv_to);
1898                 return -1;
1899         }
1900         if (unlikely((max_inv_lifetime==0) && (lifetime_inv_to!=0))){
1901                 ERR("t_set_max_lifetime: inv. interval too small (%d)\n",
1902                                 lifetime_inv_to);
1903                 return -1;
1904         }
1905         
1906         t=get_t();
1907         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
1908          * in REQUEST_ROUTE T will be set only if the transaction was already
1909          * created; if not -> use the static variables */
1910         if (!t || t==T_UNDEFINED ){
1911                 set_msgid_val(user_noninv_max_lifetime, msg->id, int,
1912                                                 (int)max_noninv_lifetime);
1913                 set_msgid_val(user_inv_max_lifetime, msg->id, int,
1914                                                 (int)max_inv_lifetime);
1915         }else{
1916                 change_end_of_life(t, 1, is_invite(t)?max_inv_lifetime:
1917                                                                                                 max_noninv_lifetime);
1918         }
1919         return 1;
1920 }
1921
1922 /* reset maximum invite/non-invite lifetime to the default value */
1923 int t_reset_max_lifetime()
1924 {
1925         struct cell *t;
1926
1927         t=get_t();
1928         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
1929          * in REQUEST_ROUTE T will be set only if the transaction was already
1930          * created; if not -> use the static variables */
1931         if (!t || t==T_UNDEFINED ){
1932                 memset(&user_inv_max_lifetime, 0, sizeof(user_inv_max_lifetime));
1933                 memset(&user_noninv_max_lifetime, 0, sizeof(user_noninv_max_lifetime));
1934         }else{
1935                 change_end_of_life(t,
1936                                 1,
1937                                 is_invite(t)?
1938                                         cfg_get(tm, tm_cfg, tm_max_inv_lifetime):
1939                                         cfg_get(tm, tm_cfg, tm_max_noninv_lifetime)
1940                                 );
1941         }
1942         return 1;
1943 }
1944
1945 #ifdef WITH_TM_CTX
1946
1947 tm_ctx_t _tm_ctx;
1948
1949 tm_ctx_t* tm_ctx_get(void)
1950 {
1951         return &_tm_ctx;
1952 }
1953
1954 void tm_ctx_init(void)
1955 {
1956         memset(&_tm_ctx, 0, sizeof(tm_ctx_t));
1957 }
1958
1959 void tm_ctx_set_branch_index(int v)
1960 {
1961         _tm_ctx.branch_index = v;
1962 }
1963
1964 #endif
1965