t_reply.c

Go to the documentation of this file.
00001 /*
00002  * $Id: t_reply.c 5826 2009-05-01 11:17:15Z miconda $
00003  *
00004  * Copyright (C) 2001-2003 FhG Fokus
00005  *
00006  * This file is part of Kamailio, a free SIP server.
00007  *
00008  * Kamailio is free software; you can redistribute it and/or modify
00009  * it under the terms of the GNU General Public License as published by
00010  * the Free Software Foundation; either version 2 of the License, or
00011  * (at your option) any later version
00012  *
00013  * Kamailio is distributed in the hope that it will be useful,
00014  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016  * GNU General Public License for more details.
00017  *
00018  * You should have received a copy of the GNU General Public License 
00019  * along with this program; if not, write to the Free Software 
00020  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00021  *
00022  * History:
00023  * --------
00024  *  2003-01-19  faked lump list created in on_reply handlers
00025  *  2003-01-27  next baby-step to removing ZT - PRESERVE_ZT (jiri)
00026  *  2003-02-13  updated to use rb->dst (andrei)
00027  *  2003-02-18  replaced TOTAG_LEN w/ TOTAG_VALUE_LEN (TOTAG_LEN was defined
00028  *               twice with different values!)  (andrei)
00029  *  2003-02-28  scratchpad compatibility abandoned (jiri)
00030  *  2003-03-01  kr set through a function now (jiri)
00031  *  2003-03-06  saving of to-tags for ACK/200 matching introduced, 
00032  *              voicemail changes accepted, updated to new callback
00033  *              names (jiri)
00034  *  2003-03-10  fixed new to tag bug/typo (if w/o {})  (andrei)
00035  *  2003-03-16  removed _TOTAG (jiri)
00036  *  2003-03-31  200 for INVITE/UAS resent even for UDP (jiri)
00037  *  2003-03-31  removed msg->repl_add_rm (andrei)
00038  *  2003-04-05  s/reply_route/failure_route, onreply_route introduced (jiri)
00039  *  2003-04-14  local acks generated before reply processing to avoid
00040  *              delays in length reply processing (like opening TCP
00041  *              connection to an unavailable destination) (jiri)
00042  *  2003-09-11  updates to new build_res_buf_from_sip_req() interface (bogdan)
00043  *  2003-09-11  t_reply_with_body() reshaped to use reply_lumps +
00044  *              build_res_buf_from_sip_req() instead of
00045  *              build_res_buf_with_body_from_sip_req() (bogdan)
00046  *  2003-11-05  flag context updated from failure/reply handlers back
00047  *              to transaction context (jiri)
00048  *  2003-11-11: build_lump_rpl() removed, add_lump_rpl() has flags (bogdan)
00049  *  2003-12-04  global TM callbacks switched to per transaction callbacks
00050  *              (bogdan)
00051  *  2004-02-06: support for user pref. added - destroy_avps (bogdan)
00052  *  2003-11-05  flag context updated from failure/reply handlers back
00053  *              to transaction context (jiri)
00054  *  2003-11-11: build_lump_rpl() removed, add_lump_rpl() has flags (bogdan)
00055  *  2004-02-13: t->is_invite and t->local replaced with flags (bogdan)
00056  *  2004-02-18  fifo_t_reply imported from vm module (bogdan)
00057  *  2004-08-23  avp list is available from failure/on_reply routes (bogdan)
00058  *  2004-10-01  added a new param.: restart_fr_on_each_reply (andrei)
00059  *  2005-03-01  force for statefull replies the incoming interface of 
00060  *              the request (bogdan)
00061  *  2005-03-01  local ACK sent to same address as INVITE ->
00062  *              all [build|send]_[local]_ack functions merged into 
00063  *              send_ack() (bogdan)
00064  *  2007-01-25  DNS failover at transaction level added (bogdan)
00065  */
00066 
00067 /*! \file
00068  * \brief TM :: Reply handling
00069  *
00070  * \ingroup tm
00071  * - Module: \ref tm
00072  */
00073 
00074 #include "../../hash_func.h"
00075 #include "../../dprint.h"
00076 #include "../../config.h"
00077 #include "../../parser/parser_f.h"
00078 #include "../../ut.h"
00079 #include "../../timer.h"
00080 #include "../../error.h"
00081 #include "../../action.h"
00082 #include "../../dset.h"
00083 #include "../../tags.h"
00084 #include "../../data_lump.h"
00085 #include "../../data_lump_rpl.h"
00086 #include "../../usr_avp.h"
00087 
00088 #include "h_table.h"
00089 #include "t_hooks.h"
00090 #include "t_funcs.h"
00091 #include "t_reply.h"
00092 #include "t_cancel.h"
00093 #include "t_msgbuilder.h"
00094 #include "t_lookup.h"
00095 #include "t_fwd.h"
00096 #include "fix_lumps.h"
00097 #include "t_stats.h"
00098 #include "uac.h"
00099 
00100 
00101 /*! restart fr timer on each provisional reply, default yes */
00102 int restart_fr_on_each_reply=1;
00103 int onreply_avp_mode = 0;
00104 /*! drop responses matching no client transaction (draft-sparks-sip-invfix-03) */
00105 int drop_stateless_replies = 0;
00106 
00107 /*! disable the 6xx fork-blocking - default no (as per RFC3261) */
00108 int disable_6xx_block = 0;
00109 
00110 /*! private place where we create to-tags for replies */
00111 char tm_tags[TOTAG_VALUE_LEN];
00112 static str  tm_tag = {tm_tags,TOTAG_VALUE_LEN};
00113 char *tm_tag_suffix;
00114 
00115 static int picked_branch=-1;
00116 
00117 /*! where to go if there is no positive reply */
00118 static int goto_on_negative=0;
00119 /*! where to go on receipt of reply */
00120 static int goto_on_reply=0;
00121 
00122 extern int _tm_branch_index;
00123 
00124 int t_get_reply_totag(struct sip_msg *msg, str *totag)
00125 {
00126    if(msg==NULL || totag==NULL)
00127       return -1;
00128    calc_crc_suffix(msg, tm_tag_suffix);
00129    *totag = tm_tag;
00130    return 1;
00131 }
00132 
00133 /*! \brief returns the picked branch */
00134 int t_get_picked_branch(void)
00135 {
00136    return picked_branch;
00137 }
00138 
00139 
00140 /* we store the reply_route # in private memory which is
00141    then processed during t_relay; we cannot set this value
00142    before t_relay creates transaction context or after
00143    t_relay when a reply may arrive after we set this
00144    value; that's why we do it how we do it, i.e.,
00145    *inside*  t_relay using hints stored in private memory
00146    before t_relay is called
00147 */
00148 
00149 /*!
00150  * \brief Set which 'reply' structure to take if only negative replies arrive
00151  */
00152 void t_on_negative( unsigned int go_to )
00153 {
00154    struct cell *t = get_t();
00155 
00156    /* in MODE_REPLY and MODE_ONFAILURE T will be set to current transaction;
00157     * in MODE_REQUEST T will be set only if the transaction was already 
00158     * created; if not -> use the static variable */
00159    if (!t || t==T_UNDEFINED )
00160       goto_on_negative=go_to;
00161    else
00162       t->on_negative = go_to;
00163 }
00164 
00165 
00166 void t_on_reply( unsigned int go_to )
00167 {
00168    struct cell *t = get_t();
00169 
00170    /* in MODE_REPLY and MODE_ONFAILURE T will be set to current transaction;
00171     * in MODE_REQUEST T will be set only if the transaction was already 
00172     * created; if not -> use the static variable */
00173    if (!t || t==T_UNDEFINED )
00174       goto_on_reply=go_to;
00175    else
00176       t->on_reply = go_to;
00177 }
00178 
00179 
00180 unsigned int get_on_negative(void)
00181 {
00182    return goto_on_negative;
00183 }
00184 unsigned int get_on_reply(void)
00185 {
00186    return goto_on_reply;
00187 }
00188 
00189 void tm_init_tags(void)
00190 {
00191    init_tags(tm_tags, &tm_tag_suffix, 
00192       "Kamailio-TM/tags", TM_TAG_SEPARATOR );
00193 }
00194 
00195 /*!
00196  * \brief Checks if the message was previously acknowledged
00197  * \return 0 if the message was previously acknowledged (i.e., no
00198  * E2EACK callback is needed) and 1 if the callback shall be executed
00199  */
00200 int unmatched_totag(struct cell *t, struct sip_msg *ack)
00201 {
00202    struct totag_elem *i;
00203    str *tag;
00204 
00205    if (parse_headers(ack, HDR_TO_F,0)==-1 || 
00206             !ack->to ) {
00207       LM_ERR("To invalid\n");
00208       return 1;
00209    }
00210    tag=&get_to(ack)->tag_value;
00211    for (i=t->fwded_totags; i; i=i->next) {
00212       if (i->tag.len==tag->len
00213             && memcmp(i->tag.s, tag->s, tag->len)==0) {
00214          LM_DBG("totag for e2e ACK found: %d\n", i->acked);
00215          /* to-tag recorded, and an ACK has been received for it */
00216          if (i->acked) return 0;
00217          /* to-tag recorded, but this ACK came for the first time */
00218          i->acked=1;
00219          return 1;
00220       }
00221    }
00222    /* surprising: to-tag never sighted before */
00223    return 1;
00224 }
00225 
00226 
00227 /*!
00228  * \brief Update local tags in transaction
00229  */
00230 static inline void update_local_tags(struct cell *trans, 
00231             struct bookmark *bm, char *dst_buffer,
00232             char *src_buffer /* to which bm refers */)
00233 {
00234    if (bm->to_tag_val.s) {
00235       trans->uas.local_totag.s=bm->to_tag_val.s-src_buffer+dst_buffer;
00236       trans->uas.local_totag.len=bm->to_tag_val.len;
00237    }
00238 }
00239 
00240 
00241 /*!
00242  * \brief Append a newly received tag from a 200/INVITE to transaction's set
00243  *
00244  * Append a newly received tag from a 200/INVITE to transaction's set,
00245  * (only safe if called from within a REPLY_LOCK).
00246  * \return 1 if such a to tag already exists, 0 on errors and if a new TO tag
00247  * was created
00248  */
00249 inline static int update_totag_set(struct cell *t, struct sip_msg *ok)
00250 {
00251    struct totag_elem *i, *n;
00252    str *tag;
00253    char *s;
00254 
00255    if (!ok->to || !ok->to->parsed) {
00256       LM_ERR("to not parsed\n");
00257       return 0;
00258    }
00259    tag=&get_to(ok)->tag_value;
00260    if (!tag->s) {
00261       LM_DBG("no tag in to\n");
00262       return 0;
00263    }
00264 
00265    for (i=t->fwded_totags; i; i=i->next) {
00266       if (i->tag.len==tag->len
00267             && memcmp(i->tag.s, tag->s, tag->len) ==0 ){
00268          /* to tag already recorded */
00269 #ifdef XL_DEBUG
00270          LM_CRIT("totag retransmission\n");
00271 #else
00272          LM_DBG("totag retransmission\n");
00273 #endif
00274          return 1;
00275       }
00276    }
00277    /* that's a new to-tag -- record it */
00278    shm_lock();
00279    n=(struct totag_elem*) shm_malloc_unsafe(sizeof(struct totag_elem));
00280    s=(char *)shm_malloc_unsafe(tag->len);
00281    shm_unlock();
00282    if (!s || !n) {
00283       LM_ERR("no more share memory \n");
00284       if (n) shm_free(n);
00285       if (s) shm_free(s);
00286       return 0;
00287    }
00288    memset(n, 0, sizeof(struct totag_elem));
00289    memcpy(s, tag->s, tag->len );
00290    n->tag.s=s;n->tag.len=tag->len;
00291    n->next=t->fwded_totags;
00292    t->fwded_totags=n;
00293    LM_DBG("new totag \n");
00294    return 0;
00295 }
00296 
00297 
00298 /*!
00299  * \brief Build and send an ACK to a negative reply
00300  * \return 0 on success, -1 for errors
00301  */
00302 static int send_ack(struct sip_msg* rpl, struct cell *trans, int branch)
00303 {
00304    str to;
00305    char *ack_p;
00306    unsigned int  ack_len;
00307 
00308    if (parse_headers( rpl, is_local(trans)?HDR_EOH_F:HDR_TO_F, 0)==-1
00309    || !rpl->to ) {
00310       LM_ERR("failed to generate a HBH ACK if key HFs in reply missing\n");
00311       goto error;
00312    }
00313    to.s=rpl->to->name.s;
00314    to.len=rpl->to->len;
00315 
00316    ack_p = is_local(trans)?
00317       build_dlg_ack(rpl, trans, branch, &to, &ack_len):
00318       build_local( trans, branch, &ack_len, ACK, ACK_LEN, &to );
00319    if (ack_p==0) {
00320       LM_ERR("failed to build ACK\n");
00321       goto error;
00322    }
00323 
00324    SEND_PR_BUFFER(&trans->uac[branch].request, ack_p, ack_len);
00325    shm_free(ack_p);
00326 
00327    return 0;
00328 error:
00329    return -1;
00330 }
00331 
00332 
00333 static int _reply_light( struct cell *trans, char* buf, unsigned int len,
00334           unsigned int code, char *to_tag, unsigned int to_tag_len,
00335           int lock, struct bookmark *bm)
00336 {
00337    struct retr_buf *rb;
00338    unsigned int buf_len;
00339    branch_bm_t cancel_bitmap;
00340    str cb_s;
00341 
00342    if (!buf)
00343    {
00344       LM_DBG("response building failed\n");
00345       /* determine if there are some branches to be canceled */
00346       if ( is_invite(trans) ) {
00347          if (lock) LOCK_REPLIES( trans );
00348          which_cancel(trans, &cancel_bitmap );
00349          if (lock) UNLOCK_REPLIES( trans );
00350       }
00351       /* and clean-up, including cancellations, if needed */
00352       goto error;
00353    }
00354 
00355    cancel_bitmap=0;
00356    if (lock) LOCK_REPLIES( trans );
00357    if ( is_invite(trans) ) which_cancel(trans, &cancel_bitmap );
00358    if (trans->uas.status>=200) {
00359       LM_ERR("failed to generate %d reply when a final %d was sent out\n",
00360             code, trans->uas.status);
00361       goto error2;
00362    }
00363 
00364 
00365    rb = & trans->uas.response;
00366    rb->activ_type=code;
00367 
00368    trans->uas.status = code;
00369    buf_len = rb->buffer.s ? len : len + REPLY_OVERBUFFER_LEN;
00370    rb->buffer.s = (char*)shm_resize( rb->buffer.s, buf_len );
00371    /* puts the reply's buffer to uas.response */
00372    if (! rb->buffer.s ) {
00373          LM_ERR("failed to allocate shmem buffer\n");
00374          goto error3;
00375    }
00376    update_local_tags(trans, bm, rb->buffer.s, buf);
00377 
00378    rb->buffer.len = len ;
00379    memcpy( rb->buffer.s , buf , len );
00380    /* needs to be protected too because what timers are set depends
00381       on current transactions status */
00382    /* t_update_timers_after_sending_reply( rb ); */
00383    trans->relayed_reply_branch=-2;
00384    if (lock) UNLOCK_REPLIES( trans );
00385    
00386    /* do UAC cleanup procedures in case we generated
00387       a final answer whereas there are pending UACs */
00388    if (code>=200) {
00389       if ( is_local(trans) ) {
00390          LM_DBG("local transaction completed\n");
00391          if ( has_tran_tmcbs(trans, TMCB_LOCAL_COMPLETED) ) {
00392             run_trans_callbacks( TMCB_LOCAL_COMPLETED, trans,
00393                0, FAKED_REPLY, code);
00394          }
00395       } else {
00396          /* run the PRE send callbacks */
00397          if ( has_tran_tmcbs(trans, TMCB_RESPONSE_PRE_OUT) ) {
00398             cb_s.s = buf;
00399             cb_s.len = len;
00400             set_extra_tmcb_params( &cb_s, &rb->dst);
00401             run_trans_callbacks( TMCB_RESPONSE_PRE_OUT, trans,
00402                trans->uas.request, FAKED_REPLY, code);
00403          }
00404       }
00405 
00406       if (!is_hopbyhop_cancel(trans)) {
00407          cleanup_uac_timers( trans );
00408          if (is_invite(trans)) cancel_uacs( trans, cancel_bitmap );
00409          set_final_timer(  trans );
00410       }
00411    }
00412 
00413    /* send it out : response.dst.send_sock is valid all the time now, 
00414     * as it's taken from original request -bogdan */
00415    if (!trans->uas.response.dst.send_sock) {
00416       LM_CRIT("send_sock is NULL\n");
00417    }
00418    SEND_PR_BUFFER( rb, buf, len );
00419    LM_DBG("reply sent out. buf=%p: %.9s..., "
00420       "shmem=%p: %.9s\n", buf, buf, rb->buffer.s, rb->buffer.s );
00421 
00422    /* run the POST send callbacks */
00423    if (code>=200&&!is_local(trans)&&has_tran_tmcbs(trans,TMCB_RESPONSE_OUT)) {
00424       cb_s.s = buf;
00425       cb_s.len = len;
00426       set_extra_tmcb_params( &cb_s, &rb->dst);
00427       run_trans_callbacks( TMCB_RESPONSE_OUT, trans,
00428          trans->uas.request, FAKED_REPLY, code);
00429    }
00430 
00431    pkg_free( buf ) ;
00432    stats_trans_rpl( code, 1 /*local*/ );
00433    LM_DBG("finished\n");
00434    return 1;
00435 
00436 error3:
00437 error2:
00438    if (lock) UNLOCK_REPLIES( trans );
00439    pkg_free ( buf );
00440 error:
00441    /* do UAC cleanup */
00442    cleanup_uac_timers( trans );
00443    if ( is_invite(trans) ) cancel_uacs( trans, cancel_bitmap );
00444    /* we did not succeed -- put the transaction on wait */
00445    put_on_wait(trans);
00446    return -1;
00447 }
00448 
00449 
00450 /*!
00451  * \brief Send a UAS reply
00452  * \return 1 if everything was OK or -1 for errors
00453  */
00454 static int _reply( struct cell *trans, struct sip_msg* p_msg, 
00455                            unsigned int code, str *text, int lock )
00456 {
00457    unsigned int len;
00458    char * buf, *dset;
00459    struct bookmark bm;
00460    int dset_len;
00461 
00462    if (code>=200) set_kr(REQ_RPLD);
00463    /* compute the buffer in private memory prior to entering lock;
00464     * create to-tag if needed */
00465 
00466    /* if that is a redirection message, dump current message set to it */
00467    if (code>=300 && code<400) {
00468       dset=print_dset(p_msg, &dset_len);
00469       if (dset) {
00470          add_lump_rpl(p_msg, dset, dset_len, LUMP_RPL_HDR);
00471       }
00472    }
00473 
00474    if (code>=180 && p_msg->to 
00475             && (get_to(p_msg)->tag_value.s==0 
00476              || get_to(p_msg)->tag_value.len==0)) {
00477       calc_crc_suffix( p_msg, tm_tag_suffix );
00478       buf = build_res_buf_from_sip_req(code,text, &tm_tag, p_msg, &len, &bm);
00479       return _reply_light( trans, buf, len, code,
00480          tm_tag.s, TOTAG_VALUE_LEN, lock, &bm);
00481    } else {
00482       buf = build_res_buf_from_sip_req(code,text, 0 /*no to-tag*/,
00483          p_msg, &len, &bm);
00484 
00485       return _reply_light(trans,buf,len,code, 0, 0 /* no to-tag */,
00486          lock, &bm);
00487    }
00488 }
00489 
00490 
00491 /*!
00492  * \brief Setup or restore a faked environment conforming with the message
00493  *
00494  * If msg is set -> it will fake the envinronmental vars conforming with the
00495  * message, if NULL the environment will be restored to the original
00496  * \param t transaction
00497  * \param msg SIP message or NULL
00498  */
00499 static inline void faked_env( struct cell *t,struct sip_msg *msg)
00500 {
00501    static struct cell *backup_t;
00502    static struct usr_avp **backup_list;
00503    static struct socket_info* backup_si;
00504    static int backup_route_type;
00505 
00506    if (msg) {
00507       swap_route_type( backup_route_type, FAILURE_ROUTE);
00508       /* tm actions look in beginning whether transaction is
00509        * set -- whether we are called from a reply-processing 
00510        * or a timer process, we need to set current transaction;
00511        * otherwise the actions would attempt to look the transaction
00512        * up (unnecessary overhead, refcounting)
00513        */
00514       /* backup */
00515       backup_t = get_t();
00516       /* fake transaction */
00517       set_t(t);
00518       /* make available the avp list from transaction */
00519       backup_list = set_avp_list( &t->user_avps );
00520       /* set default send address to the saved value */
00521       backup_si = bind_address;
00522       bind_address = t->uac[0].request.dst.send_sock;
00523    } else {
00524       /* restore original environment */
00525       set_t(backup_t);
00526       set_route_type( backup_route_type );
00527       /* restore original avp list */
00528       set_avp_list( backup_list );
00529       bind_address = backup_si;
00530    }
00531 }
00532 
00533 
00534 /*!
00535  * \brief Fake a request
00536  * \return 1 on success, 0 on errors
00537  */
00538 static inline int fake_req(struct sip_msg *faked_req, struct sip_msg *shm_msg,
00539       struct ua_server *uas, struct ua_client *uac)
00540 {
00541    /* on_negative_reply faked msg now copied from shmem msg (as opposed
00542     * to zero-ing) -- more "read-only" actions (exec in particular) will
00543     * work from reply_route as they will see msg->from, etc.; caution,
00544     * rw actions may append some pkg stuff to msg, which will possibly be
00545     * never released (shmem is released in a single block) */
00546    memcpy( faked_req, shm_msg, sizeof(struct sip_msg));
00547 
00548    /* if we set msg_id to something different from current's message
00549     * id, the first t_fork will properly clean new branch URIs */
00550    faked_req->id=shm_msg->id-1;
00551 
00552    /* dst_uri can change -- make a private copy */
00553    if (shm_msg->dst_uri.s!=0 && shm_msg->dst_uri.len!=0) {
00554       faked_req->dst_uri.s=pkg_malloc(shm_msg->dst_uri.len+1);
00555       if (!faked_req->dst_uri.s) {
00556          LM_ERR("no dst_uri pkg mem\n");
00557          goto error1;
00558       }
00559       faked_req->dst_uri.len=shm_msg->dst_uri.len;
00560       memcpy( faked_req->dst_uri.s, shm_msg->dst_uri.s,
00561          faked_req->dst_uri.len);
00562       faked_req->dst_uri.s[faked_req->dst_uri.len]=0;
00563    }
00564 
00565    /* msg->parsed_uri_ok must be reset since msg_parsed_uri is
00566     * not cloned (and cannot be cloned) */
00567    faked_req->parsed_uri_ok = 0;
00568 
00569    /* new_uri can change -- make a private copy */
00570    faked_req->new_uri.s=pkg_malloc( uac->uri.len+1 );
00571    if (!faked_req->new_uri.s) {
00572       LM_ERR("no uri/pkg mem\n");
00573       goto error;
00574    }
00575    faked_req->new_uri.len = uac->uri.len;
00576    memcpy( faked_req->new_uri.s, uac->uri.s, uac->uri.len);
00577    faked_req->new_uri.s[faked_req->new_uri.len]=0;
00578    faked_req->parsed_uri_ok = 0;
00579 
00580    /* dst_set is imposible to restore (since it's not saved),
00581     * so let it set to NULL */
00582 
00583    /* set as flags the global flags and the branch flags from the 
00584     * elected branch */
00585    faked_req->flags = uas->request->flags;
00586    setb0flags( uac->br_flags);
00587 
00588    return 1;
00589 
00590 error1:
00591    if (faked_req->dst_uri.s!=0 && faked_req->dst_uri.len!=0)
00592       pkg_free(faked_req->dst_uri.s);
00593 
00594 error:
00595    return 0;
00596 }
00597 
00598 
00599 /*!
00600  * \brief Free faked requests
00601  * \param faked_req SIP message with faked request
00602  * \param t transaction
00603  */
00604 inline static void free_faked_req(struct sip_msg *faked_req, struct cell *t)
00605 {
00606    if (faked_req->new_uri.s) {
00607       pkg_free(faked_req->new_uri.s);
00608       faked_req->new_uri.s = 0;
00609    }
00610    if (faked_req->dst_uri.s) {
00611       pkg_free(faked_req->dst_uri.s);
00612       faked_req->dst_uri.s = 0;
00613    }
00614 
00615    /* free all types of lump that were added in failure handlers */
00616    del_notflaged_lumps( &(faked_req->add_rm), LUMPFLAG_SHMEM );
00617    del_notflaged_lumps( &(faked_req->body_lumps), LUMPFLAG_SHMEM );
00618    del_nonshm_lump_rpl( &(faked_req->reply_lump) );
00619 
00620    clean_msg_clone( faked_req, t->uas.request, t->uas.end_request);
00621 }
00622 
00623 
00624 /*!
00625  * \brief Run failure handlers
00626  * \return 1 if a failure_route processes, 0 otherwise
00627  */
00628 static inline int run_failure_handlers(struct cell *t)
00629 {
00630    static struct sip_msg faked_req;
00631    struct sip_msg *shmem_msg;
00632    struct ua_client *uac;
00633    int on_failure;
00634 
00635    shmem_msg = t->uas.request;
00636    uac = &t->uac[picked_branch];
00637 
00638    /* failure_route for a local UAC? */
00639    if (!shmem_msg || REQ_LINE(shmem_msg).method_value==METHOD_CANCEL ) {
00640       LM_WARN("no UAC or CANCEL support (%d, %d) \n",
00641             t->on_negative, t->tmcb_hl.reg_types);
00642       return 0;
00643    }
00644 
00645    /* don't start faking anything if we don't have to */
00646    if ( !has_tran_tmcbs( t, TMCB_ON_FAILURE) && !t->on_negative ) {
00647       LM_WARN("no negative handler (%d, %d)\n",t->on_negative, 
00648          t->tmcb_hl.reg_types);
00649       return 1;
00650    }
00651 
00652    if (!fake_req(&faked_req, shmem_msg, &t->uas, uac)) {
00653       LM_ERR("fake_req failed\n");
00654       return 0;
00655    }
00656    /* fake also the env. conforming to the fake msg */
00657    faked_env( t, &faked_req);
00658 
00659    /* DONE with faking ;-) -> run the failure handlers */
00660    if ( has_tran_tmcbs( t, TMCB_ON_FAILURE) ) {
00661       run_trans_callbacks( TMCB_ON_FAILURE, t, &faked_req,
00662             uac->reply, uac->last_received);
00663    }
00664    if (t->on_negative) {
00665       /* avoid recursion -- if failure_route forwards, and does not 
00666        * set next failure route, failure_route will not be reentered
00667        * on failure */
00668       on_failure = t->on_negative;
00669       t->on_negative=0;
00670       /* run a reply_route action if some was marked */
00671       run_top_route(failure_rlist[on_failure], &faked_req);
00672       check_hdrs_changes(&faked_req);
00673       shmem_msg->msg_flags |= faked_req.msg_flags;
00674    }
00675 
00676    /* restore original environment and free the fake msg */
00677    faked_env( t, 0);
00678    free_faked_req(&faked_req,t);
00679 
00680    /* if failure handler changed flag, update transaction context */
00681    shmem_msg->flags = faked_req.flags;
00682    /* branch flags do not need to be updated as this branch will be never
00683     * used again */
00684    return 1;
00685 }
00686 
00687 
00688 /*!
00689  * \brief Test for DNS failover according RFC 3363 and 3261
00690  *
00691  * Test for DNS failover, according to RFC 3263 and RFC 3261, this means
00692  * a 503 reply with Retr-After header or timeout with no reply.
00693  * \param t transaction
00694  * \return 1 if this is a RFC 3263 failure, 0 otherwise
00695  */
00696 static inline int is_3263_failure(struct cell *t)
00697 {
00698    struct hdr_field *hdr; 
00699    LM_DBG("dns-failover test: branch=%d, last_recv=%d, flags=%X\n",
00700       picked_branch, t->uac[picked_branch].last_received,
00701       t->uac[picked_branch].flags);
00702 
00703    switch (t->uac[picked_branch].last_received) {
00704       case 408:
00705          return ((t->uac[picked_branch].flags&T_UAC_HAS_RECV_REPLY)==0);
00706       case 503:
00707          if (t->uac[picked_branch].reply==NULL ||
00708          t->uac[picked_branch].reply==FAKED_REPLY)
00709             return 0;
00710          /* is the Retry-After header present (if present,
00711           * it should be already parsed) */
00712          hdr = t->uac[picked_branch].reply->headers;
00713          for( ; hdr ; hdr=hdr->next)
00714             if (hdr->type==HDR_RETRY_AFTER_T)
00715                return 1;
00716          return 0;
00717    }
00718    return 0;
00719 }
00720 
00721 
00722 /*!
00723  * \brief Do DNS failover
00724  * \return 0 on success, -1 on failures
00725  */
00726 static inline int do_dns_failover(struct cell *t)
00727 {
00728    static struct sip_msg faked_req;
00729    struct sip_msg *shmem_msg;
00730    struct ua_client *uac;
00731    int ret;
00732 
00733    shmem_msg = t->uas.request;
00734    uac = &t->uac[picked_branch];
00735 
00736    /* check if the DNS resolver can get at least one new IP */
00737    if ( get_next_su( uac->proxy, &uac->request.dst.to, 1)!=0 )
00738       return -1;
00739 
00740    LM_DBG("new destination available\n");
00741 
00742    if (!fake_req(&faked_req, shmem_msg, &t->uas, uac)) {
00743       LM_ERR("fake_req failed\n");
00744       return -1;
00745    }
00746    /* fake also the env. conforming to the fake msg */
00747    faked_env( t, &faked_req);
00748    ret = -1;
00749 
00750    if (append_branch( &faked_req, &uac->uri, 0, 0, 0, uac->br_flags,
00751    shmem_msg->force_send_socket)!=1 )
00752       goto done;
00753 
00754    if (t_forward_nonack( t, &faked_req, uac->proxy)==1)
00755       ret = 0;
00756 
00757 done:
00758    /* restore original environment and free the fake msg */
00759    faked_env( t, 0);
00760    free_faked_req(&faked_req,t);
00761    return ret;
00762 }
00763 
00764 
00765 /*!
00766  * \brief Select a branch for forwarding
00767  * \return 0..X ... branch number, -1 for errors, -2 can't decide yet
00768  * -- incomplete branches present
00769  */
00770 static inline int t_pick_branch( struct cell *t, int *res_code)
00771 {
00772    int lowest_b, lowest_s, b, cancelled;
00773 
00774    lowest_b=-1; lowest_s=999;
00775    cancelled = was_cancelled(t);
00776    for ( b=t->first_branch; b<t->nr_of_outgoings ; b++ ) {
00777       /* skip 'empty branches' */
00778       if (!t->uac[b].request.buffer.s) continue;
00779       /* there is still an unfinished UAC transaction; wait now! */
00780       if ( t->uac[b].last_received<200 ) 
00781          return -2;
00782       /* replys to cancel has max priority
00783        * 503 has minimum priority */
00784       if ( (lowest_b==-1) ||
00785       (cancelled && t->uac[b].last_received==487) ||
00786       ( (lowest_s!=487 || !cancelled) && (
00787          (lowest_s==503) || (t->uac[b].last_received!=503
00788          && t->uac[b].last_received<lowest_s)
00789       ))) {
00790          lowest_b =b;
00791          lowest_s = t->uac[b].last_received;
00792       }
00793    } /* find lowest branch */
00794    LM_DBG("picked branch %d, code %d\n",lowest_b,lowest_s);
00795 
00796    *res_code=lowest_s;
00797    return lowest_b;
00798 }
00799 
00800 
00801 /*!
00802  * \brief Decide about reply processing and resulting transaction state
00803  *
00804  * Decide about reply processing and resulting transaction state.
00805  * This is the neurological point of reply processing -- called
00806  * from within a REPLY_LOCK, t_should_relay_response decides
00807  * how a reply shall be processed and how transaction state is
00808  * affected. Checks if the new reply (with new_code status) should be sent
00809  * or not based on the current transaction status.
00810  * \return the branch number (0,1,...) which should be relayed, -1 if nothing to be relayed
00811  */
00812 static enum rps t_should_relay_response( struct cell *Trans , int new_code,
00813    int branch , int *should_store, int *should_relay,
00814    branch_bm_t *cancel_bitmap, struct sip_msg *reply )
00815 {
00816    int branch_cnt, picked_code, inv_through;
00817 
00818    /* note: this code never lets replies to CANCEL go through;
00819       we generate always a local 200 for CANCEL; 200s are
00820       not relayed because it's not an INVITE transaction;
00821       >= 300 are not relayed because 200 was already sent
00822       out
00823    */
00824    LM_DBG("T_code=%d, new_code=%d\n", Trans->uas.status,new_code);
00825    inv_through=new_code>=200 && new_code<300 && is_invite(Trans);
00826    /* if final response sent out, allow only INVITE 2xx  */
00827    if ( Trans->uas.status >= 200 ) {
00828       if (inv_through) {
00829          LM_DBG("200 OK for INVITE after final sent\n");
00830          *should_store=0;
00831          Trans->uac[branch].last_received=new_code;
00832          *should_relay=branch;
00833          return RPS_PUSHED_AFTER_COMPLETION;
00834       } 
00835       if ( is_hopbyhop_cancel(Trans) && new_code>=200) {
00836          *should_store=0;
00837          *should_relay=-1;
00838          picked_branch=-1;
00839          return RPS_COMPLETED;
00840       }
00841       /* except the exception above, too late  messages will
00842          be discarded */
00843       goto discard;
00844    } 
00845 
00846    /* if final response received at this branch, allow only INVITE 2xx */
00847    if (Trans->uac[branch].last_received>=200
00848          && !(inv_through && Trans->uac[branch].last_received<300)) {
00849 #ifdef EXTRA_DEBUG
00850       /* don't report on retransmissions */
00851       if (Trans->uac[branch].last_received==new_code) {
00852          LM_DBG("final reply retransmission\n");
00853       } else
00854       /* if you FR-timed-out, faked a local 408 and 487 came, don't
00855        * report on it either */
00856       if (Trans->uac[branch].last_received==408 && new_code==487) {
00857          LM_DBG("487 reply came for a timed-out branch\n");
00858       } else {
00859       /* this looks however how a very strange status rewrite attempt;
00860        * report on it */
00861          LM_DBG("status rewrite by UAS: stored: %d, received: %d\n",
00862             Trans->uac[branch].last_received, new_code );
00863       }
00864 #endif
00865       goto discard;
00866    }
00867 
00868    /* no final response sent yet */
00869    /* negative replies subject to fork picking */
00870    if (new_code >=300 ) {
00871 
00872       Trans->uac[branch].last_received=new_code;
00873       /* also append the current reply to the transaction to 
00874        * make it available in failure routes - a kind of "fake"
00875        * save of the final reply per branch */
00876       Trans->uac[branch].reply = reply;
00877 
00878       if (new_code>=600 && !disable_6xx_block) {
00879          /* this is a winner and close all branches */
00880          which_cancel( Trans, cancel_bitmap );
00881          picked_branch=branch;
00882          /* no more new branches should be added to this transaction */
00883          Trans->flags |= T_NO_NEW_BRANCHES_FLAG;
00884       } else {
00885          /* if all_final return lowest */
00886          picked_branch = t_pick_branch( Trans, &picked_code);
00887          if (picked_branch==-2) { /* branches open yet */
00888             *should_store=1;
00889             *should_relay=-1;
00890             picked_branch=-1;
00891             Trans->uac[branch].reply = 0;
00892             return RPS_STORE;
00893          }
00894          if (picked_branch==-1) {
00895             LM_CRIT("pick_branch failed (lowest==-1) for code %d\n",new_code);
00896             Trans->uac[branch].reply = 0;
00897             goto discard;
00898          }
00899       }
00900 
00901       /* no more pending branches -- try if that changes after
00902        * a callback; save branch count to be able to determine
00903        * later if new branches were initiated */
00904       branch_cnt=Trans->nr_of_outgoings;
00905 
00906       if ( !(Trans->flags&T_NO_DNS_FAILOVER_FLAG) &&
00907       Trans->uac[picked_branch].proxy!=NULL ) {
00908          /* is is a DNS failover scenario, according to RFC 3263 ? */
00909          if (is_3263_failure(Trans)) {
00910             LM_DBG("trying DNS-based failover\n");
00911             /* do DNS failover -> add new branches */
00912             if (do_dns_failover( Trans )!=0) {
00913                /* skip the failed added branches */
00914                branch_cnt = Trans->nr_of_outgoings;
00915             }
00916          }
00917       }
00918 
00919       /* run ON_FAILURE handlers ( route and callbacks) */
00920       if ( branch_cnt==Trans->nr_of_outgoings &&
00921       (has_tran_tmcbs( Trans, TMCB_ON_FAILURE) || Trans->on_negative) ) {
00922          run_failure_handlers( Trans );
00923       }
00924 
00925       /* now reset it; after the failure logic, the reply may
00926        * not be stored any more and we don't want to keep into
00927        * transaction some broken reference */
00928       Trans->uac[branch].reply = 0;
00929 
00930       /* look if the callback perhaps replied transaction; it also
00931          covers the case in which a transaction is replied localy
00932          on CANCEL -- then it would make no sense to proceed to
00933          new branches bellow
00934       */
00935       if (Trans->uas.status >= 200) {
00936          *should_store=0;
00937          *should_relay=-1;
00938          /* this might deserve an improvement -- if something
00939             was already replied, it was put on wait and then,
00940             returning RPS_COMPLETED will make t_on_reply
00941             put it on wait again; perhaps splitting put_on_wait
00942             from send_reply or a new RPS_ code would be healthy
00943          */
00944          picked_branch=-1;
00945          return RPS_COMPLETED;
00946       }
00947       /* look if the callback/failure_route introduced new branches ... */
00948       if (branch_cnt<Trans->nr_of_outgoings)  {
00949          /* await then result of new branches */
00950          *should_store=1;
00951          *should_relay=-1;
00952          picked_branch=-1;
00953          return RPS_STORE;
00954       }
00955 
00956       /* really no more pending branches -- return selected code */
00957       *should_store=0;
00958       *should_relay=picked_branch;
00959       picked_branch=-1;
00960       return RPS_COMPLETED;
00961    } 
00962 
00963    /* not >=300 ... it must be 2xx or provisional 1xx */
00964    if (new_code>=100) {
00965       /* 1xx and 2xx except 100 will be relayed */
00966       Trans->uac[branch].last_received=new_code;
00967       *should_store=0;
00968       *should_relay= new_code==100? -1 : branch;
00969       if (new_code>=200 ) {
00970          which_cancel( Trans, cancel_bitmap );
00971          return RPS_COMPLETED;
00972       } else return RPS_PROVISIONAL;
00973    }
00974 
00975 discard:
00976    *should_store=0;
00977    *should_relay=-1;
00978    return RPS_DISCARDED;
00979 }
00980 
00981 /*!
00982  * \brief Retransmits the last sent inbound reply
00983  * \param t request for which I want to retransmit an associated reply
00984  * \return 1 on succes, -1 on errors
00985  */
00986 int t_retransmit_reply( struct cell *t )
00987 {
00988    static char b[BUF_SIZE];
00989    int len;
00990 
00991    /* we need to lock the transaction as messages from
00992       upstream may change it continuously */
00993    LOCK_REPLIES( t );
00994 
00995    if (!t->uas.response.buffer.s) {
00996       LM_DBG("nothing to retransmit\n");
00997       goto error;
00998    }
00999 
01000    /* response.dst.send_sock should be valid all the time now, as it's taken
01001       from original request -bogdan */
01002    if (t->uas.response.dst.send_sock==0) {
01003       LM_CRIT("something to retransmit, but send_sock is NULL\n");
01004       goto error;
01005    }
01006 
01007    len=t->uas.response.buffer.len;
01008    if ( len==0 || len>BUF_SIZE )  {
01009       LM_DBG("zero length or too big to retransmit: %d\n", len);
01010       goto error;
01011    }
01012    memcpy( b, t->uas.response.buffer.s, len );
01013    UNLOCK_REPLIES( t );
01014    SEND_PR_BUFFER( & t->uas.response, b, len );
01015    LM_DBG("buf=%p: %.9s..., shmem=%p: %.9s\n",b, b, t->uas.response.buffer.s,
01016          t->uas.response.buffer.s );
01017    return 1;
01018 
01019 error:
01020    UNLOCK_REPLIES(t);
01021    return -1;
01022 }
01023 
01024 
01025 
01026 /*!
01027  * \brief Small wrapper around _reply with locking
01028  */
01029 int t_reply( struct cell *t, struct sip_msg* p_msg, unsigned int code, 
01030    str * text )
01031 {
01032    return _reply( t, p_msg, code, text, 1 /* lock replies */ );
01033 }
01034 
01035 
01036 /*!
01037  * \brief Small wrapper around _reply without locking
01038  */
01039 int t_reply_unsafe( struct cell *t, struct sip_msg* p_msg, unsigned int code, 
01040    str * text )
01041 {
01042    return _reply( t, p_msg, code, text, 0 /* don't lock replies */ );
01043 }
01044 
01045 
01046 /*!
01047  * \brief Set final timer on a transaction
01048  */
01049 void set_final_timer(struct cell *t )
01050 {
01051    if ( !is_local(t) && t->uas.request->REQ_METHOD==METHOD_INVITE ) {
01052       /* crank timers for negative replies */
01053       if (t->uas.status>=300) {
01054          start_retr(&t->uas.response);
01055          return;
01056       }
01057       /* local UAS retransmits too */
01058       if (t->relayed_reply_branch==-2 && t->uas.status>=200) {
01059          /* we retransmit 200/INVs regardless of transport --
01060             even if TCP used, UDP could be used upstream and
01061             loose the 200, which is not retransmitted by proxies
01062          */
01063          force_retr( &t->uas.response );
01064          return;
01065       }
01066    } 
01067    put_on_wait(t);
01068 }
01069 
01070 /*!
01071  * \brief Cleanup UAC timers on a transaction
01072  */
01073 void cleanup_uac_timers( struct cell *t )
01074 {
01075    int i;
01076 
01077    /* reset FR/retransmission timers */
01078    for (i=t->first_branch; i<t->nr_of_outgoings; i++ )  {
01079       reset_timer( &t->uac[i].request.retr_timer );
01080       reset_timer( &t->uac[i].request.fr_timer );
01081    }
01082    LM_DBG("RETR/FR timers reset\n");
01083 }
01084 
01085 
01086 static int store_reply( struct cell *trans, int branch, struct sip_msg *rpl)
01087 {
01088 #     ifdef EXTRA_DEBUG
01089       if (trans->uac[branch].reply) {
01090          LM_ERR("replacing stored reply; aborting\n");
01091          abort();
01092       }
01093 #     endif
01094 
01095       /* when we later do things such as challenge aggregation,
01096             we should parse the message here before we conserve
01097          it in shared memory; -jiri
01098       */
01099       if (rpl==FAKED_REPLY)
01100          trans->uac[branch].reply=FAKED_REPLY;
01101       else
01102          trans->uac[branch].reply = sip_msg_cloner( rpl, 0 );
01103 
01104       if (! trans->uac[branch].reply ) {
01105          LM_ERR("failed to alloc' clone memory\n");
01106          return 0;
01107       }
01108 
01109       return 1;
01110 }
01111 
01112 
01113 /*!
01114  *\brief Decide what and when shall be relayed upstream
01115  *
01116  * This is the code which decides what and when shall be relayed upstream.
01117  * \note It assumes it is entered locked with REPLY_LOCK and it returns unlocked!
01118  * \return reply reason
01119  */
01120 enum rps relay_reply( struct cell *t, struct sip_msg *p_msg, int branch, 
01121    unsigned int msg_status, branch_bm_t *cancel_bitmap )
01122 {
01123    int relay, save_clone, relayed_code, totag_retr;
01124    char *buf;
01125    /* length of outbound reply */
01126    unsigned int res_len;
01127    struct sip_msg *relayed_msg;
01128    struct bookmark bm;
01129    enum rps reply_status;
01130    /* retransmission structure of outbound reply and request */
01131    struct retr_buf *uas_rb;
01132    str cb_s, text;
01133 
01134    relayed_code = totag_retr = 0;
01135    buf = NULL;
01136    res_len = 0;
01137    relayed_msg = NULL;
01138 
01139    /* remember, what was sent upstream to know whether we are
01140     * forwarding a first final reply or not */
01141 
01142    /* *** store and relay message as needed *** */
01143    reply_status = t_should_relay_response(t, msg_status, branch, 
01144       &save_clone, &relay, cancel_bitmap, p_msg );
01145    LM_DBG("branch=%d, save=%d, relay=%d\n",
01146       branch, save_clone, relay );
01147 
01148    /* store the message if needed */
01149    if (save_clone) /* save for later use, typically branch picking */
01150    {
01151       if (!store_reply( t, branch, p_msg ))
01152          goto error01;
01153    }
01154 
01155    uas_rb = & t->uas.response;
01156    if (relay >= 0 ) {
01157       /* initialize sockets for outbound reply */
01158       uas_rb->activ_type=msg_status;
01159       /* only messages known to be relayed immediately will be
01160        * be called on; we do not evoke this callback on messages
01161        * stored in shmem -- they are fixed and one cannot change them
01162        * anyway */
01163       if (msg_status<300 && branch==relay
01164       && has_tran_tmcbs(t,TMCB_RESPONSE_FWDED) ) {
01165          run_trans_callbacks( TMCB_RESPONSE_FWDED, t, t->uas.request,
01166             p_msg, msg_status );
01167       }
01168       /* try building the outbound reply from either the current
01169        * or a stored message */
01170       relayed_msg = branch==relay ? p_msg :  t->uac[relay].reply;
01171       if (relayed_msg==FAKED_REPLY) {
01172          relayed_code = branch==relay
01173             ? msg_status : t->uac[relay].last_received;
01174 
01175          text.s = error_text(relayed_code);
01176          text.len = strlen(text.s); /* FIXME - bogdan*/
01177 
01178          if (relayed_code>=180 && t->uas.request->to 
01179                && (get_to(t->uas.request)->tag_value.s==0 
01180                || get_to(t->uas.request)->tag_value.len==0)) {
01181             calc_crc_suffix( t->uas.request, tm_tag_suffix );
01182             buf = build_res_buf_from_sip_req(
01183                   relayed_code,
01184                   &text,
01185                   &tm_tag,
01186                   t->uas.request, &res_len, &bm );
01187          } else {
01188             buf = build_res_buf_from_sip_req( relayed_code,
01189                &text, 0/* no to-tag */,
01190                t->uas.request, &res_len, &bm );
01191          }
01192 
01193       } else {
01194          relayed_code=relayed_msg->REPLY_STATUS;
01195          buf = build_res_buf_from_sip_res( relayed_msg, &res_len );
01196          /* if we build a message from shmem, we need to remove
01197             via delete lumps which are now stirred in the shmem-ed
01198             structure
01199          */
01200          if (branch!=relay) {
01201             free_via_clen_lump(&relayed_msg->add_rm);
01202          }
01203       }
01204       if (!buf) {
01205          LM_ERR("no mem for outbound reply buffer\n");
01206          goto error02;
01207       }
01208 
01209       /* attempt to copy the message to UAS's shmem:
01210          - copy to-tag for ACK matching as well
01211          -  allocate little a bit more for provisional as
01212             larger messages are likely to follow and we will be 
01213             able to reuse the memory frag 
01214       */
01215       uas_rb->buffer.s = (char*)shm_resize( uas_rb->buffer.s, res_len +
01216          (msg_status<200 ?  REPLY_OVERBUFFER_LEN : 0));
01217       if (!uas_rb->buffer.s) {
01218          LM_ERR("no more share memory\n");
01219          goto error03;
01220       }
01221       uas_rb->buffer.len = res_len;
01222       memcpy( uas_rb->buffer.s, buf, res_len );
01223       if (relayed_msg==FAKED_REPLY) { /* to-tags for local replies */
01224          update_local_tags(t, &bm, uas_rb->buffer.s, buf);
01225       }
01226       stats_trans_rpl( relayed_code, (relayed_msg==FAKED_REPLY)?1:0 );
01227 
01228       /* update the status ... */
01229       t->uas.status = relayed_code;
01230       t->relayed_reply_branch = relay;
01231 
01232       if (is_invite(t) && relayed_msg!=FAKED_REPLY
01233       && relayed_code>=200 && relayed_code < 300
01234       && has_tran_tmcbs( t,
01235          TMCB_RESPONSE_PRE_OUT|TMCB_RESPONSE_OUT|TMCB_E2EACK_IN) ) {
01236          totag_retr=update_totag_set(t, relayed_msg);
01237       }
01238    }; /* if relay ... */
01239 
01240    UNLOCK_REPLIES( t );
01241 
01242    /* Setup retransmission timer _before_ the reply is sent
01243     * to avoid race conditions
01244     */
01245    if (reply_status == RPS_COMPLETED) {
01246       set_final_timer(t);
01247    }
01248 
01249    /* send it now (from the private buffer) */
01250    if (relay >= 0) {
01251       /* run the PRE sending out callback */
01252       if (!totag_retr && has_tran_tmcbs(t, TMCB_RESPONSE_PRE_OUT) ) {
01253          cb_s.s = buf;
01254          cb_s.len = res_len;
01255          set_extra_tmcb_params( &cb_s, &uas_rb->dst);
01256          run_trans_callbacks( TMCB_RESPONSE_PRE_OUT, t, t->uas.request,
01257             relayed_msg, relayed_code);
01258       }
01259       SEND_PR_BUFFER( uas_rb, buf, res_len );
01260       LM_DBG("sent buf=%p: %.9s..., shmem=%p: %.9s\n", 
01261          buf, buf, uas_rb->buffer.s, uas_rb->buffer.s );
01262       /* run the POST sending out callback */
01263       if (!totag_retr && has_tran_tmcbs(t, TMCB_RESPONSE_OUT) ) {
01264          cb_s.s = buf;
01265          cb_s.len = res_len;
01266          set_extra_tmcb_params( &cb_s, &uas_rb->dst);
01267          run_trans_callbacks( TMCB_RESPONSE_OUT, t, t->uas.request,
01268             relayed_msg, relayed_code);
01269       }
01270       pkg_free( buf );
01271    }
01272 
01273    /* success */
01274    return reply_status;
01275 
01276 error03:
01277    pkg_free( buf );
01278 error02:
01279    if (save_clone) {
01280       if (t->uac[branch].reply!=FAKED_REPLY)
01281          sip_msg_free( t->uac[branch].reply );
01282       t->uac[branch].reply = NULL;
01283    }
01284 error01:
01285    text.s = "Reply processing error";
01286    text.len = sizeof("Reply processing error")-1;
01287    t_reply_unsafe( t, t->uas.request, 500, &text );
01288    UNLOCK_REPLIES(t);
01289    if (is_invite(t)) cancel_uacs( t, *cancel_bitmap );
01290    /* a serious error occurred -- attempt to send an error reply;
01291       it will take care of clean-ups  */
01292 
01293    /* failure */
01294    return RPS_ERROR;
01295 }
01296 
01297 
01298 /*!
01299  * \brief "UAC" above transaction layer
01300  *
01301  * This is the "UAC" above transaction layer; if a final reply
01302  * is received, it triggers a callback.
01303  * \note It assumes it is entered locked with REPLY_LOCK and it returns unlocked!
01304  * \return reply_status
01305  */
01306 enum rps local_reply( struct cell *t, struct sip_msg *p_msg, int branch, 
01307    unsigned int msg_status, branch_bm_t *cancel_bitmap)
01308 {
01309    /* how to deal with replies for local transaction */
01310    int local_store, local_winner, winning_code, totag_retr;
01311    enum rps reply_status;
01312    struct sip_msg *winning_msg;
01313 
01314    winning_code = totag_retr=0;
01315    winning_msg=0;
01316 
01317    *cancel_bitmap=0;
01318 
01319    reply_status=t_should_relay_response( t, msg_status, branch,
01320       &local_store, &local_winner, cancel_bitmap, p_msg );
01321    LM_DBG("branch=%d, save=%d, winner=%d\n",
01322       branch, local_store, local_winner );
01323    if (local_store) {
01324       if (!store_reply(t, branch, p_msg))
01325          goto error;
01326    }
01327    if (local_winner>=0) {
01328       winning_msg= branch==local_winner 
01329          ? p_msg :  t->uac[local_winner].reply;
01330       if (winning_msg==FAKED_REPLY) {
01331          winning_code = branch==local_winner
01332             ? msg_status : t->uac[local_winner].last_received;
01333       } else {
01334          winning_code=winning_msg->REPLY_STATUS;
01335       }
01336       t->uas.status = winning_code;
01337       stats_trans_rpl( winning_code, (winning_msg==FAKED_REPLY)?1:0 );
01338       if (is_invite(t) && winning_msg!=FAKED_REPLY
01339       && winning_code>=200 && winning_code <300
01340       && has_tran_tmcbs(t,
01341          TMCB_RESPONSE_PRE_OUT|TMCB_RESPONSE_OUT|TMCB_E2EACK_IN) )  {
01342          totag_retr=update_totag_set(t, winning_msg);
01343       }
01344    }
01345    UNLOCK_REPLIES(t);
01346 
01347    if ( local_winner >= 0 ) {
01348       if (winning_code < 200) {
01349          if (!totag_retr && has_tran_tmcbs(t,TMCB_LOCAL_RESPONSE_OUT)) {
01350             LM_DBG("Passing provisional reply %d to FIFO application\n",
01351                   winning_code);
01352             run_trans_callbacks( TMCB_LOCAL_RESPONSE_OUT, t, 0,
01353                winning_msg, winning_code);
01354          }
01355       } else {
01356          LM_DBG("local transaction completed\n");
01357          if (!totag_retr && has_tran_tmcbs(t,TMCB_LOCAL_COMPLETED) ) {
01358             run_trans_callbacks( TMCB_LOCAL_COMPLETED, t, 0,
01359                winning_msg, winning_code );
01360          }
01361       }
01362    }
01363    return reply_status;
01364 
01365 error:
01366    which_cancel(t, cancel_bitmap);
01367    UNLOCK_REPLIES(t);
01368    cleanup_uac_timers(t);
01369    if ( get_cseq(p_msg)->method_id==METHOD_INVITE )
01370       cancel_uacs( t, *cancel_bitmap );
01371    put_on_wait(t);
01372    return RPS_ERROR;
01373 }
01374 
01375 
01376 /*!
01377  * \brief Called whenever a reply for our module is received
01378  *
01379  * This function is called whenever a reply for our module is received,
01380  * we need to register this function on module initialization.
01381  * \param p_msg SIP message
01382  * \return 0 - core router stops, 1 - core router relay statelessly
01383  */
01384 int reply_received( struct sip_msg  *p_msg )
01385 {
01386    int msg_status, last_uac_status, branch, reply_status;
01387    utime_t timer;
01388    /* has the transaction completed now and we need to clean-up? */
01389    branch_bm_t cancel_bitmap;
01390    struct ua_client *uac;
01391    struct cell *t;
01392    struct usr_avp **backup_list;
01393    unsigned int reply_route;
01394 
01395    /* make sure we know the associated transaction ... */
01396    branch=-1;
01397    if (t_check(p_msg, &branch ) == -1) goto not_found;
01398 
01399    /*... if there is none, tell the core router to fwd statelessly */
01400    t = get_t();
01401    if ((t == 0) || (t == T_UNDEFINED)) goto not_found;
01402 
01403    if(branch==-1) {
01404       if(p_msg->branch_index==0) goto not_found;
01405       else branch = p_msg->branch_index-1;
01406    }
01407 
01408    _tm_branch_index = branch;
01409    cancel_bitmap=0;
01410    msg_status=p_msg->REPLY_STATUS;
01411 
01412    uac=&t->uac[branch];
01413    LM_DBG("org. status uas=%d, uac[%d]=%d local=%d is_invite=%d)\n",
01414       t->uas.status, branch, uac->last_received, 
01415       is_local(t), is_invite(t));
01416    last_uac_status=uac->last_received;
01417    if_update_stat( tm_enable_stats, tm_rcv_rpls , 1);
01418 
01419    /* it's a cancel which is not e2e ? */
01420    if ( get_cseq(p_msg)->method_id==METHOD_CANCEL && is_invite(t) ) {
01421       /* ... then just stop timers */
01422       reset_timer( &uac->local_cancel.retr_timer);
01423       if ( msg_status >= 200 ) {
01424             reset_timer( &uac->local_cancel.fr_timer);
01425       }
01426       LM_DBG("reply to local CANCEL processed\n");
01427       goto done;
01428    }
01429 
01430    /* *** stop timers *** */
01431    /* stop retransmission */
01432    reset_timer(&uac->request.retr_timer);
01433 
01434    /* stop final response timer only if I got a final response */
01435    if ( msg_status >= 200 ) {
01436       reset_timer( &uac->request.fr_timer);
01437    }
01438 
01439    /* acknowledge negative INVITE replies (do it before detailed
01440     * on_reply processing, which may take very long, like if it
01441     * is attempted to establish a TCP connection to a fail-over dst */
01442    if (is_invite(t) && ((msg_status >= 300) ||
01443    (is_local(t) && !no_autoack(t) && msg_status >= 200) )) {
01444       if (send_ack(p_msg, t, branch)!=0)
01445          LM_ERR("failed to send ACK (local=%s)\n", is_local(t)?"yes":"no");
01446    }
01447 
01448    /* if it is an 503, parse the RETRY-AFTER header - we need
01449     * it later */
01450    if ( msg_status==503 && (t->flags&T_NO_DNS_FAILOVER_FLAG)==0 &&
01451    parse_headers( p_msg, HDR_RETRY_AFTER_F, 0)==-1) {
01452       LM_ERR("failed to parse reply (looking for Retry-After\n");
01453    }
01454 
01455    /* processing of on_reply block */
01456    reply_route = t->on_reply;
01457    if (reply_route) {
01458       if (onreply_avp_mode) {
01459          /* lock the reply*/
01460          LOCK_REPLIES( t );
01461          /* set the as avp_list the one from transaction */
01462          backup_list = set_avp_list(&t->user_avps);
01463       } else {
01464          backup_list = 0;
01465       }
01466       /* transfer transaction flag to branch context */
01467       p_msg->flags = t->uas.request->flags;
01468       setb0flags(t->uac[branch].br_flags);
01469       /* run block */
01470       if ( (run_top_route(onreply_rlist[reply_route], p_msg)&ACT_FL_DROP) &&
01471       (msg_status<200) ) {
01472          if (onreply_avp_mode) {
01473             UNLOCK_REPLIES( t );
01474             set_avp_list( backup_list );
01475          }
01476          LM_DBG("dropping provisional reply %d\n",
01477             msg_status);
01478          goto done;
01479       }
01480       /* transfer current message context back to t */
01481       t->uac[branch].br_flags = getb0flags();
01482       t->uas.request->flags = p_msg->flags;
01483       if (onreply_avp_mode)
01484          /* restore original avp list */
01485          set_avp_list( backup_list );
01486    }
01487 
01488    if (!onreply_avp_mode || !reply_route)
01489       /* lock the reply*/
01490       LOCK_REPLIES( t );
01491 
01492    /* mark that the UAC received replies */
01493    uac->flags |= T_UAC_HAS_RECV_REPLY;
01494 
01495    if (t->uac[branch].flags&T_UAC_TO_CANCEL_FLAG) {
01496       if ( msg_status < 200 )
01497          /* reply for an UAC with a pending cancel -> do cancel now */
01498          cancel_branch(t, branch);
01499       /* reset flag */
01500       t->uac[branch].flags &= ~(T_UAC_TO_CANCEL_FLAG);
01501    }
01502 
01503    if (is_local(t)) {
01504       reply_status = local_reply(t,p_msg, branch,msg_status,&cancel_bitmap);
01505       if (reply_status == RPS_COMPLETED) {
01506          cleanup_uac_timers(t);
01507          if (is_invite(t)) cancel_uacs(t, cancel_bitmap);
01508          /* There is no need to call set_final_timer because we know
01509           * that the transaction is local */
01510          put_on_wait(t);
01511       }
01512    } else {
01513       reply_status = relay_reply(t,p_msg,branch,msg_status,&cancel_bitmap);
01514       /* clean-up the transaction when transaction completed */
01515       if (reply_status == RPS_COMPLETED) {
01516          /* no more UAC FR/RETR (if I received a 2xx, there may
01517           * be still pending branches ...
01518           */
01519          cleanup_uac_timers(t);
01520          if (is_invite(t)) cancel_uacs(t, cancel_bitmap);
01521          /* FR for negative INVITES, WAIT anything else */
01522          /* set_final_timer(t); */
01523       }
01524    }
01525    
01526    if (reply_status!=RPS_PROVISIONAL)
01527       goto done;
01528    
01529    /* update FR/RETR timers on provisional replies */
01530    if (msg_status < 200 && (restart_fr_on_each_reply ||
01531    ((last_uac_status<msg_status) &&
01532    ((msg_status >= 180) || (last_uac_status == 0)))
01533    ) ) { /* provisional now */
01534       if (is_invite(t)) {
01535          /* invite: change FR to longer FR_INV, do not
01536           * attempt to restart retransmission any more
01537           */
01538          if(uac->local_cancel.buffer.s==NULL)
01539          {
01540             backup_list = set_avp_list(&t->user_avps);
01541             if (!fr_inv_avp2timer(&timer)) {
01542                LM_DBG("FR_INV_TIMER = %lld\n", timer);
01543                set_timer(&uac->request.fr_timer,
01544                      FR_INV_TIMER_LIST, &timer);
01545             } else {
01546                set_timer(& uac->request.fr_timer, FR_INV_TIMER_LIST, 0);
01547             }
01548             set_avp_list(backup_list);
01549          } else {
01550             /* fast failure */
01551             timer = 1;
01552             set_timer(&uac->request.fr_timer, FR_INV_TIMER_LIST, &timer);
01553          }
01554       } else {
01555          /* non-invite: restart retransmissions (slow now) */
01556          uac->request.retr_list = RT_T2;
01557          set_timer(&uac->request.retr_timer, RT_T2, 0);
01558       }
01559    } /* provisional replies */
01560    
01561 done:
01562    _tm_branch_index = 0;
01563    /* we are done with the transaction, so unref it - the reference
01564     * was incremented by t_check() function -bogdan*/
01565    t_unref(p_msg);
01566    /* don't try to relay statelessly neither on success
01567     * (we forwarded statefully) nor on error; on troubles, 
01568     * simply do nothing; that will make the other party to 
01569     * retransmit; hopefuly, we'll then be better off 
01570     */
01571    return 0;
01572 not_found:
01573    set_t(T_UNDEFINED);
01574    /* if drop_stateless_replies is enabled then replies no
01575     * matching a client transaction are dropped instead of
01576     * forwarded stateless based on Via header.
01577     */
01578    if (drop_stateless_replies) {
01579       LM_DBG("reply with no transaction -> drop\n");
01580       return 0;
01581    }
01582    return 1;
01583 }
01584 
01585 
01586 int t_reply_with_body( struct cell *trans, unsigned int code, str *text,
01587                            str *body, str *new_header, str *to_tag )
01588 {
01589    struct lump_rpl *hdr_lump;
01590    struct lump_rpl *body_lump;
01591    str  rpl;
01592    int  ret;
01593    struct bookmark bm;
01594 
01595    /* mark the transaction as replied */
01596    if (code>=200) set_kr(REQ_RPLD);
01597 
01598    /* add the lumps for new_header and for body (by bogdan) */
01599    if (new_header && new_header->len) {
01600       hdr_lump = add_lump_rpl( trans->uas.request, new_header->s,
01601          new_header->len, LUMP_RPL_HDR );
01602       if ( !hdr_lump ) {
01603          LM_ERR("failed to add hdr lump\n");
01604          goto error;
01605       }
01606    } else {
01607       hdr_lump = 0;
01608    }
01609 
01610    /* body lump */
01611    if(body && body->len) {
01612       body_lump = add_lump_rpl( trans->uas.request, body->s, body->len,
01613          LUMP_RPL_BODY );
01614       if (body_lump==0) {
01615          LM_ERR("failed add body lump\n");
01616          goto error_1;
01617       }
01618    } else {
01619       body_lump = 0;
01620    }
01621 
01622    rpl.s = build_res_buf_from_sip_req(
01623          code, text, to_tag,
01624          trans->uas.request, (unsigned int*)&rpl.len, &bm);
01625 
01626    /* since the msg (trans->uas.request) is a clone into shm memory, to avoid
01627     * memory leak or crashing (lumps are create in private memory) I will
01628     * remove the lumps by myself here (bogdan) */
01629    if ( hdr_lump ) {
01630       unlink_lump_rpl( trans->uas.request, hdr_lump);
01631       free_lump_rpl( hdr_lump );
01632    }
01633    if( body_lump ) {
01634       unlink_lump_rpl( trans->uas.request, body_lump);
01635       free_lump_rpl( body_lump );
01636    }
01637 
01638    if (rpl.s==0) {
01639       LM_ERR("failed in doing build_res_buf_from_sip_req()\n");
01640       goto error;
01641    }
01642 
01643    LM_DBG("buffer computed\n");
01644    ret=_reply_light( trans, rpl.s, rpl.len, code, to_tag->s, to_tag->len,
01645          1 /* lock replies */, &bm );
01646 
01647    /* unref since this it's used only internaly */
01648    UNREF(trans);
01649 
01650    return ret;
01651 error_1:
01652    if ( hdr_lump ) {
01653       unlink_lump_rpl( trans->uas.request, hdr_lump);
01654       free_lump_rpl( hdr_lump );
01655    }
01656 error:
01657    return -1;
01658 }

Generated on Thu May 24 20:00:32 2012 for Kamailio - The Open Source SIP Server by  doxygen 1.5.6