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