Destination blacklist parameters have been updated to the config
[sip-router] / modules / tm / t_reply.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-01-19  faked lump list created in on_reply handlers
31  *  2003-01-27  next baby-step to removing ZT - PRESERVE_ZT (jiri)
32  *  2003-02-13  updated to use rb->dst (andrei)
33  *  2003-02-18  replaced TOTAG_LEN w/ TOTAG_VALUE_LEN (TOTAG_LEN was defined
34  *               twice with different values!)  (andrei)
35  *  2003-02-28  scratchpad compatibility abandoned (jiri)
36  *  2003-03-01  kr set through a function now (jiri)
37  *  2003-03-06  saving of to-tags for ACK/200 matching introduced,
38  *              voicemail changes accepted, updated to new callback
39  *              names (jiri)
40  *  2003-03-10  fixed new to tag bug/typo (if w/o {})  (andrei)
41  *  2003-03-16  removed _TOTAG (jiri)
42  *  2003-03-31  200 for INVITE/UAS resent even for UDP (jiri)
43  *  2003-03-31  removed msg->repl_add_rm (andrei)
44  *  2003-04-05  s/reply_route/failure_route, onreply_route introduced (jiri)
45  *  2003-04-14  local acks generated before reply processing to avoid
46  *              delays in length reply processing (like opening TCP
47  *              connection to an unavailable destination) (jiri)
48  *  2003-09-11  updates to new build_res_buf_from_sip_req() interface (bogdan)
49  *  2003-09-11  t_reply_with_body() reshaped to use reply_lumps +
50  *              build_res_buf_from_sip_req() instead of
51  *              build_res_buf_with_body_from_sip_req() (bogdan)
52  *  2003-11-05  flag context updated from failure/reply handlers back
53  *              to transaction context (jiri)
54  *  2003-11-11: build_lump_rpl() removed, add_lump_rpl() has flags (bogdan)
55  *  2003-12-04  global TM callbacks switched to per transaction callbacks
56  *              (bogdan)
57  *  2004-02-06: support for user pref. added - destroy_avps (bogdan)
58  *  2003-11-05  flag context updated from failure/reply handlers back
59  *              to transaction context (jiri)
60  *  2003-11-11: build_lump_rpl() removed, add_lump_rpl() has flags (bogdan)
61  *  2004-02-13: t->is_invite and t->local replaced with flags (bogdan)
62  *  2004-02-18  fifo_t_reply imported from vm module (bogdan)
63  *  2004-08-23  avp list is available from failure/on_reply routes (bogdan)
64  *  2004-10-01  added a new param.: restart_fr_on_each_reply (andrei)
65  *  2005-03-01  force for statefull replies the incoming interface of
66  *              the request (bogdan)
67  *  2005-09-01  reverted to the old way of checking response.dst.send_sock
68  *               in t_retransmit_reply & reply_light (andrei)
69  *  2005-11-09  updated to the new timers interface (andrei)
70  *  2006-02-07  named routes support (andrei)
71  *  2006-09-13  t_pick_branch will skip also over branches with empty reply 
72  *              t_should_relay_response will re-pick the branch if failure 
73  *               route /handlers added new branches (andrei)
74  * 2006-10-05  better final reply selection: t_pick_branch will prefer 6xx,
75  *              if no 6xx reply => lowest class/code; if class==4xx =>
76  *              prefer 401, 407, 415, 420 and 484   (andrei)
77  * 2006-10-12  dns failover when a 503 is received
78  *              replace a 503 final relayed reply by a 500 (andrei)
79  * 2006-10-16  aggregate all the authorization headers/challenges when
80  *               the final response is 401 or 407 (andrei)
81  * 2007-03-08  membar_write() used in update_totag_set(...)(andrei)
82  * 2007-03-15  build_local_ack: removed next_hop and replaced with dst to 
83  *              avoid resolving next_hop twice
84  *              added TMCB_ONSEND callbacks support for replies & ACKs (andrei)
85  * 2007-05-28: build_ack() constructs the ACK from the
86  *             outgoing INVITE instead of the incomming one.
87  *             (it can be disabled with reparse_invite=0) (Miklos)
88  *
89  */
90
91
92
93 #include "../../comp_defs.h"
94 #include "../../hash_func.h"
95 #include "../../dprint.h"
96 #include "../../config.h"
97 #include "../../parser/parser_f.h"
98 #include "../../ut.h"
99 #include "../../timer.h"
100 #include "../../error.h"
101 #include "../../action.h"
102 #include "../../dset.h"
103 #include "../../tags.h"
104 #include "../../data_lump.h"
105 #include "../../data_lump_rpl.h"
106 #include "../../usr_avp.h"
107 #include "../../atomic_ops.h" /* membar_write() */
108 #include "../../compiler_opt.h"
109 #include "../../select_buf.h" /* reset_static_buffer() */
110 #ifdef USE_DST_BLACKLIST
111 #include "../../dst_blacklist.h"
112 #endif
113
114 #include "defs.h"
115 #include "h_table.h"
116 #include "t_hooks.h"
117 #include "t_funcs.h"
118 #include "t_reply.h"
119 #include "t_cancel.h"
120 #include "t_msgbuilder.h"
121 #include "t_lookup.h"
122 #include "t_fwd.h"
123 #include "fix_lumps.h"
124 #include "t_stats.h"
125 #include "uac.h"
126
127
128 /* restart fr timer on each provisional reply, default yes */
129 int restart_fr_on_each_reply=1;
130 /* if the final reponse is a 401 or a 407, aggregate all the 
131  * authorization headers (challenges) (rfc3261 requires this to be on) */
132 int tm_aggregate_auth=1;
133
134 /* if 1 blacklist 503 sources, using tm_blst_503_min, tm_blst_503_max,
135  * tm_blst_503_default and the Retry-After header in the 503 reply */
136 int tm_blst_503=0;
137 /* default 503 blacklist time (when no Retry-After header is present */
138 #ifndef DEFAULT_BLST_TIMEOUT
139 #define DEFAULT_BLST_TIMEOUT 60
140 #endif
141 int tm_blst_503_default=0; /* rfc conformant: do not blacklist if 
142                                                           no retry-after */
143 /* minimum 503 blacklist time */
144 int tm_blst_503_min=0; /* in s */
145 /* maximum 503 blacklist time */
146 int tm_blst_503_max=3600; /* in s */
147
148 /* backlist only INVITE timeouts by default */
149 unsigned int tm_blst_methods_add=METHOD_INVITE;
150 /* look-up the blacklist for every method except BYE by default */
151 unsigned int tm_blst_methods_lookup=~METHOD_BYE;
152
153 /* are we processing original or shmemed request ? */
154 enum route_mode rmode=MODE_REQUEST;
155
156 /* private place where we create to-tags for replies */
157 /* janakj: made public, I need to access this value to store it in dialogs */
158 char tm_tags[TOTAG_VALUE_LEN];
159 /* bogdan: pack tm_tag buffer and len into a str to pass them to
160  * build_res_buf_from_sip_req() */
161 static str  tm_tag = {tm_tags,TOTAG_VALUE_LEN};
162 char *tm_tag_suffix;
163
164 /* where to go if there is no positive reply */
165 static int goto_on_negative=0;
166 /* where to go on receipt of reply */
167 static int goto_on_reply=0;
168
169
170 /* responses priority (used by t_pick_branch)
171  *  0xx is used only for the initial value (=> should have no chance to be
172  *  selected => the highest value); 1xx is not used */
173 static unsigned short resp_class_prio[]={
174                         32000, /* 0-99, special */
175                         11000, /* 1xx, special, should never be used */
176                                 0,  /* 2xx, high priority (not used, 2xx are immediately 
177                                        forwarded and t_pick_branch will never be called if
178                                            a 2xx was received) */
179                         3000,  /* 3xx */
180                         4000,  /* 4xx */
181                         5000,  /* 5xx */
182                         1000   /* 6xx, highest priority */
183 };
184
185
186
187 /* we store the reply_route # in private memory which is
188    then processed during t_relay; we cannot set this value
189    before t_relay creates transaction context or after
190    t_relay when a reply may arrive after we set this
191    value; that's why we do it how we do it, i.e.,
192    *inside*  t_relay using hints stored in private memory
193    before t_relay is called
194 */
195
196
197 void t_on_negative( unsigned int go_to )
198 {
199         struct cell *t = get_t();
200
201         /* in MODE_REPLY and MODE_ONFAILURE T will be set to current transaction;
202          * in MODE_REQUEST T will be set only if the transaction was already
203          * created; if not -> use the static variable */
204         if (!t || t==T_UNDEFINED )
205                 goto_on_negative=go_to;
206         else
207                 get_t()->on_negative = go_to;
208 }
209
210
211 void t_on_reply( unsigned int go_to )
212 {
213         struct cell *t = get_t();
214
215         /* in MODE_REPLY and MODE_ONFAILURE T will be set to current transaction;
216          * in MODE_REQUEST T will be set only if the transaction was already
217          * created; if not -> use the static variable */
218         if (!t || t==T_UNDEFINED )
219                 goto_on_reply=go_to;
220         else
221                 get_t()->on_reply = go_to;
222 }
223
224
225 unsigned int get_on_negative()
226 {
227         return goto_on_negative;
228 }
229 unsigned int get_on_reply()
230 {
231         return goto_on_reply;
232 }
233
234 void tm_init_tags()
235 {
236         init_tags(tm_tags, &tm_tag_suffix,
237                 "SER-TM/tags", TM_TAG_SEPARATOR );
238 }
239
240 /* returns 0 if the message was previously acknowledged
241  * (i.e., no E2EACK callback is needed) and one if the
242  * callback shall be executed */
243 int unmatched_totag(struct cell *t, struct sip_msg *ack)
244 {
245         struct totag_elem *i;
246         str *tag;
247
248         if (parse_headers(ack, HDR_TO_F,0)==-1 ||
249                                 !ack->to ) {
250                 LOG(L_ERR, "ERROR: unmatched_totag: To invalid\n");
251                 return 1;
252         }
253         tag=&get_to(ack)->tag_value;
254         i=t->fwded_totags;
255         while(i){
256                 membar_depends(); /* make sure we don't see some old i content
257                                                         (needed on CPUs like Alpha) */
258                 if (i->tag.len==tag->len
259                                 && memcmp(i->tag.s, tag->s, tag->len)==0) {
260                         DBG("DEBUG: totag for e2e ACK found: %d\n", i->acked);
261                         /* to-tag recorded, and an ACK has been received for it */
262                         if (i->acked) return 0;
263                         /* to-tag recorded, but this ACK came for the first time */
264                         i->acked=1;
265                         return 1;
266                 }
267                 i=i->next;
268         }
269         /* surprising: to-tag never sighted before */
270         return 1;
271 }
272
273 static inline void update_local_tags(struct cell *trans,
274                                 struct bookmark *bm, char *dst_buffer,
275                                 char *src_buffer /* to which bm refers */)
276 {
277         if (bm->to_tag_val.s) {
278                 trans->uas.local_totag.s=bm->to_tag_val.s-src_buffer+dst_buffer;
279                 trans->uas.local_totag.len=bm->to_tag_val.len;
280         }
281 }
282
283
284 /* append a newly received tag from a 200/INVITE to
285  * transaction's set; (only safe if called from within
286  * a REPLY_LOCK); it returns 1 if such a to tag already
287  * exists
288  */
289 inline static int update_totag_set(struct cell *t, struct sip_msg *ok)
290 {
291         struct totag_elem *i, *n;
292         str *tag;
293         char *s;
294
295         if (!ok->to || !ok->to->parsed) {
296                 LOG(L_ERR, "ERROR: update_totag_set: to not parsed\n");
297                 return 0;
298         }
299         tag=&get_to(ok)->tag_value;
300         if (!tag->s) {
301                 DBG("ERROR: update_totag_set: no tag in to\n");
302                 return 0;
303         }
304
305         for (i=t->fwded_totags; i; i=i->next) {
306                 if (i->tag.len==tag->len
307                                 && memcmp(i->tag.s, tag->s, tag->len) ==0 ){
308                         /* to tag already recorded */
309 #ifdef XL_DEBUG
310                         LOG(L_CRIT, "DEBUG: update_totag_set: totag retransmission\n");
311 #else
312                         DBG("DEBUG: update_totag_set: totag retransmission\n");
313 #endif
314                         return 1;
315                 }
316         }
317         /* that's a new to-tag -- record it */
318         shm_lock();
319         n=(struct totag_elem*) shm_malloc_unsafe(sizeof(struct totag_elem));
320         s=(char *)shm_malloc_unsafe(tag->len);
321         shm_unlock();
322         if (!s || !n) {
323                 LOG(L_ERR, "ERROR: update_totag_set: no  memory \n");
324                 if (n) shm_free(n);
325                 if (s) shm_free(s);
326                 return 0;
327         }
328         memset(n, 0, sizeof(struct totag_elem));
329         memcpy(s, tag->s, tag->len );
330         n->tag.s=s;n->tag.len=tag->len;
331         n->next=t->fwded_totags;
332         membar_write(); /* make sure all the changes to n are visible on all cpus
333                                            before we update t->fwded_totags. This is needed for
334                                            three reasons: the compiler might reorder some of the 
335                                            writes, the cpu/cache could also reorder them with
336                                            respect to the visibility on other cpus
337                                            (e.g. some of the changes to n could be visible on
338                                             another cpu _after_ seeing t->fwded_totags=n) and
339                                            the "readers" (unmatched_tags()) do not use locks and
340                                            can be called simultaneously on another cpu.*/
341         t->fwded_totags=n;
342         DBG("DEBUG: update_totag_set: new totag \n");
343         return 0;
344 }
345
346
347 /*
348  * Build an ACK to a negative reply
349  */
350 static char *build_ack(struct sip_msg* rpl,struct cell *trans,int branch,
351         unsigned int *ret_len)
352 {
353         str to;
354
355     if (parse_headers(rpl,HDR_TO_F, 0)==-1 || !rpl->to ) {
356         LOG(L_ERR, "ERROR: build_ack: "
357             "cannot generate a HBH ACK if key HFs in reply missing\n");
358         return NULL;
359     }
360         to.s=rpl->to->name.s;
361         to.len=rpl->to->len;
362
363         if (reparse_invite) {
364                 /* build the ACK from the INVITE which was sent out */
365                 return build_local_reparse( trans, branch, ret_len,
366                                         ACK, ACK_LEN, &to );
367         } else {
368                 /* build the ACK from the reveived INVITE */
369                 return build_local( trans, branch, ret_len,
370                                         ACK, ACK_LEN, &to );
371         }
372 }
373
374
375 /*
376  * The function builds an ACK to 200 OK of local transactions, honoring the
377  * route set.
378  * The destination to which the message should be sent will be returned
379  * in the dst parameter.
380  * returns 0 on error and a pkg_malloc'ed buffer with length in ret_len
381  *  and intended destination in dst on success.
382  */
383 static char *build_local_ack(struct sip_msg* rpl, struct cell *trans, 
384                                                                 int branch, unsigned int *ret_len,
385                                                                 struct dest_info*  dst)
386 {
387         str to;
388         if (parse_headers(rpl, HDR_EOH_F, 0) == -1 || !rpl->to) {
389                 LOG(L_ERR, "ERROR: build_local_ack: Error while parsing headers\n");
390                 return 0;
391         }
392
393         to.s = rpl->to->name.s;
394         to.len = rpl->to->len;
395         return build_dlg_ack(rpl, trans, branch, &to, ret_len, dst);
396 }
397
398
399
400 #if 0 /* candidate for removal --andrei */
401      /*
402       * The function is used to send a localy generated ACK to INVITE
403       * (tm generates the ACK on behalf of application using UAC
404       */
405 static int send_local_ack(struct sip_msg* msg, str* next_hop,
406                                                         char* ack, int ack_len)
407 {
408         struct dest_info dst;
409 #ifdef USE_DNS_FAILOVER
410         struct dns_srv_handle dns_h;
411 #endif
412
413         if (!next_hop) {
414                 LOG(L_ERR, "send_local_ack: Invalid parameter value\n");
415                 return -1;
416         }
417 #ifdef USE_DNS_FAILOVER
418         if (use_dns_failover){
419                 dns_srv_handle_init(&dns_h);
420                 if ((uri2dst(&dns_h, &dst, msg,  next_hop, PROTO_NONE)==0) || 
421                                 (dst.send_sock==0)){
422                         dns_srv_handle_put(&dns_h);
423                         LOG(L_ERR, "send_local_ack: no socket found\n");
424                         return -1;
425                 }
426                 dns_srv_handle_put(&dns_h); /* not needed anymore */
427         }else{
428                 if ((uri2dst(0, &dst, msg,  next_hop, PROTO_NONE)==0) || 
429                                 (dst.send_sock==0)){
430                         LOG(L_ERR, "send_local_ack: no socket found\n");
431                         return -1;
432                 }
433         }
434 #else
435         if ((uri2dst(&dst, msg,  next_hop, PROTO_NONE)==0) || (dst.send_sock==0)){
436                 LOG(L_ERR, "send_local_ack: no socket found\n");
437                 return -1;
438         }
439 #endif
440         return msg_send(&dst, ack, ack_len);
441 }
442 #endif
443
444
445
446 static int _reply_light( struct cell *trans, char* buf, unsigned int len,
447                          unsigned int code, char * text,
448                          char *to_tag, unsigned int to_tag_len, int lock,
449                          struct bookmark *bm    )
450 {
451         struct retr_buf *rb;
452         unsigned int buf_len;
453         branch_bm_t cancel_bitmap;
454 #ifdef TMCB_ONSEND
455         struct tmcb_params onsend_params;
456 #endif
457
458         if (!buf)
459         {
460                 DBG("DEBUG: _reply_light: response building failed\n");
461                 /* determine if there are some branches to be canceled */
462                 if ( is_invite(trans) ) {
463                         if (lock) LOCK_REPLIES( trans );
464                         which_cancel(trans, &cancel_bitmap );
465                         if (lock) UNLOCK_REPLIES( trans );
466                 }
467                 /* and clean-up, including cancellations, if needed */
468                 goto error;
469         }
470
471         cancel_bitmap=0;
472         if (lock) LOCK_REPLIES( trans );
473         if ( is_invite(trans) ) which_cancel(trans, &cancel_bitmap );
474         if (trans->uas.status>=200) {
475                 LOG( L_ERR, "ERROR: _reply_light: can't generate %d reply"
476                         " when a final %d was sent out\n", code, trans->uas.status);
477                 goto error2;
478         }
479
480         rb = & trans->uas.response;
481         rb->activ_type=code;
482
483         trans->uas.status = code;
484         buf_len = rb->buffer ? len : len + REPLY_OVERBUFFER_LEN;
485         rb->buffer = (char*)shm_resize( rb->buffer, buf_len );
486         /* puts the reply's buffer to uas.response */
487         if (! rb->buffer ) {
488                         LOG(L_ERR, "ERROR: _reply_light: cannot allocate shmem buffer\n");
489                         goto error3;
490         }
491         update_local_tags(trans, bm, rb->buffer, buf);
492
493         rb->buffer_len = len ;
494         memcpy( rb->buffer , buf , len );
495         /* needs to be protected too because what timers are set depends
496            on current transactions status */
497         /* t_update_timers_after_sending_reply( rb ); */
498         update_reply_stats( code );
499         trans->relayed_reply_branch=-2;
500         t_stats_replied_locally();
501         if (lock) UNLOCK_REPLIES( trans );
502
503         /* do UAC cleanup procedures in case we generated
504            a final answer whereas there are pending UACs */
505         if (code>=200) {
506                 if ( is_local(trans) ) {
507                         DBG("DEBUG: local transaction completed from _reply\n");
508                         if ( unlikely(has_tran_tmcbs(trans, TMCB_LOCAL_COMPLETED)) )
509                                 run_trans_callbacks( TMCB_LOCAL_COMPLETED, trans,
510                                         0, FAKED_REPLY, code);
511                 } else {
512                         if ( unlikely(has_tran_tmcbs(trans, TMCB_RESPONSE_OUT)) )
513                                 run_trans_callbacks( TMCB_RESPONSE_OUT, trans,
514                                         trans->uas.request, FAKED_REPLY, code);
515                 }
516
517                 cleanup_uac_timers( trans );
518                 if (is_invite(trans)) 
519                         cancel_uacs( trans, cancel_bitmap, F_CANCEL_B_KILL );
520                 set_final_timer(  trans );
521         }
522
523         /* send it out */
524         /* first check if we managed to resolve topmost Via -- if
525            not yet, don't try to retransmit
526         */
527         /*
528            response.dst.send_sock might be unset if the process that created
529            the original transaction has not finished initialising the
530            retransmission buffer (see t_newtran/ init_rb).
531            If reply_to_via is set and via contains a host name (and not an ip)
532            the chances for this increase a lot.
533          */
534         if (!trans->uas.response.dst.send_sock) {
535                 LOG(L_ERR, "ERROR: _reply_light: no resolved dst to send reply to\n");
536         } else {
537 #ifdef TMCB_ONSEND
538                 if (SEND_PR_BUFFER( rb, buf, len )>=0)
539                         if (unlikely(has_tran_tmcbs(trans, TMCB_RESPONSE_SENT))){
540                                 INIT_TMCB_ONSEND_PARAMS(onsend_params, 0, 0, rb, &rb->dst, 
541                                                                 buf, len, TMCB_LOCAL_F, rb->branch, code);
542                                 run_onsend_callbacks2(TMCB_RESPONSE_SENT, trans,
543                                                                                 &onsend_params);
544                         }
545 #else
546                 SEND_PR_BUFFER( rb, buf, len );
547 #endif
548                 DBG("DEBUG: reply sent out. buf=%p: %.9s..., shmem=%p: %.9s\n",
549                         buf, buf, rb->buffer, rb->buffer );
550         }
551         pkg_free( buf ) ;
552         DBG("DEBUG: _reply_light: finished\n");
553         return 1;
554
555 error3:
556 error2:
557         if (lock) UNLOCK_REPLIES( trans );
558         pkg_free ( buf );
559 error:
560         /* do UAC cleanup */
561         cleanup_uac_timers( trans );
562         if ( is_invite(trans) )
563                 cancel_uacs( trans, cancel_bitmap, F_CANCEL_B_KILL);
564         /* we did not succeed -- put the transaction on wait */
565         put_on_wait(trans);
566         return -1;
567 }
568
569
570 /* send a UAS reply
571  * returns 1 if everything was OK or -1 for error
572  */
573 static int _reply( struct cell *trans, struct sip_msg* p_msg,
574         unsigned int code, char * text, int lock )
575 {
576         unsigned int len;
577         char * buf, *dset;
578         struct bookmark bm;
579         int dset_len;
580
581         if (code>=200) set_kr(REQ_RPLD);
582         /* compute the buffer in private memory prior to entering lock;
583          * create to-tag if needed */
584
585         /* if that is a redirection message, dump current message set to it */
586         if (code>=300 && code<400) {
587                 dset=print_dset(p_msg, &dset_len);
588                 if (dset) {
589                         add_lump_rpl(p_msg, dset, dset_len, LUMP_RPL_HDR);
590                 }
591         }
592
593         if (code>=180 && p_msg->to
594                                 && (get_to(p_msg)->tag_value.s==0
595                             || get_to(p_msg)->tag_value.len==0)) {
596                 calc_crc_suffix( p_msg, tm_tag_suffix );
597                 buf = build_res_buf_from_sip_req(code,text, &tm_tag, p_msg, &len, &bm);
598                 return _reply_light( trans, buf, len, code, text,
599                         tm_tag.s, TOTAG_VALUE_LEN, lock, &bm);
600         } else {
601                 buf = build_res_buf_from_sip_req(code,text, 0 /*no to-tag*/,
602                         p_msg, &len, &bm);
603
604                 return _reply_light(trans,buf,len,code,text,
605                         0, 0, /* no to-tag */lock, &bm);
606         }
607 }
608
609
610 /*if msg is set -> it will fake the env. vars conforming with the msg; if NULL
611  * the env. will be restore to original */
612 static inline void faked_env( struct cell *t,struct sip_msg *msg)
613 {
614         static enum route_mode backup_mode;
615         static struct cell *backup_t;
616         static unsigned int backup_msgid;
617         static avp_list_t* backup_user_from, *backup_user_to;
618         static avp_list_t* backup_domain_from, *backup_domain_to;
619         static avp_list_t* backup_uri_from, *backup_uri_to;
620         static struct socket_info* backup_si;
621
622         if (msg) {
623                 /* remember we are back in request processing, but process
624                  * a shmem-ed replica of the request; advertise it in rmode;
625                  * for example t_reply needs to know that
626                  */
627                 backup_mode=rmode;
628                 rmode=MODE_ONFAILURE;
629                 /* also, tm actions look in beginning whether transaction is
630                  * set -- whether we are called from a reply-processing
631                  * or a timer process, we need to set current transaction;
632                  * otherwise the actions would attempt to look the transaction
633                  * up (unnecessary overhead, refcounting)
634                  */
635                 /* backup */
636                 backup_t=get_t();
637                 backup_msgid=global_msg_id;
638                 /* fake transaction and message id */
639                 global_msg_id=msg->id;
640                 set_t(t);
641                 /* make available the avp list from transaction */
642
643                 backup_uri_from = set_avp_list(AVP_TRACK_FROM | AVP_CLASS_URI, &t->uri_avps_from );
644                 backup_uri_to = set_avp_list(AVP_TRACK_TO | AVP_CLASS_URI, &t->uri_avps_to );
645                 backup_user_from = set_avp_list(AVP_TRACK_FROM | AVP_CLASS_USER, &t->user_avps_from );
646                 backup_user_to = set_avp_list(AVP_TRACK_TO | AVP_CLASS_USER, &t->user_avps_to );
647                 backup_domain_from = set_avp_list(AVP_TRACK_FROM | AVP_CLASS_DOMAIN, &t->domain_avps_from );
648                 backup_domain_to = set_avp_list(AVP_TRACK_TO | AVP_CLASS_DOMAIN, &t->domain_avps_to );
649                 /* set default send address to the saved value */
650                 backup_si=bind_address;
651                 bind_address=t->uac[0].request.dst.send_sock;
652         } else {
653                 /* restore original environment */
654                 set_t(backup_t);
655                 global_msg_id=backup_msgid;
656                 rmode=backup_mode;
657                 /* restore original avp list */
658                 set_avp_list(AVP_TRACK_FROM | AVP_CLASS_USER, backup_user_from );
659                 set_avp_list(AVP_TRACK_TO | AVP_CLASS_USER, backup_user_to );
660                 set_avp_list(AVP_TRACK_FROM | AVP_CLASS_DOMAIN, backup_domain_from );
661                 set_avp_list(AVP_TRACK_TO | AVP_CLASS_DOMAIN, backup_domain_to );
662                 set_avp_list(AVP_TRACK_FROM | AVP_CLASS_URI, backup_uri_from );
663                 set_avp_list(AVP_TRACK_TO | AVP_CLASS_URI, backup_uri_to );
664                 bind_address=backup_si;
665         }
666 }
667
668
669 static inline int fake_req(struct sip_msg *faked_req,
670                                                         struct sip_msg *shmem_msg, int extra_flags)
671 {
672         /* on_negative_reply faked msg now copied from shmem msg (as opposed
673          * to zero-ing) -- more "read-only" actions (exec in particular) will
674          * work from reply_route as they will see msg->from, etc.; caution,
675          * rw actions may append some pkg stuff to msg, which will possibly be
676          * never released (shmem is released in a single block) */
677         memcpy( faked_req, shmem_msg, sizeof(struct sip_msg));
678
679         /* if we set msg_id to something different from current's message
680          * id, the first t_fork will properly clean new branch URIs */
681         faked_req->id=shmem_msg->id-1;
682         /* msg->parsed_uri_ok must be reset since msg_parsed_uri is
683          * not cloned (and cannot be cloned) */
684         faked_req->parsed_uri_ok = 0;
685         
686         faked_req->msg_flags|=extra_flags; /* set the extra tm flags */
687         /* new_uri can change -- make a private copy */
688         if (shmem_msg->new_uri.s!=0 && shmem_msg->new_uri.len!=0) {
689                 faked_req->new_uri.s=pkg_malloc(shmem_msg->new_uri.len+1);
690                 if (!faked_req->new_uri.s) {
691                         LOG(L_ERR, "ERROR: fake_req: no uri/pkg mem\n");
692                         goto error00;
693                 }
694                 faked_req->new_uri.len=shmem_msg->new_uri.len;
695                 memcpy( faked_req->new_uri.s, shmem_msg->new_uri.s,
696                         faked_req->new_uri.len);
697                 faked_req->new_uri.s[faked_req->new_uri.len]=0;
698         }
699         /* dst_uri can change ALSO!!! -- make a private copy */
700         if (shmem_msg->dst_uri.s!=0 && shmem_msg->dst_uri.len!=0) {
701                 faked_req->dst_uri.s=pkg_malloc(shmem_msg->dst_uri.len+1);
702                 if (!faked_req->dst_uri.s) {
703                         LOG(L_ERR, "ERROR: fake_req: no uri/pkg mem\n");
704                         goto error00;
705                 }
706                 faked_req->dst_uri.len=shmem_msg->dst_uri.len;
707                 memcpy( faked_req->dst_uri.s, shmem_msg->dst_uri.s,
708                         faked_req->dst_uri.len);
709                 faked_req->dst_uri.s[faked_req->dst_uri.len]=0;
710         }
711
712         return 1;
713 error00:
714         return 0;
715 }
716
717 void inline static free_faked_req(struct sip_msg *faked_req, struct cell *t)
718 {
719         struct hdr_field *hdr;
720
721         if (faked_req->new_uri.s) {
722                 pkg_free(faked_req->new_uri.s);
723                 faked_req->new_uri.s = 0;
724         }
725
726         if (faked_req->dst_uri.s) {
727                 pkg_free(faked_req->dst_uri.s);
728                 faked_req->dst_uri.s = 0;
729         }
730
731         /* free all types of lump that were added in failure handlers */
732         del_nonshm_lump( &(faked_req->add_rm) );
733         del_nonshm_lump( &(faked_req->body_lumps) );
734         del_nonshm_lump_rpl( &(faked_req->reply_lump) );
735
736         /* free header's parsed structures that were added by failure handlers */
737         for( hdr=faked_req->headers ; hdr ; hdr=hdr->next ) {
738                 if ( hdr->parsed && hdr_allocs_parse(hdr) &&
739                 (hdr->parsed<(void*)t->uas.request ||
740                 hdr->parsed>=(void*)t->uas.end_request)) {
741                         /* header parsed filed doesn't point inside uas.request memory
742                          * chunck -> it was added by failure funcs.-> free it as pkg */
743                         DBG("DBG:free_faked_req: removing hdr->parsed %d\n",
744                                         hdr->type);
745                         clean_hdr_field(hdr);
746                         hdr->parsed = 0;
747                 }
748         }
749 }
750
751
752 /* return 1 if a failure_route processes */
753 int run_failure_handlers(struct cell *t, struct sip_msg *rpl,
754                                         int code, int extra_flags)
755 {
756         static struct sip_msg faked_req;
757         struct sip_msg *shmem_msg = t->uas.request;
758         int on_failure;
759         struct run_act_ctx ra_ctx;
760
761         /* failure_route for a local UAC? */
762         if (!shmem_msg) {
763                 LOG(L_WARN,"Warning: run_failure_handlers: no UAC support (%d, %d) \n",
764                         t->on_negative, t->tmcb_hl.reg_types);
765                 return 0;
766         }
767
768         /* don't start faking anything if we don't have to */
769         if (unlikely(!t->on_negative && !has_tran_tmcbs( t, TMCB_ON_FAILURE))) {
770                 LOG(L_WARN,
771                         "Warning: run_failure_handlers: no negative handler (%d, %d)\n",
772                         t->on_negative,
773                         t->tmcb_hl.reg_types);
774                 return 1;
775         }
776
777         if (!fake_req(&faked_req, shmem_msg, extra_flags)) {
778                 LOG(L_ERR, "ERROR: run_failure_handlers: fake_req failed\n");
779                 return 0;
780         }
781         /* fake also the env. conforming to the fake msg */
782         faked_env( t, &faked_req);
783         /* DONE with faking ;-) -> run the failure handlers */
784
785         if (unlikely(has_tran_tmcbs( t, TMCB_ON_FAILURE)) ) {
786                 run_trans_callbacks( TMCB_ON_FAILURE, t, &faked_req, rpl, code);
787         }
788         if (t->on_negative) {
789                 /* avoid recursion -- if failure_route forwards, and does not
790                  * set next failure route, failure_route will not be reentered
791                  * on failure */
792                 on_failure = t->on_negative;
793                 t->on_negative=0;
794                 reset_static_buffer();
795                 /* run a reply_route action if some was marked */
796                 init_run_actions_ctx(&ra_ctx);
797                 if (run_actions(&ra_ctx, failure_rt.rlist[on_failure], &faked_req)<0)
798                         LOG(L_ERR, "ERROR: run_failure_handlers: Error in do_action\n");
799         }
800
801         /* restore original environment and free the fake msg */
802         faked_env( t, 0);
803         free_faked_req(&faked_req,t);
804
805         /* if failure handler changed flag, update transaction context */
806         shmem_msg->flags = faked_req.flags;
807         return 1;
808 }
809
810
811
812 /* 401, 407, 415, 420, and 484 have priority over the other 4xx*/
813 inline static short int get_4xx_prio(unsigned char xx)
814 {
815         switch(xx){
816                 case  1:
817                 case  7:
818                 case 15:
819                 case 20:
820                 case 84:
821                         return xx;
822                         break;
823         }
824         return 100+xx;
825 }
826
827
828
829 /* returns response priority, lower number => highest prio
830  *
831  * responses                    priority val
832  *  0-99                        32000+reponse         (special)
833  *  1xx                         11000+reponse         (special)
834  *  700-999                     10000+response        (very low)
835  *  5xx                          5000+xx              (low)
836  *  4xx                          4000+xx
837  *  3xx                          3000+xx
838  *  6xx                          1000+xx              (high)
839  *  2xx                          0000+xx              (highest) 
840  */
841 inline static short int get_prio(unsigned int resp)
842 {
843         int class;
844         int xx;
845         
846         class=resp/100;
847
848         if (class<7){
849                 xx=resp%100;
850                 return resp_class_prio[class]+((class==4)?get_4xx_prio(xx):xx);
851         }
852         return 10000+resp; /* unknown response class => return very low prio */
853 }
854
855
856
857 /* select a branch for forwarding; returns:
858  * 0..X ... branch number
859  * -1   ... error
860  * -2   ... can't decide yet -- incomplete branches present
861  */
862 int t_pick_branch(int inc_branch, int inc_code, struct cell *t, int *res_code)
863 {
864         int best_b, best_s, b;
865
866         best_b=-1; best_s=0;
867         for ( b=0; b<t->nr_of_outgoings ; b++ ) {
868                 /* "fake" for the currently processed branch */
869                 if (b==inc_branch) {
870                         if (get_prio(inc_code)<get_prio(best_s)) {
871                                 best_b=b;
872                                 best_s=inc_code;
873                         }
874                         continue;
875                 }
876                 /* skip 'empty branches' */
877                 if (!t->uac[b].request.buffer) continue;
878                 /* there is still an unfinished UAC transaction; wait now! */
879                 if ( t->uac[b].last_received<200 )
880                         return -2;
881                 /* if reply is null => t_send_branch "faked" reply, skip over it */
882                 if ( t->uac[b].reply && 
883                                 get_prio(t->uac[b].last_received)<get_prio(best_s) ) {
884                         best_b =b;
885                         best_s = t->uac[b].last_received;
886                 }
887         } /* find lowest branch */
888         
889         *res_code=best_s;
890         return best_b;
891 }
892
893
894
895 /* This is the neurological point of reply processing -- called
896  * from within a REPLY_LOCK, t_should_relay_response decides
897  * how a reply shall be processed and how transaction state is
898  * affected.
899  *
900  * Checks if the new reply (with new_code status) should be sent or not
901  *  based on the current
902  * transaction status.
903  * Returns      - branch number (0,1,...) which should be relayed
904  *         -1 if nothing to be relayed
905  */
906 static enum rps t_should_relay_response( struct cell *Trans , int new_code,
907         int branch , int *should_store, int *should_relay,
908         branch_bm_t *cancel_bitmap, struct sip_msg *reply )
909 {
910         int branch_cnt;
911         int picked_branch;
912         int picked_code;
913         int new_branch;
914         int inv_through;
915         int extra_flags;
916
917         /* note: this code never lets replies to CANCEL go through;
918            we generate always a local 200 for CANCEL; 200s are
919            not relayed because it's not an INVITE transaction;
920            >= 300 are not relayed because 200 was already sent
921            out
922         */
923         DBG("->>>>>>>>> T_code=%d, new_code=%d\n",Trans->uas.status,new_code);
924         inv_through=new_code>=200 && new_code<300 && is_invite(Trans);
925         /* if final response sent out, allow only INVITE 2xx  */
926         if ( Trans->uas.status >= 200 ) {
927                 if (inv_through) {
928                         DBG("DBG: t_should_relay_response: 200 INV after final sent\n");
929                         *should_store=0;
930                         Trans->uac[branch].last_received=new_code;
931                         *should_relay=branch;
932                         return RPS_PUSHED_AFTER_COMPLETION;
933                 }
934                 /* except the exception above, too late  messages will
935                    be discarded */
936                 goto discard;
937         }
938
939         /* if final response received at this branch, allow only INVITE 2xx */
940         if (Trans->uac[branch].last_received>=200
941                         && !(inv_through && Trans->uac[branch].last_received<300)) {
942                 /* don't report on retransmissions */
943                 if (Trans->uac[branch].last_received==new_code) {
944                         DBG("DEBUG: final reply retransmission\n");
945                         goto discard;
946                 }
947                 /* if you FR-timed-out, faked a local 408  and 487 came or
948                  *  faked a CANCEL on a non-replied branch don't
949                  * report on it either */
950                 if ((Trans->uac[branch].last_received==487) || 
951                                 (Trans->uac[branch].last_received==408 && new_code==487)) {
952                         DBG("DEBUG: %d came for a %d branch (ignored)\n",
953                                         new_code, Trans->uac[branch].last_received);
954                         goto discard;
955                 }
956                 /* this looks however how a very strange status rewrite attempt;
957                  * report on it */
958                 LOG(L_ERR, "ERROR: t_should_relay_response: status rewrite by UAS: "
959                         "stored: %d, received: %d\n",
960                         Trans->uac[branch].last_received, new_code );
961                 goto discard;
962         }
963
964
965         /* no final response sent yet */
966         /* negative replies subject to fork picking */
967         if (new_code >=300 ) {
968
969                 Trans->uac[branch].last_received=new_code;
970
971                 /* if all_final return lowest */
972                 picked_branch=t_pick_branch(branch,new_code, Trans, &picked_code);
973                 if (picked_branch==-2) { /* branches open yet */
974                         *should_store=1;
975                         *should_relay=-1;
976                         if (new_code>=600 && new_code<=699){
977                                 if (!(Trans->flags & T_6xx)){
978                                         /* cancel only the first time we get a 6xx */
979                                         which_cancel(Trans, cancel_bitmap);
980                                         Trans->flags|=T_6xx;
981                                 }
982                         }
983                         return RPS_STORE;
984                 }
985                 if (picked_branch==-1) {
986                         LOG(L_CRIT, "ERROR: t_should_relay_response: lowest==-1\n");
987                         goto error;
988                 }
989
990                 /* no more pending branches -- try if that changes after
991                    a callback; save branch count to be able to determine
992                    later if new branches were initiated */
993                 branch_cnt=Trans->nr_of_outgoings;
994                 /* also append the current reply to the transaction to
995                  * make it available in failure routes - a kind of "fake"
996                  * save of the final reply per branch */
997                 Trans->uac[branch].reply = reply;
998                 Trans->flags&=~T_6xx; /* clear the 6xx flag , we want to 
999                                                                  allow new branches from the failure route */
1000
1001                 /* run ON_FAILURE handlers ( route and callbacks) */
1002                 if (unlikely(has_tran_tmcbs( Trans, TMCB_ON_FAILURE_RO|TMCB_ON_FAILURE)
1003                                                 || Trans->on_negative )) {
1004                         extra_flags=
1005                                 ((Trans->uac[picked_branch].request.flags & F_RB_TIMEOUT)?
1006                                                         FL_TIMEOUT:0) | 
1007                                 ((Trans->uac[picked_branch].request.flags & F_RB_REPLIED)?
1008                                                         FL_REPLIED:0);
1009                         run_failure_handlers( Trans, Trans->uac[picked_branch].reply,
1010                                                                         picked_code, extra_flags);
1011                 }
1012
1013                 /* now reset it; after the failure logic, the reply may
1014                  * not be stored any more and we don't want to keep into
1015                  * transaction some broken reference */
1016                 Trans->uac[branch].reply = 0;
1017
1018                 /* look if the callback perhaps replied transaction; it also
1019                    covers the case in which a transaction is replied localy
1020                    on CANCEL -- then it would make no sense to proceed to
1021                    new branches bellow
1022                 */
1023                 if (Trans->uas.status >= 200) {
1024                         *should_store=0;
1025                         *should_relay=-1;
1026                         /* this might deserve an improvement -- if something
1027                            was already replied, it was put on wait and then,
1028                            returning RPS_COMPLETED will make t_on_reply
1029                            put it on wait again; perhaps splitting put_on_wait
1030                            from send_reply or a new RPS_ code would be healthy
1031                         */
1032                         return RPS_COMPLETED;
1033                 }
1034                 /* look if the callback/failure_route introduced new branches ... */
1035                 if (branch_cnt<Trans->nr_of_outgoings){
1036                         /* the new branches might be already "finished" => we
1037                          * must use t_pick_branch again */
1038                         new_branch=t_pick_branch(branch, new_code, Trans, &picked_code);
1039                         if (new_branch<0){
1040                                 if (new_branch==-2) { /* branches open yet */
1041                                         *should_store=1;
1042                                         *should_relay=-1;
1043                                         return RPS_STORE;
1044                                 }
1045                                 /* error, use the old picked_branch */
1046                         }else{
1047                                 /* found a new_branch */
1048                                 picked_branch=new_branch;
1049                         }
1050                 }
1051
1052                 /* really no more pending branches -- return lowest code */
1053                 *should_store=0;
1054                 *should_relay=picked_branch;
1055                 /* we dont need 'which_cancel' here -- all branches
1056                    known to have completed */
1057                 /* which_cancel( Trans, cancel_bitmap ); */
1058                 return RPS_COMPLETED;
1059         }
1060
1061         /* not >=300 ... it must be 2xx or provisional 1xx */
1062         if (new_code>=100) {
1063                 /* 1xx and 2xx except 100 will be relayed */
1064                 Trans->uac[branch].last_received=new_code;
1065                 *should_store=0;
1066                 *should_relay= new_code==100? -1 : branch;
1067                 if (new_code>=200 ) {
1068                         which_cancel( Trans, cancel_bitmap );
1069                         return RPS_COMPLETED;
1070                 } else return RPS_PROVISIONAL;
1071         }
1072
1073 error:
1074         /* reply_status didn't match -- it must be something weird */
1075         LOG(L_CRIT, "ERROR: Oh my gooosh! We don't know whether to relay %d\n",
1076                 new_code);
1077 discard:
1078         *should_store=0;
1079         *should_relay=-1;
1080         return RPS_DISCARDED;
1081 }
1082
1083 /* Retransmits the last sent inbound reply.
1084  * input: p_msg==request for which I want to retransmit an associated reply
1085  * Returns  -1 - error
1086  *           1 - OK
1087  */
1088 int t_retransmit_reply( struct cell *t )
1089 {
1090         static char b[BUF_SIZE];
1091         int len;
1092
1093         /* first check if we managed to resolve topmost Via -- if
1094            not yet, don't try to retransmit
1095         */
1096         /*
1097            response.dst.send_sock might be unset if the process that created
1098            the original transaction has not finished initialising the
1099            retransmission buffer (see t_newtran/ init_rb).
1100            If reply_to_via is set and via contains a host name (and not an ip)
1101            the chances for this increase a lot.
1102          */
1103         if (!t->uas.response.dst.send_sock) {
1104                 LOG(L_WARN, "WARNING: t_retransmit_reply: "
1105                         "no resolved dst to retransmit\n");
1106                 return -1;
1107         }
1108
1109         /* we need to lock the transaction as messages from
1110            upstream may change it continuously
1111         */
1112         LOCK_REPLIES( t );
1113
1114         if (!t->uas.response.buffer) {
1115                 DBG("DBG: t_retransmit_reply: nothing to retransmit\n");
1116                 goto error;
1117         }
1118
1119         len=t->uas.response.buffer_len;
1120         if ( len==0 || len>BUF_SIZE )  {
1121                 DBG("DBG: t_retransmit_reply: "
1122                         "zero length or too big to retransmit: %d\n", len);
1123                 goto error;
1124         }
1125         memcpy( b, t->uas.response.buffer, len );
1126         UNLOCK_REPLIES( t );
1127         SEND_PR_BUFFER( & t->uas.response, b, len );
1128 #ifdef TMCB_ONSEND
1129         if (unlikely(has_tran_tmcbs(t, TMCB_RESPONSE_SENT))){ 
1130                 /* we don't know if it's a retransmission of a local reply or a 
1131                  * forwarded reply */
1132                 run_onsend_callbacks(TMCB_RESPONSE_SENT, &t->uas.response, 0, 0,
1133                                                                 TMCB_RETR_F);
1134         }
1135 #endif
1136         DBG("DEBUG: reply retransmitted. buf=%p: %.9s..., shmem=%p: %.9s\n",
1137                 b, b, t->uas.response.buffer, t->uas.response.buffer );
1138         return 1;
1139
1140 error:
1141         UNLOCK_REPLIES(t);
1142         return -1;
1143 }
1144
1145
1146
1147
1148 int t_reply( struct cell *t, struct sip_msg* p_msg, unsigned int code,
1149         char * text )
1150 {
1151         return _reply( t, p_msg, code, text, 1 /* lock replies */ );
1152 }
1153
1154 int t_reply_unsafe( struct cell *t, struct sip_msg* p_msg, unsigned int code,
1155         char * text )
1156 {
1157         return _reply( t, p_msg, code, text, 0 /* don't lock replies */ );
1158 }
1159
1160
1161
1162
1163
1164 void set_final_timer( /* struct s_table *h_table, */ struct cell *t )
1165 {
1166         if ( !is_local(t) && t->uas.request->REQ_METHOD==METHOD_INVITE ) {
1167                 /* crank timers for negative replies */
1168                 if (t->uas.status>=300) {
1169                         if (start_retr(&t->uas.response)!=0)
1170                                 LOG(L_CRIT, "BUG: set_final_timer: start retr failed for %p\n",
1171                                                 &t->uas.response);
1172                         return;
1173                 }
1174                 /* local UAS retransmits too */
1175                 if (t->relayed_reply_branch==-2 && t->uas.status>=200) {
1176                         /* we retransmit 200/INVs regardless of transport --
1177                            even if TCP used, UDP could be used upstream and
1178                            loose the 200, which is not retransmitted by proxies
1179                         */
1180                         if (force_retr( &t->uas.response )!=0)
1181                                 LOG(L_CRIT, "BUG: set_final_timer: force retr failed for %p\n",
1182                                                 &t->uas.response);
1183                         return;
1184                 }
1185         }
1186         put_on_wait(t);
1187 }
1188
1189 void cleanup_uac_timers( struct cell *t )
1190 {
1191         int i;
1192
1193         /* reset FR/retransmission timers */
1194         for (i=0; i<t->nr_of_outgoings; i++ ){
1195                 stop_rb_timers(&t->uac[i].request);
1196         }
1197         DBG("DEBUG: cleanup_uac_timers: RETR/FR timers reset\n");
1198 }
1199
1200 static int store_reply( struct cell *trans, int branch, struct sip_msg *rpl)
1201 {
1202 #               ifdef EXTRA_DEBUG
1203                 if (trans->uac[branch].reply) {
1204                         LOG(L_ERR, "ERROR: replacing stored reply; aborting\n");
1205                         abort();
1206                 }
1207 #               endif
1208
1209                 /* when we later do things such as challenge aggregation,
1210                    we should parse the message here before we conserve
1211                    it in shared memory; -jiri
1212                 */
1213                 if (rpl==FAKED_REPLY)
1214                         trans->uac[branch].reply=FAKED_REPLY;
1215                 else
1216                         trans->uac[branch].reply = sip_msg_cloner( rpl, 0 );
1217
1218                 if (! trans->uac[branch].reply ) {
1219                         LOG(L_ERR, "ERROR: store_reply: can't alloc' clone memory\n");
1220                         return 0;
1221                 }
1222
1223                 return 1;
1224 }
1225
1226
1227
1228 /* returns the number of authenticate replies (401 and 407) received so far
1229  *  (FAKED_REPLYes are excluded)
1230  *  It must be called with the REPLY_LOCK held */
1231 inline static int auth_reply_count(struct cell *t, struct sip_msg* crt_reply)
1232 {
1233         int count;
1234         int r;
1235
1236         count=0;
1237         if (crt_reply && (crt_reply!=FAKED_REPLY) && 
1238                         (crt_reply->REPLY_STATUS ==401 || crt_reply->REPLY_STATUS ==407))
1239                 count=1;
1240         for (r=0; r<t->nr_of_outgoings; r++){
1241                 if (t->uac[r].reply && (t->uac[r].reply!=FAKED_REPLY) &&
1242                                 (t->uac[r].last_received==401 || t->uac[r].last_received==407))
1243                         count++;
1244         }
1245         return count;
1246 }
1247
1248
1249
1250 /* must be called with the REPY_LOCK held */
1251 inline static char* reply_aggregate_auth(int code, char* txt, str* new_tag, 
1252                                                                         struct cell* t, unsigned int* res_len, 
1253                                                                         struct bookmark* bm)
1254 {
1255         int r;
1256         struct hdr_field* hdr;
1257         struct lump_rpl** first;
1258         struct lump_rpl** crt;
1259         struct lump_rpl* lst;
1260         struct lump_rpl*  lst_end;
1261         struct sip_msg* req;
1262         char* buf;
1263         
1264         first=0;
1265         lst_end=0;
1266         req=t->uas.request;
1267         
1268         for (r=0; r<t->nr_of_outgoings; r++){
1269                 if (t->uac[r].reply && (t->uac[r].reply!=FAKED_REPLY) &&
1270                         (t->uac[r].last_received==401 || t->uac[r].last_received==407)){
1271                         for (hdr=t->uac[r].reply->headers; hdr; hdr=hdr->next){
1272                                 if (hdr->type==HDR_WWW_AUTHENTICATE_T ||
1273                                                 hdr->type==HDR_PROXY_AUTHENTICATE_T){
1274                                         crt=add_lump_rpl2(req, hdr->name.s, hdr->len,
1275                                                         LUMP_RPL_HDR|LUMP_RPL_NODUP|LUMP_RPL_NOFREE);
1276                                         if (crt==0){
1277                                                 /* some kind of error, better stop */
1278                                                 LOG(L_ERR, "ERROR: tm:reply_aggregate_auth:"
1279                                                                         " add_lump_rpl2 failed\n");
1280                                                 goto skip;
1281                                         }
1282                                         lst_end=*crt;
1283                                         if (first==0) first=crt;
1284                                 }
1285                         }
1286                 }
1287         }
1288 skip:
1289         buf=build_res_buf_from_sip_req(code, txt, new_tag, req, res_len, bm);
1290         /* clean the added lumps */
1291         if (first){
1292                 lst=*first;
1293                 *first=lst_end->next; /* "detach" the list of added rpl_lumps */
1294                 lst_end->next=0; /* terminate lst */
1295                 del_nonshm_lump_rpl(&lst);
1296                 if (lst){
1297                         LOG(L_CRIT, "BUG: tm: repply_aggregate_auth: rpl_lump list"
1298                                             "contains shm alloc'ed lumps\n");
1299                         abort();
1300                 }
1301         }
1302         return buf;
1303 }
1304
1305
1306
1307 /* this is the code which decides what and when shall be relayed
1308    upstream; note well -- it assumes it is entered locked with
1309    REPLY_LOCK and it returns unlocked!
1310 */
1311 enum rps relay_reply( struct cell *t, struct sip_msg *p_msg, int branch,
1312         unsigned int msg_status, branch_bm_t *cancel_bitmap )
1313 {
1314         int relay;
1315         int save_clone;
1316         char *buf;
1317         /* length of outbound reply */
1318         unsigned int res_len;
1319         int relayed_code;
1320         struct sip_msg *relayed_msg;
1321         struct sip_msg *reply_bak;
1322         struct bookmark bm;
1323         int totag_retr;
1324         enum rps reply_status;
1325         /* retransmission structure of outbound reply and request */
1326         struct retr_buf *uas_rb;
1327         str* to_tag;
1328 #ifdef TMCB_ONSEND
1329         struct tmcb_params onsend_params;
1330 #endif
1331
1332         /* keep compiler warnings about use of uninit vars silent */
1333         res_len=0;
1334         buf=0;
1335         relayed_msg=0;
1336         relayed_code=0;
1337         totag_retr=0;
1338
1339
1340         /* remember, what was sent upstream to know whether we are
1341          * forwarding a first final reply or not */
1342
1343         /* *** store and relay message as needed *** */
1344         reply_status = t_should_relay_response(t, msg_status, branch,
1345                 &save_clone, &relay, cancel_bitmap, p_msg );
1346         DBG("DEBUG: relay_reply: branch=%d, save=%d, relay=%d\n",
1347                 branch, save_clone, relay );
1348
1349         /* store the message if needed */
1350         if (save_clone) /* save for later use, typically branch picking */
1351         {
1352                 if (!store_reply( t, branch, p_msg ))
1353                         goto error01;
1354         }
1355
1356         uas_rb = & t->uas.response;
1357         if (relay >= 0 ) {
1358                 /* initialize sockets for outbound reply */
1359                 uas_rb->activ_type=msg_status;
1360                 /* only messages known to be relayed immediately will be
1361                  * be called on; we do not evoke this callback on messages
1362                  * stored in shmem -- they are fixed and one cannot change them
1363                  * anyway */
1364                 if (unlikely(msg_status<300 && branch==relay
1365                 && has_tran_tmcbs(t,TMCB_RESPONSE_FWDED)) ) {
1366                         run_trans_callbacks( TMCB_RESPONSE_FWDED, t, t->uas.request,
1367                                 p_msg, msg_status );
1368                 }
1369                 /* try building the outbound reply from either the current
1370                  * or a stored message */
1371                 relayed_msg = branch==relay ? p_msg :  t->uac[relay].reply;
1372                 if (relayed_msg==FAKED_REPLY) {
1373                         relayed_code = branch==relay
1374                                 ? msg_status : t->uac[relay].last_received;
1375                         /* use to_tag from the original request, or if not present,
1376                          * generate a new one */
1377                         if (relayed_code>=180 && t->uas.request->to
1378                                         && (get_to(t->uas.request)->tag_value.s==0
1379                                         || get_to(t->uas.request)->tag_value.len==0)) {
1380                                 calc_crc_suffix( t->uas.request, tm_tag_suffix );
1381                                 to_tag=&tm_tag;
1382                         } else {
1383                                 to_tag=0;
1384                         }
1385                         if (tm_aggregate_auth && 
1386                                                 (relayed_code==401 || relayed_code==407) &&
1387                                                 (auth_reply_count(t, p_msg)>1)){
1388                                 /* aggregate 401 & 407 www & proxy authenticate headers in
1389                                  *  a "FAKE" reply*/
1390                                 
1391                                 /* temporarily "store" the current reply */
1392                                 reply_bak=t->uac[branch].reply;
1393                                 t->uac[branch].reply=p_msg;
1394                                 buf=reply_aggregate_auth(relayed_code, 
1395                                                 error_text(relayed_code), to_tag, t, &res_len, &bm);
1396                                 /* revert the temporary "store" reply above */
1397                                 t->uac[branch].reply=reply_bak;
1398                         }else{
1399                                 buf = build_res_buf_from_sip_req( relayed_code,
1400                                                 error_text(relayed_code), to_tag,
1401                                                 t->uas.request, &res_len, &bm );
1402                         }
1403                 } else {
1404                         relayed_code=relayed_msg->REPLY_STATUS;
1405                         if (relayed_code==503){
1406                                 /* replace a final 503 with a 500:
1407                                  * generate a "FAKE" reply and a new to_tag (for easier
1408                                  *  debugging)*/
1409                                 relayed_msg=FAKED_REPLY;
1410                                 if ((get_to(t->uas.request)->tag_value.s==0 ||
1411                                          get_to(t->uas.request)->tag_value.len==0)) {
1412                                         calc_crc_suffix( t->uas.request, tm_tag_suffix );
1413                                         to_tag=&tm_tag;
1414                                 } else {
1415                                         to_tag=0;
1416                                 }
1417                                 /* don't relay a 503, replace it w/ 500 (rfc3261) */
1418                                 buf=build_res_buf_from_sip_req(500, error_text(relayed_code),
1419                                                                         to_tag, t->uas.request, &res_len, &bm);
1420                                 relayed_code=500;
1421                         }else if (tm_aggregate_auth && 
1422                                                 (relayed_code==401 || relayed_code==407) &&
1423                                                 (auth_reply_count(t, p_msg)>1)){
1424                                 /* aggregate 401 & 407 www & proxy authenticate headers in
1425                                  *  a "FAKE" reply*/
1426                                 if ((get_to(t->uas.request)->tag_value.s==0 ||
1427                                          get_to(t->uas.request)->tag_value.len==0)) {
1428                                         calc_crc_suffix( t->uas.request, tm_tag_suffix );
1429                                         to_tag=&tm_tag;
1430                                 } else {
1431                                         to_tag=0;
1432                                 }
1433                                 /* temporarily "store" the current reply */
1434                                 reply_bak=t->uac[branch].reply;
1435                                 t->uac[branch].reply=p_msg;
1436                                 buf=reply_aggregate_auth(relayed_code, 
1437                                                 error_text(relayed_code), to_tag, t, &res_len, &bm);
1438                                 /* revert the temporary "store" reply above */
1439                                 t->uac[branch].reply=reply_bak;;
1440                                 relayed_msg=FAKED_REPLY; /* mark the relayed_msg as a "FAKE" */
1441                         }else{
1442                                 buf = build_res_buf_from_sip_res( relayed_msg, &res_len );
1443                                 /* if we build a message from shmem, we need to remove
1444                                    via delete lumps which are now stirred in the shmem-ed
1445                                    structure
1446                                 */
1447                                 if (branch!=relay) {
1448                                         free_via_clen_lump(&relayed_msg->add_rm);
1449                                 }
1450                         }
1451                 }
1452                 update_reply_stats( relayed_code );
1453                 if (!buf) {
1454                         LOG(L_ERR, "ERROR: relay_reply: "
1455                                 "no mem for outbound reply buffer\n");
1456                         goto error02;
1457                 }
1458
1459                 /* attempt to copy the message to UAS's shmem:
1460                    - copy to-tag for ACK matching as well
1461                    -  allocate little a bit more for provisional as
1462                       larger messages are likely to follow and we will be
1463                       able to reuse the memory frag
1464                 */
1465                 uas_rb->buffer = (char*)shm_resize( uas_rb->buffer, res_len +
1466                         (msg_status<200 ?  REPLY_OVERBUFFER_LEN : 0));
1467                 if (!uas_rb->buffer) {
1468                         LOG(L_ERR, "ERROR: relay_reply: cannot alloc reply shmem\n");
1469                         goto error03;
1470                 }
1471                 uas_rb->buffer_len = res_len;
1472                 memcpy( uas_rb->buffer, buf, res_len );
1473                 if (relayed_msg==FAKED_REPLY) { /* to-tags for local replies */
1474                         update_local_tags(t, &bm, uas_rb->buffer, buf);
1475                         t_stats_replied_locally();
1476                 }
1477                 
1478                 /* update the status ... */
1479                 t->uas.status = relayed_code;
1480                 t->relayed_reply_branch = relay;
1481
1482                 if ( unlikely(is_invite(t) && relayed_msg!=FAKED_REPLY
1483                 && relayed_code>=200 && relayed_code < 300
1484                 && has_tran_tmcbs( t,
1485                                 TMCB_RESPONSE_OUT|TMCB_E2EACK_IN|TMCB_E2EACK_RETR_IN))) {
1486                         totag_retr=update_totag_set(t, relayed_msg);
1487                 }
1488         }; /* if relay ... */
1489
1490         UNLOCK_REPLIES( t );
1491
1492              /* Set retransmission timer before the reply is sent out to avoid
1493               * race conditions
1494               */
1495         if (reply_status == RPS_COMPLETED) {
1496                 set_final_timer(t);
1497         }
1498
1499         /* send it now (from the private buffer) */
1500         if (relay >= 0) {
1501                 if (SEND_PR_BUFFER( uas_rb, buf, res_len )>=0){
1502                         if (unlikely(!totag_retr && has_tran_tmcbs(t, TMCB_RESPONSE_OUT))){
1503                                 run_trans_callbacks( TMCB_RESPONSE_OUT, t, t->uas.request,
1504                                         relayed_msg, relayed_code);
1505                         }
1506 #ifdef TMCB_ONSEND
1507                         if (unlikely(has_tran_tmcbs(t, TMCB_RESPONSE_SENT))){
1508                                 INIT_TMCB_ONSEND_PARAMS(onsend_params, t->uas.request,
1509                                                                         relayed_msg, uas_rb, &uas_rb->dst, buf,
1510                                                                         res_len,
1511                                                                         (relayed_msg==FAKED_REPLY)?TMCB_LOCAL_F:0,
1512                                                                         uas_rb->branch, relayed_code);
1513                                 run_onsend_callbacks2(TMCB_RESPONSE_SENT, t, &onsend_params);
1514                         }
1515 #endif
1516                 }
1517                 pkg_free( buf );
1518         }
1519
1520         /* success */
1521         return reply_status;
1522
1523 error03:
1524         pkg_free( buf );
1525 error02:
1526         if (save_clone) {
1527                 if (t->uac[branch].reply!=FAKED_REPLY)
1528                         sip_msg_free( t->uac[branch].reply );
1529                 t->uac[branch].reply = NULL;
1530         }
1531 error01:
1532         t_reply_unsafe( t, t->uas.request, 500, "Reply processing error" );
1533         *cancel_bitmap=0; /* t_reply_unsafe already canceled everything needed */
1534         UNLOCK_REPLIES(t);
1535         /* if (is_invite(t)) cancel_uacs( t, *cancel_bitmap, 0); 
1536          *  -- not needed, t_reply_unsafe took care of this */
1537
1538         /* a serious error occurred -- attempt to send an error reply;
1539            it will take care of clean-ups  */
1540
1541         /* failure */
1542         return RPS_ERROR;
1543 }
1544
1545 /* this is the "UAC" above transaction layer; if a final reply
1546    is received, it triggers a callback; note well -- it assumes
1547    it is entered locked with REPLY_LOCK and it returns unlocked!
1548 */
1549 enum rps local_reply( struct cell *t, struct sip_msg *p_msg, int branch,
1550         unsigned int msg_status, branch_bm_t *cancel_bitmap)
1551 {
1552         /* how to deal with replies for local transaction */
1553         int local_store, local_winner;
1554         enum rps reply_status;
1555         struct sip_msg *winning_msg;
1556         int winning_code;
1557         int totag_retr;
1558         /* branch_bm_t cancel_bitmap; */
1559
1560         /* keep warning 'var might be used un-inited' silent */
1561         winning_msg=0;
1562         winning_code=0;
1563         totag_retr=0;
1564
1565         *cancel_bitmap=0;
1566
1567         reply_status=t_should_relay_response( t, msg_status, branch,
1568                 &local_store, &local_winner, cancel_bitmap, p_msg );
1569         DBG("DEBUG: local_reply: branch=%d, save=%d, winner=%d\n",
1570                 branch, local_store, local_winner );
1571         if (local_store) {
1572                 if (!store_reply(t, branch, p_msg))
1573                         goto error;
1574         }
1575         if (local_winner>=0) {
1576                 winning_msg= branch==local_winner
1577                         ? p_msg :  t->uac[local_winner].reply;
1578                 if (winning_msg==FAKED_REPLY) {
1579                         t_stats_replied_locally();
1580                         winning_code = branch==local_winner
1581                                 ? msg_status : t->uac[local_winner].last_received;
1582                 } else {
1583                         winning_code=winning_msg->REPLY_STATUS;
1584                 }
1585                 t->uas.status = winning_code;
1586                 update_reply_stats( winning_code );
1587                 if (unlikely(is_invite(t) && winning_msg!=FAKED_REPLY
1588                 && winning_code>=200 && winning_code <300
1589                 && has_tran_tmcbs(t,
1590                                 TMCB_RESPONSE_OUT|TMCB_E2EACK_IN|TMCB_E2EACK_RETR_IN) ))  {
1591                         totag_retr=update_totag_set(t, winning_msg);
1592                 }
1593         }
1594         UNLOCK_REPLIES(t);
1595  
1596         if (local_winner >= 0 && pass_provisional_replies && winning_code < 200) {
1597                         if (unlikely(!totag_retr && 
1598                                                         has_tran_tmcbs(t, TMCB_LOCAL_RESPONSE_OUT) )) {
1599                         run_trans_callbacks( TMCB_LOCAL_RESPONSE_OUT, t, 0,
1600                                 winning_msg, winning_code);
1601                 }
1602         }
1603  
1604         if (local_winner>=0 && winning_code>=200 ) {
1605                 DBG("DEBUG: local transaction completed\n");
1606                 if (!totag_retr) {
1607                         if (unlikely(has_tran_tmcbs(t,TMCB_LOCAL_COMPLETED) ))
1608                                 run_trans_callbacks( TMCB_LOCAL_COMPLETED, t, 0,
1609                                         winning_msg, winning_code );
1610                 }
1611         }
1612         return reply_status;
1613
1614 error:
1615         which_cancel(t, cancel_bitmap);
1616         UNLOCK_REPLIES(t);
1617         cleanup_uac_timers(t);
1618         if ( get_cseq(p_msg)->method.len==INVITE_LEN
1619                 && memcmp( get_cseq(p_msg)->method.s, INVITE, INVITE_LEN)==0)
1620                 cancel_uacs( t, *cancel_bitmap, F_CANCEL_B_KILL);
1621         *cancel_bitmap=0; /* we've already took care of everything */
1622         put_on_wait(t);
1623         return RPS_ERROR;
1624 }
1625
1626
1627
1628
1629
1630 /*  This function is called whenever a reply for our module is received;
1631   * we need to register  this function on module initialization;
1632   *  Returns :   0 - core router stops
1633   *              1 - core router relay statelessly
1634   */
1635 int reply_received( struct sip_msg  *p_msg )
1636 {
1637
1638         int msg_status;
1639         int last_uac_status;
1640         char *ack;
1641         unsigned int ack_len;
1642         int branch;
1643         /* has the transaction completed now and we need to clean-up? */
1644         int reply_status;
1645         branch_bm_t cancel_bitmap;
1646         struct ua_client *uac;
1647         struct cell *t;
1648         struct dest_info  lack_dst;
1649         avp_list_t* backup_user_from, *backup_user_to;
1650         avp_list_t* backup_domain_from, *backup_domain_to;
1651         avp_list_t* backup_uri_from, *backup_uri_to;
1652         struct run_act_ctx ra_ctx;
1653 #ifdef USE_DNS_FAILOVER
1654         int branch_ret;
1655         int prev_branch;
1656 #endif
1657 #ifdef USE_DST_BLACKLIST
1658         int blst_503_timeout;
1659         struct dest_info src;
1660         struct hdr_field* hf;
1661 #endif
1662 #ifdef TMCB_ONSEND
1663         struct tmcb_params onsend_params;
1664 #endif
1665
1666         /* make sure we know the associated transaction ... */
1667         if (t_check( p_msg  , &branch )==-1)
1668                 return 1;
1669         /*... if there is none, tell the core router to fwd statelessly */
1670         t=get_t();
1671         if ( (t==0)||(t==T_UNDEFINED)) return 1;
1672
1673         cancel_bitmap=0;
1674         msg_status=p_msg->REPLY_STATUS;
1675
1676         uac=&t->uac[branch];
1677         DBG("DEBUG: reply_received: org. status uas=%d, "
1678                 "uac[%d]=%d local=%d is_invite=%d)\n",
1679                 t->uas.status, branch, uac->last_received,
1680                 is_local(t), is_invite(t));
1681         last_uac_status=uac->last_received;
1682
1683         /* it's a cancel ... ? */
1684         if (get_cseq(p_msg)->method.len==CANCEL_LEN
1685                 && memcmp( get_cseq(p_msg)->method.s, CANCEL, CANCEL_LEN)==0
1686                 /* .. which is not e2e ? ... */
1687                 && is_invite(t) ) {
1688                         /* ... then just stop timers */
1689                         if ( msg_status >= 200 )
1690                                 stop_rb_timers(&uac->local_cancel); /* stop retr & fr */
1691                         else
1692                                 stop_rb_retr(&uac->local_cancel);  /* stop only retr */
1693                         DBG("DEBUG: reply to local CANCEL processed\n");
1694                         goto done;
1695         }
1696
1697
1698         if ( msg_status >= 200 ){
1699                 /* stop final response timer  & retr. only if I got a final response */
1700                 stop_rb_timers(&uac->request); 
1701                 /* acknowledge negative INVITE replies (do it before detailed
1702                  * on_reply processing, which may take very long, like if it
1703                  * is attempted to establish a TCP connection to a fail-over dst */
1704                 if (is_invite(t)) {
1705                         if (msg_status >= 300) {
1706                                 ack = build_ack(p_msg, t, branch, &ack_len);
1707                                 if (ack) {
1708 #ifdef  TMCB_ONSEND
1709                                         if (SEND_PR_BUFFER(&uac->request, ack, ack_len)>=0)
1710                                                 if (unlikely(has_tran_tmcbs(t, TMCB_REQUEST_SENT))){ 
1711                                                         INIT_TMCB_ONSEND_PARAMS(onsend_params, 
1712                                                                         t->uas.request, p_msg, &uac->request,
1713                                                                         &uac->request.dst, ack, ack_len,
1714                                                                         TMCB_LOCAL_F, branch, TYPE_LOCAL_ACK);
1715                                                         run_onsend_callbacks2(TMCB_REQUEST_SENT, t,
1716                                                                                                         &onsend_params);
1717                                                 }
1718 #else
1719                                         SEND_PR_BUFFER(&uac->request, ack, ack_len);
1720 #endif
1721                                         shm_free(ack);
1722                                 }
1723                         } else if (is_local(t) /*&& 200 <= msg_status < 300*/) {
1724                                 ack = build_local_ack(p_msg, t, branch, &ack_len, &lack_dst);
1725                                 if (ack) {
1726                                         if (msg_send(&lack_dst, ack, ack_len)<0)
1727                                                 LOG(L_ERR, "Error while sending local ACK\n");
1728 #ifdef  TMCB_ONSEND
1729                                         else if (unlikely(has_tran_tmcbs(t, TMCB_REQUEST_SENT))){
1730                                                         INIT_TMCB_ONSEND_PARAMS(onsend_params, 
1731                                                                         t->uas.request, p_msg, &uac->request,
1732                                                                         &lack_dst, ack, ack_len, TMCB_LOCAL_F,
1733                                                                         branch, TYPE_LOCAL_ACK);
1734                                                         run_onsend_callbacks2(TMCB_REQUEST_SENT, t,
1735                                                                                                         &onsend_params);
1736                                         }
1737 #endif
1738                                         shm_free(ack);
1739                                 }
1740                         }
1741                 }
1742         }else{
1743                 /* if branch already canceled re-transmit or generate cancel
1744                  * TODO: check if it really makes sense to do it for non-invites too */
1745                 if (uac->request.flags & F_RB_CANCELED){
1746                         if (uac->local_cancel.buffer_len){
1747                                 membar_read(); /* make sure we get the current value of
1748                                                                   local_cancel */
1749                                 /* re-transmit if cancel already built */
1750                                 DBG("tm: reply_received: branch CANCEL retransmit\n");
1751 #ifdef TMCB_ONSEND
1752                                 if (SEND_BUFFER( &uac->local_cancel)>=0){
1753                                         if (unlikely (has_tran_tmcbs(t, TMCB_REQUEST_SENT)))
1754                                                 run_onsend_callbacks(TMCB_REQUEST_SENT,
1755                                                                                         &uac->local_cancel,
1756                                                                                         0, 0, TMCB_LOCAL_F);
1757                                 }
1758 #else
1759                                 SEND_BUFFER( &uac->local_cancel );
1760 #endif
1761                                 /* retrs. should be already started so do nothing */
1762                         }else if (atomic_cmpxchg_long((void*)&uac->local_cancel.buffer, 0, 
1763                                                                                 (long)BUSY_BUFFER)==0){
1764                                 /* try to rebuild it if empty (not set or marked as BUSY).
1765                                  * if BUSY or set just exit, a cancel will be (or was) sent 
1766                                  * shortly on this branch */
1767                                 DBG("tm: reply_received: branch CANCEL created\n");
1768                                 cancel_branch(t, branch, F_CANCEL_B_FORCE);
1769                         }
1770                         goto done; /* nothing to do */
1771                 }
1772                 if (is_invite(t)){
1773                         /* stop only retr. (and not fr) */
1774                         stop_rb_retr(&uac->request);
1775                 }else{
1776                         /* non-invite: increase retransmissions interval (slow now) */
1777                         switch_rb_retr_to_t2(&uac->request);
1778                 }
1779         }
1780         /* processing of on_reply block */
1781         if (t->on_reply) {
1782                 rmode=MODE_ONREPLY;
1783                 /* transfer transaction flag to message context */
1784                 if (t->uas.request) p_msg->flags=t->uas.request->flags;
1785                 /* set the as avp_list the one from transaction */
1786
1787                 backup_uri_from = set_avp_list(AVP_TRACK_FROM | AVP_CLASS_URI, &t->uri_avps_from );
1788                 backup_uri_to = set_avp_list(AVP_TRACK_TO | AVP_CLASS_URI, &t->uri_avps_to );
1789                 backup_user_from = set_avp_list(AVP_TRACK_FROM | AVP_CLASS_USER, &t->user_avps_from );
1790                 backup_user_to = set_avp_list(AVP_TRACK_TO | AVP_CLASS_USER, &t->user_avps_to );
1791                 backup_domain_from = set_avp_list(AVP_TRACK_FROM | AVP_CLASS_DOMAIN, &t->domain_avps_from );
1792                 backup_domain_to = set_avp_list(AVP_TRACK_TO | AVP_CLASS_DOMAIN, &t->domain_avps_to );
1793                 reset_static_buffer();
1794                 init_run_actions_ctx(&ra_ctx);
1795                 if (run_actions(&ra_ctx, onreply_rt.rlist[t->on_reply], p_msg)<0)
1796                         LOG(L_ERR, "ERROR: on_reply processing failed\n");
1797                 /* transfer current message context back to t */
1798                 if (t->uas.request) t->uas.request->flags=p_msg->flags;
1799                 /* restore original avp list */
1800                 set_avp_list( AVP_TRACK_FROM | AVP_CLASS_URI, backup_uri_from );
1801                 set_avp_list( AVP_TRACK_TO | AVP_CLASS_URI, backup_uri_to );
1802                 set_avp_list( AVP_TRACK_FROM | AVP_CLASS_USER, backup_user_from );
1803                 set_avp_list( AVP_TRACK_TO | AVP_CLASS_USER, backup_user_to );
1804                 set_avp_list( AVP_TRACK_FROM | AVP_CLASS_DOMAIN, backup_domain_from );
1805                 set_avp_list( AVP_TRACK_TO | AVP_CLASS_DOMAIN, backup_domain_to );
1806         }
1807 #ifdef USE_DST_BLACKLIST
1808                 /* add temporary to the blacklist the source of a 503 reply */
1809                 if (tm_blst_503 && cfg_get(core, core_cfg, use_dst_blacklist) && (msg_status==503)){
1810                         blst_503_timeout=tm_blst_503_default;
1811                         if ((parse_headers(p_msg, HDR_RETRY_AFTER_F, 0)==0) && 
1812                                 (p_msg->parsed_flag & HDR_RETRY_AFTER_F)){
1813                                 for (hf=p_msg->headers; hf; hf=hf->next)
1814                                         if (hf->type==HDR_RETRY_AFTER_T){
1815                                                 /* found */
1816                                                 blst_503_timeout=(unsigned)(unsigned long)hf->parsed;
1817                                                 blst_503_timeout=MAX_unsigned(blst_503_timeout, 
1818                                                                                                                         tm_blst_503_min);
1819                                                 blst_503_timeout=MIN_unsigned(blst_503_timeout,
1820                                                                                                                         tm_blst_503_max);
1821                                                 break;
1822                                         }
1823                         }
1824                         if (blst_503_timeout){
1825                                 src.send_sock=0;
1826                                 src.to=p_msg->rcv.src_su;
1827                                 src.id=p_msg->rcv.proto_reserved1;
1828                                 src.proto=p_msg->rcv.proto;
1829                                 dst_blacklist_add_to(BLST_503, &src,  p_msg, 
1830                                                                         S_TO_TICKS(blst_503_timeout));
1831                         }
1832                 }
1833 #endif /* USE_DST_BLACKLIST */
1834 #ifdef USE_DNS_FAILOVER
1835                 /* if this is a 503 reply, the destination resolves to more ips, and
1836                  *  the branch is still active (no timeout), add another branch/uac.
1837                  *  This code is out of LOCK_REPLIES() to minimize the time the
1838                  *  reply lock is held (the lock won't be held while sending the
1839                  *   message)*/
1840                 if (use_dns_failover && (msg_status==503) && uac->request.t_active){
1841                         branch_ret=add_uac_dns_fallback(t, t->uas.request, uac, 1);
1842                         prev_branch=-1;
1843                         while((branch_ret>=0) &&(branch_ret!=prev_branch)){
1844                                 prev_branch=branch_ret;
1845                                 branch_ret=t_send_branch(t, branch_ret, t->uas.request , 0, 1);
1846                         }
1847                 }
1848 #endif
1849         LOCK_REPLIES( t );
1850         if ( is_local(t) ) {
1851                 reply_status=local_reply( t, p_msg, branch, msg_status, &cancel_bitmap );
1852                 if (reply_status == RPS_COMPLETED) {
1853                              /* no more UAC FR/RETR (if I received a 2xx, there may
1854                               * be still pending branches ...
1855                               */
1856                         cleanup_uac_timers( t );
1857                         if (is_invite(t)) cancel_uacs(t, cancel_bitmap, F_CANCEL_B_KILL);
1858                         /* There is no need to call set_final_timer because we know
1859                          * that the transaction is local */
1860                         put_on_wait(t);
1861                 }else if (cancel_bitmap){
1862                         /* cancel everything, even non-INVITEs (e.g in case of 6xx), wait
1863                          * for the cancel replies if a provisional response was received
1864                          *  or generate a fake reply if not */
1865                         cancel_uacs(t, cancel_bitmap, F_CANCEL_B_FAKE_REPLY);
1866                 }
1867         } else {
1868                 reply_status=relay_reply( t, p_msg, branch, msg_status,
1869                         &cancel_bitmap );
1870                 if (reply_status == RPS_COMPLETED) {
1871                              /* no more UAC FR/RETR (if I received a 2xx, there may
1872                                 be still pending branches ...
1873                              */
1874                         cleanup_uac_timers( t );
1875                         /* 2xx is a special case: we can have a COMPLETED request
1876                          * with branches still open => we have to cancel them */
1877                         if (is_invite(t) && cancel_bitmap) 
1878                                 cancel_uacs( t, cancel_bitmap,  F_CANCEL_B_KILL);
1879                         /* FR for negative INVITES, WAIT anything else */
1880                         /* Call to set_final_timer is embedded in relay_reply to avoid
1881                          * race conditions when reply is sent out and an ACK to stop
1882                          * retransmissions comes before retransmission timer is set.*/
1883                         /* set_final_timer(t) */
1884                 }else if (cancel_bitmap){
1885                         /* cancel everything, even non-INVITEs (e.g in case of 6xx), wait
1886                          * for the cancel replies if a provisional response was received
1887                          *  or generate a fake reply if not */
1888                         cancel_uacs(t, cancel_bitmap, F_CANCEL_B_FAKE_REPLY);
1889                 }
1890         }
1891         uac->request.flags|=F_RB_REPLIED;
1892
1893         if (reply_status==RPS_ERROR)
1894                 goto done;
1895
1896         /* update FR/RETR timers on provisional replies */
1897         if (is_invite(t) && msg_status<200 && ( restart_fr_on_each_reply ||
1898                                 ( (last_uac_status<msg_status) &&
1899                                         ((msg_status>=180) || (last_uac_status==0)) )
1900                         ) ) { /* provisional now */
1901                 restart_rb_fr(& uac->request, t->fr_inv_timeout);
1902                 uac->request.flags|=F_RB_FR_INV; /* mark fr_inv */
1903         } /* provisional replies */
1904
1905 done:
1906         /* we are done with the transaction, so unref it - the reference
1907          * was incremented by t_check() function -bogdan*/
1908         t_unref(p_msg);
1909         /* don't try to relay statelessly neither on success
1910        (we forwarded statefully) nor on error; on troubles,
1911            simply do nothing; that will make the other party to
1912            retransmit; hopefuly, we'll then be better off */
1913         return 0;
1914 }
1915
1916
1917
1918 int t_reply_with_body( struct cell *trans, unsigned int code,
1919                 char * text, char * body, char * new_header, char * to_tag )
1920 {
1921         struct lump_rpl *hdr_lump;
1922         struct lump_rpl *body_lump;
1923         str  s_to_tag;
1924         str  rpl;
1925         int  ret;
1926         struct bookmark bm;
1927
1928         s_to_tag.s = to_tag;
1929         if(to_tag)
1930                 s_to_tag.len = strlen(to_tag);
1931         else
1932                 s_to_tag.len = 0;
1933
1934         /* mark the transaction as replied */
1935         if (code>=200) set_kr(REQ_RPLD);
1936
1937         /* add the lumps for new_header and for body (by bogdan) */
1938         if (new_header && strlen(new_header)) {
1939                 hdr_lump = add_lump_rpl( trans->uas.request, new_header,
1940                                          strlen(new_header), LUMP_RPL_HDR );
1941                 if ( !hdr_lump ) {
1942                         LOG(L_ERR,"ERROR:tm:t_reply_with_body: cannot add hdr lump\n");
1943                         goto error;
1944                 }
1945         } else {
1946                 hdr_lump = 0;
1947         }
1948
1949         /* body lump */
1950         if(body && strlen(body)) {
1951                 body_lump = add_lump_rpl( trans->uas.request, body, strlen(body),
1952                         LUMP_RPL_BODY );
1953                 if (body_lump==0) {
1954                         LOG(L_ERR,"ERROR:tm:t_reply_with_body: cannot add body lump\n");
1955                         goto error_1;
1956                 }
1957         } else {
1958                 body_lump = 0;
1959         }
1960
1961         rpl.s = build_res_buf_from_sip_req(
1962                         code, text, &s_to_tag,
1963                         trans->uas.request, (unsigned int*)&rpl.len, &bm);
1964
1965         /* since the msg (trans->uas.request) is a clone into shm memory, to avoid
1966          * memory leak or crashing (lumps are create in private memory) I will
1967          * remove the lumps by myself here (bogdan) */
1968         if ( hdr_lump ) {
1969                 unlink_lump_rpl( trans->uas.request, hdr_lump);
1970                 free_lump_rpl( hdr_lump );
1971         }
1972         if( body_lump ) {
1973                 unlink_lump_rpl( trans->uas.request, body_lump);
1974                 free_lump_rpl( body_lump );
1975         }
1976
1977         if (rpl.s==0) {
1978                 LOG(L_ERR,"ERROR:tm:t_reply_with_body: failed in doing "
1979                         "build_res_buf_from_sip_req()\n");
1980                 goto error;
1981         }
1982
1983         DBG("t_reply_with_body: buffer computed\n");
1984         // frees 'res.s' ... no panic !
1985         ret=_reply_light( trans, rpl.s, rpl.len, code, text,
1986                 s_to_tag.s, s_to_tag.len, 1 /* lock replies */, &bm );
1987         /* this is ugly hack -- the function caller may wish to continue with
1988          * transaction and I unref; however, there is now only one use from
1989          * vm/fifo_vm_reply and I'm currently to lazy to export UNREF; -jiri
1990          */
1991         UNREF(trans);
1992
1993         return ret;
1994 error_1:
1995         if ( hdr_lump ) {
1996                 unlink_lump_rpl( trans->uas.request, hdr_lump);
1997                 free_lump_rpl( hdr_lump );
1998         }
1999 error:
2000         return -1;
2001 }
2002
2003
2004 #if 0
2005 static int send_reply(struct cell *trans, unsigned int code, str* text, str* body, str* headers, str* to_tag)
2006 {
2007         struct lump_rpl *hdr_lump, *body_lump;
2008         str rpl;
2009         int ret;
2010         struct bookmark bm;
2011
2012              /* mark the transaction as replied */
2013         if (code >= 200) set_kr(REQ_RPLD);
2014
2015              /* add the lumps for new_header and for body (by bogdan) */
2016         if (headers && headers->len) {
2017                 hdr_lump = add_lump_rpl(trans->uas.request, headers->s, headers->len, LUMP_RPL_HDR);
2018                 if (!hdr_lump) {
2019                         LOG(L_ERR, "send_reply: cannot add hdr lump\n");
2020                         goto sr_error;
2021                 }
2022         } else {
2023                 hdr_lump = 0;
2024         }
2025
2026              /* body lump */
2027         if (body && body->len) {
2028                 body_lump = add_lump_rpl(trans->uas.request, body->s, body->len, LUMP_RPL_BODY);
2029                 if (body_lump == 0) {
2030                         LOG(L_ERR,"send_reply: cannot add body lump\n");
2031                         goto sr_error_1;
2032                 }
2033         } else {
2034                 body_lump = 0;
2035         }
2036
2037              /* We can safely zero-terminate the text here, because it is followed
2038               * by next line in the received message
2039               */
2040         text->s[text->len] = '\0';
2041         rpl.s = build_res_buf_from_sip_req(code, text->s, to_tag, trans->uas.request, (unsigned int*)&rpl.len, &bm);
2042
2043              /* since the msg (trans->uas.request) is a clone into shm memory, to avoid
2044               * memory leak or crashing (lumps are create in private memory) I will
2045               * remove the lumps by myself here (bogdan) */
2046         if (hdr_lump) {
2047                 unlink_lump_rpl(trans->uas.request, hdr_lump);
2048                 free_lump_rpl(hdr_lump);
2049         }
2050         if (body_lump) {
2051                 unlink_lump_rpl(trans->uas.request, body_lump);
2052                 free_lump_rpl(body_lump);
2053         }
2054
2055         if (rpl.s == 0) {
2056                 LOG(L_ERR,"send_reply: failed in build_res_buf_from_sip_req\n");
2057                 goto sr_error;
2058         }
2059
2060         ret = _reply_light(trans, rpl.s, rpl.len, code, text->s,  to_tag->s, to_tag->len, 1 /* lock replies */, &bm);
2061              /* this is ugly hack -- the function caller may wish to continue with
2062               * transaction and I unref; however, there is now only one use from
2063               * vm/fifo_vm_reply and I'm currently to lazy to export UNREF; -jiri
2064               */
2065         UNREF(trans);
2066         return ret;
2067  sr_error_1:
2068         if (hdr_lump) {
2069                 unlink_lump_rpl(trans->uas.request, hdr_lump);
2070                 free_lump_rpl(hdr_lump);
2071         }
2072  sr_error:
2073         return -1;
2074 }
2075 #endif
2076
2077
2078 const char* rpc_reply_doc[2] = {
2079         "Reply transaction",
2080         0
2081 };
2082
2083 /*
2084   Syntax:
2085
2086   ":tm.reply:[response file]\n
2087   code\n
2088   reason\n
2089   trans_id\n
2090   to_tag\n
2091   [new headers]\n
2092   \n
2093   [Body]\n
2094   .\n
2095   \n"
2096  */
2097 void rpc_reply(rpc_t* rpc, void* c)
2098 {
2099         int ret;
2100         struct cell *trans;
2101         unsigned int hash_index, label, code;
2102         str ti;
2103         char* reason, *body, *headers, *tag;
2104
2105         if (rpc->scan(c, "d", &code) < 1) {
2106                 rpc->fault(c, 400, "Reply code expected");
2107                 return;
2108         }
2109
2110         if (rpc->scan(c, "s", &reason) < 1) {
2111                 rpc->fault(c, 400, "Reason phrase expected");
2112                 return;
2113         }
2114
2115         if (rpc->scan(c, "s", &ti.s) < 1) {
2116                 rpc->fault(c, 400, "Transaction ID expected");
2117                 return;
2118         }
2119         ti.len = strlen(ti.s);
2120
2121         if (rpc->scan(c, "s", &tag) < 1) {
2122                 rpc->fault(c, 400, "To tag expected");
2123                 return;
2124         }
2125
2126         if (rpc->scan(c, "s", &headers) < 0) return;
2127         if (rpc->scan(c, "s", &body) < 0) return;
2128
2129         if(sscanf(ti.s,"%u:%u", &hash_index, &label) != 2) {
2130                 ERR("Invalid trans_id (%s)\n", ti.s);
2131                 rpc->fault(c, 400, "Invalid transaction ID");
2132                 return;
2133         }
2134         DBG("hash_index=%u label=%u\n", hash_index, label);
2135
2136         if( t_lookup_ident(&trans, hash_index, label) < 0 ) {
2137                 ERR("Lookup failed\n");
2138                 rpc->fault(c, 481, "No such transaction");
2139                 return;
2140         }
2141
2142         /* it's refcounted now, t_reply_with body unrefs for me -- I can
2143          * continue but may not use T anymore  */
2144         ret = t_reply_with_body(trans, code, reason, body, headers, tag);
2145
2146         if (ret < 0) {
2147                 ERR("Reply failed\n");
2148                 rpc->fault(c, 500, "Reply failed");
2149                 return;
2150         }
2151 }