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