fb59b9adfa2923d86ad4545edfa14804eed4ec61
[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, udpated 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  */
64
65
66 #include <assert.h>
67
68 #include "../../comp_defs.h"
69 #include "../../hash_func.h"
70 #include "../../dprint.h"
71 #include "../../config.h"
72 #include "../../parser/parser_f.h"
73 #include "../../ut.h"
74 #include "../../timer.h"
75 #include "../../error.h"
76 #include "../../action.h"
77 #include "../../dset.h"
78 #include "../../tags.h"
79 #include "../../data_lump.h"
80 #include "../../data_lump_rpl.h"
81 #include "../../usr_avp.h"
82 #include "../../fifo_server.h"
83 #include "../../unixsock_server.h"
84
85 #include "defs.h"
86 #include "h_table.h"
87 #include "t_hooks.h"
88 #include "t_funcs.h"
89 #include "t_reply.h"
90 #include "t_cancel.h"
91 #include "t_msgbuilder.h"
92 #include "t_lookup.h"
93 #include "t_fwd.h"
94 #include "fix_lumps.h"
95 #include "t_stats.h"
96
97 /* are we processing original or shmemed request ? */
98 enum route_mode rmode=MODE_REQUEST;
99
100 /* private place where we create to-tags for replies */
101 /* janakj: made public, I need to access this value to store it in dialogs */
102 char tm_tags[TOTAG_VALUE_LEN];
103 /* bogdan: pack tm_tag buffer and len into a str to pass them to
104  * build_res_buf_from_sip_req() */
105 static str  tm_tag = {tm_tags,TOTAG_VALUE_LEN};
106 char *tm_tag_suffix;
107
108 /* where to go if there is no positive reply */
109 static int goto_on_negative=0;
110 /* where to go on receipt of reply */
111 static int goto_on_reply=0;
112
113
114
115 /* we store the reply_route # in private memory which is
116    then processed during t_relay; we cannot set this value
117    before t_relay creates transaction context or after
118    t_relay when a reply may arrive after we set this
119    value; that's why we do it how we do it, i.e.,
120    *inside*  t_relay using hints stored in private memory
121    before t_reay is called
122 */
123
124
125 void t_on_negative( unsigned int go_to )
126 {
127         struct cell *t = get_t();
128
129         /* in MODE_REPLY and MODE_ONFAILURE T will be set to current transaction;
130          * in MODE_REQUEST T will be set only if the transaction was already 
131          * created; if not -> use the static variable */
132         if (!t || t==T_UNDEFINED )
133                 goto_on_negative=go_to;
134         else
135                 get_t()->on_negative = go_to;
136 }
137
138
139 void t_on_reply( unsigned int go_to )
140 {
141         struct cell *t = get_t();
142
143         /* in MODE_REPLY and MODE_ONFAILURE T will be set to current transaction;
144          * in MODE_REQUEST T will be set only if the transaction was already 
145          * created; if not -> use the static variable */
146         if (!t || t==T_UNDEFINED )
147                 goto_on_reply=go_to;
148         else
149                 get_t()->on_reply = go_to;
150 }
151
152
153 unsigned int get_on_negative()
154 {
155         return goto_on_negative;
156 }
157 unsigned int get_on_reply()
158 {
159         return goto_on_reply;
160 }
161
162 void tm_init_tags()
163 {
164         init_tags(tm_tags, &tm_tag_suffix, 
165                 "SER-TM/tags", TM_TAG_SEPARATOR );
166 }
167
168 /* returns 0 if the message was previously acknowledged
169  * (i.e., no E2EACK callback is needed) and one if the
170  * callback shall be executed */
171 int unmatched_totag(struct cell *t, struct sip_msg *ack)
172 {
173         struct totag_elem *i;
174         str *tag;
175
176         if (parse_headers(ack, HDR_TO,0)==-1 || 
177                                 !ack->to ) {
178                 LOG(L_ERR, "ERROR: unmatched_totag: To invalid\n");
179                 return 1;
180         }
181         tag=&get_to(ack)->tag_value;
182         for (i=t->fwded_totags; i; i=i->next) {
183                 if (i->tag.len==tag->len
184                                 && memcmp(i->tag.s, tag->s, tag->len)==0) {
185                         DBG("DEBUG: totag for e2e ACK found: %d\n", i->acked);
186                         /* to-tag recorded, and an ACK has been received for it */
187                         if (i->acked) return 0;
188                         /* to-tag recorded, but this ACK came for the first time */
189                         i->acked=1;
190                         return 1;
191                 }
192         }
193         /* surprising: to-tag never sighted before */
194         return 1;
195 }
196
197 static inline void update_local_tags(struct cell *trans, 
198                                 struct bookmark *bm, char *dst_buffer,
199                                 char *src_buffer /* to which bm refers */)
200 {
201         if (bm->to_tag_val.s) {
202                 trans->uas.local_totag.s=bm->to_tag_val.s-src_buffer+dst_buffer;
203                 trans->uas.local_totag.len=bm->to_tag_val.len;
204         }
205 }
206
207
208 /* append a newly received tag from a 200/INVITE to 
209  * transaction's set; (only safe if called from within
210  * a REPLY_LOCK); it returns 1 if such a to tag already
211  * exists
212  */
213 inline static int update_totag_set(struct cell *t, struct sip_msg *ok)
214 {
215         struct totag_elem *i, *n;
216         str *tag;
217         char *s;
218
219         if (!ok->to || !ok->to->parsed) {
220                 LOG(L_ERR, "ERROR: update_totag_set: to not parsed\n");
221                 return 0;
222         }
223         tag=&get_to(ok)->tag_value;
224         if (!tag->s) {
225                 LOG(L_ERR, "ERROR: update_totag_set: no tag in to\n");
226                 return 0;
227         }
228
229         for (i=t->fwded_totags; i; i=i->next) {
230                 if (i->tag.len==tag->len
231                                 && memcmp(i->tag.s, tag->s, tag->len) ==0 ){
232                         /* to tag already recorded */
233 #ifdef XL_DEBUG
234                         LOG(L_CRIT, "DEBUG: update_totag_set: totag retranmission\n");
235 #else
236                         DBG("DEBUG: update_totag_set: totag retranmission\n");
237 #endif
238                         return 1;
239                 }
240         }
241         /* that's a new to-tag -- record it */
242         shm_lock();
243         n=(struct totag_elem*) shm_malloc_unsafe(sizeof(struct totag_elem));
244         s=(char *)shm_malloc_unsafe(tag->len);
245         shm_unlock();
246         if (!s || !n) {
247                 LOG(L_ERR, "ERROR: update_totag_set: no  memory \n");
248                 if (n) shm_free(n);
249                 if (s) shm_free(s);
250                 return 0;
251         }
252         memset(n, 0, sizeof(struct totag_elem));
253         memcpy(s, tag->s, tag->len );
254         n->tag.s=s;n->tag.len=tag->len;
255         n->next=t->fwded_totags;
256         t->fwded_totags=n;
257         DBG("DEBUG: update_totag_set: new totag \n");
258         return 0;
259 }
260
261
262 /*
263  * Build an ACK to a negative reply
264  */
265 static char *build_ack(struct sip_msg* rpl,struct cell *trans,int branch,
266         unsigned int *ret_len)
267 {
268         str to;
269
270     if (parse_headers(rpl,HDR_TO, 0)==-1 || !rpl->to ) {
271         LOG(L_ERR, "ERROR: build_ack: "
272             "cannot generate a HBH ACK if key HFs in reply missing\n");
273         return NULL;
274     }
275         to.s=rpl->to->name.s;
276         to.len=rpl->to->len;
277     return build_local( trans, branch, ret_len,
278         ACK, ACK_LEN, &to );
279 }
280
281
282 /*
283  * The function builds an ACK to 200 OK of local transactions, honor the
284  * route set, the URI to which the message should be sent will be returned
285  * in next_hop parameter
286  */
287 static char *build_local_ack(struct sip_msg* rpl, struct cell *trans, int branch,
288                              unsigned int *ret_len, str* next_hop)
289 {
290         str to;
291         if (parse_headers(rpl, HDR_EOH, 0) == -1 || !rpl->to) {
292                 LOG(L_ERR, "ERROR: build_local_ack: Error while parsing headers\n");
293                 return 0;
294         }
295         
296         to.s = rpl->to->name.s;
297         to.len = rpl->to->len;
298         return build_dlg_ack(rpl, trans, branch, &to, ret_len, next_hop);
299 }
300
301
302      /*
303       * The function is used to send a localy generated ACK to INVITE
304       * (tm generates the ACK on behalf of application using UAC
305       */
306 static int send_local_ack(str* next_hop, char* ack, int ack_len)
307 {
308         struct socket_info* send_sock;
309         union sockaddr_union to_su;
310         
311         if (!next_hop) {
312                 LOG(L_ERR, "send_local_ack: Invalid parameter value\n");
313                 return -1;
314         }
315         
316         send_sock = uri2sock(next_hop, &to_su, PROTO_NONE);
317         if (!send_sock) {
318                 LOG(L_ERR, "send_local_ack: no socket found\n");
319                 return -1;
320         }
321         
322         return msg_send(send_sock, send_sock->proto, &to_su, 0, ack, ack_len);
323 }
324
325
326 static int _reply_light( struct cell *trans, char* buf, unsigned int len,
327                          unsigned int code, char * text, 
328                          char *to_tag, unsigned int to_tag_len, int lock,
329                          struct bookmark *bm    )
330 {
331         struct retr_buf *rb;
332         unsigned int buf_len;
333         branch_bm_t cancel_bitmap;
334
335         if (!buf)
336         {
337                 DBG("DEBUG: _reply_light: response building failed\n");
338                 /* determine if there are some branches to be cancelled */
339                 if ( is_invite(trans) ) {
340                         if (lock) LOCK_REPLIES( trans );
341                         which_cancel(trans, &cancel_bitmap );
342                         if (lock) UNLOCK_REPLIES( trans );
343                 }
344                 /* and clean-up, including cancellations, if needed */
345                 goto error;
346         }
347
348         cancel_bitmap=0;
349         if (lock) LOCK_REPLIES( trans );
350         if ( is_invite(trans) ) which_cancel(trans, &cancel_bitmap );
351         if (trans->uas.status>=200) {
352                 LOG( L_ERR, "ERROR: _reply_light: can't generate %d reply"
353                         " when a final %d was sent out\n", code, trans->uas.status);
354                 goto error2;
355         }
356
357
358         rb = & trans->uas.response;
359         rb->activ_type=code;
360
361         trans->uas.status = code;
362         buf_len = rb->buffer ? len : len + REPLY_OVERBUFFER_LEN;
363         rb->buffer = (char*)shm_resize( rb->buffer, buf_len );
364         /* puts the reply's buffer to uas.response */
365         if (! rb->buffer ) {
366                         LOG(L_ERR, "ERROR: _reply_light: cannot allocate shmem buffer\n");
367                         goto error3;
368         }
369         update_local_tags(trans, bm, rb->buffer, buf);
370
371         rb->buffer_len = len ;
372         memcpy( rb->buffer , buf , len );
373         /* needs to be protected too because what timers are set depends
374            on current transactions status */
375         /* t_update_timers_after_sending_reply( rb ); */
376         update_reply_stats( code );
377         trans->relaied_reply_branch=-2;
378         tm_stats->replied_localy++;
379         if (lock) UNLOCK_REPLIES( trans );
380         
381         /* do UAC cleanup procedures in case we generated
382            a final answer whereas there are pending UACs */
383         if (code>=200) {
384                 if ( is_local(trans) ) {
385                         DBG("DEBUG: local transaction completed from _reply\n");
386                         if ( has_tran_tmcbs(trans, TMCB_LOCAL_COMPLETED) )
387                                 run_trans_callbacks( TMCB_LOCAL_COMPLETED, trans,
388                                         0, FAKED_REPLY, code);
389                 } else {
390                         if ( has_tran_tmcbs(trans, TMCB_RESPONSE_OUT) )
391                                 run_trans_callbacks( TMCB_RESPONSE_OUT, trans,
392                                         trans->uas.request, FAKED_REPLY, code);
393                 }
394
395                 cleanup_uac_timers( trans );
396                 if (is_invite(trans)) cancel_uacs( trans, cancel_bitmap );
397                 set_final_timer(  trans );
398         }
399
400         /* send it out */
401         /* first check if we managed to resolve topmost Via -- if
402            not yet, don't try to retransmit
403         */
404         if (!trans->uas.response.dst.send_sock) {
405                 LOG(L_ERR, "ERROR: _reply_light: no resolved dst to send reply to\n");
406         } else {
407                 SEND_PR_BUFFER( rb, buf, len );
408                 DBG("DEBUG: reply sent out. buf=%p: %.9s..., shmem=%p: %.9s\n", 
409                         buf, buf, rb->buffer, rb->buffer );
410         }
411         pkg_free( buf ) ;
412         DBG("DEBUG: _reply_light: finished\n");
413         return 1;
414
415 error3:
416 error2:
417         if (lock) UNLOCK_REPLIES( trans );
418         pkg_free ( buf );
419 error:
420         /* do UAC cleanup */
421         cleanup_uac_timers( trans );
422         if ( is_invite(trans) ) cancel_uacs( trans, cancel_bitmap );
423         /* we did not succeed -- put the transaction on wait */
424         put_on_wait(trans);
425         return -1;
426 }
427
428
429 /* send a UAS reply
430  * returns 1 if everything was OK or -1 for error
431  */
432 static int _reply( struct cell *trans, struct sip_msg* p_msg, 
433         unsigned int code, char * text, int lock )
434 {
435         unsigned int len;
436         char * buf, *dset;
437         struct bookmark bm;
438         int dset_len;
439
440         if (code>=200) set_kr(REQ_RPLD);
441         /* compute the buffer in private memory prior to entering lock;
442          * create to-tag if needed */
443
444         /* if that is a redirection message, dump current message set to it */
445         if (code>=300 && code<400) {
446                 dset=print_dset(p_msg, &dset_len);
447                 if (dset) {
448                         add_lump_rpl(p_msg, dset, dset_len, LUMP_RPL_HDR);
449                 }
450         }
451
452         if (code>=180 && p_msg->to 
453                                 && (get_to(p_msg)->tag_value.s==0 
454                             || get_to(p_msg)->tag_value.len==0)) {
455                 calc_crc_suffix( p_msg, tm_tag_suffix );
456                 buf = build_res_buf_from_sip_req(code,text, &tm_tag, p_msg, &len, &bm);
457                 return _reply_light( trans, buf, len, code, text,
458                         tm_tag.s, TOTAG_VALUE_LEN, lock, &bm);
459         } else {
460                 buf = build_res_buf_from_sip_req(code,text, 0 /*no to-tag*/,
461                         p_msg, &len, &bm);
462
463                 return _reply_light(trans,buf,len,code,text,
464                         0, 0, /* no to-tag */lock, &bm);
465         }
466 }
467
468
469 /*if msg is set -> it will fake the env. vars conforming with the msg; if NULL
470  * the env. will be restore to original */
471 static inline void faked_env( struct cell *t,struct sip_msg *msg)
472 {
473         static enum route_mode backup_mode;
474         static struct cell *backup_t;
475         static unsigned int backup_msgid;
476
477         if (msg) {
478         /* remember we are back in request processing, but process
479          * a shmem-ed replica of the request; advertise it in rmode;
480          * for example t_reply needs to know that
481          */
482         backup_mode=rmode;
483         rmode=MODE_ONFAILURE;
484         /* also, tm actions look in beginning whether tranaction is
485          * set -- whether we are called from a reply-processing 
486          * or a timer process, we need to set current transaction;
487          * otherwise the actions would attempt to look the transaction
488          * up (unnecessary overhead, refcounting)
489          */
490         /* backup */
491         backup_t=get_t();
492         backup_msgid=global_msg_id;
493         /* fake transaction and message id */
494                 global_msg_id=msg->id;
495                 set_t(t);
496         } else {
497                 /* restore original environment */
498                 set_t(backup_t);
499                 global_msg_id=backup_msgid;
500                 rmode=backup_mode;
501         }
502 }
503
504
505 static inline int fake_req(struct sip_msg *faked_req, 
506                                 struct sip_msg *shmem_msg)
507 {
508         /* on_negative_reply faked msg now copied from shmem msg (as opposed
509          * to zero-ing) -- more "read-only" actions (exec in particular) will
510          * work from reply_route as they will see msg->from, etc.; caution,
511          * rw actions may append some pkg stuff to msg, which will possibly be
512          * never released (shmem is released in a single block) */
513         memcpy( faked_req, shmem_msg, sizeof(struct sip_msg));
514
515         /* if we set msg_id to something different from current's message
516          * id, the first t_fork will properly clean new branch URIs */
517         faked_req->id=shmem_msg->id-1;
518         /* msg->parsed_uri_ok must be reset since msg_parsed_uri is
519          * not cloned (and cannot be cloned) */
520         faked_req->parsed_uri_ok = 0;
521
522         /* new_uri can change -- make a private copy */
523         if (shmem_msg->new_uri.s!=0 && shmem_msg->new_uri.len!=0) {
524                 faked_req->new_uri.s=pkg_malloc(shmem_msg->new_uri.len+1);
525                 if (!faked_req->new_uri.s) {
526                         LOG(L_ERR, "ERROR: fake_req: no uri/pkg mem\n");
527                         goto error00;
528                 }
529                 faked_req->new_uri.len=shmem_msg->new_uri.len;
530                 memcpy( faked_req->new_uri.s, shmem_msg->new_uri.s, 
531                         faked_req->new_uri.len);
532                 faked_req->new_uri.s[faked_req->new_uri.len]=0;
533         }
534
535 #if 0
536         /* create a duplicated lump list to which actions can add
537          * new pkg items  */
538         if (shmem_msg->add_rm) {
539                 faked_req->add_rm=dup_lump_list(shmem_msg->add_rm);
540                 if (!faked_req->add_rm) { /* non_emty->empty ... failure */
541                         LOG(L_ERR, "ERROR: fake_req: lump dup failed\n");
542                         goto error01;
543                 }
544         }
545         /* same for the body lumps */
546         if (shmem_msg->body_lumps) {
547                 faked_req->body_lumps=dup_lump_list(shmem_msg->body_lumps);
548                 if (!faked_req->body_lumps) { /* non_empty->empty ... failure */
549                         LOG(L_ERR, "ERROR: fake_req: lump dup failed\n");
550                         goto error02;
551                 }
552         }
553 #endif
554         return 1;
555
556 #if 0
557 error02:
558         free_duped_lump_list(faked_req->add_rm);
559 error01:
560         if (faked_req->new_uri.s) pkg_free(faked_req->new_uri.s);
561 #endif
562 error00:
563         return 0;
564 }
565
566 void inline static free_faked_req(struct sip_msg *faked_req, struct cell *t)
567 {
568         struct hdr_field *hdr;
569
570 #if 0
571         free_duped_lump_list(faked_req->add_rm);
572         free_duped_lump_list(faked_req->body_lumps);
573         faked_req->add_rm = faked_req->body_lumps = 0;
574 #endif
575         if (faked_req->new_uri.s) {
576                 pkg_free(faked_req->new_uri.s);
577                 faked_req->new_uri.s = 0;
578         }
579
580         /* free all types of lump that were added in failure handlers */
581         del_nonshm_lump( &(faked_req->add_rm) );
582         del_nonshm_lump( &(faked_req->body_lumps) );
583         del_nonshm_lump_rpl( &(faked_req->reply_lump) );
584
585         /* free header's parsed structures that were added by failure handlers */
586         for( hdr=faked_req->headers ; hdr ; hdr=hdr->next ) {
587                 if ( hdr->parsed && hdr_allocs_parse(hdr) &&
588                 (hdr->parsed<(void*)t->uas.request ||
589                 hdr->parsed>=(void*)t->uas.end_request)) {
590                         /* header parsed filed doesn't point inside uas.request memory
591                          * chunck -> it was added by failure funcs.-> free it as pkg */
592                         DBG("DBG:free_faked_req: removing hdr->parsed %d\n",
593                                         hdr->type);
594                         clean_hdr_field(hdr);
595                         hdr->parsed = 0;
596                 }
597         }
598 }
599
600
601 /* return 1 if a failure_route processes */
602 static inline int run_failure_handlers(struct cell *t, struct sip_msg *rpl,
603                                                                                                                                         int code)
604 {
605         static struct sip_msg faked_req;
606         struct sip_msg *shmem_msg = t->uas.request;
607         int on_failure;
608
609         /* failure_route for a local UAC? */
610         if (!shmem_msg) {
611                 LOG(L_WARN, 
612                         "Warning: run_failure_handlers: no UAC support (%d, %d) \n",
613                         t->on_negative, 
614                         t->tmcb_hl.reg_types);
615                 return 0;
616         }
617
618         /* don't start faking anything if we don't have to */
619         if ( !has_tran_tmcbs( t, TMCB_ON_FAILURE) && !t->on_negative ) {
620                 LOG(L_WARN, 
621                         "Warning: run_failure_handlers: no negative handler (%d, %d)\n",
622                         t->on_negative, 
623                         t->tmcb_hl.reg_types);
624                 return 1;
625         }
626
627         if (!fake_req(&faked_req, shmem_msg)) {
628                 LOG(L_ERR, "ERROR: run_failure_handlers: fake_req failed\n");
629                 return 0;
630         }
631         /* fake also the env. conforming to the fake msg */
632         faked_env( t, &faked_req);
633         /* DONE with faking ;-) -> run the failure handlers */
634
635         if ( has_tran_tmcbs( t, TMCB_ON_FAILURE) ) {
636                 run_trans_callbacks( TMCB_ON_FAILURE, t, &faked_req, rpl, code);
637         }
638         if (t->on_negative) {
639                 /* avoid recursion -- if failure_route forwards, and does not 
640                  * set next failure route, failure_route will not be rentered
641                  * on failure */
642                 on_failure = t->on_negative;
643                 t->on_negative=0;
644                 /* run a reply_route action if some was marked */
645                 if (run_actions(failure_rlist[on_failure], &faked_req)<0)
646                         LOG(L_ERR, "ERROR: run_failure_handlers: Error in do_action\n");
647                 /* destroy any eventual avps */
648                 if (users_avps)
649                         destroy_avps();
650         }
651
652         /* restore original environment and free the fake msg */
653         faked_env( t, 0);
654         free_faked_req(&faked_req,t);
655
656         /* if failure handler changed flag, update transaction context */
657         shmem_msg->flags = faked_req.flags;
658         return 1;
659 }
660
661
662 /* select a branch for forwarding; returns:
663  * 0..X ... branch number
664  * -1   ... error
665  * -2   ... can't decide yet -- incomplete branches present
666  */
667 int t_pick_branch(int inc_branch, int inc_code, struct cell *t, int *res_code)
668 {
669         int lowest_b, lowest_s, b;
670
671         lowest_b=-1; lowest_s=999;
672         for ( b=0; b<t->nr_of_outgoings ; b++ ) {
673                 /* "fake" for the currently processed branch */
674                 if (b==inc_branch) {
675                         if (inc_code<lowest_s) {
676                                 lowest_b=b;
677                                 lowest_s=inc_code;
678                         }
679                         continue;
680                 }
681                 /* skip 'empty branches' */
682                 if (!t->uac[b].request.buffer) continue;
683                 /* there is still an unfinished UAC transaction; wait now! */
684                 if ( t->uac[b].last_received<200 ) 
685                         return -2;
686                 if ( t->uac[b].last_received<lowest_s ) {
687                         lowest_b =b;
688                         lowest_s = t->uac[b].last_received;
689                 }
690         } /* find lowest branch */
691
692         *res_code=lowest_s;
693         return lowest_b;
694 }
695
696 /* This is the neuralgical point of reply processing -- called
697  * from within a REPLY_LOCK, t_should_relay_response decides
698  * how a reply shall be processed and how transaction state is
699  * affected.
700  *
701  * Checks if the new reply (with new_code status) should be sent or not
702  *  based on the current
703  * transactin status.
704  * Returns      - branch number (0,1,...) which should be relayed
705  *         -1 if nothing to be relayed
706  */
707 static enum rps t_should_relay_response( struct cell *Trans , int new_code,
708         int branch , int *should_store, int *should_relay,
709         branch_bm_t *cancel_bitmap, struct sip_msg *reply )
710 {
711         int branch_cnt;
712         int picked_branch;
713         int picked_code;
714         int inv_through;
715
716         /* note: this code never lets replies to CANCEL go through;
717            we generate always a local 200 for CANCEL; 200s are
718            not relayed because it's not an INVITE transaction;
719            >= 300 are not relayed because 200 was already sent
720            out
721         */
722         DBG("->>>>>>>>> T_code=%d, new_code=%d\n",Trans->uas.status,new_code);
723         inv_through=new_code>=200 && new_code<300 && is_invite(Trans);
724         /* if final response sent out, allow only INVITE 2xx  */
725         if ( Trans->uas.status >= 200 ) {
726                 if (inv_through) {
727                         DBG("DBG: t_should_relay_response: 200 INV after final sent\n");
728                         *should_store=0;
729                         Trans->uac[branch].last_received=new_code;
730                         *should_relay=branch;
731                         return RPS_PUSHED_AFTER_COMPLETION;
732                 } 
733                 /* except the exception above, too late  messages will
734                    be discarded */
735                 goto discard;
736         } 
737
738         /* if final response received at this branch, allow only INVITE 2xx */
739         if (Trans->uac[branch].last_received>=200
740                         && !(inv_through && Trans->uac[branch].last_received<300)) {
741                 /* don't report on retranmissions */
742                 if (Trans->uac[branch].last_received==new_code) {
743                         DBG("DEBUG: final reply retrasnmission\n");
744                         goto discard;
745                 }
746                 /* if you FR-timed-out, faked a local 408 and 487 came, don't
747                  * report on it either */
748                 if (Trans->uac[branch].last_received==408 && new_code==487) {
749                         DBG("DEBUG: 487 came for a timed-out branch\n");
750                         goto discard;
751                 }
752                 /* this looks however how a very strange status rewrite attempt;
753                  * report on it */
754                 LOG(L_ERR, "ERROR: t_should_relay_response: status rewrite by UAS: "
755                         "stored: %d, received: %d\n",
756                         Trans->uac[branch].last_received, new_code );
757                 goto discard;
758         }
759
760
761         /* no final response sent yet */
762         /* negative replies subject to fork picking */
763         if (new_code >=300 ) {
764
765                 Trans->uac[branch].last_received=new_code;
766
767                 /* if all_final return lowest */
768                 picked_branch=t_pick_branch(branch,new_code, Trans, &picked_code);
769                 if (picked_branch==-2) { /* branches open yet */
770                         *should_store=1;
771                         *should_relay=-1;
772                         return RPS_STORE;
773                 }
774                 if (picked_branch==-1) {
775                         LOG(L_CRIT, "ERROR: t_should_relay_response: lowest==-1\n");
776                         goto error;
777                 }
778
779                 /* no more pending branches -- try if that changes after
780                    a callback; save banch count to be able to determine
781                    later if new branches were initiated */
782                 branch_cnt=Trans->nr_of_outgoings;
783
784                 /* run ON_FAILURE handlers ( route and callbacks) */
785                 if ( has_tran_tmcbs( Trans, TMCB_ON_FAILURE_RO|TMCB_ON_FAILURE)
786                 || Trans->on_negative ) {
787                         run_failure_handlers( Trans,
788                                 picked_branch==branch?reply:Trans->uac[picked_branch].reply, 
789                                 picked_code);
790                 }
791
792                 /* look if the callback perhaps replied transaction; it also
793                    covers the case in which a transaction is replied localy
794                    on CANCEL -- then it would make no sense to proceed to
795                    new branches bellow
796                 */
797                 if (Trans->uas.status >= 200) {
798                         *should_store=0;
799                         *should_relay=-1;
800                         /* this might deserve an improvement -- if something
801                            was already replied, it was put on wait and then,
802                            returning RPS_COMPLETED will make t_on_reply
803                            put it on wait again; perhaps splitting put_on_wait
804                            from send_reply or a new RPS_ code would be healthy
805                         */
806                         return RPS_COMPLETED;
807                 }
808                 /* look if the callback/failure_route introduced new branches ... */
809                 if (branch_cnt<Trans->nr_of_outgoings)  {
810                         /* await then result of new branches */
811                         *should_store=1;
812                         *should_relay=-1;
813                         return RPS_STORE;
814                 }
815
816                 /* really no more pending branches -- return lowest code */
817                 *should_store=0;
818                 *should_relay=picked_branch;
819                 /* we dont need 'which_cancel' here -- all branches 
820                    known to have completed */
821                 /* which_cancel( Trans, cancel_bitmap ); */
822                 return RPS_COMPLETED;
823         } 
824
825         /* not >=300 ... it must be 2xx or provisional 1xx */
826         if (new_code>=100) {
827                 /* 1xx and 2xx except 100 will be relayed */
828                 Trans->uac[branch].last_received=new_code;
829                 *should_store=0;
830                 *should_relay= new_code==100? -1 : branch;
831                 if (new_code>=200 ) {
832                         which_cancel( Trans, cancel_bitmap );
833                         return RPS_COMPLETED;
834                 } else return RPS_PROVISIONAL;
835         }
836
837 error:
838         /* reply_status didn't match -- it must be something weird */
839         LOG(L_CRIT, "ERROR: Oh my gooosh! We don't know whether to relay %d\n",
840                 new_code);
841 discard:
842         *should_store=0;
843         *should_relay=-1;
844         return RPS_DISCARDED;
845 }
846
847 /* Retransmits the last sent inbound reply.
848  * input: p_msg==request for which I want to retransmit an associated reply
849  * Returns  -1 - error
850  *           1 - OK
851  */
852 int t_retransmit_reply( struct cell *t )
853 {
854         static char b[BUF_SIZE];
855         int len;
856
857         /* first check if we managed to resolve topmost Via -- if
858            not yet, don't try to retransmit
859         */
860         if (!t->uas.response.dst.send_sock) {
861                 LOG(L_WARN, "WARNING: t_retransmit_reply: "
862                         "no resolved dst to retransmit\n");
863                 return -1;
864         }
865
866         /* we need to lock the transaction as messages from
867            upstream may change it continuously
868         */
869         LOCK_REPLIES( t );
870
871         if (!t->uas.response.buffer) {
872                 DBG("DBG: t_retransmit_reply: nothing to retransmit\n");
873                 goto error;
874         }
875
876         len=t->uas.response.buffer_len;
877         if ( len==0 || len>BUF_SIZE )  {
878                 DBG("DBG: t_retransmit_reply: "
879                         "zero length or too big to retransmit: %d\n", len);
880                 goto error;
881         }
882         memcpy( b, t->uas.response.buffer, len );
883         UNLOCK_REPLIES( t );
884         SEND_PR_BUFFER( & t->uas.response, b, len );
885         DBG("DEBUG: reply retransmitted. buf=%p: %.9s..., shmem=%p: %.9s\n", 
886                 b, b, t->uas.response.buffer, t->uas.response.buffer );
887         return 1;
888
889 error:
890         UNLOCK_REPLIES(t);
891         return -1;
892 }
893
894
895
896
897 int t_reply( struct cell *t, struct sip_msg* p_msg, unsigned int code, 
898         char * text )
899 {
900         return _reply( t, p_msg, code, text, 1 /* lock replies */ );
901 }
902
903 int t_reply_unsafe( struct cell *t, struct sip_msg* p_msg, unsigned int code, 
904         char * text )
905 {
906         return _reply( t, p_msg, code, text, 0 /* don't lock replies */ );
907 }
908
909
910
911
912
913 void set_final_timer( /* struct s_table *h_table, */ struct cell *t )
914 {
915         if ( !is_local(t) && t->uas.request->REQ_METHOD==METHOD_INVITE ) {
916                 /* crank timers for negative replies */
917                 if (t->uas.status>=300) {
918                         start_retr(&t->uas.response);
919                         return;
920                 }
921                 /* local UAS retransmits too */
922                 if (t->relaied_reply_branch==-2 && t->uas.status>=200) {
923                         /* we retransmit 200/INVs regardless of transport --
924                            even if TCP used, UDP could be used upstream and
925                            loose the 200, which is not retransmitted by proxies
926                         */
927                         force_retr( &t->uas.response );
928                         return;
929                 }
930         } 
931         put_on_wait(t);
932 }
933
934 void cleanup_uac_timers( struct cell *t )
935 {
936         int i;
937
938         /* reset FR/retransmission timers */
939         for (i=0; i<t->nr_of_outgoings; i++ )  {
940                 reset_timer( &t->uac[i].request.retr_timer );
941                 reset_timer( &t->uac[i].request.fr_timer );
942         }
943         DBG("DEBUG: cleanup_uac_timers: RETR/FR timers reset\n");
944 }
945
946 static int store_reply( struct cell *trans, int branch, struct sip_msg *rpl)
947 {
948 #               ifdef EXTRA_DEBUG
949                 if (trans->uac[branch].reply) {
950                         LOG(L_ERR, "ERROR: replacing stored reply; aborting\n");
951                         abort();
952                 }
953 #               endif
954
955                 /* when we later do things such as challenge aggregation,
956                    we should parse the message here before we conservate
957                    it in shared memory; -jiri
958                 */
959                 if (rpl==FAKED_REPLY)
960                         trans->uac[branch].reply=FAKED_REPLY;
961                 else
962                         trans->uac[branch].reply = sip_msg_cloner( rpl, 0 );
963
964                 if (! trans->uac[branch].reply ) {
965                         LOG(L_ERR, "ERROR: store_reply: can't alloc' clone memory\n");
966                         return 0;
967                 }
968
969                 return 1;
970 }
971
972 /* this is the code which decides what and when shall be relayed
973    upstream; note well -- it assumes it is entered locked with 
974    REPLY_LOCK and it returns unlocked!
975 */
976 enum rps relay_reply( struct cell *t, struct sip_msg *p_msg, int branch, 
977         unsigned int msg_status, branch_bm_t *cancel_bitmap )
978 {
979         int relay;
980         int save_clone;
981         char *buf;
982         /* length of outbound reply */
983         unsigned int res_len;
984         int relayed_code;
985         struct sip_msg *relayed_msg;
986         struct bookmark bm;
987         int totag_retr;
988         enum rps reply_status;
989         /* retransmission structure of outbound reply and request */
990         struct retr_buf *uas_rb;
991
992         /* keep compiler warnings about use of uninit vars silent */
993         res_len=0;
994         buf=0;
995         relayed_msg=0;
996         relayed_code=0;
997         totag_retr=0;
998
999
1000         /* remember, what was sent upstream to know whether we are
1001          * forwarding a first final reply or not */
1002
1003         /* *** store and relay message as needed *** */
1004         reply_status = t_should_relay_response(t, msg_status, branch, 
1005                 &save_clone, &relay, cancel_bitmap, p_msg );
1006         DBG("DEBUG: relay_reply: branch=%d, save=%d, relay=%d\n",
1007                 branch, save_clone, relay );
1008
1009         /* store the message if needed */
1010         if (save_clone) /* save for later use, typically branch picking */
1011         {
1012                 if (!store_reply( t, branch, p_msg ))
1013                         goto error01;
1014         }
1015
1016         uas_rb = & t->uas.response;
1017         if (relay >= 0 ) {
1018                 /* initialize sockets for outbound reply */
1019                 uas_rb->activ_type=msg_status;
1020                 /* only messages known to be relayed immediately will be
1021                  * be called on; we do not evoke this callback on messages
1022                  * stored in shmem -- they are fixed and one cannot change them
1023                  * anyway */
1024                 if (msg_status<300 && branch==relay
1025                 && has_tran_tmcbs(t,TMCB_RESPONSE_FWDED) ) {
1026                         run_trans_callbacks( TMCB_RESPONSE_FWDED, t, t->uas.request,
1027                                 p_msg, msg_status );
1028                 }
1029                 /* try bulding the outbound reply from either the current
1030                  * or a stored message */
1031                 relayed_msg = branch==relay ? p_msg :  t->uac[relay].reply;
1032                 if (relayed_msg==FAKED_REPLY) {
1033                         tm_stats->replied_localy++;
1034                         relayed_code = branch==relay
1035                                 ? msg_status : t->uac[relay].last_received;
1036
1037                         if (relayed_code>=180 && t->uas.request->to 
1038                                         && (get_to(t->uas.request)->tag_value.s==0 
1039                                         || get_to(t->uas.request)->tag_value.len==0)) {
1040                                 calc_crc_suffix( t->uas.request, tm_tag_suffix );
1041                                 buf = build_res_buf_from_sip_req(
1042                                                 relayed_code,
1043                                                 error_text(relayed_code),
1044                                                 &tm_tag,
1045                                                 t->uas.request, &res_len, &bm );
1046                         } else {
1047                                 buf = build_res_buf_from_sip_req( relayed_code,
1048                                         error_text(relayed_code), 0/* no to-tag */,
1049                                         t->uas.request, &res_len, &bm );
1050                         }
1051
1052                 } else {
1053                         relayed_code=relayed_msg->REPLY_STATUS;
1054                         buf = build_res_buf_from_sip_res( relayed_msg, &res_len );
1055                         /* if we build a message from shmem, we need to remove
1056                            via delete lumps which are now stirred in the shmem-ed
1057                            structure
1058                         */
1059                         if (branch!=relay) {
1060                                 free_via_clen_lump(&relayed_msg->add_rm);
1061                         }
1062                 }
1063                 update_reply_stats( relayed_code );
1064                 if (!buf) {
1065                         LOG(L_ERR, "ERROR: relay_reply: "
1066                                 "no mem for outbound reply buffer\n");
1067                         goto error02;
1068                 }
1069
1070                 /* attempt to copy the message to UAS's shmem:
1071                    - copy to-tag for ACK matching as well
1072                    -  allocate little a bit more for provisionals as
1073                       larger messages are likely to follow and we will be 
1074                       able to reuse the memory frag 
1075                 */
1076                 uas_rb->buffer = (char*)shm_resize( uas_rb->buffer, res_len +
1077                         (msg_status<200 ?  REPLY_OVERBUFFER_LEN : 0));
1078                 if (!uas_rb->buffer) {
1079                         LOG(L_ERR, "ERROR: relay_reply: cannot alloc reply shmem\n");
1080                         goto error03;
1081                 }
1082                 uas_rb->buffer_len = res_len;
1083                 memcpy( uas_rb->buffer, buf, res_len );
1084                 if (relayed_msg==FAKED_REPLY) { /* to-tags for local replies */
1085                         update_local_tags(t, &bm, uas_rb->buffer, buf);
1086                 }
1087                 tm_stats->replied_localy++;
1088
1089                 /* update the status ... */
1090                 t->uas.status = relayed_code;
1091                 t->relaied_reply_branch = relay;
1092
1093                 if (is_invite(t) && relayed_msg!=FAKED_REPLY
1094                 && relayed_code>=200 && relayed_code < 300
1095                 && has_tran_tmcbs( t, TMCB_RESPONSE_OUT|TMCB_E2EACK_IN) ) {
1096                         totag_retr=update_totag_set(t, relayed_msg);
1097                 }
1098         }; /* if relay ... */
1099
1100         UNLOCK_REPLIES( t );
1101
1102         /* send it now (from the private buffer) */
1103         if (relay >= 0) {
1104                 SEND_PR_BUFFER( uas_rb, buf, res_len );
1105                 DBG("DEBUG: reply relayed. buf=%p: %.9s..., shmem=%p: %.9s\n", 
1106                         buf, buf, uas_rb->buffer, uas_rb->buffer );
1107                 if (!totag_retr && has_tran_tmcbs(t, TMCB_RESPONSE_OUT) ) {
1108                         run_trans_callbacks( TMCB_RESPONSE_OUT, t, t->uas.request,
1109                                 relayed_msg, relayed_code);
1110                 }
1111                 pkg_free( buf );
1112         }
1113
1114         /* success */
1115         return reply_status;
1116
1117 error03:
1118         pkg_free( buf );
1119 error02:
1120         if (save_clone) {
1121                 if (t->uac[branch].reply!=FAKED_REPLY)
1122                         sip_msg_free( t->uac[branch].reply );
1123                 t->uac[branch].reply = NULL;    
1124         }
1125 error01:
1126         t_reply_unsafe( t, t->uas.request, 500, "Reply processing error" );
1127         UNLOCK_REPLIES(t);
1128         if (is_invite(t)) cancel_uacs( t, *cancel_bitmap );
1129         /* a serious error occured -- attempt to send an error reply;
1130            it will take care of clean-ups  */
1131
1132         /* failure */
1133         return RPS_ERROR;
1134 }
1135
1136 /* this is the "UAC" above transaction layer; if a final reply
1137    is received, it triggers a callback; note well -- it assumes
1138    it is entered locked with REPLY_LOCK and it returns unlocked!
1139 */
1140 enum rps local_reply( struct cell *t, struct sip_msg *p_msg, int branch, 
1141         unsigned int msg_status, branch_bm_t *cancel_bitmap)
1142 {
1143         /* how to deal with replies for local transaction */
1144         int local_store, local_winner;
1145         enum rps reply_status;
1146         struct sip_msg *winning_msg;
1147         int winning_code;
1148         int totag_retr;
1149         /* branch_bm_t cancel_bitmap; */
1150
1151         /* keep warning 'var might be used un-inited' silent */ 
1152         winning_msg=0;
1153         winning_code=0;
1154         totag_retr=0;
1155
1156         *cancel_bitmap=0;
1157
1158         reply_status=t_should_relay_response( t, msg_status, branch,
1159                 &local_store, &local_winner, cancel_bitmap, p_msg );
1160         DBG("DEBUG: local_reply: branch=%d, save=%d, winner=%d\n",
1161                 branch, local_store, local_winner );
1162         if (local_store) {
1163                 if (!store_reply(t, branch, p_msg))
1164                         goto error;
1165         }
1166         if (local_winner>=0) {
1167                 winning_msg= branch==local_winner 
1168                         ? p_msg :  t->uac[local_winner].reply;
1169                 if (winning_msg==FAKED_REPLY) {
1170                         tm_stats->replied_localy++;
1171                         winning_code = branch==local_winner
1172                                 ? msg_status : t->uac[local_winner].last_received;
1173                 } else {
1174                         winning_code=winning_msg->REPLY_STATUS;
1175                 }
1176                 t->uas.status = winning_code;
1177                 update_reply_stats( winning_code );
1178                 if (is_invite(t) && winning_msg!=FAKED_REPLY
1179                 && winning_code>=200 && winning_code <300
1180                 && has_tran_tmcbs(t,TMCB_RESPONSE_OUT|TMCB_E2EACK_IN) )  {
1181                         totag_retr=update_totag_set(t, winning_msg);
1182                 }
1183         }
1184         UNLOCK_REPLIES(t);
1185         if (local_winner>=0 && winning_code>=200 ) {
1186                 DBG("DEBUG: local transaction completed\n");
1187                 if (!totag_retr) {
1188                         if ( has_tran_tmcbs(t,TMCB_LOCAL_COMPLETED) )
1189                                 run_trans_callbacks( TMCB_LOCAL_COMPLETED, t, 0,
1190                                         winning_msg, winning_code );
1191                 }
1192         }
1193         return reply_status;
1194
1195 error:
1196         which_cancel(t, cancel_bitmap);
1197         UNLOCK_REPLIES(t);
1198         cleanup_uac_timers(t);
1199         if ( get_cseq(p_msg)->method.len==INVITE_LEN 
1200                 && memcmp( get_cseq(p_msg)->method.s, INVITE, INVITE_LEN)==0)
1201                 cancel_uacs( t, *cancel_bitmap );
1202         put_on_wait(t);
1203         return RPS_ERROR;
1204 }
1205
1206
1207
1208
1209
1210 /*  This function is called whenever a reply for our module is received; 
1211   * we need to register  this function on module initialization;
1212   *  Returns :   0 - core router stops
1213   *              1 - core router relay statelessly
1214   */
1215 int reply_received( struct sip_msg  *p_msg )
1216 {
1217
1218         int msg_status;
1219         char *ack;
1220         unsigned int ack_len;
1221         int branch;
1222         /* has the transaction completed now and we need to clean-up? */
1223         int reply_status;
1224         branch_bm_t cancel_bitmap;
1225         struct ua_client *uac;
1226         struct cell *t;
1227         str next_hop;
1228
1229         /* make sure we know the assosociated transaction ... */
1230         if (t_check( p_msg  , &branch )==-1)
1231                 return 1;
1232         /*... if there is none, tell the core router to fwd statelessly */
1233         t=get_t();
1234         if ( (t==0)||(t==T_UNDEFINED)) return 1;
1235
1236         cancel_bitmap=0;
1237         msg_status=p_msg->REPLY_STATUS;
1238
1239         uac=&t->uac[branch];
1240         DBG("DEBUG: reply_received: org. status uas=%d, "
1241                 "uac[%d]=%d local=%d is_invite=%d)\n",
1242                 t->uas.status, branch, uac->last_received, 
1243                 is_local(t), is_invite(t));
1244
1245         /* it's a cancel ... ? */
1246         if (get_cseq(p_msg)->method.len==CANCEL_LEN 
1247                 && memcmp( get_cseq(p_msg)->method.s, CANCEL, CANCEL_LEN)==0
1248                 /* .. which is not e2e ? ... */
1249                 && is_invite(t) ) {
1250                         /* ... then just stop timers */
1251                         reset_timer( &uac->local_cancel.retr_timer);
1252                         if ( msg_status >= 200 )
1253                                 reset_timer( &uac->local_cancel.fr_timer);
1254                         DBG("DEBUG: reply to local CANCEL processed\n");
1255                         goto done;
1256         }
1257
1258
1259         /* *** stop timers *** */
1260         /* stop retransmission */
1261         reset_timer( &uac->request.retr_timer);
1262         /* stop final response timer only if I got a final response */
1263         if ( msg_status >= 200 )
1264                 reset_timer( &uac->request.fr_timer);
1265                 /* acknowledge negative INVITE replies (do it before detailed
1266                  * on_reply processing, which may take very long, like if it
1267                  * is attempted to establish a TCP connection to a fail-over dst */
1268
1269         if (t->flags & T_IS_INVITE_FLAG) {
1270                 if (msg_status >= 300) {
1271                         ack = build_ack(p_msg, t, branch, &ack_len);
1272                         if (ack) {
1273                                 SEND_PR_BUFFER(&uac->request, ack, ack_len);
1274                                 shm_free(ack);
1275                         }
1276                 } else if ((t->flags & T_IS_LOCAL_FLAG) && msg_status >= 200) {
1277                         ack = build_local_ack(p_msg, t, branch, &ack_len, &next_hop);
1278                         if (ack) {
1279                                 if (send_local_ack(&next_hop, ack, ack_len) < 0) {
1280                                         LOG(L_ERR, "Error while seding local ACK\n");
1281                                 }
1282                                 shm_free(ack);
1283                         }
1284                 }
1285         }
1286              /* processing of on_reply block */
1287         if (t->on_reply) {
1288                 rmode=MODE_ONREPLY;
1289                      /* transfer transaction flag to message context */
1290                 if (t->uas.request) p_msg->flags=t->uas.request->flags;
1291                 if (run_actions(onreply_rlist[t->on_reply], p_msg)<0) 
1292                         LOG(L_ERR, "ERROR: on_reply processing failed\n");
1293                      /* destroy any eventual avps */
1294                 if (users_avps)
1295                         destroy_avps();
1296                      /* transfer current message context back to t */
1297                 if (t->uas.request) t->uas.request->flags=p_msg->flags;
1298         }
1299         LOCK_REPLIES( t );
1300         if ( is_local(t) ) {
1301                 reply_status=local_reply( t, p_msg, branch, msg_status, &cancel_bitmap );
1302         } else {
1303                 reply_status=relay_reply( t, p_msg, branch, msg_status, 
1304                         &cancel_bitmap );
1305         }
1306
1307         if (reply_status==RPS_ERROR)
1308                 goto done;
1309
1310         /* clean-up the transaction when transaction completed */
1311         if (reply_status==RPS_COMPLETED) {
1312                 /* no more UAC FR/RETR (if I received a 2xx, there may
1313                    be still pending branches ...
1314                 */
1315                 cleanup_uac_timers( t );        
1316                 if (is_invite(t)) cancel_uacs( t, cancel_bitmap );
1317                 /* FR for negative INVITES, WAIT anything else */
1318                 set_final_timer(  t );
1319         } 
1320
1321         /* update FR/RETR timers on provisional replies */
1322         if (msg_status<200) { /* provisional now */
1323                 if (is_invite(t)) {
1324                         /* invite: change FR to longer FR_INV, do not
1325                            attempt to restart retransmission any more
1326                         */
1327                         set_timer( & uac->request.fr_timer,
1328                                 FR_INV_TIMER_LIST );
1329                 } else {
1330                         /* non-invite: restart retransmisssions (slow now) */
1331                         uac->request.retr_list=RT_T2;
1332                         set_timer(  & uac->request.retr_timer, RT_T2 );
1333                 }
1334         } /* provisional replies */
1335
1336 done:
1337         /* don't try to relay statelessly neither on success
1338        (we forwarded statefuly) nor on error; on troubles, 
1339            simply do nothing; that will make the other party to 
1340            retransmit; hopefuly, we'll then be better off */
1341         return 0;
1342 }
1343
1344
1345
1346 int t_reply_with_body( struct cell *trans, unsigned int code, 
1347                 char * text, char * body, char * new_header, char * to_tag )
1348 {
1349         struct lump_rpl *hdr_lump;
1350         struct lump_rpl *body_lump;
1351         str  s_to_tag;
1352         str  rpl;
1353         int  ret;
1354         struct bookmark bm;
1355
1356         s_to_tag.s = to_tag;
1357         if(to_tag)
1358                 s_to_tag.len = strlen(to_tag);
1359
1360         /* mark the transaction as replied */
1361         if (code>=200) set_kr(REQ_RPLD);
1362
1363         /* add the lumps for new_header and for body (by bogdan) */
1364         if (new_header && strlen(new_header)) {
1365                 hdr_lump = add_lump_rpl( trans->uas.request, new_header,
1366                                          strlen(new_header), LUMP_RPL_HDR );
1367                 if ( !hdr_lump ) {
1368                         LOG(L_ERR,"ERROR:tm:t_reply_with_body: cannot add hdr lump\n");
1369                         goto error;
1370                 }
1371         } else {
1372                 hdr_lump = 0;
1373         }
1374
1375         /* body lump */
1376         if(body && strlen(body)) {
1377                 body_lump = add_lump_rpl( trans->uas.request, body, strlen(body),
1378                         LUMP_RPL_BODY );
1379                 if (body_lump==0) {
1380                         LOG(L_ERR,"ERROR:tm:t_reply_with_body: cannot add body lump\n");
1381                         goto error_1;
1382                 }
1383         } else {
1384                 body_lump = 0;
1385         }
1386
1387         rpl.s = build_res_buf_from_sip_req(
1388                         code, text, &s_to_tag,
1389                         trans->uas.request, (unsigned int*)&rpl.len, &bm);
1390
1391         /* since the msg (trans->uas.request) is a clone into shm memory, to avoid
1392          * memory leak or crashing (lumps are create in private memory) I will
1393          * remove the lumps by myself here (bogdan) */
1394         if ( hdr_lump ) {
1395                 unlink_lump_rpl( trans->uas.request, hdr_lump);
1396                 free_lump_rpl( hdr_lump );
1397         }
1398         if( body_lump ) {
1399                 unlink_lump_rpl( trans->uas.request, body_lump);
1400                 free_lump_rpl( body_lump );
1401         }
1402
1403         if (rpl.s==0) {
1404                 LOG(L_ERR,"ERROR:tm:t_reply_with_body: failed in doing "
1405                         "build_res_buf_from_sip_req()\n");
1406                 goto error;
1407         }
1408
1409         DBG("t_reply_with_body: buffer computed\n");
1410         // frees 'res.s' ... no panic !
1411         ret=_reply_light( trans, rpl.s, rpl.len, code, text, 
1412                 s_to_tag.s, s_to_tag.len, 1 /* lock replies */, &bm );
1413         /* this is ugly hack -- the function caller may wish to continue with
1414          * transction and I unref; however, there is now only one use from
1415          * vm/fifo_vm_reply and I'm currently to lazy to export UNREF; -jiri
1416          */
1417         UNREF(trans);
1418
1419         return ret;
1420 error_1:
1421         if ( hdr_lump ) {
1422                 unlink_lump_rpl( trans->uas.request, hdr_lump);
1423                 free_lump_rpl( hdr_lump );
1424         }
1425 error:
1426         return -1;
1427 }
1428
1429
1430
1431 /*
1432   Syntax:
1433
1434   ":vm_reply:[response file]\n
1435   code\n
1436   reason\n
1437   trans_id\n
1438   to_tag\n
1439   [new headers]\n
1440   \n
1441   [Body]\n
1442   .\n
1443   \n"
1444  */
1445 int fifo_t_reply( FILE *stream, char *response_file )
1446 {
1447         int ret;
1448         struct cell *trans;
1449         char code[16];
1450         char reason[128];
1451         char trans_id[128];
1452         char new_headers[MAX_HEADER];
1453         char body[MAX_BODY];
1454         char to_tag[128];
1455         str sc;       /*  code */
1456         str sr;       /*  reason */
1457         str sti;      /*  trans_id */
1458         str snh;      /*  new_headers */
1459         str sb;       /*  body */
1460         str sttag;    /*  to-tag */
1461         unsigned int hash_index,label,icode;
1462
1463         sc.s=code;
1464         sr.s=reason;
1465         sti.s=trans_id;
1466         snh.s=new_headers; sb.s=body;
1467         sttag.s=to_tag; sttag.len=0;
1468
1469
1470         /*  get the infos from FIFO server */
1471
1472         DBG("DEBUG: fifo_t_reply: ############### begin ##############\n");
1473
1474         if (!read_line(sc.s, 16, stream, &sc.len)||sc.len==0) {
1475                 LOG(L_ERR, "ERROR: fifo_t_reply: code expected\n");
1476                 fifo_reply(response_file, "400 fifo_t_reply: code expected");
1477                 return -1;
1478         }
1479
1480         icode = str2s(sc.s,sc.len,&ret);
1481         if(ret){
1482                 LOG(L_ERR, "ERROR: fifo_t_reply: code(int) has wrong format\n");
1483                 fifo_reply(response_file, "400 fifo_t_reply: code(int) has"
1484                         " wrong format");
1485                 return -1;
1486         }
1487
1488         if(!read_line(sr.s, 128, stream, &sr.len)||sr.len==0){
1489                 LOG(L_ERR, "ERROR: fifo_t_reply: reason expected\n");
1490                 fifo_reply(response_file, "400 fifo_t_reply: reason expected");
1491                 return -1;
1492         }
1493         sr.s[sr.len]='\0';
1494
1495         if (!read_line(sti.s, 128, stream, &sti.len)||sti.len==0) {
1496                 LOG(L_ERR, "ERROR: fifo_t_reply: trans_id expected\n");
1497                 fifo_reply(response_file, "400 fifo_t_reply: trans_id expected");
1498                 return -1;
1499         }
1500         sti.s[sti.len]='\0';
1501         DBG("DEBUG: fifo_t_reply: trans_id=%.*s\n",sti.len,sti.s);
1502
1503         if(sscanf(sti.s,"%u:%u", &hash_index, &label) != 2){
1504                 LOG(L_ERR, "ERROR: fifo_t_reply: invalid trans_id (%s)\n",sti.s);
1505                 fifo_reply(response_file, "400 fifo_t_reply: invalid trans_id");
1506                 return -1;
1507         }
1508         DBG("DEBUG: fifo_t_reply: hash_index=%u label=%u\n",hash_index,label);
1509
1510         if( !read_line(sttag.s,64,stream,&sttag.len) || sttag.len==0 ){
1511                 LOG(L_ERR, "ERROR: fifo_t_reply: to-tag expected\n");
1512                 fifo_reply(response_file, "400 fifo_t_reply: to-ta expected");
1513                 return -1;
1514         }
1515         sttag.s[sttag.len]='\0';
1516         DBG("DEBUG: fifo_t_reply: to-tag: %.*s\n",sttag.len,sttag.s);
1517
1518         /* read the new headers */
1519         if (!read_line_set(snh.s, MAX_HEADER, stream, &snh.len)) {
1520                 LOG(L_ERR, "ERROR: fifo_t_reply: while reading new headers\n");
1521                 fifo_reply(response_file, "400 fifo_t_reply: while reading "
1522                         "new headers");
1523                 return -1;
1524         }
1525         snh.s[snh.len]='\0';
1526         DBG("DEBUG: fifo_t_reply: new headers: %.*s\n", snh.len, snh.s);
1527
1528         /*  body can be empty ... */
1529         read_body(sb.s, MAX_BODY, stream, &sb.len);
1530         sb.s[sb.len]='\0';
1531         DBG("DEBUG: fifo_t_reply: body: <%.*s>\n", sb.len, sb.s);
1532
1533         if( t_lookup_ident(&trans,hash_index,label)<0 ) {
1534                 LOG(L_ERR,"ERROR: fifo_t_reply: lookup failed\n");
1535                 fifo_reply(response_file, "481 fifo_t_reply: no such transaction");
1536                 return -1;
1537         }
1538
1539         /* it's refcounted now, t_reply_with body unrefs for me -- I can 
1540          * continue but may not use T anymore  */
1541         ret = t_reply_with_body(trans,icode,reason,body,new_headers,to_tag);
1542
1543         if (ret<0) {
1544                 LOG(L_ERR, "ERROR: fifo_t_reply: reply failed\n");
1545                 fifo_reply(response_file, "500 fifo_t_reply: reply failed");
1546                 return -1;
1547         }
1548
1549         fifo_reply(response_file, "200 fifo_t_reply succeeded\n");
1550         DBG("DEBUG: fifo_t_reply: ################ end ##############\n");
1551         return 1;
1552 }
1553
1554
1555 static int parse_transid(str* s, unsigned int* index, unsigned int* label)
1556 {
1557         char* buf;
1558
1559         if (!s || !index || !label) {
1560                 LOG(L_ERR, "parse_transid: Invalid parameter value\n");
1561                 return -1;
1562         }
1563
1564         buf = (char*)pkg_malloc(s->len + 1);
1565         if (!buf) {
1566                 LOG(L_ERR, "parse_transid: No memory left\n");
1567                 return -1;
1568         }
1569
1570         memcpy(buf, s->s, s->len + 1);
1571         buf[s->len] = '\0';
1572         
1573         if (sscanf(buf, "%u:%u", index, label) != 2) {
1574                 LOG(L_ERR, "parse_transid: Invalid trans_id (%s)\n", buf);
1575                 pkg_free(buf);
1576                 return -1;
1577         }
1578
1579         DBG("parse_transid: hash_index=%u label=%u\n", *index, *label);
1580         pkg_free(buf);
1581         return 0;
1582 }
1583
1584
1585
1586 static int send_reply(struct cell *trans, unsigned int code, str* text, str* body, str* headers, str* to_tag)
1587 {
1588         struct lump_rpl *hdr_lump, *body_lump;
1589         str rpl;
1590         int ret;
1591         struct bookmark bm;
1592
1593              /* mark the transaction as replied */
1594         if (code >= 200) set_kr(REQ_RPLD);
1595
1596              /* add the lumps for new_header and for body (by bogdan) */
1597         if (headers && headers->len) {
1598                 hdr_lump = add_lump_rpl(trans->uas.request, headers->s, headers->len, LUMP_RPL_HDR);
1599                 if (!hdr_lump) {
1600                         LOG(L_ERR, "send_reply: cannot add hdr lump\n");
1601                         goto sr_error;
1602                 }
1603         } else {
1604                 hdr_lump = 0;
1605         }
1606
1607              /* body lump */
1608         if (body && body->len) {
1609                 body_lump = add_lump_rpl(trans->uas.request, body->s, body->len, LUMP_RPL_BODY);
1610                 if (body_lump == 0) {
1611                         LOG(L_ERR,"send_reply: cannot add body lump\n");
1612                         goto sr_error_1;
1613                 }
1614         } else {
1615                 body_lump = 0;
1616         }
1617
1618              /* We can safely zero-terminate the text here, because it is followed
1619               * by next line in the received message
1620               */
1621         text->s[text->len] = '\0';
1622         rpl.s = build_res_buf_from_sip_req(code, text->s, to_tag, trans->uas.request, (unsigned int*)&rpl.len, &bm);
1623
1624              /* since the msg (trans->uas.request) is a clone into shm memory, to avoid
1625               * memory leak or crashing (lumps are create in private memory) I will
1626               * remove the lumps by myself here (bogdan) */
1627         if (hdr_lump) {
1628                 unlink_lump_rpl(trans->uas.request, hdr_lump);
1629                 free_lump_rpl(hdr_lump);
1630         }
1631         if (body_lump) {
1632                 unlink_lump_rpl(trans->uas.request, body_lump);
1633                 free_lump_rpl(body_lump);
1634         }
1635
1636         if (rpl.s == 0) {
1637                 LOG(L_ERR,"send_reply: failed in build_res_buf_from_sip_req\n");
1638                 goto sr_error;
1639         }
1640
1641         ret = _reply_light(trans, rpl.s, rpl.len, code, text->s,  to_tag->s, to_tag->len, 1 /* lock replies */, &bm);
1642              /* this is ugly hack -- the function caller may wish to continue with
1643               * transction and I unref; however, there is now only one use from
1644               * vm/fifo_vm_reply and I'm currently to lazy to export UNREF; -jiri
1645               */
1646         UNREF(trans);
1647         return ret;
1648  sr_error_1:
1649         if (hdr_lump) {
1650                 unlink_lump_rpl(trans->uas.request, hdr_lump);
1651                 free_lump_rpl(hdr_lump);
1652         }
1653  sr_error:
1654         return -1;
1655 }
1656
1657
1658
1659 int unixsock_t_reply(str* msg)
1660 {
1661         int ret;
1662         struct cell *trans;
1663         static char new_headers[MAX_HEADER];
1664         str code, reason, transid, headers, body, to_tag;
1665         unsigned int hash_index, label, icode;
1666
1667         headers.s = new_headers;
1668         headers.len = MAX_HEADER;
1669
1670         if (unixsock_read_line(&code, msg) != 0) {
1671                 unixsock_reply_asciiz("400 Reason code expected\n");
1672                 goto err;
1673         }
1674
1675         icode = str2s(code.s, code.len, &ret);
1676         if (ret) {
1677                 unixsock_reply_printf("400 Reason code has wrong format\n");
1678                 goto err;
1679         }
1680
1681         if (unixsock_read_line(&reason, msg) != 0) {
1682                 unixsock_reply_asciiz("400 Reason phrase expected\n");
1683                 goto err;
1684         }
1685
1686         if (unixsock_read_line(&transid, msg) != 0) {
1687                 unixsock_reply_asciiz("400 Transaction ID expected\n");
1688                 goto err;
1689         }
1690
1691         if (parse_transid(&transid, &hash_index, &label) < 0) {
1692                 unixsock_reply_asciiz("400 Error while parsing transaction ID\n");
1693                 goto err;
1694         }
1695
1696         if (unixsock_read_line(&to_tag, msg) != 0) {
1697                 unixsock_reply_asciiz("400 To tag expected\n");
1698                 goto err;
1699         }
1700
1701              /* read the new headers */
1702         if (unixsock_read_lineset(&headers, msg) < 0) {
1703                 unixsock_reply_asciiz("400 Error while reading new headers\n");
1704                 goto err;
1705         }
1706
1707         DBG("lineset: %.*s\n", headers.len, headers.s);
1708              
1709         /*  body can be empty ... */
1710         if (unixsock_read_body(&body, msg) < 0) {
1711                 unixsock_reply_asciiz("400 Error while reading body\n");
1712                 goto err;
1713         }
1714
1715         DBG("body: %.*s\n", body.len, body.s);
1716         
1717         if (t_lookup_ident(&trans, hash_index, label) < 0) {
1718                 LOG(L_ERR,"unixsock_t_reply: lookup failed\n");
1719                 unixsock_reply_asciiz("481 No such transaction\n");
1720                 goto err;
1721         }
1722
1723              /* it's refcounted now, t_reply_with body unrefs for me -- I can 
1724               * continue but may not use T anymore  
1725               */
1726         ret = send_reply(trans, icode, &reason, &body, &headers, &to_tag);
1727         if (ret < 0) {
1728                 LOG(L_ERR, "unixsock_t_reply: reply failed\n");
1729                 unixsock_reply_asciiz("500 Reply failed\n");
1730                 goto err;
1731         }
1732
1733         unixsock_reply_asciiz("200 Succeeded\n");
1734         unixsock_reply_send();
1735         return 1;
1736
1737  err:
1738         unixsock_reply_send();
1739         return -1;
1740 }