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