b0db11fb993070163cddb8ab5d659b911459a305
[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
495 int t_reply( struct cell *t, struct sip_msg* p_msg, unsigned int code, 
496         char * text )
497 {
498         return _reply( t, p_msg, code, text, 1 /* lock replies */ );
499 }
500
501 int t_reply_unsafe( struct cell *t, struct sip_msg* p_msg, unsigned int code, 
502         char * text )
503 {
504         return _reply( t, p_msg, code, text, 0 /* don't lock replies */ );
505 }
506
507
508
509 /* send a UAS reply
510  * returns 1 if everything was OK or -1 for error
511  */
512 static int _reply( struct cell *trans, struct sip_msg* p_msg, 
513         unsigned int code, char * text, int lock )
514 {
515         unsigned int len, buf_len=0;
516         char * buf;
517         struct retr_buf *rb;
518
519         branch_bm_t cancel_bitmap;
520
521         if (code>=200) trans->kr|=REQ_RPLD;
522         /*
523         buf = build_res_buf_from_sip_req(code,text,trans->uas.tag->s,
524                 trans->uas.tag->len, trans->uas.request,&len);
525         */
526         cancel_bitmap=0;
527         /* compute the buffer in private memory prior to entering lock;
528          * create to-tag if needed */
529         if (code>=180 && p_msg->to 
530                         && (get_to(p_msg)->tag_value.s==0 
531                             || get_to(p_msg)->tag_value.len==0)) {
532                 calc_crc_suffix( p_msg, tm_tag_suffix );
533                 buf = build_res_buf_from_sip_req(code,text, 
534                                 tm_tags, TOTAG_LEN, 
535                                 p_msg,&len);
536         } else {
537                 buf = build_res_buf_from_sip_req(code,text, 0,0, /* no to-tag */
538                         p_msg,&len);
539         }
540         DBG("DEBUG: t_reply: buffer computed\n");
541         if (!buf)
542         {
543                 DBG("DEBUG: t_reply: response building failed\n");
544                 /* determine if there are some branches to be cancelled */
545                 if (trans->is_invite) {
546                         if (lock) LOCK_REPLIES( trans );
547                         which_cancel(trans, &cancel_bitmap );
548                         if (lock) UNLOCK_REPLIES( trans );
549                 }
550                 /* and clean-up, including cancellations, if needed */
551                 goto error;
552         }
553
554         if (lock) LOCK_REPLIES( trans );
555         if (trans->is_invite) which_cancel(trans, &cancel_bitmap );
556         if (trans->uas.status>=200) {
557                 LOG( L_ERR, "ERROR: t_reply: can't generate %d reply"
558                         " when a final %d was sent out\n", code, trans->uas.status);
559                 goto error2;
560         }
561         rb = & trans->uas.response;
562         rb->activ_type=code;
563
564         trans->uas.status = code;
565         buf_len = rb->buffer ? len : len + REPLY_OVERBUFFER_LEN;
566         rb->buffer = (char*)shm_resize( rb->buffer, buf_len );
567         /* puts the reply's buffer to uas.response */
568         if (! rb->buffer ) {
569                         LOG(L_ERR, "ERROR: t_reply: cannot allocate shmem buffer\n");
570                         goto error2;
571         }
572         rb->buffer_len = len ;
573         memcpy( rb->buffer , buf , len );
574         /* needs to be protected too because what timers are set depends
575            on current transactions status */
576         /* t_update_timers_after_sending_reply( rb ); */
577         update_reply_stats( code );
578         tm_stats->replied_localy++;
579         if (lock) UNLOCK_REPLIES( trans );
580         
581         /* do UAC cleanup procedures in case we generated
582            a final answer whereas there are pending UACs */
583         if (code>=200) {
584                 if (trans->local) {
585                         DBG("DEBUG: local transaction completed from _reply\n");
586                         callback_event( TMCB_LOCAL_COMPLETED, trans, FAKED_REPLY, code );
587                         if (trans->completion_cb) 
588                                 trans->completion_cb( trans, FAKED_REPLY, code, 0 /* empty param */);
589                 } else {
590                         callback_event( TMCB_REPLY, trans, FAKED_REPLY, code );
591                 }
592
593                 cleanup_uac_timers( trans );
594                 if (trans->is_invite) cancel_uacs( trans, cancel_bitmap );
595                 set_final_timer(  trans );
596         }
597
598         /* send it out */
599         /* first check if we managed to resolve topmost Via -- if
600            not yet, don't try to retransmit
601         */
602         if (!trans->uas.response.send_sock) {
603                 LOG(L_ERR, "ERROR: _reply: no resolved dst to send reply to\n");
604         } else {
605                 SEND_PR_BUFFER( rb, buf, len );
606                 DBG("DEBUG: reply sent out. buf=%p: %.9s..., shmem=%p: %.9s\n", 
607                         buf, buf, rb->buffer, rb->buffer );
608         }
609         pkg_free( buf ) ;
610         DBG("DEBUG: t_reply: finished\n");
611         return 1;
612
613 error2:
614         if (lock) UNLOCK_REPLIES( trans );
615         pkg_free ( buf );
616 error:
617         /* do UAC cleanup */
618         cleanup_uac_timers( trans );
619         if (trans->is_invite) cancel_uacs( trans, cancel_bitmap );
620         /* we did not succeed -- put the transaction on wait */
621         put_on_wait(trans);
622         return -1;
623 }
624
625 void set_final_timer( /* struct s_table *h_table, */ struct cell *t )
626 {
627         if ( !t->local 
628                 && t->uas.request->REQ_METHOD==METHOD_INVITE 
629                 && t->uas.status>=300  ) {
630                         /* crank timers for negative replies */
631                         start_retr( &t->uas.response );
632         } else put_on_wait(t);
633 }
634
635 void cleanup_uac_timers( struct cell *t )
636 {
637         int i;
638
639         /* reset FR/retransmission timers */
640         for (i=0; i<t->nr_of_outgoings; i++ )  {
641                 reset_timer( &t->uac[i].request.retr_timer );
642                 reset_timer( &t->uac[i].request.fr_timer );
643         }
644         DBG("DEBUG: cleanup_uacs: RETR/FR timers reset\n");
645 }
646
647 static int store_reply( struct cell *trans, int branch, struct sip_msg *rpl)
648 {
649 #               ifdef EXTRA_DEBUG
650                 if (trans->uac[branch].reply) {
651                         LOG(L_ERR, "ERROR: replacing stored reply; aborting\n");
652                         abort();
653                 }
654 #               endif
655
656                 /* when we later do things such as challenge aggregation,
657                    we should parse the message here before we conservate
658                    it in shared memory; -jiri
659                 */
660                 if (rpl==FAKED_REPLY)
661                         trans->uac[branch].reply=FAKED_REPLY;
662                 else
663                         trans->uac[branch].reply = sip_msg_cloner( rpl );
664
665                 if (! trans->uac[branch].reply ) {
666                         LOG(L_ERR, "ERROR: store_reply: can't alloc' clone memory\n");
667                         return 0;
668                 }
669
670                 return 1;
671 }
672
673 /* this is the code which decides what and when shall be relayed
674    upstream; note well -- it assumes it is entered locked with 
675    REPLY_LOCK and it returns unlocked!
676 */
677 enum rps relay_reply( struct cell *t, struct sip_msg *p_msg, int branch, 
678         unsigned int msg_status, branch_bm_t *cancel_bitmap )
679 {
680         int relay;
681         int save_clone;
682         char *buf;
683         /* length of outbound reply */
684         unsigned int res_len;
685         int relayed_code;
686         struct sip_msg *relayed_msg;
687 #ifdef _TOTAG
688         str     to_tag;
689 #endif
690         enum rps reply_status;
691         /* retransmission structure of outbound reply and request */
692         struct retr_buf *uas_rb;
693
694         /* keep compiler warnings about use of uninit vars silent */
695         res_len=0;
696         buf=0;
697         relayed_msg=0;
698         relayed_code=0;
699
700
701         /* remember, what was sent upstream to know whether we are
702            forwarding a first final reply or not */
703
704         /* *** store and relay message as needed *** */
705         reply_status = t_should_relay_response(t, msg_status, branch, 
706                 &save_clone, &relay, cancel_bitmap, p_msg );
707         DBG("DEBUG: relay_reply: branch=%d, save=%d, relay=%d\n",
708                 branch, save_clone, relay );
709
710         /* store the message if needed */
711         if (save_clone) /* save for later use, typically branch picking */
712         {
713                 if (!store_reply( t, branch, p_msg ))
714                         goto error01;
715         }
716
717         uas_rb = & t->uas.response;
718         if (relay >= 0 ) {
719
720                 /* initialize sockets for outbound reply */
721                 uas_rb->activ_type=msg_status;
722                 /* only messages known to be relayed immediately will be
723                    be called on; we do not evoke this callback on messages
724                    stored in shmem -- they are fixed and one cannot change them
725                    anyway 
726         */
727                 if (msg_status<300 && branch==relay) {
728                         callback_event( TMCB_REPLY_IN, t, p_msg, msg_status );
729                 }
730                 /* try bulding the outbound reply from either the current
731                or a stored message */
732                 relayed_msg = branch==relay ? p_msg :  t->uac[relay].reply;
733                 if (relayed_msg ==FAKED_REPLY) {
734                         tm_stats->replied_localy++;
735                         relayed_code = branch==relay
736                                 ? msg_status : t->uac[relay].last_received;
737
738                         if (relayed_code>=180 && t->uas.request->to 
739                                         && (get_to(t->uas.request)->tag_value.s==0 
740                                         || get_to(t->uas.request)->tag_value.len==0)) {
741                                 calc_crc_suffix( t->uas.request, tm_tag_suffix );
742                                 buf = build_res_buf_from_sip_req(
743                                                 relayed_code,
744                                                 error_text(relayed_code),
745                                                 tm_tags, TOTAG_LEN, 
746                                                 t->uas.request, &res_len );
747                         } else {
748                                 buf = build_res_buf_from_sip_req( relayed_code,
749                                         error_text(relayed_code), 0,0, /* no to-tag */
750                                         t->uas.request, &res_len );
751                         }
752
753                 } else {
754                         relayed_code=relayed_msg->REPLY_STATUS;
755                         buf = build_res_buf_from_sip_res( relayed_msg, &res_len );
756                         /* if we build a message from shmem, we need to remove
757                            via delete lumps which are now stirred in the shmem-ed
758                            structure
759                         */
760                         if (branch!=relay) {
761                                 free_via_lump(&relayed_msg->repl_add_rm);
762                         }
763                 }
764                 update_reply_stats( relayed_code );
765                 if (!buf) {
766                         LOG(L_ERR, "ERROR: relay_reply: "
767                                 "no mem for outbound reply buffer\n");
768                         goto error02;
769                 }
770
771                 /* attempt to copy the message to UAS's shmem:
772                    - copy to-tag for ACK matching as well
773                    -  allocate little a bit more for provisionals as
774                       larger messages are likely to follow and we will be 
775                       able to reuse the memory frag 
776                 */
777                 uas_rb->buffer = (char*)shm_resize( uas_rb->buffer, res_len +
778                         (msg_status<200 ?  REPLY_OVERBUFFER_LEN : 0));
779                 if (!uas_rb->buffer) {
780                         LOG(L_ERR, "ERROR: relay_reply: cannot alloc reply shmem\n");
781                         goto error03;
782                 }
783                 uas_rb->buffer_len = res_len;
784                 memcpy( uas_rb->buffer, buf, res_len );
785 #ifdef _TOTAG
786                 /* to tag now */
787                 if (relayed_code>=300 && t->is_invite) {
788                         if (relayed_msg!=FAKED_REPLY) {
789                                 to_tag=get_to(relayed_msg)->tag_value;
790                                 t->uas.to_tag.s=(char *)shm_resize( t->uas.to_tag.s,
791                                         to_tag.len );
792                                 if (!t->uas.to_tag.s) {
793                                         LOG(L_ERR, "ERROR: no shmem for to-tag\n");
794                                         goto error04;
795                                 }
796                                 t->uas.to_tag.len=to_tag.len;
797                                 memcpy(t->uas.to_tag.s, to_tag.s, to_tag.len );
798                         } else {
799                                 if (t->uas.to_tag.s) shm_free(t->uas.to_tag.s);
800                                 t->uas.to_tag.s=0;
801                                 t->uas.to_tag.len=0;
802                         }
803                 }
804 #endif
805
806                 /* update the status ... */
807                 t->uas.status = relayed_code;
808                 t->relaied_reply_branch = relay;
809         }; /* if relay ... */
810
811         UNLOCK_REPLIES( t );
812
813         /* send it now (from the private buffer) */
814         if (relay >= 0) {
815                 SEND_PR_BUFFER( uas_rb, buf, res_len );
816                 DBG("DEBUG: reply relayed. buf=%p: %.9s..., shmem=%p: %.9s\n", 
817                         buf, buf, uas_rb->buffer, uas_rb->buffer );
818                 callback_event( TMCB_REPLY, t, relayed_msg, relayed_code );
819                 pkg_free( buf );
820         }
821
822         /* success */
823         return reply_status;
824
825 #ifdef _TOTAG
826 error04:
827         shm_free( uas_rb->buffer );
828         uas_rb->buffer=0;
829 #endif
830 error03:
831         pkg_free( buf );
832 error02:
833         if (save_clone) {
834                 if (t->uac[branch].reply!=FAKED_REPLY)
835                         sip_msg_free( t->uac[branch].reply );
836                 t->uac[branch].reply = NULL;    
837         }
838 error01:
839         t_reply_unsafe( t, t->uas.request, 500, "Reply processing error" );
840         UNLOCK_REPLIES(t);
841         if (t->is_invite) cancel_uacs( t, *cancel_bitmap );
842         /* a serious error occured -- attempt to send an error reply;
843            it will take care of clean-ups 
844         */
845
846         /* failure */
847         return RPS_ERROR;
848 }
849
850 /* this is the "UAC" above transaction layer; if a final reply
851    is received, it triggers a callback; note well -- it assumes
852    it is entered locked with REPLY_LOCK and it returns unlocked!
853 */
854 enum rps local_reply( struct cell *t, struct sip_msg *p_msg, int branch, 
855         unsigned int msg_status, branch_bm_t *cancel_bitmap)
856 {
857         /* how to deal with replies for local transaction */
858         int local_store, local_winner;
859         enum rps reply_status;
860         struct sip_msg *winning_msg;
861         int winning_code;
862         /* branch_bm_t cancel_bitmap; */
863
864         /* keep warning 'var might be used un-inited' silent */ 
865         winning_msg=0;
866         winning_code=0;
867
868         *cancel_bitmap=0;
869
870         reply_status=t_should_relay_response( t, msg_status, branch,
871                 &local_store, &local_winner, cancel_bitmap, p_msg );
872         DBG("DEBUG: local_reply: branch=%d, save=%d, winner=%d\n",
873                 branch, local_store, local_winner );
874         if (local_store) {
875                 if (!store_reply(t, branch, p_msg))
876                         goto error;
877         }
878         if (local_winner>=0) {
879                 winning_msg= branch==local_winner 
880                         ? p_msg :  t->uac[local_winner].reply;
881                 if (winning_msg==FAKED_REPLY) {
882                         tm_stats->replied_localy++;
883                         winning_code = branch==local_winner
884                                 ? msg_status : t->uac[local_winner].last_received;
885                 } else {
886                         winning_code=winning_msg->REPLY_STATUS;
887                 }
888                 t->uas.status = winning_code;
889                 update_reply_stats( winning_code );
890         }
891         UNLOCK_REPLIES(t);
892         if (local_winner>=0 && winning_code>=200 ) {
893                 DBG("DEBUG: local transaction completed\n");
894                 callback_event( TMCB_LOCAL_COMPLETED, t, winning_msg, winning_code );
895                 if (t->completion_cb) 
896                         t->completion_cb( t, winning_msg, winning_code, 0 /* empty param */);
897         }
898         return reply_status;
899
900 error:
901         which_cancel(t, cancel_bitmap);
902         UNLOCK_REPLIES(t);
903         cleanup_uac_timers(t);
904         if ( get_cseq(p_msg)->method.len==INVITE_LEN 
905                 && memcmp( get_cseq(p_msg)->method.s, INVITE, INVITE_LEN)==0)
906                 cancel_uacs( t, *cancel_bitmap );
907         put_on_wait(t);
908         return RPS_ERROR;
909 }
910
911
912
913
914
915 /*  This function is called whenever a reply for our module is received; 
916   * we need to register  this function on module initialization;
917   *  Returns :   0 - core router stops
918   *              1 - core router relay statelessly
919   */
920 int t_on_reply( struct sip_msg  *p_msg )
921 {
922
923         int msg_status;
924         char *ack;
925         unsigned int ack_len;
926         int branch;
927         /* has the transaction completed now and we need to clean-up? */
928         int reply_status;
929         branch_bm_t cancel_bitmap;
930         struct ua_client *uac;
931         struct cell *t;
932
933
934         /* make sure we know the assosociated transaction ... */
935         if (t_check( p_msg  , &branch )==-1)
936                 return 1;
937         /*... if there is none, tell the core router to fwd statelessly */
938         t=get_t();
939         if ( t<=0 ) return 1;
940
941         cancel_bitmap=0;
942         msg_status=p_msg->REPLY_STATUS;
943
944         uac=&t->uac[branch];
945         DBG("DEBUG: t_on_reply: org. status uas=%d, "
946                 "uac[%d]=%d local=%d is_invite=%d)\n",
947                 t->uas.status, branch, uac->last_received, 
948                 t->local, t->is_invite);
949
950         /* it's a cancel ... ? */
951         if (get_cseq(p_msg)->method.len==CANCEL_LEN 
952                 && memcmp( get_cseq(p_msg)->method.s, CANCEL, CANCEL_LEN)==0
953                 /* .. which is not e2e ? ... */
954                 && t->is_invite ) {
955                         /* ... then just stop timers */
956                         reset_timer( &uac->local_cancel.retr_timer);
957                         if ( msg_status >= 200 )
958                                 reset_timer( &uac->local_cancel.fr_timer);
959                         DBG("DEBUG: reply to local CANCEL processed\n");
960                         goto done;
961         }
962
963
964         /* *** stop timers *** */
965         /* stop retransmission */
966         reset_timer( &uac->request.retr_timer);
967         /* stop final response timer only if I got a final response */
968         if ( msg_status >= 200 )
969                 reset_timer( &uac->request.fr_timer);
970
971         LOCK_REPLIES( t );
972         if (t->local) {
973                 reply_status=local_reply( t, p_msg, branch, msg_status, &cancel_bitmap );
974         } else {
975                 reply_status=relay_reply( t, p_msg, branch, msg_status, 
976                         &cancel_bitmap );
977         }
978
979         if (reply_status==RPS_ERROR)
980                 goto done;
981
982         /* acknowledge negative INVITE replies */       
983         if (t->is_invite && (msg_status>=300 || (t->local && msg_status>=200))) {
984                 ack = build_ack( p_msg, t, branch , &ack_len);
985                 if (ack) {
986                         SEND_PR_BUFFER( &uac->request, ack, ack_len );
987                         shm_free(ack);
988                 }
989         } /* ack-ing negative INVITE replies */
990
991         /* clean-up the transaction when transaction completed */
992         if (reply_status==RPS_COMPLETED) {
993                 /* no more UAC FR/RETR (if I received a 2xx, there may
994                    be still pending branches ...
995                 */
996                 cleanup_uac_timers( t );        
997                 if (t->is_invite) cancel_uacs( t, cancel_bitmap );
998                 /* FR for negative INVITES, WAIT anything else */
999                 set_final_timer(  t );
1000         } 
1001
1002         /* update FR/RETR timers on provisional replies */
1003         if (msg_status<200) { /* provisional now */
1004                 if (t->is_invite) { 
1005                         /* invite: change FR to longer FR_INV, do not
1006                            attempt to restart retransmission any more
1007                         */
1008                         set_timer( & uac->request.fr_timer,
1009                                 FR_INV_TIMER_LIST );
1010                 } else {
1011                         /* non-invite: restart retransmisssions (slow now) */
1012                         uac->request.retr_list=RT_T2;
1013                         set_timer(  & uac->request.retr_timer, RT_T2 );
1014                 }
1015         } /* provisional replies */
1016
1017 done:
1018 #ifdef _OBSOLETED
1019         /* moved to  script callback */
1020         UNREF( t );
1021         T=T_UNDEFINED;
1022 #endif
1023         /* don't try to relay statelessly neither on success
1024        (we forwarded statefuly) nor on error; on troubles, 
1025            simply do nothing; that will make the other party to 
1026            retransmit; hopefuly, we'll then be better off */
1027         return 0;
1028 }
1029