tm: Reason header generation for local CANCELs
[sip-router] / modules / tm / t_cancel.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  * History:
29  * ----------
30  * 2003-04-14  checking if a reply sent before cancel is initiated
31  *             moved here (jiri)
32  * 2004-02-11  FIFO/CANCEL + alignments (hash=f(callid,cseq)) (uli+jiri)
33  * 2004-02-13  timer_link.payload removed (bogdan)
34  * 2006-10-10  cancel_uacs  & cancel_branch take more options now (andrei)
35  * 2007-03-15  TMCB_ONSEND hooks added (andrei)
36  * 2007-05-28: cancel_branch() constructs the CANCEL from the
37  *             outgoing INVITE instead of the incomming one.
38  *             (it can be disabled with reparse_invite=0) (Miklos)
39  * 2007-06-04  cancel_branch() can operate in lockless mode (with a lockless
40  *              should_cancel()) (andrei)
41  * 2008-03-07  cancel_branch() takes a new flag: F_CANCEL_B_FORCE_RETR (andrei)
42  * 2008-03-08  e2e_cancel handles non replied branches in 3 different ways,
43  *              selectable by the tm cancel_b_method parameter: fake reply,
44  *              retransmit request and send cancel on branch (andrei)
45  * 2009-07-14  renamed which_cancel() to prepare_to_cancel() for better
46  *              reflecting its purpose
47  *             prepare_to_cancel() takes now an additional skip_branches
48  *              bitmap parameter (andrei)
49  * 2010-02-26  cancel reason (rfc3326) basic support (andrei)
50  */
51
52 #include <stdio.h> /* for FILE* in fifo_uac_cancel */
53 #ifdef EXTRA_DEBUG
54 #include <assert.h>
55 #endif /* EXTRA_DEBUG */
56
57 #include "defs.h"
58 #include "config.h"
59
60 #include "t_funcs.h"
61 #include "../../dprint.h"
62 #include "../../ut.h"
63 #include "t_reply.h"
64 #include "t_cancel.h"
65 #include "t_msgbuilder.h"
66 #include "t_lookup.h" /* for t_lookup_callid in fifo_uac_cancel */
67 #include "t_hooks.h"
68
69
70 /** Prepare to cancel a transaction.
71  * Determine which branches should be canceled and prepare them (internally
72  * mark them as "cancel in progress", see prepare_cancel_branch()).
73  * Can be called without REPLY_LOCK, since prepare_cancel_branch() is atomic 
74  *  now *  -- andrei
75  * WARNING: - has side effects, see prepare_cancel_branch()
76  *          - one _must_ call cancel_uacs(cancel_bm) if *cancel_bm!=0 or
77  *             you'll have some un-cancelable branches (because they remain
78  *             "marked" internally)
79  * @param t - transaction whose branches will be canceled
80  * @param cancel_bm - pointer to a branch bitmap that will be filled with
81 *    the branches that must be canceled (must be passed to cancel_uacs() if
82 *    !=0).
83 *  @param skip - branch bitmap of branches that should not be canceled
84 */
85 void prepare_to_cancel(struct cell *t, branch_bm_t *cancel_bm,
86                                                 branch_bm_t skip_branches)
87 {
88         int i;
89         int branches_no;
90         branch_bm_t mask;
91         
92         *cancel_bm=0;
93         branches_no=t->nr_of_outgoings;
94         mask=~skip_branches;
95         membar_depends(); 
96         for( i=0 ; i<branches_no ; i++ ) {
97                 *cancel_bm |= ((mask & (1<<i)) &&  prepare_cancel_branch(t, i, 1))<<i;
98         }
99 }
100
101
102
103
104 /* cancel branches scheduled for deletion
105  * params: t          - transaction
106  *          cancel_data - structure filled with the cancel bitmap (bitmap with
107  *                       the branches that are supposed to be canceled) and
108  *                       the cancel reason.
109  *          flags     - how_to_cancel flags, see cancel_branch()
110  * returns: bitmap with the still active branches (on fr timer)
111  * WARNING: always fill cancel_data->cancel_bitmap using prepare_to_cancel(),
112  *          supplying values in any other way is a bug*/
113 int cancel_uacs( struct cell *t, struct cancel_info* cancel_data, int flags)
114 {
115         int i;
116         int ret;
117         int r;
118
119         ret=0;
120         /* cancel pending client transactions, if any */
121         for( i=0 ; i<t->nr_of_outgoings ; i++ ) 
122                 if (cancel_data->cancel_bitmap & (1<<i)){
123                         r=cancel_branch(
124                                 t,
125                                 i,
126                                 &cancel_data->reason,
127                                 flags | ((t->uac[i].request.buffer==NULL)?
128                                         F_CANCEL_B_FAKE_REPLY:0) /* blind UAC? */
129                         );
130                         ret|=(r!=0)<<i;
131                 }
132         return ret;
133 }
134
135 int cancel_all_uacs(struct cell *trans, int how)
136 {
137         struct cancel_info cancel_data;
138         int i,j;
139
140 #ifdef EXTRA_DEBUG
141         assert(trans);
142 #endif
143         DBG("Canceling T@%p [%u:%u]\n", trans, trans->hash_index, trans->label);
144         
145         init_cancel_info(&cancel_data);
146         prepare_to_cancel(trans, &cancel_data.cancel_bitmap, 0);
147          /* tell tm to cancel the call */
148         i=cancel_uacs(trans, &cancel_data, how);
149         
150         if (how & F_CANCEL_UNREF)
151 #ifndef TM_DEL_UNREF
152         /* in case of 'too many' _buggy_ invocations, the ref count (a uint) might 
153          * actually wrap around, possibly leaving the T leaking. */
154 #warning "use of F_CANCEL_UNREF flag is unsafe without defining TM_DEL_UNREF"
155 #endif
156                 UNREF(trans);
157
158         /* count the still active branches */
159         if (! how) {
160                 j=0;
161                 while(i){
162                         j++;
163                         i&=i-1;
164                 }
165                 return j;
166         }
167         return 0;
168 }
169
170
171 /* should be called directly only if one of the condition bellow is true:
172  *  - prepare_cancel_branch or prepare_to_cancel returned true for this branch
173  *  - buffer value was 0 and then set to BUSY in an atomic op.:
174  *     if (atomic_cmpxchg_long(&buffer, 0, BUSY_BUFFER)==0).
175  *
176  * params:  t - transaction
177  *          branch - branch number to be canceled
178  *          reason - cancel reason structure
179  *          flags - howto cancel: 
180  *                   F_CANCEL_B_KILL - will completely stop the 
181  *                     branch (stops the timers), use with care
182  *                   F_CANCEL_B_FAKE_REPLY - will send a fake 487
183  *                      to all branches that haven't received any response
184  *                      (>=100). It assumes the REPLY_LOCK is not held
185  *                      (if it is => deadlock)
186  *                  F_CANCEL_B_FORCE_C - will send a cancel (and create the 
187  *                       corresp. local cancel rb) even if no reply was 
188  *                       received; F_CANCEL_B_FAKE_REPLY will be ignored.
189  *                  F_CANCEL_B_FORCE_RETR - don't stop retransmission if no 
190  *                       reply was received on the branch; incompatible
191  *                       with F_CANCEL_B_FAKE_REPLY, F_CANCEL_B_FORCE_C and
192  *                       F_CANCEL_B_KILL (all of them take precedence) a
193  *                  default: stop only the retransmissions for the branch
194  *                      and leave it to timeout if it doesn't receive any
195  *                      response to the CANCEL
196  * returns: 0 - branch inactive after running cancel_branch() 
197  *          1 - branch still active  (fr_timer)
198  *         -1 - error
199  * WARNING:
200  *          - F_CANCEL_B_KILL should be used only if the transaction is killed
201  *            explicitly afterwards (since it might kill all the timers
202  *            the transaction won't be able to "kill" itself => if not
203  *            explicitly "put_on_wait" it might live forever)
204  *          - F_CANCEL_B_FAKE_REPLY must be used only if the REPLY_LOCK is not
205  *            held
206  *          - checking for buffer==0 under REPLY_LOCK is no enough, an 
207  *           atomic_cmpxhcg or atomic_get_and_set _must_ be used.
208  */
209 int cancel_branch( struct cell *t, int branch, struct cancel_reason* reason,
210                                         int flags )
211 {
212         char *cancel;
213         unsigned int len;
214         struct retr_buf *crb, *irb;
215         int ret;
216         struct cancel_info tmp_cd;
217         void* pcbuf;
218
219         crb=&t->uac[branch].local_cancel;
220         irb=&t->uac[branch].request;
221         irb->flags|=F_RB_CANCELED;
222         ret=1;
223
224 #       ifdef EXTRA_DEBUG
225         if (crb->buffer!=BUSY_BUFFER) {
226                 LOG(L_CRIT, "ERROR: attempt to rewrite cancel buffer: %p\n",
227                                 crb->buffer);
228                 abort();
229         }
230 #       endif
231
232         if (flags & F_CANCEL_B_KILL){
233                 stop_rb_timers( irb );
234                 ret=0;
235                 if ((t->uac[branch].last_received < 100) &&
236                                 !(flags & F_CANCEL_B_FORCE_C)) {
237                         DBG("DEBUG: cancel_branch: no response ever received: "
238                             "giving up on cancel\n");
239                         /* remove BUSY_BUFFER -- mark cancel buffer as not used */
240                         pcbuf=&crb->buffer; /* workaround for type punning warnings */
241                         atomic_set_long(pcbuf, 0);
242                         if (flags & F_CANCEL_B_FAKE_REPLY){
243                                 LOCK_REPLIES(t);
244                                 if (relay_reply(t, FAKED_REPLY, branch, 487, &tmp_cd, 1) == 
245                                                                                 RPS_ERROR){
246                                         return -1;
247                                 }
248                         }
249                         /* do nothing, hope that the caller will clean up */
250                         return ret;
251                 }
252         }else{
253                 if (t->uac[branch].last_received < 100){
254                         if (!(flags & F_CANCEL_B_FORCE_C)) {
255                                 /* no response received => don't send a cancel on this branch,
256                                  *  just drop it */
257                                 if (!(flags & F_CANCEL_B_FORCE_RETR))
258                                         stop_rb_retr(irb); /* stop retransmissions */
259                                 /* remove BUSY_BUFFER -- mark cancel buffer as not used */
260                                 pcbuf=&crb->buffer; /* workaround for type punning warnings */
261                                 atomic_set_long(pcbuf, 0);
262                                 if (flags & F_CANCEL_B_FAKE_REPLY){
263                                         stop_rb_timers( irb ); /* stop even the fr timer */
264                                         LOCK_REPLIES(t);
265                                         if (relay_reply(t, FAKED_REPLY, branch, 487, &tmp_cd, 1)== 
266                                                                                         RPS_ERROR){
267                                                 return -1;
268                                         }
269                                         return 0; /* should be inactive after the 487 */
270                                 }
271                                 /* do nothing, just wait for the final timeout */
272                                 return 1;
273                         }
274                 }
275                 stop_rb_retr(irb); /* stop retransmissions */
276         }
277
278         if (cfg_get(tm, tm_cfg, reparse_invite)) {
279                 /* build the CANCEL from the INVITE which was sent out */
280                 cancel = build_local_reparse(t, branch, &len, CANCEL, CANCEL_LEN,
281                                                                          &t->to, reason);
282         } else {
283                 /* build the CANCEL from the reveived INVITE */
284                 cancel = build_local(t, branch, &len, CANCEL, CANCEL_LEN, &t->to,
285                                                          reason);
286         }
287         if (!cancel) {
288                 LOG(L_ERR, "ERROR: attempt to build a CANCEL failed\n");
289                 /* remove BUSY_BUFFER -- mark cancel buffer as not used */
290                 pcbuf=&crb->buffer; /* workaround for type punning warnings */
291                 atomic_set_long(pcbuf, 0);
292                 return -1;
293         }
294         /* install cancel now */
295         crb->dst = irb->dst;
296         crb->branch = branch;
297         /* label it as cancel so that FR timer can better know how to
298            deal with it */
299         crb->activ_type = TYPE_LOCAL_CANCEL;
300         /* be extra carefully and check for bugs (the below if could be replaced
301          *  by an atomic_set((void*)&crb->buffer, cancel) */
302         if (unlikely(atomic_cmpxchg_long((void*)&crb->buffer, (long)BUSY_BUFFER,
303                                                         (long)cancel)!= (long)BUSY_BUFFER)){
304                 BUG("tm: cancel_branch: local_cancel buffer=%p != BUSY_BUFFER"
305                                 " (trying to continue)\n", crb->buffer);
306                 shm_free(cancel);
307                 return -1;
308         }
309         membar_write_atomic_op(); /* cancel retr. can be called from 
310                                                                  reply_received w/o the reply lock held => 
311                                                                  they check for buffer_len to 
312                                                                  see if a valid reply exists */
313         crb->buffer_len = len;
314
315         DBG("DEBUG: cancel_branch: sending cancel...\n");
316 #ifdef TMCB_ONSEND
317         if (SEND_BUFFER( crb )>=0){
318                 if (unlikely (has_tran_tmcbs(t, TMCB_REQUEST_SENT)))
319                         run_onsend_callbacks(TMCB_REQUEST_SENT, crb, 0, 0, TMCB_LOCAL_F);
320         }
321 #else
322         SEND_BUFFER( crb );
323 #endif
324         /*sets and starts the FINAL RESPONSE timer */
325         if (start_retr( crb )!=0)
326                 LOG(L_CRIT, "BUG: cancel_branch: failed to start retransmission"
327                                         " for %p\n", crb);
328         return ret;
329 }
330
331
332 const char* rpc_cancel_doc[2] = {
333         "Cancel a pending transaction",
334         0
335 };
336
337
338 /* fifo command to cancel a pending call (Uli)
339  * Syntax:
340  *
341  * ":uac_cancel:[response file]\n
342  * callid\n
343  * cseq\n
344  */
345 void rpc_cancel(rpc_t* rpc, void* c)
346 {
347         struct cell *trans;
348         static char cseq[128], callid[128];
349         struct cancel_info cancel_data;
350         int i,j;
351
352         str cseq_s;   /* cseq */
353         str callid_s; /* callid */
354
355         cseq_s.s=cseq;
356         callid_s.s=callid;
357         init_cancel_info(&cancel_data);
358
359         if (rpc->scan(c, "SS", &callid_s, &cseq_s) < 2) {
360                 rpc->fault(c, 400, "Callid and CSeq expected as parameters");
361                 return;
362         }
363
364         if( t_lookup_callid(&trans, callid_s, cseq_s) < 0 ) {
365                 DBG("Lookup failed\n");
366                 rpc->fault(c, 400, "Transaction not found");
367                 return;
368         }
369         /*  find the branches that need cancel-ing */
370         prepare_to_cancel(trans, &cancel_data.cancel_bitmap, 0);
371          /* tell tm to cancel the call */
372         DBG("Now calling cancel_uacs\n");
373         i=cancel_uacs(trans, &cancel_data, 0); /* don't fake 487s, 
374                                                                                  just wait for timeout */
375         
376         /* t_lookup_callid REF`d the transaction for us, we must UNREF here! */
377         UNREF(trans);
378         j=0;
379         while(i){
380                 j++;
381                 i&=i-1;
382         }
383         rpc->add(c, "ds", j, "branches remaining (waiting for timeout)");
384 }
385
386
387
388 /* returns <0 on error */
389 int cancel_b_flags_get(unsigned int* f, int m)
390 {
391         int ret;
392         
393         ret=0;
394         switch(m){
395                 case 1:
396                         *f=F_CANCEL_B_FORCE_RETR;
397                         break;
398                 case 0:
399                         *f=F_CANCEL_B_FAKE_REPLY;
400                         break;
401                 case 2:
402                         *f=F_CANCEL_B_FORCE_C;
403                         break;
404                 default:
405                         *f=F_CANCEL_B_FAKE_REPLY;
406                         ret=-1;
407         }
408         return ret;
409 }
410
411
412
413 /* fixup function for the default cancel branch method/flags
414  * (called by the configuration framework) */
415 int cancel_b_flags_fixup(void* handle, str* gname, str* name, void** val)
416 {
417         unsigned int m,f;
418         int ret;
419         
420         m=(unsigned int)(long)(*val);
421         ret=cancel_b_flags_get(&f, m);
422         if (ret<0)
423                 ERR("cancel_b_flags_fixup: invalid value for %.*s; %d\n",
424                                 name->len, name->s, m);
425         *val=(void*)(long)f;
426         return ret;
427 }
428
429
430
431