73805ee7152b63a32cde3770c37808ed34aa7067
[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-02-28 scratchpad compatibility abandoned (jiri)
31  * 2003-01-27  next baby-step to removing ZT - PRESERVE_ZT (jiri)
32  * 2003-01-19  faked lump list created in on_reply handlers
33  * 2003-02-13  updated to use rb->dst (andrei)
34  * 2003-02-18  replaced TOTAG_LEN w/ TOTAG_VALUE_LEN (TOTAG_LEN was defined
35  *             twice with different values!)  (andrei)
36  */
37
38 #include "defs.h"
39
40 #include "../../comp_defs.h"
41
42 #include "../../hash_func.h"
43 #include "t_funcs.h"
44 #include "../../dprint.h"
45 #include "../../config.h"
46 #include "../../parser/parser_f.h"
47 #include "../../ut.h"
48 #include "../../timer.h"
49 #include "../../error.h"
50 #include "../../action.h"
51 #include "../../dset.h"
52 #include "../../tags.h"
53 #include "../../data_lump.h"
54
55 #include "t_hooks.h"
56 #include "t_funcs.h"
57 #include "t_reply.h"
58 #include "t_cancel.h"
59 #include "t_msgbuilder.h"
60 #include "t_lookup.h"
61 #include "t_fwd.h"
62 #include "fix_lumps.h"
63 #include "t_stats.h"
64
65 /* are we processing original or shmemed request ? */
66 enum route_mode rmode=MODE_REQUEST;
67
68 /* private place where we create to-tags for replies */
69 static char tm_tags[TOTAG_VALUE_LEN];
70 static char *tm_tag_suffix;
71
72 /* where to go if there is no positive reply */
73 static int goto_on_negative=0;
74
75 /* we store the reply_route # in private memory which is
76    then processed during t_relay; we cannot set this value
77    before t_relay creates transaction context or after
78    t_relay when a reply may arrive after we set this
79    value; that's why we do it how we do it, i.e.,
80    *inside*  t_relay using hints stored in private memory
81    before t_reay is called
82 */
83   
84   
85 int t_on_negative( unsigned int go_to )
86 {
87         goto_on_negative=go_to;
88         return 1;
89 }
90
91
92 unsigned int get_on_negative()
93 {
94         return goto_on_negative;
95 }
96
97 void tm_init_tags()
98 {
99         init_tags(tm_tags, &tm_tag_suffix, 
100                 "SER-TM/tags", TM_TAG_SEPARATOR );
101 }
102
103
104 static char *build_ack(struct sip_msg* rpl,struct cell *trans,int branch,
105         unsigned int *ret_len)
106 {
107         str to;
108
109     if ( parse_headers(rpl,HDR_TO, 0)==-1 || !rpl->to )
110     {
111         LOG(L_ERR, "ERROR: t_build_ACK: "
112             "cannot generate a HBH ACK if key HFs in reply missing\n");
113         return NULL;
114     }
115         to.s=rpl->to->name.s;
116         to.len=rpl->to->len;
117     return build_local( trans, branch, ret_len,
118         ACK, ACK_LEN, &to );
119 }
120
121
122 /* create a temporary faked message environment in which a conserved
123  * t->uas.request in shmem is partially duplicated to pkgmem
124  * to allow pkg-based actions to use it; 
125  *
126  * if restore parameter is set, the environment is restored to the
127  * original setting and return value is unsignificant (always 0); 
128  * otherwise  a faked environment if created; if that fails,
129  * false is returned
130  */
131 static int faked_env(struct sip_msg *fake, 
132                                 struct cell *_t,
133                                 struct sip_msg *shmem_msg,
134                                 int _restore )
135 {
136         static enum route_mode backup_mode;
137         static struct cell *backup_t;
138         static unsigned int backup_msgid;
139
140         if (_restore) goto restore;
141
142         /* 
143      on_negative_reply faked msg now copied from shmem msg (as opposed
144      to zero-ing) -- more "read-only" actions (exec in particular) will 
145      work from reply_route as they will see msg->from, etc.; caution, 
146      rw actions may append some pkg stuff to msg, which will possibly be 
147      never released (shmem is released in a single block)
148     */
149         memcpy( fake, shmem_msg, sizeof(struct sip_msg));
150
151         /* if we set msg_id to something different from current's message
152        id, the first t_fork will properly clean new branch URIs
153         */
154         fake->id=shmem_msg->id-1;
155         /* set items, which will be duped to pkg_mem, to zero, so that
156          * "restore" called on error does not free the original items */
157         fake->add_rm=0;
158         fake->new_uri.s=0; fake->new_uri.len=0; 
159
160         /* remember we are back in request processing, but process
161          * a shmem-ed replica of the request; advertise it in rmode;
162          * for example t_reply needs to know that
163          */
164         backup_mode=rmode;
165         rmode=MODE_ONREPLY_REQUEST;
166         /* also, tm actions look in beginning whether tranaction is
167          * set -- whether we are called from a reply-processing 
168          * or a timer process, we need to set current transaction;
169          * otherwise the actions would attempt to look the transaction
170          * up (unnecessary overhead, refcounting)
171          */
172         /* backup */
173         backup_t=get_t();
174         backup_msgid=global_msg_id;
175         /* fake transaction and message id */
176         global_msg_id=fake->id;
177         set_t(_t);
178
179         /* environment is set up now, try to fake the message */
180
181         /* new_uri can change -- make a private copy */
182         if (shmem_msg->new_uri.s!=0 && shmem_msg->new_uri.len!=0) {
183                 fake->new_uri.s=pkg_malloc(shmem_msg->new_uri.len+1);
184                 if (!fake->new_uri.s) {
185                         LOG(L_ERR, "ERROR: faked_env: no uri/pkg mem\n");
186                         goto restore;
187                 }
188                 fake->new_uri.len=shmem_msg->new_uri.len;
189                 memcpy( fake->new_uri.s, shmem_msg->new_uri.s, 
190                         fake->new_uri.len);
191                 fake->new_uri.s[fake->new_uri.len]=0;
192         } 
193
194         /* create a duplicated lump list to which actions can add
195          * new pkg items 
196          */
197         if (shmem_msg->add_rm) {
198                 fake->add_rm=dup_lump_list(shmem_msg->add_rm);
199                 if (!fake->add_rm) { /* non_emty->empty ... failure */
200                         LOG(L_ERR, "ERROR: on_negative_reply: lump dup failed\n");
201                         goto restore;
202                 }
203         }
204         /* success */
205         return 1;
206
207 restore:
208         /* restore original environment and destroy faked message */
209         free_duped_lump_list(fake->add_rm);
210         if (fake->new_uri.s) pkg_free(fake->new_uri.s);
211         set_t(backup_t);
212         global_msg_id=backup_msgid;
213         rmode=backup_mode;
214         return 0;
215 }
216
217
218
219 /* the main code of stateful replying */
220 static int _reply( struct cell *t, struct sip_msg* p_msg, unsigned int code,
221     char * text, int lock );
222
223 /* This is the neuralgical point of reply processing -- called
224  * from within a REPLY_LOCK, t_should_relay_response decides
225  * how a reply shall be processed and how transaction state is
226  * affected.
227  *
228  * Checks if the new reply (with new_code status) should be sent or not
229  *  based on the current
230  * transactin status.
231  * Returns      - branch number (0,1,...) which should be relayed
232  *         -1 if nothing to be relayed
233  */
234 static enum rps t_should_relay_response( struct cell *Trans , int new_code,
235         int branch , int *should_store, int *should_relay,
236         branch_bm_t *cancel_bitmap, struct sip_msg *reply )
237 {
238         int b, lowest_b, lowest_s, dummy;
239         struct sip_msg faked_msg, *origin_rq;
240         unsigned int on_neg;
241
242         /* note: this code never lets replies to CANCEL go through;
243            we generate always a local 200 for CANCEL; 200s are
244            not relayed because it's not an INVITE transaction;
245            >= 300 are not relayed because 200 was already sent
246            out
247         */
248         DBG("->>>>>>>>> T_code=%d, new_code=%d\n",Trans->uas.status,new_code);
249         /* if final response sent out, allow only INVITE 2xx  */
250         if ( Trans->uas.status >= 200 ) {
251                 if (new_code>=200 && new_code < 300  && 
252 #ifdef _BUG_FIX /* t may be local, in which case there is no request */
253                         Trans->uas.request->REQ_METHOD==METHOD_INVITE) {
254 #endif
255                         Trans->is_invite ) {
256                         DBG("DBG: t_should_relay: 200 INV after final sent\n");
257                         *should_store=0;
258                         Trans->uac[branch].last_received=new_code;
259                         *should_relay=branch;
260                         return RPS_PUSHED_AFTER_COMPLETION;
261                 } else {
262                         /* except the exception above, too late  messages will
263                            be discarded */
264                         *should_store=0;
265                         *should_relay=-1;
266                         return RPS_DISCARDED;
267                 }
268         } 
269
270         /* no final response sent yet */
271         /* negative replies subject to fork picking */
272         if (new_code >=300 ) {
273                 /* negative reply received after we have received
274                    a final reply previously -- discard , unless
275                    a recoverable error occured, in which case
276                    retry
277             */
278                 if (Trans->uac[branch].last_received>=200) {
279                         /* then drop! */
280                         *should_store=0;
281                         *should_relay=-1;
282                         return RPS_DISCARDED;
283                 }
284
285                 Trans->uac[branch].last_received=new_code;
286                 /* if all_final return lowest */
287                 lowest_b=-1; lowest_s=999;
288                 for ( b=0; b<Trans->nr_of_outgoings ; b++ ) {
289                         /* "fake" for the currently processed branch */
290                         if (b==branch) {
291                                 if (new_code<lowest_s) {
292                                         lowest_b=b;
293                                         lowest_s=new_code;
294                                 }
295                                 continue;
296                         }
297                         /* skip 'empty branches' */
298                         if (!Trans->uac[b].request.buffer) continue;
299                         /* there is still an unfinished UAC transaction; wait now! */
300                         if ( Trans->uac[b].last_received<200 ) {
301                                 *should_store=1;        
302                                 *should_relay=-1;
303                                 return RPS_STORE;
304                         }
305                         if ( Trans->uac[b].last_received<lowest_s )
306                         {
307                                 lowest_b =b;
308                                 lowest_s = Trans->uac[b].last_received;
309                         }
310                 } /* find lowest branch */
311                 if (lowest_b==-1) {
312                         LOG(L_CRIT, "ERROR: t_should_relay_response: lowest==-1\n");
313                 }
314                 /* no more pending branches -- try if that changes after
315                    a callback
316                 */
317                 callback_event( TMCB_ON_NEGATIVE, Trans, 
318                         lowest_b==branch?reply:Trans->uac[lowest_b].reply, 
319                         lowest_s );
320
321                 /* here, we create a faked environment, from which we
322                  * return to request processing, if marked to do so */
323                 origin_rq=Trans->uas.request;
324                 on_neg=Trans->on_negative;
325                 if (on_neg) {
326                         DBG("DBG: on_negative_reply processed for transaction %p\n", 
327                                         Trans);
328                         if (faked_env(&faked_msg, Trans, Trans->uas.request, 
329                                                                         0 /* create fake */ )) 
330                         {
331                                 /* use the faked message later in forwarding */
332                                 origin_rq=&faked_msg;
333                                 /* run a reply_route action if some was marked */
334                                 if (run_actions(reply_rlist[on_neg], &faked_msg )<0)
335                                         LOG(L_ERR, "ERROR: on_negative_reply: "
336                                                 "Error in do_action\n");
337                         } else { /* faked_env creation error */
338                                 LOG(L_ERR, "ERROR: on_negative_reply: faked_env failed\n");
339                                 on_neg=0;
340                         } 
341                 } /* if (on_neg) */
342
343
344                 /* look if the callback perhaps replied transaction; it also
345                    covers the case in which a transaction is replied localy
346                    on CANCEL -- then it would make no sense to proceed to
347                    new branches bellow
348                 */
349                 if (Trans->uas.status >= 200) {
350                         *should_store=0;
351                         *should_relay=-1;
352                         /* this might deserve an improvement -- if something
353                            was already replied, it was put on wait and then,
354                            returning RPS_COMPLETED will make t_on_reply
355                            put it on wait again; perhaps splitting put_on_wait
356                            from send_reply or a new RPS_ code would be healthy
357                         */
358                         if (on_neg) faked_env(&faked_msg, 0, 0, 1 );
359                         return RPS_COMPLETED;
360                 }
361                 /* look if the callback introduced new branches ... */
362                 init_branch_iterator();
363                 if (next_branch(&dummy)) {
364                         if (t_forward_nonack(Trans, origin_rq,
365                                                 (struct proxy_l *) 0,
366                                                 Trans->uas.response.dst.proto)<0) {
367                                 /* error ... behave as if we did not try to
368                                    add a new branch */
369                                 *should_store=0;
370                                 *should_relay=lowest_b;
371                                 if (on_neg) faked_env(&faked_msg, 0, 0, 1 );
372                                 return RPS_COMPLETED;
373                         }
374                         /* we succeded to launch new branches -- await
375                            result
376                         */
377                         *should_store=1;
378                         *should_relay=-1;
379                         if (on_neg) faked_env(&faked_msg, 0, 0, 1 );
380                         return RPS_STORE;
381                 }
382                 /* really no more pending branches -- return lowest code */
383                 *should_store=0;
384                 *should_relay=lowest_b;
385                 if (on_neg) faked_env(&faked_msg, 0, 0, 1 );
386                 /* we dont need 'which_cancel' here -- all branches 
387                    known to have completed */
388                 /* which_cancel( Trans, cancel_bitmap ); */
389                 return RPS_COMPLETED;
390         } 
391
392         /* not >=300 ... it must be 2xx or provisional 1xx */
393         if (new_code>=100) {
394                 /* 1xx and 2xx except 100 will be relayed */
395                 Trans->uac[branch].last_received=new_code;
396                 *should_store=0;
397                 *should_relay= new_code==100? -1 : branch;
398                 if (new_code>=200 ) {
399                         which_cancel( Trans, cancel_bitmap );
400                         return RPS_COMPLETED;
401                 } else return RPS_PROVISIONAL;
402         }
403
404         /* reply_status didn't match -- it must be something weird */
405         LOG(L_CRIT, "ERROR: Oh my gooosh! We don't know whether to relay %d\n",
406                 new_code);
407         *should_store=0;
408         *should_relay=-1;
409         return RPS_DISCARDED;
410 }
411
412 /* Retransmits the last sent inbound reply.
413  * input: p_msg==request for which I want to retransmit an associated reply
414  * Returns  -1 - error
415  *           1 - OK
416  */
417 int t_retransmit_reply( struct cell *t )
418 {
419         static char b[BUF_SIZE];
420         int len;
421
422         /* first check if we managed to resolve topmost Via -- if
423            not yet, don't try to retransmit
424         */
425         if (!t->uas.response.dst.send_sock) {
426                 LOG(L_WARN, "WARNING: t_retransmit_reply: "
427                         "no resolved dst to retransmit\n");
428                 return -1;
429         }
430
431         /* we need to lock the transaction as messages from
432            upstream may change it continuously
433         */
434         LOCK_REPLIES( t );
435
436         if (!t->uas.response.buffer) {
437                 DBG("DBG: t_retransmit_reply: nothing to retransmit\n");
438                 goto error;
439         }
440
441         len=t->uas.response.buffer_len;
442         if ( len==0 || len>BUF_SIZE )  {
443                 DBG("DBG: t_retransmit_reply: "
444                         "zero length or too big to retransmit: %d\n", len);
445                 goto error;
446         }
447         memcpy( b, t->uas.response.buffer, len );
448         UNLOCK_REPLIES( t );
449         SEND_PR_BUFFER( & t->uas.response, b, len );
450         DBG("DEBUG: reply retransmitted. buf=%p: %.9s..., shmem=%p: %.9s\n", 
451                 b, b, t->uas.response.buffer, t->uas.response.buffer );
452         return 1;
453
454 error:
455         UNLOCK_REPLIES(t);
456         return -1;
457 }
458
459
460 #ifdef VOICE_MAIL
461 static int _reply_light( struct cell *trans, char* buf, unsigned int len,
462                          unsigned int code, char * text, 
463                          char *to_tag, unsigned int to_tag_len, int lock );
464
465 int t_reply_light( struct cell *t, char* buf, unsigned int len,
466                    unsigned int code, char * text,
467                    char *to_tag, unsigned int to_tag_len )
468 {
469     return _reply_light( t, buf, len, code, text, to_tag, to_tag_len, 1 /* lock replies */ );
470 }
471 #endif
472
473 int t_reply( struct cell *t, struct sip_msg* p_msg, unsigned int code, 
474         char * text )
475 {
476         return _reply( t, p_msg, code, text, 1 /* lock replies */ );
477 }
478
479 int t_reply_unsafe( struct cell *t, struct sip_msg* p_msg, unsigned int code, 
480         char * text )
481 {
482         return _reply( t, p_msg, code, text, 0 /* don't lock replies */ );
483 }
484
485
486
487 /* send a UAS reply
488  * returns 1 if everything was OK or -1 for error
489  */
490 static int _reply( struct cell *trans, struct sip_msg* p_msg, 
491         unsigned int code, char * text, int lock )
492 {
493 #ifndef VOICE_MAIL
494         unsigned int len, buf_len=0;
495         char * buf;
496         struct retr_buf *rb;
497
498         branch_bm_t cancel_bitmap;
499 #else
500         unsigned int len;
501         char * buf;
502 #endif
503
504         if (code>=200) trans->kr|=REQ_RPLD;
505         /*
506         buf = build_res_buf_from_sip_req(code,text,trans->uas.tag->s,
507                 trans->uas.tag->len, trans->uas.request,&len);
508         */
509 #ifndef VOICE_MAIL
510         cancel_bitmap=0;
511 #endif
512         /* compute the buffer in private memory prior to entering lock;
513          * create to-tag if needed */
514         if (code>=180 && p_msg->to 
515                         && (get_to(p_msg)->tag_value.s==0 
516                             || get_to(p_msg)->tag_value.len==0)) {
517                 calc_crc_suffix( p_msg, tm_tag_suffix );
518                 buf = build_res_buf_from_sip_req(code,text, 
519                                 tm_tags, TOTAG_VALUE_LEN, 
520                                 p_msg,&len);
521 #ifdef VOICE_MAIL
522
523                 return _reply_light(trans,buf,len,code,text,
524                                     tm_tags, TOTAG_VALUE_LEN,
525                                     lock);
526 #endif
527         } else {
528                 buf = build_res_buf_from_sip_req(code,text, 0,0, /* no to-tag */
529                         p_msg,&len);
530 #ifdef VOICE_MAIL
531
532                 return _reply_light(trans,buf,len,code,text,
533                                     0,0, /* no to-tag */
534                                     lock);
535 #endif
536         }
537         DBG("DEBUG: t_reply: buffer computed\n");
538 #ifdef VOICE_MAIL
539 }
540
541 static int _reply_light( struct cell *trans, char* buf, unsigned int len,
542                          unsigned int code, char * text, 
543                          char *to_tag, unsigned int to_tag_len, int lock )
544 {
545         struct retr_buf *rb;
546         unsigned int buf_len=0;
547         branch_bm_t cancel_bitmap=0;
548 #endif
549         if (!buf)
550         {
551                 DBG("DEBUG: t_reply: response building failed\n");
552                 /* determine if there are some branches to be cancelled */
553                 if (trans->is_invite) {
554                         if (lock) LOCK_REPLIES( trans );
555                         which_cancel(trans, &cancel_bitmap );
556                         if (lock) UNLOCK_REPLIES( trans );
557                 }
558                 /* and clean-up, including cancellations, if needed */
559                 goto error;
560         }
561
562         if (lock) LOCK_REPLIES( trans );
563         if (trans->is_invite) which_cancel(trans, &cancel_bitmap );
564         if (trans->uas.status>=200) {
565                 LOG( L_ERR, "ERROR: t_reply: can't generate %d reply"
566                         " when a final %d was sent out\n", code, trans->uas.status);
567                 goto error2;
568         }
569         rb = & trans->uas.response;
570         rb->activ_type=code;
571
572         trans->uas.status = code;
573         buf_len = rb->buffer ? len : len + REPLY_OVERBUFFER_LEN;
574         rb->buffer = (char*)shm_resize( rb->buffer, buf_len );
575         /* puts the reply's buffer to uas.response */
576         if (! rb->buffer ) {
577                         LOG(L_ERR, "ERROR: t_reply: cannot allocate shmem buffer\n");
578                         goto error2;
579         }
580         rb->buffer_len = len ;
581         memcpy( rb->buffer , buf , len );
582 #ifdef VOICE_MAIL
583         if(to_tag){
584             trans->uas.to_tag.s = (char*)shm_resize( trans->uas.to_tag.s, to_tag_len );
585             if(! trans->uas.to_tag.s ){
586                         LOG(L_ERR, "ERROR: t_reply: cannot allocate shmem buffer\n");
587                         // Is it ok? or should i free rb->buffer also, 
588                         // or will it be freed in free_cell() ?
589                         goto error2; 
590             }
591             trans->uas.to_tag.len = to_tag_len;
592             memcpy( trans->uas.to_tag.s, to_tag, to_tag_len );
593         }
594 #endif
595         /* needs to be protected too because what timers are set depends
596            on current transactions status */
597         /* t_update_timers_after_sending_reply( rb ); */
598         update_reply_stats( code );
599         tm_stats->replied_localy++;
600         if (lock) UNLOCK_REPLIES( trans );
601         
602         /* do UAC cleanup procedures in case we generated
603            a final answer whereas there are pending UACs */
604         if (code>=200) {
605                 if (trans->local) {
606                         DBG("DEBUG: local transaction completed from _reply\n");
607                         callback_event( TMCB_LOCAL_COMPLETED, trans, FAKED_REPLY, code );
608                         if (trans->completion_cb) 
609                                 trans->completion_cb( trans, FAKED_REPLY, code, 0 /* empty param */);
610                 } else {
611                         callback_event( TMCB_REPLY, trans, FAKED_REPLY, code );
612                 }
613
614                 cleanup_uac_timers( trans );
615                 if (trans->is_invite) cancel_uacs( trans, cancel_bitmap );
616                 set_final_timer(  trans );
617         }
618
619         /* send it out */
620         /* first check if we managed to resolve topmost Via -- if
621            not yet, don't try to retransmit
622         */
623         if (!trans->uas.response.dst.send_sock) {
624                 LOG(L_ERR, "ERROR: _reply: no resolved dst to send reply to\n");
625         } else {
626                 SEND_PR_BUFFER( rb, buf, len );
627                 DBG("DEBUG: reply sent out. buf=%p: %.9s..., shmem=%p: %.9s\n", 
628                         buf, buf, rb->buffer, rb->buffer );
629         }
630         pkg_free( buf ) ;
631         DBG("DEBUG: t_reply: finished\n");
632         return 1;
633
634 error2:
635         if (lock) UNLOCK_REPLIES( trans );
636         pkg_free ( buf );
637 error:
638         /* do UAC cleanup */
639         cleanup_uac_timers( trans );
640         if (trans->is_invite) cancel_uacs( trans, cancel_bitmap );
641         /* we did not succeed -- put the transaction on wait */
642         put_on_wait(trans);
643         return -1;
644 }
645
646 void set_final_timer( /* struct s_table *h_table, */ struct cell *t )
647 {
648         if ( !t->local 
649                 && t->uas.request->REQ_METHOD==METHOD_INVITE 
650                 && t->uas.status>=300  ) {
651                         /* crank timers for negative replies */
652                         start_retr( &t->uas.response );
653         } else put_on_wait(t);
654 }
655
656 void cleanup_uac_timers( struct cell *t )
657 {
658         int i;
659
660         /* reset FR/retransmission timers */
661         for (i=0; i<t->nr_of_outgoings; i++ )  {
662                 reset_timer( &t->uac[i].request.retr_timer );
663                 reset_timer( &t->uac[i].request.fr_timer );
664         }
665         DBG("DEBUG: cleanup_uacs: RETR/FR timers reset\n");
666 }
667
668 static int store_reply( struct cell *trans, int branch, struct sip_msg *rpl)
669 {
670 #               ifdef EXTRA_DEBUG
671                 if (trans->uac[branch].reply) {
672                         LOG(L_ERR, "ERROR: replacing stored reply; aborting\n");
673                         abort();
674                 }
675 #               endif
676
677                 /* when we later do things such as challenge aggregation,
678                    we should parse the message here before we conservate
679                    it in shared memory; -jiri
680                 */
681                 if (rpl==FAKED_REPLY)
682                         trans->uac[branch].reply=FAKED_REPLY;
683                 else
684                         trans->uac[branch].reply = sip_msg_cloner( rpl );
685
686                 if (! trans->uac[branch].reply ) {
687                         LOG(L_ERR, "ERROR: store_reply: can't alloc' clone memory\n");
688                         return 0;
689                 }
690
691                 return 1;
692 }
693
694 /* this is the code which decides what and when shall be relayed
695    upstream; note well -- it assumes it is entered locked with 
696    REPLY_LOCK and it returns unlocked!
697 */
698 enum rps relay_reply( struct cell *t, struct sip_msg *p_msg, int branch, 
699         unsigned int msg_status, branch_bm_t *cancel_bitmap )
700 {
701         int relay;
702         int save_clone;
703         char *buf;
704         /* length of outbound reply */
705         unsigned int res_len;
706         int relayed_code;
707         struct sip_msg *relayed_msg;
708 #ifdef _TOTAG
709         str     to_tag;
710 #endif
711         enum rps reply_status;
712         /* retransmission structure of outbound reply and request */
713         struct retr_buf *uas_rb;
714
715         /* keep compiler warnings about use of uninit vars silent */
716         res_len=0;
717         buf=0;
718         relayed_msg=0;
719         relayed_code=0;
720
721
722         /* remember, what was sent upstream to know whether we are
723            forwarding a first final reply or not */
724
725         /* *** store and relay message as needed *** */
726         reply_status = t_should_relay_response(t, msg_status, branch, 
727                 &save_clone, &relay, cancel_bitmap, p_msg );
728         DBG("DEBUG: relay_reply: branch=%d, save=%d, relay=%d\n",
729                 branch, save_clone, relay );
730
731         /* store the message if needed */
732         if (save_clone) /* save for later use, typically branch picking */
733         {
734                 if (!store_reply( t, branch, p_msg ))
735                         goto error01;
736         }
737
738         uas_rb = & t->uas.response;
739         if (relay >= 0 ) {
740
741                 /* initialize sockets for outbound reply */
742                 uas_rb->activ_type=msg_status;
743                 /* only messages known to be relayed immediately will be
744                    be called on; we do not evoke this callback on messages
745                    stored in shmem -- they are fixed and one cannot change them
746                    anyway 
747         */
748                 if (msg_status<300 && branch==relay) {
749                         callback_event( TMCB_REPLY_IN, t, p_msg, msg_status );
750                 }
751                 /* try bulding the outbound reply from either the current
752                or a stored message */
753                 relayed_msg = branch==relay ? p_msg :  t->uac[relay].reply;
754                 if (relayed_msg ==FAKED_REPLY) {
755                         tm_stats->replied_localy++;
756                         relayed_code = branch==relay
757                                 ? msg_status : t->uac[relay].last_received;
758
759                         if (relayed_code>=180 && t->uas.request->to 
760                                         && (get_to(t->uas.request)->tag_value.s==0 
761                                         || get_to(t->uas.request)->tag_value.len==0)) {
762                                 calc_crc_suffix( t->uas.request, tm_tag_suffix );
763                                 buf = build_res_buf_from_sip_req(
764                                                 relayed_code,
765                                                 error_text(relayed_code),
766                                                 tm_tags, TOTAG_VALUE_LEN, 
767                                                 t->uas.request, &res_len );
768                         } else {
769                                 buf = build_res_buf_from_sip_req( relayed_code,
770                                         error_text(relayed_code), 0,0, /* no to-tag */
771                                         t->uas.request, &res_len );
772                         }
773
774                 } else {
775                         relayed_code=relayed_msg->REPLY_STATUS;
776                         buf = build_res_buf_from_sip_res( relayed_msg, &res_len );
777                         /* if we build a message from shmem, we need to remove
778                            via delete lumps which are now stirred in the shmem-ed
779                            structure
780                         */
781                         if (branch!=relay) {
782                                 free_via_lump(&relayed_msg->repl_add_rm);
783                         }
784                 }
785                 update_reply_stats( relayed_code );
786                 if (!buf) {
787                         LOG(L_ERR, "ERROR: relay_reply: "
788                                 "no mem for outbound reply buffer\n");
789                         goto error02;
790                 }
791
792                 /* attempt to copy the message to UAS's shmem:
793                    - copy to-tag for ACK matching as well
794                    -  allocate little a bit more for provisionals as
795                       larger messages are likely to follow and we will be 
796                       able to reuse the memory frag 
797                 */
798                 uas_rb->buffer = (char*)shm_resize( uas_rb->buffer, res_len +
799                         (msg_status<200 ?  REPLY_OVERBUFFER_LEN : 0));
800                 if (!uas_rb->buffer) {
801                         LOG(L_ERR, "ERROR: relay_reply: cannot alloc reply shmem\n");
802                         goto error03;
803                 }
804                 uas_rb->buffer_len = res_len;
805                 memcpy( uas_rb->buffer, buf, res_len );
806 #ifdef _TOTAG
807                 /* to tag now */
808                 if (relayed_code>=300 && t->is_invite) {
809                         if (relayed_msg!=FAKED_REPLY) {
810                                 to_tag=get_to(relayed_msg)->tag_value;
811                                 t->uas.to_tag.s=(char *)shm_resize( t->uas.to_tag.s,
812                                         to_tag.len );
813                                 if (!t->uas.to_tag.s) {
814                                         LOG(L_ERR, "ERROR: no shmem for to-tag\n");
815                                         goto error04;
816                                 }
817                                 t->uas.to_tag.len=to_tag.len;
818                                 memcpy(t->uas.to_tag.s, to_tag.s, to_tag.len );
819                         } else {
820                                 if (t->uas.to_tag.s) shm_free(t->uas.to_tag.s);
821                                 t->uas.to_tag.s=0;
822                                 t->uas.to_tag.len=0;
823                         }
824                 }
825 #endif
826
827                 /* update the status ... */
828                 t->uas.status = relayed_code;
829                 t->relaied_reply_branch = relay;
830         }; /* if relay ... */
831
832         UNLOCK_REPLIES( t );
833
834         /* send it now (from the private buffer) */
835         if (relay >= 0) {
836                 SEND_PR_BUFFER( uas_rb, buf, res_len );
837                 DBG("DEBUG: reply relayed. buf=%p: %.9s..., shmem=%p: %.9s\n", 
838                         buf, buf, uas_rb->buffer, uas_rb->buffer );
839                 callback_event( TMCB_REPLY, t, relayed_msg, relayed_code );
840                 pkg_free( buf );
841         }
842
843         /* success */
844         return reply_status;
845
846 #ifdef _TOTAG
847 error04:
848         shm_free( uas_rb->buffer );
849         uas_rb->buffer=0;
850 #endif
851 error03:
852         pkg_free( buf );
853 error02:
854         if (save_clone) {
855                 if (t->uac[branch].reply!=FAKED_REPLY)
856                         sip_msg_free( t->uac[branch].reply );
857                 t->uac[branch].reply = NULL;    
858         }
859 error01:
860         t_reply_unsafe( t, t->uas.request, 500, "Reply processing error" );
861         UNLOCK_REPLIES(t);
862         if (t->is_invite) cancel_uacs( t, *cancel_bitmap );
863         /* a serious error occured -- attempt to send an error reply;
864            it will take care of clean-ups 
865         */
866
867         /* failure */
868         return RPS_ERROR;
869 }
870
871 /* this is the "UAC" above transaction layer; if a final reply
872    is received, it triggers a callback; note well -- it assumes
873    it is entered locked with REPLY_LOCK and it returns unlocked!
874 */
875 enum rps local_reply( struct cell *t, struct sip_msg *p_msg, int branch, 
876         unsigned int msg_status, branch_bm_t *cancel_bitmap)
877 {
878         /* how to deal with replies for local transaction */
879         int local_store, local_winner;
880         enum rps reply_status;
881         struct sip_msg *winning_msg;
882         int winning_code;
883         /* branch_bm_t cancel_bitmap; */
884
885         /* keep warning 'var might be used un-inited' silent */ 
886         winning_msg=0;
887         winning_code=0;
888
889         *cancel_bitmap=0;
890
891         reply_status=t_should_relay_response( t, msg_status, branch,
892                 &local_store, &local_winner, cancel_bitmap, p_msg );
893         DBG("DEBUG: local_reply: branch=%d, save=%d, winner=%d\n",
894                 branch, local_store, local_winner );
895         if (local_store) {
896                 if (!store_reply(t, branch, p_msg))
897                         goto error;
898         }
899         if (local_winner>=0) {
900                 winning_msg= branch==local_winner 
901                         ? p_msg :  t->uac[local_winner].reply;
902                 if (winning_msg==FAKED_REPLY) {
903                         tm_stats->replied_localy++;
904                         winning_code = branch==local_winner
905                                 ? msg_status : t->uac[local_winner].last_received;
906                 } else {
907                         winning_code=winning_msg->REPLY_STATUS;
908                 }
909                 t->uas.status = winning_code;
910                 update_reply_stats( winning_code );
911         }
912         UNLOCK_REPLIES(t);
913         if (local_winner>=0 && winning_code>=200 ) {
914                 DBG("DEBUG: local transaction completed\n");
915                 callback_event( TMCB_LOCAL_COMPLETED, t, winning_msg, winning_code );
916                 if (t->completion_cb) 
917                         t->completion_cb( t, winning_msg, winning_code, 0 /* empty param */);
918         }
919         return reply_status;
920
921 error:
922         which_cancel(t, cancel_bitmap);
923         UNLOCK_REPLIES(t);
924         cleanup_uac_timers(t);
925         if ( get_cseq(p_msg)->method.len==INVITE_LEN 
926                 && memcmp( get_cseq(p_msg)->method.s, INVITE, INVITE_LEN)==0)
927                 cancel_uacs( t, *cancel_bitmap );
928         put_on_wait(t);
929         return RPS_ERROR;
930 }
931
932
933
934
935
936 /*  This function is called whenever a reply for our module is received; 
937   * we need to register  this function on module initialization;
938   *  Returns :   0 - core router stops
939   *              1 - core router relay statelessly
940   */
941 int t_on_reply( struct sip_msg  *p_msg )
942 {
943
944         int msg_status;
945         char *ack;
946         unsigned int ack_len;
947         int branch;
948         /* has the transaction completed now and we need to clean-up? */
949         int reply_status;
950         branch_bm_t cancel_bitmap;
951         struct ua_client *uac;
952         struct cell *t;
953
954
955         /* make sure we know the assosociated transaction ... */
956         if (t_check( p_msg  , &branch )==-1)
957                 return 1;
958         /*... if there is none, tell the core router to fwd statelessly */
959         t=get_t();
960         if ( t<=0 ) return 1;
961
962         cancel_bitmap=0;
963         msg_status=p_msg->REPLY_STATUS;
964
965         uac=&t->uac[branch];
966         DBG("DEBUG: t_on_reply: org. status uas=%d, "
967                 "uac[%d]=%d local=%d is_invite=%d)\n",
968                 t->uas.status, branch, uac->last_received, 
969                 t->local, t->is_invite);
970
971         /* it's a cancel ... ? */
972         if (get_cseq(p_msg)->method.len==CANCEL_LEN 
973                 && memcmp( get_cseq(p_msg)->method.s, CANCEL, CANCEL_LEN)==0
974                 /* .. which is not e2e ? ... */
975                 && t->is_invite ) {
976                         /* ... then just stop timers */
977                         reset_timer( &uac->local_cancel.retr_timer);
978                         if ( msg_status >= 200 )
979                                 reset_timer( &uac->local_cancel.fr_timer);
980                         DBG("DEBUG: reply to local CANCEL processed\n");
981                         goto done;
982         }
983
984
985         /* *** stop timers *** */
986         /* stop retransmission */
987         reset_timer( &uac->request.retr_timer);
988         /* stop final response timer only if I got a final response */
989         if ( msg_status >= 200 )
990                 reset_timer( &uac->request.fr_timer);
991
992         LOCK_REPLIES( t );
993         if (t->local) {
994                 reply_status=local_reply( t, p_msg, branch, msg_status, &cancel_bitmap );
995         } else {
996                 reply_status=relay_reply( t, p_msg, branch, msg_status, 
997                         &cancel_bitmap );
998         }
999
1000         if (reply_status==RPS_ERROR)
1001                 goto done;
1002
1003         /* acknowledge negative INVITE replies */       
1004         if (t->is_invite && (msg_status>=300 || (t->local && msg_status>=200))) {
1005                 ack = build_ack( p_msg, t, branch , &ack_len);
1006                 if (ack) {
1007                         SEND_PR_BUFFER( &uac->request, ack, ack_len );
1008                         shm_free(ack);
1009                 }
1010         } /* ack-ing negative INVITE replies */
1011
1012         /* clean-up the transaction when transaction completed */
1013         if (reply_status==RPS_COMPLETED) {
1014                 /* no more UAC FR/RETR (if I received a 2xx, there may
1015                    be still pending branches ...
1016                 */
1017                 cleanup_uac_timers( t );        
1018                 if (t->is_invite) cancel_uacs( t, cancel_bitmap );
1019                 /* FR for negative INVITES, WAIT anything else */
1020                 set_final_timer(  t );
1021         } 
1022
1023         /* update FR/RETR timers on provisional replies */
1024         if (msg_status<200) { /* provisional now */
1025                 if (t->is_invite) { 
1026                         /* invite: change FR to longer FR_INV, do not
1027                            attempt to restart retransmission any more
1028                         */
1029                         set_timer( & uac->request.fr_timer,
1030                                 FR_INV_TIMER_LIST );
1031                 } else {
1032                         /* non-invite: restart retransmisssions (slow now) */
1033                         uac->request.retr_list=RT_T2;
1034                         set_timer(  & uac->request.retr_timer, RT_T2 );
1035                 }
1036         } /* provisional replies */
1037
1038 done:
1039         /* don't try to relay statelessly neither on success
1040        (we forwarded statefuly) nor on error; on troubles, 
1041            simply do nothing; that will make the other party to 
1042            retransmit; hopefuly, we'll then be better off */
1043         return 0;
1044 }
1045
1046 #ifdef VOICE_MAIL
1047
1048 #include <assert.h>
1049
1050 int t_reply_with_body( struct sip_msg* p_msg, unsigned int code, char * text, char * body, char * new_header, char * to_tag )
1051 {
1052     struct cell * t;
1053     //char to_tag[64];
1054     str  s_to_tag,sb,snh;
1055     char* res_buf;
1056     int res_len,ret;
1057
1058     /*  check if we have a transaction */
1059     if (t_check(p_msg, 0)==-1) {
1060         LOG(L_ERR,"ERROR: t_reply_with_body: no transaction found.\n");
1061         return -1;
1062     }
1063
1064     t=get_t();
1065     assert(t);
1066
1067     s_to_tag.s = to_tag;
1068     if(to_tag)
1069         s_to_tag.len = strlen(to_tag);
1070
1071     // mark the transaction as replied
1072     t->kr|=REQ_RPLD;
1073
1074     /* compute the response */
1075     sb.s = body;
1076     sb.len = strlen(body);
1077     snh.s = new_header;
1078     snh.len = strlen(new_header);
1079
1080     res_buf = build_res_buf_with_body_from_sip_req(code,text, s_to_tag.s, s_to_tag.len,
1081                                                    sb.s,sb.len,
1082                                                    snh.s,snh.len,
1083                                                    p_msg,&res_len);
1084     
1085     DBG("t_reply_with_body: buffer computed\n");
1086     // frees 'res_buf' ... no panic !
1087     ret = t_reply_light(t, res_buf, res_len, code, text,
1088                         s_to_tag.s, s_to_tag.len);
1089
1090     // TODO: i'm not sure i should do this here ...
1091     if(t_unref(p_msg) == -1)
1092         LOG(L_WARN,"WARNING: fifo_t_reply: could not unref transaction %p\n",t);
1093
1094     return ret;
1095 }
1096
1097 #endif