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