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