Tuesday, October 3, 2017
Kamailio HA proxy script
### add the following things after request_route
if ( is_method("OPTIONS") ) {
if($fU=='sipsak'){
sl_send_reply("200", "OK");
exit;
}
}
Note: kamailio HA script is using sipsak for monitoring the kamailio startus.
############################################ Kamailio script #################
#!/bin/bash
#
# OCF resource agent for Kamailio for pacemaker
#
# Copyright (c) 2013 FREQUENTIS AG,
# Authors: Stefan Wenk
# Rainer Brestan
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it would be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# Further, this software is distributed without any warranty that it is
# free of the rightful claim of any third person regarding infringement
# or the like. Any license provided herein, whether implied or
# otherwise, applies only to this software file. Patent licenses, if
# any, provided herein do not apply to combinations of this program with
# other software, or any other product whatsoever.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
#
# OCF input parameters:
# OCF_RESKEY_binary
# OCF_RESKEY_conffile
# OCF_RESKEY_pidfile
# OCF_RESKEY_monitoring_ip
# OCF_RESKEY_listen_address
# OCF_RESKEY_port
# OCF_RESKEY_proto
# OCF_RESKEY_sipsak
# OCF_RESKEY_kamctl
# OCF_RESKEY_kamctlrc
# OCF_RESKEY_kamuser
# OCF_RESKEY_kamgroup
# OCF_RESKEY_extra_options
# Initialization:
: ${OCF_FUNCTIONS_DIR=${OCF_ROOT}/lib/heartbeat}
. ${OCF_FUNCTIONS_DIR}/ocf-shellfuncs
#######################################################################
# Defaults
RESKEY_binary_default="/usr/sbin/kamailio"
RESKEY_conffile_default="/etc/kamailio/kamailio.cfg"
RESKEY_pidfile_default="/var/run/kamailio_${OCF_RESOURCE_INSTANCE}/kamailio.pid"
RESKEY_monitoring_ip_default=127.0.0.1
RESKEY_port_default=5060
RESKEY_proto_default="udptcp"
RESKEY_sipsak_default="/usr/bin/sipsak"
RESKEY_kamctl_default="/usr/sbin/kamctl"
RESKEY_kamctlrc_default="/etc/kamailio/kamctlrc"
RESKEY_kamuser_default=""
RESKEY_kamgroup_default=""
RESKEY_extra_options_default=""
#######################################################################
: ${OCF_RESKEY_binary=${RESKEY_binary_default}}
: ${OCF_RESKEY_conffile=${RESKEY_conffile_default}}
: ${OCF_RESKEY_pidfile=${RESKEY_pidfile_default}}
: ${OCF_RESKEY_monitoring_ip=${RESKEY_monitoring_ip_default}}
: ${OCF_RESKEY_port=${RESKEY_port_default}}
: ${OCF_RESKEY_proto=${RESKEY_proto_default}}
: ${OCF_RESKEY_sipsak=${RESKEY_sipsak_default}}
: ${OCF_RESKEY_kamctl=${RESKEY_kamctl_default}}
: ${OCF_RESKEY_kamctlrc=${RESKEY_kamctlrc_default}}
: ${OCF_RESKEY_kamuser=${RESKEY_kamuser_default}}
: ${OCF_RESKEY_kamgroup=${RESKEY_kamgroup_default}}
: ${OCF_RESKEY_extra_options=${RESKEY_extra_options_default}}
#######################################################################
usage() {
cat <
Expects to have a fully populated OCF RA-compliant environment set.
END
}
meta_data() {
cat <
Resource agent for the Kamailio SIP proxy/registrar.
Multiple instances are possible when using following parameter combinations:
Parameters for Kamailio instance 1:
listen_address=192.168.159.128
monitoring_ip=192.168.159.128
proto=udptcp
port=5060
Parameters for Kamailio instance 2:
listen_address=192.168.159.128
monitoring_ip=192.168.159.128
proto=udp
port=5070
conffile=/etc/kamailio/kamailio2.cfg
kamctlrc=""
Only one instance can be monitored via the command "kamctl monitor"
because the kamctl tool of kamailio 4.x is not designed for multiple
instances. Therefore, the provided kamctrlrc file path needs to be
empty for instance 2, 3 ...
Parameters for a third Kamailio instance:
listen_address=192.168.159.128
monitoring_ip=192.168.159.128
proto=tcp
port=5080
conffile=/etc/kamailio/kamailio3.cfg
kamctlrc=""
The kamailio configuration file name with full path.
For example, "/etc/kamailio/kamailio.cfg" , which is the default value.
Make sure to use unique names in case of having multiple instances.
The kamailio PID file. The directory used must be writable by kamailio
process user. Be sure to use unique name for running more than one
instance. Try to use absolute path names.
If empty, resource agent create a unique directory from the resource
instance name for the PID file and assign it to the process user.
SIP IP Address of the kamailio instance used for SIP OPTIONS polling monitoring.
Usually the same IP address value as for parameter listen_address should be
provided.
In order to respond with a 200 OK response to the SIP OOPTION requests,
the kamailio.cfg file needs to contain following section:
Note: The following "kamailio.cfg" code sniplet is part of an XML section.
Therefore it contains two & characters, which need to be replaced
with two ampersand characters within "kamailio.cfg":
if (is_method("OPTIONS") && ($ru=~"sip:monitor@.*")) {
##
## If the method is an OPTIONS we are simply going to respond
## with a 200 OK.
# xlog("L_INFO", "Method is an OPTIONS, probably just monitoring\n");
sl_send_reply("200", "Kamailio is alive");
exit;
}
SIP port for the kamailio instance.
Extra options to add to kamailio start.
The protocol used for SIP proto = udp|tcp|udptcp|conf_udp|conf_tcp|conf_udptcp.
Using the options "conf_*" does not add any "-l" parameters to the kamailio command,
the "listen" parameters from kamailio.conf are used instead. The sipsak checks are
performed depending what protocol is defined after the underscore.
The installation path of the sipsak tool, which is used
for monitoring Kamailio via SIP OPTIONS polling.
The installation path of the "kamctl" control tool.
The location of the "kamctlrc" file for the Kamailio instance.
The file "kamctlrc" is the Kamailio configuration file for its "kamctl" control tool.
This parameter only needs to be provided in case of using multiple Kamailio server
instances on a single cluster node:
In case that the parameter "kamctlrc" is not empty, this ressource agent monitors
the health state of the Kamailio server via the command "kamctl monitor 1". This
setting is recommended in case of using a single Kamailio server instance.
In case that the parameter "kamctlrc" is empty, the ressource agent does not
monitor the health state of the Kamailio server instance via the "kamctl" command.
Please note that the "kamctl" control command of Kamailio 4.x does not support
running multiple Kamailio instances on one host. Nevertheless this resource agent
does allow multiple Kamailio instances per host. The result of the "kamctl"
limitation in terms of number of Kamailio server instances is that the health
check via "kamctl monitor 1" can be configured for a single Kamailio instance
only.
Please refer to the long description of this resoure agent for an example
of parameter combinations in case that multiple instances are to be
configured per cluster node.
The user account for kamailio process to run with.
Uses the current user, if not specified or empty.
There is no check, if running kamailio with the specified user account is possible.
The group for kamailio process to run with.
Uses the current group, if not specified or empty.
END
exit $OCF_SUCCESS
}
#######################################################################
###
#Check if a process with given PID is running
# Parameter 1: PID
###
isRunning_PID()
{
kill -s 0 "$1" > /dev/null 2>&1
}
###
#Check if an instance with given command line is running
# Parameter 1: command line.
###
isRunning_cmd()
{
pkill -s 0 "$1" > /dev/null 2>&1
}
###
# Formats the result of a command.
#
# Parameter 1: Exit status.
# Parameter 2: Standard output (stdout).
# Parameter 3: Error output (stderr).
# Returns: Formatted result.
kamailio_format_result() {
local exitstatus="$1"
local value="$2"
local error="$3"
echo -n "exit status: ${exitstatus}"
if [ -n "$value" ]; then
echo -n ", value: ${value}"
fi
if [ -n "$error" ]; then
echo -n ", error: ${error}"
fi
echo
}
###
# Put the command line, how the kamailio process is started according
# to the configured parameters, into the variable "kam_cmd".
###
kamailio_cmd()
{
case ${OCF_RESKEY_proto} in
udp) listen_param="-T -l udp:${OCF_RESKEY_listen_address}:${OCF_RESKEY_port} -l udp:127.0.0.1:${OCF_RESKEY_port}"
;;
tcp) listen_param="-l tcp:${OCF_RESKEY_listen_address}:${OCF_RESKEY_port} -l tcp:127.0.0.1:${OCF_RESKEY_port}"
;;
udptcp) listen_param1="-l udp:${OCF_RESKEY_listen_address}:${OCF_RESKEY_port} -l udp:127.0.0.1:${OCF_RESKEY_port}"
listen_param2="-l tcp:${OCF_RESKEY_listen_address}:${OCF_RESKEY_port} -l tcp:127.0.0.1:${OCF_RESKEY_port}"
listen_param="${listen_param1} ${listen_param2}"
;;
conf_*)
# doing nothing, no listen_param set
;;
*) listen_param="-T"
;;
esac
kam_cmd="${OCF_RESKEY_binary} -P ${OCF_RESKEY_pidfile} -f ${OCF_RESKEY_conffile}"
if [ -n "${listen_param}" ]; then
kam_cmd="${kam_cmd} ${listen_param}"
fi
if [ -n "${OCF_RESKEY_kamuser}" ]; then
kam_cmd="${kam_cmd} -u ${OCF_RESKEY_kamuser}"
fi
if [ -n "${OCF_RESKEY_kamgroup}" ]; then
kam_cmd="${kam_cmd} -g ${OCF_RESKEY_kamgroup}"
fi
if [ -n "${OCF_RESKEY_extra_options}" ]; then
kam_cmd="${kam_cmd} ${OCF_RESKEY_extra_options}"
fi
}
###
# Gets the PID for the running Kamailio instance.
#
# Returns: The variable $PID contains the found PID value or an empty string.
# Exit Status: Zero if the PID file was found and this process run under
# the command line parameters of our instance.
# 1) if the PID file is not present and no process running under
# our command line options is active.
# 2) in all other fatal cases, which we classify in the followig
# as OCF_ERR_genering. These are folloing cases:
# a) The PID file contains a PID value which does no match to
# to our instance
# b) The PID contains a empty string in its first line
# c) The PID file contains some text and some processeses
# from our instance are still active
kamailio_get_pid() {
if [ -f ${OCF_RESKEY_pidfile} ]; then
PID=`head -n 1 $OCF_RESKEY_pidfile`
if [ ! -z "$PID" ]; then
#Cross check if the PID file really contains a process of our kamailio instance:
kamailio_cmd
CROSSPID=`pgrep -o -f "${kam_cmd}"`
if [ x"$PID" == x"$CROSSPID" ]; then
#ocf_log debug "Found kamailio process PID with value: $PID."
return 0
fi
#ocf_log debug "PID file does not contain a PID of a $OCF_RESKEY_binary process!"
return 2
fi
#PID file does not contain a valid PID
rm -f ${OCF_RESKEY_pidfile}
return 2
fi
# No PID file found!
# Check if still a process exists even though we don't have the PID any longer:
kamailio_cmd
pgrep -f "${kam_cmd}"
if [ $? -eq 0 ]; then
ocf_log info "PID file does not contain a valid PID, but kamailio process is still active"
return 2
fi
ocf_log info "No PID file found and our kamailio instance is not active"
return 1
}
kamailio_status() {
local not_running_log_level="warn"
local errorfile error output
if [ "$__OCF_ACTION" = "start" ]; then
not_running_log_level="debug"
fi
kamailio_get_pid >/dev/null
RET=$?
if [ $RET -ne 0 ]; then
if [ $RET -eq 2 ]; then
ocf_log $not_running_log_level "PID file does not contain a PID of a ${OCF_RESKEY_binary} process!"
return $OCF_ERR_GENERIC
fi
return $OCF_NOT_RUNNING
fi
PID=`head -n 1 $OCF_RESKEY_pidfile`
isRunning_PID "$PID"
RET=$?
if [ "$RET" -ne 0 ]; then
ocf_log $not_running_log_level "PID from $PID from ${OCF_RESKEY_pidfile} not running"
rm -f ${OCF_RESKEY_pidfile}
return $OCF_NOT_RUNNING
fi
rc=0
# In case that OCF_RESKEY_kamctlrc we perfom a health check via "kamctl monitor 1"
if [ ! -z ${OCF_RESKEY_kamctlrc} ]; then
# PID is running now but it is not save to check via kamctl without care, because
# the implementation analysis in the case that we kill all running processes
# shows that in case that the fifo cannot be read, then kamctl blocks. This needs
# to be avoided.
# In order to be on the safe side, we run this check therefore under "timeout" control:
rc=1
timeout 3 ${OCF_RESKEY_kamctl} monitor 1 |grep "since" ; rc=$?
fi
if [ $rc -ne 0 ]; then
ocf_log $not_running_log_level "Kamailio is not up according to kamctl monitor!"
return $OCF_NOT_RUNNING
fi
errorfile=`mktemp`
case ${OCF_RESKEY_proto} in
udp) output=`$OCF_RESKEY_sipsak -s sip:monitor@$OCF_RESKEY_monitoring_ip:${OCF_RESKEY_port} -H localhost --transport udp>/dev/null 2>>$errorfile`
result=$?
;;
tcp) output=`$OCF_RESKEY_sipsak -s sip:monitor@$OCF_RESKEY_monitoring_ip:${OCF_RESKEY_port} -H localhost --transport tcp>/dev/null 2>>$errorfile`
result=$?
;;
udptcp) output=`$OCF_RESKEY_sipsak -s sip:monitor@$OCF_RESKEY_monitoring_ip:${OCF_RESKEY_port} -H localhost --transport tcp>/dev/null 2>>$errorfile`
result=$?
if [ $result -eq 0 ]; then
output=`$OCF_RESKEY_sipsak -s sip:monitor@$OCF_RESKEY_monitoring_ip:${OCF_RESKEY_port} -H localhost --transport udp>/dev/null 2>>$errorfile`
result=$?
fi
;;
*) output=`$OCF_RESKEY_sipsak -s sip:monitor@$OCF_RESKEY_monitoring_ip:${OCF_RESKEY_port} -H localhost --transport udp>/dev/null 2>>$errorfile`
result=$?
;;
esac
error=`cat $errorfile`
rm -f $errorfile
if [ $result -ne 0 ]; then
ocf_log $not_running_log_level "Kamailio is running, but not functional as sipsak ${OCF_RESKEY_proto} failed with $(kamailio_format_result $result "$output" "$error")"
return $OCF_ERR_GENERIC
fi
return $OCF_SUCCESS
}
kamailio_monitor() {
kamailio_status
}
kamailio_start() {
local errorfile error output piddir
if
kamailio_status
then
ocf_log info "kamailio already running."
return $OCF_SUCCESS
fi
# if pidfile directory does not exist, create it with kamailio process owner
piddir=`dirname "${OCF_RESKEY_pidfile}"`
if [ ! -d "$piddir" ]; then
mkdir -p "$piddir"
if [ "$OCF_RESKEY_kamuser" != "" ]; then
chown ${OCF_RESKEY_kamuser} "$piddir"
fi
fi
kamailio_cmd
if [ "$OCF_RESKEY_kamuser" != "" ]; then
kam_cmd="su -s /bin/bash $OCF_RESKEY_kamuser -c \"$kam_cmd\""
fi
ocf_log info "start kamailio with $kam_cmd."
errorfile=`mktemp`
output=$(eval ${kam_cmd} 2>>$errorfile)
result=$?
error=`cat $errorfile`
rm -f $errorfile
if [ $result -eq 0 ]; then
result=1
while [ $result -ne 0 ]; do
sleep 1
kamailio_get_pid >/dev/null
result=$?
done
ocf_log info "kamailio instance PID=$PID started."
# check with monitor operation if running correctly
result=$OCF_ERR_GENERIC
while [ $result -ne $OCF_SUCCESS ]; do
sleep 1
kamailio_monitor
result=$?
ocf_log info "monitor in start returned $result"
done
ocf_log info "kamailio started successful."
else
ocf_log err "kamailio instance could not be started, $(kamailio_format_result $result "$output" "$error")"
result=$OCF_ERR_GENERIC
fi
return $result
}
kamailio_stop() {
local piddir
local TRIES=0
result=$OCF_SUCCESS
kamailio_cmd
ocf_log info "Stopping kamailio by sending SIGTERM to ${kam_cmd}"
pkill -SIGTERM -x -f "${kam_cmd}"
if [ $? -eq 1 ]; then
# already stopped. no processes found
# in case of not specified pidfile, delete the created directory
# otherwise only the pidfile itself
if [ "${OCF_RESKEY_pidfile}" == "${RESKEY_pidfile_default}" ]; then
piddir=`dirname "${OCF_RESKEY_pidfile}"`
rm -rf "$piddir"
else
rm -f "${OCF_RESKEY_pidfile}"
fi
return $result
fi
if [ "$OCF_RESKEY_CRM_meta_timeout" != "" ]; then
KAMAILIO_STOP_TIMEOUT=$(( ($OCF_RESKEY_CRM_meta_timeout/1000) - 7 ))
else
KAMAILIO_STOP_TIMEOUT=20
fi
while isRunning_cmd "${kam_cmd}" && [ "$TRIES" -lt "${KAMAILIO_STOP_TIMEOUT}" ]
do
sleep 1
ocf_log info "kamailio ${kam_cmd} is still running after SIGTERM"
((TRIES++))
done
isRunning_cmd "${kam_cmd}"
RET=$?
if [ "$RET" -eq 0 ]; then
ocf_log info "Killing ${kam_cmd} with SIGKILL"
TRIES=0
pkill -SIGKILL -x -f "${kam_cmd}" > /dev/null 2>&1
while isRunning_cmd "${kam_cmd}" && [ "$TRIES" -lt 3 ]
do
sleep 1
ocf_log info "kamailio ${kam_cmd} is still running after SIGKILL"
((TRIES++))
done
isRunning_cmd "${kam_cmd}"
RET=$?
if [ "$RET" -eq 0 ]; then
ocf_log fatal "kamailio is still running even after SIGKILL"
result=$OCF_ERR_GENERIC
fi
else
ocf_log info "${kam_cmd} has stopped."
fi
# in case of not specified pidfile, delete the created directory
# otherwise only the pidfile itself
if [ "${OCF_RESKEY_pidfile}" == "${RESKEY_pidfile_default}" ]; then
piddir=`dirname "${OCF_RESKEY_pidfile}"`
rm -rf "$piddir"
else
rm -f "${OCF_RESKEY_pidfile}"
fi
return $result
}
kamailio_validate_all() {
# Check if kamailio configuration is valid before starting the server
if [ ! -f $OCF_RESKEY_binary ]; then
ocf_log err "File OCF_RESKEY_binary [${OCF_RESKEY_binary}] does not exist!"
return $OCF_NOT_INSTALLED
fi
out=$($OCF_RESKEY_binary -c 2>&1 > /dev/null)
retcode=$?
if [ "$retcode" -ne '0' ]; then
ocf_log info "Not starting kamailio: $OCF_RESKEY_binary does not start!"
return $OCF_ERR_CONFIGURED
fi
case $OCF_RESKEY_monitoring_ip in
"") ocf_log err "Required parameter OCF_RESKEY_monitoring_ip is missing!"
return $OCF_ERR_CONFIGURED
;;
[0-9]*.[0-9]*.[0-9]*.[0-9]*) : OK
;;
*) ocf_log err "Parameter OCF_RESKEY_monitoring_ip [$OCF_RESKEY_monitoring_ip] is not an IP address!"
return $OCF_ERR_CONFIGURED
;;
esac
case $OCF_RESKEY_listen_address in
"") ocf_log err "Required parameter $OCF_RESKEY_listen_address is missing!"
return $OCF_ERR_CONFIGURED
;;
[0-9]*.[0-9]*.[0-9]*.[0-9]*) : OK
;;
*) ocf_log err "Parameter OCF_RESKEY_listen_address [$OCF_RESKEY_listen_address] not an IP address!"
return $OCF_ERR_CONFIGURED
;;
esac
if [ ! -f ${OCF_RESKEY_sipsak} ]; then
ocf_log err "sipsak [${OCF_RESKEY_sipsak}] does not exist!"
return $OCF_NOT_INSTALLED
fi
if [ ! -z ${OCF_RESKEY_kamctlrc} ]; then
if [ ! -f ${OCF_RESKEY_kamctlrc} ]; then
ocf_log err "kamctlrc file [${kamctlrc}] does not exist!"
return $OCF_NOT_INSTALLED
fi
else
ocf_log debug "No monitoring via kamctl monitor because the parameter [kamctlrc] is empty."
fi
if [ ! -f ${OCF_RESKEY_conffile} ]; then
ocf_log err "Kamailio configuration file provided in the parameter conffile [${OCF_RESKEY_conffile}] does not exist!"
return $OCF_ERR_CONFIGURED
fi
case $OCF_RESKEY_proto in
"") ocf_log err "Parameter $OCF_RESKEY_proto is empty!"
return $OCF_ERR_CONFIGURED
;;
udp|tcp|udptcp) : OK
;;
*) ocf_log err "Parameter value $OCF_RESKEY_proto for parameter [proto] not yet supported!"
return $OCF_ERR_CONFIGURED
;;
esac
return $OCF_SUCCESS
}
if [ $# -ne 1 ]; then
usage
exit $OCF_ERR_ARGS
fi
case $__OCF_ACTION in
meta-data) meta_data
exit $OCF_SUCCESS
;;
start|stop|status|monitor)
kamailio_${__OCF_ACTION}
;;
validate-all) kamailio_validate_all
;;
notify) exit $OCF_SUCCESS
;;
usage) usage
exit $OCF_SUCCESS
;;
# reload) #Not supported by Kamailio, but not needed by pacemaker
# ;;
# recover #Not needed by pacemaker
# ;;
*) usage
exit $OCF_ERR_UNIMPLEMENTED
;;
esac
exit $?
#############################################
Kamailio KA proxy
##High Availability Cluster on Centos 7 using Corosync & Pacemaker & pcs
yum -y install corosync pacemaker pcs
yum install gdb*
systemctl enable pcsd.service
systemctl start pcsd.service
#### set the hacluster user password in both node (password must be same)
passwd hacluster
##### verify the both node are able to communicate
pcs cluster auth vm1 vm2
###### Set the VM cluster (vmserver is VM cluster name and vm1 vm2 are the node)
pcs cluster setup --name vmserver vm1 vm2
####### disable the stonith and quorum option. for 2 node, both options are not required.
pcs property set stonith-enabled=false
pcs property set no-quorum-policy=ignore
########## create the vertual IP resource
pcs resource create virtualip ocf:heartbeat:IPaddr2 ip=192.168.1.243 cidr_netmask=32 op monitor interval=30s
########## add the kamailio script in side below location
cd /usr/lib/ocf/resource.d/heartbeat/
##########create the kamailio script
pcs resource create kamailio1 ocf:heartbeat:kamailio listen_address=192.168.1.240 op monitor interval=30s
pcs constraint colocation add kamailio1 virtualip INFINITY
pcs constraint order virtualip then kamailio1
pcs cluster stop --all
pcs cluster start --all
Thursday, November 11, 2010
OpenSIPs Core functions and parameters
This section lists the all the parameters and functions exported by OpenSIPS core for script usage (to be used in opensips.cfg)
This document is for OpenSIPS 1.7.x / devel
1. Core Keywords
Keywords specific to SIP messages which can be used mainly in 'if' expressions.
1.1 af
The address family of the received SIP message. It is INET if the message was received over IPv4 or INET6 if the message was received over IPv6.
Exampe of usage:
if(af==INET6) {
log("Message received over IPv6 link\n");
};
1.2 dst_ip
The IP of the local interface where the SIP message was received. When the proxy listens on many network interfaces, makes possible to detect which was the one that received the packet.
Example of usage:
if(dst_ip==127.0.0.1) {
log("message received on loopback interface\n");
};
1.3 dst_port
The local port where the SIP packet was received. When OpenSIPS is listening on many ports, it is useful to learn which was the one that received the SIP packet.
Example of usage:
if(dst_port==5061)
{
log("message was received on port 5061\n");
};
1.4 from_uri
This script variable is a reference to the URI of 'From' header. It can be used to test 'From'- header URI value.
Example of usage:
if(is_method("INVITE") && from_uri=~".*@opensips.org")
{
log("the caller is from opensips.org\n");
};
1.5 method
The variable is a reference to the SIP method of the message.
Example of usage:
if(method=="REGISTER")
{
log("this SIP request is a REGISTER message\n");
};
1.6 msg:len
The variable is a reference to the size of the message. It can be used in 'if' constructs to test message's size.
Example of usage:
if(msg:len>2048)
{
sl_send_reply("413", "message too large");
exit;
};
1.7 $retcode
It represents the value returned by last function executed (similar to $? from bash -- if you wish, you can use also $? in OpenSIPS config, both names '$retcode' and '$?' are supported). If tested after a call of a route, it is the value retuned by that route.
Example of usage:
route {
route(1);
if($retcode==1)
{
log("The request is an INVITE\n");
};
}
route[1] {
if(is_method("INVITE"))
return(1);
return(2);
}
1.8 proto
This variable can be used to test the transport protocol of the SIP message.
Example of usage:
if(proto==UDP)
{
log("SIP message received over UDP\n");
};
1.9 status
If used in onreply_route, this variable is a reference to the status code of the reply. If it used in a standard route block, the variable is a reference to the status of the last reply sent out for the current request.
Example of usage:
if(status=="200")
{
log("this is a 200 OK reply\n");
};
1.10 src_ip
Reference to source IP address of the SIP message.
Example of usage:
if(src_ip==127.0.0.1)
{
log("the message was sent from localhost!\n");
};
1.11 src_port
Reference to source port of the SIP message (from which port the message was sent by previous hop).
Example of usage:
if(src_port==5061)
{
log("message sent from port 5061\n");
}
1.12 to_uri
This variable can be used to test the value of URI from To header.
Example of usage:
if(to_uri=~"sip:.+@opensips.org")
{
log("this is a request for opensips.org users\n");
};
1.13 uri
This variable can be used to test the value of the request URI.
Example of usage:
if(uri=~"sip:.+@opensips.org")
{
log("this is a request for opensips.org users\n");
};
2. Core Values
Values that can be used in 'if' expressions to check against Core Keywords
2.1 INET
This keyword can be used to test whether the SIP packet was received over an IPv4 connection.
Example of usage:
if(af==INET)
{
log("the SIP message was received over IPv4\n");
};
2.2 INET6
This keyword can be used to test whether the SIP packet was received over an IPv6 connection.
Example of usage:
if(af==INET6)
{
log("the SIP message was received over IPv6\n");
};
2.3 TCP
This keyword can be used to test the value of 'proto' and check whether the SIP packet was received over TCP or not.
Example of usage:
if(proto==TCP)
{
log("the SIP message was received over TCP\n");
};
2.4 UDP
This keyword can be used to test the value of 'proto' and check whether the SIP packet was received over UDP or not.
Example of usage:
if(proto==UDP)
{
log("the SIP message was received over UDP\n");
};
2.5 max_len
This keyword is set to the maximum size of an UDP packet. It can be used to test message's size.
Example of usage:
if(msg:len>max_len)
{
sl_send_reply("413", "message too large to be forwarded over UDP without fragmentation");
exit;
}
2.6 myself
It is a reference to the list of local IP addresses, hostnames and aliases that has been set in OpenSIPS configuration file. This lists contain the domains served by OpenSIPS.
The variable can be used to test if the host part of an URI is in the list. The usefulness of this test is to select the messages that has to be processed locally or has to be forwarded to another server.
See "alias" to add hostnames,IP addresses and aliases to the list.
Example of usage:
if(uri==myself) {
log("the request is for local processing\n");
};
2.7 null
Can be used in assignment to reset the value of a per-script variable or to delete an avp.
Example of usage:
$avp(i:12) = null;
$var(x) = null;
3. Core parameters
Global parameters that can be set in configuration file. Accepted values are, depending on the actual parameters strings, numbers and yes/ no. If you need to specify either "yes" or "no" as part of a string, wrap this in double quotes.
3.1 advertised_address
It can be an IP address or string and represents the address advertised in Via header and
other destination lumps (e.g RR header). If empty or not set (default value) the socket
address from where the request will be sent is used.
WARNING:
- don't set it unless you know what you are doing (e.g. nat traversal)
- you can set anything here, no check is made (e.g. foo.bar will be
accepted even if foo.bar doesn't exist)
Example of usage:
advertised_address="opensips.org"
3.2 advertised_port
The port advertised in Via header and other destination lumps (e.g. RR). If empty or not set (default value) the port from where the message will be sent is used. Same warnings as for 'advertised_address'.
Example of usage:
advertised_port=5080
3.3 alias
Parameter to set alias hostnames for the server. It can be set many times, each value being added in a list to match the hostname when 'myself' is checked.
It is necessary to include the port (the port value used in the "port=" or "listen=" definitions) in the alias definition otherwise the loose_route() function will not work as expected for local forwards
Example of usage:
alias=other.domain.com:5060
alias=another.domain.com:5060
3.4 avp_aliases
Contains a multiple definition of aliases for AVP names.
Example of usage:
avp_aliases="uuid=I:660;email=s:email_addr;fwd=i:753"
3.5 auto_aliases
This parameter controls if aliases should be automatically discovered and added during fixing listening sockets. The auto discovered aliases are result of the DNS lookup (if listen is a name and not IP) or of a reverse DNS lookup on the listen IP.
Far backward compatibility reasons, the default value is "on".
Example of usage:
auto_aliases=no
auto_aliases=0
3.6 check_via
Check if the address in top most via of replies is local. Default value is 0 (check disabled).
Example of usage:
check_via=1
3.7 children
Number of children to fork for the UDP interfaces (one set for each interface - ip:port). Default value is 8.
Example of usage:
children=16
3.8 chroot
The value must be a valid path in the system. If set, OpenSIPS will chroot (change root directory) to its value.
Example of usage:
chroot=/other/fakeroot
3.9 db_version_table
The name of the table version to be used by the DB API to check the version of the used tables.
Default value is "version"
Example of usage:
db_version_table="version_1_5"
3.10 debug
Set the debug level. Higher values make OpenSIPS to print more debug messages.
Examples of usage:
debug=3 -- print only important messages (like errors or more critical situations)
- recommended for running proxy as daemon
debug=9 -- print a lot of debug messages - use it only when doing debugging sessions
The 'debug' parameter is usually used in concordance with 'log_stderror' parameter.
Value of 'debug' parameter can also be get and set dynamically using 'debug' Core MI function.
For more see: http://www.voice-system.ro/docs/ser-syslog/
3.11 disable_503_translation
If 'yes', OpenSIPS will not translate the received 503 replies into 500 replies (RFC 3261 clearly states that a proxy should never relay a 503 response, but instead it must transform it into a 500).
Default value is 'no' (do translation).
3.12 disable_core_dump
Can be 'yes' or 'no'. By default core dump limits are set to unlimited or
a high enough value. Set this config variable to 'yes' to disable core dump-ing
(will set core limits to 0).
Default value is 'no'.
Example of usage:
disable_core_dump=yes
3.13 disable_dns_blacklist
The DNS resolver, when configured with failover, can automatically store in a temporary blacklist the failed destinations. This will prevent (for a limited period of time) OpenSIPS to send requests to destination known as failed. So, the blacklist can be used as a memory for the DNS resolver.
The temporary blacklist created by DNS resolver is named "dns" and it is by default selected for usage (no need use the use_blacklist()) function. The rules from this list have a life time of 4 minutes - you can change it at compile time, from blacklists.h .
Can be 'yes' or 'no'. By default the blacklist is disabled (Default value is 'yes').
Example of usage:
disable_dns_blacklist=no
3.14 disable_dns_failover
Can be 'yes' or 'no'. By default DNS-based failover is enabled. Set this config variable to 'yes' to disable the DNS-based failover. This is a global option, affecting the core and the modules also.
Default value is 'no'.
Example of usage:
disable_dns_failover=yes
3.15 disable_stateless_fwd
Can be 'yes' or 'no'. This parameter controls the handling of stateless replies:
yes - drop stateless replies if stateless fwd functions (like forward) are not used in script
no - forward stateless replies
Default value is 'yes'.
3.16 disable_tcp
Global parameter to disable TCP support in the SIP server. Default value is 'no'.
Example of usage:
disable_tcp=yes
3.17 disable_tls
Global parameter to disable TLS support in the SIP server. Default value is 'yes'.
Example of usage:
disable_tcp=no
3.18 dns
This parameter controls if the SIP server should attempt to lookup its own domain name in DNS. If this parameter is set to yes and the domain name is not in DNS a warning is printed on syslog and a "received=" field is added to the via header.
Default is no.
3.19 dns_retr_time
Time in seconds before retrying a dns request. Default value is system specific,
depends also on the '/etc/resolv.conf' content (usually 5s).
Example of usage:
dns_retr_time=3
3.20 dns_retr_no
Number of dns retransmissions before giving up. Default value is system specific,
depends also on the '/etc/resolv.conf' content (usually 4).
Example of usage:
dns_retr_no=3
3.21 dns_servers_no
How many dns servers from the ones defined in '/etc/resolv.conf' will be used.
Default value is to use all of them.
Example of usage:
dns_servers_no=2
3.22 dns_try_ipv6
Can be 'yes' or 'no'. If it is set to 'yes' and a DNS lookup fails, it will retry it
for ipv6 (AAAA record). Default value is 'no'.
Example of usage:
dns_try_ipv6=yes
3.23 dns_use_search_list
Can be 'yes' or 'no'. If set to 'no', the search list in '/etc/resolv.conf'
will be ignored (=> fewer lookups => gives up faster). Default value is 'yes'.
HINT: even if you don't have a search list defined, setting this option
to 'no' will still be "faster", because an empty search list is in
fact search "" (so even if the search list is empty/missing there will
still be 2 dns queries, eg. foo+'.' and foo+""+'.')
Example of usage:
dns_use_search_list=no
3.24 dst_blacklist
Definition of a static (read-only) IP/destination blacklist. These lists can be selected from script (at runtime) to filter the outgoing requests, based on IP, protocol, port, etc.
Its primary purposes will be to prevent sending requests to critical IPs (like GWs) due DNS or to avoid sending to destinations that are known to be unavailable (temporary or permanent).
Example of usage:
# filter out requests going to ips of my gws
dst_blacklist = gw:{( tcp , 192.168.2.100 , 5060 , "" ),( any , 192.168.2.101 , 0 , "" )}
# block requests going to "evil" networks
dst_blacklist = net_filter:{ ( any , 192.168.1.100/255.255.255.0 , 0 , "" )}
# block message requests with nasty words
dst_blacklist = msg_filter:{ ( any , 192.168.20.0/255.255.255.0 , 0 , "MESSAGE*ugly_word" )}
# block requests not going to a specific subnet
dst_blacklist = net_filter2:{ !( any , 192.168.30.0/255.255.255.0 , 0 , "" )}
Each rule is defined by:
- protocol : TCP, UDP, TLS or "any" for anything
- port : number or 0 for any
- ip/mask
- test patter - is a filename like matching (see "man 3 fnmatch") applied on the outgoing request buffer (first_line+hdrs+body)
3.25 fork
If set to 'yes' the proxy will fork and run in daemon mode - one process will be created for each network interface the proxy listens to and for each protocol (TCP/UDP), multiplied with the value of 'children' parameter.
When set to 'no', the proxy will stay bound to the terminal and runs as single process. First interface is used for listening to.
Default value is 'yes'.
Example of usage:
fork=no
3.26 group gid
The group id to run OpenSIPS.
Example of usage:
group="opensips"
3.27 listen
Set the network addresses the SIP server should listen to. It can be an IP address, hostname or network interface id or combination of protocol:address:port (e.g., udp:10.10.10.10:5060). This parameter can be set multiple times in same configuration file, the server listening on all addresses specified.
Example of usage:
listen=10.10.10.10
listen=eth1:5062
listen=udp:10.10.10.10:5064
If you omit this directive then the SIP server will listen on all interfaces. On start the SIP server reports all the interfaces that it is listening on. Even if you specify only UDP interfaces here, the server will start the TCP engine too. If you don't want this, you need to disable the TCP support completely with the core parameter disable_tcp.
3.28 log_facility
If OpenSIPS logs to syslog, you can control the facility for logging. Very
useful when you want to divert all OpenSIPS logs to a different log file.
See the man page syslog(3) for more details.
For more see: http://www.voice-system.ro/docs/ser-syslog/
Default value is LOG_DAEMON.
Example of usage:
log_facility=LOG_LOCAL0
3.29 log_name
Set the id to be printed in syslog. The value must be a string and has
effect only when OpenSIPS runs in daemon mode (fork=yes), after daemonize.
Default value is argv[0].
Example of usage:
log_name="osips-5070"
3.30 log_stderror
With this parameter you can make OpenSIPS to write log and debug messages to standard error. Possible values are:
- "yes" - write the messages to standard error
- "no" - write the messages to syslog
Default value is "no".
For more see: http://www.voice-system.ro/docs/ser-syslog/
Example of usage:
log_stderror=yes
3.31 max_while_loops
The parameters set the value of maximum loops that can be done within a "while". Comes as a protection to avoid infinite loops in config file execution. Default is 100.
Example of usage:
max_while_loops=200
3.32 maxbuffer
The size in bytes not to be exceeded during the auto-probing procedure of discovering the maximum buffer size for receiving UDP messages. Default value is 262144.
Example of usage:
maxbuffer=65536
3.33 memdump | mem_dump
Log level to print memory status information (runtime and shutdown). It has to be less than the value of 'debug' parameter if you want memory info to be logged. Default: memdump=L_DBG (4)
Example of usage:
memdump=2
NOTE that setting memlog (see below), will also set the memdump parameter - if you want different values for memlog and memdump, you need to first set memlog and then memdump.
3.34 memlog | mem_log
Log level to print memory debug info. It has to be less than the value of 'debug' parameter if you want memory info to be logged. Default: memlog=L_DBG (4)
Example of usage:
memlog=2
NOTE: by setting memlog parameter, the memdump will automatically be set to the same value (see memdump docs).
3.35 mcast_loopback
It can be 'yes' or 'no'. If set to 'yes', multicast datagram are sent over loopback. Default value is 'no'.
Example of usage:
mcast_loopback=yes
3.36 mcast_ttl
Set the value for multicast ttl. Default value is OS specific (usually 1).
Example of usage:
mcast_ttl=32
3.37 mhomed
Set the server to try to locate outbound interface on multihomed host. By default is not (0) - it is rather time consuming.
Example of usage:
mhomed=1
3.38 mpath
Set the module search path. This can be used to simplify the loadmodule parameter
Example of usage:
mpath="/usr/local/lib/opensips/modules"
loadmodule "mysql.so"
loadmodule "uri.so"
loadmodule "uri_db.so"
loadmodule "sl.so"
loadmodule "tm.so"
...
3.39 open_files_limit
If set and bigger than the current open file limit, OpenSIPS will try
to increase its open file limit to this number. Note: OpenSIPS must be
started as root to be able to increase a limit past the hard limit
(which, for open files, is 1024 on most systems).
Example of usage:
open_files_limit=2048
3.40 port
The port the SIP server listens to. The default value for it is 5060.
Example of usage:
port=5080
3.41 reply_to_via
If it is set to 1, any local reply is sent to the address advertised in top most Via of the request. Default value is 0 (off).
Example of usage:
reply_to_via=0
3.42 rev_dns
This parameter controls if the SIP server should attempt to lookup its own IP address in DNS. If this parameter is set to yes and the IP address is not in DNS a warning is printed on syslog and a "received=" field is added to the via header.
Default is no.
3.43 server_header
The body of Server header field generated by OpenSIPS when it sends a request as UAS. It defaults to "OpenSIPS (<version> (<arch>/<os>))".
Example of usage:
server_header="Server: My Company SIP Proxy"
Please note that you have to add the header name "Server:", otherwise OpenSIPS will just write a header like:
My Company SIP Proxy
3.44 server_signature
This parameter controls the "Server" header in any locally generated message.
Example of usage:
server_signature=no
If it is enabled (default=yes) a header is generated as in the following example:
Server: OpenSIPS (0.9.5 (i386/linux))
3.45 sip_warning
Can be 0 or 1. If set to 1 (default value is 0) a 'Warning' header is added to each reply generated by OpenSIPS.
The header contains several details that help troubleshooting using the network traffic dumps.
Example of usage:
sip_warning=0
3.46 tcp_children
Number of children processes to be created for reading from TCP connections. If no value is explicitly set, the same number of TCP children as UDP children (see "children" parameter) will be used.
Example of usage:
tcp_children=4
3.47 tcp_accept_aliases
3.48 tcp_send_timeout
Time in seconds after a TCP connection will be closed if it is not available
for writing in this interval (and OpenSIPS wants to send something on it).
Example of usage:
tcp_send_timeout=3
3.49 tcp_connect_timeout
Time in seconds before an ongoing attempt to connect will be aborted.
Example of usage:
tcp_connect_timeout=5
3.50 tcp_connection_lifetime!!!!
Lifetime in seconds for TCP sessions. TCP sessions which are inactive for >tcp_connection_lifetime will be closed by OpenSIPS. Default value is defined in tcp_conn.h: #define DEFAULT_TCP_CONNECTION_LIFETIME 120. Setting this value to 0 will close the TCP connection pretty quick ;-). You can also set the TCP lifetime to the expire value of the REGISTER by using the tcp_persistent_flag parameter of the registrar module.
Example of usage:
tcp_connection_lifetime=3600
3.51 tcp_max_connections
maximum number of tcp connections (if the number is exceeded no new tcp connections will be accepted). Default is defined in tcp_conn.h: #define DEFAULT_TCP_MAX_CONNECTIONS 2048
Example of usage:
tcp_max_connections=4096
3.52 tcp_poll_method
poll method used (by default the best one for the current OS is selected). For available types see io_wait.c and poll_types.h: none, poll, epoll_lt, epoll_et, sigio_rt, select, kqueue, /dev/poll
Example of usage:
tcp_poll_method=select
3.53 tls_ca_list
3.54 tls_certificate
3.55 tls_ciphers_list
3.56 tls_domain
3.57 tls_handshake_timeout
3.58 tls_log
3.59 tls_method
3.60 tls_port_no
3.61 tls_private_key
3.62 tls_require_certificate
3.63 tls_send_timeout
3.64 tls_verify
3.65 tos
The TOS (Type Of Service) to be used for the sent IP packages (both TCP and UDP).
Example of usage:
tos=IPTOS_LOWDELAY
tos=0x10
tos=IPTOS_RELIABILITY
3.66 user uid
The user id to run OpenSIPS (OpenSIPS will suid to it).
Example of usage:
user="opensips"
3.67 user_agent_header
The body of User-Agent header field generated by OpenSIPS when it sends a request as UAC. It defaults to "OpenSIPS (<version> (<arch>/<os>))".
Example of usage:
user_agent_header="User-Agent: My Company SIP Proxy"
Please note that you have to include the header name "User-Agent:" as OpenSIPS does not add it and you will get an erroneous header like:
My Company SIP Proxy
3.68 wdir
The working directory used by OpenSIPS at runtime. You might find it usefull when come to generating core files :)
Example of usage:
wdir="/usr/local/opensips"
or
wdir=/usr/opensips_wd
4. Core Functions
Functions exported by core that can be used in route blocks.
4.1 add_local_rport()
Add 'rport' parameter to the Via header generated by server (see RFC3581 for its meaning). It affects only the current processed request.
Example of usage:
add_local_rport()
4.2 append_branch()
Similarly to t_fork_to, it extends destination set by a new entry. The difference is that current URI is taken as new entry.
Without parameter, the function copies the current URI into a new branch. Thus, leaving the main branch (the URI) for further manipulation.
With a parameter, the function copies the URI in the parameter into a new branch. Thus, the current URI is not manipulated.
Note that it's not possible to append a new branch in "on_failure_route" block if a 6XX response has been previously received (it would be against RFC 3261).
Example of usage:
# if someone calls B, the call should be forwarded to C too.
#
if (method=="INVITE" && uri=~"sip:B@xx.xxx.xx ")
{
# copy the current branch (branches[0]) into
# a new branch (branches[1])
append_branch();
# all URI manipulation functions work on branches[0]
# thus, URI manipulation does not touch the
# appended branch (branches[1])
seturi("sip:C@domain");
# now: branch 0 = C@domain
# branch 1 = B@xx.xx.xx.xx
# and if you need a third destination ...
# copy the current branch (branches[0]) into
# a new branch (branches[2])
append_branch();
# all URI manipulation functions work on branches[0]
# thus, URI manipulation does not touch the
# appended branch (branches[1-2])
seturi("sip:D@domain");
# now: branch 0 = D@domain
# branch 1 = B@xx.xx.xx.xx
# branch 2 = C@domain
t_relay();
exit;
};
# You could also use append_branch("sip:C@domain") which adds a branch with the new URI:
if(method=="INVITE" && uri=~"sip:B@xx.xxx.xx ") {
# append a new branch with the second destination
append_branch("sip:user@domain");
# now: branch 0 = B@xx.xx.xx.xx
# now: branch 1 = C@domain
t_relay();
exit;
}
4.3 cache_store( storage_id, attribute_name, attribute_name [,timeout])
This sets in a memory-cache-like-storage system a new value for an attribute. Both the attribute name and value may contain pseudo-variables. If the attribute does not already exist in the memcache, it will be inserted with the given value; if already present, its value will be replaced with the new one. The function may optionally take an extra parameter, a timeout (or lifetime) value for the attribute - after the lifetime is exceeded, the attribute is automatically purged from memcache.
As these functions (memcache) are just part of a generic memcache interface, you need to specify what memcache implementation you want to use via this command -> the storage_id points the memcache implementation. Currently there is only one available, "local", provided by the localcache module.
Function returns true is the new attribute was successfully inserted.
cache_store("local","my_attr","$avp(i:55)",1200);
cache_store("local","passwd_$tu","$var(x)");
A more complex example can be found in the MemCache Tutorial.
4.4 cache_remove( storage_id, attribute_name)
This removes an attribute from a memory-cache-like-storage system. The attribute name may contain pseudo-variables.
As these functions (memcache) are just part of a generic memcache interface, you need to specify what memcache implementation you want to use via this command -> the storage_id points the memcache implementation. Currently there is only one available, "local", provided by the localcache module.
Function returns false only if the storage_id is invalid.
cache_remove("local","my_attr");
cache_remove("local","passwd_$tu");
A more complex example can be found in the MemCache Tutorial.
4.5 cache_fetch( storage_id, attribute_name, result_avp)
This function fetches from a memory-cache-like-storage system the value of an attribute. The attribute name may contain pseudo-variables. The result (if any) will be stored in the result_avp AVP variable.
As these functions (memcache) are just part of a generic memcache interface, you need to specify what memcache implementation you want to use via this command -> the storage_id points the memcache implementation. Currently there is only one available, "local", provided by the localcache module.
Function returns true if the attribute was found and its value returned.
cache_fetch("local","my_attr", $avp(i:11) );
cache_fetch("local","passwd_$tu", $var(x) );
A more complex example can be found in the MemCache Tutorial.
4.6 break()
Since v0.10.0-dev3, 'break' can no longer be used to stop the execution of a route. The only place to use is to end a 'case' block in a 'switch' statement. 'return' must be now used instead of old 'break'.
'return' and 'break' have now a similar meaning as in c/shell.
4.7 construct_uri(proto,user,domain,port,extra,result_avp)
The function builds a valid sip uri based on the arguments it receives. The result (if any) will be stored in the result_avp AVP variable.
The function accepts plain text arguments, as well as $var and $avp variables. If you want to omit a part of the sip uri, just set the respective parameter to a blank string.
Example usage:
construct_uri("$var(proto)", "vlad", "$var(domain)", "", "$var(params)",$avp(s:newuri));
xlog("Constructed URI is <$avp(s:newuri)> \n");
4.8 drop()
Stop the execution of the configuration script and alter the implicit action which is done afterwards.
If the function is called in a 'branch_route' then the branch is discarded (implicit action for 'branch_route' is to forward the request).
If the function is called in a 'onreply_route' then any provisional reply is discarded (implicit action for 'onreply_route' is to send the reply upstream according to Via header).
Example of usage:
onreply_route {
if(status=="183") {
drop();
}
}
4.9 exit()
Stop the execution of the configuration script -- it has the same behaviour as return(0). It does not affect the implicit action to be taken after script execution.
route {
if (route(2)) {
xlog("L_NOTICE","method $rm is INVITE\n");
} else {
xlog("L_NOTICE","method is $rm\n");
};
}
route[2] {
if (is_method("INVITE")) {
return(1);
} else if (is_method("REGISTER")) {
return(-1);
} else if (is_method("MESSAGE")) {
sl_send_reply("403","IM not allowed");
exit;
};
}
4.10 force_rport()
Force_rport() adds the rport parameter to the first Via header. Thus, OpenSIPS will add the received IP port to the top most via header in the SIP message, even if the client does not indicate support for rport. This enables subsequent SIP messages to return to the proper port later on in a SIP transaction.
The rport parameter is defined in RFC 3581.
Example of usage:
force_rport();
4.11 force_send_socket([proto:]address[:port])
Force OpenSIPS to send the message from the specified socket (it _must_ be one of the sockets OpenSIPS listens on). If the protocol doesn't match (e.g. UDP message "forced" to a TCP socket) the closest socket of the same protocol is used.
Example of usage:
force_send_socket(10.10.10.10:5060);
4.12 force_tcp_alias()
force_tcp_alias(port)
adds a tcp port alias for the current connection (if tcp).
Usefull if you want to send all the trafic to port_alias through
the same connection this request came from [it could help
for firewall or nat traversal].
With no parameters adds the port from the message via as the alias.
When the "aliased" connection is closed (e.g. it's idle for too
much time), all the port aliases are removed.
4.13 forward(destination)
Forward the SIP request to the given destination in stateless mode. This has the format of [proto:]host[:port]. Host can be an IP or hostname; supported protocols are UDP, TCP and TLS. (For TLS, you need to compile the TLS support into core).
If proto or port are not specified, NAPTR and SRV lookups will be used to determine them (if possible).
If destination parameter is missing, the forward will be done based on RURI.
Example of usage:
forward("10.0.0.10:5060");
#or
forward();
4.14 isdsturiset()
Test if the dst_uri field (next hop address) is set.
Example of usage:
if(isdsturiset()) {
log("dst_uri is set\n");
};
4.15 isflagset(int)
Test if a flag is set for current processed message (if the flag value is 1). The value of the parameter can be in range of 0..31.
For more see http://www.voice-system.ro/docs/ser-flags/ or Flags Documentation.
Example of usage:
if(isflagset(3)) {
log("flag 3 is set\n");
};
4.16 isbflagset([branch_idx,] flag_idx)
Test if a flag is set for a specific branch (if the flag value is 1). The value of the "flag_idx" parameter can be in range of 0..31. "branch_idx" identify the branch for which the flags are tested - it must be a positiv number. Branch index 0 refers to the RURI branch. If this parameter is missing, 0 branch index is used as default.
For more about script flags, see Flags Documentation.
Example of usage:
if(isbflagset(1,3)) {
log("flag 3 is set in branch 1\n");
};
4.17 issflagset(flag_idx)
Test if a script flag is set (if the flag value is 1). The value of the "flag_idx" parameter can be in range of 0..31.
For more about script flags, see Flags Documentation.
Example of usage:
if(issflagset(2)) {
log("script flag 2 is set\n");
};
4.18 log([level,] string)
Write text message to standard error terminal or syslog. You can specify the log level as first parameter.
For more see: http://www.voice-system.ro/docs/ser-syslog/
Example of usage:
log("just some text message\n");
4.19 next_branches()
Adds to the request a new destination set that includes all highest priority class contacts ('q' value based) from the serialized branches (see serialize_branches()). If called from a route block, it rewrites the request uri with first contact and adds the remaining contacts as parallel branches. If called from failure route block, adds all contacts as parallel branches. All used
contacts are removes the serialized branches.
Returns true if at least one contact was added for the request's destination set - returns 1 if other branches are still pending and return 2 if no other branches are left for future processing - shortly, if 2: this is the last branch, if 1: other will follow. False is return is nothing was done (no more serialized branches).
Example of usage:
next_branches();
4.20 prefix(string)
Add the string parameter in front of username in R-URI.
Example of usage:
prefix("00");
4.21 pv_printf(pv, string)
Prints the formatted 'string' in the AVP 'pv'. The 'string' parameter can include any pseudo-variable defined in OpenSIPS. The 'pv' can be any writable pseudo-variable -- e.g.,: AVPs, VARs, $ru, $rU, $rd, $du, $br, $fs.
It was extended from the avp_printf(...) function exported in previous versions by the avpops module. Starting with 1.3.0, avp_printf(...) is just an alias to pv_printf(...).
Example of usage:
pv_printf("$var(x)", "r-uri: $ru");
pv_printf("$avp(i:3)", "from uri: $fu");
4.22 return(int)
The return() function allows you to return any integer value from a called route() block.
You can test the value returned by a route using "$retcode" variable.
return(0) is same as "exit()";
In bool expressions:
* Negative and ZERO is FALSE
* Positive is TRUE
Example usage:
route {
if (route(2)) {
xlog("L_NOTICE","method $rm is INVITE\n");
} else {
xlog("L_NOTICE","method $rm is REGISTER\n");
};
}
route[2] {
if (is_method("INVITE")) {
return(1);
} else if (is_method("REGISTER")) {
return(-1);
} else {
return(0);
};
}
4.23 resetdsturi()
Set the value of dst_uri filed to NULL. dst_uri field is usually set after loose_route() or lookup("location") if the contact address is behind a NAT.
Example of usage:
resetdsturi();
4.24 resetflag(int)
Reset a flag for current processed message (set the value to 0). The value of the parameter can be in range of 0..31.
For more see http://www.voice-system.ro/docs/ser-flags/ or Flags Documentation.
Example of usage:
resetflag(3);
4.25 resetbflag([branch_idx,] flag_idx)
Reset a flag for a specific branch (set flag to value 0). The value of the "flag_idx" parameter can be in range of 0..31. "branch_idx" identify the branch for which the flag is reset - it must be a positiv number. Branch index 0 refers to the RURI branch. If this parameter is missing, 0 branch index is used as default.
For more about script flags, see Flags Documentation.
Example of usage:
resetbflag(1,3);
# or
resetbflag(3); # same with resetbflag(0,3)
4.26 resetsflag(flag_idx)
Reset a script flag (set flag to value 0). The value of the "flag_idx" parameter can be in range of 0..31.
For more about script flags, see Flags Documentation.
Example of usage:
resetsflag(2);
4.27 revert_uri()
Set the R-URI to the value of the R-URI as it was when the request was received by server (undo all changes of R-URI).
Example of usage:
revert_uri();
4.28 rewritehost() / sethost()
Rewrite the domain part of the R-URI with the value of function's parameter. Other parts of the R-URI like username, port and URI parameters remain unchanged.
Example of usage:
rewritehost("1.2.3.4");
4.29 rewritehostport() / sethostport()
Rewrite the domain part and port of the R-URI with the value of function's parameter. Other parts of the R-URI like username and URI parameters remain unchanged.
Example of usage:
rewritehostport("1.2.3.4:5080");
4.30 rewriteuser(string) / setuser(string)
Rewrite the user part of the R-URI with the value of function's parameter.
Example of usage:
rewriteuser("newuser");
4.31 rewriteuserpass() / setuserpass()
Rewrite the password part of the R-URI with the value of function's parameter.
Example of usage:
rewriteuserpass("my_secret_passwd");
4.32 rewriteport() / setport()
Rewrites/sets the port part of the R-URI with the value of function's parameter.
Example of usage:
rewriteport("5070");
4.33 rewriteuri(str) / seturi(str)
Rewrite the request URI.
Example of usage:
rewriteuri("sip:test@opensips.org");
4.34 send(destination)
Send the original SIP message to a specific destination in stateless mode. This is definied as [proto:]host[:port]. No changes are applied to received message, no Via header is added. Host can be an IP or hostname; supported protocols are UDP, TCP and TLS. (For TLS, you need to compile the TLS support into core). If proto or port are not specified, NAPTR and SRV lookups will be used to determine them (if possible).
Parameter is mandatory and has string format.
Example of usage:
send("udp:10.10.10.10:5070");
4.35 serialize_branches(clear)
Takes all the branches added for parallel forking (with append_branch() and including the current RURI) and prepare them for serial forking. The ordering is done in increasing "q" order. The serialized branches are internally stored in AVPs - you will be able to fetch and use via the "next_branches()" function.
NOTE that (according to RFC3261), the branches with the same "q" value will still be parallel forked during a certain step in the serial forking (it will result a combination of serial with parallel forking).
NOTE that this function is not changing RURI in the messages - it is just converting from parallel to serial branches (preparing branches).
If "clear" is set to non-zero, all previous results of another "serialize_branches" (serialized branches which were not yet used) will be deleted before setting the new serialized branches.
Example of usage:
serialize_branches(1);
4.36 set_advertised_address(ip|string)
Same as 'advertised_address' but it affects only the current message. It has priority if 'advertised_address' is also set.
Example of usage:
set_advertised_address("opensips.org");
4.37 set_advertised_port(int)
Same as 'advertised_port' but it affects only the current message. It has priority over 'advertised_port'.
Example of usage:
set_advertised_port(5080);
4.38 setdebug([level])
Changes the debug level of the current process from script. If called without the parameter then the debug level of the current process will be reset to the global level. If the debug level of the current process is changed then changing the global debug level (using MI function) does not affect it, so be careful and make sure to reset the process debug level when you are done. This function is very helpful if you are tracing and debugging only a specific piece of code.
Example of usage:
debug= -1 # errors only
.....
{
......
setdebug(4); # set the debug level of the current process to DBG
uac_replace_from(....);
setdebug(); # reset the debug level of the current process to the global level
.......
}
4.39 setdsturi(string)
Explicitely set the dst_uri field to the value of the paramater. The parameter has to be a valid SIP URI.
Example of usage:
setdsturi("sip:10.10.10.10:5090");
4.40 setflag(int)
Set a flag for current processed message. The value of the parameter can be in range of 0..31. The flags are used to mark the message for special processing (e.g., accounting) or to keep some state (e.g., message authenticated).
For more see http://www.voice-system.ro/docs/ser-flags/ .
Example of usage:
setflag(3);
4.41 setbflag([branch_idx,] flag_idx)
Set a flag for a specific branch (set flag to value 1). The value of the "flag_idx" parameter can be in range of 0..31. "branch_idx" identify the branch for which the flag is set - it must be a positiv number. Branch index 0 refers to the RURI branch. If this parameter is missing, 0 branch index is used as default.
For more about script flags, see Flags Documentation.
Example of usage:
setbflag(1,3);
# or
setbflag(3); # same with setbflag(0,3)
4.42 setsflag(flag_idx)
Set a script flag (set flag to value 0). The value of the "flag_idx" parameter can be in range of 0..31.
For more about script flags, see Flags Documentation.
Example of usage:
setsflag(2);
4.43 strip(int)
Strip the first N-th characters from username of R-URI (N is the value of the parameter).
Example of usage:
strip(3);
4.44 strip_tail(int)
Strip the last N-th characters from username of R-URI (N is the value of the parameter).
Example of usage:
strip_tail(3);
