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