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