tm: no reason modparams if compiled with no cancelr. support
[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         int ret;
507         struct via_param *branch;
508         int match_status;
509         struct cell *e2e_ack_trans;
510         struct entry* hash_bucket;
511
512         /* parse all*/
513         if (unlikely(check_transaction_quadruple(p_msg)==0))
514         {
515                 LOG(L_ERR, "ERROR: TM module: t_lookup_request: too few headers\n");
516                 set_t(0, T_BR_UNDEFINED);
517                 /* stop processing */
518                 return 0;
519         }
520
521         /* start searching into the table */
522         if (!(p_msg->msg_flags & FL_HASH_INDEX)){
523                 p_msg->hash_index=hash( p_msg->callid->body , get_cseq(p_msg)->number);
524                 p_msg->msg_flags|=FL_HASH_INDEX;
525         }
526         isACK = p_msg->REQ_METHOD==METHOD_ACK;
527         DBG("t_lookup_request: start searching: hash=%d, isACK=%d\n",
528                 p_msg->hash_index,isACK);
529
530
531         /* assume not found */
532         ret=-1;
533         e2e_ack_trans = 0;
534
535         /* first of all, look if there is RFC3261 magic cookie in branch; if
536          * so, we can do very quick matching and skip the old-RFC bizzar
537          * comparison of many header fields
538          */
539         if (!p_msg->via1) {
540                 LOG(L_ERR, "ERROR: t_lookup_request: no via\n");
541                 set_t(0, T_BR_UNDEFINED);
542                 return 0;
543         }
544         branch=p_msg->via1->branch;
545         if (branch && branch->value.s && branch->value.len>MCOOKIE_LEN
546                         && memcmp(branch->value.s,MCOOKIE,MCOOKIE_LEN)==0) {
547                 /* huhuhu! the cookie is there -- let's proceed fast */
548                 LOCK_HASH(p_msg->hash_index);
549                 match_status=matching_3261(p_msg,&p_cell, 
550                                 /* skip transactions with different method; otherwise CANCEL 
551                                  * would  match the previous INVITE trans.  */
552                                 isACK ? ~METHOD_INVITE: ~p_msg->REQ_METHOD, 
553                                 cancel);
554                 switch(match_status) {
555                                 case 0: goto notfound;  /* no match */
556                                 case 1:  goto found;    /* match */
557                                 case 2: goto e2e_ack;   /* e2e proxy ACK */
558                 }
559         }
560
561         /* ok -- it's ugly old-fashioned transaction matching -- it is
562          * a bit simplified to be fast -- we don't do all the comparisons
563          * of parsed uri, which was simply too bloated */
564         DBG("DEBUG: proceeding to pre-RFC3261 transaction matching\n");
565         *cancel=0;
566         /* lock the whole entry*/
567         LOCK_HASH(p_msg->hash_index);
568
569         hash_bucket=&(get_tm_table()->entries[p_msg->hash_index]);
570         
571         if (likely(!isACK)) {   
572                 /* all the transactions from the entry are compared */
573                 clist_foreach(hash_bucket, p_cell, next_c){
574                         prefetch_loc_r(p_cell->next_c, 1);
575                         t_msg = p_cell->uas.request;
576                         if (!t_msg) continue; /* skip UAC transactions */
577                         /* for non-ACKs we want same method matching, we 
578                          * make an exception for pre-exisiting CANCELs because we
579                          * want to set *cancel */
580                         if ((t_msg->REQ_METHOD!=p_msg->REQ_METHOD) &&
581                                         (t_msg->REQ_METHOD!=METHOD_CANCEL))
582                                         continue;
583                         /* compare lengths first */ 
584                         if (!EQ_LEN(callid)) continue;
585                         /* CSeq only the number without method ! */
586                         if (get_cseq(t_msg)->number.len!=get_cseq(p_msg)->number.len)
587                                 continue;
588                         if (!EQ_LEN(from)) continue;
589                         if (!EQ_LEN(to)) continue;
590                         if (cfg_get(tm, tm_cfg, ruri_matching) && !EQ_REQ_URI_LEN) 
591                                 continue;
592                         if (cfg_get(tm, tm_cfg, via1_matching) && !EQ_VIA_LEN(via1))
593                                 continue;
594                         /* length ok -- move on */
595                         if (!EQ_STR(callid)) continue;
596                         if (memcmp(get_cseq(t_msg)->number.s, get_cseq(p_msg)->number.s,
597                                 get_cseq(p_msg)->number.len)!=0) continue;
598                         if (!EQ_STR(from)) continue;
599                         if (!EQ_STR(to)) continue;
600                         if (cfg_get(tm, tm_cfg, ruri_matching) && !EQ_REQ_URI_STR)
601                                 continue;
602                         if (cfg_get(tm, tm_cfg, via1_matching) && !EQ_VIA_STR(via1))
603                                 continue;
604                         
605                         if ((t_msg->REQ_METHOD==METHOD_CANCEL) &&
606                                 (p_msg->REQ_METHOD!=METHOD_CANCEL)){
607                                 /* we've matched an existing CANCEL */
608                                 *cancel=1;
609                                 continue;
610                         }
611                         
612                         /* request matched ! */
613                         DBG("DEBUG: non-ACK matched\n");
614                         goto found;
615                 } /* synonym loop */
616         } else { /* it's an ACK request*/
617                 /* all the transactions from the entry are compared */
618                 clist_foreach(hash_bucket, p_cell, next_c){
619                         prefetch_loc_r(p_cell->next_c, 1);
620                         t_msg = p_cell->uas.request;
621                         if (!t_msg) continue; /* skip UAC transactions */
622                         /* ACK's relate only to INVITEs */
623                         if (t_msg->REQ_METHOD!=METHOD_INVITE) continue;
624                         /* From|To URI , CallID, CSeq # must be always there */
625                         /* compare lengths now */
626                         if (!EQ_LEN(callid)) continue;
627                         /* CSeq only the number without method ! */
628                         if (get_cseq(t_msg)->number.len!=get_cseq(p_msg)->number.len)
629                                 continue;
630                         /* To only the uri -- to many UACs screw up tags  */
631                         if (get_to(t_msg)->uri.len!=get_to(p_msg)->uri.len)
632                                 continue;
633                         if (!EQ_STR(callid)) continue;
634                         if (memcmp(get_cseq(t_msg)->number.s, get_cseq(p_msg)->number.s,
635                                 get_cseq(p_msg)->number.len)!=0) continue;
636                         if (memcmp(get_to(t_msg)->uri.s, get_to(p_msg)->uri.s,
637                                 get_to(t_msg)->uri.len)!=0) continue;
638                         
639                         /* it is e2e ACK/200 */
640                         if (p_cell->uas.status<300) {
641                                 /* For e2e ACKs, From's tag 'MUST' equal INVITE's, while use
642                                  * of the URI in this case is to be deprecated (Sec. 12.2.1.1).
643                                  * Comparing entire From body is dangerous, since some UAs
644                                  * screw the display name up. */
645                                 if (parse_from_header(p_msg) < 0) {
646                                         ERR("failed to parse From HF; ACK might not match.\n");
647                                         continue;
648                                 }
649                                 if (! STR_EQ(get_from(t_msg)->tag_value, 
650                                                 get_from(p_msg)->tag_value))
651                                         continue;
652 #ifdef TM_E2E_ACK_CHECK_FROM_URI
653                                 if (! STR_EQ(get_from(t_msg)->uri, 
654                                                 get_from(p_msg)->uri))
655                                         continue;
656 #endif
657
658                                 /* all criteria for proxied ACK are ok */
659                                 if (likely(p_cell->relayed_reply_branch!=-2)) {
660                                         if (unlikely(has_tran_tmcbs(p_cell, 
661                                                                         TMCB_E2EACK_IN|TMCB_E2EACK_RETR_IN))){
662                                                 if (likely(totag_e2e_ack_matching(p_cell, p_msg)==2))
663                                                         goto e2e_ack;
664                                                 else if (e2e_ack_trans==0)
665                                                         e2e_ack_trans=p_cell;
666                                         }
667                                         continue;
668                                 }
669                                 /* it's a local UAS transaction */
670                                 if (dlg_matching(p_cell, p_msg))
671                                         goto found;
672                                 continue;
673                         } else {
674                                 /* for hbh ACKs, From HF 'MUST' equal INVITE's one */
675                                 if (! EQ_LEN(from)) continue;
676                                 if (! EQ_STR(from)) continue;
677                         }
678                         
679                         /* it is not an e2e ACK/200 -- perhaps it is 
680                          * local negative case; in which case we will want
681                          * more elements to match: r-uri and via; allow
682                          * mismatching r-uri as an config option for broken
683                          * UACs */
684                         if (cfg_get(tm, tm_cfg, ruri_matching) && !EQ_REQ_URI_LEN )
685                                 continue;
686                         if (cfg_get(tm, tm_cfg, via1_matching) && !EQ_VIA_LEN(via1))
687                                 continue;
688                         if (cfg_get(tm, tm_cfg, ruri_matching) && !EQ_REQ_URI_STR)
689                                 continue;
690                         if (cfg_get(tm, tm_cfg, via1_matching) && !EQ_VIA_STR(via1))
691                                 continue;
692                         
693                         /* wow -- we survived all the check! we matched! */
694                         DBG("DEBUG: non-2xx ACK matched\n");
695                         goto found;
696                 } /* synonym loop */
697         } /* ACK */
698
699 notfound:
700
701         if (e2e_ack_trans) {
702                 p_cell=e2e_ack_trans;
703                 goto e2e_ack;
704         }
705                 
706         /* no transaction found */
707         set_t(0, T_BR_UNDEFINED);
708         if (!leave_new_locked) {
709                 UNLOCK_HASH(p_msg->hash_index);
710         }
711         DBG("DEBUG: t_lookup_request: no transaction found\n");
712         return -1;
713
714 e2e_ack:
715         t_ack=p_cell;   /* e2e proxied ACK */
716         set_t(0, T_BR_UNDEFINED);
717         if (!leave_new_locked) {
718                 UNLOCK_HASH(p_msg->hash_index);
719         }
720         DBG("DEBUG: t_lookup_request: e2e proxy ACK found\n");
721         return -2;
722
723 found:
724         set_t(p_cell, T_BR_UNDEFINED);
725         REF_UNSAFE( T );
726         set_kr(REQ_EXIST);
727         UNLOCK_HASH( p_msg->hash_index );
728         DBG("DEBUG: t_lookup_request: transaction found (T=%p)\n",T);
729         return 1;
730 }
731
732
733
734 /* function lookups transaction being canceled by CANCEL in p_msg;
735  * it returns:
736  *       0 - transaction wasn't found
737  *       T - transaction found
738  */
739 struct cell* t_lookupOriginalT(  struct sip_msg* p_msg )
740 {
741         struct cell     *p_cell;
742         unsigned int     hash_index;
743         struct sip_msg  *t_msg;
744         struct via_param *branch;
745         struct entry* hash_bucket;
746         int foo;
747         int ret;
748
749
750         /* start searching in the table */
751         if (!(p_msg->msg_flags & FL_HASH_INDEX)){
752                 /* parse all*/
753                 if (check_transaction_quadruple(p_msg)==0)
754                 {
755                         LOG(L_ERR, "ERROR: TM module: t_lookupOriginalT:"
756                                         " too few headers\n");
757                         /* stop processing */
758                         return 0;
759                 }
760                 p_msg->hash_index=hash( p_msg->callid->body , get_cseq(p_msg)->number);
761                 p_msg->msg_flags|=FL_HASH_INDEX;
762         }
763         hash_index = p_msg->hash_index;
764         DBG("DEBUG: t_lookupOriginalT: searching on hash entry %d\n",hash_index );
765
766
767         /* first of all, look if there is RFC3261 magic cookie in branch; if
768          * so, we can do very quick matching and skip the old-RFC bizzar
769          * comparison of many header fields
770          */
771         if (!p_msg->via1) {
772                 LOG(L_ERR, "ERROR: t_lookupOriginalT: no via\n");
773                 return 0;
774         }
775         branch=p_msg->via1->branch;
776         if (branch && branch->value.s && branch->value.len>MCOOKIE_LEN
777                         && memcmp(branch->value.s,MCOOKIE,MCOOKIE_LEN)==0) {
778                 /* huhuhu! the cookie is there -- let's proceed fast */
779                 LOCK_HASH(hash_index);
780                 ret=matching_3261(p_msg, &p_cell,
781                                 /* we are seeking the original transaction --
782                                  * skip CANCEL transactions during search
783                                  */
784                                 METHOD_CANCEL, &foo);
785                 if (ret==1) goto found; else goto notfound;
786         }
787
788         /* no cookies --proceed to old-fashioned pre-3261 t-matching */
789
790         LOCK_HASH(hash_index);
791
792         hash_bucket=&(get_tm_table()->entries[hash_index]);
793         /* all the transactions from the entry are compared */
794         clist_foreach(hash_bucket, p_cell, next_c){
795                 prefetch_loc_r(p_cell->next_c, 1);
796                 t_msg = p_cell->uas.request;
797
798                 if (!t_msg) continue; /* skip UAC transactions */
799
800                 /* we don't cancel CANCELs ;-) */
801                 if (unlikely(t_msg->REQ_METHOD==METHOD_CANCEL))
802                         continue;
803
804                 /* check lengths now */ 
805                 if (!EQ_LEN(callid))
806                         continue;
807                 if (get_cseq(t_msg)->number.len!=get_cseq(p_msg)->number.len)
808                         continue;
809                 if (!EQ_LEN(from))
810                         continue;
811 #ifdef CANCEL_TAG
812                 if (!EQ_LEN(to))
813                         continue;
814 #else
815                 /* relaxed matching -- we don't care about to-tags anymore,
816                  * many broken UACs screw them up and ignoring them does not
817                  * actually hurt
818                  */
819                 if (get_to(t_msg)->uri.len!=get_to(p_msg)->uri.len)
820                         continue;
821 #endif
822                 if (cfg_get(tm, tm_cfg, ruri_matching) && !EQ_REQ_URI_LEN)
823                         continue;
824                 if (cfg_get(tm, tm_cfg, via1_matching) && !EQ_VIA_LEN(via1))
825                         continue;
826
827                 /* check the content now */
828                 if (!EQ_STR(callid))
829                         continue;
830                 if (memcmp(get_cseq(t_msg)->number.s,
831                         get_cseq(p_msg)->number.s,get_cseq(p_msg)->number.len)!=0)
832                         continue;
833                 if (!EQ_STR(from))
834                         continue;
835 #ifdef CANCEL_TAG
836                 if (!EQ_STR(to))
837                         continue;
838 #else
839                 if (memcmp(get_to(t_msg)->uri.s, get_to(p_msg)->uri.s,
840                                         get_to(t_msg)->uri.len)!=0)
841                         continue;
842 #endif
843                 if (cfg_get(tm, tm_cfg, ruri_matching) && !EQ_REQ_URI_STR)
844                         continue;
845                 if (cfg_get(tm, tm_cfg, via1_matching) && !EQ_VIA_STR(via1))
846                         continue;
847
848                 /* found */
849                 goto found;
850         }
851
852 notfound:
853         /* no transaction found */
854         DBG("DEBUG: t_lookupOriginalT: no CANCEL matching found! \n" );
855         UNLOCK_HASH(hash_index);
856         DBG("DEBUG: t_lookupOriginalT completed\n");
857         return 0;
858
859 found:
860         DBG("DEBUG: t_lookupOriginalT: canceled transaction"
861                 " found (%p)! \n",p_cell );
862         REF_UNSAFE( p_cell );
863         UNLOCK_HASH(hash_index);
864         DBG("DEBUG: t_lookupOriginalT completed\n");
865         return p_cell;
866 }
867
868
869
870
871 /** get the transaction corresponding to a reply.
872  * @return -1 - nothing found,  1  - T found
873  * Side-effects: sets T and T_branch on success.
874  */
875 int t_reply_matching( struct sip_msg *p_msg , int *p_branch )
876 {
877         struct cell*  p_cell;
878         unsigned int hash_index   = 0;
879         unsigned int entry_label  = 0;
880         unsigned int branch_id    = 0;
881         char  *hashi, *branchi, *p, *n;
882         struct entry* hash_bucket;
883         int hashl, branchl;
884         int scan_space;
885         str cseq_method;
886         str req_method;
887
888         char *loopi;
889         int loopl;
890         char *syni;
891         int synl;
892         
893         short is_cancel;
894
895         /* make compiler warnings happy */
896         loopi=0;
897         loopl=0;
898         syni=0;
899         synl=0;
900
901         /* split the branch into pieces: loop_detection_check(ignored),
902          hash_table_id, synonym_id, branch_id */
903
904         if (!(p_msg->via1 && p_msg->via1->branch && p_msg->via1->branch->value.s))
905                 goto nomatch2;
906
907         /* we do RFC 3261 tid matching and want to see first if there is
908          * magic cookie in branch */
909         if (p_msg->via1->branch->value.len<=MCOOKIE_LEN)
910                 goto nomatch2;
911         if (memcmp(p_msg->via1->branch->value.s, MCOOKIE, MCOOKIE_LEN)!=0)
912                 goto nomatch2;
913
914         p=p_msg->via1->branch->value.s+MCOOKIE_LEN;
915         scan_space=p_msg->via1->branch->value.len-MCOOKIE_LEN;
916
917
918         /* hash_id */
919         n=eat_token2_end( p, p+scan_space, BRANCH_SEPARATOR);
920         hashl=n-p;
921         scan_space-=hashl;
922         if (!hashl || scan_space<2 || *n!=BRANCH_SEPARATOR) goto nomatch2;
923         hashi=p;
924         p=n+1;scan_space--;
925
926         if (!syn_branch) {
927                 /* md5 value */
928                 n=eat_token2_end( p, p+scan_space, BRANCH_SEPARATOR );
929                 loopl = n-p;
930                 scan_space-= loopl;
931                 if (n==p || scan_space<2 || *n!=BRANCH_SEPARATOR) 
932                         goto nomatch2;
933                 loopi=p;
934                 p=n+1; scan_space--;
935         } else {
936                 /* synonym id */
937                 n=eat_token2_end( p, p+scan_space, BRANCH_SEPARATOR);
938                 synl=n-p;
939                 scan_space-=synl;
940                 if (!synl || scan_space<2 || *n!=BRANCH_SEPARATOR) 
941                         goto nomatch2;
942                 syni=p;
943                 p=n+1;scan_space--;
944         }
945
946         /* branch id  -  should exceed the scan_space */
947         n=eat_token_end( p, p+scan_space );
948         branchl=n-p;
949         if (!branchl ) goto nomatch2;
950         branchi=p;
951
952         /* sanity check */
953         if (unlikely(reverse_hex2int(hashi, hashl, &hash_index)<0
954                 ||hash_index>=TABLE_ENTRIES
955                 || reverse_hex2int(branchi, branchl, &branch_id)<0
956                 ||branch_id>=MAX_BRANCHES
957                 || (syn_branch ? (reverse_hex2int(syni, synl, &entry_label))<0 
958                         : loopl!=MD5_LEN ))
959         ) {
960                 DBG("DEBUG: t_reply_matching: poor reply labels %d label %d "
961                         "branch %d\n", hash_index, entry_label, branch_id );
962                 goto nomatch2;
963         }
964
965
966         DBG("DEBUG: t_reply_matching: hash %d label %d branch %d\n",
967                 hash_index, entry_label, branch_id );
968
969
970         /* search the hash table list at entry 'hash_index'; lock the
971            entry first 
972         */
973         cseq_method=get_cseq(p_msg)->method;
974         is_cancel=cseq_method.len==CANCEL_LEN 
975                 && memcmp(cseq_method.s, CANCEL, CANCEL_LEN)==0;
976         LOCK_HASH(hash_index);
977         hash_bucket=&(get_tm_table()->entries[hash_index]);
978         /* all the transactions from the entry are compared */
979         clist_foreach(hash_bucket, p_cell, next_c){
980                 prefetch_loc_r(p_cell->next_c, 1);
981                 /* first look if branch matches */
982                 if (likely(syn_branch)) {
983                         if (p_cell->label != entry_label) 
984                                 continue;
985                 } else {
986                         if ( memcmp(p_cell->md5, loopi,MD5_LEN)!=0)
987                                         continue;
988                 }
989
990                 /* sanity check ... too high branch ? */
991                 if (unlikely(branch_id>=p_cell->nr_of_outgoings))
992                         continue;
993
994                 /* does method match ? (remember -- CANCELs have the same branch
995                    as canceled transactions) */
996                 req_method=p_cell->method;
997                 if ( /* method match */
998                         ! ((cseq_method.len==req_method.len 
999                         && memcmp( cseq_method.s, req_method.s, cseq_method.len )==0)
1000                         /* or it is a local cancel */
1001                         || (is_cancel && is_invite(p_cell)
1002                                 /* commented out -- should_cancel_branch set it to
1003                                    BUSY_BUFFER to avoid collisions with replies;
1004                                    thus, we test here by buffer size
1005                                 */
1006                                 /* && p_cell->uac[branch_id].local_cancel.buffer ))) */
1007                                 && p_cell->uac[branch_id].local_cancel.buffer_len ))) 
1008                         continue;
1009
1010
1011                 /* we passed all disqualifying factors .... the transaction has been
1012                    matched !
1013                 */
1014                 set_t(p_cell, (int)branch_id);
1015                 *p_branch =(int) branch_id;
1016                 REF_UNSAFE( T );
1017                 UNLOCK_HASH(hash_index);
1018                 DBG("DEBUG: t_reply_matching: reply matched (T=%p)!\n",T);
1019                 /* if this is a 200 for INVITE, we will wish to store to-tags to be
1020                  * able to distinguish retransmissions later and not to call
1021                  * TMCB_RESPONSE_OUT uselessly; we do it only if callbacks are
1022                  * enabled -- except callback customers, nobody cares about 
1023                  * retransmissions of multiple 200/INV or ACK/200s
1024                  */
1025                 if (unlikely( is_invite(p_cell) && p_msg->REPLY_STATUS>=200 
1026                         && p_msg->REPLY_STATUS<300 
1027                         && ((!is_local(p_cell) &&
1028                                 has_tran_tmcbs(p_cell, 
1029                                         TMCB_RESPONSE_OUT|TMCB_E2EACK_IN|TMCB_E2EACK_RETR_IN) )
1030                         || (is_local(p_cell)&&has_tran_tmcbs(p_cell, TMCB_LOCAL_COMPLETED))
1031                 )) ) {
1032                         if (parse_headers(p_msg, HDR_TO_F, 0)==-1) {
1033                                 LOG(L_ERR, "ERROR: t_reply_matching: to parsing failed\n");
1034                         }
1035                 }
1036                 if (unlikely(has_tran_tmcbs(T, TMCB_RESPONSE_IN |
1037                                                                                 TMCB_LOCAL_RESPONSE_IN))){
1038                         if (!is_local(p_cell)) {
1039                                 run_trans_callbacks( TMCB_RESPONSE_IN, T, T->uas.request,
1040                                                                                 p_msg, p_msg->REPLY_STATUS);
1041                         }else{
1042                                 run_trans_callbacks( TMCB_LOCAL_RESPONSE_IN, T, T->uas.request,
1043                                                                                 p_msg, p_msg->REPLY_STATUS);
1044                         }
1045                 }
1046                 return 1;
1047         } /* for cycle */
1048
1049         /* nothing found */
1050         UNLOCK_HASH(hash_index);
1051         DBG("DEBUG: t_reply_matching: no matching transaction exists\n");
1052
1053 nomatch2:
1054         DBG("DEBUG: t_reply_matching: failure to match a transaction\n");
1055         *p_branch = -1;
1056         set_t(0, T_BR_UNDEFINED);
1057         return -1;
1058 }
1059
1060
1061
1062
1063 /** Determine current transaction (w/ e2eack support).
1064  *
1065  * script/t_lookup_request  return convention:
1066  *                   Found      Not Found     Error (e.g. parsing) E2E ACK
1067  *  @return          1         -1              0                  -2
1068  *  T                ptr        0              T_UNDEFINED| 0      0
1069  * Side-effects: sets T and T_branch.
1070  */
1071 int t_check_msg( struct sip_msg* p_msg , int *param_branch )
1072 {
1073         int local_branch;
1074         int canceled;
1075         int ret;
1076         
1077         ret=0;
1078         /* is T still up-to-date ? */
1079         DBG("DEBUG: t_check_msg: msg id=%d global id=%d T start=%p\n", 
1080                 p_msg->id,global_msg_id,T);
1081         if ( p_msg->id != global_msg_id || T==T_UNDEFINED )
1082         {
1083                 global_msg_id = p_msg->id;
1084                 set_t(T_UNDEFINED, T_BR_UNDEFINED);
1085                 /* transaction lookup */
1086                 if ( p_msg->first_line.type==SIP_REQUEST ) {
1087                         /* force parsing all the needed headers*/
1088                         prefetch_loc_r(p_msg->unparsed+64, 1);
1089                         if (parse_headers(p_msg, HDR_EOH_F, 0 )==-1) {
1090                                 LOG(L_ERR, "ERROR: t_check_msg: parsing error\n");
1091                                 goto error;
1092                         }
1093                         /* in case, we act as UAS for INVITE and reply with 200,
1094                          * we will need to run dialog-matching for subsequent
1095                          * ACK, for which we need From-tag; We also need from-tag
1096                          * in case people want to have proxied e2e ACKs accounted
1097                          */
1098                         if (p_msg->REQ_METHOD==METHOD_INVITE 
1099                                                         && parse_from_header(p_msg)==-1) {
1100                                 LOG(L_ERR, "ERROR: t_check_msg: from parsing failed\n");
1101                                 goto error;
1102                         }
1103                         ret=t_lookup_request( p_msg , 0 /* unlock before returning */,
1104                                                                         &canceled);
1105                 } else {
1106                         /* we need Via for branch and Cseq method to distinguish
1107                            replies with the same branch/cseqNr (CANCEL)
1108                            and we need all the WWW/Proxy Authenticate headers for
1109                            401 & 407 replies
1110                         */
1111                         if (cfg_get(tm, tm_cfg, tm_aggregate_auth) && 
1112                                         (p_msg->REPLY_STATUS==401 || p_msg->REPLY_STATUS==407)){
1113                                 if (parse_headers(p_msg, HDR_EOH_F,0)==-1){
1114                                         LOG(L_WARN, "WARNING: the reply cannot be "
1115                                                                 "completely parsed\n");
1116                                         /* try to continue, via1 & cseq are checked below */
1117                                 }
1118                         }else if ( parse_headers(p_msg, HDR_VIA1_F|HDR_CSEQ_F, 0 )==-1) {
1119                                 LOG(L_ERR, "ERROR: reply cannot be parsed\n");
1120                                 goto error;
1121                         }
1122                         if ((p_msg->via1==0) || (p_msg->cseq==0)){
1123                                 LOG(L_ERR, "ERROR: reply doesn't have a via or cseq"
1124                                                         " header\n");
1125                                 goto error;
1126                         }
1127                         /* if that is an INVITE, we will also need to-tag
1128                            for later ACK matching
1129                         */
1130                         if ( get_cseq(p_msg)->method.len==INVITE_LEN 
1131                                 && memcmp( get_cseq(p_msg)->method.s, INVITE, INVITE_LEN )==0)
1132                         {
1133                                 if (parse_headers(p_msg, HDR_TO_F, 0)==-1 || !p_msg->to) {
1134                                         LOG(L_ERR, "ERROR: INVITE reply cannot be parsed\n");
1135                                         goto error;
1136                                 }
1137                         }
1138                         ret=t_reply_matching( p_msg ,
1139                                                         param_branch!=0?param_branch:&local_branch );
1140                 }
1141 #ifdef EXTRA_DEBUG
1142                 if ( T && T!=T_UNDEFINED && T->flags & (T_IN_AGONY)) {
1143                         LOG( L_WARN, "WARNING: transaction %p scheduled for deletion "
1144                                 "and called from t_check_msg (flags=%x) (but it might be ok)"
1145                                 "\n", T, T->flags);
1146                 }
1147 #endif
1148                 DBG("DEBUG: t_check_msg: msg id=%d global id=%d T end=%p\n",
1149                         p_msg->id,global_msg_id,T);
1150         } else { /*  ( p_msg->id == global_msg_id && T!=T_UNDEFINED ) */
1151                 if (T){
1152                         DBG("DEBUG: t_check_msg: T already found!\n");
1153                         ret=1;
1154                 }else{
1155                         DBG("DEBUG: t_check_msg: T previously sought and not found\n");
1156                         ret=-1;
1157                 }
1158                 if (likely(param_branch))
1159                         *param_branch=T_branch;
1160         }
1161         return ret;
1162 error:
1163         return 0;
1164 }
1165
1166
1167
1168 /** Determine current transaction (old version).
1169  *
1170  *                   Found      Not Found     Error (e.g. parsing)
1171  *  @return          1          0             -1
1172  *  T                ptr        0             T_UNDEFINED | 0
1173  *
1174  * Side-effects: sets T and T_branch.
1175  */
1176 int t_check( struct sip_msg* p_msg , int *param_branch )
1177 {
1178         int ret;
1179
1180         ret=t_check_msg(p_msg, param_branch);
1181         /* fix t_check_msg return */
1182         switch(ret){
1183                 case -2: /* e2e ack */     return 0;  /* => not found */
1184                 case -1: /* not found */   return 0;  /* => not found */
1185                 case  0: /* parse error */ return -1; /* => error */
1186                 case  1: /* found */       return ret; /* =>  found */
1187         };
1188         return ret;
1189 }
1190
1191
1192
1193 int init_rb( struct retr_buf *rb, struct sip_msg *msg)
1194 {
1195         /*struct socket_info* send_sock;*/
1196         struct via_body* via;
1197         int proto;
1198         int backup_mhomed;
1199
1200         /* rb. timers are init. init_t()/new_cell() */
1201         via=msg->via1;
1202         /* rb->dst is already init (0) by new_t()/build_cell() */
1203         if (!reply_to_via) {
1204                 update_sock_struct_from_ip( &rb->dst.to, msg );
1205                 proto=msg->rcv.proto;
1206         } else {
1207                 /*init retrans buffer*/
1208                 if (update_sock_struct_from_via( &(rb->dst.to), msg, via )==-1) {
1209                         LOG(L_ERR, "ERROR: init_rb: cannot lookup reply dst: %.*s\n",
1210                                 via->host.len, via->host.s );
1211                         ser_error=E_BAD_VIA;
1212                         return 0;
1213                 }
1214                 proto=via->proto;
1215         }
1216         rb->dst.proto=proto;
1217         rb->dst.id=msg->rcv.proto_reserved1;
1218 #ifdef USE_COMP
1219         rb->dst.comp=via->comp_no;
1220 #endif
1221         rb->dst.send_flags=msg->rpl_send_flags;
1222         /* turn off mhomed for generating replies -- they are ideally sent to where
1223            request came from to make life with NATs and other beasts easier
1224         */
1225         backup_mhomed=mhomed;
1226         mhomed=0;
1227         mhomed=backup_mhomed;
1228         /* use for sending replies the incoming interface of the request -bogdan */
1229         /*send_sock=get_send_socket(msg, &rb->dst.to, proto);
1230         if (send_sock==0) {
1231                 LOG(L_ERR, "ERROR: init_rb: cannot fwd to af %d, proto %d "
1232                         "no socket\n", rb->dst.to.s.sa_family, proto);
1233                 ser_error=E_BAD_VIA;
1234                 return 0;
1235         }*/
1236         rb->dst.send_sock=msg->rcv.bind_address;
1237         return 1;
1238 }
1239
1240
1241 static inline void init_new_t(struct cell *new_cell, struct sip_msg *p_msg)
1242 {
1243         struct sip_msg *shm_msg;
1244         unsigned int timeout; /* avp timeout gets stored here (in s) */
1245         ticks_t lifetime;
1246
1247         shm_msg=new_cell->uas.request;
1248         new_cell->from.s=shm_msg->from->name.s;
1249         new_cell->from.len=HF_LEN(shm_msg->from);
1250         new_cell->to.s=shm_msg->to->name.s;
1251         new_cell->to.len=HF_LEN(shm_msg->to);
1252         new_cell->callid.s=shm_msg->callid->name.s;
1253         new_cell->callid.len=HF_LEN(shm_msg->callid);
1254         new_cell->cseq_n.s=shm_msg->cseq->name.s;
1255         new_cell->cseq_n.len=get_cseq(shm_msg)->number.s
1256                 +get_cseq(shm_msg)->number.len
1257                 -shm_msg->cseq->name.s;
1258
1259         new_cell->method=new_cell->uas.request->first_line.u.request.method;
1260         if (p_msg->REQ_METHOD==METHOD_INVITE){
1261                 /* set flags */
1262                 new_cell->flags |= T_IS_INVITE_FLAG |
1263                         get_msgid_val(user_cell_set_flags, p_msg->id, int);
1264                 new_cell->flags|=T_AUTO_INV_100 &
1265                                         (!cfg_get(tm, tm_cfg, tm_auto_inv_100) -1);
1266                 new_cell->flags|=T_DISABLE_6xx &
1267                                         (!cfg_get(tm, tm_cfg, disable_6xx) -1);
1268 #ifdef CANCEL_REASON_SUPPORT
1269                 new_cell->flags|=T_NO_E2E_CANCEL_REASON &
1270                                         (!!cfg_get(tm, tm_cfg, e2e_cancel_reason) -1);
1271 #endif /* CANCEL_REASON_SUPPORT */
1272                 /* reset flags */
1273                 new_cell->flags &=
1274                         (~ get_msgid_val(user_cell_reset_flags, p_msg->id, int));
1275                 
1276                 lifetime=(ticks_t)get_msgid_val(user_inv_max_lifetime,
1277                                                                                                 p_msg->id, int);
1278                 if (likely(lifetime==0))
1279                         lifetime=cfg_get(tm, tm_cfg, tm_max_inv_lifetime);
1280         }else{
1281                 lifetime=(ticks_t)get_msgid_val(user_noninv_max_lifetime, 
1282                                                                                         p_msg->id, int);
1283                 if (likely(lifetime==0))
1284                         lifetime=cfg_get(tm, tm_cfg, tm_max_noninv_lifetime);
1285         }
1286         new_cell->on_negative=get_on_negative();
1287         new_cell->on_reply=get_on_reply();
1288         new_cell->end_of_life=get_ticks_raw()+lifetime;;
1289         new_cell->fr_timeout=(ticks_t)get_msgid_val(user_fr_timeout,
1290                                                                                                 p_msg->id, int);
1291         new_cell->fr_inv_timeout=(ticks_t)get_msgid_val(user_fr_inv_timeout,
1292                                                                                                 p_msg->id, int);
1293         if (likely(new_cell->fr_timeout==0)){
1294                 if (unlikely(!fr_avp2timer(&timeout))) {
1295                         DBG("init_new_t: FR__TIMER = %d s\n", timeout);
1296                         new_cell->fr_timeout=S_TO_TICKS((ticks_t)timeout);
1297                 }else{
1298                         new_cell->fr_timeout=cfg_get(tm, tm_cfg, fr_timeout);
1299                 }
1300         }
1301         if (likely(new_cell->fr_inv_timeout==0)){
1302                 if (unlikely(!fr_inv_avp2timer(&timeout))) {
1303                         DBG("init_new_t: FR_INV_TIMER = %d s\n", timeout);
1304                         new_cell->fr_inv_timeout=S_TO_TICKS((ticks_t)timeout);
1305                         new_cell->flags |= T_NOISY_CTIMER_FLAG;
1306                 }else{
1307                         new_cell->fr_inv_timeout=cfg_get(tm, tm_cfg, fr_inv_timeout);
1308                 }
1309         }
1310 #ifdef TM_DIFF_RT_TIMEOUT
1311         new_cell->rt_t1_timeout=(ticks_t)get_msgid_val(user_rt_t1_timeout,
1312                                                                                                 p_msg->id, int);
1313         if (likely(new_cell->rt_t1_timeout==0))
1314                 new_cell->rt_t1_timeout=cfg_get(tm, tm_cfg, rt_t1_timeout);
1315         new_cell->rt_t2_timeout=(ticks_t)get_msgid_val(user_rt_t2_timeout,
1316                                                                                                 p_msg->id, int);
1317         if (likely(new_cell->rt_t2_timeout==0))
1318                 new_cell->rt_t2_timeout=cfg_get(tm, tm_cfg, rt_t2_timeout);
1319 #endif
1320         new_cell->on_branch=get_on_branch();
1321 }
1322
1323
1324
1325 /** creates a new transaction from a message.
1326  * No checks are made if the transaction exists. It is created and
1327  * added to the tm hashes. T is set to the new transaction.
1328  * @param p_msg - pointer to sip message
1329  * @return  >0 on success, <0 on error (an E_* error code, see error.h)
1330  * Side-effects: sets T and T_branch (T_branch always to T_BR_UNDEFINED).
1331  */
1332 static inline int new_t(struct sip_msg *p_msg)
1333 {
1334         struct cell *new_cell;
1335
1336         /* for ACK-dlw-wise matching, we want From-tags */
1337         if (p_msg->REQ_METHOD==METHOD_INVITE && parse_from_header(p_msg)<0) {
1338                         LOG(L_ERR, "ERROR: new_t: no valid From in INVITE\n");
1339                         return E_BAD_REQ;
1340         }
1341         /* make sure uri will be parsed before cloning */
1342         if (parse_sip_msg_uri(p_msg)<0) {
1343                 LOG(L_ERR, "ERROR: new_t: uri invalid\n");
1344                 return E_BAD_REQ;
1345         }
1346                         
1347         /* add new transaction */
1348         new_cell = build_cell( p_msg ) ;
1349         if  ( !new_cell ){
1350                 LOG(L_ERR, "ERROR: new_t: out of mem:\n");
1351                 return E_OUT_OF_MEM;
1352         } 
1353
1354 #ifdef TM_DEL_UNREF
1355         INIT_REF(new_cell, 2); /* 1 because it will be ref'ed from the
1356                                                                            hash and +1 because we set T to it */
1357 #endif
1358         insert_into_hash_table_unsafe( new_cell, p_msg->hash_index );
1359         set_t(new_cell, T_BR_UNDEFINED);
1360 #ifndef TM_DEL_UNREF
1361         INIT_REF_UNSAFE(T);
1362 #endif
1363         /* init pointers to headers needed to construct local
1364            requests such as CANCEL/ACK
1365         */
1366         init_new_t(new_cell, p_msg);
1367         return 1;
1368 }
1369
1370
1371
1372 /** if no transaction already exists for the message, create a new one.
1373  * atomic "new_tran" construct; it returns:
1374  *
1375  * @return <0   on error
1376  *          +1  if a request did not match a transaction
1377  *           0  on retransmission
1378  * On success, if the request was an ack, the calling function shall
1379  * forward statelessly. Otherwise it means, a new transaction was
1380  * introduced and the calling function shall reply/relay/whatever_appropriate.
1381  * Side-effects: sets T and T_branch (T_branch always to T_BR_UNDEFINED).
1382 */
1383 int t_newtran( struct sip_msg* p_msg )
1384 {
1385         int lret, my_err;
1386         int canceled;
1387
1388
1389         /* is T still up-to-date ? */
1390         DBG("DEBUG: t_newtran: msg id=%d , global msg id=%d ,"
1391                 " T on entrance=%p\n",p_msg->id,global_msg_id,T);
1392
1393         if ( T && T!=T_UNDEFINED  ) {
1394                 /* ERROR message moved to w_t_newtran */
1395                 DBG("DEBUG: t_newtran: "
1396                         "transaction already in process %p\n", T );
1397
1398                 /* t_newtran() has been already called, and the script
1399                 might changed the flags after it, so we must update the flags
1400                 in shm memory -- Miklos */
1401                 if (T->uas.request)
1402                         T->uas.request->flags = p_msg->flags;
1403
1404                 return E_SCRIPT;
1405         }
1406
1407         global_msg_id = p_msg->id;
1408         set_t(T_UNDEFINED, T_BR_UNDEFINED);
1409         /* first of all, parse everything -- we will store in shared memory 
1410            and need to have all headers ready for generating potential replies 
1411            later; parsing later on demand is not an option since the request 
1412            will be in shmem and applying parse_headers to it would intermix 
1413            shmem with pkg_mem
1414         */
1415         
1416         if (parse_headers(p_msg, HDR_EOH_F, 0 )) {
1417                 LOG(L_ERR, "ERROR: t_newtran: parse_headers failed\n");
1418                 return E_BAD_REQ;
1419         }
1420         if ((p_msg->parsed_flag & HDR_EOH_F)!=HDR_EOH_F) {
1421                         LOG(L_ERR, "ERROR: t_newtran: EoH not parsed\n");
1422                         return E_OUT_OF_MEM;
1423         }
1424         /* t_lookup_requests attempts to find the transaction; 
1425            it also calls check_transaction_quadruple -> it is
1426            safe to assume we have from/callid/cseq/to
1427         */ 
1428         lret = t_lookup_request( p_msg, 1 /* leave locked if not found */,
1429                                                                 &canceled );
1430
1431         /* on error, pass the error in the stack ... nothing is locked yet
1432            if 0 is returned */
1433         if (lret==0) return E_BAD_TUPEL;
1434
1435         /* transaction found, it's a retransmission  */
1436         if (lret>0) {
1437                 if (p_msg->REQ_METHOD==METHOD_ACK) {
1438                         if (unlikely(has_tran_tmcbs(T, TMCB_ACK_NEG_IN)))
1439                                 run_trans_callbacks(TMCB_ACK_NEG_IN, T, p_msg, 0, 
1440                                                                                 p_msg->REQ_METHOD);
1441                         t_release_transaction(T);
1442                 } else {
1443                         if (unlikely(has_tran_tmcbs(T, TMCB_REQ_RETR_IN)))
1444                                 run_trans_callbacks(TMCB_REQ_RETR_IN, T, p_msg, 0,
1445                                                                                 p_msg->REQ_METHOD);
1446                         t_retransmit_reply(T);
1447                 }
1448                 /* things are done -- return from script */
1449                 return 0;
1450         }
1451
1452         /* from now on, be careful -- hash table is locked */
1453
1454         if (lret==-2) { /* was it an e2e ACK ? if so, trigger a callback */
1455                 /* no callbacks? complete quickly */
1456                 if (likely( !has_tran_tmcbs(t_ack, 
1457                                                 TMCB_E2EACK_IN|TMCB_E2EACK_RETR_IN) )) {
1458                         UNLOCK_HASH(p_msg->hash_index);
1459                         return 1;
1460                 } 
1461                 REF_UNSAFE(t_ack);
1462                 UNLOCK_HASH(p_msg->hash_index);
1463                 /* we don't call from within REPLY_LOCK -- that introduces
1464                  * a race condition; however, it is so unlikely and the
1465                  * impact is so small (callback called multiple times of
1466                  * multiple ACK/200s received in parallel), that we do not
1467                  * better waste time in locks  */
1468                 if (unmatched_totag(t_ack, p_msg)) {
1469                         if (likely (has_tran_tmcbs(t_ack, TMCB_E2EACK_IN)))
1470                                 run_trans_callbacks( TMCB_E2EACK_IN , t_ack, p_msg, 0,
1471                                                                                 -p_msg->REQ_METHOD );
1472                 }else if (unlikely(has_tran_tmcbs(t_ack, TMCB_E2EACK_RETR_IN))){
1473                         run_trans_callbacks( TMCB_E2EACK_RETR_IN , t_ack, p_msg, 0,
1474                                                                         -p_msg->REQ_METHOD );
1475                 }
1476                 UNREF(t_ack);
1477                 return 1;
1478         }
1479
1480
1481         /* transaction not found, it's a new request (lret<0, lret!=-2);
1482            establish a new transaction ... */
1483         if (p_msg->REQ_METHOD==METHOD_ACK) { /* ... unless it is in ACK */
1484                 my_err=1;
1485                 goto new_err;
1486         }
1487
1488         my_err=new_t(p_msg);
1489         if (my_err<0) {
1490                 LOG(L_ERR, "ERROR: t_newtran: new_t failed\n");
1491                 goto new_err;
1492         }
1493         if (canceled) T->flags|=T_CANCELED; /* mark it for future ref. */
1494
1495
1496         UNLOCK_HASH(p_msg->hash_index);
1497         /* now, when the transaction state exists, check if
1498            there is a meaningful Via and calculate it; better
1499            do it now than later: state is established so that
1500            subsequent retransmissions will be absorbed and will
1501           not possibly block during Via DNS resolution; doing
1502            it later would only burn more CPU as if there is an
1503            error, we cannot relay later whatever comes out of the
1504            the transaction 
1505         */
1506         if (!init_rb( &T->uas.response, p_msg)) {
1507                 LOG(L_ERR, "ERROR: t_newtran: unresolvable via1\n");
1508                 put_on_wait( T );
1509                 t_unref(p_msg);
1510                 return E_BAD_VIA;
1511         }
1512
1513         return 1;
1514
1515
1516 new_err:
1517         UNLOCK_HASH(p_msg->hash_index);
1518         return my_err;
1519
1520 }
1521
1522
1523
1524 /** releases the current transaction (corresp. to p_msg).
1525  * The current transaction (T) corresponding to the sip message being
1526  * processed is released. Delayed replies are sent (if no other reply
1527  * was sent in the script). Extra checks are made to see if the transaction
1528  * was forwarded, explicitly replied or explicitly released. If not the
1529  * transaction * is force-killed and a warning is logged (script error).
1530  * @param p_msg - sip message being processed
1531  * @return -1 on error, 1 on success.
1532  * Side-effects: resets T and T_branch to T_UNDEFINED, T_BR_UNDEFINED,
1533  *  resets tm_error.
1534  */
1535 int t_unref( struct sip_msg* p_msg  )
1536 {
1537         enum kill_reason kr;
1538
1539         if (T==T_UNDEFINED || T==T_NULL_CELL)
1540                 return -1;
1541         if (p_msg->first_line.type==SIP_REQUEST){
1542                 kr=get_kr();
1543                 if (unlikely(kr == REQ_ERR_DELAYED)){
1544                         DBG("t_unref: delayed error reply generation(%d)\n", tm_error);
1545                         if (unlikely(is_route_type(FAILURE_ROUTE))){
1546                                 BUG("tm: t_unref: called w/ kr=REQ_ERR_DELAYED in failure"
1547                                                 " route for %p\n", T);
1548                         }else if (unlikely( kill_transaction(T, tm_error)<=0 )){
1549                                 ERR("ERROR: t_unref: generation of a delayed stateful reply"
1550                                                 " failed\n");
1551                                 t_release_transaction(T);
1552                         }
1553                 }else if ( unlikely (kr==0 ||(p_msg->REQ_METHOD==METHOD_ACK && 
1554                                                                 !(kr & REQ_RLSD)))) {
1555                         LOG(L_WARN, "WARNING: script writer didn't release transaction\n");
1556                         t_release_transaction(T);
1557                 }else if (unlikely((kr & REQ_ERR_DELAYED) &&
1558                                          (kr & ~(REQ_RLSD|REQ_RPLD|REQ_ERR_DELAYED)))){
1559                         BUG("tm: t_unref: REQ_ERR DELAYED should have been caught much"
1560                                         " earlier for %p: %d (hex %x)\n",T, kr, kr);
1561                         t_release_transaction(T);
1562                 }
1563         }
1564         tm_error=0; /* clear it */
1565         UNREF( T );
1566         set_t(T_UNDEFINED, T_BR_UNDEFINED);
1567         return 1;
1568 }
1569
1570
1571
1572 int t_get_trans_ident(struct sip_msg* p_msg, unsigned int* hash_index, unsigned int* label)
1573 {
1574     struct cell* t;
1575     if(t_check(p_msg,0) != 1){
1576         LOG(L_ERR,"ERROR: t_get_trans_ident: no transaction found\n");
1577         return -1;
1578     }
1579     t = get_t();
1580     if(!t){
1581         LOG(L_ERR,"ERROR: t_get_trans_ident: transaction found is NULL\n");
1582         return -1;
1583     }
1584     
1585     *hash_index = t->hash_index;
1586     *label = t->label;
1587
1588     return 1;
1589 }
1590
1591 #ifdef WITH_AS_SUPPORT
1592 /**
1593  * Returns the hash coordinates of the transaction current CANCEL is targeting.
1594  */
1595 int t_get_canceled_ident(struct sip_msg* msg, unsigned int* hash_index, 
1596                 unsigned int* label)
1597 {
1598         struct cell *orig;
1599         if (msg->REQ_METHOD != METHOD_CANCEL) {
1600                 WARN("looking up original transaction for non-CANCEL method (%d).\n",
1601                                 msg->REQ_METHOD);
1602                 return -1;
1603         }
1604         orig = t_lookupOriginalT(msg);
1605         if ((orig == T_NULL_CELL) || (orig == T_UNDEFINED))
1606                 return -1;
1607         *hash_index = orig->hash_index;
1608         *label = orig->label;
1609         DEBUG("original T found @%p, %d:%d.\n", orig, *hash_index, *label);
1610         /* TODO: why's w_t_lookup_cancel setting T to 'undefined'?? */
1611         UNREF(orig);
1612         return 1;
1613 }
1614 #endif /* WITH_AS_SUPPORT */
1615
1616
1617
1618 /** lookup a transaction based on its identifier (hash_index:label).
1619  * @param trans - double pointer to cell structure, that will be filled
1620  *                with the result (a pointer to an existing transaction or
1621  *                0).
1622  * @param hash_index - searched transaction hash_index (part of the ident).
1623  * @param label - searched transaction label (part of the ident).
1624  * @return -1 on error/not found, 1 on success (found)
1625  * Side-effects: sets T and T_branch (T_branch always to T_BR_UNDEFINED).
1626  */
1627 int t_lookup_ident(struct cell ** trans, unsigned int hash_index, 
1628                                         unsigned int label)
1629 {
1630         struct cell* p_cell;
1631         struct entry* hash_bucket;
1632
1633         if(unlikely(hash_index >= TABLE_ENTRIES)){
1634                 LOG(L_ERR,"ERROR: t_lookup_ident: invalid hash_index=%u\n",hash_index);
1635                 return -1;
1636         }
1637         
1638         LOCK_HASH(hash_index);
1639
1640 #ifndef E2E_CANCEL_HOP_BY_HOP
1641 #warning "t_lookup_ident() can only reliably match INVITE transactions in " \
1642                 "E2E_CANCEL_HOP_BY_HOP mode"
1643 #endif
1644         hash_bucket=&(get_tm_table()->entries[hash_index]);
1645         /* all the transactions from the entry are compared */
1646         clist_foreach(hash_bucket, p_cell, next_c){
1647                 prefetch_loc_r(p_cell->next_c, 1);
1648                 if(p_cell->label == label){
1649                         REF_UNSAFE(p_cell);
1650                         UNLOCK_HASH(hash_index);
1651                         set_t(p_cell, T_BR_UNDEFINED);
1652                         *trans=p_cell;
1653                         DBG("DEBUG: t_lookup_ident: transaction found\n");
1654                         return 1;
1655                 }
1656     }
1657         
1658         UNLOCK_HASH(hash_index);
1659         set_t(0, T_BR_UNDEFINED);
1660         *trans=p_cell;
1661
1662         DBG("DEBUG: t_lookup_ident: transaction not found\n");
1663     
1664     return -1;
1665 }
1666
1667
1668
1669 /** check if a transaction is local or not.
1670  * Check if the transaction corresponding to the current message
1671  * is local or not.
1672  * @param p_msg - pointer to sip_msg
1673  * @return -1 on error, 0 if the transaction is not local, 1 if it is local.
1674  * Side-effects: sets T and T_branch.
1675  */
1676 int t_is_local(struct sip_msg* p_msg)
1677 {
1678     struct cell* t;
1679     if(t_check(p_msg,0) != 1){
1680         LOG(L_ERR,"ERROR: t_is_local: no transaction found\n");
1681         return -1;
1682     }
1683     t = get_t();
1684     if(!t){
1685         LOG(L_ERR,"ERROR: t_is_local: transaction found is NULL\n");
1686         return -1;
1687     }
1688     
1689     return is_local(t);
1690 }
1691
1692 /** lookup a transaction based on callid and cseq.
1693  * The parameters are pure header field content only,
1694  * e.g. "123@10.0.0.1" and "11"
1695  * @param trans - double pointer to the transaction, filled with a pointer
1696  *                to the found transaction on success and with 0 if the
1697  *                transaction was not found.
1698  * @param callid - callid for the searched transaction.
1699  * @param cseq - cseq for the searched transaction.
1700  * @return -1 on error/not found, 1 if found.
1701  * Side-effects: sets T and T_branch (T_branch always to T_BR_UNDEFINED).
1702  */
1703 int t_lookup_callid(struct cell ** trans, str callid, str cseq) {
1704         struct cell* p_cell;
1705         unsigned hash_index;
1706         struct entry* hash_bucket;
1707
1708         /* I use MAX_HEADER, not sure if this is a good choice... */
1709         char callid_header[MAX_HEADER];
1710         char cseq_header[MAX_HEADER];
1711         /* save return value of print_* functions here */
1712         char* endpos;
1713
1714         /* need method, which is always INVITE in our case */
1715         /* CANCEL is only useful after INVITE */
1716         str invite_method;
1717         char* invite_string = INVITE;
1718         
1719         invite_method.s = invite_string;
1720         invite_method.len = INVITE_LEN;
1721         
1722         /* lookup the hash index where the transaction is stored */
1723         hash_index=hash(callid, cseq);
1724
1725         if(unlikely(hash_index >= TABLE_ENTRIES)){
1726                 LOG(L_ERR,"ERROR: t_lookup_callid: invalid hash_index=%u\n",hash_index);
1727                 return -1;
1728         }
1729
1730         /* create header fields the same way tm does itself, then compare headers */
1731         endpos = print_callid_mini(callid_header, callid);
1732         DBG("created comparable call_id header field: >%.*s<\n", 
1733                         (int)(endpos - callid_header), callid_header); 
1734
1735         endpos = print_cseq_mini(cseq_header, &cseq, &invite_method);
1736         DBG("created comparable cseq header field: >%.*s<\n", 
1737                         (int)(endpos - cseq_header), cseq_header); 
1738
1739         LOCK_HASH(hash_index);
1740         DBG("just locked hash index %u, looking for transactions there:\n", hash_index);
1741
1742         hash_bucket=&(get_tm_table()->entries[hash_index]);
1743         /* all the transactions from the entry are compared */
1744         clist_foreach(hash_bucket, p_cell, next_c){
1745                 
1746                 prefetch_loc_r(p_cell->next_c, 1);
1747                 /* compare complete header fields, casecmp to make sure invite=INVITE*/
1748                 if ((strncmp(callid_header, p_cell->callid.s, p_cell->callid.len) == 0)
1749                         && (strncasecmp(cseq_header, p_cell->cseq_n.s, p_cell->cseq_n.len)
1750                                 == 0)) {
1751                         DBG("we have a match: callid=>>%.*s<< cseq=>>%.*s<<\n",
1752                                         p_cell->callid.len, p_cell->callid.s, p_cell->cseq_n.len,
1753                                         p_cell->cseq_n.s);
1754                         REF_UNSAFE(p_cell);
1755                         UNLOCK_HASH(hash_index);
1756                         set_t(p_cell, T_BR_UNDEFINED);
1757                         *trans=p_cell;
1758                         DBG("DEBUG: t_lookup_callid: transaction found.\n");
1759                         return 1;
1760                 }
1761                 DBG("NO match: callid=%.*s cseq=%.*s\n", p_cell->callid.len, 
1762                         p_cell->callid.s, p_cell->cseq_n.len, p_cell->cseq_n.s);
1763                         
1764         }
1765
1766         UNLOCK_HASH(hash_index);
1767         DBG("DEBUG: t_lookup_callid: transaction not found.\n");
1768     
1769         return -1;
1770 }
1771
1772
1773
1774 /* params: fr_inv & fr value in ms, 0 means "do not touch"
1775  * ret: 1 on success, -1 on error (script safe)*/
1776 int t_set_fr(struct sip_msg* msg, unsigned int fr_inv_to, unsigned int fr_to)
1777 {
1778         struct cell *t;
1779         ticks_t fr_inv, fr;
1780         
1781         
1782         fr_inv=MS_TO_TICKS((ticks_t)fr_inv_to);
1783         if ((fr_inv==0) && (fr_inv_to!=0)){
1784                 ERR("t_set_fr_inv: fr_inv_timeout too small (%d)\n", fr_inv_to);
1785                 return -1;
1786         }
1787         fr=MS_TO_TICKS((ticks_t)fr_to);
1788         if ((fr==0) && (fr_to!=0)){
1789                 ERR("t_set_fr_inv: fr_timeout too small (%d)\n", fr_to);
1790                 return -1;
1791         }
1792         
1793         t=get_t();
1794         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
1795          * in REQUEST_ROUTE T will be set only if the transaction was already
1796          * created; if not -> use the static variables */
1797         if (!t || t==T_UNDEFINED ){
1798                 set_msgid_val(user_fr_inv_timeout, msg->id, int, (int)fr_inv);
1799                 set_msgid_val(user_fr_timeout, msg->id, int, (int)fr);
1800         }else{
1801                 change_fr(t, fr_inv, fr); /* change running uac timers */
1802         }
1803         return 1;
1804 }
1805
1806 /* reset fr_timer and fr_inv_timer to the default values */
1807 int t_reset_fr()
1808 {
1809         struct cell *t;
1810
1811         t=get_t();
1812         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
1813          * in REQUEST_ROUTE T will be set only if the transaction was already
1814          * created; if not -> use the static variables */
1815         if (!t || t==T_UNDEFINED ){
1816                 memset(&user_fr_inv_timeout, 0, sizeof(user_fr_inv_timeout));
1817                 memset(&user_fr_timeout, 0, sizeof(user_fr_timeout));
1818         }else{
1819                 change_fr(t,
1820                         cfg_get(tm, tm_cfg, fr_inv_timeout),
1821                         cfg_get(tm, tm_cfg, fr_timeout)); /* change running uac timers */
1822         }
1823         return 1;
1824 }
1825
1826 #ifdef TM_DIFF_RT_TIMEOUT
1827
1828 /* params: retr. t1 & retr. t2 value in ms, 0 means "do not touch"
1829  * ret: 1 on success, -1 on error (script safe)*/
1830 int t_set_retr(struct sip_msg* msg, unsigned int t1_to, unsigned int t2_to)
1831 {
1832         struct cell *t;
1833         ticks_t retr_t1, retr_t2;
1834         
1835         
1836         retr_t1=MS_TO_TICKS((ticks_t)t1_to);
1837         if (unlikely((retr_t1==0) && (t1_to!=0))){
1838                 ERR("t_set_retr: retr. t1 interval too small (%u)\n", t1_to);
1839                 return -1;
1840         }
1841         if (unlikely(MAX_UVAR_VALUE(t->rt_t1_timeout) < retr_t1)){
1842                 ERR("t_set_retr: retr. t1 interval too big: %d (max %lu)\n",
1843                                 t1_to, TICKS_TO_MS(MAX_UVAR_VALUE(t->rt_t1_timeout))); 
1844                 return -1;
1845         } 
1846         retr_t2=MS_TO_TICKS((ticks_t)t2_to);
1847         if (unlikely((retr_t2==0) && (t2_to!=0))){
1848                 ERR("t_set_retr: retr. t2 interval too small (%d)\n", t2_to);
1849                 return -1;
1850         }
1851         if (unlikely(MAX_UVAR_VALUE(t->rt_t2_timeout) < retr_t2)){
1852                 ERR("t_set_retr: retr. t2 interval too big: %u (max %lu)\n",
1853                                 t2_to, TICKS_TO_MS(MAX_UVAR_VALUE(t->rt_t2_timeout))); 
1854                 return -1;
1855         } 
1856         
1857         t=get_t();
1858         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
1859          * in REQUEST_ROUTE T will be set only if the transaction was already
1860          * created; if not -> use the static variables */
1861         if (!t || t==T_UNDEFINED ){
1862                 set_msgid_val(user_rt_t1_timeout, msg->id, int, (int)retr_t1);
1863                 set_msgid_val(user_rt_t2_timeout, msg->id, int, (int)retr_t2);
1864         }else{
1865                 change_retr(t, 1, retr_t1, retr_t2); /* change running uac timers */
1866         }
1867         return 1;
1868 }
1869
1870 /* reset retr. t1 and t2 to the default values */
1871 int t_reset_retr()
1872 {
1873         struct cell *t;
1874
1875         t=get_t();
1876         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
1877          * in REQUEST_ROUTE T will be set only if the transaction was already
1878          * created; if not -> use the static variables */
1879         if (!t || t==T_UNDEFINED ){
1880                 memset(&user_rt_t1_timeout, 0, sizeof(user_rt_t1_timeout));
1881                 memset(&user_rt_t2_timeout, 0, sizeof(user_rt_t2_timeout));
1882         }else{
1883                 change_retr(t,
1884                         1,
1885                         cfg_get(tm, tm_cfg, rt_t1_timeout),
1886                         cfg_get(tm, tm_cfg, rt_t2_timeout)); /* change running uac timers */
1887         }
1888         return 1;
1889 }
1890 #endif
1891
1892
1893 /* params: maximum transaction lifetime for inv and non-inv
1894  *         0 means do not touch"
1895  * ret: 1 on success, -1 on error (script safe)*/
1896 int t_set_max_lifetime(struct sip_msg* msg,
1897                                                 unsigned int lifetime_inv_to,
1898                                                 unsigned int lifetime_noninv_to)
1899 {
1900         struct cell *t;
1901         ticks_t max_inv_lifetime, max_noninv_lifetime;
1902         
1903         
1904         max_noninv_lifetime=MS_TO_TICKS((ticks_t)lifetime_noninv_to);
1905         max_inv_lifetime=MS_TO_TICKS((ticks_t)lifetime_inv_to);
1906         if (unlikely((max_noninv_lifetime==0) && (lifetime_noninv_to!=0))){
1907                 ERR("t_set_max_lifetime: non-inv. interval too small (%d)\n",
1908                                 lifetime_noninv_to);
1909                 return -1;
1910         }
1911         if (unlikely((max_inv_lifetime==0) && (lifetime_inv_to!=0))){
1912                 ERR("t_set_max_lifetime: inv. interval too small (%d)\n",
1913                                 lifetime_inv_to);
1914                 return -1;
1915         }
1916         
1917         t=get_t();
1918         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
1919          * in REQUEST_ROUTE T will be set only if the transaction was already
1920          * created; if not -> use the static variables */
1921         if (!t || t==T_UNDEFINED ){
1922                 set_msgid_val(user_noninv_max_lifetime, msg->id, int,
1923                                                 (int)max_noninv_lifetime);
1924                 set_msgid_val(user_inv_max_lifetime, msg->id, int,
1925                                                 (int)max_inv_lifetime);
1926         }else{
1927                 change_end_of_life(t, 1, is_invite(t)?max_inv_lifetime:
1928                                                                                                 max_noninv_lifetime);
1929         }
1930         return 1;
1931 }
1932
1933 /* reset maximum invite/non-invite lifetime to the default value */
1934 int t_reset_max_lifetime()
1935 {
1936         struct cell *t;
1937
1938         t=get_t();
1939         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
1940          * in REQUEST_ROUTE T will be set only if the transaction was already
1941          * created; if not -> use the static variables */
1942         if (!t || t==T_UNDEFINED ){
1943                 memset(&user_inv_max_lifetime, 0, sizeof(user_inv_max_lifetime));
1944                 memset(&user_noninv_max_lifetime, 0, sizeof(user_noninv_max_lifetime));
1945         }else{
1946                 change_end_of_life(t,
1947                                 1,
1948                                 is_invite(t)?
1949                                         cfg_get(tm, tm_cfg, tm_max_inv_lifetime):
1950                                         cfg_get(tm, tm_cfg, tm_max_noninv_lifetime)
1951                                 );
1952         }
1953         return 1;
1954 }
1955
1956 #ifdef WITH_TM_CTX
1957
1958 tm_ctx_t _tm_ctx;
1959
1960 tm_ctx_t* tm_ctx_get(void)
1961 {
1962         return &_tm_ctx;
1963 }
1964
1965 void tm_ctx_init(void)
1966 {
1967         memset(&_tm_ctx, 0, sizeof(tm_ctx_t));
1968 }
1969
1970 void tm_ctx_set_branch_index(int v)
1971 {
1972         _tm_ctx.branch_index = v;
1973 }
1974
1975 #endif
1976