# Functions

## `t_relay([host, port])`

Relay a SIP request statefully either to the destination indicated in the current URI (if called without any parameters) or to the specified host and port. In the later case (host and port specified) the protocol used is the same protocol on which the message was received. It creates the SIP transaction, if none was created before (e.g., with t_newtran()).

`t_relay()` is the stateful version for `forward()` while `t_relay(host, port)` is similar to `forward(host, port)`.

In the forward to uri case (`t_relay()`), if the original URI was rewritten (by UsrLoc, RR, strip/prefix, etc.) the new URI will be taken). The destination (including the protocol) is determined from the uri, using SIP specific DNS resolving if needed (NAPTR, SRV a.s.o depending also on the dns options).

Returns a negative value on failure -- you may still want to send a negative reply upstream statelessly not to leave upstream UAC in lurch.

### `t_relay` usage

    ...
    if (!t_relay())
    {
        send_reply_error();
        break;
    };
    ...

## `t_relay_to_udp([ip, port])`

Relay a message statefully using a fixed protocol either to the specified fixed destination or to a destination derived from the message uri (if the host address and port are not specified). These along with `t_relay` are the functions most users want to use--all other are mostly for programming. Programmers interested in writing TM logic should review how t_relay is implemented in tm.c and how TM callbacks work.

Meaning of the parameters is as follows:

- ip - IP address where the message should be sent.

- port - Port number.

If no parameters are specified the message is sent to a destination derived from the message uri (using sip specific DNS lookups), but with the protocol corresponding to the function name.

### `t_relay_to_udp` usage

    ...
    if (src_ip==10.0.0.0/8)
    	t_relay_to_udp("1.2.3.4", "5060"); # sent to 1.2.3.4:5060 over udp
    else
    	t_relay_to_tcp(); # relay to msg. uri, but over tcp
    ...

## `t_relay_to_tcp([ip, port])`

See function `t_relay_to_udp([ip, port])`.

## `t_relay_to_tls([ip, port])`

See function `t_relay_to_udp([ip, port])`.

## `t_relay_to_sctp([ip, port])`

See function `t_relay_to_udp([ip, port])`.

## `t_on_failure(failure_route)`

Sets failure routing block, to which control is passed after a transaction completed with a negative result but before sending a final reply. In the referred block, you can either start a new branch (good for services such as forward_on_no_reply) or send a final reply on your own (good for example for message silo, which received a negative reply from upstream and wants to tell upstream "202 I will take care of it"). Note that the set of commands which are usable within failure_routes is strictly limited to rewriting URI, initiating new branches, logging, and sending stateful replies (`t_reply`). Any other commands may result in unpredictable behavior and possible server failure. Note that whenever failure_route is entered, uri is reset to value which it had on relaying. If it temporarily changed during a reply_route processing, subsequent reply_route will ignore the changed value and use again the original one.

Meaning of the parameters is as follows:

- failure_route - Failure route block to be called.

### `t_on_failure` usage

    ...
    route {
        t_on_failure("1");
        t_relay();
    }

    failure_route[1] {
        revert_uri();
        setuser("voicemail");
        append_branch();
    }
    ...

See `misc/examples/mixed/onr.cfg` for a more complex example of combination of serial with parallel forking.

## `t_on_branch_failure(branch_failure_route)`

Sets the branch_failure routing block, to which control is passed on each negative response to a transaction. This route is run before deciding if the transaction is complete. In the referred block, you can start a new branch which is required for failover of multiple outbound flows (RFC 5626). Note that the set of commands which are usable within a branch_failure route is limited to a subset of the failure_route commands including logging, rewriting URI and initiating new branches. Any other commands may generate errors or result in unpredictable behavior. Note that whenever failure_route is entered, uri is reset to value which it had on relaying. If it temporarily changed during a reply_route processing, subsequent reply_route will ignore the changed value and use again the original one.

Function Parameters:

- branch_failure_route - Name of the branch_failure route block to be called (it is prefixed internally with 'tm:branch-failure:').

