GPLization banner introduced to *.[hc] files
[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
29
30
31 #include "../../hash_func.h"
32 #include "t_funcs.h"
33 #include "../../dprint.h"
34 #include "../../config.h"
35 #include "../../parser/parser_f.h"
36 #include "../../ut.h"
37 #include "../../timer.h"
38 #include "../../error.h"
39 #include "../../action.h"
40 #include "../../dset.h"
41
42 #include "t_hooks.h"
43 #include "t_funcs.h"
44 #include "t_reply.h"
45 #include "t_cancel.h"
46 #include "t_msgbuilder.h"
47 #include "t_lookup.h"
48 #include "t_fwd.h"
49 #include "fix_lumps.h"
50 #include "t_stats.h"
51
52 /* where to go if there is no positive reply */
53 static int goto_on_negative=0;
54
55 /* we store the reply_route # in private memory which is
56    then processed during t_relay; we cannot set this value
57    before t_relay creates transaction context or after
58    t_relay when a reply may arrive after we set this
59    value; that's why we do it how we do it, i.e.,
60    *inside*  t_relay using hints stored in private memory
61    before t_reay is called
62 */
63   
64   
65 int t_on_negative( unsigned int go_to )
66 {
67         goto_on_negative=go_to;
68         return 1;
69 }
70
71
72 unsigned int get_on_negative()
73 {
74         return goto_on_negative;
75 }
76
77 static void update_reply_stats( int code ) {
78         if (code>=600) {
79                 acc_stats->completed_6xx++;
80         } else if (code>=500) {
81                 acc_stats->completed_5xx++;
82         } else if (code>=400) {
83                 acc_stats->completed_4xx++;
84         } else if (code>=300) {
85                 acc_stats->completed_3xx++;
86         } else if (code>=200) {
87                 acc_stats->completed_2xx++;
88         }
89 }
90
91
92 /* the main code of stateful replying */
93 static int _reply( struct cell *t, struct sip_msg* p_msg, unsigned int code,
94     char * text, int lock );
95
96 /* Retransmits the last sent inbound reply.
97  * input: p_msg==request for which I want to retransmit an associated reply
98  * Returns  -1 - error
99  *           1 - OK
100  */
101 int t_retransmit_reply( struct cell *t )
102 {
103         static char b[BUF_SIZE];
104         int len;
105
106         /* first check if we managed to resolve topmost Via -- if
107            not yet, don't try to retransmit
108         */
109         if (!t->uas.response.send_sock) {
110                 LOG(L_ERR, "ERROR: no resolved dst to retransmit\n");
111                 return -1;
112         }
113
114         /* we need to lock the transaction as messages from
115            upstream may change it continuously
116         */
117         LOCK_REPLIES( t );
118
119         if (!t->uas.response.buffer) {
120                 DBG("DBG: t_retransmit_reply: nothing to retransmit\n");
121                 goto error;
122         }
123
124         len=t->uas.response.buffer_len;
125         if ( len==0 || len>BUF_SIZE )  {
126                 DBG("DBG: t_retransmit_reply: "
127                         "zero length or too big to retransmit: %d\n", len);
128                 goto error;
129         }
130         memcpy( b, t->uas.response.buffer, len );
131         UNLOCK_REPLIES( t );
132         SEND_PR_BUFFER( & t->uas.response, b, len );
133         DBG("DEBUG: reply retransmitted. buf=%p: %.9s..., shmem=%p: %.9s\n", 
134                 b, b, t->uas.response.buffer, t->uas.response.buffer );
135         return 1;
136
137 error:
138         UNLOCK_REPLIES(t);
139         return -1;
140 }
141
142
143
144 int t_reply( struct cell *t, struct sip_msg* p_msg, unsigned int code, 
145         char * text )
146 {
147         return _reply( t, p_msg, code, text, 1 /* lock replies */ );
148 }
149
150 int t_reply_unsafe( struct cell *t, struct sip_msg* p_msg, unsigned int code, 
151         char * text )
152 {
153         return _reply( t, p_msg, code, text, 0 /* don't lock replies */ );
154 }
155
156
157
158 /* send a UAS reply
159  * returns 1 if everything was OK or -1 for error
160  */
161 static int _reply( struct cell *trans, struct sip_msg* p_msg, 
162         unsigned int code, char * text, int lock )
163 {
164         unsigned int len, buf_len=0;
165         char * buf;
166         struct retr_buf *rb;
167
168         branch_bm_t cancel_bitmap;
169
170         if (code>=200) trans->kr|=REQ_RPLD;
171         /*
172         buf = build_res_buf_from_sip_req(code,text,trans->uas.tag->s,
173                 trans->uas.tag->len, trans->uas.request,&len);
174         */
175         cancel_bitmap=0;
176         /* compute the buffer in private memory prior to entering lock */
177         buf = build_res_buf_from_sip_req(code,text, 0,0, /* no to-tag */
178                 p_msg,&len);
179         DBG("DEBUG: t_reply: buffer computed\n");
180         if (!buf)
181         {
182                 DBG("DEBUG: t_reply: response building failed\n");
183                 /* determine if there are some branches to be cancelled */
184                 if (trans->is_invite) {
185                         if (lock) LOCK_REPLIES( trans );
186                         which_cancel(trans, &cancel_bitmap );
187                         if (lock) UNLOCK_REPLIES( trans );
188                 }
189                 /* and clean-up, including cancellations, if needed */
190                 goto error;
191         }
192
193         if (lock) LOCK_REPLIES( trans );
194         if (trans->is_invite) which_cancel(trans, &cancel_bitmap );
195         if (trans->uas.status>=200) {
196                 LOG( L_ERR, "ERROR: t_reply: can't generate replies"
197                         "when a final was sent out\n");
198                 goto error2;
199         }
200         rb = & trans->uas.response;
201         rb->activ_type=code;
202
203         trans->uas.status = code;
204         buf_len = rb->buffer ? len : len + REPLY_OVERBUFFER_LEN;
205         rb->buffer = (char*)shm_resize( rb->buffer, buf_len );
206         /* puts the reply's buffer to uas.response */
207         if (! rb->buffer ) {
208                         LOG(L_ERR, "ERROR: t_reply: cannot allocate shmem buffer\n");
209                         goto error2;
210         }
211         rb->buffer_len = len ;
212         memcpy( rb->buffer , buf , len );
213         /* needs to be protected too because what timers are set depends
214            on current transactions status */
215         /* t_update_timers_after_sending_reply( rb ); */
216         update_reply_stats( code );
217         acc_stats->replied_localy++;
218         if (lock) UNLOCK_REPLIES( trans );
219         
220         /* do UAC cleanup procedures in case we generated
221            a final answer whereas there are pending UACs */
222         if (code>=200) {
223                 if (trans->local) {
224                         DBG("DEBUG: local transaction completed from _reply\n");
225                         callback_event( TMCB_LOCAL_COMPLETED, trans, FAKED_REPLY, code );
226                         if (trans->completion_cb) 
227                                 trans->completion_cb( trans, FAKED_REPLY, code, 0 /* empty param */);
228                 } else {
229                         callback_event( TMCB_REPLY, trans, FAKED_REPLY, code );
230                 }
231
232                 cleanup_uac_timers( trans );
233                 if (trans->is_invite) cancel_uacs( trans, cancel_bitmap );
234                 set_final_timer(  trans );
235         }
236
237         /* send it out */
238         /* first check if we managed to resolve topmost Via -- if
239            not yet, don't try to retransmit
240         */
241         if (!trans->uas.response.send_sock) {
242                 LOG(L_ERR, "ERROR: _reply: no resolved dst to send reply to\n");
243         } else {
244                 SEND_PR_BUFFER( rb, buf, len );
245                 DBG("DEBUG: reply sent out. buf=%p: %.9s..., shmem=%p: %.9s\n", 
246                         buf, buf, rb->buffer, rb->buffer );
247         }
248         pkg_free( buf ) ;
249         DBG("DEBUG: t_reply: finished\n");
250         return 1;
251
252 error2:
253         if (lock) UNLOCK_REPLIES( trans );
254         pkg_free ( buf );
255 error:
256         /* do UAC cleanup */
257         cleanup_uac_timers( trans );
258         if (trans->is_invite) cancel_uacs( trans, cancel_bitmap );
259         /* we did not succeed -- put the transaction on wait */
260         put_on_wait(trans);
261         return -1;
262 }
263
264 void set_final_timer( /* struct s_table *h_table, */ struct cell *t )
265 {
266         if ( !t->local 
267                 && t->uas.request->REQ_METHOD==METHOD_INVITE 
268                 && t->uas.status>=300  ) {
269                         /* crank timers for negative replies */
270                         start_retr( &t->uas.response );
271         } else put_on_wait(t);
272 }
273
274 void cleanup_uac_timers( struct cell *t )
275 {
276         int i;
277
278         /* reset FR/retransmission timers */
279         for (i=0; i<t->nr_of_outgoings; i++ )  {
280                 reset_timer( &t->uac[i].request.retr_timer );
281                 reset_timer( &t->uac[i].request.fr_timer );
282         }
283         DBG("DEBUG: cleanup_uacs: RETR/FR timers reset\n");
284 }
285
286 int store_reply( struct cell *trans, int branch, struct sip_msg *rpl)
287 {
288 #               ifdef EXTRA_DEBUG
289                 if (trans->uac[branch].reply) {
290                         LOG(L_ERR, "ERROR: replacing stored reply; aborting\n");
291                         abort();
292                 }
293 #               endif
294
295                 /* when we later do things such as challenge aggregation,
296                    we should parse the message here before we conservate
297                    it in shared memory; -jiri
298                 */
299                 if (rpl==FAKED_REPLY)
300                         trans->uac[branch].reply=FAKED_REPLY;
301                 else
302                         trans->uac[branch].reply = sip_msg_cloner( rpl );
303
304                 if (! trans->uac[branch].reply ) {
305                         LOG(L_ERR, "ERROR: store_reply: can't alloc' clone memory\n");
306                         return 0;
307                 }
308
309                 return 1;
310 }
311
312 /* this is the code which decides what and when shall be relayed
313    upstream; note well -- it assumes it is entered locked with 
314    REPLY_LOCK and it returns unlocked!
315 */
316 enum rps relay_reply( struct cell *t, struct sip_msg *p_msg, int branch, 
317         unsigned int msg_status, branch_bm_t *cancel_bitmap )
318 {
319         int relay;
320         int save_clone;
321         char *buf;
322         /* length of outbound reply */
323         unsigned int res_len;
324         int relayed_code;
325         struct sip_msg *relayed_msg;
326         str     to_tag;
327         enum rps reply_status;
328         /* retransmission structure of outbound reply and request */
329         struct retr_buf *uas_rb;
330
331         /* keep compiler warnings about use of uninit vars silent */
332         res_len=0;
333         buf=0;
334         relayed_msg=0;
335         relayed_code=0;
336
337
338         /* remember, what was sent upstream to know whether we are
339            forwarding a first final reply or not */
340
341         /* *** store and relay message as needed *** */
342         reply_status = t_should_relay_response(t, msg_status, branch, 
343                 &save_clone, &relay, cancel_bitmap );
344         DBG("DEBUG: relay_reply: branch=%d, save=%d, relay=%d\n",
345                 branch, save_clone, relay );
346
347         /* store the message if needed */
348         if (save_clone) /* save for later use, typically branch picking */
349         {
350                 if (!store_reply( t, branch, p_msg ))
351                         goto error01;
352         }
353
354         uas_rb = & t->uas.response;
355         if (relay >= 0 ) {
356
357                 /* initialize sockets for outbound reply */
358                 uas_rb->activ_type=msg_status;
359                 /* only messages known to be relayed immediately will be
360                    be called on; we do not evoke this callback on messages
361                    stored in shmem -- they are fixed and one cannot change them
362                    anyway 
363         */
364                 if (msg_status<300 && branch==relay) {
365                         callback_event( TMCB_REPLY_IN, t, p_msg, msg_status );
366                 }
367                 /* try bulding the outbound reply from either the current
368                or a stored message */
369                 relayed_msg = branch==relay ? p_msg :  t->uac[relay].reply;
370                 if (relayed_msg ==FAKED_REPLY) {
371                         relayed_code = branch==relay
372                                 ? msg_status : t->uac[relay].last_received;
373                         buf = build_res_buf_from_sip_req( relayed_code,
374                                 error_text(relayed_code), 0,0, /* no to-tag */
375                                 t->uas.request, &res_len );
376                 } else {
377                         relayed_code=relayed_msg->REPLY_STATUS;
378                         buf = build_res_buf_from_sip_res( relayed_msg, &res_len );
379                         /* if we build a message from shmem, we need to remove
380                            via delete lumps which are now stirred in the shmem-ed
381                            structure
382                         */
383                         if (branch!=relay) {
384                                 free_via_lump(&relayed_msg->repl_add_rm);
385                         }
386                 }
387                 update_reply_stats( relayed_code );
388                 if (!buf) {
389                         LOG(L_ERR, "ERROR: relay_reply: "
390                                 "no mem for outbound reply buffer\n");
391                         goto error02;
392                 }
393
394                 /* attempt to copy the message to UAS's shmem:
395                    - copy to-tag for ACK matching as well
396                    -  allocate little a bit more for provisionals as
397                       larger messages are likely to follow and we will be 
398                       able to reuse the memory frag 
399                 */
400                 uas_rb->buffer = (char*)shm_resize( uas_rb->buffer, res_len +
401                         (msg_status<200 ?  REPLY_OVERBUFFER_LEN : 0));
402                 if (!uas_rb->buffer) {
403                         LOG(L_ERR, "ERROR: relay_reply: cannot alloc reply shmem\n");
404                         goto error03;
405                 }
406                 uas_rb->buffer_len = res_len;
407                 memcpy( uas_rb->buffer, buf, res_len );
408                 /* to tag now */
409                 if (relayed_code>=300 && t->is_invite) {
410                         if (relayed_msg!=FAKED_REPLY) {
411                                 to_tag=get_to(relayed_msg)->tag_value;
412                                 t->uas.to_tag.s=(char *)shm_resize( t->uas.to_tag.s,
413                                         to_tag.len );
414                                 if (!t->uas.to_tag.s) {
415                                         LOG(L_ERR, "ERROR: no shmem for to-tag\n");
416                                         goto error04;
417                                 }
418                                 t->uas.to_tag.len=to_tag.len;
419                                 memcpy(t->uas.to_tag.s, to_tag.s, to_tag.len );
420                         } else {
421                                 if (t->uas.to_tag.s) shm_free(t->uas.to_tag.s);
422                                 t->uas.to_tag.s=0;
423                                 t->uas.to_tag.len=0;
424                         }
425                 }
426
427                 /* update the status ... */
428                 t->uas.status = relayed_code;
429                 t->relaied_reply_branch = relay;
430         }; /* if relay ... */
431
432         UNLOCK_REPLIES( t );
433
434         /* send it now (from the private buffer) */
435         if (relay >= 0) {
436                 SEND_PR_BUFFER( uas_rb, buf, res_len );
437                 DBG("DEBUG: reply relayed. buf=%p: %.9s..., shmem=%p: %.9s\n", 
438                         buf, buf, uas_rb->buffer, uas_rb->buffer );
439                 callback_event( TMCB_REPLY, t, relayed_msg, relayed_code );
440                 pkg_free( buf );
441         }
442
443         /* success */
444         return reply_status;
445
446 error04:
447         shm_free( uas_rb->buffer );
448         uas_rb->buffer=0;
449 error03:
450         pkg_free( buf );
451 error02:
452         if (save_clone) {
453                 if (t->uac[branch].reply!=FAKED_REPLY)
454                         sip_msg_free( t->uac[branch].reply );
455                 t->uac[branch].reply = NULL;    
456         }
457 error01:
458         t_reply_unsafe( t, t->uas.request, 500, "Reply processing error" );
459         UNLOCK_REPLIES(t);
460         if (t->is_invite) cancel_uacs( t, *cancel_bitmap );
461         /* a serious error occured -- attempt to send an error reply;
462            it will take care of clean-ups 
463         */
464
465         /* failure */
466         return RPS_ERROR;
467 }
468
469 /* this is the "UAC" above transaction layer; if a final reply
470    is received, it triggers a callback; note well -- it assumes
471    it is entered locked with REPLY_LOCK and it returns unlocked!
472 */
473 enum rps local_reply( struct cell *t, struct sip_msg *p_msg, int branch, 
474         unsigned int msg_status, branch_bm_t *cancel_bitmap)
475 {
476         /* how to deal with replies for local transaction */
477         int local_store, local_winner;
478         enum rps reply_status;
479         struct sip_msg *winning_msg;
480         int winning_code;
481         /* branch_bm_t cancel_bitmap; */
482
483         /* keep warning 'var might be used un-inited' silent */ 
484         winning_msg=0;
485         winning_code=0;
486
487         *cancel_bitmap=0;
488
489         reply_status=t_should_relay_response( t, msg_status, branch,
490                 &local_store, &local_winner, cancel_bitmap );
491         DBG("DEBUG: local_reply: branch=%d, save=%d, winner=%d\n",
492                 branch, local_store, local_winner );
493         if (local_store) {
494                 if (!store_reply(t, branch, p_msg))
495                         goto error;
496         }
497         if (local_winner>=0) {
498                 winning_msg= branch==local_winner 
499                         ? p_msg :  t->uac[local_winner].reply;
500                 if (winning_msg==FAKED_REPLY) {
501                         winning_code = branch==local_winner
502                                 ? msg_status : t->uac[local_winner].last_received;
503                 } else {
504                         winning_code=winning_msg->REPLY_STATUS;
505                 }
506                 t->uas.status = winning_code;
507                 update_reply_stats( winning_code );
508         }
509         UNLOCK_REPLIES(t);
510         if (local_winner>=0 && winning_code>=200 ) {
511                 DBG("DEBUG: local transaction completed\n");
512                 callback_event( TMCB_LOCAL_COMPLETED, t, winning_msg, winning_code );
513                 if (t->completion_cb) 
514                         t->completion_cb( t, winning_msg, winning_code, 0 /* empty param */);
515         }
516         return reply_status;
517
518 error:
519         which_cancel(t, cancel_bitmap);
520         UNLOCK_REPLIES(t);
521         cleanup_uac_timers(t);
522         if ( get_cseq(p_msg)->method.len==INVITE_LEN 
523                 && memcmp( get_cseq(p_msg)->method.s, INVITE, INVITE_LEN)==0)
524                 cancel_uacs( t, *cancel_bitmap );
525         put_on_wait(t);
526         return RPS_ERROR;
527 }
528
529
530
531
532
533 /*  This function is called whenever a reply for our module is received; 
534   * we need to register  this function on module initialization;
535   *  Returns :   0 - core router stops
536   *              1 - core router relay statelessly
537   */
538 int t_on_reply( struct sip_msg  *p_msg )
539 {
540
541         int msg_status;
542         char *ack;
543         unsigned int ack_len;
544         int branch;
545         /* has the transaction completed now and we need to clean-up? */
546         int reply_status;
547         branch_bm_t cancel_bitmap;
548         struct ua_client *uac;
549         struct cell *t;
550
551
552         /* make sure we know the assosociated transaction ... */
553         if (t_check( p_msg  , &branch )==-1)
554                 return 1;
555         /*... if there is none, tell the core router to fwd statelessly */
556         t=get_t();
557         if ( t<=0 ) return 1;
558
559         cancel_bitmap=0;
560         msg_status=p_msg->REPLY_STATUS;
561
562         uac=&t->uac[branch];
563         DBG("DEBUG: t_on_reply: org. status uas=%d, "
564                 "uac[%d]=%d local=%d is_invite=%d)\n",
565                 t->uas.status, branch, uac->last_received, 
566                 t->local, t->is_invite);
567
568         /* it's a cancel ... ? */
569         if (get_cseq(p_msg)->method.len==CANCEL_LEN 
570                 && memcmp( get_cseq(p_msg)->method.s, CANCEL, CANCEL_LEN)==0
571                 /* .. which is not e2e ? ... */
572                 && t->is_invite ) {
573                         /* ... then just stop timers */
574                         reset_timer( &uac->local_cancel.retr_timer);
575                         if ( msg_status >= 200 )
576                                 reset_timer( &uac->local_cancel.fr_timer);
577                         DBG("DEBUG: reply to local CANCEL processed\n");
578                         goto done;
579         }
580
581
582         /* *** stop timers *** */
583         /* stop retransmission */
584         reset_timer( &uac->request.retr_timer);
585         /* stop final response timer only if I got a final response */
586         if ( msg_status >= 200 )
587                 reset_timer( &uac->request.fr_timer);
588
589         LOCK_REPLIES( t );
590         if (t->local) {
591                 reply_status=local_reply( t, p_msg, branch, msg_status, &cancel_bitmap );
592         } else {
593                 reply_status=relay_reply( t, p_msg, branch, msg_status, 
594                         &cancel_bitmap );
595         }
596
597         if (reply_status==RPS_ERROR)
598                 goto done;
599
600         /* acknowledge negative INVITE replies */       
601         if (t->is_invite && (msg_status>=300 || (t->local && msg_status>=200))) {
602                 ack = build_ack( p_msg, t, branch , &ack_len);
603                 if (ack) {
604                         SEND_PR_BUFFER( &uac->request, ack, ack_len );
605                         shm_free(ack);
606                 }
607         } /* ack-ing negative INVITE replies */
608
609         /* clean-up the transaction when transaction completed */
610         if (reply_status==RPS_COMPLETED) {
611                 /* no more UAC FR/RETR (if I received a 2xx, there may
612                    be still pending branches ...
613                 */
614                 cleanup_uac_timers( t );        
615                 if (t->is_invite) cancel_uacs( t, cancel_bitmap );
616                 /* FR for negative INVITES, WAIT anything else */
617                 set_final_timer(  t );
618         } 
619
620         /* update FR/RETR timers on provisional replies */
621         if (msg_status<200) { /* provisional now */
622                 if (t->is_invite) { 
623                         /* invite: change FR to longer FR_INV, do not
624                            attempt to restart retransmission any more
625                         */
626                         set_timer( & uac->request.fr_timer,
627                                 FR_INV_TIMER_LIST );
628                 } else {
629                         /* non-invite: restart retransmisssions (slow now) */
630                         uac->request.retr_list=RT_T2;
631                         set_timer(  & uac->request.retr_timer, RT_T2 );
632                 }
633         } /* provisional replies */
634
635 done:
636 #ifdef _OBSOLETED
637         /* moved to  script callback */
638         UNREF( t );
639         T=T_UNDEFINED;
640 #endif
641         /* don't try to relay statelessly neither on success
642        (we forwarded statefuly) nor on error; on troubles, 
643            simply do nothing; that will make the other party to 
644            retransmit; hopefuly, we'll then be better off */
645         return 0;
646 }
647
648
649 /* This is the neuralgical point of reply processing -- called
650  * from within a REPLY_LOCK, t_should_relay_response decides
651  * how a reply shall be processed and how transaction state is
652  * affected.
653  *
654  * Checks if the new reply (with new_code status) should be sent or not
655  *  based on the current
656  * transactin status.
657  * Returns      - branch number (0,1,...) which should be relayed
658  *         -1 if nothing to be relayed
659  */
660 enum rps t_should_relay_response( struct cell *Trans , int new_code,
661         int branch , int *should_store, int *should_relay,
662         branch_bm_t *cancel_bitmap )
663 {
664         int b, lowest_b, lowest_s, dummy;
665
666         /* note: this code never lets replies to CANCEL go through;
667            we generate always a local 200 for CANCEL; 200s are
668            not relayed because it's not an INVITE transaction;
669            >= 300 are not relayed because 200 was already sent
670            out
671         */
672         DBG("->>>>>>>>> T_code=%d, new_code=%d\n",Trans->uas.status,new_code);
673         /* if final response sent out, allow only INVITE 2xx  */
674         if ( Trans->uas.status >= 200 ) {
675                 if (new_code>=200 && new_code < 300  && 
676 #ifdef _BUG_FIX /* t may be local, in which case there is no request */
677                         Trans->uas.request->REQ_METHOD==METHOD_INVITE) {
678 #endif
679                         Trans->is_invite ) {
680                         DBG("DBG: t_should_relay: 200 INV after final sent\n");
681                         *should_store=0;
682                         Trans->uac[branch].last_received=new_code;
683                         *should_relay=branch;
684                         return RPS_PUSHED_AFTER_COMPLETION;
685                 } else {
686                         /* except the exception above, too late  messages will
687                            be discarded */
688                         *should_store=0;
689                         *should_relay=-1;
690                         return RPS_DISCARDED;
691                 }
692         } 
693
694         /* no final response sent yet */
695         /* negative replies subject to fork picking */
696         if (new_code >=300 ) {
697                 /* negative reply received after we have received
698                    a final reply previously -- discard , unless
699                    a recoverable error occured, in which case
700                    retry
701             */
702                 if (Trans->uac[branch].last_received>=200) {
703                         /* then drop! */
704                         *should_store=0;
705                         *should_relay=-1;
706                         return RPS_DISCARDED;
707                 }
708
709                 Trans->uac[branch].last_received=new_code;
710                 /* if all_final return lowest */
711                 lowest_b=-1; lowest_s=999;
712                 for ( b=0; b<Trans->nr_of_outgoings ; b++ ) {
713                         /* "fake" for the currently processed branch */
714                         if (b==branch) {
715                                 if (new_code<lowest_s) {
716                                         lowest_b=b;
717                                         lowest_s=new_code;
718                                 }
719                                 continue;
720                         }
721                         /* skip 'empty branches' */
722                         if (!Trans->uac[b].request.buffer) continue;
723                         /* there is still an unfinished UAC transaction; wait now! */
724                         if ( Trans->uac[b].last_received<200 ) {
725                                 *should_store=1;        
726                                 *should_relay=-1;
727                                 return RPS_STORE;
728                         }
729                         if ( Trans->uac[b].last_received<lowest_s )
730                         {
731                                 lowest_b =b;
732                                 lowest_s = Trans->uac[b].last_received;
733                         }
734                 } /* find lowest branch */
735                 if (lowest_b==-1) {
736                         LOG(L_CRIT, "ERROR: t_should_relay_response: lowest==-1\n");
737                 }
738                 /* no more pending branches -- try if that changes after
739                    a callback
740                 */
741                 callback_event( TMCB_ON_NEGATIVE, Trans, 0, lowest_s );
742                 /* look if the callback perhaps replied transaction; it also
743                    covers the case in which a transaction is replied localy
744                    on CANCEL -- then it would make no sense to proceed to
745                    new branches bellow
746                 */
747                 if (Trans->uas.status >= 200) {
748                         *should_store=0;
749                         *should_relay=-1;
750                         /* this might deserve an improvement -- if something
751                            was already replied, it was put on wait and then,
752                            returning RPS_COMPLETED will make t_on_reply
753                            put it on wait again; perhaps splitting put_on_wait
754                            from send_reply or a new RPS_ code would be healthy
755                         */
756                         return RPS_COMPLETED;
757                 }
758                 /* look if the callback introduced new branches ... */
759                 init_branch_iterator();
760                 if (next_branch(&dummy)) {
761                         if (t_forward_nonack(Trans, Trans->uas.request, 
762                                                 (struct proxy_l *) 0 ) <0) {
763                                 /* error ... behave as if we did not try to
764                                    add a new branch */
765                                 *should_store=0;
766                                 *should_relay=lowest_b;
767                                 return RPS_COMPLETED;
768                         }
769                         /* we succeded to launch new branches -- await
770                            result
771                         */
772                         *should_store=1;
773                         *should_relay=-1;
774                         return RPS_STORE;
775                 }
776                 /* really no more pending branches -- return lowest code */
777                 *should_store=0;
778                 *should_relay=lowest_b;
779                 /* we dont need 'which_cancel' here -- all branches 
780                    known to have completed */
781                 /* which_cancel( Trans, cancel_bitmap ); */
782                 return RPS_COMPLETED;
783         } 
784
785         /* not >=300 ... it must be 2xx or provisional 1xx */
786         if (new_code>=100) {
787                 /* 1xx and 2xx except 100 will be relayed */
788                 Trans->uac[branch].last_received=new_code;
789                 *should_store=0;
790                 *should_relay= new_code==100? -1 : branch;
791                 if (new_code>=200 ) {
792                         which_cancel( Trans, cancel_bitmap );
793                         return RPS_COMPLETED;
794                 } else return RPS_PROVISIONAL;
795         }
796
797         /* reply_status didn't match -- it must be something weird */
798         LOG(L_CRIT, "ERROR: Oh my gooosh! We don't know whether to relay %d\n",
799                 new_code);
800         *should_store=0;
801         *should_relay=-1;
802         return RPS_DISCARDED;
803 }
804
805 char *build_ack(struct sip_msg* rpl,struct cell *trans,int branch,
806         int *ret_len)
807 {
808         str to;
809
810     if ( parse_headers(rpl,HDR_TO, 0)==-1 || !rpl->to )
811     {
812         LOG(L_ERR, "ERROR: t_build_ACK: "
813             "cannot generate a HBH ACK if key HFs in reply missing\n");
814         return NULL;
815     }
816         to.len=rpl->to->body.s+rpl->to->body.len-rpl->to->name.s;
817         to.s=rpl->orig+(rpl->to->name.s-rpl->buf);
818     return build_local( trans, branch, ret_len,
819         ACK, ACK_LEN, &to );
820 }
821
822 void on_negative_reply( struct cell* t, struct sip_msg* msg, 
823         int code, void *param )
824 {
825         int act_ret;
826         struct sip_msg faked_msg;
827
828         /* nobody cares about a negative transaction -- ok, return */
829         if (!t->on_negative) {
830                 DBG("DBG: on_negative_reply: no on_negative\n");
831                 return;
832         }
833
834         DBG("DBG: on_negative_reply processed for transaction %p\n", t);
835
836         /* create faked environment  -- uri rewriting stuff needs the
837            original uri
838         */
839         memset( &faked_msg, 0, sizeof( struct sip_msg ));
840         /* original URI doesn't change -- feel free to refer to shmem */
841         faked_msg.first_line.u.request.uri=
842                 t->uas.request->first_line.u.request.uri;
843         /* new_uri can change -- make a private copy */
844         if (t->uas.request->new_uri.s!=0 && t->uas.request->new_uri.len!=0) {
845                 faked_msg.new_uri.s=pkg_malloc(t->uas.request->new_uri.len+1);
846                 if (!faked_msg.new_uri.s) return;
847                 faked_msg.new_uri.len=t->uas.request->new_uri.len;
848                 memcpy( faked_msg.new_uri.s, t->uas.request->new_uri.s, 
849                         faked_msg.new_uri.len);
850                 faked_msg.new_uri.s[faked_msg.new_uri.len]=0;
851         } else { faked_msg.new_uri.s=0; faked_msg.new_uri.len=0; }
852         faked_msg.flags=t->uas.request->flags;  
853         /* if we set msg_id to something different from current's message
854        id, the first t_fork will properly clean new branch URIs
855         */
856         faked_msg.id=t->uas.request->id-1;
857
858         act_ret=run_actions(reply_rlist[t->on_negative], &faked_msg );
859
860         if (act_ret<0) {
861                 LOG(L_ERR, "on_negative_reply: Error in do_action\n");
862         }
863
864 #ifdef _OBSOLETED
865         /* this didn't work becaue URI is a part of shmem "monoblock";
866            I could split it but it does not seem to be worth the
867            effor
868         */
869         /* project changes in faked message back to shmem copy */
870         t->uas.request->flags=faked_msg.flags;
871         if (faked_msg.new_uri.s) {
872                 t->uas.request->new_uri.s=shm_resize(t->uas.request->new_uri.s,
873                         faked_msg.new_uri.len);
874                 if (!t->uas.request->new_uri.s) goto done;
875                 memcpy(t->uas.request->new_uri.s, faked_msg.new_uri.s, 
876                         faked_msg.new_uri.len );
877                 t->uas.request->new_uri.len=faked_msg.new_uri.len;
878         }
879 done:
880 #endif
881         /* destroy faked environment, new_uri in particular */
882         if (faked_msg.new_uri.s) pkg_free(faked_msg.new_uri.s);
883 }
884
885