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