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