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