Merge branch 'rpc_async'
[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 executed (Miklos)
82  */
83
84 #include "defs.h"
85
86
87 #include "../../dprint.h"
88 #include "../../config.h"
89 #include "../../parser/parser_f.h"
90 #include "../../ut.h"
91 #include "../../timer.h"
92 #include "../../hash_func.h"
93 #include "../../globals.h"
94 #include "../../cfg_core.h"
95 #include "../../mem/mem.h"
96 #include "../../dset.h"
97 #include "../../action.h"
98 #include "../../data_lump.h"
99 #include "../../onsend.h"
100 #include "../../compiler_opt.h"
101 #include "../../route.h"
102 #include "../../script_cb.h"
103 #include "t_funcs.h"
104 #include "t_hooks.h"
105 #include "t_msgbuilder.h"
106 #include "ut.h"
107 #include "t_cancel.h"
108 #include "t_lookup.h"
109 #include "t_fwd.h"
110 #include "../../fix_lumps.h"
111 #include "config.h"
112 #ifdef USE_DNS_FAILOVER
113 #include "../../dns_cache.h"
114 #include "../../cfg_core.h" /* cfg_get(core, core_cfg, use_dns_failover) */
115 #include "../../msg_translator.h"
116 #include "lw_parser.h"
117 #endif
118 #ifdef USE_DST_BLACKLIST
119 #include "../../dst_blacklist.h"
120 #endif
121 #ifdef POSTPONE_MSG_CLONING
122 #include "../../atomic_ops.h" /* membar_depends() */
123 #endif
124
125 static int goto_on_branch = 0, branch_route = 0;
126
127 void t_on_branch( unsigned int go_to )
128 {
129         struct cell *t = get_t();
130
131        /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction;
132         * in REQUEST_ROUTE T will be set only if the transaction was already
133         * created; if not -> use the static variable */
134         if (!t || t==T_UNDEFINED ) {
135                 goto_on_branch=go_to;
136         } else {
137                 get_t()->on_branch = go_to;
138         }
139 }
140
141 unsigned int get_on_branch(void)
142 {
143         return goto_on_branch;
144 }
145
146
147 static char *print_uac_request( struct cell *t, struct sip_msg *i_req,
148         int branch, str *uri, unsigned int *len, struct dest_info* dst)
149 {
150         char *buf, *shbuf;
151         str* msg_uri;
152         struct lump* add_rm_backup, *body_lumps_backup;
153         struct sip_uri parsed_uri_bak;
154         int parsed_uri_ok_bak, uri_backed_up;
155         str msg_uri_bak;
156         int backup_route_type;
157
158         shbuf=0;
159         msg_uri_bak.s=0; /* kill warnings */
160         msg_uri_bak.len=0;
161         parsed_uri_ok_bak=0;
162         uri_backed_up=0;
163
164         /* ... we calculate branch ... */       
165         if (!t_calc_branch(t, branch, i_req->add_to_branch_s,
166                         &i_req->add_to_branch_len ))
167         {
168                 LOG(L_ERR, "ERROR: print_uac_request: branch computation failed\n");
169                 goto error00;
170         }
171
172         /* ... update uri ... */
173         msg_uri=GET_RURI(i_req);
174         if ((msg_uri->s!=uri->s) || (msg_uri->len!=uri->len)){
175                 msg_uri_bak=i_req->new_uri;
176                 parsed_uri_ok_bak=i_req->parsed_uri_ok;
177                 parsed_uri_bak=i_req->parsed_uri;
178                 i_req->new_uri=*uri;
179                 i_req->parsed_uri_ok=0;
180                 uri_backed_up=1;
181         }
182
183 #ifdef POSTPONE_MSG_CLONING
184         /* lumps can be set outside of the lock, make sure that we read
185          * the up-to-date values */
186         membar_depends();
187 #endif
188         add_rm_backup = i_req->add_rm;
189         body_lumps_backup = i_req->body_lumps;
190         i_req->add_rm = dup_lump_list(i_req->add_rm);
191         i_req->body_lumps = dup_lump_list(i_req->body_lumps);
192
193         if (unlikely(branch_route)) {
194                      /* run branch_route actions if provided */
195                 backup_route_type = get_route_type();
196                 set_route_type(BRANCH_ROUTE);
197                 tm_ctx_set_branch_index(branch+1);
198                 if (exec_pre_script_cb(i_req, BRANCH_CB_TYPE)>0) {
199                         if (run_top_route(branch_rt.rlist[branch_route], i_req, 0) < 0) {
200                                 LOG(L_ERR, "ERROR: print_uac_request: Error in run_top_route\n");
201                         }
202                         exec_post_script_cb(i_req, BRANCH_CB_TYPE);
203                 }               
204                 tm_ctx_set_branch_index(0);
205                 set_route_type(backup_route_type);
206         }
207
208         /* run the specific callbacks for this transaction */
209         if (unlikely(has_tran_tmcbs(t, TMCB_REQUEST_FWDED)))
210                 run_trans_callbacks( TMCB_REQUEST_FWDED , t, i_req, 0,
211                                                                 -i_req->REQ_METHOD);
212
213         /* ... and build it now */
214         buf=build_req_buf_from_sip_req( i_req, len, dst, 0);
215 #ifdef DBG_MSG_QA
216         if (buf[*len-1]==0) {
217                 LOG(L_ERR, "ERROR: print_uac_request: sanity check failed\n");
218                 abort();
219         }
220 #endif
221         if (!buf) {
222                 LOG(L_ERR, "ERROR: print_uac_request: no pkg_mem\n"); 
223                 ser_error=E_OUT_OF_MEM;
224                 goto error01;
225         }
226
227         shbuf=(char *)shm_malloc(*len);
228         if (!shbuf) {
229                 ser_error=E_OUT_OF_MEM;
230                 LOG(L_ERR, "ERROR: print_uac_request: no shmem\n");
231                 goto error02;
232         }
233         memcpy( shbuf, buf, *len );
234
235 error02:
236         pkg_free( buf );
237 error01:
238              /* Delete the duplicated lump lists, this will also delete
239               * all lumps created here, such as lumps created in per-branch
240               * routing sections, Via, and Content-Length headers created in
241               * build_req_buf_from_sip_req
242               */
243         free_duped_lump_list(i_req->add_rm);
244         free_duped_lump_list(i_req->body_lumps);
245              /* Restore the lists from backups */
246         i_req->add_rm = add_rm_backup;
247         i_req->body_lumps = body_lumps_backup;
248         /* restore the new_uri from the backup */
249         if (uri_backed_up){
250                 i_req->new_uri=msg_uri_bak;
251                 i_req->parsed_uri=parsed_uri_bak;
252                 i_req->parsed_uri_ok=parsed_uri_ok_bak;
253         }
254
255  error00:
256         return shbuf;
257 }
258
259 #ifdef USE_DNS_FAILOVER
260 /* Similar to print_uac_request(), but this function uses the outgoing message buffer of
261    the failed branch to construt the new message in case of DNS failover.
262
263    WARNING: only the first VIA header is replaced in the buffer, the rest
264    of the message is untuched, thus, the send socket is corrected only in the VIA HF.
265 */
266 static char *print_uac_request_from_buf( struct cell *t, struct sip_msg *i_req,
267         int branch, str *uri, unsigned int *len, struct dest_info* dst,
268         char *buf, short buf_len)
269 {
270         char *shbuf;
271         str branch_str;
272         char *via, *old_via_begin, *old_via_end;
273         unsigned int via_len;
274
275         shbuf=0;
276
277         /* ... we calculate branch ... */       
278         if (!t_calc_branch(t, branch, i_req->add_to_branch_s,
279                         &i_req->add_to_branch_len ))
280         {
281                 LOG(L_ERR, "ERROR: print_uac_request_from_buf: branch computation failed\n");
282                 goto error00;
283         }
284         branch_str.s = i_req->add_to_branch_s;
285         branch_str.len = i_req->add_to_branch_len;
286
287         /* find the beginning of the first via header in the buffer */
288         old_via_begin = lw_find_via(buf, buf+buf_len);
289         if (!old_via_begin) {
290                 LOG(L_ERR, "ERROR: print_uac_request_from_buf: beginning of via header not found\n");
291                 goto error00;
292         }
293         /* find the end of the first via header in the buffer */
294         old_via_end = lw_next_line(old_via_begin, buf+buf_len);
295         if (!old_via_end) {
296                 LOG(L_ERR, "ERROR: print_uac_request_from_buf: end of via header not found\n");
297                 goto error00;
298         }
299
300         /* create the new VIA HF */
301         via = create_via_hf(&via_len, i_req, dst, &branch_str);
302         if (!via) {
303                 LOG(L_ERR, "ERROR: print_uac_request_from_buf: via building failed\n");
304                 goto error00;
305         }
306
307         /* allocate memory for the new buffer */
308         *len = buf_len + via_len - (old_via_end - old_via_begin);
309         shbuf=(char *)shm_malloc(*len);
310         if (!shbuf) {
311                 ser_error=E_OUT_OF_MEM;
312                 LOG(L_ERR, "ERROR: print_uac_request_from_buf: no shmem\n");
313                 goto error01;
314         }
315
316         /* construct the new buffer */
317         memcpy(shbuf, buf, old_via_begin-buf);
318         memcpy(shbuf+(old_via_begin-buf), via, via_len);
319         memcpy(shbuf+(old_via_begin-buf)+via_len, old_via_end, (buf+buf_len)-old_via_end);
320
321 #ifdef DBG_MSG_QA
322         if (shbuf[*len-1]==0) {
323                 LOG(L_ERR, "ERROR: print_uac_request_from_buf: sanity check failed\n");
324                 abort();
325         }
326 #endif
327
328 error01:
329         pkg_free(via);
330 error00:
331         return shbuf;
332 }
333 #endif
334
335 /* introduce a new uac, which is blind -- it only creates the
336    data structures and starts FR timer, but that's it; it does
337    not print messages and send anything anywhere; that is good
338    for FIFO apps -- the transaction must look operationally
339    and FR must be ticking, whereas the request is "forwarded"
340    using a non-SIP way and will be replied the same way
341 */
342 int add_blind_uac( /*struct cell *t*/ )
343 {
344         unsigned short branch;
345         struct cell *t;
346
347         t=get_t();
348         if (t==T_UNDEFINED || !t ) {
349                 LOG(L_ERR, "ERROR: add_blind_uac: no transaction context\n");
350                 return -1;
351         }
352
353         branch=t->nr_of_outgoings;      
354         if (branch==MAX_BRANCHES) {
355                 LOG(L_ERR, "ERROR: add_blind_uac: "
356                         "maximum number of branches exceeded\n");
357                 return -1;
358         }
359         /* make sure it will be replied */
360         t->flags |= T_NOISY_CTIMER_FLAG;
361         membar_write(); /* to allow lockless prepare_to_cancel() we want to be sure
362                                            all the writes finished before updating branch number*/
363         t->nr_of_outgoings=(branch+1);
364         /* start FR timer -- protocol set by default to PROTO_NONE,
365        which means retransmission timer will not be started
366     */
367         if (start_retr(&t->uac[branch].request)!=0)
368                 LOG(L_CRIT, "BUG: add_blind_uac: start retr failed for %p\n",
369                                 &t->uac[branch].request);
370         /* we are on a timer -- don't need to put on wait on script
371            clean-up     
372         */
373         set_kr(REQ_FWDED); 
374
375         return 1; /* success */
376 }
377
378 /* introduce a new uac to transaction; returns its branch id (>=0)
379    or error (<0); it doesn't send a message yet -- a reply to it
380    might interfere with the processes of adding multiple branches;
381    On error returns <0 & sets ser_error to the same value
382 */
383 int add_uac( struct cell *t, struct sip_msg *request, str *uri, str* next_hop,
384         struct proxy_l *proxy, int proto )
385 {
386
387         int ret;
388         unsigned short branch;
389         char *shbuf;
390         unsigned int len;
391
392         branch=t->nr_of_outgoings;
393         if (branch==MAX_BRANCHES) {
394                 LOG(L_ERR, "ERROR: add_uac: maximum number of branches exceeded\n");
395                 ret=ser_error=E_TOO_MANY_BRANCHES;
396                 goto error;
397         }
398
399         /* check existing buffer -- rewriting should never occur */
400         if (t->uac[branch].request.buffer) {
401                 LOG(L_CRIT, "ERROR: add_uac: buffer rewrite attempt\n");
402                 ret=ser_error=E_BUG;
403                 goto error;
404         }
405
406         /* check DNS resolution */
407         if (proxy){
408                 /* dst filled from the proxy */
409                 init_dest_info(&t->uac[branch].request.dst);
410                 t->uac[branch].request.dst.proto=get_proto(proto, proxy->proto);
411                 proxy2su(&t->uac[branch].request.dst.to, proxy);
412                 /* fill dst send_sock */
413                 t->uac[branch].request.dst.send_sock =
414                 get_send_socket( request, &t->uac[branch].request.dst.to,
415                                                                 t->uac[branch].request.dst.proto);
416                 t->uac[branch].request.dst.send_flags=request?
417                                                                                                 request->fwd_send_flags:0;
418         }else {
419 #ifdef USE_DNS_FAILOVER
420                 if (uri2dst(&t->uac[branch].dns_h, &t->uac[branch].request.dst,
421                                         request, next_hop?next_hop:uri, proto) == 0)
422 #else
423                 /* dst filled from the uri & request (send_socket) */
424                 if (uri2dst(&t->uac[branch].request.dst, request,
425                                                 next_hop ? next_hop: uri, proto)==0)
426 #endif
427                 {
428                         ret=ser_error=E_BAD_ADDRESS;
429                         goto error;
430                 }
431         }
432         
433         /* check if send_sock is ok */
434         if (t->uac[branch].request.dst.send_sock==0) {
435                 LOG(L_ERR, "ERROR: add_uac: can't fwd to af %d, proto %d "
436                         " (no corresponding listening socket)\n",
437                         t->uac[branch].request.dst.to.s.sa_family, 
438                         t->uac[branch].request.dst.proto );
439                 ret=ser_error=E_NO_SOCKET;
440                 goto error01;
441         }
442
443         /* now message printing starts ... */
444         shbuf=print_uac_request( t, request, branch, uri, 
445                                                         &len, &t->uac[branch].request.dst);
446         if (!shbuf) {
447                 ret=ser_error=E_OUT_OF_MEM;
448                 goto error01;
449         }
450
451         /* things went well, move ahead and install new buffer! */
452         t->uac[branch].request.buffer=shbuf;
453         t->uac[branch].request.buffer_len=len;
454         t->uac[branch].uri.s=t->uac[branch].request.buffer+
455                 request->first_line.u.request.method.len+1;
456         t->uac[branch].uri.len=uri->len;
457 #ifdef TM_UAC_FLAGS
458         len = count_applied_lumps(request->add_rm, HDR_RECORDROUTE_T);
459         if(len==1)
460                 t->uac[branch].flags = TM_UAC_FLAG_RR;
461         else if(len==2)
462                 t->uac[branch].flags = TM_UAC_FLAG_RR|TM_UAC_FLAG_R2;
463 #endif
464         getbflagsval(0, &t->uac[branch].branch_flags);
465         membar_write(); /* to allow lockless ops (e.g. prepare_to_cancel()) we want
466                                            to be sure everything above is fully written before
467                                            updating branches no. */
468         t->nr_of_outgoings=(branch+1);
469
470         /* update stats */
471         if (proxy){
472                 proxy_mark(proxy, 1);
473         }
474         /* done! */
475         ret=branch;
476                 
477 error01:
478 error:
479         return ret;
480 }
481
482
483
484 #ifdef USE_DNS_FAILOVER
485 /* Similar to add_uac(), but this function uses the outgoing message buffer of
486    the failed branch to construt the new message in case of DNS failover.
487 */
488 static int add_uac_from_buf( struct cell *t, struct sip_msg *request, str *uri, int proto,
489                         char *buf, short buf_len)
490 {
491
492         int ret;
493         unsigned short branch;
494         char *shbuf;
495         unsigned int len;
496
497         branch=t->nr_of_outgoings;
498         if (branch==MAX_BRANCHES) {
499                 LOG(L_ERR, "ERROR: add_uac_from_buf: maximum number of branches exceeded\n");
500                 ret=ser_error=E_TOO_MANY_BRANCHES;
501                 goto error;
502         }
503
504         /* check existing buffer -- rewriting should never occur */
505         if (t->uac[branch].request.buffer) {
506                 LOG(L_CRIT, "ERROR: add_uac_from_buf: buffer rewrite attempt\n");
507                 ret=ser_error=E_BUG;
508                 goto error;
509         }
510
511         if (uri2dst(&t->uac[branch].dns_h, &t->uac[branch].request.dst,
512                                 request, uri, proto) == 0)
513         {
514                 ret=ser_error=E_BAD_ADDRESS;
515                 goto error;
516         }
517         
518         /* check if send_sock is ok */
519         if (t->uac[branch].request.dst.send_sock==0) {
520                 LOG(L_ERR, "ERROR: add_uac_from_buf: can't fwd to af %d, proto %d "
521                         " (no corresponding listening socket)\n",
522                         t->uac[branch].request.dst.to.s.sa_family, 
523                         t->uac[branch].request.dst.proto );
524                 ret=ser_error=E_NO_SOCKET;
525                 goto error;
526         }
527
528         /* now message printing starts ... */
529         shbuf=print_uac_request_from_buf( t, request, branch, uri, 
530                                                         &len, &t->uac[branch].request.dst,
531                                                         buf, buf_len);
532         if (!shbuf) {
533                 ret=ser_error=E_OUT_OF_MEM;
534                 goto error;
535         }
536
537         /* things went well, move ahead and install new buffer! */
538         t->uac[branch].request.buffer=shbuf;
539         t->uac[branch].request.buffer_len=len;
540         t->uac[branch].uri.s=t->uac[branch].request.buffer+
541                 request->first_line.u.request.method.len+1;
542         t->uac[branch].uri.len=uri->len;
543         membar_write(); /* to allow lockless ops (e.g. prepare_to_cancel()) we want
544                                            to be sure everything above is fully written before
545                                            updating branches no. */
546         t->nr_of_outgoings=(branch+1);
547
548         /* done! */
549         ret=branch;
550                 
551 error:
552         return ret;
553 }
554
555 /* introduce a new uac to transaction, based on old_uac and a possible
556  *  new ip address (if the dns name resolves to more ips). If no more
557  *   ips are found => returns -1.
558  *  returns its branch id (>=0)
559    or error (<0) and sets ser_error if needed; it doesn't send a message 
560    yet -- a reply to it
561    might interfere with the processes of adding multiple branches
562    if lock_replies is 1 replies will be locked for t until the new branch
563    is added (to prevent add branches races). Use 0 if the reply lock is
564    already held, e.g. in failure route/handlers (WARNING: using 1 in a 
565    failure route will cause a deadlock).
566 */
567 int add_uac_dns_fallback( struct cell *t, struct sip_msg* msg, 
568                                                                         struct ua_client* old_uac,
569                                                                         int lock_replies)
570 {
571         int ret;
572         
573         ret=-1;
574         if (cfg_get(core, core_cfg, use_dns_failover) && 
575                         !((t->flags & T_DONT_FORK) || uac_dont_fork(old_uac)) &&
576                         dns_srv_handle_next(&old_uac->dns_h, 0)){
577                         if (lock_replies){
578                                 /* use reply lock to guarantee nobody is adding a branch
579                                  * in the same time */
580                                 LOCK_REPLIES(t);
581                                 /* check again that we can fork */
582                                 if ((t->flags & T_DONT_FORK) || uac_dont_fork(old_uac)){
583                                         UNLOCK_REPLIES(t);
584                                         DBG("add_uac_dns_fallback: no forking on => no new"
585                                                         " branches\n");
586                                         return ret;
587                                 }
588                         }
589                         if (t->nr_of_outgoings >= MAX_BRANCHES){
590                                 LOG(L_ERR, "ERROR: add_uac_dns_fallback: maximum number of "
591                                                         "branches exceeded\n");
592                                 if (lock_replies)
593                                         UNLOCK_REPLIES(t);
594                                         ret=ser_error=E_TOO_MANY_BRANCHES;
595                                 return ret;
596                         }
597                         /* copy the dns handle into the new uac */
598                         dns_srv_handle_cpy(&t->uac[t->nr_of_outgoings].dns_h,
599                                                                 &old_uac->dns_h);
600
601                         if (cfg_get(tm, tm_cfg, reparse_on_dns_failover))
602                                 /* Reuse the old buffer and only replace the via header.
603                                  * The drowback is that the send_socket is not corrected
604                                  * in the rest of the message, only in the VIA HF (Miklos) */
605                                 ret=add_uac_from_buf(t,  msg, &old_uac->uri, 
606                                                         old_uac->request.dst.proto,
607                                                         old_uac->request.buffer,
608                                                         old_uac->request.buffer_len);
609                         else
610                                 /* add_uac will use dns_h => next_hop will be ignored.
611                                  * Unfortunately we can't reuse the old buffer, the branch id
612                                  *  must be changed and the send_socket might be different =>
613                                  *  re-create the whole uac */
614                                 ret=add_uac(t,  msg, &old_uac->uri, 0, 0, 
615                                                         old_uac->request.dst.proto);
616
617                         if (ret<0){
618                                 /* failed, delete the copied dns_h */
619                                 dns_srv_handle_put(&t->uac[t->nr_of_outgoings].dns_h);
620                         }
621                         if (lock_replies){
622                                 UNLOCK_REPLIES(t);
623                         }
624         }
625         return ret;
626 }
627
628 #endif
629
630 int e2e_cancel_branch( struct sip_msg *cancel_msg, struct cell *t_cancel, 
631         struct cell *t_invite, int branch )
632 {
633         int ret;
634         char *shbuf;
635         unsigned int len;
636
637         ret=-1;
638         if (t_cancel->uac[branch].request.buffer) {
639                 LOG(L_CRIT, "ERROR: e2e_cancel_branch: buffer rewrite attempt\n");
640                 ret=ser_error=E_BUG;
641                 goto error;
642         }
643         if (t_invite->uac[branch].request.buffer==0){
644                 /* inactive / deleted  branch */
645                 goto error;
646         }
647         t_invite->uac[branch].request.flags|=F_RB_CANCELED;
648
649         /* note -- there is a gap in proxy stats -- we don't update 
650            proxy stats with CANCEL (proxy->ok, proxy->tx, etc.)
651         */
652
653         /* print */
654         if (cfg_get(tm, tm_cfg, reparse_invite)) {
655                 /* buffer is built localy from the INVITE which was sent out */
656 #ifdef POSTPONE_MSG_CLONING
657                 /* lumps can be set outside of the lock, make sure that we read
658                  * the up-to-date values */
659                 membar_depends();
660 #endif
661                 if (cancel_msg->add_rm || cancel_msg->body_lumps) {
662                         LOG(L_WARN, "WARNING: e2e_cancel_branch: CANCEL is built locally, "
663                         "thus lumps are not applied to the message!\n");
664                 }
665                 shbuf=build_local_reparse( t_invite, branch, &len, CANCEL, CANCEL_LEN, &t_invite->to);
666
667         } else {
668                 /* buffer is constructed from the received CANCEL with applying lumps */
669                 shbuf=print_uac_request( t_cancel, cancel_msg, branch, 
670                                                         &t_invite->uac[branch].uri, &len, 
671                                                         &t_invite->uac[branch].request.dst);
672         }
673
674         if (!shbuf) {
675                 LOG(L_ERR, "ERROR: e2e_cancel_branch: printing e2e cancel failed\n");
676                 ret=ser_error=E_OUT_OF_MEM;
677                 goto error;
678         }
679         
680         /* install buffer */
681         t_cancel->uac[branch].request.dst=t_invite->uac[branch].request.dst;
682         t_cancel->uac[branch].request.buffer=shbuf;
683         t_cancel->uac[branch].request.buffer_len=len;
684         t_cancel->uac[branch].uri.s=t_cancel->uac[branch].request.buffer+
685                 cancel_msg->first_line.u.request.method.len+1;
686         t_cancel->uac[branch].uri.len=t_invite->uac[branch].uri.len;
687         
688
689         /* success */
690         ret=1;
691
692
693 error:
694         return ret;
695 }
696
697 void e2e_cancel( struct sip_msg *cancel_msg, 
698         struct cell *t_cancel, struct cell *t_invite )
699 {
700         branch_bm_t cancel_bm;
701 #ifndef E2E_CANCEL_HOP_BY_HOP
702         branch_bm_t tmp_bm;
703 #endif
704         int i;
705         int lowest_error;
706         int ret;
707         struct tmcb_params tmcb;
708
709         cancel_bm=0;
710         lowest_error=0;
711
712         if (unlikely(has_tran_tmcbs(t_invite, TMCB_E2ECANCEL_IN))){
713                 INIT_TMCB_PARAMS(tmcb, cancel_msg, 0, cancel_msg->REQ_METHOD);
714                 run_trans_callbacks_internal(&t_invite->tmcb_hl, TMCB_E2ECANCEL_IN, 
715                                                                                 t_invite, &tmcb);
716         }
717         /* mark transaction as canceled, so that no new message are forwarded
718          * on it and t_is_canceled() returns true 
719          * WARNING: it's safe to do it without locks, at least for now (in a race
720          * event even if a flag is unwillingly reset nothing bad will happen),
721          * however this should be rechecked for any future new flags use.
722          */
723         t_invite->flags|=T_CANCELED;
724         /* first check if there are any branches */
725         if (t_invite->nr_of_outgoings==0){
726                 /* no branches yet => force a reply to the invite */
727                 t_reply( t_invite, t_invite->uas.request, 487, CANCELED );
728                 DBG("DEBUG: e2e_cancel: e2e cancel -- no more pending branches\n");
729                 t_reply( t_cancel, cancel_msg, 200, CANCEL_DONE );
730                 return;
731         }
732         
733         /* determine which branches to cancel ... */
734         prepare_to_cancel(t_invite, &cancel_bm, 0);
735 #ifdef E2E_CANCEL_HOP_BY_HOP
736         /* we don't need to set t_cancel label to be the same as t_invite if
737          * we do hop by hop cancel. The cancel transaction will have a different 
738          * label, but this is not a problem since this transaction is only used to
739          * send a reply back. The cancels sent upstream will be part of the invite
740          * transaction (local_cancel retr. bufs) and they will be generated with
741          * the same via as the invite.
742          * Note however that setting t_cancel label the same as t_invite will work
743          * too (the upstream cancel replies will properly match the t_invite
744          * transaction and will not match the t_cancel because t_cancel will always
745          * have 0 branches and we check for the branch number in 
746          * t_reply_matching() ).
747          */
748         for (i=0; i<t_invite->nr_of_outgoings; i++)
749                 if (cancel_bm & (1<<i)) {
750                         /* it's safe to get the reply lock since e2e_cancel is
751                          * called with the cancel as the "current" transaction so
752                          * at most t_cancel REPLY_LOCK is held in this process =>
753                          * no deadlock possibility */
754                         ret=cancel_branch(
755                                 t_invite,
756                                 i,
757                                 cfg_get(tm,tm_cfg, cancel_b_flags)
758                                         | ((t_invite->uac[i].request.buffer==NULL)?
759                                                 F_CANCEL_B_FAKE_REPLY:0) /* blind UAC? */
760                         );
761                         if (ret<0) cancel_bm &= ~(1<<i);
762                         if (ret<lowest_error) lowest_error=ret;
763                 }
764 #else /* ! E2E_CANCEL_HOP_BY_HOP */
765         /* fix label -- it must be same for reply matching (the label is part of
766          * the generated via branch for the cancels sent upstream and if it
767          * would be different form the one in the INVITE the transactions would not
768          * match */
769         t_cancel->label=t_invite->label;
770         t_cancel->nr_of_outgoings=t_invite->nr_of_outgoings;
771         /* ... and install CANCEL UACs */
772         for (i=0; i<t_invite->nr_of_outgoings; i++)
773                 if ((cancel_bm & (1<<i)) && (t_invite->uac[i].last_received>=100)) {
774                         ret=e2e_cancel_branch(cancel_msg, t_cancel, t_invite, i);
775                         if (ret<0) cancel_bm &= ~(1<<i);
776                         if (ret<lowest_error) lowest_error=ret;
777                 }
778
779         /* send them out */
780         for (i = 0; i < t_cancel->nr_of_outgoings; i++) {
781                 if (cancel_bm & (1 << i)) {
782                         if (t_invite->uac[i].last_received>=100){
783                                 /* Provisional reply received on this branch, send CANCEL */
784                                 /* we do need to stop the retr. timers if the request is not 
785                                  * an invite and since the stop_rb_retr() cost is lower then
786                                  * the invite check we do it always --andrei */
787                                 stop_rb_retr(&t_invite->uac[i].request);
788                                 if (SEND_BUFFER(&t_cancel->uac[i].request) == -1) {
789                                         LOG(L_ERR, "ERROR: e2e_cancel: send failed\n");
790                                 }
791 #ifdef TMCB_ONSEND
792                                 else{
793                                         if (unlikely(has_tran_tmcbs(t_cancel, TMCB_REQUEST_SENT)))
794                                                 run_onsend_callbacks(TMCB_REQUEST_SENT, 
795                                                                                                 &t_cancel->uac[i].request,
796                                                                                                 cancel_msg, 0, TMCB_LOCAL_F);
797                                 }
798 #endif
799                                 if (start_retr( &t_cancel->uac[i].request )!=0)
800                                         LOG(L_CRIT, "BUG: e2e_cancel: failed to start retr."
801                                                         " for %p\n", &t_cancel->uac[i].request);
802                         } else {
803                                 /* No provisional response received, stop
804                                  * retransmission timers */
805                                 if (!(cfg_get(tm, tm_cfg, cancel_b_flags) & 
806                                                         F_CANCEL_B_FORCE_RETR))
807                                         stop_rb_retr(&t_invite->uac[i].request);
808                                 /* no need to stop fr, it will be stopped by relay_reply
809                                  * put_on_wait -- andrei */
810                                 /* Generate faked reply */
811                                 if (cfg_get(tm, tm_cfg, cancel_b_flags) &
812                                                 F_CANCEL_B_FAKE_REPLY){
813                                         LOCK_REPLIES(t_invite);
814                                         if (relay_reply(t_invite, FAKED_REPLY, i,
815                                                                         487, &tmp_bm, 1) == RPS_ERROR) {
816                                                 lowest_error = -1;
817                                         }
818                                 }
819                         }
820                 }
821         }
822 #endif /*E2E_CANCEL_HOP_BY_HOP */
823
824         /* if error occurred, let it know upstream (final reply
825            will also move the transaction on wait state
826         */
827         if (lowest_error<0) {
828                 LOG(L_ERR, "ERROR: cancel error\n");
829                 /* if called from failure_route, make sure that the unsafe version
830                  * is called (we are already holding the reply mutex for the cancel
831                  * transaction).
832                  */
833                 if ((is_route_type(FAILURE_ROUTE)) && (t_cancel==get_t()))
834                         t_reply_unsafe( t_cancel, cancel_msg, 500, "cancel error");
835                 else
836                         t_reply( t_cancel, cancel_msg, 500, "cancel error");
837         } else if (cancel_bm) {
838                 /* if there are pending branches, let upstream know we
839                    are working on it
840                 */
841                 DBG("DEBUG: e2e_cancel: e2e cancel proceeding\n");
842                 /* if called from failure_route, make sure that the unsafe version
843                  * is called (we are already hold the reply mutex for the cancel
844                  * transaction).
845                  */
846                 if ((is_route_type(FAILURE_ROUTE)) && (t_cancel==get_t()))
847                         t_reply_unsafe( t_cancel, cancel_msg, 200, CANCELING );
848                 else
849                         t_reply( t_cancel, cancel_msg, 200, CANCELING );
850         } else {
851                 /* if the transaction exists, but there are no more pending
852                    branches, tell upstream we're done
853                 */
854                 DBG("DEBUG: e2e_cancel: e2e cancel -- no more pending branches\n");
855                 /* if called from failure_route, make sure that the unsafe version
856                  * is called (we are already hold the reply mutex for the cancel
857                  * transaction).
858                  */
859                 if ((is_route_type(FAILURE_ROUTE)) && (t_cancel==get_t()))
860                         t_reply_unsafe( t_cancel, cancel_msg, 200, CANCEL_DONE );
861                 else
862                         t_reply( t_cancel, cancel_msg, 200, CANCEL_DONE );
863         }
864 }
865
866
867
868 /* sends one uac/branch buffer and fallbacks to other ips if
869  *  the destination resolves to several addresses
870  *  Takes care of starting timers a.s.o. (on send success)
871  *  returns: -2 on error, -1 on drop,  current branch id on success,
872  *   new branch id on send error/blacklist, when failover is possible
873  *    (ret>=0 && ret!=branch)
874  *    if lock_replies is 1, the replies for t will be locked when adding
875  *     new branches (to prevent races). Use 0 from failure routes or other
876  *     places where the reply lock is already held, to avoid deadlocks. */
877 int t_send_branch( struct cell *t, int branch, struct sip_msg* p_msg ,
878                                         struct proxy_l * proxy, int lock_replies)
879 {
880         struct ip_addr ip; /* debugging */
881         int ret;
882         struct ua_client* uac;
883         
884         uac=&t->uac[branch];
885         ret=branch;
886         if (run_onsend(p_msg,   &uac->request.dst, uac->request.buffer,
887                                         uac->request.buffer_len)==0){
888                 /* disable the current branch: set a "fake" timeout
889                  *  reply code but don't set uac->reply, to avoid overriding 
890                  *  a higly unlikely, perfectly timed fake reply (to a message
891                  *   we never sent).
892                  * (code=final reply && reply==0 => t_pick_branch won't ever pick it)*/
893                         uac->last_received=408;
894                         su2ip_addr(&ip, &uac->request.dst.to);
895                         DBG("t_send_branch: onsend_route dropped msg. to %s:%d (%d)\n",
896                                                         ip_addr2a(&ip), su_getport(&uac->request.dst.to),
897                                                         uac->request.dst.proto);
898 #ifdef USE_DNS_FAILOVER
899                         /* if the destination resolves to more ips, add another
900                          *  branch/uac */
901                         if (cfg_get(core, core_cfg, use_dns_failover)){
902                                 ret=add_uac_dns_fallback(t, p_msg, uac, lock_replies);
903                                 if (ret>=0){
904                                         su2ip_addr(&ip, &uac->request.dst.to);
905                                         DBG("t_send_branch: send on branch %d failed "
906                                                         "(onsend_route), trying another ip %s:%d (%d)\n",
907                                                         branch, ip_addr2a(&ip),
908                                                         su_getport(&uac->request.dst.to),
909                                                         uac->request.dst.proto);
910                                         /* success, return new branch */
911                                         return ret;
912                                 }
913                         }
914 #endif /* USE_DNS_FAILOVER*/
915                 return -1; /* drop, try next branch */
916         }
917 #ifdef USE_DST_BLACKLIST
918         if (cfg_get(core, core_cfg, use_dst_blacklist)
919                 && p_msg
920                 && (p_msg->REQ_METHOD & cfg_get(tm, tm_cfg, tm_blst_methods_lookup))
921         ){
922                 if (dst_is_blacklisted(&uac->request.dst, p_msg)){
923                         su2ip_addr(&ip, &uac->request.dst.to);
924                         DBG("t_send_branch: blacklisted destination: %s:%d (%d)\n",
925                                                         ip_addr2a(&ip), su_getport(&uac->request.dst.to),
926                                                         uac->request.dst.proto);
927                         /* disable the current branch: set a "fake" timeout
928                          *  reply code but don't set uac->reply, to avoid overriding 
929                          *  a higly unlikely, perfectly timed fake reply (to a message
930                          *   we never sent).  (code=final reply && reply==0 => 
931                          *   t_pick_branch won't ever pick it)*/
932                         uac->last_received=408;
933 #ifdef USE_DNS_FAILOVER
934                         /* if the destination resolves to more ips, add another
935                          *  branch/uac */
936                         if (cfg_get(core, core_cfg, use_dns_failover)){
937                                 ret=add_uac_dns_fallback(t, p_msg, uac, lock_replies);
938                                 if (ret>=0){
939                                         su2ip_addr(&ip, &uac->request.dst.to);
940                                         DBG("t_send_branch: send on branch %d failed (blacklist),"
941                                                         " trying another ip %s:%d (%d)\n", branch,
942                                                         ip_addr2a(&ip), su_getport(&uac->request.dst.to),
943                                                         uac->request.dst.proto);
944                                         /* success, return new branch */
945                                         return ret;
946                                 }
947                         }
948 #endif /* USE_DNS_FAILOVER*/
949                         return -1; /* don't send */
950                 }
951         }
952 #endif /* USE_DST_BLACKLIST */
953         if (SEND_BUFFER( &uac->request)==-1) {
954                 /* disable the current branch: set a "fake" timeout
955                  *  reply code but don't set uac->reply, to avoid overriding 
956                  *  a highly unlikely, perfectly timed fake reply (to a message
957                  *  we never sent).
958                  * (code=final reply && reply==0 => t_pick_branch won't ever pick it)*/
959                 uac->last_received=408;
960                 su2ip_addr(&ip, &uac->request.dst.to);
961                 DBG("t_send_branch: send to %s:%d (%d) failed\n",
962                                                         ip_addr2a(&ip), su_getport(&uac->request.dst.to),
963                                                         uac->request.dst.proto);
964 #ifdef USE_DST_BLACKLIST
965                 if (cfg_get(core, core_cfg, use_dst_blacklist))
966                         dst_blacklist_add(BLST_ERR_SEND, &uac->request.dst, p_msg);
967 #endif
968 #ifdef USE_DNS_FAILOVER
969                 /* if the destination resolves to more ips, add another
970                  *  branch/uac */
971                 if (cfg_get(core, core_cfg, use_dns_failover)){
972                         ret=add_uac_dns_fallback(t, p_msg, uac, lock_replies);
973                         if (ret>=0){
974                                 /* success, return new branch */
975                                 DBG("t_send_branch: send on branch %d failed, adding another"
976                                                 " branch with another ip\n", branch);
977                                 return ret;
978                         }
979                 }
980 #endif
981                 LOG(L_ERR, "ERROR: t_send_branch: sending request on branch %d "
982                                 "failed\n", branch);
983                 if (proxy) { proxy->errors++; proxy->ok=0; }
984                 return -2;
985         } else {
986 #ifdef TMCB_ONSEND
987                 if (unlikely(has_tran_tmcbs(t, TMCB_REQUEST_SENT)))
988                         run_onsend_callbacks(TMCB_REQUEST_SENT, &uac->request, p_msg, 0,0);
989 #endif
990                 /* start retr. only if the send succeeded */
991                 if (start_retr( &uac->request )!=0){
992                         LOG(L_CRIT, "BUG: t_send_branch: retr. already started for %p\n",
993                                         &uac->request);
994                         return -2;
995                 }
996         }
997         return ret;
998 }
999
1000
1001
1002 /* function returns:
1003  *       1 - forward successful
1004  *      -1 - error during forward
1005  */
1006 int t_forward_nonack( struct cell *t, struct sip_msg* p_msg , 
1007         struct proxy_l * proxy, int proto)
1008 {
1009         int branch_ret, lowest_ret;
1010         str current_uri;
1011         branch_bm_t     added_branches;
1012         int first_branch;
1013         int i, q;
1014         struct cell *t_invite;
1015         int success_branch;
1016         int try_new;
1017         int lock_replies;
1018         str dst_uri;
1019         struct socket_info* si, *backup_si;
1020         flag_t backup_bflags = 0;
1021         flag_t bflags = 0;
1022         
1023
1024         /* make -Wall happy */
1025         current_uri.s=0;
1026
1027         if (t->flags & T_CANCELED){
1028                 DBG("t_forward_non_ack: no forwarding on a canceled transaction\n");
1029                 ser_error=E_CANCELED;
1030                 return -1;
1031         }
1032         if (p_msg->REQ_METHOD==METHOD_CANCEL) { 
1033                 t_invite=t_lookupOriginalT(  p_msg );
1034                 if (t_invite!=T_NULL_CELL) {
1035                         e2e_cancel( p_msg, t, t_invite );
1036                         UNREF(t_invite);
1037                         /* it should be set to REQ_RPLD by e2e_cancel, which should
1038                          * send a final reply */
1039                         set_kr(REQ_FWDED);
1040                         return 1;
1041                 }
1042         }
1043
1044         backup_si = p_msg->force_send_socket;
1045         getbflagsval(0, &backup_bflags);
1046
1047         /* if no more specific error code is known, use this */
1048         lowest_ret=E_UNSPEC;
1049         /* branches added */
1050         added_branches=0;
1051         /* branch to begin with */
1052         first_branch=t->nr_of_outgoings;
1053
1054         if (t->on_branch) {
1055                 /* tell add_uac that it should run branch route actions */
1056                 branch_route = t->on_branch;
1057                 /* reset the flag before running the actions (so that it
1058                  * could be set again in branch_route if needed
1059                  */
1060                 t_on_branch(0);
1061         } else {
1062                 branch_route = 0;
1063         }
1064         
1065         /* on first-time forwarding, use current uri, later only what
1066            is in additional branches (which may be continuously refilled
1067         */
1068         if (first_branch==0) {
1069 #ifdef POSTPONE_MSG_CLONING
1070                 /* update the shmem-ized msg with the lumps */
1071                 if ((is_route_type(REQUEST_ROUTE)) &&
1072                         save_msg_lumps(t->uas.request, p_msg)) {
1073                                 LOG(L_ERR, "ERROR: t_forward_nonack: "
1074                                         "failed to save the message lumps\n");
1075                                 return -1;
1076                         }
1077 #endif
1078                 try_new=1;
1079                 branch_ret=add_uac( t, p_msg, GET_RURI(p_msg), GET_NEXT_HOP(p_msg),
1080                                                         proxy, proto );
1081                 if (branch_ret>=0) 
1082                         added_branches |= 1<<branch_ret;
1083                 else
1084                         lowest_ret=MIN_int(lowest_ret, branch_ret);
1085         } else try_new=0;
1086
1087         init_branch_iterator();
1088         while((current_uri.s=next_branch( &current_uri.len, &q, &dst_uri.s,
1089                                                                                 &dst_uri.len, &si))) {
1090                 try_new++;
1091                 p_msg->force_send_socket = si;
1092                 getbflagsval(get_branch_iterator(), &bflags);
1093                 setbflagsval(0, bflags);
1094
1095                 branch_ret=add_uac( t, p_msg, &current_uri, 
1096                                                         (dst_uri.len) ? (&dst_uri) : &current_uri, 
1097                                                         proxy, proto);
1098                 /* pick some of the errors in case things go wrong;
1099                    note that picking lowest error is just as good as
1100                    any other algorithm which picks any other negative
1101                    branch result */
1102                 if (branch_ret>=0) 
1103                         added_branches |= 1<<branch_ret;
1104                 else
1105                         lowest_ret=MIN_int(lowest_ret, branch_ret);
1106         }
1107         /* consume processed branches */
1108         clear_branches();
1109
1110         p_msg->force_send_socket = backup_si;
1111         setbflagsval(0, backup_bflags);
1112
1113         /* don't forget to clear all branches processed so far */
1114
1115         /* things went wrong ... no new branch has been fwd-ed at all */
1116         if (added_branches==0) {
1117                 if (try_new==0) {
1118                         LOG(L_ERR, "ERROR: t_forward_nonack: no branches for"
1119                                                 " forwarding\n");
1120                         /* either failed to add branches, or there were no more branches
1121                         */
1122                         ser_error=MIN_int(lowest_ret, E_CFG);
1123                         return -1;
1124                 }
1125                 LOG(L_ERR, "ERROR: t_forward_nonack: failure to add branches\n");
1126                 ser_error=lowest_ret;
1127                 return lowest_ret;
1128         }
1129
1130 #ifdef TM_UAC_FLAGS
1131         /* mark the fist branch in this fwd step */
1132         t->uac[first_branch].flags |= TM_UAC_FLAG_FB;
1133 #endif
1134
1135         ser_error=0; /* clear branch adding errors */
1136         /* send them out now */
1137         success_branch=0;
1138         lock_replies= ! ((is_route_type(FAILURE_ROUTE)) && (t==get_t()));
1139         for (i=first_branch; i<t->nr_of_outgoings; i++) {
1140                 if (added_branches & (1<<i)) {
1141                         
1142                         branch_ret=t_send_branch(t, i, p_msg , proxy, lock_replies);
1143                         if (branch_ret>=0){ /* some kind of success */
1144                                 if (branch_ret==i) /* success */
1145                                         success_branch++;
1146                                 else /* new branch added */
1147                                         added_branches |= 1<<branch_ret;
1148                         }
1149                 }
1150         }
1151         if (success_branch<=0) {
1152                 /* return always E_SEND for now
1153                  * (the real reason could be: denied by onsend routes, blacklisted,
1154                  *  send failed or any of the errors listed before + dns failed
1155                  *  when attempting dns failover) */
1156                 ser_error=E_SEND;
1157                 /* else return the last error (?) */
1158                 /* the caller should take care and delete the transaction */
1159                 return -1;
1160         }
1161         ser_error=0; /* clear branch send errors, we have overall success */
1162         set_kr(REQ_FWDED);
1163         return 1;
1164 }
1165
1166
1167
1168 /* cancel handling/forwarding function
1169  * CANCELs with no matching transaction are handled in function of
1170  * the unmatched_cancel config var: they are either forwarded statefully,
1171  * statelessly or dropped.
1172  * function returns:
1173  *       1 - forward successful
1174  *       0 - error, but do not reply 
1175  *      <0 - error during forward
1176  * it also sets *tran if a transaction was created
1177  */
1178 int t_forward_cancel(struct sip_msg* p_msg , struct proxy_l * proxy, int proto,
1179                                                 struct cell** tran)
1180 {
1181         struct cell* t_invite;
1182         struct cell* t;
1183         int ret;
1184         int new_tran;
1185         struct dest_info dst;
1186         str host;
1187         unsigned short port;
1188         short comp;
1189         
1190         t=0;
1191         /* handle cancels for which no transaction was created yet */
1192         if (cfg_get(tm, tm_cfg, unmatched_cancel)==UM_CANCEL_STATEFULL){
1193                 /* create cancel transaction */
1194                 new_tran=t_newtran(p_msg);
1195                 if (new_tran<=0 && new_tran!=E_SCRIPT){
1196                         if (new_tran==0)
1197                                  /* retransmission => do nothing */
1198                                 ret=1;
1199                         else
1200                                 /* some error => return it or DROP */
1201                                 ret=(ser_error==E_BAD_VIA && reply_to_via) ? 0: new_tran;
1202                         goto end;
1203                 }
1204                 t=get_t();
1205                 ret=t_forward_nonack(t, p_msg, proxy, proto);
1206                 goto end;
1207         }
1208         
1209         t_invite=t_lookupOriginalT(  p_msg );
1210         if (t_invite!=T_NULL_CELL) {
1211                 /* create cancel transaction */
1212                 new_tran=t_newtran(p_msg);
1213                 if (new_tran<=0 && new_tran!=E_SCRIPT){
1214                         if (new_tran==0)
1215                                  /* retransmission => do nothing */
1216                                 ret=1;
1217                         else
1218                                 /* some error => return it or DROP */
1219                                 ret=(ser_error==E_BAD_VIA && reply_to_via) ? 0: new_tran;
1220                         UNREF(t_invite);
1221                         goto end;
1222                 }
1223                 t=get_t();
1224                 e2e_cancel( p_msg, t, t_invite );
1225                 UNREF(t_invite);
1226                 ret=1;
1227                 goto end;
1228         }else /* no coresponding INVITE transaction */
1229              if (cfg_get(tm, tm_cfg, unmatched_cancel)==UM_CANCEL_DROP){
1230                                 DBG("t_forward_nonack: non matching cancel dropped\n");
1231                                 ret=1; /* do nothing -> drop */
1232                                 goto end;
1233                  }else{
1234                         /* UM_CANCEL_STATELESS -> stateless forward */
1235                                 DBG( "SER: forwarding CANCEL statelessly \n");
1236                                 if (proxy==0) {
1237                                         init_dest_info(&dst);
1238                                         dst.proto=proto;
1239                                         if (get_uri_send_info(GET_NEXT_HOP(p_msg), &host,
1240                                                                 &port, &dst.proto, &comp)!=0){
1241                                                 ret=E_BAD_ADDRESS;
1242                                                 goto end;
1243                                         }
1244 #ifdef USE_COMP
1245                                         dst.comp=comp;
1246 #endif
1247                                         /* dst->send_sock not set, but forward_request 
1248                                          * will take care of it */
1249                                         ret=forward_request(p_msg, &host, port, &dst);
1250                                         goto end;
1251                                 } else {
1252                                         init_dest_info(&dst);
1253                                         dst.proto=get_proto(proto, proxy->proto);
1254                                         proxy2su(&dst.to, proxy);
1255                                         /* dst->send_sock not set, but forward_request 
1256                                          * will take care of it */
1257                                         ret=forward_request( p_msg , 0, 0, &dst) ;
1258                                         goto end;
1259                                 }
1260                 }
1261 end:
1262         if (tran)
1263                 *tran=t;
1264         return ret;
1265 }
1266
1267 /* Relays a CANCEL request if a corresponding INVITE transaction
1268  * can be found. The function is supposed to be used at the very
1269  * beginning of the script with reparse_invite=1 module parameter.
1270  *
1271  * return value:
1272  *    0: the CANCEL was successfully relayed
1273  *       (or error occured but reply cannot be sent) => DROP
1274  *    1: no corresponding INVITE transaction exisis
1275  *   <0: corresponding INVITE transaction exisis but error occured
1276  */
1277 int t_relay_cancel(struct sip_msg* p_msg)
1278 {
1279         struct cell* t_invite;
1280         struct cell* t;
1281         int ret;
1282         int new_tran;
1283
1284         t_invite=t_lookupOriginalT(  p_msg );
1285         if (t_invite!=T_NULL_CELL) {
1286                 /* create cancel transaction */
1287                 new_tran=t_newtran(p_msg);
1288                 if (new_tran<=0 && new_tran!=E_SCRIPT){
1289                         if (new_tran==0)
1290                                 /* retransmission => DROP,
1291                                 t_newtran() takes care about it */
1292                                 ret=0;
1293                         else
1294                                 /* some error => return it or DROP */
1295                                 ret=(ser_error==E_BAD_VIA && reply_to_via) ? 0: new_tran;
1296                         UNREF(t_invite);
1297                         goto end;
1298                 }
1299                 t=get_t();
1300                 e2e_cancel( p_msg, t, t_invite );
1301                 UNREF(t_invite);
1302                 /* return 0 to stop the script processing */
1303                 ret=0;
1304                 goto end;
1305
1306         } else {
1307                 /* no corresponding INVITE trasaction found */
1308                 ret=1;
1309         }
1310 end:
1311         return ret;
1312 }
1313
1314 /* WARNING: doesn't work from failure route (deadlock, uses t_relay_to which
1315  *  is failure route unsafe) */
1316 int t_replicate(struct sip_msg *p_msg,  struct proxy_l *proxy, int proto )
1317 {
1318         /* this is a quite horrible hack -- we just take the message
1319            as is, including Route-s, Record-route-s, and Vias ,
1320            forward it downstream and prevent replies received
1321            from relaying by setting the replication/local_trans bit;
1322
1323                 nevertheless, it should be good enough for the primary
1324                 customer of this function, REGISTER replication
1325
1326                 if we want later to make it thoroughly, we need to
1327                 introduce delete lumps for all the header fields above
1328         */
1329         return t_relay_to(p_msg, proxy, proto, 1 /* replicate */);
1330 }
1331
1332 /* fixup function for reparse_on_dns_failover modparam */
1333 int reparse_on_dns_failover_fixup(void *handle, str *gname, str *name, void **val)
1334 {
1335 #ifdef USE_DNS_FAILOVER
1336         if ((int)(long)(*val) && mhomed) {
1337                 LOG(L_WARN, "WARNING: reparse_on_dns_failover_fixup:"
1338                 "reparse_on_dns_failover is enabled on a "
1339                 "multihomed host -- check the readme of tm module!\n");
1340         }
1341 #endif
1342         return 0;
1343 }