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