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