More log message fixes.
[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  *  2003-11-05  flag context updated from failure/reply handlers back
53  *              to transaction context (jiri)
54  *  2003-11-11: build_lump_rpl() removed, add_lump_rpl() has flags (bogdan)
55  *  2003-12-04  global TM callbacks switched to per transaction callbacks
56  *              (bogdan)
57  *  2004-02-06: support for user pref. added - destroy_avps (bogdan)
58  *  2003-11-05  flag context updated from failure/reply handlers back
59  *              to transaction context (jiri)
60  *  2003-11-11: build_lump_rpl() removed, add_lump_rpl() has flags (bogdan)
61  *  2004-02-13: t->is_invite and t->local replaced with flags (bogdan)
62  *  2004-02-18  fifo_t_reply imported from vm module (bogdan)
63  */
64
65
66 #include <assert.h>
67
68 #include "../../comp_defs.h"
69 #include "../../hash_func.h"
70 #include "../../dprint.h"
71 #include "../../config.h"
72 #include "../../parser/parser_f.h"
73 #include "../../ut.h"
74 #include "../../timer.h"
75 #include "../../error.h"
76 #include "../../action.h"
77 #include "../../dset.h"
78 #include "../../tags.h"
79 #include "../../data_lump.h"
80 #include "../../data_lump_rpl.h"
81 #include "../../usr_avp.h"
82 #include "../../fifo_server.h"
83 #include "../../unixsock_server.h"
84
85 #include "defs.h"
86 #include "h_table.h"
87 #include "t_hooks.h"
88 #include "t_funcs.h"
89 #include "t_reply.h"
90 #include "t_cancel.h"
91 #include "t_msgbuilder.h"
92 #include "t_lookup.h"
93 #include "t_fwd.h"
94 #include "fix_lumps.h"
95 #include "t_stats.h"
96
97 /* are we processing original or shmemed request ? */
98 enum route_mode rmode=MODE_REQUEST;
99
100 /* private place where we create to-tags for replies */
101 /* janakj: made public, I need to access this value to store it in dialogs */
102 char tm_tags[TOTAG_VALUE_LEN];
103 /* bogdan: pack tm_tag buffer and len into a str to pass them to
104  * build_res_buf_from_sip_req() */
105 static str  tm_tag = {tm_tags,TOTAG_VALUE_LEN};
106 char *tm_tag_suffix;
107
108 /* where to go if there is no positive reply */
109 static int goto_on_negative=0;
110 /* where to go on receipt of reply */
111 static int goto_on_reply=0;
112
113
114
115 /* we store the reply_route # in private memory which is
116    then processed during t_relay; we cannot set this value
117    before t_relay creates transaction context or after
118    t_relay when a reply may arrive after we set this
119    value; that's why we do it how we do it, i.e.,
120    *inside*  t_relay using hints stored in private memory
121    before t_reay is called
122 */
123
124
125 void t_on_negative( unsigned int go_to )
126 {
127         struct cell *t = get_t();
128
129         /* in MODE_REPLY and MODE_ONFAILURE T will be set to current transaction;
130          * in MODE_REQUEST T will be set only if the transaction was already 
131          * created; if not -> use the static variable */
132         if (!t || t==T_UNDEFINED )
133                 goto_on_negative=go_to;
134         else
135                 get_t()->on_negative = go_to;
136 }
137
138
139 void t_on_reply( unsigned int go_to )
140 {
141         struct cell *t = get_t();
142
143         /* in MODE_REPLY and MODE_ONFAILURE T will be set to current transaction;
144          * in MODE_REQUEST T will be set only if the transaction was already 
145          * created; if not -> use the static variable */
146         if (!t || t==T_UNDEFINED )
147                 goto_on_reply=go_to;
148         else
149                 get_t()->on_reply = go_to;
150 }
151
152
153 unsigned int get_on_negative()
154 {
155         return goto_on_negative;
156 }
157 unsigned int get_on_reply()
158 {
159         return goto_on_reply;
160 }
161
162 void tm_init_tags()
163 {
164         init_tags(tm_tags, &tm_tag_suffix, 
165                 "SER-TM/tags", TM_TAG_SEPARATOR );
166 }
167
168 /* returns 0 if the message was previously acknowledged
169  * (i.e., no E2EACK callback is needed) and one if the
170  * callback shall be executed */
171 int unmatched_totag(struct cell *t, struct sip_msg *ack)
172 {
173         struct totag_elem *i;
174         str *tag;
175
176         if (parse_headers(ack, HDR_TO,0)==-1 || 
177                                 !ack->to ) {
178                 LOG(L_ERR, "ERROR: unmatched_totag: To invalid\n");
179                 return 1;
180         }
181         tag=&get_to(ack)->tag_value;
182         for (i=t->fwded_totags; i; i=i->next) {
183                 if (i->tag.len==tag->len
184                                 && memcmp(i->tag.s, tag->s, tag->len)==0) {
185                         DBG("DEBUG: totag for e2e ACK found: %d\n", i->acked);
186                         /* to-tag recorded, and an ACK has been received for it */
187                         if (i->acked) return 0;
188                         /* to-tag recorded, but this ACK came for the first time */
189                         i->acked=1;
190                         return 1;
191                 }
192         }
193         /* surprising: to-tag never sighted before */
194         return 1;
195 }
196
197 static inline void update_local_tags(struct cell *trans, 
198                                 struct bookmark *bm, char *dst_buffer,
199                                 char *src_buffer /* to which bm refers */)
200 {
201         if (bm->to_tag_val.s) {
202                 trans->uas.local_totag.s=bm->to_tag_val.s-src_buffer+dst_buffer;
203                 trans->uas.local_totag.len=bm->to_tag_val.len;
204         }
205 }
206
207
208 /* append a newly received tag from a 200/INVITE to 
209  * transaction's set; (only safe if called from within
210  * a REPLY_LOCK); it returns 1 if such a to tag already
211  * exists
212  */
213 inline static int update_totag_set(struct cell *t, struct sip_msg *ok)
214 {
215         struct totag_elem *i, *n;
216         str *tag;
217         char *s;
218
219         if (!ok->to || !ok->to->parsed) {
220                 LOG(L_ERR, "ERROR: update_totag_set: to not parsed\n");
221                 return 0;
222         }
223         tag=&get_to(ok)->tag_value;
224         if (!tag->s) {
225                 LOG(L_ERR, "ERROR: update_totag_set: no tag in to\n");
226                 return 0;
227         }
228
229         for (i=t->fwded_totags; i; i=i->next) {
230                 if (i->tag.len==tag->len
231                                 && memcmp(i->tag.s, tag->s, tag->len) ==0 ){
232                         /* to tag already recorded */
233 #ifdef XL_DEBUG
234                         LOG(L_CRIT, "DEBUG: update_totag_set: totag retranmission\n");
235 #else
236                         DBG("DEBUG: update_totag_set: totag retranmission\n");
237 #endif
238                         return 1;
239                 }
240         }
241         /* that's a new to-tag -- record it */
242         shm_lock();
243         n=(struct totag_elem*) shm_malloc_unsafe(sizeof(struct totag_elem));
244         s=(char *)shm_malloc_unsafe(tag->len);
245         shm_unlock();
246         if (!s || !n) {
247                 LOG(L_ERR, "ERROR: update_totag_set: no  memory \n");
248                 if (n) shm_free(n);
249                 if (s) shm_free(s);
250                 return 0;
251         }
252         memset(n, 0, sizeof(struct totag_elem));
253         memcpy(s, tag->s, tag->len );
254         n->tag.s=s;n->tag.len=tag->len;
255         n->next=t->fwded_totags;
256         t->fwded_totags=n;
257         DBG("DEBUG: update_totag_set: new totag \n");
258         return 0;
259 }
260
261
262 /*
263  * Build an ACK to a negative reply
264  */
265 static char *build_ack(struct sip_msg* rpl,struct cell *trans,int branch,
266         unsigned int *ret_len)
267 {
268         str to;
269
270     if (parse_headers(rpl,HDR_TO, 0)==-1 || !rpl->to ) {
271         LOG(L_ERR, "ERROR: build_ack: "
272             "cannot generate a HBH ACK if key HFs in reply missing\n");
273         return NULL;
274     }
275         to.s=rpl->to->name.s;
276         to.len=rpl->to->len;
277     return build_local( trans, branch, ret_len,
278         ACK, ACK_LEN, &to );
279 }
280
281
282 /*
283  * The function builds an ACK to 200 OK of local transactions, honor the
284  * route set, the URI to which the message should be sent will be returned
285  * in next_hop parameter
286  */
287 static char *build_local_ack(struct sip_msg* rpl, struct cell *trans, int branch,
288                              unsigned int *ret_len, str* next_hop)
289 {
290         str to;
291         if (parse_headers(rpl, HDR_EOH, 0) == -1 || !rpl->to) {
292                 LOG(L_ERR, "ERROR: build_local_ack: Error while parsing headers\n");
293                 return 0;
294         }
295         
296         to.s = rpl->to->name.s;
297         to.len = rpl->to->len;
298         return build_dlg_ack(rpl, trans, branch, &to, ret_len, next_hop);
299 }
300
301
302      /*
303       * The function is used to send a localy generated ACK to INVITE
304       * (tm generates the ACK on behalf of application using UAC
305       */
306 static int send_local_ack(str* next_hop, char* ack, int ack_len)
307 {
308         struct socket_info* send_sock;
309         union sockaddr_union to_su;
310         
311         if (!next_hop) {
312                 LOG(L_ERR, "send_local_ack: Invalid parameter value\n");
313                 return -1;
314         }
315         
316         send_sock = uri2sock(next_hop, &to_su, PROTO_NONE);
317         if (!send_sock) {
318                 LOG(L_ERR, "send_local_ack: no socket found\n");
319                 return -1;
320         }
321         
322         return msg_send(send_sock, send_sock->proto, &to_su, 0, ack, ack_len);
323 }
324
325
326 static int _reply_light( struct cell *trans, char* buf, unsigned int len,
327                          unsigned int code, char * text, 
328                          char *to_tag, unsigned int to_tag_len, int lock,
329                          struct bookmark *bm    )
330 {
331         struct retr_buf *rb;
332         unsigned int buf_len;
333         branch_bm_t cancel_bitmap;
334
335         if (!buf)
336         {
337                 DBG("DEBUG: _reply_light: response building failed\n");
338                 /* determine if there are some branches to be cancelled */
339                 if ( is_invite(trans) ) {
340                         if (lock) LOCK_REPLIES( trans );
341                         which_cancel(trans, &cancel_bitmap );
342                         if (lock) UNLOCK_REPLIES( trans );
343                 }
344                 /* and clean-up, including cancellations, if needed */
345                 goto error;
346         }
347
348         cancel_bitmap=0;
349         if (lock) LOCK_REPLIES( trans );
350         if ( is_invite(trans) ) which_cancel(trans, &cancel_bitmap );
351         if (trans->uas.status>=200) {
352                 LOG( L_ERR, "ERROR: _reply_light: can't generate %d reply"
353                         " when a final %d was sent out\n", code, trans->uas.status);
354                 goto error2;
355         }
356
357
358         rb = & trans->uas.response;
359         rb->activ_type=code;
360
361         trans->uas.status = code;
362         buf_len = rb->buffer ? len : len + REPLY_OVERBUFFER_LEN;
363         rb->buffer = (char*)shm_resize( rb->buffer, buf_len );
364         /* puts the reply's buffer to uas.response */
365         if (! rb->buffer ) {
366                         LOG(L_ERR, "ERROR: _reply_light: cannot allocate shmem buffer\n");
367                         goto error3;
368         }
369         update_local_tags(trans, bm, rb->buffer, buf);
370
371         rb->buffer_len = len ;
372         memcpy( rb->buffer , buf , len );
373         /* needs to be protected too because what timers are set depends
374            on current transactions status */
375         /* t_update_timers_after_sending_reply( rb ); */
376         update_reply_stats( code );
377         trans->relaied_reply_branch=-2;
378         tm_stats->replied_localy++;
379         if (lock) UNLOCK_REPLIES( trans );
380         
381         /* do UAC cleanup procedures in case we generated
382            a final answer whereas there are pending UACs */
383         if (code>=200) {
384                 if ( is_local(trans) ) {
385                         DBG("DEBUG: local transaction completed from _reply\n");
386                         if ( has_tran_tmcbs(trans, TMCB_LOCAL_COMPLETED) )
387                                 run_trans_callbacks( TMCB_LOCAL_COMPLETED, trans,
388                                         0, FAKED_REPLY, code);
389                 } else {
390                         if ( has_tran_tmcbs(trans, TMCB_RESPONSE_OUT) )
391                                 run_trans_callbacks( TMCB_RESPONSE_OUT, trans,
392                                         trans->uas.request, FAKED_REPLY, code);
393                 }
394
395                 cleanup_uac_timers( trans );
396                 if (is_invite(trans)) cancel_uacs( trans, cancel_bitmap );
397                 set_final_timer(  trans );
398         }
399
400         /* send it out */
401         /* first check if we managed to resolve topmost Via -- if
402            not yet, don't try to retransmit
403         */
404         if (!trans->uas.response.dst.send_sock) {
405                 LOG(L_ERR, "ERROR: _reply_light: no resolved dst to send reply to\n");
406         } else {
407                 SEND_PR_BUFFER( rb, buf, len );
408                 DBG("DEBUG: reply sent out. buf=%p: %.9s..., shmem=%p: %.9s\n", 
409                         buf, buf, rb->buffer, rb->buffer );
410         }
411         pkg_free( buf ) ;
412         DBG("DEBUG: _reply_light: finished\n");
413         return 1;
414
415 error3:
416 error2:
417         if (lock) UNLOCK_REPLIES( trans );
418         pkg_free ( buf );
419 error:
420         /* do UAC cleanup */
421         cleanup_uac_timers( trans );
422         if ( is_invite(trans) ) cancel_uacs( trans, cancel_bitmap );
423         /* we did not succeed -- put the transaction on wait */
424         put_on_wait(trans);
425         return -1;
426 }
427
428
429 /* send a UAS reply
430  * returns 1 if everything was OK or -1 for error
431  */
432 static int _reply( struct cell *trans, struct sip_msg* p_msg, 
433         unsigned int code, char * text, int lock )
434 {
435         unsigned int len;
436         char * buf;
437         struct bookmark bm;
438
439         if (code>=200) set_kr(REQ_RPLD);
440         /* compute the buffer in private memory prior to entering lock;
441          * create to-tag if needed */
442         if (code>=180 && p_msg->to 
443                                 && (get_to(p_msg)->tag_value.s==0 
444                             || get_to(p_msg)->tag_value.len==0)) {
445                 calc_crc_suffix( p_msg, tm_tag_suffix );
446                 buf = build_res_buf_from_sip_req(code,text, &tm_tag, p_msg, &len, &bm);
447                 return _reply_light( trans, buf, len, code, text,
448                         tm_tag.s, TOTAG_VALUE_LEN, lock, &bm);
449         } else {
450                 buf = build_res_buf_from_sip_req(code,text, 0 /*no to-tag*/,
451                         p_msg, &len, &bm);
452
453                 return _reply_light(trans,buf,len,code,text,
454                         0, 0, /* no to-tag */lock, &bm);
455         }
456 }
457
458
459 /*if msg is set -> it will fake the env. vars conforming with the msg; if NULL
460  * the env. will be restore to original */
461 static inline void faked_env( struct cell *t,struct sip_msg *msg)
462 {
463         static enum route_mode backup_mode;
464         static struct cell *backup_t;
465         static unsigned int backup_msgid;
466
467         if (msg) {
468         /* remember we are back in request processing, but process
469          * a shmem-ed replica of the request; advertise it in rmode;
470          * for example t_reply needs to know that
471          */
472         backup_mode=rmode;
473         rmode=MODE_ONFAILURE;
474         /* also, tm actions look in beginning whether tranaction is
475          * set -- whether we are called from a reply-processing 
476          * or a timer process, we need to set current transaction;
477          * otherwise the actions would attempt to look the transaction
478          * up (unnecessary overhead, refcounting)
479          */
480         /* backup */
481         backup_t=get_t();
482         backup_msgid=global_msg_id;
483         /* fake transaction and message id */
484                 global_msg_id=msg->id;
485                 set_t(t);
486         } else {
487                 /* restore original environment */
488                 set_t(backup_t);
489                 global_msg_id=backup_msgid;
490                 rmode=backup_mode;
491         }
492 }
493
494
495 static inline int fake_req(struct sip_msg *faked_req, 
496                                 struct sip_msg *shmem_msg)
497 {
498         /* on_negative_reply faked msg now copied from shmem msg (as opposed
499          * to zero-ing) -- more "read-only" actions (exec in particular) will
500          * work from reply_route as they will see msg->from, etc.; caution,
501          * rw actions may append some pkg stuff to msg, which will possibly be
502          * never released (shmem is released in a single block) */
503         memcpy( faked_req, shmem_msg, sizeof(struct sip_msg));
504
505         /* if we set msg_id to something different from current's message
506          * id, the first t_fork will properly clean new branch URIs */
507         faked_req->id=shmem_msg->id-1;
508         /* msg->parsed_uri_ok must be reset since msg_parsed_uri is
509          * not cloned (and cannot be cloned) */
510         faked_req->parsed_uri_ok = 0;
511
512         /* new_uri can change -- make a private copy */
513         if (shmem_msg->new_uri.s!=0 && shmem_msg->new_uri.len!=0) {
514                 faked_req->new_uri.s=pkg_malloc(shmem_msg->new_uri.len+1);
515                 if (!faked_req->new_uri.s) {
516                         LOG(L_ERR, "ERROR: fake_req: no uri/pkg mem\n");
517                         goto error00;
518                 }
519                 faked_req->new_uri.len=shmem_msg->new_uri.len;
520                 memcpy( faked_req->new_uri.s, shmem_msg->new_uri.s, 
521                         faked_req->new_uri.len);
522                 faked_req->new_uri.s[faked_req->new_uri.len]=0;
523         }
524
525 #if 0
526         /* create a duplicated lump list to which actions can add
527          * new pkg items  */
528         if (shmem_msg->add_rm) {
529                 faked_req->add_rm=dup_lump_list(shmem_msg->add_rm);
530                 if (!faked_req->add_rm) { /* non_emty->empty ... failure */
531                         LOG(L_ERR, "ERROR: fake_req: lump dup failed\n");
532                         goto error01;
533                 }
534         }
535         /* same for the body lumps */
536         if (shmem_msg->body_lumps) {
537                 faked_req->body_lumps=dup_lump_list(shmem_msg->body_lumps);
538                 if (!faked_req->body_lumps) { /* non_empty->empty ... failure */
539                         LOG(L_ERR, "ERROR: fake_req: lump dup failed\n");
540                         goto error02;
541                 }
542         }
543 #endif
544         return 1;
545
546 #if 0
547 error02:
548         free_duped_lump_list(faked_req->add_rm);
549 error01:
550         if (faked_req->new_uri.s) pkg_free(faked_req->new_uri.s);
551 #endif
552 error00:
553         return 0;
554 }
555
556 void inline static free_faked_req(struct sip_msg *faked_req, struct cell *t)
557 {
558         struct hdr_field *hdr;
559
560 #if 0
561         free_duped_lump_list(faked_req->add_rm);
562         free_duped_lump_list(faked_req->body_lumps);
563         faked_req->add_rm = faked_req->body_lumps = 0;
564 #endif
565         if (faked_req->new_uri.s) {
566                 pkg_free(faked_req->new_uri.s);
567                 faked_req->new_uri.s = 0;
568         }
569
570         /* free all types of lump that were added in failure handlers */
571         del_nonshm_lump( &(faked_req->add_rm) );
572         del_nonshm_lump( &(faked_req->body_lumps) );
573         del_nonshm_lump_rpl( &(faked_req->reply_lump) );
574
575         /* free header's parsed structures that were added by failure handlers */
576         for( hdr=faked_req->headers ; hdr ; hdr=hdr->next ) {
577                 if ( hdr->parsed && hdr_allocs_parse(hdr) &&
578                 (hdr->parsed<(void*)t->uas.request ||
579                 hdr->parsed>=(void*)t->uas.end_request)) {
580                         /* header parsed filed doesn't point inside uas.request memory
581                          * chunck -> it was added by failure funcs.-> free it as pkg */
582                         DBG("DBG:free_faked_req: removing hdr->parsed %d\n",
583                                         hdr->type);
584                         clean_hdr_field(hdr);
585                         hdr->parsed = 0;
586                 }
587         }
588 }
589
590
591 /* return 1 if a failure_route processes */
592 static inline int run_failure_handlers(struct cell *t, struct sip_msg *rpl,
593                                                                                                                                         int code)
594 {
595         static struct sip_msg faked_req;
596         struct sip_msg *shmem_msg = t->uas.request;
597         int on_failure;
598
599         /* failure_route for a local UAC? */
600         if (!shmem_msg) {
601                 LOG(L_WARN, "Warning: run_failure_handlers: no UAC support\n");
602                 return 0;
603         }
604
605         /* don't start faking anything if we don't have to */
606         if ( !has_tran_tmcbs( t, TMCB_ON_FAILURE) && !t->on_negative ) {
607                 return 1;
608         }
609
610         if (!fake_req(&faked_req, shmem_msg)) {
611                 LOG(L_ERR, "ERROR: run_failure_handlers: fake_req failed\n");
612                 return 0;
613         }
614         /* fake also the env. conforming to the fake msg */
615         faked_env( t, &faked_req);
616         /* DONE with faking ;-) -> run the failure handlers */
617
618         if ( has_tran_tmcbs( t, TMCB_ON_FAILURE) ) {
619                 run_trans_callbacks( TMCB_ON_FAILURE, t, &faked_req, rpl, code);
620         }
621         if (t->on_negative) {
622                 /* avoid recursion -- if failure_route forwards, and does not 
623                  * set next failure route, failure_route will not be rentered
624                  * on failure */
625                 on_failure = t->on_negative;
626                 t->on_negative=0;
627                 /* run a reply_route action if some was marked */
628                 if (run_actions(failure_rlist[on_failure], &faked_req)<0)
629                         LOG(L_ERR, "ERROR: run_failure_handlers: Error in do_action\n");
630                 /* destroy any eventual avps */
631                 if (users_avps)
632                         destroy_avps();
633         }
634
635         /* restore original environment and free the fake msg */
636         faked_env( t, 0);
637         free_faked_req(&faked_req,t);
638
639         /* if failure handler changed flag, update transaction context */
640         shmem_msg->flags = faked_req.flags;
641         return 1;
642 }
643
644
645 /* select a branch for forwarding; returns:
646  * 0..X ... branch number
647  * -1   ... error
648  * -2   ... can't decide yet -- incomplete branches present
649  */
650 int t_pick_branch(int inc_branch, int inc_code, struct cell *t, int *res_code)
651 {
652         int lowest_b, lowest_s, b;
653
654         lowest_b=-1; lowest_s=999;
655         for ( b=0; b<t->nr_of_outgoings ; b++ ) {
656                 /* "fake" for the currently processed branch */
657                 if (b==inc_branch) {
658                         if (inc_code<lowest_s) {
659                                 lowest_b=b;
660                                 lowest_s=inc_code;
661                         }
662                         continue;
663                 }
664                 /* skip 'empty branches' */
665                 if (!t->uac[b].request.buffer) continue;
666                 /* there is still an unfinished UAC transaction; wait now! */
667                 if ( t->uac[b].last_received<200 ) 
668                         return -2;
669                 if ( t->uac[b].last_received<lowest_s ) {
670                         lowest_b =b;
671                         lowest_s = t->uac[b].last_received;
672                 }
673         } /* find lowest branch */
674
675         *res_code=lowest_s;
676         return lowest_b;
677 }
678
679 /* This is the neuralgical point of reply processing -- called
680  * from within a REPLY_LOCK, t_should_relay_response decides
681  * how a reply shall be processed and how transaction state is
682  * affected.
683  *
684  * Checks if the new reply (with new_code status) should be sent or not
685  *  based on the current
686  * transactin status.
687  * Returns      - branch number (0,1,...) which should be relayed
688  *         -1 if nothing to be relayed
689  */
690 static enum rps t_should_relay_response( struct cell *Trans , int new_code,
691         int branch , int *should_store, int *should_relay,
692         branch_bm_t *cancel_bitmap, struct sip_msg *reply )
693 {
694         int branch_cnt;
695         int picked_branch;
696         int picked_code;
697         int inv_through;
698
699         /* note: this code never lets replies to CANCEL go through;
700            we generate always a local 200 for CANCEL; 200s are
701            not relayed because it's not an INVITE transaction;
702            >= 300 are not relayed because 200 was already sent
703            out
704         */
705         DBG("->>>>>>>>> T_code=%d, new_code=%d\n",Trans->uas.status,new_code);
706         inv_through=new_code>=200 && new_code<300 && is_invite(Trans);
707         /* if final response sent out, allow only INVITE 2xx  */
708         if ( Trans->uas.status >= 200 ) {
709                 if (inv_through) {
710                         DBG("DBG: t_should_relay_response: 200 INV after final sent\n");
711                         *should_store=0;
712                         Trans->uac[branch].last_received=new_code;
713                         *should_relay=branch;
714                         return RPS_PUSHED_AFTER_COMPLETION;
715                 } 
716                 /* except the exception above, too late  messages will
717                    be discarded */
718                 goto discard;
719         } 
720
721         /* if final response received at this branch, allow only INVITE 2xx */
722         if (Trans->uac[branch].last_received>=200
723                         && !(inv_through && Trans->uac[branch].last_received<300)) {
724                 /* don't report on retranmissions */
725                 if (Trans->uac[branch].last_received==new_code) {
726                         DBG("DEBUG: final reply retrasnmission\n");
727                         goto discard;
728                 }
729                 /* if you FR-timed-out, faked a local 408 and 487 came, don't
730                  * report on it either */
731                 if (Trans->uac[branch].last_received==408 && new_code==487) {
732                         DBG("DEBUG: 487 came for a timed-out branch\n");
733                         goto discard;
734                 }
735                 /* this looks however how a very strange status rewrite attempt;
736                  * report on it */
737                 LOG(L_ERR, "ERROR: t_should_relay_response: status rewrite by UAS: "
738                         "stored: %d, received: %d\n",
739                         Trans->uac[branch].last_received, new_code );
740                 goto discard;
741         }
742
743
744         /* no final response sent yet */
745         /* negative replies subject to fork picking */
746         if (new_code >=300 ) {
747
748                 Trans->uac[branch].last_received=new_code;
749
750                 /* if all_final return lowest */
751                 picked_branch=t_pick_branch(branch,new_code, Trans, &picked_code);
752                 if (picked_branch==-2) { /* branches open yet */
753                         *should_store=1;
754                         *should_relay=-1;
755                         return RPS_STORE;
756                 }
757                 if (picked_branch==-1) {
758                         LOG(L_CRIT, "ERROR: t_should_relay_response: lowest==-1\n");
759                         goto error;
760                 }
761
762                 /* no more pending branches -- try if that changes after
763                    a callback; save banch count to be able to determine
764                    later if new branches were initiated */
765                 branch_cnt=Trans->nr_of_outgoings;
766
767                 /* run ON_FAILURE handlers ( route and callbacks) */
768                 if ( has_tran_tmcbs( Trans, TMCB_ON_FAILURE_RO|TMCB_ON_FAILURE)
769                 || Trans->on_negative ) {
770                         run_failure_handlers( Trans,
771                                 picked_branch==branch?reply:Trans->uac[picked_branch].reply, 
772                                 picked_code);
773                 }
774
775                 /* look if the callback perhaps replied transaction; it also
776                    covers the case in which a transaction is replied localy
777                    on CANCEL -- then it would make no sense to proceed to
778                    new branches bellow
779                 */
780                 if (Trans->uas.status >= 200) {
781                         *should_store=0;
782                         *should_relay=-1;
783                         /* this might deserve an improvement -- if something
784                            was already replied, it was put on wait and then,
785                            returning RPS_COMPLETED will make t_on_reply
786                            put it on wait again; perhaps splitting put_on_wait
787                            from send_reply or a new RPS_ code would be healthy
788                         */
789                         return RPS_COMPLETED;
790                 }
791                 /* look if the callback/failure_route introduced new branches ... */
792                 if (branch_cnt<Trans->nr_of_outgoings)  {
793                         /* await then result of new branches */
794                         *should_store=1;
795                         *should_relay=-1;
796                         return RPS_STORE;
797                 }
798
799                 /* really no more pending branches -- return lowest code */
800                 *should_store=0;
801                 *should_relay=picked_branch;
802                 /* we dont need 'which_cancel' here -- all branches 
803                    known to have completed */
804                 /* which_cancel( Trans, cancel_bitmap ); */
805                 return RPS_COMPLETED;
806         } 
807
808         /* not >=300 ... it must be 2xx or provisional 1xx */
809         if (new_code>=100) {
810                 /* 1xx and 2xx except 100 will be relayed */
811                 Trans->uac[branch].last_received=new_code;
812                 *should_store=0;
813                 *should_relay= new_code==100? -1 : branch;
814                 if (new_code>=200 ) {
815                         which_cancel( Trans, cancel_bitmap );
816                         return RPS_COMPLETED;
817                 } else return RPS_PROVISIONAL;
818         }
819
820 error:
821         /* reply_status didn't match -- it must be something weird */
822         LOG(L_CRIT, "ERROR: Oh my gooosh! We don't know whether to relay %d\n",
823                 new_code);
824 discard:
825         *should_store=0;
826         *should_relay=-1;
827         return RPS_DISCARDED;
828 }
829
830 /* Retransmits the last sent inbound reply.
831  * input: p_msg==request for which I want to retransmit an associated reply
832  * Returns  -1 - error
833  *           1 - OK
834  */
835 int t_retransmit_reply( struct cell *t )
836 {
837         static char b[BUF_SIZE];
838         int len;
839
840         /* first check if we managed to resolve topmost Via -- if
841            not yet, don't try to retransmit
842         */
843         if (!t->uas.response.dst.send_sock) {
844                 LOG(L_WARN, "WARNING: t_retransmit_reply: "
845                         "no resolved dst to retransmit\n");
846                 return -1;
847         }
848
849         /* we need to lock the transaction as messages from
850            upstream may change it continuously
851         */
852         LOCK_REPLIES( t );
853
854         if (!t->uas.response.buffer) {
855                 DBG("DBG: t_retransmit_reply: nothing to retransmit\n");
856                 goto error;
857         }
858
859         len=t->uas.response.buffer_len;
860         if ( len==0 || len>BUF_SIZE )  {
861                 DBG("DBG: t_retransmit_reply: "
862                         "zero length or too big to retransmit: %d\n", len);
863                 goto error;
864         }
865         memcpy( b, t->uas.response.buffer, len );
866         UNLOCK_REPLIES( t );
867         SEND_PR_BUFFER( & t->uas.response, b, len );
868         DBG("DEBUG: reply retransmitted. buf=%p: %.9s..., shmem=%p: %.9s\n", 
869                 b, b, t->uas.response.buffer, t->uas.response.buffer );
870         return 1;
871
872 error:
873         UNLOCK_REPLIES(t);
874         return -1;
875 }
876
877
878
879
880 int t_reply( struct cell *t, struct sip_msg* p_msg, unsigned int code, 
881         char * text )
882 {
883         return _reply( t, p_msg, code, text, 1 /* lock replies */ );
884 }
885
886 int t_reply_unsafe( struct cell *t, struct sip_msg* p_msg, unsigned int code, 
887         char * text )
888 {
889         return _reply( t, p_msg, code, text, 0 /* don't lock replies */ );
890 }
891
892
893
894
895
896 void set_final_timer( /* struct s_table *h_table, */ struct cell *t )
897 {
898         if ( !is_local(t) && t->uas.request->REQ_METHOD==METHOD_INVITE ) {
899                 /* crank timers for negative replies */
900                 if (t->uas.status>=300) {
901                         start_retr(&t->uas.response);
902                         return;
903                 }
904                 /* local UAS retransmits too */
905                 if (t->relaied_reply_branch==-2 && t->uas.status>=200) {
906                         /* we retransmit 200/INVs regardless of transport --
907                            even if TCP used, UDP could be used upstream and
908                            loose the 200, which is not retransmitted by proxies
909                         */
910                         force_retr( &t->uas.response );
911                         return;
912                 }
913         } 
914         put_on_wait(t);
915 }
916
917 void cleanup_uac_timers( struct cell *t )
918 {
919         int i;
920
921         /* reset FR/retransmission timers */
922         for (i=0; i<t->nr_of_outgoings; i++ )  {
923                 reset_timer( &t->uac[i].request.retr_timer );
924                 reset_timer( &t->uac[i].request.fr_timer );
925         }
926         DBG("DEBUG: cleanup_uac_timers: RETR/FR timers reset\n");
927 }
928
929 static int store_reply( struct cell *trans, int branch, struct sip_msg *rpl)
930 {
931 #               ifdef EXTRA_DEBUG
932                 if (trans->uac[branch].reply) {
933                         LOG(L_ERR, "ERROR: replacing stored reply; aborting\n");
934                         abort();
935                 }
936 #               endif
937
938                 /* when we later do things such as challenge aggregation,
939                    we should parse the message here before we conservate
940                    it in shared memory; -jiri
941                 */
942                 if (rpl==FAKED_REPLY)
943                         trans->uac[branch].reply=FAKED_REPLY;
944                 else
945                         trans->uac[branch].reply = sip_msg_cloner( rpl, 0 );
946
947                 if (! trans->uac[branch].reply ) {
948                         LOG(L_ERR, "ERROR: store_reply: can't alloc' clone memory\n");
949                         return 0;
950                 }
951
952                 return 1;
953 }
954
955 /* this is the code which decides what and when shall be relayed
956    upstream; note well -- it assumes it is entered locked with 
957    REPLY_LOCK and it returns unlocked!
958 */
959 enum rps relay_reply( struct cell *t, struct sip_msg *p_msg, int branch, 
960         unsigned int msg_status, branch_bm_t *cancel_bitmap )
961 {
962         int relay;
963         int save_clone;
964         char *buf;
965         /* length of outbound reply */
966         unsigned int res_len;
967         int relayed_code;
968         struct sip_msg *relayed_msg;
969         struct bookmark bm;
970         int totag_retr;
971         enum rps reply_status;
972         /* retransmission structure of outbound reply and request */
973         struct retr_buf *uas_rb;
974
975         /* keep compiler warnings about use of uninit vars silent */
976         res_len=0;
977         buf=0;
978         relayed_msg=0;
979         relayed_code=0;
980         totag_retr=0;
981
982
983         /* remember, what was sent upstream to know whether we are
984          * forwarding a first final reply or not */
985
986         /* *** store and relay message as needed *** */
987         reply_status = t_should_relay_response(t, msg_status, branch, 
988                 &save_clone, &relay, cancel_bitmap, p_msg );
989         DBG("DEBUG: relay_reply: branch=%d, save=%d, relay=%d\n",
990                 branch, save_clone, relay );
991
992         /* store the message if needed */
993         if (save_clone) /* save for later use, typically branch picking */
994         {
995                 if (!store_reply( t, branch, p_msg ))
996                         goto error01;
997         }
998
999         uas_rb = & t->uas.response;
1000         if (relay >= 0 ) {
1001                 /* initialize sockets for outbound reply */
1002                 uas_rb->activ_type=msg_status;
1003                 /* only messages known to be relayed immediately will be
1004                  * be called on; we do not evoke this callback on messages
1005                  * stored in shmem -- they are fixed and one cannot change them
1006                  * anyway */
1007                 if (msg_status<300 && branch==relay
1008                 && has_tran_tmcbs(t,TMCB_RESPONSE_FWDED) ) {
1009                         run_trans_callbacks( TMCB_RESPONSE_FWDED, t, t->uas.request,
1010                                 p_msg, msg_status );
1011                 }
1012                 /* try bulding the outbound reply from either the current
1013                  * or a stored message */
1014                 relayed_msg = branch==relay ? p_msg :  t->uac[relay].reply;
1015                 if (relayed_msg==FAKED_REPLY) {
1016                         tm_stats->replied_localy++;
1017                         relayed_code = branch==relay
1018                                 ? msg_status : t->uac[relay].last_received;
1019
1020                         if (relayed_code>=180 && t->uas.request->to 
1021                                         && (get_to(t->uas.request)->tag_value.s==0 
1022                                         || get_to(t->uas.request)->tag_value.len==0)) {
1023                                 calc_crc_suffix( t->uas.request, tm_tag_suffix );
1024                                 buf = build_res_buf_from_sip_req(
1025                                                 relayed_code,
1026                                                 error_text(relayed_code),
1027                                                 &tm_tag,
1028                                                 t->uas.request, &res_len, &bm );
1029                         } else {
1030                                 buf = build_res_buf_from_sip_req( relayed_code,
1031                                         error_text(relayed_code), 0/* no to-tag */,
1032                                         t->uas.request, &res_len, &bm );
1033                         }
1034
1035                 } else {
1036                         relayed_code=relayed_msg->REPLY_STATUS;
1037                         buf = build_res_buf_from_sip_res( relayed_msg, &res_len );
1038                         /* if we build a message from shmem, we need to remove
1039                            via delete lumps which are now stirred in the shmem-ed
1040                            structure
1041                         */
1042                         if (branch!=relay) {
1043                                 free_via_clen_lump(&relayed_msg->add_rm);
1044                         }
1045                 }
1046                 update_reply_stats( relayed_code );
1047                 if (!buf) {
1048                         LOG(L_ERR, "ERROR: relay_reply: "
1049                                 "no mem for outbound reply buffer\n");
1050                         goto error02;
1051                 }
1052
1053                 /* attempt to copy the message to UAS's shmem:
1054                    - copy to-tag for ACK matching as well
1055                    -  allocate little a bit more for provisionals as
1056                       larger messages are likely to follow and we will be 
1057                       able to reuse the memory frag 
1058                 */
1059                 uas_rb->buffer = (char*)shm_resize( uas_rb->buffer, res_len +
1060                         (msg_status<200 ?  REPLY_OVERBUFFER_LEN : 0));
1061                 if (!uas_rb->buffer) {
1062                         LOG(L_ERR, "ERROR: relay_reply: cannot alloc reply shmem\n");
1063                         goto error03;
1064                 }
1065                 uas_rb->buffer_len = res_len;
1066                 memcpy( uas_rb->buffer, buf, res_len );
1067                 if (relayed_msg==FAKED_REPLY) { /* to-tags for local replies */
1068                         update_local_tags(t, &bm, uas_rb->buffer, buf);
1069                 }
1070                 tm_stats->replied_localy++;
1071
1072                 /* update the status ... */
1073                 t->uas.status = relayed_code;
1074                 t->relaied_reply_branch = relay;
1075
1076                 if (is_invite(t) && relayed_msg!=FAKED_REPLY
1077                 && relayed_code>=200 && relayed_code < 300
1078                 && has_tran_tmcbs( t, TMCB_RESPONSE_OUT|TMCB_E2EACK_IN) ) {
1079                         totag_retr=update_totag_set(t, relayed_msg);
1080                 }
1081         }; /* if relay ... */
1082
1083         UNLOCK_REPLIES( t );
1084
1085         /* send it now (from the private buffer) */
1086         if (relay >= 0) {
1087                 SEND_PR_BUFFER( uas_rb, buf, res_len );
1088                 DBG("DEBUG: reply relayed. buf=%p: %.9s..., shmem=%p: %.9s\n", 
1089                         buf, buf, uas_rb->buffer, uas_rb->buffer );
1090                 if (!totag_retr && has_tran_tmcbs(t, TMCB_RESPONSE_OUT) ) {
1091                         run_trans_callbacks( TMCB_RESPONSE_OUT, t, t->uas.request,
1092                                 relayed_msg, relayed_code);
1093                 }
1094                 pkg_free( buf );
1095         }
1096
1097         /* success */
1098         return reply_status;
1099
1100 error03:
1101         pkg_free( buf );
1102 error02:
1103         if (save_clone) {
1104                 if (t->uac[branch].reply!=FAKED_REPLY)
1105                         sip_msg_free( t->uac[branch].reply );
1106                 t->uac[branch].reply = NULL;    
1107         }
1108 error01:
1109         t_reply_unsafe( t, t->uas.request, 500, "Reply processing error" );
1110         UNLOCK_REPLIES(t);
1111         if (is_invite(t)) cancel_uacs( t, *cancel_bitmap );
1112         /* a serious error occured -- attempt to send an error reply;
1113            it will take care of clean-ups  */
1114
1115         /* failure */
1116         return RPS_ERROR;
1117 }
1118
1119 /* this is the "UAC" above transaction layer; if a final reply
1120    is received, it triggers a callback; note well -- it assumes
1121    it is entered locked with REPLY_LOCK and it returns unlocked!
1122 */
1123 enum rps local_reply( struct cell *t, struct sip_msg *p_msg, int branch, 
1124         unsigned int msg_status, branch_bm_t *cancel_bitmap)
1125 {
1126         /* how to deal with replies for local transaction */
1127         int local_store, local_winner;
1128         enum rps reply_status;
1129         struct sip_msg *winning_msg;
1130         int winning_code;
1131         int totag_retr;
1132         /* branch_bm_t cancel_bitmap; */
1133
1134         /* keep warning 'var might be used un-inited' silent */ 
1135         winning_msg=0;
1136         winning_code=0;
1137         totag_retr=0;
1138
1139         *cancel_bitmap=0;
1140
1141         reply_status=t_should_relay_response( t, msg_status, branch,
1142                 &local_store, &local_winner, cancel_bitmap, p_msg );
1143         DBG("DEBUG: local_reply: branch=%d, save=%d, winner=%d\n",
1144                 branch, local_store, local_winner );
1145         if (local_store) {
1146                 if (!store_reply(t, branch, p_msg))
1147                         goto error;
1148         }
1149         if (local_winner>=0) {
1150                 winning_msg= branch==local_winner 
1151                         ? p_msg :  t->uac[local_winner].reply;
1152                 if (winning_msg==FAKED_REPLY) {
1153                         tm_stats->replied_localy++;
1154                         winning_code = branch==local_winner
1155                                 ? msg_status : t->uac[local_winner].last_received;
1156                 } else {
1157                         winning_code=winning_msg->REPLY_STATUS;
1158                 }
1159                 t->uas.status = winning_code;
1160                 update_reply_stats( winning_code );
1161                 if (is_invite(t) && winning_msg!=FAKED_REPLY
1162                 && winning_code>=200 && winning_code <300
1163                 && has_tran_tmcbs(t,TMCB_RESPONSE_OUT|TMCB_E2EACK_IN) )  {
1164                         totag_retr=update_totag_set(t, winning_msg);
1165                 }
1166         }
1167         UNLOCK_REPLIES(t);
1168         if (local_winner>=0 && winning_code>=200 ) {
1169                 DBG("DEBUG: local transaction completed\n");
1170                 if (!totag_retr) {
1171                         if ( has_tran_tmcbs(t,TMCB_LOCAL_COMPLETED) )
1172                                 run_trans_callbacks( TMCB_LOCAL_COMPLETED, t, 0,
1173                                         winning_msg, winning_code );
1174                 }
1175         }
1176         return reply_status;
1177
1178 error:
1179         which_cancel(t, cancel_bitmap);
1180         UNLOCK_REPLIES(t);
1181         cleanup_uac_timers(t);
1182         if ( get_cseq(p_msg)->method.len==INVITE_LEN 
1183                 && memcmp( get_cseq(p_msg)->method.s, INVITE, INVITE_LEN)==0)
1184                 cancel_uacs( t, *cancel_bitmap );
1185         put_on_wait(t);
1186         return RPS_ERROR;
1187 }
1188
1189
1190
1191
1192
1193 /*  This function is called whenever a reply for our module is received; 
1194   * we need to register  this function on module initialization;
1195   *  Returns :   0 - core router stops
1196   *              1 - core router relay statelessly
1197   */
1198 int reply_received( struct sip_msg  *p_msg )
1199 {
1200
1201         int msg_status;
1202         char *ack;
1203         unsigned int ack_len;
1204         int branch;
1205         /* has the transaction completed now and we need to clean-up? */
1206         int reply_status;
1207         branch_bm_t cancel_bitmap;
1208         struct ua_client *uac;
1209         struct cell *t;
1210         str next_hop;
1211
1212         /* make sure we know the assosociated transaction ... */
1213         if (t_check( p_msg  , &branch )==-1)
1214                 return 1;
1215         /*... if there is none, tell the core router to fwd statelessly */
1216         t=get_t();
1217         if ( (t==0)||(t==T_UNDEFINED)) return 1;
1218
1219         cancel_bitmap=0;
1220         msg_status=p_msg->REPLY_STATUS;
1221
1222         uac=&t->uac[branch];
1223         DBG("DEBUG: reply_received: org. status uas=%d, "
1224                 "uac[%d]=%d local=%d is_invite=%d)\n",
1225                 t->uas.status, branch, uac->last_received, 
1226                 is_local(t), is_invite(t));
1227
1228         /* it's a cancel ... ? */
1229         if (get_cseq(p_msg)->method.len==CANCEL_LEN 
1230                 && memcmp( get_cseq(p_msg)->method.s, CANCEL, CANCEL_LEN)==0
1231                 /* .. which is not e2e ? ... */
1232                 && is_invite(t) ) {
1233                         /* ... then just stop timers */
1234                         reset_timer( &uac->local_cancel.retr_timer);
1235                         if ( msg_status >= 200 )
1236                                 reset_timer( &uac->local_cancel.fr_timer);
1237                         DBG("DEBUG: reply to local CANCEL processed\n");
1238                         goto done;
1239         }
1240
1241
1242         /* *** stop timers *** */
1243         /* stop retransmission */
1244         reset_timer( &uac->request.retr_timer);
1245         /* stop final response timer only if I got a final response */
1246         if ( msg_status >= 200 )
1247                 reset_timer( &uac->request.fr_timer);
1248                 /* acknowledge negative INVITE replies (do it before detailed
1249                  * on_reply processing, which may take very long, like if it
1250                  * is attempted to establish a TCP connection to a fail-over dst */
1251
1252         if (t->flags & T_IS_INVITE_FLAG) {
1253                 if (msg_status >= 300) {
1254                         ack = build_ack(p_msg, t, branch, &ack_len);
1255                         if (ack) {
1256                                 SEND_PR_BUFFER(&uac->request, ack, ack_len);
1257                                 shm_free(ack);
1258                         }
1259                 } else if ((t->flags & T_IS_LOCAL_FLAG) && msg_status >= 200) {
1260                         ack = build_local_ack(p_msg, t, branch, &ack_len, &next_hop);
1261                         if (ack) {
1262                                 if (send_local_ack(&next_hop, ack, ack_len) < 0) {
1263                                         LOG(L_ERR, "Error while seding local ACK\n");
1264                                 }
1265                                 shm_free(ack);
1266                         }
1267                 }
1268         }
1269              /* processing of on_reply block */
1270         if (t->on_reply) {
1271                 rmode=MODE_ONREPLY;
1272                      /* transfer transaction flag to message context */
1273                 if (t->uas.request) p_msg->flags=t->uas.request->flags;
1274                 if (run_actions(onreply_rlist[t->on_reply], p_msg)<0) 
1275                         LOG(L_ERR, "ERROR: on_reply processing failed\n");
1276                      /* destroy any eventual avps */
1277                 if (users_avps)
1278                         destroy_avps();
1279                      /* transfer current message context back to t */
1280                 if (t->uas.request) t->uas.request->flags=p_msg->flags;
1281         }
1282         LOCK_REPLIES( t );
1283         if ( is_local(t) ) {
1284                 reply_status=local_reply( t, p_msg, branch, msg_status, &cancel_bitmap );
1285         } else {
1286                 reply_status=relay_reply( t, p_msg, branch, msg_status, 
1287                         &cancel_bitmap );
1288         }
1289
1290         if (reply_status==RPS_ERROR)
1291                 goto done;
1292
1293         /* clean-up the transaction when transaction completed */
1294         if (reply_status==RPS_COMPLETED) {
1295                 /* no more UAC FR/RETR (if I received a 2xx, there may
1296                    be still pending branches ...
1297                 */
1298                 cleanup_uac_timers( t );        
1299                 if (is_invite(t)) cancel_uacs( t, cancel_bitmap );
1300                 /* FR for negative INVITES, WAIT anything else */
1301                 set_final_timer(  t );
1302         } 
1303
1304         /* update FR/RETR timers on provisional replies */
1305         if (msg_status<200) { /* provisional now */
1306                 if (is_invite(t)) {
1307                         /* invite: change FR to longer FR_INV, do not
1308                            attempt to restart retransmission any more
1309                         */
1310                         set_timer( & uac->request.fr_timer,
1311                                 FR_INV_TIMER_LIST );
1312                 } else {
1313                         /* non-invite: restart retransmisssions (slow now) */
1314                         uac->request.retr_list=RT_T2;
1315                         set_timer(  & uac->request.retr_timer, RT_T2 );
1316                 }
1317         } /* provisional replies */
1318
1319 done:
1320         /* don't try to relay statelessly neither on success
1321        (we forwarded statefuly) nor on error; on troubles, 
1322            simply do nothing; that will make the other party to 
1323            retransmit; hopefuly, we'll then be better off */
1324         return 0;
1325 }
1326
1327
1328
1329 int t_reply_with_body( struct cell *trans, unsigned int code, 
1330                 char * text, char * body, char * new_header, char * to_tag )
1331 {
1332         struct lump_rpl *hdr_lump;
1333         struct lump_rpl *body_lump;
1334         str  s_to_tag;
1335         str  rpl;
1336         int  ret;
1337         struct bookmark bm;
1338
1339         s_to_tag.s = to_tag;
1340         if(to_tag)
1341                 s_to_tag.len = strlen(to_tag);
1342
1343         /* mark the transaction as replied */
1344         if (code>=200) set_kr(REQ_RPLD);
1345
1346         /* add the lumps for new_header and for body (by bogdan) */
1347         if (new_header && strlen(new_header)) {
1348                 hdr_lump = add_lump_rpl( trans->uas.request, new_header,
1349                                          strlen(new_header), LUMP_RPL_HDR );
1350                 if ( !hdr_lump ) {
1351                         LOG(L_ERR,"ERROR:tm:t_reply_with_body: cannot add hdr lump\n");
1352                         goto error;
1353                 }
1354         } else {
1355                 hdr_lump = 0;
1356         }
1357
1358         /* body lump */
1359         if(body && strlen(body)) {
1360                 body_lump = add_lump_rpl( trans->uas.request, body, strlen(body),
1361                         LUMP_RPL_BODY );
1362                 if (body_lump==0) {
1363                         LOG(L_ERR,"ERROR:tm:t_reply_with_body: cannot add body lump\n");
1364                         goto error_1;
1365                 }
1366         } else {
1367                 body_lump = 0;
1368         }
1369
1370         rpl.s = build_res_buf_from_sip_req(
1371                         code, text, &s_to_tag,
1372                         trans->uas.request, (unsigned int*)&rpl.len, &bm);
1373
1374         /* since the msg (trans->uas.request) is a clone into shm memory, to avoid
1375          * memory leak or crashing (lumps are create in private memory) I will
1376          * remove the lumps by myself here (bogdan) */
1377         if ( hdr_lump ) {
1378                 unlink_lump_rpl( trans->uas.request, hdr_lump);
1379                 free_lump_rpl( hdr_lump );
1380         }
1381         if( body_lump ) {
1382                 unlink_lump_rpl( trans->uas.request, body_lump);
1383                 free_lump_rpl( body_lump );
1384         }
1385
1386         if (rpl.s==0) {
1387                 LOG(L_ERR,"ERROR:tm:t_reply_with_body: failed in doing "
1388                         "build_res_buf_from_sip_req()\n");
1389                 goto error;
1390         }
1391
1392         DBG("t_reply_with_body: buffer computed\n");
1393         // frees 'res.s' ... no panic !
1394         ret=_reply_light( trans, rpl.s, rpl.len, code, text, 
1395                 s_to_tag.s, s_to_tag.len, 1 /* lock replies */, &bm );
1396         /* this is ugly hack -- the function caller may wish to continue with
1397          * transction and I unref; however, there is now only one use from
1398          * vm/fifo_vm_reply and I'm currently to lazy to export UNREF; -jiri
1399          */
1400         UNREF(trans);
1401
1402         return ret;
1403 error_1:
1404         if ( hdr_lump ) {
1405                 unlink_lump_rpl( trans->uas.request, hdr_lump);
1406                 free_lump_rpl( hdr_lump );
1407         }
1408 error:
1409         return -1;
1410 }
1411
1412
1413
1414 /*
1415   Syntax:
1416
1417   ":vm_reply:[response file]\n
1418   code\n
1419   reason\n
1420   trans_id\n
1421   to_tag\n
1422   [new headers]\n
1423   \n
1424   [Body]\n
1425   .\n
1426   \n"
1427  */
1428 int fifo_t_reply( FILE *stream, char *response_file )
1429 {
1430         int ret;
1431         struct cell *trans;
1432         char code[16];
1433         char reason[128];
1434         char trans_id[128];
1435         char new_headers[MAX_HEADER];
1436         char body[MAX_BODY];
1437         char to_tag[128];
1438         str sc;       /*  code */
1439         str sr;       /*  reason */
1440         str sti;      /*  trans_id */
1441         str snh;      /*  new_headers */
1442         str sb;       /*  body */
1443         str sttag;    /*  to-tag */
1444         unsigned int hash_index,label,icode;
1445
1446         sc.s=code;
1447         sr.s=reason;
1448         sti.s=trans_id;
1449         snh.s=new_headers; sb.s=body;
1450         sttag.s=to_tag; sttag.len=0;
1451
1452
1453         /*  get the infos from FIFO server */
1454
1455         DBG("DEBUG: fifo_t_reply: ############### begin ##############\n");
1456
1457         if (!read_line(sc.s, 16, stream, &sc.len)||sc.len==0) {
1458                 LOG(L_ERR, "ERROR: fifo_t_reply: code expected\n");
1459                 fifo_reply(response_file, "400 fifo_t_reply: code expected");
1460                 return -1;
1461         }
1462
1463         icode = str2s(sc.s,sc.len,&ret);
1464         if(ret){
1465                 LOG(L_ERR, "ERROR: fifo_t_reply: code(int) has wrong format\n");
1466                 fifo_reply(response_file, "400 fifo_t_reply: code(int) has"
1467                         " wrong format");
1468                 return -1;
1469         }
1470
1471         if(!read_line(sr.s, 128, stream, &sr.len)||sr.len==0){
1472                 LOG(L_ERR, "ERROR: fifo_t_reply: reason expected\n");
1473                 fifo_reply(response_file, "400 fifo_t_reply: reason expected");
1474                 return -1;
1475         }
1476         sr.s[sr.len]='\0';
1477
1478         if (!read_line(sti.s, 128, stream, &sti.len)||sti.len==0) {
1479                 LOG(L_ERR, "ERROR: fifo_t_reply: trans_id expected\n");
1480                 fifo_reply(response_file, "400 fifo_t_reply: trans_id expected");
1481                 return -1;
1482         }
1483         sti.s[sti.len]='\0';
1484         DBG("DEBUG: fifo_t_reply: trans_id=%.*s\n",sti.len,sti.s);
1485
1486         if(sscanf(sti.s,"%u:%u", &hash_index, &label) != 2){
1487                 LOG(L_ERR, "ERROR: fifo_t_reply: invalid trans_id (%s)\n",sti.s);
1488                 fifo_reply(response_file, "400 fifo_t_reply: invalid trans_id");
1489                 return -1;
1490         }
1491         DBG("DEBUG: fifo_t_reply: hash_index=%u label=%u\n",hash_index,label);
1492
1493         if( !read_line(sttag.s,64,stream,&sttag.len) || sttag.len==0 ){
1494                 LOG(L_ERR, "ERROR: fifo_t_reply: to-tag expected\n");
1495                 fifo_reply(response_file, "400 fifo_t_reply: to-ta expected");
1496                 return -1;
1497         }
1498         sttag.s[sttag.len]='\0';
1499         DBG("DEBUG: fifo_t_reply: to-tag: %.*s\n",sttag.len,sttag.s);
1500
1501         /* read the new headers */
1502         if (!read_line_set(snh.s, MAX_HEADER, stream, &snh.len)) {
1503                 LOG(L_ERR, "ERROR: fifo_t_reply: while reading new headers\n");
1504                 fifo_reply(response_file, "400 fifo_t_reply: while reading "
1505                         "new headers");
1506                 return -1;
1507         }
1508         snh.s[snh.len]='\0';
1509         DBG("DEBUG: fifo_t_reply: new headers: %.*s\n", snh.len, snh.s);
1510
1511         /*  body can be empty ... */
1512         read_body(sb.s, MAX_BODY, stream, &sb.len);
1513         sb.s[sb.len]='\0';
1514         DBG("DEBUG: fifo_t_reply: body: <%.*s>\n", sb.len, sb.s);
1515
1516         if( t_lookup_ident(&trans,hash_index,label)<0 ) {
1517                 LOG(L_ERR,"ERROR: fifo_t_reply: lookup failed\n");
1518                 fifo_reply(response_file, "481 fifo_t_reply: no such transaction");
1519                 return -1;
1520         }
1521
1522         /* it's refcounted now, t_reply_with body unrefs for me -- I can 
1523          * continue but may not use T anymore  */
1524         ret = t_reply_with_body(trans,icode,reason,body,new_headers,to_tag);
1525
1526         if (ret<0) {
1527                 LOG(L_ERR, "ERROR: fifo_t_reply: reply failed\n");
1528                 fifo_reply(response_file, "500 fifo_t_reply: reply failed");
1529                 return -1;
1530         }
1531
1532         fifo_reply(response_file, "200 fifo_t_reply succeeded\n");
1533         DBG("DEBUG: fifo_t_reply: ################ end ##############\n");
1534         return 1;
1535 }
1536
1537
1538 static int parse_transid(str* s, unsigned int* index, unsigned int* label)
1539 {
1540         char* buf;
1541
1542         if (!s || !index || !label) {
1543                 LOG(L_ERR, "parse_transid: Invalid parameter value\n");
1544                 return -1;
1545         }
1546
1547         buf = (char*)pkg_malloc(s->len + 1);
1548         if (!buf) {
1549                 LOG(L_ERR, "parse_transid: No memory left\n");
1550                 return -1;
1551         }
1552
1553         memcpy(buf, s->s, s->len + 1);
1554         buf[s->len] = '\0';
1555         
1556         if (sscanf(buf, "%u:%u", index, label) != 2) {
1557                 LOG(L_ERR, "parse_transid: Invalid trans_id (%s)\n", buf);
1558                 pkg_free(buf);
1559                 return -1;
1560         }
1561
1562         DBG("parse_transid: hash_index=%u label=%u\n", *index, *label);
1563         pkg_free(buf);
1564         return 0;
1565 }
1566
1567
1568
1569 static int send_reply(struct cell *trans, unsigned int code, str* text, str* body, str* headers, str* to_tag)
1570 {
1571         struct lump_rpl *hdr_lump, *body_lump;
1572         str rpl;
1573         int ret;
1574         struct bookmark bm;
1575
1576              /* mark the transaction as replied */
1577         if (code >= 200) set_kr(REQ_RPLD);
1578
1579              /* add the lumps for new_header and for body (by bogdan) */
1580         if (headers && headers->len) {
1581                 hdr_lump = add_lump_rpl(trans->uas.request, headers->s, headers->len, LUMP_RPL_HDR);
1582                 if (!hdr_lump) {
1583                         LOG(L_ERR, "send_reply: cannot add hdr lump\n");
1584                         goto sr_error;
1585                 }
1586         } else {
1587                 hdr_lump = 0;
1588         }
1589
1590              /* body lump */
1591         if (body && body->len) {
1592                 body_lump = add_lump_rpl(trans->uas.request, body->s, body->len, LUMP_RPL_BODY);
1593                 if (body_lump == 0) {
1594                         LOG(L_ERR,"send_reply: cannot add body lump\n");
1595                         goto sr_error_1;
1596                 }
1597         } else {
1598                 body_lump = 0;
1599         }
1600
1601              /* We can safely zero-terminate the text here, because it is followed
1602               * by next line in the received message
1603               */
1604         text->s[text->len] = '\0';
1605         rpl.s = build_res_buf_from_sip_req(code, text->s, to_tag, trans->uas.request, (unsigned int*)&rpl.len, &bm);
1606
1607              /* since the msg (trans->uas.request) is a clone into shm memory, to avoid
1608               * memory leak or crashing (lumps are create in private memory) I will
1609               * remove the lumps by myself here (bogdan) */
1610         if (hdr_lump) {
1611                 unlink_lump_rpl(trans->uas.request, hdr_lump);
1612                 free_lump_rpl(hdr_lump);
1613         }
1614         if (body_lump) {
1615                 unlink_lump_rpl(trans->uas.request, body_lump);
1616                 free_lump_rpl(body_lump);
1617         }
1618
1619         if (rpl.s == 0) {
1620                 LOG(L_ERR,"send_reply: failed in build_res_buf_from_sip_req\n");
1621                 goto sr_error;
1622         }
1623
1624         ret = _reply_light(trans, rpl.s, rpl.len, code, text->s,  to_tag->s, to_tag->len, 1 /* lock replies */, &bm);
1625              /* this is ugly hack -- the function caller may wish to continue with
1626               * transction and I unref; however, there is now only one use from
1627               * vm/fifo_vm_reply and I'm currently to lazy to export UNREF; -jiri
1628               */
1629         UNREF(trans);
1630         return ret;
1631  sr_error_1:
1632         if (hdr_lump) {
1633                 unlink_lump_rpl(trans->uas.request, hdr_lump);
1634                 free_lump_rpl(hdr_lump);
1635         }
1636  sr_error:
1637         return -1;
1638 }
1639
1640
1641
1642 int unixsock_t_reply(str* msg)
1643 {
1644         int ret;
1645         struct cell *trans;
1646         static char new_headers[MAX_HEADER];
1647         str code, reason, transid, headers, body, to_tag;
1648         unsigned int hash_index, label, icode;
1649
1650         headers.s = new_headers;
1651         headers.len = MAX_HEADER;
1652
1653         if (unixsock_read_line(&code, msg) != 0) {
1654                 unixsock_reply_asciiz("400 Reason code expected\n");
1655                 goto err;
1656         }
1657
1658         icode = str2s(code.s, code.len, &ret);
1659         if (ret) {
1660                 unixsock_reply_printf("400 Reason code has wrong format\n");
1661                 goto err;
1662         }
1663
1664         if (unixsock_read_line(&reason, msg) != 0) {
1665                 unixsock_reply_asciiz("400 Reason phrase expected\n");
1666                 goto err;
1667         }
1668
1669         if (unixsock_read_line(&transid, msg) != 0) {
1670                 unixsock_reply_asciiz("400 Transaction ID expected\n");
1671                 goto err;
1672         }
1673
1674         if (parse_transid(&transid, &hash_index, &label) < 0) {
1675                 unixsock_reply_asciiz("400 Error while parsing transaction ID\n");
1676                 goto err;
1677         }
1678
1679         if (unixsock_read_line(&to_tag, msg) != 0) {
1680                 unixsock_reply_asciiz("400 To tag expected\n");
1681                 goto err;
1682         }
1683
1684              /* read the new headers */
1685         if (unixsock_read_lineset(&headers, msg) < 0) {
1686                 unixsock_reply_asciiz("400 Error while reading new headers\n");
1687                 goto err;
1688         }
1689
1690         DBG("lineset: %.*s\n", headers.len, headers.s);
1691              
1692         /*  body can be empty ... */
1693         if (unixsock_read_body(&body, msg) < 0) {
1694                 unixsock_reply_asciiz("400 Error while reading body\n");
1695                 goto err;
1696         }
1697
1698         DBG("body: %.*s\n", body.len, body.s);
1699         
1700         if (t_lookup_ident(&trans, hash_index, label) < 0) {
1701                 LOG(L_ERR,"unixsock_t_reply: lookup failed\n");
1702                 unixsock_reply_asciiz("481 No such transaction\n");
1703                 goto err;
1704         }
1705
1706              /* it's refcounted now, t_reply_with body unrefs for me -- I can 
1707               * continue but may not use T anymore  
1708               */
1709         ret = send_reply(trans, icode, &reason, &body, &headers, &to_tag);
1710         if (ret < 0) {
1711                 LOG(L_ERR, "unixsock_t_reply: reply failed\n");
1712                 unixsock_reply_asciiz("500 Reply failed\n");
1713                 goto err;
1714         }
1715
1716         unixsock_reply_asciiz("200 Succeeded\n");
1717         unixsock_reply_send();
1718         return 1;
1719
1720  err:
1721         unixsock_reply_send();
1722         return -1;
1723 }