tm: fix possible uninit. use of cancel_reason
[sip-router] / modules / tm / t_reply.c
1 /*
2  * $Id$
3  *
4  *
5  * Copyright (C) 2001-2003 FhG Fokus
6  *
7  * This file is part of ser, a free SIP server.
8  *
9  * ser is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version
13  *
14  * For a license to use the ser software under conditions
15  * other than those described here, or to purchase support for this
16  * software, please contact iptel.org by e-mail at the following addresses:
17  *    info@iptel.org
18  *
19  * ser is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, write to the Free Software
26  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27  *
28  * History:
29  * --------
30  *  2003-01-19  faked lump list created in on_reply handlers
31  *  2003-01-27  next baby-step to removing ZT - PRESERVE_ZT (jiri)
32  *  2003-02-13  updated to use rb->dst (andrei)
33  *  2003-02-18  replaced TOTAG_LEN w/ TOTAG_VALUE_LEN (TOTAG_LEN was defined
34  *               twice with different values!)  (andrei)
35  *  2003-02-28  scratchpad compatibility abandoned (jiri)
36  *  2003-03-01  kr set through a function now (jiri)
37  *  2003-03-06  saving of to-tags for ACK/200 matching introduced,
38  *              voicemail changes accepted, updated to new callback
39  *              names (jiri)
40  *  2003-03-10  fixed new to tag bug/typo (if w/o {})  (andrei)
41  *  2003-03-16  removed _TOTAG (jiri)
42  *  2003-03-31  200 for INVITE/UAS resent even for UDP (jiri)
43  *  2003-03-31  removed msg->repl_add_rm (andrei)
44  *  2003-04-05  s/reply_route/failure_route, onreply_route introduced (jiri)
45  *  2003-04-14  local acks generated before reply processing to avoid
46  *              delays in length reply processing (like opening TCP
47  *              connection to an unavailable destination) (jiri)
48  *  2003-09-11  updates to new build_res_buf_from_sip_req() interface (bogdan)
49  *  2003-09-11  t_reply_with_body() reshaped to use reply_lumps +
50  *              build_res_buf_from_sip_req() instead of
51  *              build_res_buf_with_body_from_sip_req() (bogdan)
52  *  2003-11-05  flag context updated from failure/reply handlers back
53  *              to transaction context (jiri)
54  *  2003-11-11: build_lump_rpl() removed, add_lump_rpl() has flags (bogdan)
55  *  2003-12-04  global TM callbacks switched to per transaction callbacks
56  *              (bogdan)
57  *  2004-02-06: support for user pref. added - destroy_avps (bogdan)
58  *  2003-11-05  flag context updated from failure/reply handlers back
59  *              to transaction context (jiri)
60  *  2003-11-11: build_lump_rpl() removed, add_lump_rpl() has flags (bogdan)
61  *  2004-02-13: t->is_invite and t->local replaced with flags (bogdan)
62  *  2004-02-18  fifo_t_reply imported from vm module (bogdan)
63  *  2004-08-23  avp list is available from failure/on_reply routes (bogdan)
64  *  2004-10-01  added a new param.: restart_fr_on_each_reply (andrei)
65  *  2005-03-01  force for statefull replies the incoming interface of
66  *              the request (bogdan)
67  *  2005-09-01  reverted to the old way of checking response.dst.send_sock
68  *               in t_retransmit_reply & reply_light (andrei)
69  *  2005-11-09  updated to the new timers interface (andrei)
70  *  2006-02-07  named routes support (andrei)
71  *  2006-09-13  t_pick_branch will skip also over branches with empty reply 
72  *              t_should_relay_response will re-pick the branch if failure 
73  *               route /handlers added new branches (andrei)
74  * 2006-10-05  better final reply selection: t_pick_branch will prefer 6xx,
75  *              if no 6xx reply => lowest class/code; if class==4xx =>
76  *              prefer 401, 407, 415, 420 and 484   (andrei)
77  * 2006-10-12  dns failover when a 503 is received
78  *              replace a 503 final relayed reply by a 500 (andrei)
79  * 2006-10-16  aggregate all the authorization headers/challenges when
80  *               the final response is 401 or 407 (andrei)
81  * 2007-03-08  membar_write() used in update_totag_set(...)(andrei)
82  * 2007-03-15  build_local_ack: removed next_hop and replaced with dst to 
83  *              avoid resolving next_hop twice
84  *              added TMCB_ONSEND callbacks support for replies & ACKs (andrei)
85  * 2007-05-28: build_ack() constructs the ACK from the
86  *             outgoing INVITE instead of the incomming one.
87  *             (it can be disabled with reparse_invite=0) (Miklos)
88  * 2007-09-03: drop_replies() has been introduced (Miklos)
89  * 2008-03-12  use cancel_b_method on 6xx (andrei)
90  * 2008-05-30  make sure the wait timer is started after we don't need t
91  *             anymore to allow safe calls from fr_timer (andrei)
92  * 2009-06-01  Pre- and post-script callbacks of branch route are 
93  *             executed (Miklos)
94  * 2009-12-10  reply route is executed under lock to protect the avps (andrei)
95  * 2010-02-22  _reply() will cleanup any reply lumps that it might have added
96  *             (andrei)
97  * 2010-02-26  added experimental support for final reply dropping, not
98  *             enabled by default (performance hit) (andrei)
99  * 2010-02-26  cancel reason (rfc3326) basic support (andrei)
100  *
101  */
102
103  /* Defines:
104   *           TM_ONREPLY_FINAL_DROP_OK - allows dropping the final reply
105   *            from the tm onreply_routes, but comes with a small performance
106   *            hit (extra unlock()/lock() for each final reply when a onreply
107   *            route is set).
108   */
109
110 #ifdef EXTRA_DEBUG
111 #include <assert.h>
112 #endif
113 #include "../../comp_defs.h"
114 #include "../../hash_func.h"
115 #include "../../dprint.h"
116 #include "../../config.h"
117 #include "../../parser/parser_f.h"
118 #include "../../parser/parse_to.h"
119 #include "../../ut.h"
120 #include "../../timer.h"
121 #include "../../error.h"
122 #include "../../action.h"
123 #include "../../script_cb.h"
124 #include "../../dset.h"
125 #include "../../tags.h"
126 #include "../../route.h"
127 #include "../../data_lump.h"
128 #include "../../data_lump_rpl.h"
129 #include "../../usr_avp.h"
130 #ifdef WITH_XAVP
131 #include "../../usr_avp.h"
132 #endif
133 #include "../../atomic_ops.h" /* membar_write() */
134 #include "../../compiler_opt.h"
135 #ifdef USE_DST_BLACKLIST
136 #include "../../dst_blacklist.h"
137 #endif
138 #ifdef USE_DNS_FAILOVER
139 #include "../../dns_cache.h"
140 #include "../../cfg_core.h" /* cfg_get(core, core_cfg, use_dns_failover) */
141 #endif
142
143 #include "defs.h"
144 #include "config.h"
145 #include "h_table.h"
146 #include "t_hooks.h"
147 #include "t_funcs.h"
148 #include "t_reply.h"
149 #include "t_cancel.h"
150 #include "t_msgbuilder.h"
151 #include "t_lookup.h"
152 #include "t_fwd.h"
153 #include "../../fix_lumps.h"
154 #include "../../sr_compat.h"
155 #include "t_stats.h"
156 #include "uac.h"
157
158
159 #ifdef NO_TM_ONREPLY_FINAL_DROP_OK
160 #undef TM_ONREPLY_FINAL_DROP_OK
161 #endif
162
163 /* private place where we create to-tags for replies */
164 /* janakj: made public, I need to access this value to store it in dialogs */
165 char tm_tags[TOTAG_VALUE_LEN];
166 /* bogdan: pack tm_tag buffer and len into a str to pass them to
167  * build_res_buf_from_sip_req() */
168 static str  tm_tag = {tm_tags,TOTAG_VALUE_LEN};
169 char *tm_tag_suffix;
170
171 /* where to go if there is no positive reply */
172 static int goto_on_negative=0;
173 /* where to go on receipt of reply */
174 static int goto_on_reply=0;
175 /* where to go on receipt of reply without transaction context */
176 int goto_on_sl_reply=0;
177
178 /* how to deal with winning branch reply selection in failure_route
179  * can be overwritten per transaction with t_drop_replies(...)
180  * Values:
181  * - 0 - all branches are kept (default, and default ser 2.1.x behaviour)
182  * - 1 - all branches are discarded
183  * - 2 - braches of last step of serial forking are discarded
184  * - 3 - all branches are discarded if a new leg of serial forking
185  *       is started (default kamailio 1.5.x behaviour)
186  */
187 int failure_reply_mode = 0;
188
189 /* responses priority (used by t_pick_branch)
190  *  0xx is used only for the initial value (=> should have no chance to be
191  *  selected => the highest value); 1xx is not used */
192 static unsigned short resp_class_prio[]={
193                         32000, /* 0-99, special */
194                         11000, /* 1xx, special, should never be used */
195                                 0,  /* 2xx, high priority (not used, 2xx are immediately 
196                                        forwarded and t_pick_branch will never be called if
197                                            a 2xx was received) */
198                         3000,  /* 3xx */
199                         4000,  /* 4xx */
200                         5000,  /* 5xx */
201                         1000   /* 6xx, highest priority */
202 };
203
204
205 int t_get_reply_totag(struct sip_msg *msg, str *totag)
206 {
207         if(msg==NULL || totag==NULL) {
208                 return -1;
209         }
210
211     calc_crc_suffix(msg, tm_tag_suffix);
212         *totag = tm_tag;
213         
214         return 1;
215 }
216
217 static int picked_branch = -1;
218
219 /*! \brief returns the picked branch */
220 int t_get_picked_branch(void)
221 {
222         return picked_branch;
223 }
224
225
226
227
228 /* we store the reply_route # in private memory which is
229    then processed during t_relay; we cannot set this value
230    before t_relay creates transaction context or after
231    t_relay when a reply may arrive after we set this
232    value; that's why we do it how we do it, i.e.,
233    *inside*  t_relay using hints stored in private memory
234    before t_relay is called
235 */
236
237
238 void t_on_negative( unsigned int go_to )
239 {
240         struct cell *t = get_t();
241
242         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
243          * in REQUEST_ROUTE T will be set only if the transaction was already
244          * created; if not -> use the static variable */
245         if (!t || t==T_UNDEFINED )
246                 goto_on_negative=go_to;
247         else
248                 get_t()->on_negative = go_to;
249 }
250
251
252 void t_on_reply( unsigned int go_to )
253 {
254         struct cell *t = get_t();
255
256         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
257          * in REQUEST_ROUTE T will be set only if the transaction was already
258          * created; if not -> use the static variable */
259         if (!t || t==T_UNDEFINED )
260                 goto_on_reply=go_to;
261         else
262                 get_t()->on_reply = go_to;
263 }
264
265
266 unsigned int get_on_negative()
267 {
268         return goto_on_negative;
269 }
270 unsigned int get_on_reply()
271 {
272         return goto_on_reply;
273 }
274
275 void tm_init_tags()
276 {
277         init_tags(tm_tags, &tm_tag_suffix,
278                 "SER-TM/tags", TM_TAG_SEPARATOR );
279 }
280
281 /* returns 0 if the message was previously acknowledged
282  * (i.e., no E2EACK callback is needed) and one if the
283  * callback shall be executed */
284 int unmatched_totag(struct cell *t, struct sip_msg *ack)
285 {
286         struct totag_elem *i;
287         str *tag;
288
289         if (parse_headers(ack, HDR_TO_F,0)==-1 ||
290                                 !ack->to ) {
291                 LOG(L_ERR, "ERROR: unmatched_totag: To invalid\n");
292                 return 1;
293         }
294         tag=&get_to(ack)->tag_value;
295         i=t->fwded_totags;
296         while(i){
297                 membar_depends(); /* make sure we don't see some old i content
298                                                         (needed on CPUs like Alpha) */
299                 if (i->tag.len==tag->len
300                                 && memcmp(i->tag.s, tag->s, tag->len)==0) {
301                         DBG("DEBUG: totag for e2e ACK found: %d\n", i->acked);
302                         /* mark totag as acked and return 1 if this was the first ack
303                          * and 0 otherwise */
304                         return (atomic_get_and_set_int(&i->acked, 1)==0);
305                 }
306                 i=i->next;
307         }
308         /* surprising: to-tag never sighted before */
309         return 1;
310 }
311
312 static inline void update_local_tags(struct cell *trans,
313                                 struct bookmark *bm, char *dst_buffer,
314                                 char *src_buffer /* to which bm refers */)
315 {
316         if (bm->to_tag_val.s) {
317                 trans->uas.local_totag.s=bm->to_tag_val.s-src_buffer+dst_buffer;
318                 trans->uas.local_totag.len=bm->to_tag_val.len;
319         }
320 }
321
322
323 /* append a newly received tag from a 200/INVITE to
324  * transaction's set; (only safe if called from within
325  * a REPLY_LOCK); it returns 1 if such a to tag already
326  * exists
327  */
328 inline static int update_totag_set(struct cell *t, struct sip_msg *ok)
329 {
330         struct totag_elem *i, *n;
331         str *tag;
332         char *s;
333
334         if (!ok->to || !ok->to->parsed) {
335                 LOG(L_ERR, "ERROR: update_totag_set: to not parsed\n");
336                 return 0;
337         }
338         tag=&get_to(ok)->tag_value;
339         if (!tag->s) {
340                 DBG("ERROR: update_totag_set: no tag in to\n");
341                 return 0;
342         }
343
344         for (i=t->fwded_totags; i; i=i->next) {
345                 if (i->tag.len==tag->len
346                                 && memcmp(i->tag.s, tag->s, tag->len) ==0 ){
347                         /* to tag already recorded */
348 #ifdef XL_DEBUG
349                         LOG(L_CRIT, "DEBUG: update_totag_set: totag retransmission\n");
350 #else
351                         DBG("DEBUG: update_totag_set: totag retransmission\n");
352 #endif
353                         return 1;
354                 }
355         }
356         /* that's a new to-tag -- record it */
357         shm_lock();
358         n=(struct totag_elem*) shm_malloc_unsafe(sizeof(struct totag_elem));
359         s=(char *)shm_malloc_unsafe(tag->len);
360         shm_unlock();
361         if (!s || !n) {
362                 LOG(L_ERR, "ERROR: update_totag_set: no  memory \n");
363                 if (n) shm_free(n);
364                 if (s) shm_free(s);
365                 return 0;
366         }
367         memset(n, 0, sizeof(struct totag_elem));
368         memcpy(s, tag->s, tag->len );
369         n->tag.s=s;n->tag.len=tag->len;
370         n->next=t->fwded_totags;
371         membar_write(); /* make sure all the changes to n are visible on all cpus
372                                            before we update t->fwded_totags. This is needed for
373                                            three reasons: the compiler might reorder some of the 
374                                            writes, the cpu/cache could also reorder them with
375                                            respect to the visibility on other cpus
376                                            (e.g. some of the changes to n could be visible on
377                                             another cpu _after_ seeing t->fwded_totags=n) and
378                                            the "readers" (unmatched_tags()) do not use locks and
379                                            can be called simultaneously on another cpu.*/
380         t->fwded_totags=n;
381         DBG("DEBUG: update_totag_set: new totag \n");
382         return 0;
383 }
384
385
386 /*
387  * Build an ACK to a negative reply
388  */
389 static char *build_ack(struct sip_msg* rpl,struct cell *trans,int branch,
390         unsigned int *ret_len)
391 {
392         str to;
393
394     if (parse_headers(rpl,HDR_TO_F, 0)==-1 || !rpl->to ) {
395         LOG(L_ERR, "ERROR: build_ack: "
396             "cannot generate a HBH ACK if key HFs in reply missing\n");
397         return NULL;
398     }
399         to.s=rpl->to->name.s;
400         to.len=rpl->to->len;
401
402         if (cfg_get(tm, tm_cfg, reparse_invite)) {
403                 /* build the ACK from the INVITE which was sent out */
404                 return build_local_reparse( trans, branch, ret_len,
405                                         ACK, ACK_LEN, &to
406         #ifdef CANCEL_REASON_SUPPORT
407                                         , 0
408         #endif /* CANCEL_REASON_SUPPORT */
409                                         );
410         } else {
411                 /* build the ACK from the reveived INVITE */
412                 return build_local( trans, branch, ret_len,
413                                         ACK, ACK_LEN, &to
414         #ifdef CANCEL_REASON_SUPPORT
415                                         , 0
416         #endif /* CANCEL_REASON_SUPPORT */
417                                         );
418         }
419 }
420
421
422 /*
423  * The function builds an ACK to 200 OK of local transactions, honoring the
424  * route set.
425  * The destination to which the message should be sent will be returned
426  * in the dst parameter.
427  * returns 0 on error and a pkg_malloc'ed buffer with length in ret_len
428  *  and intended destination in dst on success.
429  */
430 static char *build_local_ack(struct sip_msg* rpl, struct cell *trans, 
431                                                                 int branch, unsigned int *ret_len,
432                                                                 struct dest_info*  dst)
433 {
434 #ifdef WITH_AS_SUPPORT
435         struct retr_buf *local_ack, *old_lack;
436
437         /* do we have the ACK cache, previously build? */
438         if ((local_ack = trans->uac[0].local_ack) && local_ack->buffer_len) {
439                 DEBUG("reusing ACK retr. buffer.\n");
440                 *ret_len = local_ack->buffer_len;
441                 *dst = local_ack->dst;
442                 return local_ack->buffer;
443         }
444
445         /* the ACK will be built (and cached) by the AS (ack_local_uac()) */
446         if (trans->flags & T_NO_AUTO_ACK) 
447                 return NULL;
448
449         if (! (local_ack = local_ack_rb(rpl, trans, branch, /*hdrs*/NULL, 
450                         /*body*/NULL))) {
451                 ERR("failed to build local ACK retransmission buffer (T@%p).\n",trans);
452                 return NULL;
453         }
454
455         /* set the new buffer, but only if not already set (concurrent 2xx) */
456         /* a memory write barrier is needed to make sure the local_ack
457            content is fully written, before we try to add it to the transaction
458            -- andrei */
459         membar_write_atomic_op();
460         if ((old_lack = (struct retr_buf *)atomic_cmpxchg_long(
461                         (void *)&trans->uac[0].local_ack, 0, (long)local_ack))) {
462                 /* buffer already set: trash current and use the winning one */
463                 INFO("concurrent 2xx to local INVITE detected (T@%p).\n", trans);
464                 free_local_ack(local_ack);
465                 local_ack = old_lack;
466         }
467         
468         *ret_len = local_ack->buffer_len;
469         *dst = local_ack->dst;
470         return local_ack->buffer;
471 #else /* ! WITH_AS_SUPPORT */
472         return build_dlg_ack(rpl, trans, branch, /*hdrs*/NULL, /*body*/NULL, 
473                         ret_len, dst);
474 #endif /* WITH_AS_SUPPORT */
475 }
476
477
478
479 #if 0 /* candidate for removal --andrei */
480      /*
481       * The function is used to send a localy generated ACK to INVITE
482       * (tm generates the ACK on behalf of application using UAC
483       */
484 static int send_local_ack(struct sip_msg* msg, str* next_hop,
485                                                         char* ack, int ack_len)
486 {
487         struct dest_info dst;
488 #ifdef USE_DNS_FAILOVER
489         struct dns_srv_handle dns_h;
490 #endif
491
492         if (!next_hop) {
493                 LOG(L_ERR, "send_local_ack: Invalid parameter value\n");
494                 return -1;
495         }
496 #ifdef USE_DNS_FAILOVER
497         if (cfg_get(core, core_cfg, use_dns_failover)){
498                 dns_srv_handle_init(&dns_h);
499                 if ((uri2dst(&dns_h, &dst, msg,  next_hop, PROTO_NONE)==0) || 
500                                 (dst.send_sock==0)){
501                         dns_srv_handle_put(&dns_h);
502                         LOG(L_ERR, "send_local_ack: no socket found\n");
503                         return -1;
504                 }
505                 dns_srv_handle_put(&dns_h); /* not needed anymore */
506         }else{
507                 if ((uri2dst(0, &dst, msg,  next_hop, PROTO_NONE)==0) || 
508                                 (dst.send_sock==0)){
509                         LOG(L_ERR, "send_local_ack: no socket found\n");
510                         return -1;
511                 }
512         }
513 #else
514         if ((uri2dst(&dst, msg,  next_hop, PROTO_NONE)==0) || (dst.send_sock==0)){
515                 LOG(L_ERR, "send_local_ack: no socket found\n");
516                 return -1;
517         }
518 #endif
519         return msg_send(&dst, ack, ack_len);
520 }
521 #endif
522
523
524
525 inline static void start_final_repl_retr( struct cell *t )
526 {
527         if (unlikely(!is_local(t) && t->uas.request->REQ_METHOD==METHOD_INVITE )){
528                 /* crank timers for negative replies */
529                 if (t->uas.status>=300) {
530                         if (start_retr(&t->uas.response)!=0)
531                                 LOG(L_CRIT, "BUG: start_final_repl_retr: start retr failed"
532                                                 " for %p\n", &t->uas.response);
533                         return;
534                 }
535                 /* local UAS retransmits too */
536                 if (t->relayed_reply_branch==-2 && t->uas.status>=200) {
537                         /* we retransmit 200/INVs regardless of transport --
538                            even if TCP used, UDP could be used upstream and
539                            loose the 200, which is not retransmitted by proxies
540                         */
541                         if (force_retr( &t->uas.response )!=0)
542                                 LOG(L_CRIT, "BUG: start_final_repl_retr: force retr failed for"
543                                                 " %p\n", &t->uas.response);
544                         return;
545                 }
546         }
547 }
548
549
550
551 static int _reply_light( struct cell *trans, char* buf, unsigned int len,
552                          unsigned int code,
553                          char *to_tag, unsigned int to_tag_len, int lock,
554                          struct bookmark *bm    )
555 {
556         struct retr_buf *rb;
557         unsigned int buf_len;
558         struct cancel_info cancel_data;
559 #ifdef TMCB_ONSEND
560         struct tmcb_params onsend_params;
561 #endif
562
563         init_cancel_info(&cancel_data);
564         if (!buf)
565         {
566                 DBG("DEBUG: _reply_light: response building failed\n");
567                 /* determine if there are some branches to be canceled */
568                 if ( is_invite(trans) ) {
569                         prepare_to_cancel(trans, &cancel_data.cancel_bitmap, 0);
570                 }
571                 /* and clean-up, including cancellations, if needed */
572                 goto error;
573         }
574
575         if (lock) LOCK_REPLIES( trans );
576         if (trans->uas.status>=200) {
577                 LOG( L_ERR, "ERROR: _reply_light: can't generate %d reply"
578                         " when a final %d was sent out\n", code, trans->uas.status);
579                 goto error2;
580         }
581
582         rb = & trans->uas.response;
583         rb->activ_type=code;
584
585         trans->uas.status = code;
586         buf_len = rb->buffer ? len : len + REPLY_OVERBUFFER_LEN;
587         rb->buffer = (char*)shm_resize( rb->buffer, buf_len );
588         /* puts the reply's buffer to uas.response */
589         if (! rb->buffer ) {
590                         LOG(L_ERR, "ERROR: _reply_light: cannot allocate shmem buffer\n");
591                         goto error3;
592         }
593         update_local_tags(trans, bm, rb->buffer, buf);
594
595         rb->buffer_len = len ;
596         memcpy( rb->buffer , buf , len );
597         /* needs to be protected too because what timers are set depends
598            on current transactions status */
599         /* t_update_timers_after_sending_reply( rb ); */
600         update_reply_stats( code );
601         trans->relayed_reply_branch=-2;
602         t_stats_replied_locally();
603         if (lock) UNLOCK_REPLIES( trans );
604
605         /* do UAC cleanup procedures in case we generated
606            a final answer whereas there are pending UACs */
607         if (code>=200) {
608                 if (unlikely(is_local(trans))) {
609                         if(unlikely(has_tran_tmcbs(trans, TMCB_LOCAL_COMPLETED)))
610                                 run_trans_callbacks(TMCB_LOCAL_COMPLETED, trans,
611                                                                         0, FAKED_REPLY, code);
612                 } else {
613                         if(unlikely(has_tran_tmcbs(trans, TMCB_RESPONSE_READY))) {
614                                 run_trans_callbacks(TMCB_RESPONSE_READY, trans,
615                                         trans->uas.request, FAKED_REPLY, code);
616                         }
617                 }
618                 cleanup_uac_timers( trans );
619                 if (is_invite(trans)){
620                         prepare_to_cancel(trans, &cancel_data.cancel_bitmap, 0);
621 #ifdef CANCEL_REASON_SUPPORT
622                         cancel_data.reason.cause=code;
623 #endif /* CANCEL_REASON_SUPPORT */
624                         cancel_uacs( trans, &cancel_data, F_CANCEL_B_KILL );
625                 }
626                 start_final_repl_retr(  trans );
627         }
628
629         /* send it out */
630         /* first check if we managed to resolve topmost Via -- if
631            not yet, don't try to retransmit
632         */
633         /*
634            response.dst.send_sock might be unset if the process that created
635            the original transaction has not finished initialising the
636            retransmission buffer (see t_newtran/ init_rb).
637            If reply_to_via is set and via contains a host name (and not an ip)
638            the chances for this increase a lot.
639          */
640         if (unlikely(!trans->uas.response.dst.send_sock)) {
641                 LOG(L_ERR, "ERROR: _reply_light: no resolved dst to send reply to\n");
642         } else {
643                 if (likely(SEND_PR_BUFFER( rb, buf, len )>=0)){
644                         if (unlikely(code>=200 && !is_local(trans) &&
645                                                 has_tran_tmcbs(trans, TMCB_RESPONSE_OUT)) )
646                                 run_trans_callbacks(TMCB_RESPONSE_OUT, trans,
647                                                                         trans->uas.request, FAKED_REPLY, code);
648 #ifdef TMCB_ONSEND
649                         if (unlikely(has_tran_tmcbs(trans, TMCB_RESPONSE_SENT))){
650                                 INIT_TMCB_ONSEND_PARAMS(onsend_params, trans->uas.request,
651                                                                 FAKED_REPLY, rb, &rb->dst, 
652                                                                 buf, len, TMCB_LOCAL_F, rb->branch, code);
653                                 run_onsend_callbacks2(TMCB_RESPONSE_SENT, trans,
654                                                                                 &onsend_params);
655                         }
656 #endif /* TMCB_ONSEND */
657                 }
658                 DBG("DEBUG: reply sent out. buf=%p: %.20s..., shmem=%p: %.20s\n",
659                         buf, buf, rb->buffer, rb->buffer );
660         }
661         if (code>=200) {
662                 /* start wait timer after finishing with t so that this function can
663                  * be safely called from a fr_timer which allows quick timer dels
664                  * (timer_allow_del()) (there's no chance of having the wait handler
665                  *  executed while we still need t) --andrei */
666                 put_on_wait(trans);
667         }
668         pkg_free( buf ) ;
669         DBG("DEBUG: _reply_light: finished\n");
670         return 1;
671
672 error3:
673         prepare_to_cancel(trans, &cancel_data.cancel_bitmap, 0);
674 error2:
675         if (lock) UNLOCK_REPLIES( trans );
676         pkg_free ( buf );
677 error:
678         /* do UAC cleanup */
679         cleanup_uac_timers( trans );
680         if ( is_invite(trans) && cancel_data.cancel_bitmap )
681                 cancel_uacs( trans, &cancel_data, F_CANCEL_B_KILL);
682         /* we did not succeed -- put the transaction on wait */
683         put_on_wait(trans);
684         return -1;
685 }
686
687
688 /* send a UAS reply
689  * returns 1 if everything was OK or -1 for error
690  */
691 static int _reply( struct cell *trans, struct sip_msg* p_msg,
692         unsigned int code, char * text, int lock )
693 {
694         unsigned int len;
695         char * buf, *dset;
696         struct bookmark bm;
697         int dset_len;
698         struct lump_rpl* rpl_l;
699         str reason;
700
701         rpl_l=0;
702         if (code>=200) set_kr(REQ_RPLD);
703         /* compute the buffer in private memory prior to entering lock;
704          * create to-tag if needed */
705
706         /* if that is a redirection message, dump current message set to it */
707         if (code>=300 && code<400) {
708                 dset=print_dset(p_msg, &dset_len);
709                 if (dset) {
710                         add_lump_rpl(p_msg, dset, dset_len, LUMP_RPL_HDR);
711                 }
712         }
713
714         reason.s = text;
715         reason.len = strlen(text);
716         if (code>=180 && p_msg->to
717                                 && (get_to(p_msg)->tag_value.s==0
718                             || get_to(p_msg)->tag_value.len==0)) {
719                 calc_crc_suffix( p_msg, tm_tag_suffix );
720                 buf = build_res_buf_from_sip_req(code, &reason, &tm_tag, p_msg,
721                                 &len, &bm);
722                 if (unlikely(rpl_l)){
723                         unlink_lump_rpl(p_msg, rpl_l);
724                         free_lump_rpl(rpl_l);
725                 }
726                 return _reply_light( trans, buf, len, code,
727                         tm_tag.s, TOTAG_VALUE_LEN, lock, &bm);
728         } else {
729                 buf = build_res_buf_from_sip_req(code, &reason, 0 /*no to-tag*/,
730                         p_msg, &len, &bm);
731                 if (unlikely(rpl_l)){
732                         unlink_lump_rpl(p_msg, rpl_l);
733                         free_lump_rpl(rpl_l);
734                 }
735                 return _reply_light(trans,buf,len,code,
736                         0, 0, /* no to-tag */lock, &bm);
737         }
738 }
739
740 /** create or restore a "fake environment" for running a failure_route.
741  *if msg is set -> it will fake the env. vars conforming with the msg; if NULL
742  * the env. will be restore to original.
743  * Side-effect: mark_ruri_consumed().
744  */
745 void faked_env( struct cell *t, struct sip_msg *msg)
746 {
747         static int backup_route_type;
748         static struct cell *backup_t;
749         static int backup_branch;
750         static unsigned int backup_msgid;
751         static avp_list_t* backup_user_from, *backup_user_to;
752         static avp_list_t* backup_domain_from, *backup_domain_to;
753         static avp_list_t* backup_uri_from, *backup_uri_to;
754 #ifdef WITH_XAVP
755         static sr_xavp_t **backup_xavps;
756 #endif
757         static struct socket_info* backup_si;
758
759         if (msg) {
760                 /* remember we are back in request processing, but process
761                  * a shmem-ed replica of the request; advertise it in route type;
762                  * for example t_reply needs to know that
763                  */
764                 backup_route_type=get_route_type();
765                 set_route_type(FAILURE_ROUTE);
766                 /* don't bother backing up ruri state, since failure route
767                    is called either on reply or on timer and in both cases
768                    the ruri should not be used again for forking */
769                 ruri_mark_consumed(); /* in failure route we assume ruri
770                                                                  should not be used again for forking */
771                 /* also, tm actions look in beginning whether transaction is
772                  * set -- whether we are called from a reply-processing
773                  * or a timer process, we need to set current transaction;
774                  * otherwise the actions would attempt to look the transaction
775                  * up (unnecessary overhead, refcounting)
776                  */
777                 /* backup */
778                 backup_t=get_t();
779                 backup_branch=get_t_branch();
780                 backup_msgid=global_msg_id;
781                 /* fake transaction and message id */
782                 global_msg_id=msg->id;
783                 set_t(t, T_BR_UNDEFINED);
784                 /* make available the avp list from transaction */
785
786                 backup_uri_from = set_avp_list(AVP_TRACK_FROM | AVP_CLASS_URI, &t->uri_avps_from );
787                 backup_uri_to = set_avp_list(AVP_TRACK_TO | AVP_CLASS_URI, &t->uri_avps_to );
788                 backup_user_from = set_avp_list(AVP_TRACK_FROM | AVP_CLASS_USER, &t->user_avps_from );
789                 backup_user_to = set_avp_list(AVP_TRACK_TO | AVP_CLASS_USER, &t->user_avps_to );
790                 backup_domain_from = set_avp_list(AVP_TRACK_FROM | AVP_CLASS_DOMAIN, &t->domain_avps_from );
791                 backup_domain_to = set_avp_list(AVP_TRACK_TO | AVP_CLASS_DOMAIN, &t->domain_avps_to );
792 #ifdef WITH_XAVP
793                 backup_xavps = xavp_set_list(&t->xavps_list);
794 #endif
795                 /* set default send address to the saved value */
796                 backup_si=bind_address;
797                 bind_address=t->uac[0].request.dst.send_sock;
798         } else {
799                 /* restore original environment */
800                 set_t(backup_t, backup_branch);
801                 global_msg_id=backup_msgid;
802                 set_route_type(backup_route_type);
803                 /* restore original avp list */
804                 set_avp_list(AVP_TRACK_FROM | AVP_CLASS_USER, backup_user_from );
805                 set_avp_list(AVP_TRACK_TO | AVP_CLASS_USER, backup_user_to );
806                 set_avp_list(AVP_TRACK_FROM | AVP_CLASS_DOMAIN, backup_domain_from );
807                 set_avp_list(AVP_TRACK_TO | AVP_CLASS_DOMAIN, backup_domain_to );
808                 set_avp_list(AVP_TRACK_FROM | AVP_CLASS_URI, backup_uri_from );
809                 set_avp_list(AVP_TRACK_TO | AVP_CLASS_URI, backup_uri_to );
810 #ifdef WITH_XAVP
811                 xavp_set_list(backup_xavps);
812 #endif
813                 bind_address=backup_si;
814         }
815 }
816
817
818 int fake_req(struct sip_msg *faked_req,
819                 struct sip_msg *shmem_msg, int extra_flags, struct ua_client *uac)
820 {
821         /* on_negative_reply faked msg now copied from shmem msg (as opposed
822          * to zero-ing) -- more "read-only" actions (exec in particular) will
823          * work from reply_route as they will see msg->from, etc.; caution,
824          * rw actions may append some pkg stuff to msg, which will possibly be
825          * never released (shmem is released in a single block) */
826         memcpy( faked_req, shmem_msg, sizeof(struct sip_msg));
827
828         /* if we set msg_id to something different from current's message
829          * id, the first t_fork will properly clean new branch URIs */
830         faked_req->id=shmem_msg->id-1;
831         /* msg->parsed_uri_ok must be reset since msg_parsed_uri is
832          * not cloned (and cannot be cloned) */
833         faked_req->parsed_uri_ok = 0;
834         
835         faked_req->msg_flags|=extra_flags; /* set the extra tm flags */
836
837         /* dst_uri can change ALSO!!! -- make a private copy */
838         if (shmem_msg->dst_uri.s!=0 && shmem_msg->dst_uri.len!=0) {
839                 faked_req->dst_uri.s=pkg_malloc(shmem_msg->dst_uri.len+1);
840                 if (!faked_req->dst_uri.s) {
841                         LOG(L_ERR, "ERROR: fake_req: no uri/pkg mem\n");
842                         goto error01;
843                 }
844                 faked_req->dst_uri.len=shmem_msg->dst_uri.len;
845                 memcpy( faked_req->dst_uri.s, shmem_msg->dst_uri.s,
846                         faked_req->dst_uri.len);
847                 faked_req->dst_uri.s[faked_req->dst_uri.len]=0;
848         }else{
849                 /* in case len==0, but shmem_msg->dst_uri.s!=0 (extra safety) */
850                 faked_req->dst_uri.s = 0;
851         }
852         /* new_uri can change -- make a private copy */
853         if (shmem_msg->new_uri.s!=0 && shmem_msg->new_uri.len!=0) {
854                 faked_req->new_uri.s=pkg_malloc(shmem_msg->new_uri.len+1);
855                 if (!faked_req->new_uri.s) {
856                         LOG(L_ERR, "ERROR: fake_req: no uri/pkg mem\n");
857                         goto error00;
858                 }
859                 faked_req->new_uri.len=shmem_msg->new_uri.len;
860                 memcpy( faked_req->new_uri.s, shmem_msg->new_uri.s,
861                         faked_req->new_uri.len);
862                 faked_req->new_uri.s[faked_req->new_uri.len]=0;
863         }else{
864                 /* in case len==0, but shmem_msg->new_uri.s!=0  (extra safety)*/
865                 faked_req->new_uri.s = 0;
866         }
867         if(uac) setbflagsval(0, uac->branch_flags);
868         else setbflagsval(0, 0);
869
870         return 1;
871 error00:
872         if (faked_req->dst_uri.s) {
873                 pkg_free(faked_req->dst_uri.s);
874                 faked_req->dst_uri.s = 0;
875         }
876 error01:
877         return 0;
878 }
879
880 void free_faked_req(struct sip_msg *faked_req, struct cell *t)
881 {
882         struct hdr_field *hdr;
883
884         if (faked_req->new_uri.s) {
885                 pkg_free(faked_req->new_uri.s);
886                 faked_req->new_uri.s = 0;
887         }
888
889         if (faked_req->dst_uri.s) {
890                 pkg_free(faked_req->dst_uri.s);
891                 faked_req->dst_uri.s = 0;
892         }
893
894         /* free all types of lump that were added in failure handlers */
895         del_nonshm_lump( &(faked_req->add_rm) );
896         del_nonshm_lump( &(faked_req->body_lumps) );
897         del_nonshm_lump_rpl( &(faked_req->reply_lump) );
898
899         /* free header's parsed structures that were added by failure handlers */
900         for( hdr=faked_req->headers ; hdr ; hdr=hdr->next ) {
901                 if ( hdr->parsed && hdr_allocs_parse(hdr) &&
902                 (hdr->parsed<(void*)t->uas.request ||
903                 hdr->parsed>=(void*)t->uas.end_request)) {
904                         /* header parsed filed doesn't point inside uas.request memory
905                          * chunck -> it was added by failure funcs.-> free it as pkg */
906                         DBG("DBG:free_faked_req: removing hdr->parsed %d\n",
907                                         hdr->type);
908                         clean_hdr_field(hdr);
909                         hdr->parsed = 0;
910                 }
911         }
912 }
913
914
915 /* return 1 if a failure_route processes */
916 int run_failure_handlers(struct cell *t, struct sip_msg *rpl,
917                                         int code, int extra_flags)
918 {
919         static struct sip_msg faked_req;
920         struct sip_msg *shmem_msg = t->uas.request;
921         int on_failure;
922
923         /* failure_route for a local UAC? */
924         if (!shmem_msg) {
925                 LOG(L_WARN,"Warning: run_failure_handlers: no UAC support (%d, %d) \n",
926                         t->on_negative, t->tmcb_hl.reg_types);
927                 return 0;
928         }
929
930         /* don't start faking anything if we don't have to */
931         if (unlikely(!t->on_negative && !has_tran_tmcbs( t, TMCB_ON_FAILURE))) {
932                 LOG(L_WARN,
933                         "Warning: run_failure_handlers: no negative handler (%d, %d)\n",
934                         t->on_negative,
935                         t->tmcb_hl.reg_types);
936                 return 1;
937         }
938
939         if (!fake_req(&faked_req, shmem_msg, extra_flags, &t->uac[picked_branch])) {
940                 LOG(L_ERR, "ERROR: run_failure_handlers: fake_req failed\n");
941                 return 0;
942         }
943         /* fake also the env. conforming to the fake msg */
944         faked_env( t, &faked_req);
945         /* DONE with faking ;-) -> run the failure handlers */
946
947         if (unlikely(has_tran_tmcbs( t, TMCB_ON_FAILURE)) ) {
948                 run_trans_callbacks( TMCB_ON_FAILURE, t, &faked_req, rpl, code);
949         }
950         if (t->on_negative) {
951                 /* avoid recursion -- if failure_route forwards, and does not
952                  * set next failure route, failure_route will not be reentered
953                  * on failure */
954                 on_failure = t->on_negative;
955                 t->on_negative=0;
956                 if (exec_pre_script_cb(&faked_req, FAILURE_CB_TYPE)>0) {
957                         /* run a reply_route action if some was marked */
958                         if (run_top_route(failure_rt.rlist[on_failure], &faked_req, 0)<0)
959                                 LOG(L_ERR, "ERROR: run_failure_handlers: Error in run_top_route\n");
960                         exec_post_script_cb(&faked_req, FAILURE_CB_TYPE);
961                 }
962         }
963
964         /* restore original environment and free the fake msg */
965         faked_env( t, 0);
966         free_faked_req(&faked_req,t);
967
968         /* if failure handler changed flag, update transaction context */
969         shmem_msg->flags = faked_req.flags;
970         return 1;
971 }
972
973
974
975 /* 401, 407, 415, 420, and 484 have priority over the other 4xx*/
976 inline static short int get_4xx_prio(unsigned char xx)
977 {
978         switch(xx){
979                 case  1:
980                 case  7:
981                 case 15:
982                 case 20:
983                 case 84:
984                         return xx;
985                         break;
986         }
987         return 100+xx;
988 }
989
990
991
992 /* returns response priority, lower number => highest prio
993  *
994  * responses                    priority val
995  *  0-99                        32000+reponse         (special)
996  *  1xx                         11000+reponse         (special)
997  *  700-999                     10000+response        (very low)
998  *  5xx                          5000+xx              (low)
999  *  4xx                          4000+xx
1000  *  3xx                          3000+xx
1001  *  6xx                          1000+xx              (high)
1002  *  2xx                          0000+xx              (highest) 
1003  */
1004 inline static short int get_prio(unsigned int resp)
1005 {
1006         int class;
1007         int xx;
1008         
1009         class=resp/100;
1010
1011         if (class<7){
1012                 xx=resp%100;
1013                 return resp_class_prio[class]+((class==4)?get_4xx_prio(xx):xx);
1014         }
1015         return 10000+resp; /* unknown response class => return very low prio */
1016 }
1017
1018
1019
1020 /* select a branch for forwarding; returns:
1021  * 0..X ... branch number
1022  * -1   ... error
1023  * -2   ... can't decide yet -- incomplete branches present
1024  */
1025 int t_pick_branch(int inc_branch, int inc_code, struct cell *t, int *res_code)
1026 {
1027         int best_b, best_s, b;
1028
1029         best_b=-1; best_s=0;
1030         for ( b=0; b<t->nr_of_outgoings ; b++ ) {
1031                 /* "fake" for the currently processed branch */
1032                 if (b==inc_branch) {
1033                         if (get_prio(inc_code)<get_prio(best_s)) {
1034                                 best_b=b;
1035                                 best_s=inc_code;
1036                         }
1037                         continue;
1038                 }
1039                 /* skip 'empty branches' */
1040                 if (!t->uac[b].request.buffer) continue;
1041                 /* there is still an unfinished UAC transaction; wait now! */
1042                 if ( t->uac[b].last_received<200 )
1043                         return -2;
1044                 /* if reply is null => t_send_branch "faked" reply, skip over it */
1045                 if ( t->uac[b].reply && 
1046                                 get_prio(t->uac[b].last_received)<get_prio(best_s) ) {
1047                         best_b =b;
1048                         best_s = t->uac[b].last_received;
1049                 }
1050         } /* find lowest branch */
1051         
1052         *res_code=best_s;
1053         return best_b;
1054 }
1055
1056 /* The same as t_pick_branch(), but allows also
1057  * blind branches to be picked up.
1058  * This function should be used only in failure_route
1059  * to check which response has been 
1060  * picked up by t_pick_branch().
1061  * returns:
1062  * 0..X ... branch number
1063  * -1   ... error
1064  * -2   ... can't decide yet -- incomplete branches present
1065  */
1066 int t_pick_branch_blind(struct cell *t, int *res_code)
1067 {
1068         int best_b, best_s, b;
1069
1070         best_b=-1; best_s=0;
1071         for ( b=0; b<t->nr_of_outgoings ; b++ ) {
1072                 /* there is still an unfinished UAC transaction; wait now! */
1073                 if ( t->uac[b].last_received<200 )
1074                         return -2;
1075                 /* if reply is null => t_send_branch "faked" reply, skip over it */
1076                 if ( t->uac[b].reply && 
1077                                 get_prio(t->uac[b].last_received)<get_prio(best_s) ) {
1078                         best_b = b;
1079                         best_s = t->uac[b].last_received;
1080                 }
1081         } /* find lowest branch */
1082         
1083         *res_code=best_s;
1084         return best_b;
1085 }
1086
1087 /* flag indicating whether it is requested
1088  * to drop the already saved replies or not */
1089 static unsigned char drop_replies;
1090
1091 /* This is the neurological point of reply processing -- called
1092  * from within a REPLY_LOCK, t_should_relay_response decides
1093  * how a reply shall be processed and how transaction state is
1094  * affected.
1095  *
1096  * Checks if the new reply (with new_code status) should be sent or not
1097  *  based on the current
1098  * transaction status.
1099  *
1100  * @param cancel_data - initialized cancel_info structure.
1101  * Returns      - branch number (0,1,...) which should be relayed
1102  *         -1 if nothing to be relayed
1103  * WARNING: cancel_data should be initialized prior to calling this function.
1104  */
1105 static enum rps t_should_relay_response( struct cell *Trans , int new_code,
1106         int branch , int *should_store, int *should_relay,
1107         struct cancel_info *cancel_data, struct sip_msg *reply )
1108 {
1109         int branch_cnt;
1110         int picked_code;
1111         int new_branch;
1112         int inv_through;
1113         int extra_flags;
1114         int i;
1115         int replies_dropped;
1116
1117         /* note: this code never lets replies to CANCEL go through;
1118            we generate always a local 200 for CANCEL; 200s are
1119            not relayed because it's not an INVITE transaction;
1120            >= 300 are not relayed because 200 was already sent
1121            out
1122         */
1123         DBG("->>>>>>>>> T_code=%d, new_code=%d\n",Trans->uas.status,new_code);
1124         inv_through=new_code>=200 && new_code<300 && is_invite(Trans);
1125         /* if final response sent out, allow only INVITE 2xx  */
1126         if ( Trans->uas.status >= 200 ) {
1127                 if (inv_through) {
1128                         DBG("DBG: t_should_relay_response: 200 INV after final sent\n");
1129                         *should_store=0;
1130                         Trans->uac[branch].last_received=new_code;
1131                         *should_relay=branch;
1132                         return RPS_PUSHED_AFTER_COMPLETION;
1133                 }
1134                 /* except the exception above, too late  messages will
1135                    be discarded */
1136                 goto discard;
1137         }
1138
1139         /* if final response received at this branch, allow only INVITE 2xx */
1140         if (Trans->uac[branch].last_received>=200
1141                         && !(inv_through && Trans->uac[branch].last_received<300)) {
1142                 /* don't report on retransmissions */
1143                 if (Trans->uac[branch].last_received==new_code) {
1144                         DBG("DEBUG: final reply retransmission\n");
1145                         goto discard;
1146                 }
1147                 /* if you FR-timed-out, faked a local 408  and 487 came or
1148                  *  faked a CANCEL on a non-replied branch don't
1149                  * report on it either */
1150                 if ((Trans->uac[branch].last_received==487) || 
1151                                 (Trans->uac[branch].last_received==408 && new_code==487)) {
1152                         DBG("DEBUG: %d came for a %d branch (ignored)\n",
1153                                         new_code, Trans->uac[branch].last_received);
1154                         goto discard;
1155                 }
1156                 /* this looks however how a very strange status rewrite attempt;
1157                  * report on it */
1158                 LOG(L_ERR, "ERROR: t_should_relay_response: status rewrite by UAS: "
1159                         "stored: %d, received: %d\n",
1160                         Trans->uac[branch].last_received, new_code );
1161                 goto discard;
1162         }
1163
1164
1165         /* no final response sent yet */
1166         /* negative replies subject to fork picking */
1167         if (new_code >=300 ) {
1168
1169                 Trans->uac[branch].last_received=new_code;
1170
1171                 /* if all_final return lowest */
1172                 picked_branch=t_pick_branch(branch,new_code, Trans, &picked_code);
1173                 if (picked_branch==-2) { /* branches open yet */
1174                         *should_store=1;
1175                         *should_relay=-1;
1176                         if (new_code>=600 && new_code<=699){
1177                                 if (!(Trans->flags & (T_6xx | T_DISABLE_6xx))){
1178                                         /* cancel only the first time we get a 6xx and only
1179                                           if the 6xx handling is not disabled */
1180                                         prepare_to_cancel(Trans, &cancel_data->cancel_bitmap, 0);
1181                                         Trans->flags|=T_6xx;
1182 #ifdef CANCEL_REASON_SUPPORT
1183                                         cancel_data->reason.cause=new_code;
1184 #endif /* CANCEL_REASON_SUPPORT */
1185                                 }
1186                         }
1187                         return RPS_STORE;
1188                 }
1189                 if (picked_branch==-1) {
1190                         LOG(L_CRIT, "ERROR: t_should_relay_response: lowest==-1\n");
1191                         goto error;
1192                 }
1193
1194                 /* no more pending branches -- try if that changes after
1195                    a callback; save branch count to be able to determine
1196                    later if new branches were initiated */
1197                 branch_cnt=Trans->nr_of_outgoings;
1198                 /* also append the current reply to the transaction to
1199                  * make it available in failure routes - a kind of "fake"
1200                  * save of the final reply per branch */
1201                 Trans->uac[branch].reply = reply;
1202                 Trans->flags&=~T_6xx; /* clear the 6xx flag , we want to 
1203                                                                  allow new branches from the failure route */
1204
1205                 drop_replies = failure_reply_mode;
1206                 replies_dropped = 0;
1207                 /* run ON_FAILURE handlers ( route and callbacks) */
1208                 if (unlikely(has_tran_tmcbs( Trans, TMCB_ON_FAILURE_RO|TMCB_ON_FAILURE)
1209                                                 || Trans->on_negative )) {
1210                         extra_flags=
1211                                 ((Trans->uac[picked_branch].request.flags & F_RB_TIMEOUT)?
1212                                                         FL_TIMEOUT:0) | 
1213                                 ((Trans->uac[picked_branch].request.flags & F_RB_REPLIED)?
1214                                                         FL_REPLIED:0);
1215                         run_failure_handlers( Trans, Trans->uac[picked_branch].reply,
1216                                                                         picked_code, extra_flags);
1217                         if (unlikely((drop_replies==3 && branch_cnt<Trans->nr_of_outgoings) ||
1218                                                          (drop_replies!=0 && drop_replies!=3))
1219                                         ) {
1220                                 /* drop all the replies that we have already saved */
1221                                 i = 0;
1222                                 if(drop_replies==2)
1223                                 {
1224                                         for(i=branch_cnt-1; i>=0; i--)
1225                                                 if(Trans->uac[i].flags&TM_UAC_FLAG_FB)
1226                                                         break;
1227                                         if(i<0) i=0;
1228                                 }
1229                                 for (; i<branch_cnt; i++) {
1230                                         if (Trans->uac[i].reply &&
1231                                         (Trans->uac[i].reply != FAKED_REPLY) &&
1232                                         (Trans->uac[i].reply->msg_flags & FL_SHM_CLONE))
1233                                                 /* we have to drop the reply which is already in shm mem */
1234                                                 sip_msg_free(Trans->uac[i].reply);
1235
1236                                         Trans->uac[i].reply = 0;
1237                                 }
1238                                 /* make sure that the selected reply is not relayed even if
1239                                 there is not any new branch added -- should not happen */
1240                                 picked_branch = -1;
1241                                 replies_dropped = 1;
1242                         }
1243                 }
1244
1245                 /* now reset it; after the failure logic, the reply may
1246                  * not be stored any more and we don't want to keep into
1247                  * transaction some broken reference */
1248                 Trans->uac[branch].reply = 0;
1249
1250                 /* look if the callback perhaps replied transaction; it also
1251                    covers the case in which a transaction is replied localy
1252                    on CANCEL -- then it would make no sense to proceed to
1253                    new branches bellow
1254                 */
1255                 if (Trans->uas.status >= 200) {
1256                         *should_store=0;
1257                         *should_relay=-1;
1258                         /* this might deserve an improvement -- if something
1259                            was already replied, it was put on wait and then,
1260                            returning RPS_COMPLETED will make t_on_reply
1261                            put it on wait again; perhaps splitting put_on_wait
1262                            from send_reply or a new RPS_ code would be healthy
1263                         */
1264                         return RPS_COMPLETED;
1265                 }
1266                 /* look if the callback/failure_route introduced new branches ... */
1267                 if (branch_cnt<Trans->nr_of_outgoings){
1268                         /* the new branches might be already "finished" => we
1269                          * must use t_pick_branch again */
1270                         new_branch=t_pick_branch((replies_dropped==0)?
1271                                                         branch :
1272                                                         -1, /* make sure we do not pick
1273                                                                 the current branch */
1274                                                 new_code,
1275                                                 Trans,
1276                                                 &picked_code);
1277
1278                         if (new_branch<0){
1279                                 if (likely(replies_dropped==0)) {
1280                                         if (new_branch==-2) { /* branches open yet */
1281                                                 *should_store=1;
1282                                                 *should_relay=-1;
1283                                                 return RPS_STORE;
1284                                         }
1285                                         /* error, use the old picked_branch */
1286                                 } else {
1287                                         if (new_branch==-2) { /* branches open yet */
1288                                                 /* we are not allowed to relay the reply */
1289                                                 *should_store=0;
1290                                                 *should_relay=-1;
1291                                                 return RPS_DISCARDED;
1292                                         } else {
1293                                                 /* There are no open branches,
1294                                                 and all the newly created branches failed
1295                                                 as well. We are not allowed to send back
1296                                                 the previously picked-up branch, thus,
1297                                                 let us reply with an error instead. */
1298                                                 goto branches_failed;
1299                                         }
1300                                 }
1301                         }else{
1302                                 /* found a new_branch */
1303                                 picked_branch=new_branch;
1304                         }
1305                 } else if (unlikely(replies_dropped)) {
1306                         /* Either the script writer did not add new branches
1307                         after calling t_drop_replies(), or tm was unable
1308                         to add the new branches to the transaction. */
1309                         goto branches_failed;
1310                 }
1311
1312                 /* really no more pending branches -- return lowest code */
1313                 *should_store=0;
1314                 *should_relay=picked_branch;
1315                 /* we dont need 'prepare_to_cancel' here -- all branches
1316                    known to have completed */
1317                 /* prepare_to_cancel( Trans, cancel_bitmap, 0 ); */
1318                 return RPS_COMPLETED;
1319         }
1320
1321         /* not >=300 ... it must be 2xx or provisional 1xx */
1322         if (new_code>=100) {
1323 #ifdef WITH_AS_SUPPORT
1324                         /* need a copy of the message for ACK generation */
1325                         *should_store = (inv_through && is_local(Trans) && 
1326                                         (Trans->uac[branch].last_received < 200) &&
1327                                         (Trans->flags & T_NO_AUTO_ACK)) ? 1 : 0;
1328 #else
1329                 *should_store=0;
1330 #endif
1331                 /* 1xx and 2xx except 100 will be relayed */
1332                 Trans->uac[branch].last_received=new_code;
1333                 *should_relay= new_code==100? -1 : branch;
1334                 if (new_code>=200 ) {
1335                         prepare_to_cancel( Trans, &cancel_data->cancel_bitmap, 0);
1336 #ifdef CANCEL_REASON_SUPPORT
1337                         cancel_data->reason.cause=new_code;
1338 #endif /* CANCEL_REASON_SUPPORT */
1339                         return RPS_COMPLETED;
1340                 } else return RPS_PROVISIONAL;
1341         }
1342
1343 error:
1344         /* reply_status didn't match -- it must be something weird */
1345         LOG(L_CRIT, "ERROR: Oh my gooosh! We don't know whether to relay %d\n",
1346                 new_code);
1347 discard:
1348         *should_store=0;
1349         *should_relay=-1;
1350         return RPS_DISCARDED;
1351
1352 branches_failed:
1353         *should_store=0;
1354         if (is_local(Trans)){
1355                 /* for local transactions use the current reply */
1356                 *should_relay=branch;
1357         }else{
1358                 *should_relay=-1;
1359                 /* We have hopefully set tm_error in failure_route when
1360                         the branches failed. If not, reply with E_UNSPEC */
1361                 if ((kill_transaction_unsafe(Trans,
1362                                 tm_error ? tm_error : E_UNSPEC)) <=0 ){
1363                         LOG(L_ERR, "ERROR: t_should_relay_response: "
1364                                                 "reply generation failed\n");
1365                 }
1366         }
1367         return RPS_COMPLETED;
1368 }
1369
1370 /* Retransmits the last sent inbound reply.
1371  * input: p_msg==request for which I want to retransmit an associated reply
1372  * Returns  -1 - error
1373  *           1 - OK
1374  */
1375 int t_retransmit_reply( struct cell *t )
1376 {
1377         static char b[BUF_SIZE];
1378         int len;
1379
1380         /* first check if we managed to resolve topmost Via -- if
1381            not yet, don't try to retransmit
1382         */
1383         /*
1384            response.dst.send_sock might be unset if the process that created
1385            the original transaction has not finished initialising the
1386            retransmission buffer (see t_newtran/ init_rb).
1387            If reply_to_via is set and via contains a host name (and not an ip)
1388            the chances for this increase a lot.
1389          */
1390         if (!t->uas.response.dst.send_sock) {
1391                 LOG(L_WARN, "WARNING: t_retransmit_reply: "
1392                         "no resolved dst to retransmit\n");
1393                 return -1;
1394         }
1395
1396         /* we need to lock the transaction as messages from
1397            upstream may change it continuously
1398         */
1399         LOCK_REPLIES( t );
1400
1401         if (!t->uas.response.buffer) {
1402                 DBG("DBG: t_retransmit_reply: nothing to retransmit\n");
1403                 goto error;
1404         }
1405
1406         len=t->uas.response.buffer_len;
1407         if ( len==0 || len>BUF_SIZE )  {
1408                 DBG("DBG: t_retransmit_reply: "
1409                         "zero length or too big to retransmit: %d\n", len);
1410                 goto error;
1411         }
1412         memcpy( b, t->uas.response.buffer, len );
1413         UNLOCK_REPLIES( t );
1414         SEND_PR_BUFFER( & t->uas.response, b, len );
1415 #ifdef TMCB_ONSEND
1416         if (unlikely(has_tran_tmcbs(t, TMCB_RESPONSE_SENT))){ 
1417                 /* we don't know if it's a retransmission of a local reply or a 
1418                  * forwarded reply */
1419                 run_onsend_callbacks(TMCB_RESPONSE_SENT, &t->uas.response, 0, 0,
1420                                                                 TMCB_RETR_F);
1421         }
1422 #endif
1423         DBG("DEBUG: reply retransmitted. buf=%p: %.9s..., shmem=%p: %.9s\n",
1424                 b, b, t->uas.response.buffer, t->uas.response.buffer );
1425         return 1;
1426
1427 error:
1428         UNLOCK_REPLIES(t);
1429         return -1;
1430 }
1431
1432
1433
1434
1435 int t_reply( struct cell *t, struct sip_msg* p_msg, unsigned int code,
1436         char * text )
1437 {
1438         return _reply( t, p_msg, code, text, 1 /* lock replies */ );
1439 }
1440
1441 int t_reply_unsafe( struct cell *t, struct sip_msg* p_msg, unsigned int code,
1442         char * text )
1443 {
1444         return _reply( t, p_msg, code, text, 0 /* don't lock replies */ );
1445 }
1446
1447
1448
1449 void set_final_timer( struct cell *t )
1450 {
1451         start_final_repl_retr(t);
1452         put_on_wait(t);
1453 }
1454
1455
1456 void cleanup_uac_timers( struct cell *t )
1457 {
1458         int i;
1459
1460         /* reset FR/retransmission timers */
1461         for (i=0; i<t->nr_of_outgoings; i++ ){
1462                 stop_rb_timers(&t->uac[i].request);
1463         }
1464         DBG("DEBUG: cleanup_uac_timers: RETR/FR timers reset\n");
1465 }
1466
1467 static int store_reply( struct cell *trans, int branch, struct sip_msg *rpl)
1468 {
1469 #               ifdef EXTRA_DEBUG
1470                 if (trans->uac[branch].reply) {
1471                         LOG(L_ERR, "ERROR: replacing stored reply; aborting\n");
1472                         abort();
1473                 }
1474 #               endif
1475
1476                 /* when we later do things such as challenge aggregation,
1477                    we should parse the message here before we conserve
1478                    it in shared memory; -jiri
1479                 */
1480                 if (rpl==FAKED_REPLY)
1481                         trans->uac[branch].reply=FAKED_REPLY;
1482                 else
1483                         trans->uac[branch].reply = sip_msg_cloner( rpl, 0 );
1484
1485                 if (! trans->uac[branch].reply ) {
1486                         LOG(L_ERR, "ERROR: store_reply: can't alloc' clone memory\n");
1487                         return 0;
1488                 }
1489
1490                 return 1;
1491 }
1492
1493
1494
1495 /* returns the number of authenticate replies (401 and 407) received so far
1496  *  (FAKED_REPLYes are excluded)
1497  *  It must be called with the REPLY_LOCK held */
1498 inline static int auth_reply_count(struct cell *t, struct sip_msg* crt_reply)
1499 {
1500         int count;
1501         int r;
1502
1503         count=0;
1504         if (crt_reply && (crt_reply!=FAKED_REPLY) && 
1505                         (crt_reply->REPLY_STATUS ==401 || crt_reply->REPLY_STATUS ==407))
1506                 count=1;
1507         for (r=0; r<t->nr_of_outgoings; r++){
1508                 if (t->uac[r].reply && (t->uac[r].reply!=FAKED_REPLY) &&
1509                                 (t->uac[r].last_received==401 || t->uac[r].last_received==407))
1510                         count++;
1511         }
1512         return count;
1513 }
1514
1515
1516
1517 /* must be called with the REPY_LOCK held */
1518 inline static char* reply_aggregate_auth(int code, char* txt, str* new_tag, 
1519                                                                         struct cell* t, unsigned int* res_len, 
1520                                                                         struct bookmark* bm)
1521 {
1522         int r;
1523         struct hdr_field* hdr;
1524         struct lump_rpl** first;
1525         struct lump_rpl** crt;
1526         struct lump_rpl* lst;
1527         struct lump_rpl*  lst_end;
1528         struct sip_msg* req;
1529         char* buf;
1530         str reason;
1531         
1532         first=0;
1533         lst_end=0;
1534         req=t->uas.request;
1535         
1536         for (r=0; r<t->nr_of_outgoings; r++){
1537                 if (t->uac[r].reply && (t->uac[r].reply!=FAKED_REPLY) &&
1538                         (t->uac[r].last_received==401 || t->uac[r].last_received==407)){
1539                         for (hdr=t->uac[r].reply->headers; hdr; hdr=hdr->next){
1540                                 if (hdr->type==HDR_WWW_AUTHENTICATE_T ||
1541                                                 hdr->type==HDR_PROXY_AUTHENTICATE_T){
1542                                         crt=add_lump_rpl2(req, hdr->name.s, hdr->len,
1543                                                         LUMP_RPL_HDR|LUMP_RPL_NODUP|LUMP_RPL_NOFREE);
1544                                         if (crt==0){
1545                                                 /* some kind of error, better stop */
1546                                                 LOG(L_ERR, "ERROR: tm:reply_aggregate_auth:"
1547                                                                         " add_lump_rpl2 failed\n");
1548                                                 goto skip;
1549                                         }
1550                                         lst_end=*crt;
1551                                         if (first==0) first=crt;
1552                                 }
1553                         }
1554                 }
1555         }
1556 skip:
1557         reason.s = txt;
1558         reason.len = strlen(txt);
1559         buf=build_res_buf_from_sip_req(code, &reason, new_tag, req, res_len, bm);
1560         /* clean the added lumps */
1561         if (first){
1562                 lst=*first;
1563                 *first=lst_end->next; /* "detach" the list of added rpl_lumps */
1564                 lst_end->next=0; /* terminate lst */
1565                 del_nonshm_lump_rpl(&lst);
1566                 if (lst){
1567                         LOG(L_CRIT, "BUG: tm: repply_aggregate_auth: rpl_lump list"
1568                                             "contains shm alloc'ed lumps\n");
1569                         abort();
1570                 }
1571         }
1572         return buf;
1573 }
1574
1575
1576
1577 /* this is the code which decides what and when shall be relayed
1578    upstream; note well -- it assumes it is entered locked with
1579    REPLY_LOCK and it returns unlocked!
1580    If do_put_on_wait==1 and this is the final reply, the transaction
1581    wait timer will be started (put_on_wait(t)).
1582  *
1583  * @param cancel_data - initialized cancel_info structure.
1584  *
1585  * WARNING: cancel_data should be initialized prior to calling this function.
1586 */
1587 enum rps relay_reply( struct cell *t, struct sip_msg *p_msg, int branch,
1588         unsigned int msg_status, struct cancel_info *cancel_data,
1589         int do_put_on_wait )
1590 {
1591         int relay;
1592         int save_clone;
1593         char *buf;
1594         /* length of outbound reply */
1595         unsigned int res_len;
1596         int relayed_code;
1597         struct sip_msg *relayed_msg;
1598         struct sip_msg *reply_bak;
1599         struct bookmark bm;
1600         int totag_retr;
1601         enum rps reply_status;
1602         /* retransmission structure of outbound reply and request */
1603         struct retr_buf *uas_rb;
1604         str* to_tag;
1605         str reason;
1606 #ifdef TMCB_ONSEND
1607         struct tmcb_params onsend_params;
1608 #endif
1609
1610         /* keep compiler warnings about use of uninit vars silent */
1611         res_len=0;
1612         buf=0;
1613         relayed_msg=0;
1614         relayed_code=0;
1615         totag_retr=0;
1616
1617
1618         /* remember, what was sent upstream to know whether we are
1619          * forwarding a first final reply or not */
1620
1621         /* *** store and relay message as needed *** */
1622         reply_status = t_should_relay_response(t, msg_status, branch,
1623                 &save_clone, &relay, cancel_data, p_msg );
1624         DBG("DEBUG: relay_reply: branch=%d, save=%d, relay=%d\n",
1625                 branch, save_clone, relay );
1626
1627         /* store the message if needed */
1628         if (save_clone) /* save for later use, typically branch picking */
1629         {
1630                 if (!store_reply( t, branch, p_msg ))
1631                         goto error01;
1632         }
1633
1634         uas_rb = & t->uas.response;
1635         if (relay >= 0 ) {
1636                 /* initialize sockets for outbound reply */
1637                 uas_rb->activ_type=msg_status;
1638                 /* only messages known to be relayed immediately will be
1639                  * be called on; we do not evoke this callback on messages
1640                  * stored in shmem -- they are fixed and one cannot change them
1641                  * anyway */
1642                 if (unlikely(msg_status<300 && branch==relay
1643                 && has_tran_tmcbs(t,TMCB_RESPONSE_FWDED)) ) {
1644                         run_trans_callbacks( TMCB_RESPONSE_FWDED, t, t->uas.request,
1645                                 p_msg, msg_status );
1646                 }
1647                 /* try building the outbound reply from either the current
1648                  * or a stored message */
1649                 relayed_msg = branch==relay ? p_msg :  t->uac[relay].reply;
1650                 if (relayed_msg==FAKED_REPLY) {
1651                         relayed_code = branch==relay
1652                                 ? msg_status : t->uac[relay].last_received;
1653                         /* use to_tag from the original request, or if not present,
1654                          * generate a new one */
1655                         if (relayed_code>=180 && t->uas.request->to
1656                                         && (get_to(t->uas.request)->tag_value.s==0
1657                                         || get_to(t->uas.request)->tag_value.len==0)) {
1658                                 calc_crc_suffix( t->uas.request, tm_tag_suffix );
1659                                 to_tag=&tm_tag;
1660                         } else {
1661                                 to_tag=0;
1662                         }
1663                         if (cfg_get(tm, tm_cfg, tm_aggregate_auth) && 
1664                                                 (relayed_code==401 || relayed_code==407) &&
1665                                                 (auth_reply_count(t, p_msg)>1)){
1666                                 /* aggregate 401 & 407 www & proxy authenticate headers in
1667                                  *  a "FAKE" reply*/
1668                                 
1669                                 /* temporarily "store" the current reply */
1670                                 reply_bak=t->uac[branch].reply;
1671                                 t->uac[branch].reply=p_msg;
1672                                 buf=reply_aggregate_auth(relayed_code, 
1673                                                 error_text(relayed_code), to_tag, t, &res_len, &bm);
1674                                 /* revert the temporary "store" reply above */
1675                                 t->uac[branch].reply=reply_bak;
1676                         }else{
1677                                 reason.s = error_text(relayed_code);
1678                                 reason.len = strlen(reason.s);
1679                                 buf = build_res_buf_from_sip_req( relayed_code,
1680                                                 &reason, to_tag,
1681                                                 t->uas.request, &res_len, &bm );
1682                         }
1683                 } else {
1684                         relayed_code=relayed_msg->REPLY_STATUS;
1685                         if (relayed_code==503){
1686                                 /* replace a final 503 with a 500:
1687                                  * generate a "FAKE" reply and a new to_tag (for easier
1688                                  *  debugging)*/
1689                                 relayed_msg=FAKED_REPLY;
1690                                 if ((get_to(t->uas.request)->tag_value.s==0 ||
1691                                          get_to(t->uas.request)->tag_value.len==0)) {
1692                                         calc_crc_suffix( t->uas.request, tm_tag_suffix );
1693                                         to_tag=&tm_tag;
1694                                 } else {
1695                                         to_tag=0;
1696                                 }
1697                                 /* don't relay a 503, replace it w/ 500 (rfc3261) */
1698                                 reason.s = error_text(relayed_code);
1699                                 reason.len = strlen(reason.s);
1700                                 buf=build_res_buf_from_sip_req(500, &reason,
1701                                                                         to_tag, t->uas.request, &res_len, &bm);
1702                                 relayed_code=500;
1703                         }else if (cfg_get(tm, tm_cfg, tm_aggregate_auth) && 
1704                                                 (relayed_code==401 || relayed_code==407) &&
1705                                                 (auth_reply_count(t, p_msg)>1)){
1706                                 /* aggregate 401 & 407 www & proxy authenticate headers in
1707                                  *  a "FAKE" reply*/
1708                                 if ((get_to(t->uas.request)->tag_value.s==0 ||
1709                                          get_to(t->uas.request)->tag_value.len==0)) {
1710                                         calc_crc_suffix( t->uas.request, tm_tag_suffix );
1711                                         to_tag=&tm_tag;
1712                                 } else {
1713                                         to_tag=0;
1714                                 }
1715                                 /* temporarily "store" the current reply */
1716                                 reply_bak=t->uac[branch].reply;
1717                                 t->uac[branch].reply=p_msg;
1718                                 buf=reply_aggregate_auth(relayed_code, 
1719                                                 error_text(relayed_code), to_tag, t, &res_len, &bm);
1720                                 /* revert the temporary "store" reply above */
1721                                 t->uac[branch].reply=reply_bak;;
1722                                 relayed_msg=FAKED_REPLY; /* mark the relayed_msg as a "FAKE" */
1723                         }else{
1724                                 buf = build_res_buf_from_sip_res( relayed_msg, &res_len );
1725                                 /* if we build a message from shmem, we need to remove
1726                                    via delete lumps which are now stirred in the shmem-ed
1727                                    structure
1728                                 */
1729                                 if (branch!=relay) {
1730                                         free_via_clen_lump(&relayed_msg->add_rm);
1731                                 }
1732                                 /* update send_flags with possible additions from the
1733                                    reply route */
1734                                 SND_FLAGS_OR(&uas_rb->dst.send_flags, &uas_rb->dst.send_flags,
1735                                                                 &relayed_msg->rpl_send_flags);
1736                         }
1737                 }
1738                 update_reply_stats( relayed_code );
1739                 if (!buf) {
1740                         LOG(L_ERR, "ERROR: relay_reply: "
1741                                 "no mem for outbound reply buffer\n");
1742                         goto error02;
1743                 }
1744
1745                 /* attempt to copy the message to UAS's shmem:
1746                    - copy to-tag for ACK matching as well
1747                    -  allocate little a bit more for provisional as
1748                       larger messages are likely to follow and we will be
1749                       able to reuse the memory frag
1750                 */
1751                 uas_rb->buffer = (char*)shm_resize( uas_rb->buffer, res_len +
1752                         (msg_status<200 ?  REPLY_OVERBUFFER_LEN : 0));
1753                 if (!uas_rb->buffer) {
1754                         LOG(L_ERR, "ERROR: relay_reply: cannot alloc reply shmem\n");
1755                         goto error03;
1756                 }
1757                 uas_rb->buffer_len = res_len;
1758                 memcpy( uas_rb->buffer, buf, res_len );
1759                 if (relayed_msg==FAKED_REPLY) { /* to-tags for local replies */
1760                         update_local_tags(t, &bm, uas_rb->buffer, buf);
1761                         t_stats_replied_locally();
1762                 }
1763                 
1764                 /* update the status ... */
1765                 t->uas.status = relayed_code;
1766                 t->relayed_reply_branch = relay;
1767
1768                 if ( unlikely(is_invite(t) && relayed_msg!=FAKED_REPLY
1769                 && relayed_code>=200 && relayed_code < 300
1770                 && has_tran_tmcbs( t,
1771                                 TMCB_RESPONSE_OUT|TMCB_RESPONSE_READY
1772                                 |TMCB_E2EACK_IN|TMCB_E2EACK_RETR_IN))) {
1773                         totag_retr=update_totag_set(t, relayed_msg);
1774                 }
1775         }; /* if relay ... */
1776
1777         UNLOCK_REPLIES( t );
1778
1779         /* send it now (from the private buffer) */
1780         if (relay >= 0) {
1781                 if (unlikely(!totag_retr && has_tran_tmcbs(t, TMCB_RESPONSE_READY))){
1782                         run_trans_callbacks(TMCB_RESPONSE_READY, t,
1783                                         t->uas.request, relayed_msg, relayed_code);
1784                 }
1785                 /* Set retransmission timer before the reply is sent out to avoid
1786                 * race conditions
1787                 *
1788                 * Call start_final_repl_retr/put_on_wait() only if we really send out
1789                 * the reply. It can happen that the reply has been already sent from
1790                 * failure_route or from a callback and the timer has been already
1791                 * started. (Miklos)
1792                 */
1793                 if (reply_status == RPS_COMPLETED) {
1794                         start_final_repl_retr(t);
1795                 }
1796                 if (likely(uas_rb->dst.send_sock &&
1797                                         SEND_PR_BUFFER( uas_rb, buf, res_len ) >= 0)){
1798                         if (unlikely(!totag_retr && has_tran_tmcbs(t, TMCB_RESPONSE_OUT))){
1799                                 run_trans_callbacks( TMCB_RESPONSE_OUT, t, t->uas.request,
1800                                         relayed_msg, relayed_code);
1801                         }
1802 #ifdef TMCB_ONSEND
1803                         if (unlikely(has_tran_tmcbs(t, TMCB_RESPONSE_SENT))){
1804                                 INIT_TMCB_ONSEND_PARAMS(onsend_params, t->uas.request,
1805                                                                         relayed_msg, uas_rb, &uas_rb->dst, buf,
1806                                                                         res_len,
1807                                                                         (relayed_msg==FAKED_REPLY)?TMCB_LOCAL_F:0,
1808                                                                         uas_rb->branch, relayed_code);
1809                                 run_onsend_callbacks2(TMCB_RESPONSE_SENT, t, &onsend_params);
1810                         }
1811 #endif
1812                 } else if (unlikely(uas_rb->dst.send_sock == 0))
1813                         ERR("no resolved dst to send reply to\n");
1814                 /* Call put_on_wait() only if we really send out
1815                 * the reply. It can happen that the reply has been already sent from
1816                 * failure_route  or from a callback and the timer has been already
1817                 * started. (Miklos)
1818                 *
1819                 * put_on_wait() should always be called after we finished dealling 
1820                 * with t, because otherwise the wait timer might fire before we
1821                 *  finish with t, and by the time we want to use t it could
1822                 *  be already deleted. This could happen only if this function is
1823                 *  called from timer (fr_timer) (the timer doesn't refcnt) and the
1824                 *  timer allows quick dels (timer_allow_del()). --andrei
1825                 */
1826                 if (do_put_on_wait && (reply_status == RPS_COMPLETED)) {
1827                         put_on_wait(t);
1828                 }
1829                 pkg_free( buf );
1830         }
1831
1832         /* success */
1833         return reply_status;
1834
1835 error03:
1836         pkg_free( buf );
1837 error02:
1838         if (save_clone) {
1839                 if (t->uac[branch].reply!=FAKED_REPLY)
1840                         sip_msg_free( t->uac[branch].reply );
1841                 t->uac[branch].reply = NULL;
1842         }
1843 error01:
1844         t_reply_unsafe( t, t->uas.request, 500, "Reply processing error" );
1845         cancel_data->cancel_bitmap=0; /* t_reply_unsafe already canceled
1846                                                                          everything needed */
1847         UNLOCK_REPLIES(t);
1848         /* if (is_invite(t)) cancel_uacs( t, *cancel_bitmap, 0); 
1849          *  -- not needed, t_reply_unsafe took care of this */
1850
1851         /* a serious error occurred -- attempt to send an error reply;
1852            it will take care of clean-ups  */
1853
1854         /* failure */
1855         return RPS_ERROR;
1856 }
1857
1858 /* this is the "UAC" above transaction layer; if a final reply
1859    is received, it triggers a callback; note well -- it assumes
1860    it is entered locked with REPLY_LOCK and it returns unlocked!
1861  *
1862  * @param cancel_data - initialized cancel_info structure.
1863  *
1864  * WARNING: cancel_data should be initialized prior to calling this function.
1865 */
1866 enum rps local_reply( struct cell *t, struct sip_msg *p_msg, int branch,
1867         unsigned int msg_status, struct cancel_info *cancel_data)
1868 {
1869         /* how to deal with replies for local transaction */
1870         int local_store, local_winner;
1871         enum rps reply_status;
1872         struct sip_msg *winning_msg;
1873         int winning_code;
1874         int totag_retr;
1875
1876         /* keep warning 'var might be used un-inited' silent */
1877         winning_msg=0;
1878         winning_code=0;
1879         totag_retr=0;
1880
1881         cancel_data->cancel_bitmap=0;
1882
1883         reply_status=t_should_relay_response( t, msg_status, branch,
1884                 &local_store, &local_winner, cancel_data, p_msg );
1885         DBG("DEBUG: local_reply: branch=%d, save=%d, winner=%d\n",
1886                 branch, local_store, local_winner );
1887         if (local_store) {
1888                 if (!store_reply(t, branch, p_msg))
1889                         goto error;
1890         }
1891         if (local_winner>=0) {
1892                 winning_msg= branch==local_winner
1893                         ? p_msg :  t->uac[local_winner].reply;
1894                 if (winning_msg==FAKED_REPLY) {
1895                         t_stats_replied_locally();
1896                         winning_code = branch==local_winner
1897                                 ? msg_status : t->uac[local_winner].last_received;
1898                 } else {
1899                         winning_code=winning_msg->REPLY_STATUS;
1900                 }
1901                 t->uas.status = winning_code;
1902                 update_reply_stats( winning_code );
1903                 if (unlikely(is_invite(t) && winning_msg!=FAKED_REPLY &&
1904                                          winning_code>=200 && winning_code <300 &&
1905                                          has_tran_tmcbs(t, TMCB_LOCAL_COMPLETED) ))  {
1906                                 totag_retr=update_totag_set(t, winning_msg);
1907                 }
1908         }
1909         UNLOCK_REPLIES(t);
1910                 
1911         if (local_winner >= 0
1912                 && cfg_get(tm, tm_cfg, pass_provisional_replies)
1913                 && winning_code < 200) {
1914                         /* no retr. detection for provisional replies &
1915                          * TMCB_LOCAL_RESPONSE_OUT */
1916                         if (unlikely(has_tran_tmcbs(t, TMCB_LOCAL_RESPONSE_OUT) )) {
1917                                 run_trans_callbacks( TMCB_LOCAL_RESPONSE_OUT, t, 0, 
1918                                                                                 winning_msg, winning_code);
1919                         }
1920         }
1921         
1922         if (local_winner>=0 && winning_code>=200 ) {
1923                 DBG("DEBUG: local transaction completed\n");
1924                 if (!totag_retr) {
1925                         if (unlikely(has_tran_tmcbs(t,TMCB_LOCAL_COMPLETED) ))
1926                                 run_trans_callbacks( TMCB_LOCAL_COMPLETED, t, 0,
1927                                         winning_msg, winning_code );
1928                 }
1929         }
1930         return reply_status;
1931
1932 error:
1933         prepare_to_cancel(t, &cancel_data->cancel_bitmap, 0);
1934         UNLOCK_REPLIES(t);
1935         cleanup_uac_timers(t);
1936         if (p_msg && p_msg!=FAKED_REPLY && get_cseq(p_msg)->method.len==INVITE_LEN
1937                 && memcmp( get_cseq(p_msg)->method.s, INVITE, INVITE_LEN)==0){
1938                 cancel_uacs( t, cancel_data, F_CANCEL_B_KILL);
1939         }
1940         cancel_data->cancel_bitmap=0; /* we've already took care of everything */
1941         put_on_wait(t);
1942         return RPS_ERROR;
1943 }
1944
1945
1946
1947
1948
1949 /*  This function is called whenever a reply for our module is received;
1950   * we need to register  this function on module initialization;
1951   *  Returns :   0 - core router stops
1952   *              1 - core router relay statelessly
1953   */
1954 int reply_received( struct sip_msg  *p_msg )
1955 {
1956
1957         int msg_status;
1958         int last_uac_status;
1959         char *ack;
1960         unsigned int ack_len;
1961         int branch;
1962         /* has the transaction completed now and we need to clean-up? */
1963         int reply_status;
1964         int onreply_route;
1965         struct cancel_info cancel_data;
1966         struct ua_client *uac;
1967         struct cell *t;
1968         struct dest_info  lack_dst;
1969         avp_list_t* backup_user_from, *backup_user_to;
1970         avp_list_t* backup_domain_from, *backup_domain_to;
1971         avp_list_t* backup_uri_from, *backup_uri_to;
1972 #ifdef WITH_XAVP
1973         sr_xavp_t **backup_xavps;
1974 #endif
1975         int replies_locked;
1976 #ifdef USE_DNS_FAILOVER
1977         int branch_ret;
1978         int prev_branch;
1979 #endif
1980 #ifdef USE_DST_BLACKLIST
1981         int blst_503_timeout;
1982         struct hdr_field* hf;
1983 #endif
1984 #ifdef TMCB_ONSEND
1985         struct tmcb_params onsend_params;
1986 #endif
1987         struct run_act_ctx ctx;
1988
1989         /* make sure we know the associated transaction ... */
1990         if (t_check( p_msg  , &branch )==-1)
1991                 goto trans_not_found;
1992         /*... if there is none, tell the core router to fwd statelessly */
1993         t=get_t();
1994         if ( (t==0)||(t==T_UNDEFINED))
1995                 goto trans_not_found;
1996
1997         if (unlikely(branch==T_BR_UNDEFINED))
1998                 BUG("invalid branch, please report to sr-dev@sip-router.org\n");
1999         tm_ctx_set_branch_index(branch);
2000         init_cancel_info(&cancel_data);
2001         msg_status=p_msg->REPLY_STATUS;
2002         replies_locked=0;
2003
2004         uac=&t->uac[branch];
2005         DBG("DEBUG: reply_received: org. status uas=%d, "
2006                 "uac[%d]=%d local=%d is_invite=%d)\n",
2007                 t->uas.status, branch, uac->last_received,
2008                 is_local(t), is_invite(t));
2009         last_uac_status=uac->last_received;
2010
2011         /* it's a cancel ... ? */
2012         if (get_cseq(p_msg)->method.len==CANCEL_LEN
2013                 && memcmp( get_cseq(p_msg)->method.s, CANCEL, CANCEL_LEN)==0
2014                 /* .. which is not e2e ? ... */
2015                 && is_invite(t) ) {
2016                         /* ... then just stop timers */
2017                         if ( msg_status >= 200 )
2018                                 stop_rb_timers(&uac->local_cancel); /* stop retr & fr */
2019                         else
2020                                 stop_rb_retr(&uac->local_cancel);  /* stop only retr */
2021                         DBG("DEBUG: reply to local CANCEL processed\n");
2022                         goto done;
2023         }
2024         
2025         onreply_route=t->on_reply;
2026         if ( msg_status >= 200 ){
2027 #ifdef TM_ONREPLY_FINAL_DROP_OK
2028 #warning Experimental tm onreply_route final reply DROP support active
2029                 if (onreply_route)
2030                         /* stop only retr., but leave the final reply timers on, in case
2031                            the final reply is dropped in the on_reply route */
2032                         stop_rb_retr(&uac->request);
2033                 else
2034 #endif /* TM_ONREPLY_FINAL_DROP_OK */
2035                         /* stop final response timer  & retr. if I got a
2036                            final response */
2037                         stop_rb_timers(&uac->request); 
2038                 /* acknowledge negative INVITE replies (do it before detailed
2039                  * on_reply processing, which may take very long, like if it
2040                  * is attempted to establish a TCP connection to a fail-over dst */
2041                 if (is_invite(t)) {
2042                         if (msg_status >= 300) {
2043                                 ack = build_ack(p_msg, t, branch, &ack_len);
2044                                 if (ack) {
2045 #ifdef  TMCB_ONSEND
2046                                         if (SEND_PR_BUFFER(&uac->request, ack, ack_len)>=0)
2047                                                 if (unlikely(has_tran_tmcbs(t, TMCB_REQUEST_SENT))){ 
2048                                                         INIT_TMCB_ONSEND_PARAMS(onsend_params, 
2049                                                                         t->uas.request, p_msg, &uac->request,
2050                                                                         &uac->request.dst, ack, ack_len,
2051                                                                         TMCB_LOCAL_F, branch, TYPE_LOCAL_ACK);
2052                                                         run_onsend_callbacks2(TMCB_REQUEST_SENT, t,
2053                                                                                                         &onsend_params);
2054                                                 }
2055 #else
2056                                         SEND_PR_BUFFER(&uac->request, ack, ack_len);
2057 #endif
2058                                         shm_free(ack);
2059                                 }
2060                         } else if (is_local(t) /*&& 200 <= msg_status < 300*/) {
2061                                 ack = build_local_ack(p_msg, t, branch, &ack_len, &lack_dst);
2062                                 if (ack) {
2063                                         if (msg_send(&lack_dst, ack, ack_len)<0)
2064                                                 LOG(L_ERR, "Error while sending local ACK\n");
2065 #ifdef  TMCB_ONSEND
2066                                         else if (unlikely(has_tran_tmcbs(t, TMCB_REQUEST_SENT))){
2067                                                         INIT_TMCB_ONSEND_PARAMS(onsend_params, 
2068                                                                         t->uas.request, p_msg, &uac->request,
2069                                                                         &lack_dst, ack, ack_len, TMCB_LOCAL_F,
2070                                                                         branch, TYPE_LOCAL_ACK);
2071                                                         run_onsend_callbacks2(TMCB_REQUEST_SENT, t,
2072                                                                                                         &onsend_params);
2073                                         }
2074 #endif
2075 #ifndef WITH_AS_SUPPORT
2076                                         shm_free(ack);
2077 #endif
2078                                 }
2079                         }
2080                 }
2081         }else{
2082                 /* if branch already canceled re-transmit or generate cancel
2083                  * TODO: check if it really makes sense to do it for non-invites too */
2084                 if (uac->request.flags & F_RB_CANCELED){
2085                         if (uac->local_cancel.buffer_len){
2086                                 membar_read(); /* make sure we get the current value of
2087                                                                   local_cancel */
2088                                 /* re-transmit if cancel already built */
2089                                 DBG("tm: reply_received: branch CANCEL retransmit\n");
2090 #ifdef TMCB_ONSEND
2091                                 if (SEND_BUFFER( &uac->local_cancel)>=0){
2092                                         if (unlikely (has_tran_tmcbs(t, TMCB_REQUEST_SENT)))
2093                                                 run_onsend_callbacks(TMCB_REQUEST_SENT,
2094                                                                                         &uac->local_cancel,
2095                                                                                         0, 0, TMCB_LOCAL_F);
2096                                 }
2097 #else
2098                                 SEND_BUFFER( &uac->local_cancel );
2099 #endif
2100                                 /* retrs. should be already started so do nothing */
2101                         }else if (atomic_cmpxchg_long((void*)&uac->local_cancel.buffer, 0,
2102                                                                                 (long)BUSY_BUFFER)==0){
2103                                 /* try to rebuild it if empty (not set or marked as BUSY).
2104                                  * if BUSY or set just exit, a cancel will be (or was) sent 
2105                                  * shortly on this branch */
2106                                 DBG("tm: reply_received: branch CANCEL created\n");
2107 #ifdef CANCEL_REASON_SUPPORT
2108                                 if (t->uas.cancel_reas) {
2109                                         /* cancel reason was saved, use it */
2110                                         cancel_branch(t, branch, t->uas.cancel_reas,
2111                                                                                                                 F_CANCEL_B_FORCE_C);
2112                                 } else {
2113                                         /* note that in this case we do not know the reason,
2114                                            we only know it's a final reply (either locally
2115                                            generated via script t_reply(), timeout, a received
2116                                            2xx or 6xx) => try to use t->uas.status as the reason*/
2117                                         cancel_data.reason.cause =
2118                                                 (t->uas.status>=200)?t->uas.status:CANCEL_REAS_UNKNOWN;
2119                                         cancel_branch(t, branch, &cancel_data.reason,
2120                                                                                                                 F_CANCEL_B_FORCE_C);
2121                                 }
2122 #else /* CANCEL_REASON_SUPPORT */
2123                                 cancel_branch(t, branch, F_CANCEL_B_FORCE_C);
2124 #endif /* CANCEL_REASON_SUPPORT */
2125                         }
2126                         goto done; /* nothing to do */
2127                 }
2128                 if (is_invite(t)){
2129                         /* stop only retr. (and not fr) */
2130                         stop_rb_retr(&uac->request);
2131                 }else{
2132                         /* non-invite: increase retransmissions interval (slow now) */
2133                         switch_rb_retr_to_t2(&uac->request);
2134                 }
2135         }
2136         /* pre-set the ignore BLST_503 flag in the message, if the
2137            corresponding branch had it set on send */
2138         p_msg->fwd_send_flags.blst_imask|=
2139                 uac->request.dst.send_flags.blst_imask & BLST_503;
2140         /* processing of on_reply block */
2141         if (onreply_route) {
2142                 set_route_type(TM_ONREPLY_ROUTE);
2143                 /* transfer transaction flag to message context */
2144                 if (t->uas.request) p_msg->flags=t->uas.request->flags;
2145                 /* set the as avp_list the one from transaction */
2146
2147                 backup_uri_from = set_avp_list(AVP_TRACK_FROM | AVP_CLASS_URI, &t->uri_avps_from );
2148                 backup_uri_to = set_avp_list(AVP_TRACK_TO | AVP_CLASS_URI, &t->uri_avps_to );
2149                 backup_user_from = set_avp_list(AVP_TRACK_FROM | AVP_CLASS_USER, &t->user_avps_from );
2150                 backup_user_to = set_avp_list(AVP_TRACK_TO | AVP_CLASS_USER, &t->user_avps_to );
2151                 backup_domain_from = set_avp_list(AVP_TRACK_FROM | AVP_CLASS_DOMAIN, &t->domain_avps_from );
2152                 backup_domain_to = set_avp_list(AVP_TRACK_TO | AVP_CLASS_DOMAIN, &t->domain_avps_to );
2153 #ifdef WITH_XAVP
2154                 backup_xavps = xavp_set_list(&t->xavps_list);
2155 #endif
2156                 setbflagsval(0, uac->branch_flags);
2157                 /* Pre- and post-script callbacks have already
2158                  * been executed by the core. (Miklos)
2159                  */
2160                 /* lock onreply_route, for safe avp usage */
2161                 LOCK_REPLIES( t );
2162                 replies_locked=1;
2163                 run_top_route(onreply_rt.rlist[onreply_route], p_msg, &ctx);
2164                 /* transfer current message context back to t */
2165                 if (t->uas.request) t->uas.request->flags=p_msg->flags;
2166                 getbflagsval(0, &uac->branch_flags);
2167
2168                 /* restore original avp list */
2169                 set_avp_list( AVP_TRACK_FROM | AVP_CLASS_URI, backup_uri_from );
2170                 set_avp_list( AVP_TRACK_TO | AVP_CLASS_URI, backup_uri_to );
2171                 set_avp_list( AVP_TRACK_FROM | AVP_CLASS_USER, backup_user_from );
2172                 set_avp_list( AVP_TRACK_TO | AVP_CLASS_USER, backup_user_to );
2173                 set_avp_list( AVP_TRACK_FROM | AVP_CLASS_DOMAIN, backup_domain_from );
2174                 set_avp_list( AVP_TRACK_TO | AVP_CLASS_DOMAIN, backup_domain_to );
2175 #ifdef WITH_XAVP
2176                 xavp_set_list(backup_xavps);
2177 #endif
2178                 /* handle a possible DROP in the script, but only if this
2179                    is not a final reply (final replies already stop the timers
2180                    and droping them might leave a transaction living forever) */
2181 #ifdef TM_ONREPLY_FINAL_DROP_OK
2182                 if (unlikely(ctx.run_flags&DROP_R_F))
2183 #else
2184                 if (unlikely((ctx.run_flags&DROP_R_F) && (msg_status<200)))
2185 #endif /* TM_ONREPLY_FINAL_DROP_OK */
2186                 {
2187                         if (likely(replies_locked)) {
2188                                 replies_locked = 0;
2189                                 UNLOCK_REPLIES( t );
2190                         }
2191                         goto done;
2192                 }
2193 #ifdef TM_ONREPLY_FINAL_DROP_OK
2194                 if (msg_status >= 200) {
2195                         /* stop final reply timers, now that we executed the onreply route
2196                            and the reply was not DROPed */
2197                         if (likely(replies_locked)){
2198                                 /* if final reply => we have to execute stop_rb_timers, but
2199                                    with replies unlocked to avoid a possible deadlock
2200                                    (if the timer is currently running, stop_rb_timers()
2201                                    will wait until the timer handler ends, but the
2202                                    final_response_handler() will try to lock replies =>
2203                                    deadlock).
2204                                 */
2205                                 UNLOCK_REPLIES( t );
2206                                 replies_locked=0;
2207                         }
2208                         stop_rb_timers(&uac->request);
2209                 }
2210 #endif /* TM_ONREPLY_FINAL_DROP_OK */
2211                 /* Re-read the status code, it can be changed in the route block. */
2212 #ifdef EXTRA_DEBUG
2213                 /* The class of provisional and positive final replies cannot be changed. */
2214                 if (((msg_status < 300) || (p_msg->REPLY_STATUS < 300))
2215                         && (msg_status/100 != p_msg->REPLY_STATUS/100)
2216                 ) {
2217                         LOG(L_ERR, "ERROR: The class of provisional and "
2218                                 "positive final replies should not be changed!\n");
2219                 }
2220 #endif /* EXTRA_DEBUG */
2221                 msg_status=p_msg->REPLY_STATUS;
2222         }
2223 #ifdef USE_DST_BLACKLIST
2224                 /* add temporary to the blacklist the source of a 503 reply */
2225                 if (    (msg_status==503) &&
2226                                 cfg_get(tm, tm_cfg, tm_blst_503) &&
2227                                 /* check if the request sent on the branch had the the
2228                                    blst 503 ignore flags set or it was set in the onreply_r*/
2229                                 should_blacklist_su(BLST_503, &p_msg->fwd_send_flags,
2230                                                                                 p_msg->rcv.proto, &p_msg->rcv.src_su)
2231                         ){
2232                         blst_503_timeout=cfg_get(tm, tm_cfg, tm_blst_503_default);
2233                         if ((parse_headers(p_msg, HDR_RETRY_AFTER_F, 0)==0) && 
2234                                 (p_msg->parsed_flag & HDR_RETRY_AFTER_F)){
2235                                 for (hf=p_msg->headers; hf; hf=hf->next)
2236                                         if (hf->type==HDR_RETRY_AFTER_T){
2237                                                 /* found */
2238                                                 blst_503_timeout=(unsigned)(unsigned long)hf->parsed;
2239                                                 blst_503_timeout=MAX_unsigned(blst_503_timeout, 
2240                                                                         cfg_get(tm, tm_cfg, tm_blst_503_min));
2241                                                 blst_503_timeout=MIN_unsigned(blst_503_timeout,
2242                                                                         cfg_get(tm, tm_cfg, tm_blst_503_max));
2243                                                 break;
2244                                         }
2245                         }
2246                         if (blst_503_timeout){
2247                                 dst_blacklist_force_su_to(BLST_503, p_msg->rcv.proto,
2248                                                                                         &p_msg->rcv.src_su, p_msg,
2249                                                                                         S_TO_TICKS(blst_503_timeout));
2250                         }
2251                 }
2252 #endif /* USE_DST_BLACKLIST */
2253 #ifdef USE_DNS_FAILOVER
2254                 /* if this is a 503 reply, and the destination resolves to more ips,
2255                  *  add another branch/uac.
2256                  *  This code is out of LOCK_REPLIES() to minimize the time the
2257                  *  reply lock is held (the lock won't be held while sending the
2258                  *   message)*/
2259                 if (cfg_get(core, core_cfg, use_dns_failover) && (msg_status==503)) {
2260                         branch_ret=add_uac_dns_fallback(t, t->uas.request,
2261                                                                                                 uac, !replies_locked);
2262                         prev_branch=-1;
2263                         /* unlock replies to avoid sending() while holding a lock */
2264                         if (unlikely(replies_locked)) {
2265                                 UNLOCK_REPLIES( t );
2266                                 replies_locked = 0;
2267                         }
2268                         while((branch_ret>=0) &&(branch_ret!=prev_branch)){
2269                                 prev_branch=branch_ret;
2270                                 branch_ret=t_send_branch(t, branch_ret, t->uas.request , 0, 1);
2271                         }
2272                 }
2273 #endif
2274         if (unlikely(!replies_locked)){
2275                 LOCK_REPLIES( t );
2276                 replies_locked=1;
2277         }
2278         if ( is_local(t) ) {
2279                 reply_status=local_reply( t, p_msg, branch, msg_status, &cancel_data );
2280                 if (reply_status == RPS_COMPLETED) {
2281                              /* no more UAC FR/RETR (if I received a 2xx, there may
2282                               * be still pending branches ...
2283                               */
2284                         cleanup_uac_timers( t );
2285                         if (is_invite(t)) cancel_uacs(t, &cancel_data, F_CANCEL_B_KILL);
2286                         /* There is no need to call set_final_timer because we know
2287                          * that the transaction is local */
2288                         put_on_wait(t);
2289                 }else if (unlikely(cancel_data.cancel_bitmap)){
2290                         /* cancel everything, even non-INVITEs (e.g in case of 6xx), use
2291                          * cancel_b_method for canceling unreplied branches */
2292                         cancel_uacs(t, &cancel_data, cfg_get(tm,tm_cfg, cancel_b_flags));
2293                 }
2294         } else {
2295                 reply_status=relay_reply( t, p_msg, branch, msg_status,
2296                                                                         &cancel_data, 1 );
2297                 if (reply_status == RPS_COMPLETED) {
2298                              /* no more UAC FR/RETR (if I received a 2xx, there may
2299                                 be still pending branches ...
2300                              */
2301                         cleanup_uac_timers( t );
2302                         /* 2xx is a special case: we can have a COMPLETED request
2303                          * with branches still open => we have to cancel them */
2304                         if (is_invite(t) && cancel_data.cancel_bitmap) 
2305                                 cancel_uacs( t, &cancel_data,  F_CANCEL_B_KILL);
2306                         /* FR for negative INVITES, WAIT anything else */
2307                         /* Call to set_final_timer is embedded in relay_reply to avoid
2308                          * race conditions when reply is sent out and an ACK to stop
2309                          * retransmissions comes before retransmission timer is set.*/
2310                 }else if (unlikely(cancel_data.cancel_bitmap)){
2311                         /* cancel everything, even non-INVITEs (e.g in case of 6xx), use
2312                          * cancel_b_method for canceling unreplied branches */
2313                         cancel_uacs(t, &cancel_data, cfg_get(tm,tm_cfg, cancel_b_flags));
2314                 }
2315         }
2316         uac->request.flags|=F_RB_REPLIED;
2317
2318         if (reply_status==RPS_ERROR)
2319                 goto done;
2320
2321         /* update FR/RETR timers on provisional replies */
2322         if (is_invite(t) && msg_status<200 &&
2323                 ( cfg_get(tm, tm_cfg, restart_fr_on_each_reply) ||
2324                                 ( (last_uac_status<msg_status) &&
2325                                         ((msg_status>=180) || (last_uac_status==0)) )
2326                         ) ) { /* provisional now */
2327                 restart_rb_fr(& uac->request, t->fr_inv_timeout);
2328                 uac->request.flags|=F_RB_FR_INV; /* mark fr_inv */
2329         } /* provisional replies */
2330
2331 done:
2332         tm_ctx_set_branch_index(0);
2333         /* we are done with the transaction, so unref it - the reference
2334          * was incremented by t_check() function -bogdan*/
2335         t_unref(p_msg);
2336         /* don't try to relay statelessly neither on success
2337        (we forwarded statefully) nor on error; on troubles,
2338            simply do nothing; that will make the other party to
2339            retransmit; hopefuly, we'll then be better off */
2340         return 0;
2341
2342 trans_not_found:
2343         /* transaction context was not found */
2344         if (goto_on_sl_reply) {
2345                 /* The script writer has a chance to decide whether to
2346                  * forward the reply or not.
2347                  * Pre- and post-script callbacks have already
2348                  * been execueted by the core. (Miklos)
2349                  */
2350                 return run_top_route(onreply_rt.rlist[goto_on_sl_reply], p_msg, 0);
2351         } else {
2352                 /* let the core forward the reply */
2353                 return 1;
2354         }
2355 }
2356
2357
2358
2359 int t_reply_with_body( struct cell *trans, unsigned int code,
2360                 str *text, str *body, str *new_header, str *to_tag )
2361 {
2362         struct lump_rpl *hdr_lump;
2363         struct lump_rpl *body_lump;
2364         str  s_to_tag;
2365         str  rpl;
2366         int  ret;
2367         struct bookmark bm;
2368
2369         if(to_tag) {
2370                 s_to_tag.s = to_tag->s;
2371                 s_to_tag.len = to_tag->len;
2372         } else {
2373                 s_to_tag.len = 0;
2374         }
2375
2376         /* mark the transaction as replied */
2377         if (code>=200) set_kr(REQ_RPLD);
2378
2379         /* add the lumps for new_header and for body (by bogdan) */
2380         if (new_header && new_header->len) {
2381                 hdr_lump = add_lump_rpl( trans->uas.request, new_header->s,
2382                                          new_header->len, LUMP_RPL_HDR );
2383                 if ( !hdr_lump ) {
2384                         LOG(L_ERR,"ERROR:tm:t_reply_with_body: cannot add hdr lump\n");
2385                         goto error;
2386                 }
2387         } else {
2388                 hdr_lump = 0;
2389         }
2390
2391         /* body lump */
2392         if(body && body->len) {
2393                 body_lump = add_lump_rpl( trans->uas.request, body->s, body->len,
2394                         LUMP_RPL_BODY );
2395                 if (body_lump==0) {
2396                         LOG(L_ERR,"ERROR:tm:t_reply_with_body: cannot add body lump\n");
2397                         goto error_1;
2398                 }
2399         } else {
2400                 body_lump = 0;
2401         }
2402
2403         rpl.s = build_res_buf_from_sip_req(
2404                         code, text, &s_to_tag,
2405                         trans->uas.request, (unsigned int*)&rpl.len, &bm);
2406
2407         /* since the msg (trans->uas.request) is a clone into shm memory, to avoid
2408          * memory leak or crashing (lumps are create in private memory) I will
2409          * remove the lumps by myself here (bogdan) */
2410         if ( hdr_lump ) {
2411                 unlink_lump_rpl( trans->uas.request, hdr_lump);
2412                 free_lump_rpl( hdr_lump );
2413         }
2414         if( body_lump ) {
2415                 unlink_lump_rpl( trans->uas.request, body_lump);
2416                 free_lump_rpl( body_lump );
2417         }
2418
2419         if (rpl.s==0) {
2420                 LOG(L_ERR,"ERROR:tm:t_reply_with_body: failed in doing "
2421                         "build_res_buf_from_sip_req()\n");
2422                 goto error;
2423         }
2424
2425         DBG("t_reply_with_body: buffer computed\n");
2426         // frees 'res.s' ... no panic !
2427         ret=_reply_light( trans, rpl.s, rpl.len, code,
2428                 s_to_tag.s, s_to_tag.len, 1 /* lock replies */, &bm );
2429         /* this is ugly hack -- the function caller may wish to continue with
2430          * transaction and I unref; however, there is now only one use from
2431          * vm/fifo_vm_reply and I'm currently to lazy to export UNREF; -jiri
2432          */
2433         UNREF(trans);
2434
2435         return ret;
2436 error_1:
2437         if ( hdr_lump ) {
2438                 unlink_lump_rpl( trans->uas.request, hdr_lump);
2439                 free_lump_rpl( hdr_lump );
2440         }
2441 error:
2442         return -1;
2443 }
2444
2445 /* drops all the replies to make sure
2446  * that none of them is picked up again
2447  */
2448 void t_drop_replies(int v)
2449 {
2450         /* It is too risky to free the replies that are in shm mem
2451         at the middle of failure_route block, because other functions might
2452         need them as well. And it can also happen that the current reply is not yet
2453         in shm mem, we are just going to clone it. So better to set a flag
2454         and check it after failure_route has ended. (Miklos) */
2455         drop_replies = v;
2456 }
2457
2458 #if 0
2459 static int send_reply(struct cell *trans, unsigned int code, str* text, str* body, str* headers, str* to_tag)
2460 {
2461         struct lump_rpl *hdr_lump, *body_lump;
2462         str rpl;
2463         int ret;
2464         struct bookmark bm;
2465
2466              /* mark the transaction as replied */
2467         if (code >= 200) set_kr(REQ_RPLD);
2468
2469              /* add the lumps for new_header and for body (by bogdan) */
2470         if (headers && headers->len) {
2471                 hdr_lump = add_lump_rpl(trans->uas.request, headers->s, headers->len, LUMP_RPL_HDR);
2472                 if (!hdr_lump) {
2473                         LOG(L_ERR, "send_reply: cannot add hdr lump\n");
2474                         goto sr_error;
2475                 }
2476         } else {
2477                 hdr_lump = 0;
2478         }
2479
2480              /* body lump */
2481         if (body && body->len) {
2482                 body_lump = add_lump_rpl(trans->uas.request, body->s, body->len, LUMP_RPL_BODY);
2483                 if (body_lump == 0) {
2484                         LOG(L_ERR,"send_reply: cannot add body lump\n");
2485                         goto sr_error_1;
2486                 }
2487         } else {
2488                 body_lump = 0;
2489         }
2490
2491              /* We can safely zero-terminate the text here, because it is followed
2492               * by next line in the received message
2493               */
2494         text->s[text->len] = '\0';
2495         rpl.s = build_res_buf_from_sip_req(code, text->s, to_tag, trans->uas.request, (unsigned int*)&rpl.len, &bm);
2496
2497              /* since the msg (trans->uas.request) is a clone into shm memory, to avoid
2498               * memory leak or crashing (lumps are create in private memory) I will
2499               * remove the lumps by myself here (bogdan) */
2500         if (hdr_lump) {
2501                 unlink_lump_rpl(trans->uas.request, hdr_lump);
2502                 free_lump_rpl(hdr_lump);
2503         }
2504         if (body_lump) {
2505                 unlink_lump_rpl(trans->uas.request, body_lump);
2506                 free_lump_rpl(body_lump);
2507         }
2508
2509         if (rpl.s == 0) {
2510                 LOG(L_ERR,"send_reply: failed in build_res_buf_from_sip_req\n");
2511                 goto sr_error;
2512         }
2513
2514         ret = _reply_light(trans, rpl.s, rpl.len, code,  to_tag->s, to_tag->len,
2515                         1 /* lock replies */, &bm);
2516              /* this is ugly hack -- the function caller may wish to continue with
2517               * transaction and I unref; however, there is now only one use from
2518               * vm/fifo_vm_reply and I'm currently to lazy to export UNREF; -jiri
2519               */
2520         UNREF(trans);
2521         return ret;
2522  sr_error_1:
2523         if (hdr_lump) {
2524                 unlink_lump_rpl(trans->uas.request, hdr_lump);
2525                 free_lump_rpl(hdr_lump);
2526         }
2527  sr_error:
2528         return -1;
2529 }
2530 #endif
2531
2532
2533 /*
2534   Syntax:
2535
2536   ":tm.reply:[response file]\n
2537   code\n
2538   reason\n
2539   trans_id\n
2540   to_tag\n
2541   [new headers]\n
2542   \n
2543   [Body]\n
2544   .\n
2545   \n"
2546  */
2547 void rpc_reply(rpc_t* rpc, void* c)
2548 {
2549         int ret;
2550         struct cell *trans;
2551         unsigned int hash_index, label, code;
2552         str ti, body, headers, tag, reason;
2553
2554         if (rpc->scan(c, "d", &code) < 1) {
2555                 rpc->fault(c, 400, "Reply code expected");
2556                 return;
2557         }
2558
2559         if (rpc->scan(c, "S", &reason) < 1) {
2560                 rpc->fault(c, 400, "Reason phrase expected");
2561                 return;
2562         }
2563
2564         if (rpc->scan(c, "S", &ti) < 1) {
2565                 rpc->fault(c, 400, "Transaction ID expected");
2566                 return;
2567         }
2568
2569         if (rpc->scan(c, "S", &tag) < 1) {
2570                 rpc->fault(c, 400, "To tag expected");
2571                 return;
2572         }
2573
2574         if (rpc->scan(c, "S", &headers) < 0) return;
2575         if (rpc->scan(c, "S", &body) < 0) return;
2576
2577         if(sscanf(ti.s,"%u:%u", &hash_index, &label) != 2) {
2578                 ERR("Invalid trans_id (%s)\n", ti.s);
2579                 rpc->fault(c, 400, "Invalid transaction ID");
2580                 return;
2581         }
2582         DBG("hash_index=%u label=%u\n", hash_index, label);
2583
2584         if( t_lookup_ident(&trans, hash_index, label) < 0 ) {
2585                 ERR("Lookup failed\n");
2586                 rpc->fault(c, 481, "No such transaction");
2587                 return;
2588         }
2589
2590         /* it's refcounted now, t_reply_with body unrefs for me -- I can
2591          * continue but may not use T anymore  */
2592         ret = t_reply_with_body(trans, code, &reason, &body, &headers, &tag);
2593
2594         if (ret < 0) {
2595                 ERR("Reply failed\n");
2596                 rpc->fault(c, 500, "Reply failed");
2597                 return;
2598         }
2599 }