Merge branch 'master' into treimann/master_tm-extend-callbacks
[sip-router] / modules / tm / t_fwd.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 /*
29  * History:
30  * -------
31  *  2003-02-13  proto support added (andrei)
32  *  2003-02-24  s/T_NULL/T_NULL_CELL/ to avoid redefinition conflict w/
33  *              nameser_compat.h (andrei)
34  *  2003-03-01  kr set through a function now (jiri)
35  *  2003-03-06  callbacks renamed; "blind UAC" introduced, which makes
36  *              transaction behave as if it was forwarded even if it was
37  *              not -- good for local UAS, like VM (jiri)
38  *  2003-03-19  replaced all the mallocs/frees w/ pkg_malloc/pkg_free (andrei)
39  *  2003-03-30  we now watch downstream delivery and if it fails, send an
40  *              error message upstream (jiri)
41  *  2003-04-14  use protocol from uri (jiri)
42  *  2003-12-04  global TM callbacks switched to per transaction callbacks
43  *              (bogdan)
44  *  2004-02-13: t->is_invite and t->local replaced with flags (bogdan)
45  *  2005-08-04  msg->parsed_uri and parsed_uri_ok are no saved & restored
46  *               before & after handling the branches (andrei)
47  *  2005-12-11  onsend_route support added for forwarding (andrei)
48  *  2006-01-27  t_forward_no_ack will return error if a forward on an 
49  *              already canceled transaction is attempted (andrei)
50  *  2006-02-07  named routes support (andrei)
51  *  2006-04-18  add_uac simplified + switched to struct dest_info (andrei)
52  *  2006-04-20  pint_uac_request uses now struct dest_info (andrei)
53  *  2006-08-11  dns failover support (andrei)
54  *              t_forward_non_ack won't start retransmission on send errors
55  *               anymore (WARNING: callers should release/kill the transaction
56  *               if error is returned) (andrei)
57  *  2006-09-15  e2e_cancel uses t_reply_unsafe when called from the 
58  *               failure_route and replying to a cancel (andrei)
59  *  2006-10-10  e2e_cancel update for the new/modified 
60  *               which_cancel()/should_cancel() (andrei)
61  *  2006-10-11  don't fork a new branch if the transaction or branch was
62  *               canceled, or a 6xx was received
63  *              stop retr. timers fix on cancel for non-invites     (andrei)
64  *  2006-11-20  new_uri is no longer saved/restore across add_uac calls, since
65  *              print_uac_request is now uri safe (andrei)
66  *  2007-03-15  TMCB_ONSEND hooks added (andrei)
67  *  2007-05-02  added t_forward_cancel(unmatched_cancel) (andrei)
68  *  2007-05-24  added TMCB_E2ECANCEL_IN hook support (andrei)
69  *  2007-05-28: e2e_cancel_branch() constructs the CANCEL from the
70  *              outgoing INVITE instead of applying the lumps to the
71  *              incomming one. (it can be disabled with reparse_invite=0) (Miklos)
72  *              t_relay_cancel() introduced -- can be used to relay CANCELs
73  *              at the beginning of the script. (Miklos)
74  * 2007-06-04  running transaction are canceled hop by hop (andrei)
75  * 2007-08-37  In case of DNS failover the new SIP message is constructed
76  *              from the message buffer of the failed branch instead of
77  *              applying the lumps again, because the per-branch lumps are no
78  *              t saved, thus, are not available. Set reparse_on_dns_failover
79  *              to 0 to revert the change. (Miklos)
80  * 2008-06-04  T_CANCELED is now set each time a CANCEL is received (andrei)
81  * 2009-06-01  Pre- and post-script callbacks of branch route are 
82  *             executed (Miklos)
83  * 2009-10-26  support for changing dst_uri in branch routes,
84  *             s/print_uac_request/prepare_new_uac/ (andrei)
85  * 2009-10-28  support for changing r-uris and path in branch routes; more of
86  *             add_uac() functionality moved into prepare_new_uac()  (andrei)
87  */
88
89 #include "defs.h"
90
91
92 #include "../../dprint.h"
93 #include "../../config.h"
94 #include "../../parser/parser_f.h"
95 #include "../../ut.h"
96 #include "../../timer.h"
97 #include "../../hash_func.h"
98 #include "../../globals.h"
99 #include "../../cfg_core.h"
100 #include "../../mem/mem.h"
101 #include "../../dset.h"
102 #include "../../action.h"
103 #include "../../data_lump.h"
104 #include "../../onsend.h"
105 #include "../../compiler_opt.h"
106 #include "../../route.h"
107 #include "../../script_cb.h"
108 #include "t_funcs.h"
109 #include "t_hooks.h"
110 #include "t_msgbuilder.h"
111 #include "ut.h"
112 #include "t_cancel.h"
113 #include "t_lookup.h"
114 #include "t_fwd.h"
115 #include "../../fix_lumps.h"
116 #include "config.h"
117 #ifdef USE_DNS_FAILOVER
118 #include "../../dns_cache.h"
119 #include "../../cfg_core.h" /* cfg_get(core, core_cfg, use_dns_failover) */
120 #include "../../msg_translator.h"
121 #include "lw_parser.h"
122 #endif
123 #ifdef USE_DST_BLACKLIST
124 #include "../../dst_blacklist.h"
125 #endif
126 #include "../../atomic_ops.h" /* membar_depends() */
127
128
129 static int goto_on_branch = 0, branch_route = 0;
130
131 void t_on_branch( unsigned int go_to )
132 {
133         struct cell *t = get_t();
134
135        /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
136         * in REQUEST_ROUTE T will be set only if the transaction was already
137         * created; if not -> use the static variable */
138         if (!t || t==T_UNDEFINED ) {
139                 goto_on_branch=go_to;
140         } else {
141                 get_t()->on_branch = go_to;
142         }
143 }
144
145 unsigned int get_on_branch(void)
146 {
147         return goto_on_branch;
148 }
149
150
151
152 /* prepare_new_uac flags */
153 #define UAC_DNS_FAILOVER_F 1 /**< new branch due to dns failover */
154 #define UAC_SKIP_BR_DST_F  2 /**< don't set next hop as dst_uri for
155                                                            branch_route */
156
157
158 /** prepares a new branch "buffer".
159  * Creates the buffer used in the branch rb, fills everything needed (
160    the sending information: t->uac[branch].request.dst, branch buffer, uri
161    path vector a.s.o.) and runs the on_branch route.
162  * t->uac[branch].request.dst will be filled if next_hop !=0 with the result
163  * of the DNS resolution (next_hop, fproto and fsocket).
164  * If next_hop is 0 all the dst members except the send_flags are read-only
165  * (send_flags it's updated) and are supposed to be pre-filled.
166  *
167  * @param t  - transaction
168  * @param i_req - corresponding sip_msg, must be non-null, flags might be
169  *                be modified (on_branch route)
170  * @param branch - branch no
171  * @param uri
172  * @param path  - path vector (list of route like destination in text form,
173  *                 e.g.: "<sip:1.2.3.4;lr>, <sip:5.6.7.8;lr>")
174  * @param next_hop - uri of the next hop. If non 0 it will be used
175  *              for DNS resolution and the branch request.dst structure will
176  *              be filled. If 0 the branch must already have
177  *              a pre-filled valid request.dst.
178  * @param fsocket - forced send socket for forwarding.
179  * @param send_flags - special flags for sending (see SND_F_* / snd_flags_t).
180  * @param fproto - forced proto for forwarding. Used only if next_hop!=0.
181  * @param flags - 0, UAC_DNS_FAILOVER_F or UAC_SKIP_BR_DST_F for now.
182  *
183  * @return  0 on success, < 0 (ser_errror E***) on failure.
184  */
185 static int prepare_new_uac( struct cell *t, struct sip_msg *i_req,
186                                                                         int branch, str *uri, str* path,
187                                                                         str* next_hop,
188                                                                         struct socket_info* fsocket,
189                                                                         snd_flags_t snd_flags,
190                                                                         int fproto, int flags)
191 {
192         char *shbuf;
193         struct lump* add_rm_backup, *body_lumps_backup;
194         struct sip_uri parsed_uri_bak;
195         int ret;
196         unsigned int len;
197         int parsed_uri_ok_bak, free_new_uri;
198         str msg_uri_bak;
199         str dst_uri_bak;
200         int dst_uri_backed_up;
201         str path_bak;
202         int free_path;
203         int backup_route_type;
204         snd_flags_t fwd_snd_flags_bak;
205         snd_flags_t rpl_snd_flags_bak;
206         struct socket_info *force_send_socket_bak;
207         struct dest_info *dst;
208         struct run_act_ctx ctx;
209
210         shbuf=0;
211         ret=E_UNSPEC;
212         msg_uri_bak.s=0; /* kill warnings */
213         msg_uri_bak.len=0;
214         parsed_uri_ok_bak=0;
215         free_new_uri=0;
216         dst_uri_bak.s=0;
217         dst_uri_bak.len=0;
218         dst_uri_backed_up=0;
219         path_bak.s=0;
220         path_bak.len=0;
221         free_path=0;
222         dst=&t->uac[branch].request.dst;
223
224         /* ... we calculate branch ... */       
225         if (!t_calc_branch(t, branch, i_req->add_to_branch_s,
226                         &i_req->add_to_branch_len ))
227         {
228                 LOG(L_ERR, "ERROR: print_uac_request: branch computation failed\n");
229                 ret=E_UNSPEC;
230                 goto error00;
231         }
232
233         /* dup lumps
234          * TODO: clone lumps only if needed */
235         /* lumps can be set outside of the lock, make sure that we read
236          * the up-to-date values */
237         membar_depends();
238         add_rm_backup = i_req->add_rm;
239         body_lumps_backup = i_req->body_lumps;
240         if (unlikely(i_req->add_rm)){
241                 i_req->add_rm = dup_lump_list(i_req->add_rm);
242                 if (unlikely(i_req->add_rm==0)){
243                         ret=E_OUT_OF_MEM;
244                         goto error04;
245                 }
246         }
247         if (unlikely(i_req->body_lumps)){
248                 i_req->body_lumps = dup_lump_list(i_req->body_lumps);
249                 if (unlikely(i_req->body_lumps==0)){
250                         ret=E_OUT_OF_MEM;
251                         goto error04;
252                 }
253         }
254         /* backup uri & path: we need to change them so that build_req...()
255            will use uri & path and not the ones in the original msg (i_req)
256            => we must back them up so that we can restore them to the original
257            value after building the send buffer */
258         msg_uri_bak=i_req->new_uri;
259         parsed_uri_bak=i_req->parsed_uri;
260         parsed_uri_ok_bak=i_req->parsed_uri_ok;
261         path_bak=i_req->path_vec;
262         
263         if (unlikely(branch_route || has_tran_tmcbs(t, TMCB_REQUEST_FWDED))){
264                 /* dup uris, path a.s.o. if we have a branch route or callback */
265                 /* ... set ruri ... */
266                 /* if uri points to new_uri, it needs to be "fixed" so that we can
267                    change msg->new_uri */
268                 if (uri==&i_req->new_uri)
269                         uri=&msg_uri_bak;
270                 i_req->parsed_uri_ok=0;
271                 i_req->new_uri.s=pkg_malloc(uri->len);
272                 if (unlikely(i_req->new_uri.s==0)){
273                         ret=E_OUT_OF_MEM;
274                         goto error03;
275                 }
276                 free_new_uri=1;
277                 memcpy(i_req->new_uri.s, uri->s, uri->len);
278                 i_req->new_uri.len=uri->len;
279         
280                 /* update path_vec */
281                 /* if path points to msg path_vec, it needs to be "fixed" so that we 
282                    can change/update msg->path_vec */
283                 if (path==&i_req->path_vec)
284                         path=&path_bak;
285                 /* zero it first so that set_path_vector will work */
286                 i_req->path_vec.s=0;
287                 i_req->path_vec.len=0;
288                 if (unlikely(path)){
289                         if (unlikely(set_path_vector(i_req, path)<0)){
290                                 ret=E_OUT_OF_MEM;
291                                 goto error03;
292                         }
293                         free_path=1;
294                 }
295         
296                 /* backup dst uri  & zero it*/
297                 dst_uri_bak=i_req->dst_uri;
298                 dst_uri_backed_up=1;
299                 /* if next_hop points to dst_uri, it needs to be "fixed" so that we
300                    can change msg->dst_uri */
301                 if (next_hop==&i_req->dst_uri)
302                         next_hop=&dst_uri_bak;
303                 /* zero it first so that set_dst_uri will work */
304                 i_req->dst_uri.s=0;
305                 i_req->dst_uri.len=0;
306                 if (likely(next_hop)){
307                         if(unlikely((flags & UAC_SKIP_BR_DST_F)==0)){
308                                 /* set dst uri to next_hop for the on_branch route */
309                                 if (unlikely(set_dst_uri(i_req, next_hop)<0)){
310                                         ret=E_OUT_OF_MEM;
311                                         goto error03;
312                                 }
313                         }
314                 }
315
316                 if (likely(branch_route)) {
317                         /* run branch_route actions if provided */
318                         backup_route_type = get_route_type();
319                         set_route_type(BRANCH_ROUTE);
320                         tm_ctx_set_branch_index(branch+1);
321                         /* no need to backup/set avp lists: the on_branch route is run
322                            only in the main route context (e.g. t_relay() in the main
323                            route) or in the failure route context (e.g. append_branch &
324                            t_relay()) and in both cases the avp lists are properly set
325                            Note: the branch route is not run on delayed dns failover 
326                            (for that to work one would have to set branch_route prior to
327                            calling add_uac(...) and then reset it afterwards).
328                            (
329                          */
330                         if (exec_pre_script_cb(i_req, BRANCH_CB_TYPE)>0) {
331                                 /* backup ireq msg send flags and force_send_socket*/
332                                 fwd_snd_flags_bak=i_req->fwd_send_flags;;
333                                 rpl_snd_flags_bak=i_req->rpl_send_flags;
334                                 force_send_socket_bak=i_req->force_send_socket;
335                                 /* set the new values */
336                                 i_req->fwd_send_flags=snd_flags /* intial value  */;
337                                 set_force_socket(i_req, fsocket);
338                                 if (run_top_route(branch_rt.rlist[branch_route], i_req, &ctx)
339                                                 < 0)
340                                 {
341                                         LOG(L_ERR, "Error in run_top_route\n");
342                                 }
343                                 /* update dst send_flags  and send socket*/
344                                 snd_flags=i_req->fwd_send_flags;
345                                 fsocket=i_req->force_send_socket;
346                                 /* restore ireq_msg force_send_socket & flags */
347                                 set_force_socket(i_req, force_send_socket_bak);
348                                 i_req->fwd_send_flags=fwd_snd_flags_bak;
349                                 i_req->rpl_send_flags=rpl_snd_flags_bak;
350                                 exec_post_script_cb(i_req, BRANCH_CB_TYPE);
351                                 /* if DROP was called in cfg, don't forward, jump to end */
352                                 if (unlikely(ctx.run_flags&DROP_R_F))
353                                 {
354                                         tm_ctx_set_branch_index(0);
355                                         set_route_type(backup_route_type);
356                                         /* triggered by drop in CFG */
357                                         ret=E_CFG;
358                                         goto error03;
359                                 }
360                         }
361                         tm_ctx_set_branch_index(0);
362                         set_route_type(backup_route_type);
363                 }
364
365                 /* run the specific callbacks for this transaction */
366                 if (unlikely(has_tran_tmcbs(t, TMCB_REQUEST_FWDED)))
367                         run_trans_callbacks( TMCB_REQUEST_FWDED , t, i_req, 0,
368                                                                         -i_req->REQ_METHOD);
369                 
370                 if (likely( !(flags & UAC_DNS_FAILOVER_F) && i_req->dst_uri.s &&
371                                         i_req->dst_uri.len)){
372                         /* no dns failover and non-empty dst_uri => use it as dst
373                           (on dns failover dns_h will be non-empty => next_hop will be
374                            ignored) */
375                         next_hop=&i_req->dst_uri;
376                 }
377                 /* no path vector initially, but now is set after branch route and
378                  * callbacks execution */
379                 if(i_req->path_vec.s!=0 && free_path==0)
380                         free_path=1;
381         }else{
382                 /* no branch route and no TMCB_REQUEST_FWDED callback => set
383                    msg uri and path to the new values (if needed) */
384                 if (unlikely((uri->s!=i_req->new_uri.s || uri->len!=i_req->new_uri.len)
385                                         && (i_req->new_uri.s!=0 ||
386                                                 uri->s!=i_req->first_line.u.request.uri.s ||
387                                                 uri->len!=i_req->first_line.u.request.uri.len) )){
388                         /* uri is different from i_req uri => replace i_req uri and force
389                            uri re-parsing */
390                         i_req->new_uri=*uri;
391                         i_req->parsed_uri_ok=0;
392                 }
393                 if (unlikely(path && (i_req->path_vec.s!=path->s ||
394                                                           i_req->path_vec.len!=path->len))){
395                         i_req->path_vec=*path;
396                 }else if (unlikely(path==0 && i_req->path_vec.len!=0)){
397                         i_req->path_vec.s=0;
398                         i_req->path_vec.len=0;
399                 }
400         }
401         
402         if (likely(next_hop!=0 || (flags & UAC_DNS_FAILOVER_F))){
403                 /* next_hop present => use it for dns resolution */
404 #ifdef USE_DNS_FAILOVER
405                 if (uri2dst2(&t->uac[branch].dns_h, dst, fsocket, snd_flags,
406                                                         next_hop?next_hop:uri, fproto) == 0)
407 #else
408                 /* dst filled from the uri & request (send_socket) */
409                 if (uri2dst2(dst, fsocket, snd_flags,
410                                                         next_hop?next_hop:uri, fproto)==0)
411 #endif
412                 {
413                         ret=E_BAD_ADDRESS;
414                         goto error01;
415                 }
416         } /* else next_hop==0 =>
417                 no dst_uri / empty dst_uri and initial next_hop==0 =>
418                 dst is pre-filled with a valid dst => use the pre-filled dst */
419         
420         /* check if send_sock is ok */
421         if (t->uac[branch].request.dst.send_sock==0) {
422                 LOG(L_ERR, "ERROR: can't fwd to af %d, proto %d "
423                         " (no corresponding listening socket)\n",
424                         dst->to.s.sa_family, dst->proto );
425                 ret=E_NO_SOCKET;
426                 goto error01;
427         }
428         /* ... and build it now */
429         shbuf=build_req_buf_from_sip_req( i_req, &len, dst, BUILD_IN_SHM);
430         if (!shbuf) {
431                 LOG(L_ERR, "ERROR: print_uac_request: no shm mem\n"); 
432                 ret=E_OUT_OF_MEM;
433                 goto error01;
434         }
435 #ifdef DBG_MSG_QA
436         if (shbuf[len-1]==0) {
437                 LOG(L_ERR, "ERROR: print_uac_request: sanity check failed\n");
438                 abort();
439         }
440 #endif
441         /* things went well, move ahead and install new buffer! */
442         t->uac[branch].request.buffer=shbuf;
443         t->uac[branch].request.buffer_len=len;
444         t->uac[branch].uri.s=t->uac[branch].request.buffer+
445                                                         i_req->first_line.u.request.method.len+1;
446         t->uac[branch].uri.len=GET_RURI(i_req)->len;
447         if (unlikely(i_req->path_vec.s && i_req->path_vec.len)){
448                 t->uac[branch].path.s=shm_malloc(i_req->path_vec.len+1);
449                 if (unlikely(t->uac[branch].path.s==0)) {
450                         shm_free(shbuf);
451                         t->uac[branch].request.buffer=0;
452                         t->uac[branch].request.buffer_len=0;
453                         t->uac[branch].uri.s=0;
454                         t->uac[branch].uri.len=0;
455                         ret=E_OUT_OF_MEM;
456                         goto error01;
457                 }
458                 t->uac[branch].path.len=i_req->path_vec.len;
459                 t->uac[branch].path.s[i_req->path_vec.len]=0;
460                 memcpy( t->uac[branch].path.s, i_req->path_vec.s, i_req->path_vec.len);
461         }
462         ret=0;
463
464 error01:
465 error03:
466         /* restore the new_uri & path from the backup */
467         if (unlikely(free_new_uri && i_req->new_uri.s)){
468                         pkg_free(i_req->new_uri.s);
469         }
470         if (unlikely(free_path)){
471                 reset_path_vector(i_req);
472         }
473         if (dst_uri_backed_up){
474                 reset_dst_uri(i_req); /* free dst_uri */
475                 i_req->dst_uri=dst_uri_bak;
476         }
477         /* restore original new_uri and path values */
478         i_req->new_uri=msg_uri_bak;
479         i_req->parsed_uri=parsed_uri_bak;
480         i_req->parsed_uri_ok=parsed_uri_ok_bak;
481         i_req->path_vec=path_bak;
482         
483         /* Delete the duplicated lump lists, this will also delete
484          * all lumps created here, such as lumps created in per-branch
485          * routing sections, Via, and Content-Length headers created in
486          * build_req_buf_from_sip_req
487          */
488 error04:
489         free_duped_lump_list(i_req->add_rm);
490         free_duped_lump_list(i_req->body_lumps);
491              /* Restore the lists from backups */
492         i_req->add_rm = add_rm_backup;
493         i_req->body_lumps = body_lumps_backup;
494
495 error00:
496         return ret;
497 }
498
499 #ifdef USE_DNS_FAILOVER
500 /* Similar to print_uac_request(), but this function uses the outgoing message
501    buffer of the failed branch to construct the new message in case of DNS 
502    failover.
503
504    WARNING: only the first VIA header is replaced in the buffer, the rest
505    of the message is untouched, thus, the send socket is corrected only in the
506    VIA HF.
507 */
508 static char *print_uac_request_from_buf( struct cell *t, struct sip_msg *i_req,
509         int branch, str *uri, unsigned int *len, struct dest_info* dst,
510         char *buf, short buf_len)
511 {
512         char *shbuf;
513         str branch_str;
514         char *via, *old_via_begin, *old_via_end;
515         unsigned int via_len;
516
517         shbuf=0;
518
519         /* ... we calculate branch ... */       
520         if (!t_calc_branch(t, branch, i_req->add_to_branch_s,
521                         &i_req->add_to_branch_len ))
522         {
523                 LOG(L_ERR, "ERROR: print_uac_request_from_buf: branch computation failed\n");
524                 goto error00;
525         }
526         branch_str.s = i_req->add_to_branch_s;
527         branch_str.len = i_req->add_to_branch_len;
528
529         /* find the beginning of the first via header in the buffer */
530         old_via_begin = lw_find_via(buf, buf+buf_len);
531         if (!old_via_begin) {
532                 LOG(L_ERR, "ERROR: print_uac_request_from_buf: beginning of via header not found\n");
533                 goto error00;
534         }
535         /* find the end of the first via header in the buffer */
536         old_via_end = lw_next_line(old_via_begin, buf+buf_len);
537         if (!old_via_end) {
538                 LOG(L_ERR, "ERROR: print_uac_request_from_buf: end of via header not found\n");
539                 goto error00;
540         }
541
542         /* create the new VIA HF */
543         via = create_via_hf(&via_len, i_req, dst, &branch_str);
544         if (!via) {
545                 LOG(L_ERR, "ERROR: print_uac_request_from_buf: via building failed\n");
546                 goto error00;
547         }
548
549         /* allocate memory for the new buffer */
550         *len = buf_len + via_len - (old_via_end - old_via_begin);
551         shbuf=(char *)shm_malloc(*len);
552         if (!shbuf) {
553                 ser_error=E_OUT_OF_MEM;
554                 LOG(L_ERR, "ERROR: print_uac_request_from_buf: no shmem\n");
555                 goto error01;
556         }
557
558         /* construct the new buffer */
559         memcpy(shbuf, buf, old_via_begin-buf);
560         memcpy(shbuf+(old_via_begin-buf), via, via_len);
561         memcpy(shbuf+(old_via_begin-buf)+via_len, old_via_end, (buf+buf_len)-old_via_end);
562
563 #ifdef DBG_MSG_QA
564         if (shbuf[*len-1]==0) {
565                 LOG(L_ERR, "ERROR: print_uac_request_from_buf: sanity check failed\n");
566                 abort();
567         }
568 #endif
569
570 error01:
571         pkg_free(via);
572 error00:
573         return shbuf;
574 }
575 #endif
576
577 /* introduce a new uac, which is blind -- it only creates the
578    data structures and starts FR timer, but that's it; it does
579    not print messages and send anything anywhere; that is good
580    for FIFO apps -- the transaction must look operationally
581    and FR must be ticking, whereas the request is "forwarded"
582    using a non-SIP way and will be replied the same way
583 */
584 int add_blind_uac( /*struct cell *t*/ )
585 {
586         unsigned short branch;
587         struct cell *t;
588
589         t=get_t();
590         if (t==T_UNDEFINED || !t ) {
591                 LOG(L_ERR, "ERROR: add_blind_uac: no transaction context\n");
592                 return -1;
593         }
594
595         branch=t->nr_of_outgoings;      
596         if (branch==MAX_BRANCHES) {
597                 LOG(L_ERR, "ERROR: add_blind_uac: "
598                         "maximum number of branches exceeded\n");
599                 return -1;
600         }
601         /* make sure it will be replied */
602         t->flags |= T_NOISY_CTIMER_FLAG;
603         membar_write(); /* to allow lockless prepare_to_cancel() we want to be sure
604                                            all the writes finished before updating branch number*/
605         t->nr_of_outgoings=(branch+1);
606         /* start FR timer -- protocol set by default to PROTO_NONE,
607        which means retransmission timer will not be started
608     */
609         if (start_retr(&t->uac[branch].request)!=0)
610                 LOG(L_CRIT, "BUG: add_blind_uac: start retr failed for %p\n",
611                                 &t->uac[branch].request);
612         /* we are on a timer -- don't need to put on wait on script
613            clean-up     
614         */
615         set_kr(REQ_FWDED); 
616
617         return 1; /* success */
618 }
619
620 /** introduce a new uac to transaction.
621  *  It doesn't send a message yet -- a reply to it might interfere with the
622  *  processes of adding multiple branches; On error returns <0 & sets ser_error
623  *  to the same value.
624  *  @param t - transaction
625  *  @param request - corresponding sip_mst, must be non-null, flags might be
626  *                   modified (on_branch route).
627  *  @param uri - uri used for the branch (must be non-null).
628  *  @param next_hop - next_hop in sip uri format. If null and proxy is null
629  *                    too, the uri will be used 
630  *  @param path     - path vector (list of route like destinations in sip
631  *                     uri format, e.g.: "<sip:1.2.3.4;lr>, <sip:5.6.7.8;lr>").
632  *  @param proxy    - proxy structure. If non-null it takes precedence over
633  *                    next_hop/uri and it will be used for forwarding.
634  *  @param fsocket  - forced forward send socket (can be 0).
635  *  @param snd_flags - special send flags (see SND_F_* / snd_flags_t)
636  *  @param proto    - forced protocol for forwarding (overrides the protocol
637  *                    in next_hop/uri or proxy if != PROTO_NONE).
638  *  @param flags    - special flags passed to prepare_new_uac().
639  *                    @see prepare_new_uac().
640  *  @returns branch id (>=0) or error (<0)
641 */
642 static int add_uac( struct cell *t, struct sip_msg *request, str *uri,
643                                         str* next_hop, str* path, struct proxy_l *proxy,
644                                         struct socket_info* fsocket, snd_flags_t snd_flags,
645                                         int proto, int flags)
646 {
647
648         int ret;
649         unsigned short branch;
650 #ifdef TM_UAC_FLAGS
651         unsigned int len;
652 #endif /* TM_UAC_FLAGS */
653
654         branch=t->nr_of_outgoings;
655         if (branch==MAX_BRANCHES) {
656                 LOG(L_ERR, "ERROR: add_uac: maximum number of branches exceeded\n");
657                 ret=ser_error=E_TOO_MANY_BRANCHES;
658                 goto error;
659         }
660
661         /* check existing buffer -- rewriting should never occur */
662         if (t->uac[branch].request.buffer) {
663                 LOG(L_CRIT, "ERROR: add_uac: buffer rewrite attempt\n");
664                 ret=ser_error=E_BUG;
665                 goto error;
666         }
667
668         /* check DNS resolution */
669         if (proxy){
670                 /* dst filled from the proxy */
671                 init_dest_info(&t->uac[branch].request.dst);
672                 t->uac[branch].request.dst.proto=get_proto(proto, proxy->proto);
673                 proxy2su(&t->uac[branch].request.dst.to, proxy);
674                 /* fill dst send_sock */
675                 t->uac[branch].request.dst.send_sock =
676                 get_send_socket( request, &t->uac[branch].request.dst.to,
677                                                                 t->uac[branch].request.dst.proto);
678                 if (request)
679                         t->uac[branch].request.dst.send_flags=request->fwd_send_flags;
680                 else
681                         SND_FLAGS_INIT(&t->uac[branch].request.dst.send_flags);
682                 next_hop=0;
683         }else {
684                 next_hop= next_hop?next_hop:uri;
685         }
686
687         /* now message printing starts ... */
688         if (unlikely( (ret=prepare_new_uac(t, request, branch, uri, path,
689                                                                                 next_hop, fsocket, snd_flags,
690                                                                                 proto, flags)) < 0)){
691                 ser_error=ret;
692                 goto error01;
693         }
694 #ifdef TM_UAC_FLAGS
695         len = count_applied_lumps(request->add_rm, HDR_RECORDROUTE_T);
696         if(len==1)
697                 t->uac[branch].flags = TM_UAC_FLAG_RR;
698         else if(len==2)
699                 t->uac[branch].flags = TM_UAC_FLAG_RR|TM_UAC_FLAG_R2;
700 #endif
701         getbflagsval(0, &t->uac[branch].branch_flags);
702         membar_write(); /* to allow lockless ops (e.g. prepare_to_cancel()) we want
703                                            to be sure everything above is fully written before
704                                            updating branches no. */
705         t->nr_of_outgoings=(branch+1);
706
707         /* update stats */
708         if (proxy){
709                 proxy_mark(proxy, 1);
710         }
711         /* done! */
712         ret=branch;
713                 
714 error01:
715 error:
716         return ret;
717 }
718
719
720
721 #ifdef USE_DNS_FAILOVER
722 /* Similar to add_uac(), but this function uses the outgoing message buffer of
723    the failed branch to construct the new message in case of DNS failover.
724 */
725 static int add_uac_from_buf( struct cell *t, struct sip_msg *request,
726                                                                 str *uri, str* path,
727                                                                 struct socket_info* fsocket,
728                                                                 snd_flags_t send_flags,
729                                                                 int proto,
730                                                                 char *buf, short buf_len)
731 {
732
733         int ret;
734         unsigned short branch;
735         char *shbuf;
736         unsigned int len;
737
738         branch=t->nr_of_outgoings;
739         if (branch==MAX_BRANCHES) {
740                 LOG(L_ERR, "ERROR: add_uac_from_buf: maximum number of branches"
741                                         " exceeded\n");
742                 ret=ser_error=E_TOO_MANY_BRANCHES;
743                 goto error;
744         }
745
746         /* check existing buffer -- rewriting should never occur */
747         if (t->uac[branch].request.buffer) {
748                 LOG(L_CRIT, "ERROR: add_uac_from_buf: buffer rewrite attempt\n");
749                 ret=ser_error=E_BUG;
750                 goto error;
751         }
752
753         if (uri2dst2(&t->uac[branch].dns_h, &t->uac[branch].request.dst,
754                                         fsocket, send_flags, uri, proto) == 0)
755         {
756                 ret=ser_error=E_BAD_ADDRESS;
757                 goto error;
758         }
759         
760         /* check if send_sock is ok */
761         if (t->uac[branch].request.dst.send_sock==0) {
762                 LOG(L_ERR, "ERROR: add_uac_from_buf: can't fwd to af %d, proto %d "
763                         " (no corresponding listening socket)\n",
764                         t->uac[branch].request.dst.to.s.sa_family, 
765                         t->uac[branch].request.dst.proto );
766                 ret=ser_error=E_NO_SOCKET;
767                 goto error;
768         }
769
770         /* now message printing starts ... */
771         shbuf=print_uac_request_from_buf( t, request, branch, uri,
772                                                         &len, &t->uac[branch].request.dst,
773                                                         buf, buf_len);
774         if (!shbuf) {
775                 ret=ser_error=E_OUT_OF_MEM;
776                 goto error;
777         }
778
779         /* things went well, move ahead and install new buffer! */
780         t->uac[branch].request.buffer=shbuf;
781         t->uac[branch].request.buffer_len=len;
782         t->uac[branch].uri.s=t->uac[branch].request.buffer+
783                 request->first_line.u.request.method.len+1;
784         t->uac[branch].uri.len=uri->len;
785         /* copy the path */
786         if (unlikely(path && path->s)){
787                 t->uac[branch].path.s=shm_malloc(path->len+1);
788                 if (unlikely(t->uac[branch].path.s==0)) {
789                         shm_free(shbuf);
790                         t->uac[branch].request.buffer=0;
791                         t->uac[branch].request.buffer_len=0;
792                         t->uac[branch].uri.s=0;
793                         t->uac[branch].uri.len=0;
794                         ret=ser_error=E_OUT_OF_MEM;
795                         goto error;
796                 }
797                 t->uac[branch].path.len=path->len;
798                 t->uac[branch].path.s[path->len]=0;
799                 memcpy( t->uac[branch].path.s, path->s, path->len);
800         }
801         membar_write(); /* to allow lockless ops (e.g. prepare_to_cancel()) we want
802                                            to be sure everything above is fully written before
803                                            updating branches no. */
804         t->nr_of_outgoings=(branch+1);
805
806         /* done! */
807         ret=branch;
808                 
809 error:
810         return ret;
811 }
812
813 /* introduce a new uac to transaction, based on old_uac and a possible
814  *  new ip address (if the dns name resolves to more ips). If no more
815  *   ips are found => returns -1.
816  *  returns its branch id (>=0)
817    or error (<0) and sets ser_error if needed; it doesn't send a message 
818    yet -- a reply to it
819    might interfere with the processes of adding multiple branches
820    if lock_replies is 1 replies will be locked for t until the new branch
821    is added (to prevent add branches races). Use 0 if the reply lock is
822    already held, e.g. in failure route/handlers (WARNING: using 1 in a 
823    failure route will cause a deadlock).
824 */
825 int add_uac_dns_fallback(struct cell *t, struct sip_msg* msg,
826                                                                         struct ua_client* old_uac,
827                                                                         int lock_replies)
828 {
829         int ret;
830         
831         ret=-1;
832         if (cfg_get(core, core_cfg, use_dns_failover) &&
833                         !((t->flags & (T_DONT_FORK|T_DISABLE_FAILOVER)) ||
834                                 uac_dont_fork(old_uac)) &&
835                         dns_srv_handle_next(&old_uac->dns_h, 0)){
836                         if (lock_replies){
837                                 /* use reply lock to guarantee nobody is adding a branch
838                                  * in the same time */
839                                 LOCK_REPLIES(t);
840                                 /* check again that we can fork */
841                                 if ((t->flags & T_DONT_FORK) || uac_dont_fork(old_uac)){
842                                         UNLOCK_REPLIES(t);
843                                         DBG("add_uac_dns_fallback: no forking on => no new"
844                                                         " branches\n");
845                                         return ret;
846                                 }
847                         }
848                         if (t->nr_of_outgoings >= MAX_BRANCHES){
849                                 LOG(L_ERR, "ERROR: add_uac_dns_fallback: maximum number of "
850                                                         "branches exceeded\n");
851                                 if (lock_replies)
852                                         UNLOCK_REPLIES(t);
853                                         ret=ser_error=E_TOO_MANY_BRANCHES;
854                                 return ret;
855                         }
856                         /* copy the dns handle into the new uac */
857                         dns_srv_handle_cpy(&t->uac[t->nr_of_outgoings].dns_h,
858                                                                 &old_uac->dns_h);
859
860                         if (cfg_get(tm, tm_cfg, reparse_on_dns_failover)){
861                                 /* Reuse the old buffer and only replace the via header.
862                                  * The drawback is that the send_socket is not corrected
863                                  * in the rest of the message, only in the VIA HF (Miklos) */
864                                 ret=add_uac_from_buf(t,  msg, &old_uac->uri,
865                                                         &old_uac->path,
866                                                          (old_uac->request.dst.send_flags.f &
867                                                                 SND_F_FORCE_SOCKET)?
868                                                                         old_uac->request.dst.send_sock:0,
869                                                         old_uac->request.dst.send_flags,
870                                                         old_uac->request.dst.proto,
871                                                         old_uac->request.buffer,
872                                                         old_uac->request.buffer_len);
873                         }else
874                                 /* add_uac will use dns_h => next_hop will be ignored.
875                                  * Unfortunately we can't reuse the old buffer, the branch id
876                                  *  must be changed and the send_socket might be different =>
877                                  *  re-create the whole uac */
878                                 ret=add_uac(t,  msg, &old_uac->uri, 0, &old_uac->path, 0,
879                                                          (old_uac->request.dst.send_flags.f &
880                                                                 SND_F_FORCE_SOCKET)?
881                                                                         old_uac->request.dst.send_sock:0,
882                                                         old_uac->request.dst.send_flags,
883                                                         old_uac->request.dst.proto, UAC_DNS_FAILOVER_F);
884
885                         if (ret<0){
886                                 /* failed, delete the copied dns_h */
887                                 dns_srv_handle_put(&t->uac[t->nr_of_outgoings].dns_h);
888                         }
889                         if (lock_replies){
890                                 UNLOCK_REPLIES(t);
891                         }
892         }
893         return ret;
894 }
895
896 #endif
897
898 int e2e_cancel_branch( struct sip_msg *cancel_msg, struct cell *t_cancel, 
899         struct cell *t_invite, int branch )
900 {
901         int ret;
902         char *shbuf;
903         unsigned int len;
904         snd_flags_t snd_flags;
905
906         ret=-1;
907         if (t_cancel->uac[branch].request.buffer) {
908                 LOG(L_CRIT, "ERROR: e2e_cancel_branch: buffer rewrite attempt\n");
909                 ret=ser_error=E_BUG;
910                 goto error;
911         }
912         if (t_invite->uac[branch].request.buffer==0){
913                 /* inactive / deleted  branch */
914                 goto error;
915         }
916         t_invite->uac[branch].request.flags|=F_RB_CANCELED;
917
918         /* note -- there is a gap in proxy stats -- we don't update 
919            proxy stats with CANCEL (proxy->ok, proxy->tx, etc.)
920         */
921         
922         /* set same dst as the invite */
923         t_cancel->uac[branch].request.dst=t_invite->uac[branch].request.dst;
924         /* print */
925         if (cfg_get(tm, tm_cfg, reparse_invite)) {
926                 /* buffer is built localy from the INVITE which was sent out */
927                 /* lumps can be set outside of the lock, make sure that we read
928                  * the up-to-date values */
929                 membar_depends();
930                 if (cancel_msg->add_rm || cancel_msg->body_lumps) {
931                         LOG(L_WARN, "WARNING: e2e_cancel_branch: CANCEL is built locally, "
932                         "thus lumps are not applied to the message!\n");
933                 }
934                 shbuf=build_local_reparse( t_invite, branch, &len, CANCEL,
935                                                                         CANCEL_LEN, &t_invite->to
936 #ifdef CANCEL_REASON_SUPPORT
937                                                                         , 0
938 #endif /* CANCEL_REASON_SUPPORT */
939                                                                         );
940                 if (unlikely(!shbuf)) {
941                         LOG(L_ERR, "e2e_cancel_branch: printing e2e cancel failed\n");
942                         ret=ser_error=E_OUT_OF_MEM;
943                         goto error;
944                 }
945                 /* install buffer */
946                 t_cancel->uac[branch].request.buffer=shbuf;
947                 t_cancel->uac[branch].request.buffer_len=len;
948                 t_cancel->uac[branch].uri.s=t_cancel->uac[branch].request.buffer+
949                         cancel_msg->first_line.u.request.method.len+1;
950                 t_cancel->uac[branch].uri.len=t_invite->uac[branch].uri.len;
951         } else {
952                 SND_FLAGS_INIT(&snd_flags);
953                 /* buffer is constructed from the received CANCEL with lumps applied */
954                 /*  t_cancel...request.dst is already filled (see above) */
955                 if (unlikely((ret=prepare_new_uac( t_cancel, cancel_msg, branch,
956                                                                         &t_invite->uac[branch].uri,
957                                                                         &t_invite->uac[branch].path,
958                                                                         0, 0, snd_flags, PROTO_NONE, 0)) <0)){
959                         ser_error=ret;
960                         goto error;
961                 }
962         }
963         /* success */
964         ret=1;
965
966 error:
967         return ret;
968 }
969
970
971
972 #ifdef CANCEL_REASON_SUPPORT
973 /** create a cancel reason structure packed into a single shm. block.
974   * From a cause and a pointer to a str or cancel_msg, build a
975   * packed cancel reason structure (CANCEL_REAS_PACKED_HDRS), using a
976   * single memory allocation (so that it can be freed by a simple shm_free().
977   * @param cause - cancel cause, @see cancel_reason for more details.
978   * @param data - depends on the cancel cause.
979   * @return pointer to shm. packed cancel reason struct. on success,
980   *        0 on error
981   */
982 static struct cancel_reason* cancel_reason_pack(short cause, void* data,
983                                                                                                         struct cell* t)
984 {
985         char* d;
986         struct cancel_reason* cr;
987         int reason_len;
988         int code_len;
989         struct hdr_field *reas1, *reas_last, *hdr;
990         str* txt;
991         struct sip_msg* e2e_cancel;
992         
993         if (likely(cause != CANCEL_REAS_UNKNOWN)){
994                 reason_len = 0;
995                 txt = 0;
996                 e2e_cancel = 0;
997                 reas1 = 0;
998                 reas_last = 0;
999                 if (likely(cause == CANCEL_REAS_RCVD_CANCEL &&
1000                                         data && !(t->flags & T_NO_E2E_CANCEL_REASON))) {
1001                         /* parse the entire cancel, to get all the Reason headers */
1002                         e2e_cancel = data;
1003                         parse_headers(e2e_cancel, HDR_EOH_F, 0);
1004                         for(hdr=get_hdr(e2e_cancel, HDR_REASON_T), reas1=hdr;
1005                                         hdr; hdr=next_sibling_hdr(hdr)) {
1006                                 /* hdr->len includes CRLF */
1007                                 reason_len += hdr->len;
1008                                 reas_last=hdr;
1009                         }
1010                 } else if (likely(cause > 0 &&
1011                                         cfg_get(tm, tm_cfg, local_cancel_reason))){
1012                         txt = (str*) data;
1013                         /* Reason: SIP;cause=<reason->cause>[;text=<reason->u.text.s>] */
1014                         reason_len = REASON_PREFIX_LEN + USHORT2SBUF_MAX_LEN +
1015                                 ((txt && txt->s)?
1016                                         REASON_TEXT_LEN + 1 + txt->len + 1 : 0) +
1017                                 CRLF_LEN;
1018                 } else if (cause == CANCEL_REAS_PACKED_HDRS &&
1019                                         !(t->flags & T_NO_E2E_CANCEL_REASON) && data) {
1020                         txt = (str*) data;
1021                         reason_len = txt?txt->len:0;
1022                 } else if (unlikely(cause < CANCEL_REAS_MIN)) {
1023                         BUG("unhandled reason cause %d\n", cause);
1024                         goto error;
1025                 }
1026                 
1027                 if (unlikely(reason_len == 0))
1028                         return 0; /* nothing to do, no reason */
1029                 cr = shm_malloc(sizeof(struct cancel_reason) + reason_len);
1030                 if (unlikely(cr == 0))
1031                                 goto error;
1032                 d = (char*)cr +sizeof(*cr);
1033                 cr->cause = CANCEL_REAS_PACKED_HDRS;
1034                 cr->u.packed_hdrs.s = d;
1035                 cr->u.packed_hdrs.len = reason_len;
1036                 
1037                 if (cause == CANCEL_REAS_RCVD_CANCEL) {
1038                         for(hdr=reas1; hdr; hdr=next_sibling_hdr(hdr)) {
1039                                 /* hdr->len includes CRLF */
1040                                 append_str(d, hdr->name.s, hdr->len);
1041                                 if (likely(hdr==reas_last))
1042                                         break;
1043                         }
1044                 } else if (likely(cause > 0)) {
1045                         append_str(d, REASON_PREFIX, REASON_PREFIX_LEN);
1046                         code_len=ushort2sbuf(cause, d, reason_len - 
1047                                                                         (int)(d - (char*)cr - sizeof(*cr)));
1048                         if (unlikely(code_len==0)) {
1049                                 shm_free(cr);
1050                                 cr = 0;
1051                                 BUG("not enough space to write reason code");
1052                                 goto error;
1053                         }
1054                         d+=code_len;
1055                         if (txt && txt->s){
1056                                 append_str(d, REASON_TEXT, REASON_TEXT_LEN);
1057                                 *d='"'; d++;
1058                                 append_str(d, txt->s, txt->len);
1059                                 *d='"'; d++;
1060                         }
1061                         append_str(d, CRLF, CRLF_LEN);
1062                 } else if (cause == CANCEL_REAS_PACKED_HDRS) {
1063                         append_str(d, txt->s, txt->len);
1064                 }
1065                 return cr;
1066         }
1067 error:
1068         return 0;
1069 }
1070 #endif /* CANCEL_REASON_SUPPORT */
1071
1072
1073
1074 void e2e_cancel( struct sip_msg *cancel_msg,
1075         struct cell *t_cancel, struct cell *t_invite )
1076 {
1077         branch_bm_t cancel_bm;
1078 #ifndef E2E_CANCEL_HOP_BY_HOP
1079         branch_bm_t tmp_bm;
1080 #elif defined (CANCEL_REASON_SUPPORT)
1081         struct cancel_reason* reason;
1082         int free_reason;
1083 #endif /* E2E_CANCEL_HOP_BY_HOP */
1084         int i;
1085         int lowest_error;
1086         int ret;
1087         struct tmcb_params tmcb;
1088
1089         cancel_bm=0;
1090         lowest_error=0;
1091
1092         if (unlikely(has_tran_tmcbs(t_invite, TMCB_E2ECANCEL_IN))){
1093                 INIT_TMCB_PARAMS(tmcb, cancel_msg, 0, cancel_msg->REQ_METHOD);
1094                 run_trans_callbacks_internal(&t_invite->tmcb_hl, TMCB_E2ECANCEL_IN, 
1095                                                                                 t_invite, &tmcb);
1096         }
1097         /* mark transaction as canceled, so that no new message are forwarded
1098          * on it and t_is_canceled() returns true 
1099          * WARNING: it's safe to do it without locks, at least for now (in a race
1100          * event even if a flag is unwillingly reset nothing bad will happen),
1101          * however this should be rechecked for any future new flags use.
1102          */
1103         t_invite->flags|=T_CANCELED;
1104         /* first check if there are any branches */
1105         if (t_invite->nr_of_outgoings==0){
1106                 /* no branches yet => force a reply to the invite */
1107                 t_reply( t_invite, t_invite->uas.request, 487, CANCELED );
1108                 DBG("DEBUG: e2e_cancel: e2e cancel -- no more pending branches\n");
1109                 t_reply( t_cancel, cancel_msg, 200, CANCEL_DONE );
1110                 return;
1111         }
1112         
1113         /* determine which branches to cancel ... */
1114         prepare_to_cancel(t_invite, &cancel_bm, 0);
1115 #ifdef E2E_CANCEL_HOP_BY_HOP
1116         /* we don't need to set t_cancel label to be the same as t_invite if
1117          * we do hop by hop cancel. The cancel transaction will have a different 
1118          * label, but this is not a problem since this transaction is only used to
1119          * send a reply back. The cancels sent upstream will be part of the invite
1120          * transaction (local_cancel retr. bufs) and they will be generated with
1121          * the same via as the invite.
1122          * Note however that setting t_cancel label the same as t_invite will work
1123          * too (the upstream cancel replies will properly match the t_invite
1124          * transaction and will not match the t_cancel because t_cancel will always
1125          * have 0 branches and we check for the branch number in 
1126          * t_reply_matching() ).
1127          */
1128 #ifdef CANCEL_REASON_SUPPORT
1129         free_reason = 0;
1130         reason = 0;
1131         if (likely(t_invite->uas.cancel_reas == 0)){
1132                 reason = cancel_reason_pack(CANCEL_REAS_RCVD_CANCEL, cancel_msg,
1133                                                                         t_invite);
1134                 /* set if not already set */
1135                 if (unlikely(reason &&
1136                                         atomic_cmpxchg_long((void*)&t_invite->uas.cancel_reas,
1137                                                                                 0, (long)reason) != 0)) {
1138                         /* already set, failed to re-set it */
1139                         free_reason = 1;
1140                 }
1141         }
1142 #endif /* CANCEL_REASON_SUPPORT */
1143         for (i=0; i<t_invite->nr_of_outgoings; i++)
1144                 if (cancel_bm & (1<<i)) {
1145                         /* it's safe to get the reply lock since e2e_cancel is
1146                          * called with the cancel as the "current" transaction so
1147                          * at most t_cancel REPLY_LOCK is held in this process =>
1148                          * no deadlock possibility */
1149                         ret=cancel_branch(
1150                                 t_invite,
1151                                 i,
1152 #ifdef CANCEL_REASON_SUPPORT
1153                                 reason,
1154 #endif /* CANCEL_REASON_SUPPORT */
1155                                 cfg_get(tm,tm_cfg, cancel_b_flags)
1156                                         | ((t_invite->uac[i].request.buffer==NULL)?
1157                                                 F_CANCEL_B_FAKE_REPLY:0) /* blind UAC? */
1158                         );
1159                         if (ret<0) cancel_bm &= ~(1<<i);
1160                         if (ret<lowest_error) lowest_error=ret;
1161                 }
1162 #ifdef CANCEL_REASON_SUPPORT
1163         if (unlikely(free_reason)) {
1164                 /* reason was not set as the global reason => free it */
1165                 shm_free(reason);
1166         }
1167 #endif /* CANCEL_REASON_SUPPORT */
1168 #else /* ! E2E_CANCEL_HOP_BY_HOP */
1169         /* fix label -- it must be same for reply matching (the label is part of
1170          * the generated via branch for the cancels sent upstream and if it
1171          * would be different form the one in the INVITE the transactions would not
1172          * match */
1173         t_cancel->label=t_invite->label;
1174         t_cancel->nr_of_outgoings=t_invite->nr_of_outgoings;
1175         /* ... and install CANCEL UACs */
1176         for (i=0; i<t_invite->nr_of_outgoings; i++)
1177                 if ((cancel_bm & (1<<i)) && (t_invite->uac[i].last_received>=100)) {
1178                         ret=e2e_cancel_branch(cancel_msg, t_cancel, t_invite, i);
1179                         if (ret<0) cancel_bm &= ~(1<<i);
1180                         if (ret<lowest_error) lowest_error=ret;
1181                 }
1182
1183         /* send them out */
1184         for (i = 0; i < t_cancel->nr_of_outgoings; i++) {
1185                 if (cancel_bm & (1 << i)) {
1186                         if (t_invite->uac[i].last_received>=100){
1187                                 /* Provisional reply received on this branch, send CANCEL */
1188                                 /* we do need to stop the retr. timers if the request is not 
1189                                  * an invite and since the stop_rb_retr() cost is lower then
1190                                  * the invite check we do it always --andrei */
1191                                 stop_rb_retr(&t_invite->uac[i].request);
1192                                 if (SEND_BUFFER(&t_cancel->uac[i].request) == -1) {
1193                                         LOG(L_ERR, "ERROR: e2e_cancel: send failed\n");
1194                                 }
1195                                 else{
1196                                         if (unlikely(has_tran_tmcbs(t_cancel, TMCB_REQUEST_SENT)))
1197                                                 run_trans_callbacks_with_buf(TMCB_REQUEST_SENT,
1198                                                                              &t_cancel->uac[i].request,
1199                                                                              cancel_msg, 0, TMCB_LOCAL_F);
1200                                 }
1201                                 if (start_retr( &t_cancel->uac[i].request )!=0)
1202                                         LOG(L_CRIT, "BUG: e2e_cancel: failed to start retr."
1203                                                         " for %p\n", &t_cancel->uac[i].request);
1204                         } else {
1205                                 /* No provisional response received, stop
1206                                  * retransmission timers */
1207                                 if (!(cfg_get(tm, tm_cfg, cancel_b_flags) & 
1208                                                         F_CANCEL_B_FORCE_RETR))
1209                                         stop_rb_retr(&t_invite->uac[i].request);
1210                                 /* no need to stop fr, it will be stopped by relay_reply
1211                                  * put_on_wait -- andrei */
1212                                 /* Generate faked reply */
1213                                 if (cfg_get(tm, tm_cfg, cancel_b_flags) &
1214                                                 F_CANCEL_B_FAKE_REPLY){
1215                                         LOCK_REPLIES(t_invite);
1216                                         if (relay_reply(t_invite, FAKED_REPLY, i,
1217                                                                         487, &tmp_bm, 1) == RPS_ERROR) {
1218                                                 lowest_error = -1;
1219                                         }
1220                                 }
1221                         }
1222                 }
1223         }
1224 #endif /*E2E_CANCEL_HOP_BY_HOP */
1225
1226         /* if error occurred, let it know upstream (final reply
1227            will also move the transaction on wait state
1228         */
1229         if (lowest_error<0) {
1230                 LOG(L_ERR, "ERROR: cancel error\n");
1231                 /* if called from failure_route, make sure that the unsafe version
1232                  * is called (we are already holding the reply mutex for the cancel
1233                  * transaction).
1234                  */
1235                 if ((is_route_type(FAILURE_ROUTE)) && (t_cancel==get_t()))
1236                         t_reply_unsafe( t_cancel, cancel_msg, 500, "cancel error");
1237                 else
1238                         t_reply( t_cancel, cancel_msg, 500, "cancel error");
1239         } else if (cancel_bm) {
1240                 /* if there are pending branches, let upstream know we
1241                    are working on it
1242                 */
1243                 DBG("DEBUG: e2e_cancel: e2e cancel proceeding\n");
1244                 /* if called from failure_route, make sure that the unsafe version
1245                  * is called (we are already hold the reply mutex for the cancel
1246                  * transaction).
1247                  */
1248                 if ((is_route_type(FAILURE_ROUTE)) && (t_cancel==get_t()))
1249                         t_reply_unsafe( t_cancel, cancel_msg, 200, CANCELING );
1250                 else
1251                         t_reply( t_cancel, cancel_msg, 200, CANCELING );
1252         } else {
1253                 /* if the transaction exists, but there are no more pending
1254                    branches, tell upstream we're done
1255                 */
1256                 DBG("DEBUG: e2e_cancel: e2e cancel -- no more pending branches\n");
1257                 /* if called from failure_route, make sure that the unsafe version
1258                  * is called (we are already hold the reply mutex for the cancel
1259                  * transaction).
1260                  */
1261                 if ((is_route_type(FAILURE_ROUTE)) && (t_cancel==get_t()))
1262                         t_reply_unsafe( t_cancel, cancel_msg, 200, CANCEL_DONE );
1263                 else
1264                         t_reply( t_cancel, cancel_msg, 200, CANCEL_DONE );
1265         }
1266 }
1267
1268
1269
1270 /* sends one uac/branch buffer and fallbacks to other ips if
1271  *  the destination resolves to several addresses
1272  *  Takes care of starting timers a.s.o. (on send success)
1273  *  returns: -2 on error, -1 on drop,  current branch id on success,
1274  *   new branch id on send error/blacklist, when failover is possible
1275  *    (ret>=0 && ret!=branch)
1276  *    if lock_replies is 1, the replies for t will be locked when adding
1277  *     new branches (to prevent races). Use 0 from failure routes or other
1278  *     places where the reply lock is already held, to avoid deadlocks. */
1279 int t_send_branch( struct cell *t, int branch, struct sip_msg* p_msg ,
1280                                         struct proxy_l * proxy, int lock_replies)
1281 {
1282         struct ip_addr ip; /* debugging */
1283         int ret;
1284         struct ua_client* uac;
1285         
1286         uac=&t->uac[branch];
1287         ret=branch;
1288         if (run_onsend(p_msg,   &uac->request.dst, uac->request.buffer,
1289                                         uac->request.buffer_len)==0){
1290                 /* disable the current branch: set a "fake" timeout
1291                  *  reply code but don't set uac->reply, to avoid overriding 
1292                  *  a higly unlikely, perfectly timed fake reply (to a message
1293                  *   we never sent).
1294                  * (code=final reply && reply==0 => t_pick_branch won't ever pick it)*/
1295                         uac->last_received=408;
1296                         su2ip_addr(&ip, &uac->request.dst.to);
1297                         DBG("t_send_branch: onsend_route dropped msg. to %s:%d (%d)\n",
1298                                                         ip_addr2a(&ip), su_getport(&uac->request.dst.to),
1299                                                         uac->request.dst.proto);
1300 #ifdef USE_DNS_FAILOVER
1301                         /* if the destination resolves to more ips, add another
1302                          *  branch/uac */
1303                         if (cfg_get(core, core_cfg, use_dns_failover)){
1304                                 ret=add_uac_dns_fallback(t, p_msg, uac, lock_replies);
1305                                 if (ret>=0){
1306                                         su2ip_addr(&ip, &uac->request.dst.to);
1307                                         DBG("t_send_branch: send on branch %d failed "
1308                                                         "(onsend_route), trying another ip %s:%d (%d)\n",
1309                                                         branch, ip_addr2a(&ip),
1310                                                         su_getport(&uac->request.dst.to),
1311                                                         uac->request.dst.proto);
1312                                         /* success, return new branch */
1313                                         return ret;
1314                                 }
1315                         }
1316 #endif /* USE_DNS_FAILOVER*/
1317                 return -1; /* drop, try next branch */
1318         }
1319 #ifdef USE_DST_BLACKLIST
1320         if (cfg_get(core, core_cfg, use_dst_blacklist)
1321                 && p_msg
1322                 && (p_msg->REQ_METHOD & cfg_get(tm, tm_cfg, tm_blst_methods_lookup))
1323         ){
1324                 if (dst_is_blacklisted(&uac->request.dst, p_msg)){
1325                         su2ip_addr(&ip, &uac->request.dst.to);
1326                         DBG("t_send_branch: blacklisted destination: %s:%d (%d)\n",
1327                                                         ip_addr2a(&ip), su_getport(&uac->request.dst.to),
1328                                                         uac->request.dst.proto);
1329                         /* disable the current branch: set a "fake" timeout
1330                          *  reply code but don't set uac->reply, to avoid overriding 
1331                          *  a higly unlikely, perfectly timed fake reply (to a message
1332                          *   we never sent).  (code=final reply && reply==0 => 
1333                          *   t_pick_branch won't ever pick it)*/
1334                         uac->last_received=408;
1335 #ifdef USE_DNS_FAILOVER
1336                         /* if the destination resolves to more ips, add another
1337                          *  branch/uac */
1338                         if (cfg_get(core, core_cfg, use_dns_failover)){
1339                                 ret=add_uac_dns_fallback(t, p_msg, uac, lock_replies);
1340                                 if (ret>=0){
1341                                         su2ip_addr(&ip, &uac->request.dst.to);
1342                                         DBG("t_send_branch: send on branch %d failed (blacklist),"
1343                                                         " trying another ip %s:%d (%d)\n", branch,
1344                                                         ip_addr2a(&ip), su_getport(&uac->request.dst.to),
1345                                                         uac->request.dst.proto);
1346                                         /* success, return new branch */
1347                                         return ret;
1348                                 }
1349                         }
1350 #endif /* USE_DNS_FAILOVER*/
1351                         return -1; /* don't send */
1352                 }
1353         }
1354 #endif /* USE_DST_BLACKLIST */
1355         if (SEND_BUFFER( &uac->request)==-1) {
1356                 /* disable the current branch: set a "fake" timeout
1357                  *  reply code but don't set uac->reply, to avoid overriding 
1358                  *  a highly unlikely, perfectly timed fake reply (to a message
1359                  *  we never sent).
1360                  * (code=final reply && reply==0 => t_pick_branch won't ever pick it)*/
1361                 uac->last_received=408;
1362                 su2ip_addr(&ip, &uac->request.dst.to);
1363                 DBG("t_send_branch: send to %s:%d (%d) failed\n",
1364                                                         ip_addr2a(&ip), su_getport(&uac->request.dst.to),
1365                                                         uac->request.dst.proto);
1366 #ifdef USE_DST_BLACKLIST
1367                 dst_blacklist_add(BLST_ERR_SEND, &uac->request.dst, p_msg);
1368 #endif
1369 #ifdef USE_DNS_FAILOVER
1370                 /* if the destination resolves to more ips, add another
1371                  *  branch/uac */
1372                 if (cfg_get(core, core_cfg, use_dns_failover)){
1373                         ret=add_uac_dns_fallback(t, p_msg, uac, lock_replies);
1374                         if (ret>=0){
1375                                 /* success, return new branch */
1376                                 DBG("t_send_branch: send on branch %d failed, adding another"
1377                                                 " branch with another ip\n", branch);
1378                                 return ret;
1379                         }
1380                 }
1381 #endif
1382                 LOG(L_ERR, "ERROR: t_send_branch: sending request on branch %d "
1383                                 "failed\n", branch);
1384                 if (proxy) { proxy->errors++; proxy->ok=0; }
1385                 return -2;
1386         } else {
1387                 if (unlikely(has_tran_tmcbs(t, TMCB_REQUEST_SENT)))
1388                         run_trans_callbacks_with_buf(TMCB_REQUEST_SENT, &uac->request, p_msg, 0,0);
1389                 /* start retr. only if the send succeeded */
1390                 if (start_retr( &uac->request )!=0){
1391                         LOG(L_CRIT, "BUG: t_send_branch: retr. already started for %p\n",
1392                                         &uac->request);
1393                         return -2;
1394                 }
1395         }
1396         return ret;
1397 }
1398
1399
1400
1401 /* function returns:
1402  *       1 - forward successful
1403  *      -1 - error during forward
1404  */
1405 int t_forward_nonack( struct cell *t, struct sip_msg* p_msg , 
1406         struct proxy_l * proxy, int proto)
1407 {
1408         int branch_ret, lowest_ret;
1409         str current_uri;
1410         branch_bm_t     added_branches;
1411         int first_branch;
1412         int i, q;
1413         struct cell *t_invite;
1414         int success_branch;
1415         int try_new;
1416         int lock_replies;
1417         str dst_uri, path;
1418         struct socket_info* si;
1419         flag_t backup_bflags = 0;
1420         flag_t bflags = 0;
1421         
1422
1423         /* make -Wall happy */
1424         current_uri.s=0;
1425
1426         if (t->flags & T_CANCELED){
1427                 DBG("t_forward_non_ack: no forwarding on a canceled transaction\n");
1428                 ser_error=E_CANCELED;
1429                 return -1;
1430         }
1431         if (p_msg->REQ_METHOD==METHOD_CANCEL) { 
1432                 t_invite=t_lookupOriginalT(  p_msg );
1433                 if (t_invite!=T_NULL_CELL) {
1434                         e2e_cancel( p_msg, t, t_invite );
1435                         UNREF(t_invite);
1436                         /* it should be set to REQ_RPLD by e2e_cancel, which should
1437                          * send a final reply */
1438                         set_kr(REQ_FWDED);
1439                         return 1;
1440                 }
1441         }
1442
1443         getbflagsval(0, &backup_bflags);
1444
1445         /* if no more specific error code is known, use this */
1446         lowest_ret=E_UNSPEC;
1447         /* branches added */
1448         added_branches=0;
1449         /* branch to begin with */
1450         first_branch=t->nr_of_outgoings;
1451
1452         if (t->on_branch) {
1453                 /* tell add_uac that it should run branch route actions */
1454                 branch_route = t->on_branch;
1455                 /* reset the flag before running the actions (so that it
1456                  * could be set again in branch_route if needed
1457                  */
1458                 t_on_branch(0);
1459         } else {
1460                 branch_route = 0;
1461         }
1462         
1463         /* on first-time forwarding, update the lumps */
1464         if (first_branch==0) {
1465                 /* update the shmem-ized msg with the lumps */
1466                 if ((is_route_type(REQUEST_ROUTE)) &&
1467                         save_msg_lumps(t->uas.request, p_msg)) {
1468                                 LOG(L_ERR, "ERROR: t_forward_nonack: "
1469                                         "failed to save the message lumps\n");
1470                                 return -1;
1471                         }
1472         }
1473
1474         /* if ruri is not already consumed (by another invocation), use current
1475            uri too. Else add only additional branches (which may be continuously
1476            refilled).
1477         */
1478         if (ruri_get_forking_state()) {
1479                 try_new=1;
1480                 branch_ret=add_uac( t, p_msg, GET_RURI(p_msg), GET_NEXT_HOP(p_msg),
1481                                                         &p_msg->path_vec, proxy, p_msg->force_send_socket,
1482                                                         p_msg->fwd_send_flags, proto,
1483                                                         (p_msg->dst_uri.len)?0:UAC_SKIP_BR_DST_F);
1484                 if (branch_ret>=0) 
1485                         added_branches |= 1<<branch_ret;
1486                 else
1487                         lowest_ret=MIN_int(lowest_ret, branch_ret);
1488         } else try_new=0;
1489
1490         init_branch_iterator();
1491         while((current_uri.s=next_branch( &current_uri.len, &q, &dst_uri, &path,
1492                                                                                 &bflags, &si))) {
1493                 try_new++;
1494                 setbflagsval(0, bflags);
1495
1496                 branch_ret=add_uac( t, p_msg, &current_uri,
1497                                                         (dst_uri.len) ? (&dst_uri) : &current_uri,
1498                                                         &path, proxy, si, p_msg->fwd_send_flags,
1499                                                         proto, (dst_uri.len)?0:UAC_SKIP_BR_DST_F);
1500                 /* pick some of the errors in case things go wrong;
1501                    note that picking lowest error is just as good as
1502                    any other algorithm which picks any other negative
1503                    branch result */
1504                 if (branch_ret>=0) 
1505                         added_branches |= 1<<branch_ret;
1506                 else
1507                         lowest_ret=MIN_int(lowest_ret, branch_ret);
1508         }
1509         /* consume processed branches */
1510         clear_branches();
1511
1512         setbflagsval(0, backup_bflags);
1513
1514         /* update message flags, if changed in branch route */
1515         t->uas.request->flags = p_msg->flags;
1516
1517         /* don't forget to clear all branches processed so far */
1518
1519         /* things went wrong ... no new branch has been fwd-ed at all */
1520         if (added_branches==0) {
1521                 if (try_new==0) {
1522                         LOG(L_ERR, "ERROR: t_forward_nonack: no branches for"
1523                                                 " forwarding\n");
1524                         /* either failed to add branches, or there were no more branches
1525                         */
1526                         ser_error=MIN_int(lowest_ret, E_CFG);
1527                         return -1;
1528                 }
1529                 if(lowest_ret!=E_CFG)
1530                         LOG(L_ERR, "ERROR: t_forward_nonack: failure to add branches\n");
1531                 ser_error=lowest_ret;
1532                 return lowest_ret;
1533         }
1534
1535 #ifdef TM_UAC_FLAGS
1536         /* mark the fist branch in this fwd step */
1537         t->uac[first_branch].flags |= TM_UAC_FLAG_FB;
1538 #endif
1539
1540         ser_error=0; /* clear branch adding errors */
1541         /* send them out now */
1542         success_branch=0;
1543         lock_replies= ! ((is_route_type(FAILURE_ROUTE)) && (t==get_t()));
1544         for (i=first_branch; i<t->nr_of_outgoings; i++) {
1545                 if (added_branches & (1<<i)) {
1546                         
1547                         branch_ret=t_send_branch(t, i, p_msg , proxy, lock_replies);
1548                         if (branch_ret>=0){ /* some kind of success */
1549                                 if (branch_ret==i) { /* success */
1550                                         success_branch++;
1551                                         if (unlikely(has_tran_tmcbs(t, TMCB_REQUEST_OUT)))
1552                                                 run_trans_callbacks_with_buf( TMCB_REQUEST_OUT, &t->uac[i].request,
1553                                                                               p_msg, 0, -p_msg->REQ_METHOD);
1554                                 }
1555                                 else /* new branch added */
1556                                         added_branches |= 1<<branch_ret;
1557                         }
1558                 }
1559         }
1560         if (success_branch<=0) {
1561                 /* return always E_SEND for now
1562                  * (the real reason could be: denied by onsend routes, blacklisted,
1563                  *  send failed or any of the errors listed before + dns failed
1564                  *  when attempting dns failover) */
1565                 ser_error=E_SEND;
1566                 /* else return the last error (?) */
1567                 /* the caller should take care and delete the transaction */
1568                 return -1;
1569         }
1570         ser_error=0; /* clear branch send errors, we have overall success */
1571         set_kr(REQ_FWDED);
1572         return 1;
1573 }
1574
1575
1576
1577 /* cancel handling/forwarding function
1578  * CANCELs with no matching transaction are handled in function of
1579  * the unmatched_cancel config var: they are either forwarded statefully,
1580  * statelessly or dropped.
1581  * function returns:
1582  *       1 - forward successful
1583  *       0 - error, but do not reply 
1584  *      <0 - error during forward
1585  * it also sets *tran if a transaction was created
1586  */
1587 int t_forward_cancel(struct sip_msg* p_msg , struct proxy_l * proxy, int proto,
1588                                                 struct cell** tran)
1589 {
1590         struct cell* t_invite;
1591         struct cell* t;
1592         int ret;
1593         int new_tran;
1594         struct dest_info dst;
1595         str host;
1596         unsigned short port;
1597         short comp;
1598         
1599         t=0;
1600         /* handle cancels for which no transaction was created yet */
1601         if (cfg_get(tm, tm_cfg, unmatched_cancel)==UM_CANCEL_STATEFULL){
1602                 /* create cancel transaction */
1603                 new_tran=t_newtran(p_msg);
1604                 if (new_tran<=0 && new_tran!=E_SCRIPT){
1605                         if (new_tran==0)
1606                                  /* retransmission => do nothing */
1607                                 ret=1;
1608                         else
1609                                 /* some error => return it or DROP */
1610                                 ret=(ser_error==E_BAD_VIA && reply_to_via) ? 0: new_tran;
1611                         goto end;
1612                 }
1613                 t=get_t();
1614                 ret=t_forward_nonack(t, p_msg, proxy, proto);
1615                 goto end;
1616         }
1617         
1618         t_invite=t_lookupOriginalT(  p_msg );
1619         if (t_invite!=T_NULL_CELL) {
1620                 /* create cancel transaction */
1621                 new_tran=t_newtran(p_msg);
1622                 if (new_tran<=0 && new_tran!=E_SCRIPT){
1623                         if (new_tran==0)
1624                                  /* retransmission => do nothing */
1625                                 ret=1;
1626                         else
1627                                 /* some error => return it or DROP */
1628                                 ret=(ser_error==E_BAD_VIA && reply_to_via) ? 0: new_tran;
1629                         UNREF(t_invite);
1630                         goto end;
1631                 }
1632                 t=get_t();
1633                 e2e_cancel( p_msg, t, t_invite );
1634                 UNREF(t_invite);
1635                 ret=1;
1636                 goto end;
1637         }else /* no coresponding INVITE transaction */
1638              if (cfg_get(tm, tm_cfg, unmatched_cancel)==UM_CANCEL_DROP){
1639                                 DBG("t_forward_nonack: non matching cancel dropped\n");
1640                                 ret=1; /* do nothing -> drop */
1641                                 goto end;
1642                  }else{
1643                         /* UM_CANCEL_STATELESS -> stateless forward */
1644                                 DBG( "SER: forwarding CANCEL statelessly \n");
1645                                 if (proxy==0) {
1646                                         init_dest_info(&dst);
1647                                         dst.proto=proto;
1648                                         if (get_uri_send_info(GET_NEXT_HOP(p_msg), &host,
1649                                                                 &port, &dst.proto, &comp)!=0){
1650                                                 ret=E_BAD_ADDRESS;
1651                                                 goto end;
1652                                         }
1653 #ifdef USE_COMP
1654                                         dst.comp=comp;
1655 #endif
1656                                         /* dst->send_sock not set, but forward_request 
1657                                          * will take care of it */
1658                                         ret=forward_request(p_msg, &host, port, &dst);
1659                                         goto end;
1660                                 } else {
1661                                         init_dest_info(&dst);
1662                                         dst.proto=get_proto(proto, proxy->proto);
1663                                         proxy2su(&dst.to, proxy);
1664                                         /* dst->send_sock not set, but forward_request 
1665                                          * will take care of it */
1666                                         ret=forward_request( p_msg , 0, 0, &dst) ;
1667                                         goto end;
1668                                 }
1669                 }
1670 end:
1671         if (tran)
1672                 *tran=t;
1673         return ret;
1674 }
1675
1676 /* Relays a CANCEL request if a corresponding INVITE transaction
1677  * can be found. The function is supposed to be used at the very
1678  * beginning of the script with reparse_invite=1 module parameter.
1679  *
1680  * return value:
1681  *    0: the CANCEL was successfully relayed
1682  *       (or error occured but reply cannot be sent) => DROP
1683  *    1: no corresponding INVITE transaction exisis
1684  *   <0: corresponding INVITE transaction exisis but error occured
1685  */
1686 int t_relay_cancel(struct sip_msg* p_msg)
1687 {
1688         struct cell* t_invite;
1689         struct cell* t;
1690         int ret;
1691         int new_tran;
1692
1693         t_invite=t_lookupOriginalT(  p_msg );
1694         if (t_invite!=T_NULL_CELL) {
1695                 /* create cancel transaction */
1696                 new_tran=t_newtran(p_msg);
1697                 if (new_tran<=0 && new_tran!=E_SCRIPT){
1698                         if (new_tran==0)
1699                                 /* retransmission => DROP,
1700                                 t_newtran() takes care about it */
1701                                 ret=0;
1702                         else
1703                                 /* some error => return it or DROP */
1704                                 ret=(ser_error==E_BAD_VIA && reply_to_via) ? 0: new_tran;
1705                         UNREF(t_invite);
1706                         goto end;
1707                 }
1708                 t=get_t();
1709                 e2e_cancel( p_msg, t, t_invite );
1710                 UNREF(t_invite);
1711                 /* return 0 to stop the script processing */
1712                 ret=0;
1713                 goto end;
1714
1715         } else {
1716                 /* no corresponding INVITE trasaction found */
1717                 ret=1;
1718         }
1719 end:
1720         return ret;
1721 }
1722
1723 /* WARNING: doesn't work from failure route (deadlock, uses t_relay_to which
1724  *  is failure route unsafe) */
1725 int t_replicate(struct sip_msg *p_msg,  struct proxy_l *proxy, int proto )
1726 {
1727         /* this is a quite horrible hack -- we just take the message
1728            as is, including Route-s, Record-route-s, and Vias ,
1729            forward it downstream and prevent replies received
1730            from relaying by setting the replication/local_trans bit;
1731
1732                 nevertheless, it should be good enough for the primary
1733                 customer of this function, REGISTER replication
1734
1735                 if we want later to make it thoroughly, we need to
1736                 introduce delete lumps for all the header fields above
1737         */
1738         return t_relay_to(p_msg, proxy, proto, 1 /* replicate */);
1739 }
1740
1741 /* fixup function for reparse_on_dns_failover modparam */
1742 int reparse_on_dns_failover_fixup(void *handle, str *gname, str *name, void **val)
1743 {
1744 #ifdef USE_DNS_FAILOVER
1745         if ((int)(long)(*val) && mhomed) {
1746                 LOG(L_WARN, "WARNING: reparse_on_dns_failover_fixup:"
1747                 "reparse_on_dns_failover is enabled on a "
1748                 "multihomed host -- check the readme of tm module!\n");
1749         }
1750 #endif
1751         return 0;
1752 }