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