### `t_on_branch_failure` usage

    ...
    route {
        t_on_branch_failure("myroute");
        t_relay();
    }

    event_route[tm:branch-failure:myroute] {
        if (t_check_status("430|403") {
            unregister("location", "$tu", "$T_reply_ruid");
        }
    }
    ...

## `t_on_reply(onreply_route)`

Sets the reply routing block, to which control is passed when a reply for the current transaction is received. Note that the set of commands which are usable within onreply_routes is limited.

Meaning of the parameters is as follows:

- onreply_route - Onreply route block to be called.

### `t_on_reply` usage

    ...
    loadmodule "/usr/local/lib/ser/modules/nathelper.so"
    ...
    route {
    	/* if natted */
    	t_on_reply("1");
    	t_relay();
    }

    onreply_route[1] {
    	if (status=~ "(183)|2[0-9][0-9]"){
    		force_rtp_proxy();
    		search_append('^(Contact|m)[ \t]*:.*sip:[^>[:cntrl:]]*', ';nat=yes');
    	}
    	if (nat_uac_test("1")){
    		fix_nated_contact();
    	}
    }

## `t_on_branch(branch_route)`

Sets the branch routing block, to which control is passed after forking (when a new branch is created). For now branch routes are intended only for last minute changes of the SIP messages (like adding new headers). Note that the set of commands which are usable within branch_routes is very limited. It is not possible to generate a reply.

Meaning of the parameters is as follows:

- branch_route - branch route block to be called.

### `t_on_branch` usage

    ...
    route {
    	t_on_branch("1");
    	t_relay();
    }

    branch_route[1] {
    	if (uri=~"sip:[0-9]+"){
    		append_hf("P-Warn: numeric uri\r\n");
    	}
    }

## `t_newtran()`

Creates a new transaction, returns a negative value on error. Typically, it is used to deploy a UAS.

Note: once the t_newtran() is executed, the new message flag operations (i.e., setflag() and resetflag()) are not synchronized to the transaction, being stored only in the private memory SIP message structure. Use the tmx module function t_flush_flags() to synchronize the modified message flags to the already created transaction.

### `t_newtran` usage

    ...
    if (t_newtran()) {
        xlog("the transaction has been created\n");
        t_reply("999","hello");
    } else {
        sl_reply_error();
    }
    ...

See `misc/examples/mixed/uas.cfg` for more examples.

## `t_reply(code, reason_phrase)`

Sends a stateful reply after a transaction has been established. See `t_newtran` for usage.

If the code is in the range 300-399 (redirect reply), the current destination set is appended to the reply as Contact headers. The destination set contains the request URI (R-URI), if it is modified compared to the received one, plus the branches added to the request (e.g., after an append_branch() or lookup("location")). If the R-URI was changed but it is not desired to be part of the destination set, it can be reverted using the function revert_uri().

Custom headers to the reply can be added using append_to_reply() function from textops module.

Meaning of the parameters is as follows:

- code - Reply code number.

- reason_phrase - Reason string.

This function can be used from REQUEST_ROUTE, FAILURE_ROUTE, ONREPLY_ROUTE.

### `t_reply` usage

    ...
    t_reply("404", "Not found");
    ...

## `t_reply_error()`

Sends a stateful reply based in internal error code, similar to sl_send_error() from sl module.

This function can be used from REQUEST_ROUTE, FAILURE_ROUTE, ONREPLY_ROUTE.

### `t_reply_error` usage

    ...
    t_reply_error();
    ...

## `t_send_reply(code, reason)`

Creates the transaction if it does not exist (executing internally t_newtran()) and sends a stateful reply (executing internally t_reply()). If transaction exists, this function does not stop the execution of config, t_reply() being still executed.

For more, see the docs for t_newtran() and t_reply().

Meaning of the parameters is as follows:

- code - Reply code number.

- reason - Reason string.

### `t_send_reply` usage

    ...
    t_send_reply("404", "Not found");
    ...

## `t_lookup_request()`

Checks if a transaction exists. Returns a positive value if so, negative otherwise. Most likely you will not want to use it, as a typical application of a look-up is to introduce a new transaction if none was found. However this is safely (atomically) done using `t_newtran`.

### `t_lookup_request` usage

    ...
    if (t_lookup_request()) {
        ...
    };
    ...

## `t_retransmit_reply()`

Retransmits a reply sent previously by UAS transaction.

### `t_retransmit_reply` usage

    ...
    t_retransmit_reply();
    ...

## `t_release()`

Remove transaction from memory (it will be first put on a wait timer to absorb delayed messages).

### `t_release` usage

    ...
    t_release();
    ...

## `t_forward_nonack([ip, port])`

Mainly for internal usage -- forward a non-ACK request statefully. Variants of this functions can enforce a specific transport protocol.

Meaning of the parameters is as follows:

- ip - IP address where the message should be sent.

- port - Port number.

### `t_forward_nonack` usage

    ...
    t_forward_nonack("1.2.3.4", "5060");
    ...

## `t_forward_nonack_udp(ip, port)`

See function `t_forward_nonack([ip, port])`.

## `t_forward_nonack_tcp(ip, port)`

See function `t_forward_nonack([ip, port])`.

## `t_forward_nonack_tls(ip, port)`

See function `t_forward_nonack([ip, port])`.

## `t_forward_nonack_sctp(ip, port)`

See function `t_forward_nonack([ip, port])`.

## `t_set_fr(fr_inv_timeout [, fr_timeout])`

Sets the fr_inv_timeout and optionally fr_timeout for the current transaction or for transactions created during the same script invocation, after calling this function. If the transaction is already created (e.g called after `t_relay()` or in an onreply_route) all the branches will have their final response timeout updated on-the-fly. If one of the parameters is 0, its value won't be changed.

Meaning of the parameters is as follows:

- fr_inv_timeout - new final response timeout (in milliseconds) for INVITEs. See also `fr_inv_timer`.

- fr_timeout - new final response timeout (in milliseconds) for non-INVITE transaction, or INVITEs which haven't received yet a provisional response. See also `fr_timer`.

See also: `fr_timer`, `fr_inv_timer`, `t_reset_fr()`.

### `t_set_fr` usage

    ...
    route {
    	t_set_fr(10000); # set only fr invite timeout to 10s
    	t_on_branch("1");
    	t_relay();
    }

    branch_route[1] {
    	# if we are calling the pstn, extend the invite timeout to 50s
    	# for all the branches, and set the no-reply-received timeout to 2s
    	if (uri=~"sip:[0-9]+"){
    		t_set_fr(50000, 2000);
    	}
    }

## `t_reset_fr()`

Resets the `fr_inv_timer` and `fr_timer` for the current transaction to the default values (set using the tm module parameters `fr_inv_timer` and `fr_timer`).

It will effectively cancel any previous calls to `t_set_fr` for the same transaction.

See also: `fr_timer`, `fr_inv_timer`, `t_set_fr`.

### `t_reset_fr` usage

    ...
    route {
    ...
    		t_reset_fr();
    ...
    }

## `t_set_max_lifetime(inv_lifetime, noninv_lifetime)`

Sets the maximum lifetime for the current INVITE or non-INVITE transaction, or for transactions created during the same script invocation, after calling this function (that's why it takes values for both INVITE and non-INVITE). If one of the parameters is 0, its value won't be changed.

It works as a per transaction `max_inv_lifetime` or `max_noninv_lifetime`.

Meaning of the parameters is as follows:

- inv_lifetime - maximum INVITE transaction lifetime (in milliseconds). See also `max_inv_lifetime`.

- noninv_lifetime - maximum non-INVITE transaction lifetime (in milliseconds). See also `max_noninv_lifetime`.

See also: `max_inv_lifetime`, `max_noninv_lifetime`, `t_reset_max_lifetime`.

### `t_set_max_lifetime` usage

    ...
    route {
        if (src_ip=1.2.3.4)
            t_set_max_lifetime(120000, 0); # set only max_inv_lifetime to 120s
        else
            t_set_max_lifetime(90000, 15000); # set the maximum lifetime to 90s if
                                              # the current transaction is an
                                              # INVITE and to 15s if not
    }

## `t_reset_max_lifetime()`

Resets the maximum lifetime for the current INVITE or non-INVITE transaction to the default value (set using the tm module parameter `max_inv_lifetime` or `max_noninv_lifetime`).

It will effectively cancel any previous calls to `t_set_max_lifetime` for the same transaction.

See also: `max_inv_lifetime`, `max_noninv_lifetime`, `t_set_max_lifetime`.

### `t_reset_max_lifetime` usage

    ...
    route {
    ...
    		t_reset_max_lifetime();
    ...
    }

## `t_set_retr(retr_t1_interval, retr_t2_interval)`

Sets the retr_t1_interval and retr_t2_interval for the current transaction or for transactions created during the same script invocation, after calling this function. If one of the parameters is 0, its value won't be changed. If the transaction is already created (e.g called after `t_relay()` or in an onreply_route) all the existing branches will have their retransmissions intervals updated on-the-fly: if the retransmission interval for the branch has not yet reached T2 the interval will be reset to retr_t1_interval, else to retr_t2_interval. Note that the change will happen after the current interval expires (after the next retransmission, the next-next retransmission will take place at retr_t1_interval or retr_t2_interval). All new branches of the same transaction will start with the new values. This function will work even if it's called in the script before a transaction creating function (e.g.: t_set_retr(500, 4000); t_relay()). All new transaction created after this function call, during the same script invocation will use the new values.

Meaning of the parameters is as follows:

- retr_t1_interval - new T1 retransmission interval (in milliseconds). See also `retr_t1_timeout`.

- retr_t2_interval - new T2 (or maximum) retransmission interval (in milliseconds). See also `retr_t2_timeout`.

See also: `retr_timer1`, `retr_timer2`, `t_reset_retr()`.

### `t_set_retr` usage

    ...
    route {
    	t_set_retr(250, 0); # set only T1 to 250 ms
    	t_on_branch("1");
    	t_relay();
    }

    branch_route[1] {
    	# if we are calling the a remote pstn, extend T1 and decrease T2
    	# for all the branches
    	if (uri=~"sip:[0-9]+"){
    		t_set_retr(500, 2000);
    	}
    }

## `t_reset_retr()`

Resets the `retr_timer1` and `retr_timer2` for the current transaction to the default values (set using the tm module parameters `retr_timer1` and `retr_timer2`).

It will effectively cancel any previous calls to `t_set_retr` for the same transaction.

See also: `retr_timer1`, `retr_timer2`, `t_set_retr`.

### `t_reset_retr` usage

    ...
    route {
    ...
    		t_reset_retr();
    ...
    }

## `t_set_auto_inv_100(0|1)`

Switch automatically sending 100 replies to INVITEs on/off on a per transaction basis. It overrides the `auto_inv_100` value for the current transaction.

See also: `auto_inv_100`.

### `t_set_auto_inv_100` usage

    ...
    route {
    ...
    	if (src_ip==1.2.3.0/24)
    		t_set_auto_inv_100(0); # turn off automatic 100 replies
    ...
    }

## `t_branch_timeout()`

Returns true if the failure route is executed for a branch that did timeout. It can be used from FAILURE_ROUTE and BRANCH_FAILURE_ROUTE event route.

### `t_branch_timeout` usage

    ...
    failure_route[0]{
    	if (t_branch_timeout()){
    		log("timeout\n");
    		# ...
    	}
    }

## `t_branch_replied()`

Returns true if the failure route is executed for a branch that did receive at least one reply in the past (the "current" reply is not taken into account). It can be used from failure_route and branch-failure event route.

### `t_branch_replied` usage

    ...
    failure_route[0]{
    	if (t_branch_timeout()){
    		if (t_branch_replied())
    			log("timeout after receiving a reply (no answer?)\n");
    		else
    			log("timeout, remote side seems to be down\n");
    		# ...
    	}
    }

## `t_any_timeout()`

Returns true if at least one of the current transactions branches did timeout.

### `t_any_timeout` usage

    ...
    failure_route[0]{
    	if (!t_branch_timeout()){
    		if (t_any_timeout()){
    			log("one branch did timeout\n");
    			sl_send_reply("408", "Timeout");
    		}
    	}
    }

## `t_any_replied()`

Returns true if at least one of the current transactions branches did receive some reply in the past. If called from a failure or onreply route, the "current" reply is not taken into account.

### `t_any_replied` usage

    ...
    onreply_route[0]{
    	if (!t_any_replied()){
    		log("first reply received\n");
    		# ...
    	}
    }

## `t_grep_status("code")`

Returns true if "code" is the final reply received (or locally generated) in at least one of the current transactions branches.

### `t_grep_status` usage

    ...
    onreply_route[0]{
    	if (t_grep_status("486")){
    		/* force a 486 reply, even if this is not the winning branch */
    		t_reply("486", "Busy");
    	}
    }

## `t_is_canceled()`

Returns true if the current transaction was canceled.

### `t_is_canceled` usage

    ...
    failure_route[0]{
    	if (t_is_canceled()){
    		log("transaction canceled\n");
    		# ...
    	}
    }

## `t_is_expired()`

Returns true if the current transaction has already expired, i.e. the max_inv_lifetime/max_noninv_lifetime interval has already elapsed.

### `t_is_expired` usage

    ...
    failure_route[0]{
    	if (t_is_expired()){
    		log("transaction expired\n");
    		# There is no point in adding a new branch.
    	}
    }

## `t_relay_cancel()`

Forwards the CANCEL if the corresponding INVITE transaction exists. The function is supposed to be used at the very beginning of the script, because the CANCELs can be caught and the rest of the script can be bypassed this way. Do not disable `reparse_invite` module parameter, and call `t_relay_cancel()` right after the sanity tests.

Return value is 0 (drop) if the corresponding INVITE was found and the CANCELs were successfully sent to the pending branches, true if the INVITE was not found, and false in case of any error.

### `t_relay_cancel` usage

    if (method == CANCEL) {
    	if (!t_relay_cancel()) {  # implicit drop if relaying was successful,
                                      # nothing to do

    		# corresponding INVITE transaction found but error occurred
    		sl_reply("500", "Internal Server Error");
    		drop;
    	}
    	# bad luck, corresponding INVITE transaction is missing,
    	# do the same as for INVITEs
    }

## `t_lookup_cancel([1])`

Returns true if the corresponding INVITE transaction exists for a CANCEL request. The function can be called at the beginning of the script to check whether or not the CANCEL can be immediately forwarded bypassing the rest of the script. Note however that `t_relay_cancel` includes `t_lookup_cancel` as well, therefore it is not needed to explicitly call this function unless something has to be logged for example.

If the function parameter (optional) is set to 1, the message flags are overwritten with the flags of the INVITE. isflagset() can be used to check the flags of the previously forwarded INVITE in this case.

### `t_lookup_cancel` usage

    if (method == CANCEL) {
    	if (t_lookup_cancel()) {
    		log("INVITE transaction exists");
    		if (!t_relay_cancel()) {  # implicit drop if
                                              # relaying was successful,
                                              # nothing to do

    			# corresponding INVITE transaction found
    			# but error occurred
    			sl_reply("500", "Internal Server Error");
    			drop;
    		}
    	}
    	# bad luck, corresponding INVITE transaction is missing,
    	# do the same as for INVITEs
    }

## `t_drop_replies([mode])`

Drops all the previously received replies in failure_route block to make sure that none of them is picked up again.

The parameter 'mode' controls which replies are dropped: 'a' or missing - all replies are dropped; 'l' - replies received for last set of branches are dropped; 'n' - no reply is dropped.

Dropping replies works only if a new branch is added to the transaction, or it is explicitly replied in the script!

### `t_drop_replies()` usage

    ...
    failure_route[0]{
    	if (t_check_status("5[0-9][0-9]")){
    		# I do not like the 5xx responses,
    		# so I give another chance to "foobar.com",
    		# and I drop all the replies to make sure that
    		# they are not forwarded to the caller.
    		t_drop_replies();

    		rewritehostport("foobar.com");
    		append_branch();
    		t_relay();
    	}
    }

## `t_save_lumps()`

Forces the modifications of the processed SIP message to be saved in shared memory before t_relay() is called. The new branches which are created in failure_route will contain the same modifications, and any other modification after t_save_lumps() will be lost.

Note that t_relay() automatically saves the modifications when it is called the first time, there is no need for t_save_lumps() unless message changes between t_save_lumps() and t_relay() must not be propagated to failure_route.

The transaction must be created by t_newtran() before calling t_save_lumps().

### `t_save_lumps()` usage

    route {
    	...
    	t_newtran();
    	append_hf("hf1: my first header\r\n");
    	...
    	t_save_lumps();
    	append_hf("hf2: my second header\r\n");
    	...
    	t_on_failure("1");
    	t_relay();
    }

    failure_route[1] {
    	append_branch();
    	append_hf("hf3: my third header\r\n");
    	#
    	# This branch contains hf1 and hf3, but does
    	# not contain hf2 header.
    	# hf2 would be also present here without
    	# t_save_lumps().
    	...
    	t_relay();
    }

## `t_load_contacts([mode])`

This is the first of the three functions that can be used to implement serial/parallel forking based on q and +sip.instance values of individual branches in the destination set.

Function `t_load_contacts()` removes all branches from the current destination set and stores them into the XAVP whose name is configured with the parameter `contacts_avp`. Note that you have to configure this parameter before you can use the function, the parameter is set to NULL by default, which disables the function.

If the destination set contains only one branch, the function does nothing.

If the current destination set contains more than one branch, the function sorts them according to the algorithm selected with the 'mode' parameter and then stores the branches in reverse order into the XAVP.

The q parameter of a branch contains a value from range 0-1.0 and it expresses relative preference of the branch among all branches in the destination set. The higher the q value the more preference the user agent gave to the branch. The parameter 'mode' controls which type of algorithm kamailio will apply to sort the branches based on the q values:

- '0' or missing: branches with higher q values will be tried before branches with lower ones when serial forking takes place Equals q values will result in a parallel forking.

- '1': branches are ordered using a proportional algorithm that uses to q value as the weight of the branch. Higher is the q value, higher is the probability to be tried as first. Equals q values means equals probability to be tried. Differently from the previous mode there is no possibility to have parallel forking. Branches with q values equals to 0 or lower are not considered by the ordering algorithm, but just added at the end of the list as backup option if all other branches fail. This algorithm can be useful in case of endpoints in ACTIVE-ACTIVE configuration to load-balance the calls.

After calling `t_load_contacts()`, function `t_next_contacts()` and possibly also `t_next_contact_flow()` need to be called one or more times in order to retrieve the branches based on their order.

Function returns 1 if loading of contacts succeeded or there was nothing to do. In case of an error, function returns -1 (see syslog).

This function can be used from REQUEST_ROUTE and FAILURE_ROUTE.

### `t_load_contacts` usage

    ...
    if (!t_load_contacts()) {
            sl_send_reply("500", "Server Internal Error - Cannot load contacts");
            exit;
    };
    ...

## `t_next_contacts()`

Function `t_next_contacts()` is the second of the three functions that can be used to implement serial/parallel forking based on the q value of the individual branches in a destination set.

The function adds to request a new destination set that includes the highest priority contacts in contacts_avp, but only one contact with the same +sip.instance value is included. Duplicate contacts are added to contact_flows_avp for later consumption by function `next_contact_flow()`. Upon each call, Request URI is rewritten with the first contact and the remaining contacts (if any) are added as branches. Then all highest priority contacts are removed from contacts_avp.

Function does nothing if `contact_avp` has no values.

Function returns 1 if contacts_avp was not empty and a destination set was successfully added, returns -2 if contacts_avp was empty and thus there was nothing to do, and returns -1 in case of an error (see syslog). Function can be called from REQUEST_ROUTE and FAILURE_ROUTE.

Note that if you use `t_load_contacts` and `t_next_contacts` functions then you should also set the value of `restart_fr_on_each_reply` parameter to 0. If you do not do that, it can happen that a broken user agent that retransmits 180 periodically will keep resetting the fr_inv_timer value and serial forking never happens.

Before calling t_relay(), you can check if the previous call of `next_contacts()` consumed all branches by checking if `contact_avp` and `contact_flows_avp` are not anymore set. Based on that test, you can then use t_set_fr() function to set timers according to your needs.

### `t_next_contacts` usage

    ...
    # First call after t_load_contacts() when transaction does not exist yet
    # and contacts should be available
    if (!t_next_contacts()) {
            sl_send_reply("500", "Server Internal Error - Cannot get contacts");
    } else {
            t_relay();
    };
    ...
    # Following call, when transaction exists and there may or may not be
    # contacts left
    if (!t_next_contacts()) {
            t_reply("408", "Request Timeout");
    } else {
            t_relay();
    };
    ...

## `t_next_contact_flow()`

Function `t_next_contact_flow()` is the last of the three functions that can be used to implement serial/parallel forking based on the q value and instance value of individual branches in a destination set.

Function adds a new branch to the request that includes the first contact from `contact_flows_avp` that matches the +sip.instance value of the flow that has failed. Upon each call, Request URI is rewritten with the contact. The used contact is removed from `contact_flows_avp`.

Function does nothing if there are no `contact_flows_avp` values.

Function returns 1 if `contact_flows_avp` was not empty and a destination set was successfully added, returns -2 if `contacts_avp` was empty and thus there was nothing to do, and returns -1 in case of an error (see syslog). This function can be used from a BRANCH_FAILURE_ROUTE event route.

### `t_next_contact_flow` usage

    ...
    event_route[tm:branch-failure:outbound]
    {
    	if (t_next_contact_flow())
    	{
    		t_relay();
    	} else {
    		xlog("L_INFO", "No more flows\n");
    	}
    ...

## `t_check_status(re)`

Returns true if the regular expression re match the reply code of the response message as follows:

- in routing block - the code of the last sent reply.

- in on_reply block - the code of the current received reply.

- in on_failure block - the code of the selected negative final reply.

This function can be used from ANY_ROUTE .

### `t_check_status` usage

    ...
    if (t_check_status("(487)|(408)")) {
        log("487 or 408 negative reply\n");
    }
    ...

## `t_check_trans()`

`t_check_trans()` can be used to quickly check if a message belongs or is related to a transaction. It behaves differently for different types of messages:

- For a SIP Reply it returns true if the reply belongs to an existing transaction and false otherwise.

- For a CANCEL it behaves exactly as `t_lookup_cancel()`: returns true if a corresponding INVITE transaction exists for the CANCEL and false otherwise.

- For ACKs to negative replies or for ACKs to local transactions it will terminate the script if the ACK belongs to a transaction (it would make very little sense to process an ACK to a negative reply for an existing transaction in some other way then to simply pass it to tm) or return false if not.

- For end-to-end ACKs (ACKs to 2xx responses for forwarded INVITE transactions) it will return true if the corresponding INVITE transaction is found and still active and false if not.

  Note that the e2e ACK matching is more of a hint then a certainty. A delayed e2e ACK might arrive after the transaction wait time elapses, when the INVITE transaction no longer exists and thus would not match anything. There are also cases when tm would not keep all the information needed for e2e ACK matching (since this is not needed for a stateful proxy and it requires additional memory, tm will not keep this information unless needed by some other module or callbacks).

- For other requests (non ACKs and non CANCELs), in case of a retransmission matching a transaction, it resends the last reply for that transaction and terminates the config execution. Otherwise, it returns false (in case of new requests for which no transaction exists yet).

An important difference from kamailio version is that for an ACK to negative reply or for a local transaction, the script execution will be immediately stopped and the message handled by tm, instead of returning true.

`t_check_trans()` functionality for requests, except for the e2e ACK matching, can be replicated in the script using `t_lookup_cancel()` and `t_lookup_request()`.

See also: `t_lookup_request()`, `t_lookup_cancel()`.

### `t_check_trans` usage

    if ( method == "CANCEL" && !t_check_trans())
    	sl_reply("403", "cancel out of the blue forbidden");
    # note: in this example t_check_trans() can be replaced by t_lookup_cancel()

## `t_set_disable_6xx(0|1)`

Turn off/on 6xx replies special rfc conforming handling on a per transaction basis. If turned off (`t_set_disable_6xx("1")`) 6XXs will be treated like normal replies.

It overrides the `disable_6xx_block` value for the current transaction.

See also: `disable_6xx_block`.

### `t_set_disable_6xx` usage

    ...
    route {
    ...
    	if (src_ip==1.2.3.4) # bad user agent that sends 603
    		t_set_disable_6xx(1); # turn off 6xx special handling
    ...
    }

## `t_set_disable_failover(0|1)`

Turn off/on dns failover on a per transaction basis.

See also: `use_dns_failover`.

### `t_set_disable_failover` usage

    ...
    route {
    ...
    	if (uri=~"@foo.bar$")
    		t_set_disable_failover(1); # turn off dns failover
    ...
    }

## `t_set_disable_internal_reply(0|1)`

Turn off/on sending internally a SIP reply in case of relay errors.

### `t_set_disable_internal_reply` usage

    ...
    t_set_disable_internal_reply(1); # turn off sending internal reply on error
    if(!t_relay()) {
       send_reply("500", "Server error");
    }
    ...

## `t_set_no_auto_ack(0|1)`

Turn off/on generating e2e ACKs automatically for successfully answered local transactions (uac)

### `t_set_no_auto_ack` usage

    ...
    t_set_no_auto_ack(1); # when receiving a 200-299 fr for local transaction (uac), do not reply automatically
    if(!t_relay()) {
       send_reply("500", "Server error");
    }
    ...

## `t_replicate([params])`

Replicate the SIP request to a specific address. Return values are the same as for `t_relay()`. Note that responses to the replicated request are suppressed and will not show up in any reply_route.

There are several function prototypes:

- `t_replicate([uri])`,

- `t_replicate(host, port)`,

- `t_replicate_udp(host, port)`

- `t_replicate_tcp(host, port)`

- `t_replicate_tls(host, port)`

- `t_replicate_sctp(host, port)`

- `t_replicate_to(proto, hostport)`

Meaning of the parameters is as follows:

- uri - SIP URI where the message should be sent. It can be given via a script variable. It is optional - when missing, the dst-uri or r-uri are used as next hop address.

- host - host address where the message should be sent.

- port - port number.

- proto - transport protocol to be used.

- hostport - address in "host:port" format. It can be given via an AVP.

### `t_replicate` usage

    ...
    # sent to 1.2.3.4:5060 over tcp
    t_replicate("sip:1.2.3.4:5060;transport=tcp");

    # sent to 1.2.3.4:5061 over tls
    $var(h) = "1.2.3.4:5061";
    t_replicate("sip:$var(h);transport=tls");

    # sent to 1.2.3.4:5060 over udp
    t_replicate_to_udp("1.2.3.4", "5060");
    ...

## `t_relay_to(proxy, flags)`

Forward the SIP request to a specific address, controlling internal behavior via flags.

There are several function prototypes:

- `t_relay_to()`,

- `t_relay_to(proxy)`,

- `t_relay_to(flags)`

- `t_relay_to(proxy, flags)`

Meaning of the parameters is as follows:

- proxy - address where the request should be sent. Format is: "proto:host:port" - any of proto or port can be omitted, along with the semicolon after or before.

- flags - bitmask integer value to control the internal behavior. Bits can be:

  - 0x01 - do not generate 100 reply.

  - 0x02 - do not generate reply on internal error.

  - 0x04 - disable dns failover.

### `t_relay_to` usage

    ...
    # sent to 1.2.3.4:5060 over tcp
    t_relay_to("tcp:1.2.3.4:5060");

    # sent to 1.2.3.4 over tls
    t_relay_to("tls:1.2.3.4");

    # sent to dst URI or R-URI without a 100 reply
    t_relay_to("0x01");
    ...

## `t_relay_to_proxy(proxy [, flags])`

Alternative function to relay the SIP request to a specific address, with the parameter supporting variables inside it.

The format of the proxy parameter is: "proto:host:port" - any of proto or port can be omitted, along with the semicolon after or before. The flags parameter is optional, with possible values like for t_relay_to().

The function can be used in REQUEST_ROUTE and FAILURE_ROUTE.

### `t_relay_to_proxy` usage

    ...
    t_relay_to_proxy("udp:$var(addr):5060");
    ...

## `t_set_no_e2e_cancel_reason(0|1)`

Enables/disables reason header (RFC 3326) copying from the triggering received CANCEL to the generated hop-by-hop CANCEL. 0 enables and 1 disables.

It overrides the `e2e_cancel_reason` setting (module parameter) for the current transaction.

Note: the function has to be used when processing the INVITE (not when processing the CANCEL).

See also: `e2e_cancel_reason`.

### `t_set_no_e2e_cancel_reason` usage

    ...
    route {
    ...
    	if (src_ip!=10.0.0.0/8) #  don't trust CANCELs from the outside
    		t_set_no_e2e_cancel_reason(1); # turn off CANCEL reason header copying
    ...
    }

## `t_is_set(target)`

Return true if the attribute specified by 'target' is set for transaction.

The target parameter can be:

- branch_route - the function returns true if a branch route is set to be executed.

- failure_route - the function returns true if a failure route is set to be executed.

- onreply_route - the function returns true if an onreply route is set to be executed.

### `t_replicate` usage

    ...
    if(!t_is_set("failure_route"))
        LM_DBG("no failure route will be executed for current transaction\n");
    ...

## `t_use_uac_headers()`

Set internal flags to tell tm to use UAC side for building headers for local generated requests (ACK, CANCEL) - useful when changing From/To headers using other functions than uac_replace_[from|to]().

It returns true.

### `t_use_uac_headers` usage

    ...
    t_use_uac_headers();
    ...

## `t_is_retr_async_reply()`

Check to see if the reply is a retransmitted reply on a transaction that is currently suspended asynchronously (suspended during reply processing). Right now the check is only on the transaction, we don't actually check to see if the reply message is an actual retransmission of the suspended reply. This is expected as you should not process another reply until the suspended reply processing has been completed. The trick here is to make sure you don't suspend for too long or even worse, indefinitely.

returns true if the transaction is currently reply suspended or false if not.

### `t_is_retr_async_reply` usage

    ...
    if (t_is_retr_async_reply()) {
    	xlog("L_DBG", "Dropping retransmitted reply which is still currently suspended\n");
            drop();
    }
    ...

## `t_uac_send(method, ruri, nexthop, socket, headers, body)`

Send a UAC request.

It returns true (1) if successful, false (-1) on failure.

The parameters:

- method - SIP method. Add a "." to the end of the method name to suppress automatic ACK generation (the dot is not transmitted, of course).

- ruri - request URI.

- nexthop - destination URI (can be empty).

- socket - local send socket (can be empty).

- headers - SIP headers. At least From and To have to be provided. It can include From/To tags, Call-ID, CSeq. If body is provided, then Content-Type header must exist.

- body - SIP message body (can be empty).

### `t_uac_send` usage

    ...
    t_uac_send("OPTIONS", "sip:alice@kamailio.org", "", "",
        "From: bob@kamailio.org;tag=2w3e\r\nTo: bob@kamailio.org", "");
    ...

## `t_get_status_code()`

Return the status code for transaction - the most relevant SIP reply status code, or -1 in case of error or no status code was set.

### `t_get_status_code` usage

    ...
    $var(ts) = t_get_status_code();
    if($var(ts) == 500) { ... }
    ...

## `t_clean()`

Cleans active but very old transactions. Returns true (1). Can be called from any route.

### `t_clean` usage

    ...
    t_clean();
    ...

## `t_exists()`

Return true if a transaction for the current message exists, without setting the global references.

### `t_exists` usage

    ...
    reply_route {
        if (!t_exists()) {
            drop();
        }
    }
    ...

## `t_cell_append_branches(tindex, tlabel)`

Append destination set branches to the transaction identified by (tindex, tlabel). The parameters can also be variables.

### `t_cell_append_branches` usage

    ...
        append_branch("sip:1.2.3.4:5060");
        t_cell_append_branches("1234", "$var(tlabel)");
    ...

## `t_msg_apply_changes()`

Apply changes to the SIP request processed in a branch_route block. It changes the request only for that particular branch, not the transaction incoming request. It is similar to msg_apply_changes(), but designed to be used in the context of the branch route, after the transaction was created.

It is not needed to use this function explicitely, unless the changes to the SIP request are needed for the next functions in the same branch_route block, otherwise the operations for adding/removing headers or changing the body of the request are applied before writing to the outbound socket.

It requires to set core parameter msg_apply_changes_mode = 1.

### `t_msg_apply_changes` usage

    ...
    msg_apply_changes_mode = 1;
    ...
    branch_route[OUT] {
        append_hf("X-Hdr: abc\n");
        t_msg_apply_changes();
    }
    ...