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