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