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