Openser中文网

专注于VoIP,Opensips,Kamailio等技术,QQ群:QQ群:293697898

opensips 配置文件


tags:opensips 配置文件 创建时间:2016-01-18 17:16:55

The OpenSIPS configuration file contains all the parameters that control the OpenSIPS core and modules, along with the actual routing logic that OpenSIPS will use to route the SIP traffic.

Upon installation, the default configuration file path is :
[INSTALL_PATH]/etc/opensips/opensips.cfg

The configuration file is text-based, written in an OpenSIPS custom language, very similar to the C language. You will find different variables ( each with different scopes - explained further down the manual ), you can do the classical constructs like if / while / switch, etc, and you can also call sub-routines with parameters, so the script should be fairly easily read-able by somebody with some SIP & programming skills.

If you do any change to the configuration file, in order for them to take effect, you MUST restart OpenSIPS

Due to the fact that you must restart OpenSIPS every time you make a change to the configuration file, it is of vital importance to ensure that all the changes you have made are correct according to the OpenSIPS language syntax.
You can check the OpenSIPS configuration file validity by running

[INSTALL_PATH]/sbin/opensips -C [PATH_TO_CFG]

When checking the configuration file for validity, If the cfg is OK, OpenSIPS will return 0.

If the config file contains any errors, they will be displayed in the console and OpenSIPS will return -1


Generating OpenSIPS config files is accomplished by using the menuconfig tool. Because the graphical interface is ncurses based, please make sure to first install the ncurses development library ( typically libncurses5-dev ).
1.  Using the Menuconfig Tool

The menuconfig can be ran either directly from the OpenSIPS sources, or post installation, from the installation path :
From sources, you can run
    make menuconfig
After installation, you can run menuconfig directly from the installation path, by running
    [install_path]/sbin/osipsconfig
Once in the menuconfig tool, navigate to the 'Generate OpenSIPS Script' option, and then choose your desired script type. Once you have chosen you script type, you will be able to go to configure the various available options for that script ( described below ). Enabling certain options per script is done by using the spacebar key. Once you have configured your desired options, you can hit the 'q' key to go to the previous menu, and hit 'Save Changes'. Then, you can generate the OpenSIPS script with your configurations. At the end, the graphical tool will give you the path for your newly generated config file ( eg : Config generated : /usr/local/opensips_proxy_1.11/etc/opensips/opensips_residential_2013-5-21_11:39:48.cfg )

2.  Types of Configs

So far, the OpenSIPS 1.11 menuconfig automated script generator supports 3 types of scripts. Here are the types of scripts, along with the available options per script :
Residential Script
ENABLE_TCP : OpenSIPS will listen on TCP for SIP requests
ENABLE_TLS : OpenSIPS will listen on TCP for SIP requests
USE_ALIASES : OpenSIPS will allow the use of Aliases for SIP users
USE_AUTH : OpenSIPS will authenticate Register & Invite requests
USE_DBACC : OpenSIPS will save ACC entries in DB for all calls
USE_DBUSRLOC : OpenSIPS will persistently store User Location entries in the DB
USE_DIALOG : OpenSIPS will keep track of active dialogs
USE_MULTIDOMAIN : OpenSIPS will handle multiple domains for subscribers
USE_NAT : OpenSIPS will try to cope with NAT by fixing SIP msgs and engaging RTPProxy
USE_PRESENCE : OpenSIPS will act as a Presence server
USE_DIALPLAN : OpenSIPS will use dialplan for transformation of local numbers
VM_DIVERSION : OpenSIPS will redirect to VM calls not reaching the subscribers
HAVE_INBOUND_PSTN : OpenSIPS will accept calls from PSTN gateways (with static IP authentication)
HAVE_OUTBOUND_PSTN : OpenSIPS will send numerical dials to PSTN gateways (with static IP definition)
USE_DR_PSTN : OpenSIPS will use Dynamic Routing Support ( LCR ) for PSTN interconnection
Trunking Script
ENABLE_TCP : OpenSIPS will listen on TCP for SIP requests
ENABLE_TLS : OpenSIPS will listen on TCP for SIP requests
USE_DBACC : OpenSIPS will save ACC entries in DB for all calls
USE_DIALPLAN : OpenSIPS will use dialplan for transformation of local numbers
USE_DIALOG : OpenSIPS will keep track of active dialogs
DO_CALL_LIMITATION : OpenSIPS will limit the number of parallel calls per trunk
Load-Balancer Script
ENABLE_TCP : OpenSIPS will listen on TCP for SIP requests
ENABLE_TLS : OpenSIPS will listen on TCP for SIP requests
USE_DBACC : OpenSIPS will save ACC entries in DB for all calls
USE_DISPATCHER : OpenSIPS will use DISPATCHER instead of Load-Balancer for distributing the traffic
DISABLE_PINGING : OpenSIPS will not ping at all the destinations (otherwise it will ping when detected as failed)
3.  Post-Generation Script editing

After generating your OpenSIPS script with the menuconfig tool, you need to open the script with your favorite editor, and go through all the '# CUSTOMIZE ME' comments in the script. Those comments mark the places where user attention is needed, and usually refer to customizing the OpenSIPS listening address or setting the proper database URL.
Upon making the appropriate '# CUSTOMIZE ME' changes, you can save your script and take it for a test drive.

The OpenSIPs configuration script has three main logical parts :
global parameters
modules section
routing logic
Global parameters

Usually, in the first part, you declare the OpenSIPS global parameters - these global or core parameters are affecting the OpenSIPS core and possible the modules.
Configuring the network listeners, available transport protocols, forking (and number of processes), the logging and other global stuff is provided by these global parameters.
Example:
disable_tcp = yes
listen = udp:192.168.2.10:5060
listen = udp:192.168.2.10:5070
fork = yes
children = 4
log_stderror = no
Modules section

In regards to the OpenSIPS modules,the modules that are to be loaded (no module is loaded by default) are specified by using the directive loadmodule. Modules are to be specified by name and an optional path (to the .so file). If no path is provided (and just the name of the module), the default path will be assumed for locating the loading the module (default path is /usr/lib/opensips/modules if not other one configured at compile time. For configuring a different path, either the path is pushed directly with the module name (to get control per module) or it can be globally (for all modules) configured via the mpath global parameter.

Once the modules are loaded, the parameters of the modules may be set using the modparam directive - to list of available parameters for each module, the type of parameter value (integer or string) can be found in the documentation of the modules, the Parameters section.
Examples:
loadmodule "modules/mi_datagram/mi_datagram.so"
modparam("mi_datagram", "socket_name", "udp:127.0.0.1:4343")
modparam("mi_datagram", "children_count", 3)
or
mpath="/usr/local/opensips_proxy/lib/modules"
loadmodule "mi_datagram.so"
modparam("mi_datagram", "socket_name", "udp:127.0.0.1:4343")
modparam("mi_datagram", "children_count", 3)
loadmodule "mi_fifo.so"
modparam("mi_fifo", "fifo_name", "/tmp/opensips_fifo")
Routing logic

The routing logic is actually a sum of routes (script routes) that contain the OpenSIPS logic for routing SIP traffic. The description of OpenSIPS behavior in relation to the SIP traffic is done via this routes.

There are different types of routes :
top routes - routes that are directly triggered by OpenSIPs when some events occurs (like SIP request received, SIP reply received, transaction failed, etc)
sub-routes - routes that are triggered / used from other routes in script.

What are the existing top routes, when they are triggered, what kind of SIP messages is handled, what SIP operations are allowed and other are documented in the types of routes section.

The sub-routes have names and they are to be called from any other route (top or sub) in the script via their names. The sub-routes may take parameters (when called) or return a numerical code (avoid returning 0 value as this will terminate your whole script. The sub-routes are similar to functions / procedure in any programing language. See the description of the route directive.
Example:
route { # top route triggered on incoming SIP requests
   if ( route(src_ip_is_gw) ) {
      xlog("request $rm comes from GW\n");
   }
}

onreply_route { # top route triggered on incoming SIP replies
   if ( route(src_ip_is_gw) ) {
      xlog("reply $rc comes from GW\n");
   }
}

route[src_ip_is_gw] { #sub-route
   if ($si=='11.22.33.44' || $si=='11.22.33.45')
      return 1;
   return -1;
}

This section lists the all the parameters exported by OpenSIPS core for script usage (to be used in opensips.cfg)
This document is for OpenSIPS 1.11.x
Core keywords
Core values
Core parameters
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");
    };
↑ Contents
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;
↑ Contents
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"
NOTE: Aside this global approach, you can also define an advertise IP and port in a per-interface manner (see the "listen" parameter). When advertise values are defined per interface, they will be used only for traffic leaving that interface only.
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
NOTE: Aside this global approach, you can also define an advertise IP and port in a per-interface manner (see the "listen" parameter). When advertise values are defined per interface, they will be used only for traffic leaving that interface only.
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 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.5 bin_listen

Defines a UDP listening interface for one or more Binary Packet Receivers. Default value is "null" (not listening).
Example of usage:
    bin_listen=10.0.0.150:5062
3.6 bin_children

The number of UDP listeners for the Binary Internal Interface. Default value is 1.
Example of usage:
    bin_children=4
3.7 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.8 children

Number of children to fork for each UDP or SCTP interface you have defined. Default value is 8.
Example of usage:
    children=16
NOTE: this global value (applicable for all UDP/SCTP interfaces) can be override if you set a different number of children in the definition of a specific interface - so actually you can define a different number of children for each interface (see the "listen" parameter for syntax).
3.9 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.10 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_8"
3.11 db_default_url

The default DB URL to be used by modules if no per-module URL is given. Default is NULL (not defined)
Example of usage:
    db_default_url="mysql://opensips:opensipsrw@localhost/opensips"
3.12 debug

Set the debug level. Higher values make OpenSIPS to print more debug messages.
Examples of usage:
    debug=1 -- print only important messages (like errors or more critical situations) 
    - recommended for running proxy as daemon

    debug=4 -- print a lot of debug messages - use it only when doing debugging sessions
Actual values are:
-3 - Alert level
-2 - Critical level
-1 - Error level
1 - Warning level
2 - Notice level
3 - Info level
4 - Debug level
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.
3.13 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.14 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.15 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 resolve.c .
Can be 'yes' or 'no'. By default the blacklist is disabled (Default value is 'yes').
Example of usage:
    disable_dns_blacklist=no
3.16 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.17 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.18 disable_tcp

Global parameter to disable TCP support in the SIP server. Default value is 'no'.
Example of usage:
    disable_tcp=yes
3.19 disable_tls

Global parameter to disable TLS support in the SIP server. Default value is 'yes'.
Example of usage:
    disable_tcp=no
3.20 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.21 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.22 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.23 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.24 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.25 dns_try_naptr

Disables the NAPTR lookups when doing DNS based routing for SIP requests - if disabled, the DNS lookup will start with SRV lookups. Can be 'yes' or 'no'. By default it is enabled, value 'yes'.
Example of usage:
    dns_try_naptr=no
3.26 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.27 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.110/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.28 event_pkg_threshold

A number representing the percentage threshold above which the E_CORE_PKG_THRESHOLD event is raised, warning about low amount of free private memory. It accepts integer values between 0 and 100.
Default value is 0 ( event disabled ).
Example of usage:
    event_pkg_threshold = 90
3.29 event_shm_threshold

A number representing the percentage threshold above which the E_CORE_SHM_THRESHOLD event is raised, warning about low amount of free shared memory. It accepts integer values between 0 and 100.
Default value is 0 ( event disabled ).
Example of usage:
    event_shm_threshold = 90
3.30 exec_dns_threshold

A number representing the maximum number of microseconds a DNS query is expected to last. Anything above the set number will trigger a warning message to the logging facility.
Default value is 0 ( logging disabled ).
Example of usage:
    exec_dns_threshold = 60000
3.31 exec_msg_threshold

A number representing the maximum number of microseconds the processing of a SIP msg is expected to last. Anything above the set number will trigger a warning message to the logging facility. Aside from the message and the processing time, the most time consuming function calls from the script will also be logged.
Default value is 0 ( logging disabled ).
Example of usage:
    exec_msg_threshold = 60000
3.32 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. OpenSIPS will only listen on UDP. Since the process is attached to the controlling terminal, not PID file will be created even if the -P command line option was specified.
Default value is 'yes'.
Example of usage:
    fork=no
3.33 group gid

The group id to run OpenSIPS.
Example of usage:
  group="opensips"
3.34 include_file

Can be called from outside route blocks to load additional routes/blocks or from inside them to simply preform more functions. The file path can be relative or absolute. If it is not an absolute path, first attempt is to locate it relative to current directory. If that fails, second try is relative to directory of the file that includes it. Will throw an error if file is not found.
Example of usage:
    include_file "proxy_regs.cfg"
3.35 import_file

Same as include_file but will not throw an error if file is not found.
Example of usage:
    import_file "proxy_regs.cfg"
3.36 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.
The listen definition may accept several optional parameters for:
configuring an advertise IP and port only for this interface. Syntax "AS 11.22.33.44:5060"
setting a different number of children for this interface only (for UDP and SCTP interfaces only). This will override the global "children" parameter. Syntax "use_children 5"
Remember that this parameters have affect only for the interface they are configured for; if not defined per interface, the global values will be used.
Example of usage:
    listen=10.10.10.10
    listen=eth1:5062
    listen=udp:10.10.10.10:5064
    listen=udp:127.0.0.1:5060 use_children 5
    listen=udp:127.0.0.1:5060 as 99.88.44.33:5060 use_children 3
    listen=127.0.0.1 use_children 3
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.37 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.38 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.39 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.40 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.41 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.42 mem_warming

Default value: off

Only relevant when the HP_MALLOC compile flag is enabled. If set to "on", on each startup, OpenSIPS will attempt to restore the memory fragmentation pattern it had before the stop/restart. If no pattern_file from a previous run is found, memory warning is skipped, and the memory allocator simply starts with a big chunk of memory.

Memory warming is useful when dealing with high volumes of traffic (thousands of cps on multi-core machines - the more cores, the more useful), because processes must mutually exclude themselves when chopping up the initial big memory chunk. By performing fragmentation on startup, OpenSIPS will also behave optimally in the first minute(s) after a restart. Fragmentation usually lasts a few seconds - OpenSIPS will not process traffic during this period.
Example of usage:
    mem_warming = on
3.43 mem_warming_percentage

Default value: 75

How much of OpenSIPS's memory should be fragmented with the pattern of the previous run, upon a restart. Used at startup, if mem_warming is enabled.
Example of usage:
    mem_warming_percentage = 50
3.44 mem_warming_pattern_file

Default value: "CFG_DIR/mem_warming_pattern"

The memory fragmentation pattern of a previous OpenSIPS run. Used at startup, if mem_warming is enabled.
Example of usage:
    mem_warming_pattern_file = "/var/tmp/my_memory_pattern"
3.45 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.46 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.47 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.48 mcast_ttl

Set the value for multicast ttl. Default value is OS specific (usually 1).
Example of usage:
    mcast_ttl=32
3.49 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.50 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.51 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.52 port

The port the SIP server listens to. The default value for it is 5060.
Example of usage:
    port=5080
3.53 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.54 query_buffer_size

If set to a value greater than 1, inserts to DB will not be flushed one by one. Rows to be inserted will be kept in memory until until they gather up to query_buffer_size rows, and only then they will be flushed to the database.
Example of usage:
    query_buffer_size=5
3.55 query_flush_time

If query_buffer_size is set to a value greater than 1, a timer will trigger once every query_flush_time seconds, ensuring that no row will be kept for too long in memory.
Example of usage:
     query_flush_time=10
3.56 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.57 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.58 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.59 shm_hash_split_percentage

Only relevant when the HP_MALLOC compile flag is enabled. It controls how many memory buckets will be optimized. (e.g. setting it to 2% will optimize the first 81 most used buckets as frequency). The default value is 1.
3.60 shm_secondary_hash_size

Only relevant when the HP_MALLOC compile flag is enabled. It represents the optimization factor of a single bucket (e.g. setting it to 4 will cause the optimized buckets to be further split into 4). The default value is 8.
3.61 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.62 tcp_async

If the TCP connect and write operations should be done in an asynchronous mode. Default value is 0 ( blocking connect & write )
Example of usage:
    tcp_async = 1
3.63 tcp_async_local_connect_timeout

If tcp_async is enabled, this specifies the number of milliseconds during which connects will be done in blocking mode (optimization). If the connect operation lasts more than this, it will switch to async mode and will be passed to TCP MAIN for polling. Default value is 100 ms.
Example of usage:
    tcp_async_local_connect_timeout = 10
3.64 tcp_async_local_write_timeout

If tcp_async is enabled, this specifies the number of milliseconds during which a write op will be tried in blocking mode (optimization). If the write operation lasts more than this, it will switch to async mode and will be passed to TCP MAIN for polling. Default value is 10 ms.
Example of usage:
    tcp_async_local_write_timeout = 20
3.65 tcp_async_max_postponed_chunks

If tcp_async is enabled, this specifies the maximum number of SIP messages that can be stashed for later/async writing. If the connection pending writes exceed this number, the connection will be marked as broken and dropped. Default value is 32
Example of usage:
    tcp_async_max_postponed_chunks = 64
3.66 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.67 tcp_accept_aliases

3.68 tcp_listen_backlog

The backlog argument defines the maximum length to which the queue of pending connections for the TCP listeners may grow. If a connection request arrives when the queue is full, the client may receive an error with an indication of ECONNREFUSED or, if the underlying protocol supports retransmission, the request may be ignored so that a later reattempt at connection succeeds.
Default configured value is 10.
3.69 tcp_send_timeout

Time in milliseconds after a TCP connection will be closed if it is not available for blocking writing in this interval (and OpenSIPS wants to send something on it). Default is 100ms
Example of usage:
    tcp_send_timeout = 200
3.70 tcp_connect_timeout

Time in milliseconds before an ongoing blocking attempt to connect will be aborted. Default is 100ms
Example of usage:
    tcp_connect_timeout = 10
3.71 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.72 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.73 tcp_max_msg_chunks

The maximum number of chunks that a SIP message is expected to arrive via TCP. If a packet is received more fragmented than this, the connection is dropped ( either the connection is very overloaded and this leads to high fragmentation - or we are the victim of an ongoing attack where the attacker is sending the traffic very fragmented in order to decrease our performance ). Default value is is 4
Example of usage:
    tcp_max_msg_chunks = 8
3.74 tcp_max_msg_time

The maximum number of seconds that a SIP message is expected to arrive via TCP. If a single SIP packet is still not fully received after this number of seconds, the connection is dropped ( either the connection is very overloaded and this leads to high fragmentation - or we are the victim of an ongoing attack where the attacker is sending the traffic very fragmented in order to decrease our performance ). Default value is is 4
Example of usage:
    tcp_max_msg_time = 8
3.75 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.76 tcp_no_new_conn_bflag

A branch flag to be used as marker to instruct OpenSIPS not to attempt to open a new TCP connection when delivering a request, but only to reuse an existing one (if available). If no existing conn, a generic send error will be returned.
This is intended to be used in NAT scenarios, where makes no sense to open a TCP connection towards a destination behind a NAT (like TCP connection created during registration was lost, so there is no way to contact the device until it re-REGISTER). Also this can be used to detect when a NATed registered user lost his TCP connection, so that opensips can disable his registration as useless.
Example of usage:
     tcp_no_new_conn_bflag = 6
     ....
     route{
         ....
         if( destination_behin_nat && proto==TCP )
            setbflag(6);
         ....
         t_relay("0x02"); # no auto error reply
         $var(retcode) = $rc;
         if ($var(retcode)==-6) {
             #send error
             xlog("unable to send request to destination");
             send_reply("404","Not found");
             exit;
         } else if ($var(retcode)<0) {
             sl_reply_error();
             exit;
         }
         ....
     }
3.77 tcp_threshold

A number representing the maximum number of microseconds sending of a TCP request is expected to last. Anything above the set number will trigger a warning message to the logging facility.
Default value is 0 ( logging disabled ).
Example of usage:
    tcp_threshold = 60000
3.78 tcp_keepalive

Enable / disable TCP keepalive
Example of usage:
    tcp_keepalive = 1
3.79 tcp_keepcount

Number of keepalives to send before closing the connection (Linux only)
Example of usage:
    tcp_keepcount = 5
3.80 tcp_keepidle

Amount of time before OpenSIPS will start to send keepalives if the connection is idle (Linux only)
Example of usage:
    tcp_keepidle = 30
3.81 tcp_keepinterval

Interval between keepalive probes, if the previous one failed (Linux only)
Example of usage:
    tcp_keepinterval = 10
3.82 tls_ca_list

3.83 tls_certificate

3.84 tls_ciphers_list

3.85 tls_domain

3.86 tls_handshake_timeout

3.87 tls_log

3.88 tls_method

3.89 tls_port_no

3.90 tls_private_key

3.91 tls_require_certificate

3.92 tls_send_timeout

3.93 tls_verify

3.94 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.95 user uid

The user id to run OpenSIPS (OpenSIPS will suid to it).
Example of usage:
    user="opensips"
3.96 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.97 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
3.98 xlog_buf_size

Default value: 4096

Size of the buffer used to print a single line on the chosen logging facility of OpenSIPS. If the buffer is too small, an overflow error will be printed, and the concerned line will be skipped.
Usage example:
    xlog_buf_size = 8388608 #given in bytes
3.99 xlog_force_color

Default value: false

Only relevant when log_stderror is set to true. Enables the use of the color escape sequences, otherwise they will have no effect.
Usage example:
    xlog_force_color = true


OpenSIPS routing logic uses several types of routes. Each type of route is triggered by a certain event and allows you to process a certain type of message (request or reply).
1. route

Request routing block. It contains a set of actions to be taken for SIP requests.
Triggered by : receiving an external request from the network.
Processing : the triggering SIP request.
Type : initially stateless, may be forced to stateful by using TM functions.
Default action : if the request is not either forwarded nor replied, the route will simply discard the request at the end.
The main 'route' block identified by 'route{...}' or 'route[0]{...}' is executed for each SIP request.
The implicit action after execution of the main route block is to drop the SIP request. To send a reply or forward the request, explicit actions must be called inside the route block.
Example of usage:
    route {
         if(is_method("OPTIONS")) {
            # send reply for each options request
            sl_send_reply("200", "ok");
            exit();
         }
         route(1);
    }
    route[1] {
         # forward according to uri
         forward();
    }
Note that if a 'route(X)' is called from a 'branch_route[Y]' then in 'route[X]' is just processed each separate branch instead of all branches together as occurs in main route.
2. branch_route

Request's branch routing block. It contains a set of actions to be taken for each branch of a SIP request.
Triggered by : preparation a new branch (of a request); the branch is well formed, but not yet sent out.
Processing : the SIP request (with the branch particularities, like RURI, branch flags)
Type : stateful
Default action : if the branch is not dropped (via "drop" statement), the branch will be automatically sent out.
It is executed only by TM module after it was armed via t_on_branch("branch_route_index").
Example of usage:
    route {
        lookup("location");
        t_on_branch("1");
        if(!t_relay()) {
            sl_send_reply("500", "relaying failed");
        }
    }
    branch_route[1] {
        if(uri=~"10\.10\.10\.10") {
            # discard branches that go to 10.10.10.10
            drop();
        }
    }
3. failure_route

Failed transaction routing block. It contains a set of actions to be taken each transaction that received only negative replies (>=300) for all branches.
Triggered by : receiving or generation(internal) of a negative reply that completes the transaction (all branches are terminated with negative replies)
Processing : the original SIP request (that was sent out)
Type : stateful
Default action : if no new branch is generated or no reply is forced over, by default, the winning reply will be sent back to UAC.
The 'failure_route' is executed only by TM module after it was armed via t_on_failure("failure_route_index").
Note that inside the 'failure_route', the request that initiated the transaction is being processed, and not its reply.
Example of usage:
    route {
        lookup("location");
        t_on_failure("1");
        if(!t_relay()) {
            sl_send_reply("500", "relaying failed");
        }
    }
    failure_route[1] {
        if(is_method("INVITE")) {
             # call failed - relay to voice mail
             t_relay("udp:voicemail.server.com:5060");
        }
    }
4. onreply_route

Reply routing block. It contains a set of actions to be taken for SIP replies.
Triggered by : receiving of a reply from the network
Processing : the received reply
Type : stateful (if bound to a transaction) or stateless (if global reply route).
Default action : if the reply is not dropped (only provisional replies can be), it will be injected and processed by the transaction engine.
There are three types of onreply routes:
global - it catches all replies received by OpenSIPS and does not need any special arming (simple definition is enough) - named 'onreply_route {...}' or 'onreply_route[0] {...}'.
per request/transaction - it catches all received replies belonging to a certain transaction and need to be armed (via "t_on_reply()" ) at request time, in REQUEST ROUTE - named 'onreply_route[N] {...}'.
per branch - it catches only the replies that belong to a certain branch from a transaction. It needs to be armed (also via "t_on_reply()" ) at request time, but in BRANCH ROUTE, when a certain outgoing branch is processed - named 'onreply_route[N] {...}'.
Certain 'onreply_route' blocks can be executed by TM module for special replies. For this, the 'onreply_route' must be armed for the SIP requests whose replies should be processed within it, via t_on_reply("onreply_route_index").
route {
        seturi("sip:bob@opensips.org");  # first branch
        append_branch("sip:alice@opensips.org"); # second branch

        t_on_reply("global"); # the "global" reply route
                              # is set the whole transaction
        t_on_branch("1");

        t_relay();
}

branch_route[1] {
        if ($rU=="alice")
                t_on_reply("alice"); # the "alice" reply route
                                      # is set only for second branch
}

onreply_route {
        xlog("OpenSIPS received a reply from $si\n");
}


onreply_route[alice] {
        xlog("received reply on the branch from alice\n");
}

onreply_route[global] {
        if (t_check_status("1[0-9][0-9]")) {
                setflag(1);
                log("provisional reply received\n");
                if (t_check_status("183"))
                        drop;
        }
}

5. error_route

The error route is executed automatically when a parsing error occurred during SIP request processing. This allow the administrator to decide what to do in case of error.
Triggered by : parsing error in "route"
Processing : failed request
Type : stateless (recommended)
Default action : discard request.
In error_route, the following pseudo-variables are available to get access to error details:
$(err.class) - the class of error (now is '1' for parsing errors)
$(err.level) - severity level for the error
$(err.info) - text describing the error
$(err.rcode) - recommended reply code
$(err.rreason) - recommended reply reason phrase
  error_route {
     xlog("--- error route class=$(err.class) level=$(err.level)
            info=$(err.info) rcode=$(err.rcode) rreason=$(err.rreason) ---\n");
     xlog("--- error from [$si:$sp]\n+++++\n$mb\n++++\n");
     sl_send_reply("$err.rcode", "$err.rreason");
     exit;
  }
6. local_route

The local route is executed automatically when a new SIP request is generated by TM, internally (no UAC side). This is a route intended to be used for message inspection, accounting and for applying last changes on the message headers. Routing and signaling functions are not allowed.
Triggered by : TM generating a brand new request
Processing : the new request
Type : stateful
Default action : send the request out
  local_route {
     if (is_method("INVITE") && $ru=~"@foreign.com") {
        append_hf("P-hint: foreign request\r\n");
        exit;
     }
     if (is_method("BYE") ) {
        acc_log_request("internally generated BYE");
     }
  }
7. startup_route

The startup_route is executed only once when OpenSIPS is started and before the processing of SIP messages begins. This is useful if some initiation actions are needed, like loading some data in the cache, to ease up the future processing. Notice that this route, compared to the others is not triggered at the receipt of a message, so the functions that can be called here must not do processing on the message.
Triggered : At startup, before the listener processes are started.
Processing : Initializing functions.
  startup_route {
    avp_db_query("select gwlist where ruleid==1",$avp(i:100));
    cache_store("local", "rule1", "$avp(i:100)");
  }
8. timer_route

The timer_route is as the name suggests, a route executed periodically at a configured interval of time specified next to the name(in seconds). The same as the startup_route, this route does not process a message. You can defined more timer routes.
Triggered by : The time keeper.
Processing : Functions that do refresh actions.
  timer_route[gw_update, 300] {
    avp_db_query("select gwlist where ruleid==1",$avp(i:100));
    $shv(i:100) =$avp(i:100);
  }
9.  event_route

The event_route is used by the OpenSIPS Event Interface to execute script code when an event is triggered. The name of the route is the event that has to be handled by that route.
Triggered by : the event_route module when an event raised by the OpenSIPS Event Interface
Processing : the event triggered
Type : stateless (recommended)
Default action : no script code is executed when the event is raised.
  event_route[E_PIKE_BLOCKED] {
    xlog("The E_PIKE_BLOCKED event was raised\n");
  }


Assignments, string and arithmetic operations can be done directly in the configuration file.
1. Assignment

Assignments can be done like in C, via '=' (equal) operator. Not that not all variables (from script) can be written, some are read-only. Check with listing of variables to see which ones can be written too.
$var(a) = 123;
$ru = "sip:user@domain";
There is a special assign operator ':=' (colon equal) that can be used with AVPs. If the right value is null, all AVPs with that name are deleted. If different, the new value will overwrite any existing values for the AVPs with than name (on other words, delete existing AVPs with same name, add a new one with the right side value).
$avp(val) := 123;
2. String operations

For strings, '+' is available to concatenate.
$var(a) = "test";
$var(b) = "sip:" + $var(a) + "@" + $fd;
3. Arithmetic and bitwise operations

For numbers, one can use:
+ : plus
- : minus
/ : divide
* : multiply
% : modulo
| : bitwise OR
& : bitwise AND
^ : bitwise XOR
~ : bitwise NOT
<< : bitwise left shift
>> : bitwise right shift
Example:
$var(a) = 4 + ( 7 & ( ~2 ) );
NOTE: to ensure the priority of operands in expression evaluations do use __parenthesis__.
Arithmetic expressions can be used in condition expressions via test operator ' [ ... ] '.
if( [ $var(a) & 4 ] )
    log("var a has third bit set\n");



Statements you can use in the OpenSIPS config file while building the routing logic.
1. if

IF-ELSE statement
Prototype:
    if (expr) {
       actions;
    } else {
       actions;
    }
The 'expr' should be a valid logical expression.
The logical operators that can be used in the logical expressions:
== - equal
!= - not equal
=~ - regular expression matching (e.g. $rU =~ '^1800*' is "$rU begins with 1800" )
!~ - regular expression not-matching
> - greater
>= - greater or equal
< - less
<= - less or equal
&& - logical AND
|| - logical OR
! - logical NOT
[ ... ] - test operator - inside can be any arithmetic expression
Example of usage:
    if ( is_method("INVITE") && $rp==5060 )
    {
        log("this sip message is an invite\n");
    } else {
        log("this sip message is not an invite\n");
    }
2. switch

SWITCH statement - it can be used to test the value of a pseudo-variable.
IMPORTANT NOTE: 'break' can be used only to mark the end of a 'case' branch (as it is in shell scripts). If you are trying to use 'break' outside a 'case' block the script will return error -- you must use 'return' there.
Example of usage:
    route {
        route(my_logic);
        switch($retcode)
        {
            case -1:
                log("process INVITE requests here\n");
            break;
            case 1:
                log("process REGISTER requests here\n");
            break;
            case 2:
            case 3:
                log("process SUBSCRIBE and NOTIFY requests here\n");
            break;
            default:
                log("process other requests here\n");
       }

        # switch of R-URI username
        switch($rU)
        {
            case "101":
                log("destination number is 101\n");
            break;
            case "102":
                log("destination number is 102\n");
            break;
            case "103":
            case "104":
                log("destination number is 103 or 104\n");
            break;
            default:
                log("unknown destination number\n");
       }
    }

    route[my_logic]{
        if(is_method("INVITE"))
        {
            return(-1);
        };
        if(is_method("REGISTER"))
            return(1);
        }
        if(is_method("SUBSCRIBE"))
            return(2);
        }
        if(is_method("NOTIFY"))
            return(3);
        }
        return(-2);
    }
Take care while using 'return' - 'return(0)' stops the execution of the script.
3. while

while statement
Example of usage:
    $var(i) = 0;
    while($var(i) < 10)
    {
        xlog("counter: $var(i)\n");
        $var(i) = $var(i) + 1;
    }
4. for each

for each statement - easy iteration over indexed pseudo variables
Example of usage:
    $avp(arr) = 0;
    $avp(arr) = 1;
    $avp(arr) = 2;
    $avp(arr) = 3;
    $avp(arr) = 4;

    for ($var(it) in $(avp(arr)[*]))
        xlog("array value: $var(it)\n");

    # iterate through all Contact URIs from each Contact header
    for ($var(ct) in $(ct[*]))
        xlog("Contact: $var(ct)\n");

    # iterate through all Via headers of a SIP request
    for ($var(via) in $(hdr(Via)[*]))
        xlog("Found \"Via\" header: $var(via)\n");


This section lists the all the functions exported by OpenSIPS core for script usage (to be used in opensips.cfg)
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()
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;
}
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.
Function returns true is the new attribute was successfully inserted.
cache_store("local","my_attr","$avp(i:55)",1200);

OR

modparam("cachedb_redis","cachedb_url","redis:cluster1://192.168.2.134:6379/")
...
cache_store("redis:cluster1","passwd_$tu","$var(x)");
More complex examples can be found in the Key-Value Interface Tutorial.
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. Function returns false only if the storage_id is invalid.
cache_remove("local","my_attr");

OR

modparam("cachedb_redis","cachedb_url","redis:cluster1://192.168.2.134:6379/")
...
cache_remove("redis:cluster1","my_attr");
More complex examples can be found in the Key-Value Interface Tutorial.
5. cache_fetch( storage_id, attribute_name, result_pvar)

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 pseudo-variable specified by result_pvar.
Function returns true if the attribute was found and its value returned.
cache_fetch("local","my_attr", $avp(i:11) );

OR

modparam("cachedb_redis","cachedb_url","redis:cluster1://192.168.2.134:6379/")
...
cache_fetch("redis:cluster1","my_attr",$avp(i:11));
More complex examples can be found in the Key-Value Interface Tutorial.
6. cache_counter_fetch( storage_id, counter_attribute_name, result_avp)

This function fetches from a memory-cache-like-storage system the value of a counter. The attribute name may contain pseudo-variables. The result (if any) will be stored in the pseudo-variable specified by result_pvar.
Function returns true if the attribute was found and its value returned.
cache_counter_fetch("local","my_counter", $avp(counter_val) );

OR

modparam("cachedb_redis","cachedb_url","redis:cluster1://192.168.2.134:6379/")
...
cache_fetch("redis:cluster1","my_counter",$avp(redis_counter_val));
7. cache_add( storage_id, attribute_name,increment_value,expire,[new_val_pvar])

This increments an attribute in a memory-cache-like-storage system that supports such an operation. The attribute name may contain pseudo-variables. If the attribute does not exit, it will be created with the increment_value. If expire > 0, the key will also expire in the specified number of seconds.
Function returns false if increment fails.
Optionally, the function receives one last parameter as a pvar in which to fetch the new value of the counter.

modparam("cachedb_redis","cachedb_url","redis:cluster1://192.168.2.134:6379/")
...
cache_add("redis:cluster1",5);
More complex examples can be found in the Key-Value Interface Tutorial.
8. cache_sub( storage_id, attribute_name,increment_value,expire,[new_val_pvar])

This decrements an attribute in a memory-cache-like-storage system that supports such an operation. The attribute name may contain pseudo-variables. If expire > 0, the key will also expire in the specified number of seconds.
Function returns false if decrement fails.
Optionally, the function receives one last parameter as a pvar in which to fetch the new value of the counter.

modparam("cachedb_redis","cachedb_url","redis:cluster1://192.168.2.134:6379/")
...
cache_sub("redis:cluster1",5);
More complex examples can be found in the Key-Value Interface Tutorial.
9. cache_raw_query( storage_id, raw_query,result_avp)

The function runs the provided raw query ( in the back-end dependent language ) and returns the results ( if any ) in the provided AVP. The result_avp can be missing, if the query returns no results.
Function returns false if query fails.
...
cache_raw_query("mongodb","{ \"op\" : \"count\",\"query\": { \"username\" : $rU} }","$avp(mongo_count_result)");
...
More complex examples can be found in the Key-Value Interface Tutorial.
10. 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.
11. 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");
12. 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();
        }
    }
13. 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;
    };
  }
14. 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();
15. 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);
16. 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.
17. 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();
18. get_timestamp(sec_avp,usec_avp)

Returns the current timestamp, seconds and microseconds of the current second, from a single system call.
Example of usage:
     get_timestamp($avp(sec),$avp(usec));
19. isdsturiset()

Test if the dst_uri field (next hop address) is set.
Example of usage:
    if(isdsturiset()) {
        log("dst_uri is set\n");
    };
20. 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 Flags Documentation.
Example of usage:
    if(isflagset(3)) {
        log("flag 3 is set\n");
    };
21. 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");
    };
22. 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");
    };
23. log([level,] string)

Write text message to standard error terminal or syslog. You can specify the log level as first parameter.
Example of usage:
    log("just some text message\n");
24. 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();
25. prefix(string)

Add the string parameter in front of username in R-URI.
Example of usage:
    prefix("00");
26. 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");
27. raise_event(string[, avp[, avp]])

Raises from script an event through OpenSIPS Event Interface. The first parameter is a string that indicates the event which should be raised. The next two parameters should be AVPs and they are optional. If only one is present, it should contain the values attached to the event. If both of them are specified, the first one should contain the names of the attributes, and the last one the values attached to the event.
This function triggers an event for all subscribers for that event, regardless the transport module used.
Example of usage (raises an event with no attributes):
raise_event("E_NO_PARAM");
Example of usage (raises an event with two attributes):
$avp(attr-name) = "param1";
$avp(attr-name) = "param2";
$avp(attr-val) = 1;
$avp(attr-val) = "2"
raise_event("E_TWO_PARAMS", $avp(attr-name), $avp(attr-val));
28. remove_branch(pv|int)

Removes a given branch. The branch to be removed can be given via an integer or a pseudovariable. Once a branch is remove, all the subsequent branches are shifted (i.e. if branch n is removed, then the old n+1 branch becomes the new n branch, the old n+2 branch becomes n+1 and so on).
Example of usage (remove all branches with URI hostname "127.0.0.1"):
$var(i) = 0;
while ($(branch(uri)[$var(i)]) != null) {
   xlog("L_INFO","$$(branch(uri)[$var(i)])=[$(branch(uri)[$var(i)])]\n");
   if ($(branch(uri)[$var(i)]{uri.host}) == "127.0.0.1") {
       xlog("L_INFO","removing branch $var(i) with URI=[$(branch(uri)[$var(i)])]\n");
       remove_branch($var(i));
   } else {
       $var(i) = $var(i) + 1;
   }
}
29. 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);
  };
}
30. 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();
31. 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 Flags Documentation.
Example of usage:
    resetflag(3);
32. 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)
33. 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);
34. 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();
35. 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");
36. 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");
37. rewriteuser(string) / setuser(string)

Rewrite the user part of the R-URI with the value of function's parameter.
Example of usage:
    rewriteuser("newuser");
38. rewriteuserpass() / setuserpass()

Rewrite the password part of the R-URI with the value of function's parameter.
Example of usage:
    rewriteuserpass("my_secret_passwd");
39. rewriteport() / setport()

Rewrites/sets the port part of the R-URI with the value of function's parameter.
Example of usage:
    rewriteport("5070");
40. rewriteuri(str) / seturi(str)

Rewrite the request URI.
Example of usage:
    rewriteuri("sip:test@opensips.org");
41.  route(name [, param1 [, param2 [, ...] ] ] )

This function is used to run the code from the 'name' route, declared in the script. Optionally, it can receive several parameters (up to 7), that can be later retrieved using the '$param(idx)' pseudo-variable.
The name of the route is an identifier format, whereas the parameters can be either int, string, or a pseudo-variable.
Example of usage:
   route(HANDLE_SEQUENTIALS);
   route(HANDLE_SEQUENTIALS, 1, "param", $var(param));
42.  script_trace( log_level, pv_format_string[, info_string])

This function enables script tracing - this helps to better understand the flow of execution in the OpenSIPS script (current function and line). Moreover, you can also trace the values of pseudo-variables, as script execution progresses.
The blocks of the script where script tracing is enabled will print a line for each individual action that is done (e.g. assignments, conditional tests, module functions, core functions, etc.). Multiple pseudo-variables can be monitored by specifying a pv_format_string (e.g. "$ru---$avp(var1)").
The logs produced by multiple/different traced regions of your script can be differentiated (tagged) by specifying an additional plain string - info_string - as the 3rd parameter.
To disable script tracing, just do script_trace(). Otherwise, the tracing will automatically stop at the end the end of the top route.
Example of usage:
    script_trace( 1, "$rm from $si, ruri=$ru", "me");
will produce:
    [line 578][me][module consume_credentials] -> (INVITE from 127.0.0.1 , ruri=sip:111111@opensips.org)
    [line 581][me][core setsflag] -> (INVITE from 127.0.0.1 , ruri=sip:111111@opensips.org)
    [line 583][me][assign equal] -> (INVITE from 127.0.0.1 , ruri=sip:111111@opensips.org)
    [line 592][me][core if] -> (INVITE from 127.0.0.1 , ruri=sip:tester@opensips.org)
    [line 585][me][module is_avp_set] -> (INVITE from 127.0.0.1 , ruri=sip:tester@opensips.org)
    [line 589][me][core if] -> (INVITE from 127.0.0.1 , ruri=sip:tester@opensips.org)
    [line 586][me][module is_method] -> (INVITE from 127.0.0.1 , ruri=sip:tester@opensips.org)
    [line 587][me][module trace_dialog] -> (INVITE 127.0.0.1 , ruri=sip:tester@opensips.org)
    [line 590][me][core setflag] -> (INVITE from 127.0.0.1 , ruri=sip:tester@opensips.org) 
43. send(destination [, headers])

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, unless headers parameter is specified. 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). The headers parameter should end in '\r\n' and can accept both plain text and pseudo variables.
Parameter is mandatory and has string format.
Example of usage:
   send("udp:10.10.10.10:5070");
   send("udp:10.10.10.10:5070", "Server: opensips\r\n");
44. 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);
45. 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");
46. 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);
47. 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
      .......
    }
48. 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");
49. 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).
Example of usage:
    setflag(3);
50. 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)
51. 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);
52. 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);
53. 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);
54. subscribe_event(string, string [, int])

Subscribes an external application for a certain event for the OpenSIPS Event Interface. This is used for transport protocols that cannot subscribe by themselves (example event_rabbitmq). This function should be called only once in the startup_route if the subscription doesn't expire, or in a timer route if the subscription should be renewed once in a while.
The first parameter is a string represents the name of the event an external application should be notified for. The second parameter is a string that specifies the socket of the external application. Note that this socket should follow the syntax of an existing loaded Event Interface transport module (example: event_datagram, event_rabbitmq). The last parameter is optional and specifies the expire time of the subscription. If it is not present, then the subscription does not expire at all.
Example of usage (subscriber that never expires, notified by the RabbitMQ module):
startup_route {
    subscribe_event("E_PIKE_BLOCKED", "rabbitmq:127.0.0.1/pike");
}
Example of usage (subscriber expires every 5 seconds, notified through UDP):
timer_route[event_subscribe, 4] {
    subscribe_event("E_PIKE_BLOCKED", "udp:127.0.0.1:5051", 5);
}
55. use_blacklist(string)

Enables the DNS blacklist name received as parameter. 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).
    use_blacklist("pstn-gws");
56. xlog([log_level, ]format_string)

Allows various debugging / runtime / critical messages to be printed as the execution of the OpenSIPS script is done. All pseudo-variables included in the format_string parameter will be expanded. There are several optional logging levels which can be specified. They work in accordance with the severity levels of syslog. The levels are named as follows:
L_ALERT (-3)
L_CRIT (-2)
L_ERR (-1) - this is used by default if log_level is omitted
L_WARN (0)
L_NOTICE (1)
L_INFO (2)
L_DBG (3)

    # a few xlog scripting examples
    xlog("Received $rm from $fu (callid: $ci)\n");
    xlog("L_ERR", "key $var(username) not found in cache!\n");


OpenSIPS provides multiple type of variables to be used in the routing script. The difference between the types of variables comes from (1) the visibility of the variable (when it is visible), (2) what the variable is attached to (where the variable resides), (3) read-write status of the variable (some types of the variables are read-only and (4) how multiple values (for the same variable are handled).
The OpenSIPS variables can be easily identified in the script as all their names (or notations) start with the $ sign.
Syntax:
The complete syntax for a pseudo variable is:
$(<context>name(subname)[index]{transformation})
The fields written in green are optional. The fields meaning is:
name(compulsory) - the pseudo-variable name(type).
Ex: pvar, avp, ru, DLG_status, etc.
subname - the identifier of a certain pv from the given type.
Ex: hdr(From), avp(name).
index - a pv can store more than one value - it can refer to a list of values. You can access a certain value from the list if you specify its index. You can also specify indexes with negative values, -1 means the last inserted, -2 the value before the previous inserted one.
transformation - a series of processing actions can be applied on pseudo-variable. You can find the whole list of possible transformations here. The transformations can be cascaded, using the output of one transformation as the input of another.
context - the context in which the pseudo0variable will be evaluated. Now there are 2 pv contexts: reply and request. The reply context can be used in the failure route to request for the pseudo-variable to be evaluated in the context of the reply message. The request context can be used if in a reply route is desired for the pv to be evaluated in the context of the corresponding request.
Usage examples:
Only name: $ru
Name and 'subname: $hdr(Contact)
Name and index: $(ct[0])
Name, subname and index: $(avp(i:10)[2])
Context
$(<request>ru) from a reply route will get the Request-URI from the request
$(<reply>hdr(Contact)) context can be used from failure route to access information from the reply
Types of variables:
script variables - as the name says, these variables are strictly bound to the script routes. The variables are visible only in the routing blocks - they are not message or transaction related, but they are process related (script variables will be inherited by script routes executed by the same OpenSIPS process).
Script variables are read write and they can have integer or string values. A script variable can only hold a single value. A new assignment (or write operation) will overwrite the existing value.
AVP - Attribute Value Pair - the AVPs are dynamic variables (as name) that can be created - the AVPS are linked to a singular message or transaction (if stateful processing is used). A message or a transaction will initially (when received or created) have an empty list of AVPS attached to it. During the routing script, the script directly or functions called from script may create new AVPS that will automatically attached to the message/transaction. The AVPS will be visible in all routes where any message (reply or request) of the transaction will be processed - branch_route , failure_route, onreply_route (for this last route you need to enable the TM parameter onreply_avp_mode).
AVPs are read write and an existing AVP can be even deleted (removed). An AVP may contain multiple values - a new assignment (or write operation) will add a new value to the AVP; the values are kept in "last added first to be used" order (stack).
pseudo variables - pseudo-variables (or PV) provide access to information from the processed SIP message (headers, RURI, transport level info, a.s.o) or from OpenSIPS inners (time values, process PID, return code of a function). Depending of what info they provide, the PVs are either bound to the message, either to nothing (global). Most of the PVs are read-only and only several allow write operations. A PV may return several values or only one, depending of the referred info (if can have multiple values or not).
Standard PV is read-only and returns a single value (if not otherwise documented).
escape sequences - escape sequences used to format the strings; they are actually not variables, but rather formatters.
1. Script variables

Naming: **$var(name)**
Hints:
if you want to start using a script variable in a route, better initialize it with same value (or reset it), otherwise you may inherit a value from a previous route that was executed by the same process.
script variables are faster than AVPs, as they directly reference a memory location.
the value of script variables persists over a OpenSIPS process.
a script value can have only one value.
Example of usage:
$var(a) = 2;  # sets the value of variable 'a' to integer '2'
$var(a) = "2";  # sets the value of variable 'a' to string '2'
$var(a) = 3 + (7&(~2)); # arithmetic and bitwise operation
$var(a) = "sip:" + $au + "@" + $fd; # compose a value from authentication username and From URI domain

# using a script variable for tests
if( [ $var(a) & 4 ] ) {
  xlog("var a has third bit set\n");
}
Setting a variable to NULL is actually initializing the value to integer '0'. Script variables don't have NULL value.
2. AVP variables

Naming: **$avp(name)** or **$(avp(name)[N])**
When using the index "N" you can force the AVP to return a certain value (the N-th value). If no index is given, the first value will be returned.
Hints:
to enable AVPs in onreply_route, use "modparam("tm", "onreply_avp_mode", 1)"
if multiple values are used for a single AVP, the values are index in revert order than added
AVPs are part of the transaction context, so they will be visible everywhere where the transaction is present.
the value of an AVP can be deleted
Example of usage:
Transaction persistence example
# enable avps in onreply route
modparam("tm", "onreply_avp_mode", 1)
...
route{
...
$avp(tmp) = $Ts ; # store the current time (at request processing)
...
t_onreply("1");
t_relay();
...
}

onreply_route[1] {
    if (t_check_status("200")) {
        # calculate the setup time
        $var(setup_time) = $Ts - $avp(tmp);
    }
}
Multilple values example
$avp(17) = "one";
# we have a single value
$avp(17) = "two";
# we have two values ("two","one")
$avp(17) = "three";
# we have three values ("three","two","one")

xlog("accessing values with no index: $avp(17)\n");
# this will print the first value, which is the last added value -> "three"

xlog("accessing values with no index: $(avp(17)[2])\n");
# this will print the index 2 value (third one), -> "one"

# remove the last value of the avp; if there is only one value, the AVP itself will be destroyed
$avp(17) = NULL;

# delete all values and destroy the AVP
avp_delete("$avp(17)/g");

# delete the value located at a certain index 
$(avp(17)[1]) = NULL;

#overwrite the value at a certain index
$(avp(17)[0]) = "zero";
The AVPOPS module provides a lot of useful functions to operate AVPs (like checking values, pushing values into different other locations, deleting AVPs, etc).
3. Pseudo Variables

Naming: $name
Hints:
the PV tokens can be given as parameters to different script functions and they will be replaced with a value before the execution of the function.
most of PVs are made available by OpenSIPS core, but there are also module exporting PV (to make available info specific to that module) - check the modules documentation.
Predefined (provided by core) PVs are listed in alphabetical order.
3.1 URI in SIP Request's P-Asserted-Identity header

$ai - reference to URI in request's P-Asserted-Identity header (see RFC 3325)
3.2 Authentication Digest URI

$adu - URI from Authorization or Proxy-Authorization header. This URI is used when calculating the HTTP Digest Response.
3.3 Authentication realm

$ar - realm from Authorization or Proxy-Authorization header
3.4 Auth username user

$au - user part of username from Authorization or Proxy-Authorization header
3.5 Auth username domain

$ad - domain part of username from Authorization or Proxy-Authorization header
3.6 Auth nonce

$an - the nonce from Authorization or Proxy-Authorization header
3.7 Auth response

$auth.resp - the authentication response from Authorization or Proxy-Authorization header
3.8 Auth nonce

$auth.nonce - the nonce string from Authorization or Proxy-Authorization header
3.9 Auth opaque

$auth.opaque - the opaque string from Authorization or Proxy-Authorization header
3.10 Auth algorithm

$auth.alg - the algorithm string from Authorization or Proxy-Authorization header
3.11 Auth QOP

$auth.qop - the value of qop parameter from Authorization or Proxy-Authorization header
3.12 Auth nonce count (nc)

$auth.nc - the value of nonce count parameter from Authorization or Proxy-Authorization header
3.13 Auth whole username

$aU - whole username from Authorization or Proxy-Authorization header
3.14 Acc username

$Au - username for accounting purposes. It's a selective pseudo variable (inherited from acc module). It returns $au if exits or From username otherwise.
3.15 Argument options

$argv - provides access to command line arguments specified with '-o' option. Examples:
   # for option '-o foo=0'
   xlog("foo is $argv(foo) \n");
3.16 Branch flags

$bf - displays a list with the branch flags set for the current SIP request
3.17 Branch flags (hexadecimal) (Removed in OpenSIPS 1.9)

$bF - reference to branch flags - hexa output
3.18 Branch

$branch - this variable is used for creating new branches by writing into it the value of a SIP URI. Examples:
   # creates a new branch
   $branch = "sip:new@doamin.org";
   # print its URI
   xlog("last added branch has URI $(branch(uri)[-1]) \n");
3.19 Branch fields

$branch() - this variable provides read/write access to all fields/attributes of an already existing branch (priorly created with append_branch() ). The fields of the branch are:
uri - the RURI of the branch (string value)
duri - destination URI of the branch (outbound proxy of the branch) (string value)
q - q value of the branch (int value)
path - the PATH string for this branch (string value)
flags - the branch flags of this branch (int value)
socket - the local socket to be used for relaying this branch (string value)
The variable accepts also index $(branch(uri)[1]) for accessing a specific branch (multiple branches can be defined at a moment). The index starts from 0 (first branch). If the index is negative, it is considered the n-th branch from the end ( index -1 means the last branch).
To get all branches, use the * index - $(branch(uri)[*]).
Examples:
   # creates the first branch
   append_branch();
   # creates the second branch
   force_send_socket(udp:192.168.1.11:5060);
   $du = "sip:192.168.2.10";
   append_branch("sip:foo@bar.com","0.5");

   # display branches
   xlog("----- branch 0: $(branch(uri)[0]) , $(branch(q)[0]), $(branch(duri)[0]), $(branch(path)[0]), $(branch(flags)[0]), $(branch(socket)[0]) \n");
   xlog("----- branch 1: $(branch(uri)[1]) , $(branch(q)[1]), $(branch(duri)[1]), $(branch(path)[1]), $(branch(flags)[1]), $(branch(socket)[1]) \n");

   # do some changes over the branches
   $branch(uri) = "sip:user@domain.ro";   # set URI for the first branch
   $(branch(q)[0]) = 1000;  # set to 1.00 for the first branch
   $(branch(socket)[1]) = NULL;  # reset the socket of the second branch
   $branch(duri) = NULL;  # reset the destination URI or the first branch
It is R/W variable (you can assign values to it from routing logic)
3.20 Call-Id

$ci - reference to body of call-id header
3.21 Content-Length

$cl - reference to body of content-length header
3.22 CSeq number

$cs - reference to cseq number from cseq header
3.23 Contact instance

$ct - reference to contact instance/body from the contact header. A contact instance is display_name + URI + contact_params. As a Contact header may contain multiple Contact instances and a message may contain multiple Contact headers, an index was added to the $ct variable:
$ct -first contact instance from message
$(ct[n]) - the n-th contact instance form the beginning of message, starting with index 0
$(ct[-n]) - the n-th contact instance form the end of the message, starting with index -1 (the last contact instance)
3.24 Fields of a contact instance

$ct.fields() - reference to the fields of a contact instance/body (see above). Supported fields are:
name - display name
uri - contact uri
q - q param (value only)
expires - expires param (value only)
methods - methods param (value only)
received - received param (value only)
params - all params (including names)
Examples:
$ct.fields(uri) - the URI of the first contact instance
$(ct.fields(name)[1]) - the display name of the second contact instance
3.25 Content-Type

$cT - reference to body of content-type header
3.26 Domain of destination URI

$dd - reference to domain of destination uri
It is R/W variable (you can assign values to it from routing logic)
3.27 Diversion header URI

$di - reference to Diversion header URI
3.28 Diversion "privacy" parameter

$dip - reference to Diversion header "privacy" parameter value
3.29 Diversion "reason" parameter

$dir - reference to Diversion header "reason" parameter value
3.30 Port of destination URI

$dp - reference to port of destination uri
It is R/W variable (you can assign values to it from routing logic)
3.31 Transport protocol of destination URI

$dP - reference to transport protocol of destination uri
3.32 Destination set

$ds - reference to destination set
3.33 Destination URI

$du - reference to destination uri (outbound proxy to be used for sending the request) If loose_route() returns TRUE a destination uri is set according to the first Route header.
It is R/W variable (you can assign values to it from routing logic)
3.34 Error class

$err.class - the class of error (now is '1' for parsing errors)
3.35 Error level

$err.level - severity level for the error
3.36 Error info

$err.info - text describing the error
3.37 Error reply code

$err.rcode - recommended reply code
3.38 Error reply reason

$err.rreason - recommended reply reason phrase
3.39 From URI domain

$fd - reference to domain in URI of 'From' header
3.40 From display name

$fn - reference to display name of 'From' header
3.41 Forced socket

$fs - reference to the forced socket for message sending (if any) in the form proto:ip:port
It is R/W variable (you can assign values to it routing script)
3.42 From tag

$ft - reference to tag parameter of 'From' header
3.43 From URI

$fu - reference to URI of 'From' header
3.44 From URI username

$fU - reference to username in URI of 'From' header
3.45 SIP message buffer

$mb - reference to SIP message buffer
3.46 Message Flags

$mf - displays a list with the message/transaction flags set for the current SIP request
3.47 Message Flags (hexadecimal) (Removed in OpenSIPS 1.9)

$mF -reference to message/transaction flags set for current SIP request in hexa
3.48 SIP message ID

$mi - reference to SIP message id
3.49 SIP message length

$ml - reference to SIP message length
3.50 Domain in SIP Request's original URI

$od - reference to domain in request's original R-URI
3.51 Port of SIP request's original URI

$op - reference to port of original R-URI
3.52 Transport protocol of SIP request original URI

$oP - reference to transport protocol of original R-URI
3.53 SIP Request's original URI

$ou - reference to request's original URI
3.54 Username in SIP Request's original URI

$oU - reference to username in request's original URI
3.55 Route parameter

$param(idx) - retrieves the parameters of the route. The index can be an integer, or a pseudo-variable (index starts at 1).
Example:
   route {
      ...
      $var(debug) = "DBUG:"
      route(PRINT_VAR, $var(debug), "param value");
      ...
   }

   route[PRINT_VAR] {
      $var(index) = 2;
      xlog("$param(1): The parameter value is <$param($var(index))>\n");
   }
3.56 Domain in SIP Request's P-Preferred-Identity header URI

$pd - reference to domain in request's P-Preferred-Identity header URI (see RFC 3325)
3.57 Display Name in SIP Request's P-Preferred-Identity header

$pn - reference to Display Name in request's P-Preferred-Identity header (see RFC 3325)
3.58 Process id

$pp - reference to process id (pid)
3.59 Protocol of received message

$pr or $proto - protocol of received message (UDP, TCP, TLS, SCTP)
3.60 User in SIP Request's P-Preferred-Identity header URI

$pU - reference to user in request's P-Preferred-Identity header URI (see RFC 3325)
3.61 URI in SIP Request's P-Preferred-Identity header

$pu - reference to URI in request's P-Preferred-Identity header (see RFC 3325)
3.62 Domain in SIP Request's URI

$rd - reference to domain in request's URI
It is R/W variable (you can assign values to it routing script)
3.63 Body of request/reply

$rb - reference to message body
3.64 Returned code

$rc - reference to returned code by last invoked function
$retcode - same as **$rc**
3.65 Remote-Party-ID header URI

$re - reference to Remote-Party-ID header URI
3.66 SIP request's method

$rm - reference to request's method
3.67 SIP request's port

$rp - reference to port of R-URI
It is R/W variable (you can assign values to it routing script)
3.68 Transport protocol of SIP request URI

$rP - reference to transport protocol of R-URI
3.69 SIP reply's reason

$rr - reference to reply's reason
3.70 SIP reply's status

$rs - reference to reply's status
3.71 Refer-to URI

$rt - reference to URI of refer-to header
3.72 SIP Request's URI

$ru - reference to request's URI
It is R/W variable (you can assign values to it routing script)
3.73 Username in SIP Request's URI

$rU - reference to username in request's URI
It is R/W variable (you can assign values to it routing script)
3.74 Q value of the SIP Request's URI

$ru_q - reference to q value of the R-URI
It is R/W variable (you can assign values to it routing script)
3.75 Received IP address

$Ri - reference to IP address of the interface where the request has been received
3.76 Received port

$Rp - reference to the port where the message was received
3.77 Script flags

$sf - displays a list with the script flags set for the current SIP request
3.78 Script flags (hexadecimal) (Removed in OpenSIPS 1.9)

$sF - reference to script flags - hexa output
3.79 IP source address

$si - reference to IP source address of the message
3.80 Source port

$sp - reference to the source port of the message
3.81 To URI Domain

$td - reference to domain in URI of 'To' header
3.82 To display name

$tn - reference to display name of 'To' header
3.83 To tag

$tt - reference to tag parameter of 'To' header
3.84 To URI

$tu - reference to URI of 'To' header
3.85 To URI Username

$tU - reference to username in URI of 'To' header
3.86 Formatted date and time

$time(format) - returns the string formatted time according to UNIX date (see: man date).
3.87 Branch index

$T_branch_idx - the index (starting with 1 for the first branch) of the branch for which is executed the branch_route[]. If used outside of branch_route[] block, the value is '0'. This is exported by TM module.
3.88 String formatted time

$Tf - reference string formatted time
3.89 Current unix time stamp in seconds

$Ts - reference to current unix time stamp in seconds
3.90 Current microseconds of the current second

$Tsm - reference to current microseconds of the current second
3.91 Startup unix time stamp

$TS - reference to startup unix time stamp
3.92 User agent header

$ua - reference to user agent header field
3.93 SIP Headers

$(hdr(name)[N]) - represents the body of the N-th header identified by 'name'. If [N] is omitted then the body of the first header is printed. The first header is got when N=0, for the second N=1, a.s.o. To print the last header of that type, use -1, no other negative values are supported now. No white spaces are allowed inside the specifier (before }, before or after {, [, ] symbols). When N='*', all headers of that type are printed.
The module should identify most of compact header names (the ones recognized by OpenSIPS which should be all at this moment), if not, the compact form has to be specified explicitly. It is recommended to use dedicated specifiers for headers (e.g., %ua for user agent header), if they are available -- they are faster.
$(hdrcnt(name)) -- returns number of headers of type given by 'name'. Uses same rules for specifying header names as $hdr(name) above. Many headers (e.g., Via, Path, Record-Route) may appear more than once in the message. This variable returns the number of headers of a given type.
Note that some headers (e.g., Path) may be joined together with commas and appear as a single header line. This variable counts the number of header lines, not header values.
For message fragment below, $hdrcnt(Path) will have value 2 and $(hdr(Path)[0]) will have value <a.com>:
    Path: <a.com>
    Path: <b.com>
For message fragment below, $hdrcnt(Path) will have value 1 and $(hdr(Path)[0]) will have value <a.com>,<b.com>:
    Path: <a.com>,<b.com>
Note that both examples above are semantically equivalent but the variables take on different values.
4. Escape Sequences

These sequences are exported, and mainly used, by xlog module to print messages in many colors (foreground and background) using escape sequences.
4.1 Foreground and background colors

$C(xy) - reference to an escape sequence. ¿x¿ represents the foreground color and ¿y¿ represents the background color.
Colors could be:
x : default color of the terminal
s : Black
r : Red
g : Green
y : Yellow
b : Blue
p : Purple
c : Cyan
w : White
4.2 Examples

A few examples of usage.
...
route {
...
    $avp(uuid)="caller_id";
    $avp(tmp)= $avp(uuid) + ": " + $fu;
    xlog("$C(bg)$avp(tmp)$C(xx) [$avp(tmp)] $C(br)$cseq$C(xx)=[$hdr(cseq)]\n");
...
}
...


1.  Types of flags

message flags (or transaction flags) these flags are transaction persistent. They are visible in all routes and cases where the transaction context is visible
branch flags are saved also in transaction, but per branch; also they will be saved in usrloc (per contact). A new set of functions were added for manipulating these flags from script. So, there flags will be registration persistent and branch persistent.
script flags are no-message-related flags - they are only script persistent and you can strictly use them for scripting. Once you exit a top level route, they will be lost. These flags are useful and they offer an option to de-congest the message flags - many flags have no need to be saved as they just reflect some scripting status.
2.  Corresponding Functions

Starting from OpenSIPS 1.9, flags may receive alphanumerical values. However, this does not affect performance, since they are converted into bit indexes upon startup. When it comes to DB persistency (only a few modules do this - e.g. usrloc), flags are generally stored in their string form, in order to preserve their semantics, and not the bit index they received during a given OpenSIPS run.
2.1  Message/transaction flags

setflag(FLAG)
resetflag(FLAG)
isflagset(FLAG)
Examples: setflag(accounting), resetflag(DO_NAT) or setflag(19)
2.2  Branch flags

setbflag/setbranchflag(branch_idx, FLAG)
resetbflag/resetbranchflag(branch_idx, FLAG)
isbflagset/isbranchflagset(branch_idx, FLAG)

or, the shorter format, working on the default (branch 0) flags:
setbflag(FLAG)
resetbflag(FLAG)
isbflagset(FLAG)
2.3  Script flags

setsflag/setscriptflag(FLAG)
resetsflag/resetscriptflag(FLAG)
issflagset/isscriptflagset(FLAG)
3.  Flags and Pseudo Variables

3.1  Message/transaction flags

$mf - ReadOnly; outputs a list of flags
3.2  Branch flags

$bf - ReadOnly; returns a list of flags
3.3  Script flags

$sf - ReadOnly; outputs a list of flags
4.  Flags and routes

4.1  Message/transaction flags

These flags will show up in all routes where messages related to the initial request are processed. So, they will be visible and changeable in onbranch, failure and onreply routes; the flags will be visible in all branch routes; if you change a flag in a branch route, the next branch routes will inherit the change.
4.2  Branch flags

There flags will show up in all routes where messages related to initial branch request are processed. So, in branch route you will see different sets of flags (as they are different branches); in onreply route yo will see the branch flags corresponding to the branch the reply belongs to; in failure route, the branch flags corresponding to the branch the winning reply belongs to will be visible. In request route, you can have multiple branches (as a result of a lookup(), enum query, append_branch(), etc) - the default branch is 0 (corresponding to the RURI); In reply routes there will be only one branch , the 0 one. In branch route the default branch is the current process branch (having index 0); In failure route, initially there is only one branch (index 0), corresponding the failed branch.
4.3  Script flags

There flags are available only in script and are reset after each top level route execution (routes internally triggered by OpenSIPS). They will be persistent per main route, onreply_route, branch_route, failure_route. Note they will be inherit in routes called from other routes.
5.  Example

5.1  Nat flag handling

 ..........
 # 3 - the nat flag
 modparam("usrloc", "nat_bflag", "NAT_BFLAG")
 ..........

 route {
   ..........
   if (nat detected)
      setbflag(NAT_BFLAG); # set branch flag "NAT_BFLAG" for the branch 0

   ..........
   if (is_method("REGISTER")) {
      # the branch flags (including "NAT_BFLAG") will be saved into location
      save("location");
      exit;
   } else {
      # lookup will load the branch flag from location
      if (!lookup("location")) {
         sl_send_reply("404","Not Found");
         exit;
      }
      t_on_branch("1")
      t_relay();
   }
 }

 branch_route[1] {
   xlog("-------branch=$T_branch_idx, branch flags=$bF\n");
   if (isbflagset(NAT_BFLAG)) {
      #current branch is marked as natted
      .........
   }
 }
if no parallel forking is done, you can get rid of the branch route and add instead of t_on_branch():
   ........
   if (isbflagset(NAT_BFLAG)) {
      #current branch is marked as natted
      .........
   }
   .........


A Transformation is basically a function that is applied to a variable(script variable, pseudo-variables, AVPS, static strings) to get a special value from it. The value of the original variable is not altered.
Example of using different kind of variables in OpenSIPS script:
# check if username in From header is equal with username in To header
if($fU==$tU) {
   ...
}

# r-uri username based processing
switch($ruri.user) {
   case "1234":
      ...
   break;
   case "5678":
      ...
   break;
   default:
     ...
}

# assign integer value to an AVP
$avp(i:11) = 1;

#assing string value to an AVP
$avp(i:22) = "opensips";

# write ruri in an AVP
$avp(i:33) = $ruri;

# concat "sip:" + From username + "@" + To domain in a script variable x
$var(x) = "sip:" + $fU +"@" + $td;


The transformations are intended to facilitate access to different attributes of variables (like strlen of value, parts of value, substrings) or complete different value of variables (encoded in hexa, md5 value, escape/unescape value for DB operations...).
A transformation is represented in between '{' and '}' and follows the name of a variable. When using transformations, the variable name and transformations must be enclosed in between '(' and ')'.
Example:
# the length of From URI ($fu is pseudo-variable for From URI)

$(fu{s.len})
Many transformations can be applied in the same time to a variable.
# the length of escaped 'Test' header body

$(hdr(Test){s.escape.common}{s.len})
The transformations can be used anywhere, being considered parts of script variables support -- in xlog, avpops or other modules' functions and parameters, in right side assignment expressions or in comparisons.
IMPORTANT: To learn what variables can be used with transformations see Scripting variables list.
1. String Transformations

The name of these transformation starts with 's.'. They are intended to apply string operations to variables.
Available transformations in this class:
1.1 {s.len}

Return strlen of variable value
$var(x) = "abc";
if($(var(x){s.len}) == 3)
{
   ...
}
1.2 {s.int}

Return integer value of a string-represented number
$var(x) = "1234";
if($(var(x){s.int})==1234) {
  ...
}
1.3 {s.md5}

Return md5 over variable value
xlog("MD4 over From username: $(fU{s.md5})");
1.4 {s.substr,offset,length}

Return substring starting at offset having size of 'length'. If offset is negative, then it is counted from the end of the value, -1 being the last char. In case of positive value, 0 is first char. Length must be positive, in case of 0, substring to the end of variable value is returned. offset and length can be a varibale as well.
Example:
$var(x) = "abcd";
$(var(x){s.substr,1,0}) = "bcd"
1.5 {s.select,index,separator}

Return a field from the value of a variable. The field is selected based on separator and index. The separator must be a character used to identify the fields. Index must be a integer value or a variable. If index is negative, the count of fields starts from end of value, -1 being last field. If index is positive, 0 is the first field.
Example:
$var(x) = "12,34,56";
$(var(x){s.select,1,,}) => "34" ;

$var(x) = "12,34,56";
$(var(x){s.select,-2,,}) => "34"
1.6 {s.encode.hexa}

Return encoding in hexa of variable's value
1.7 {s.decode.hexa}

Return decoding from hexa of variable's value
1.8 {s.escape.common}

Return escaped string of variable's value. Characters escaped are ', ", and 0. Useful when doing DB queries (care should be taken for non Latin character set).
1.9 {s.unescape.common}

Return unescaped string of variable's value. Reverse of above transformation.
1.10 {s.escape.user}

Return escaped string of variable's value, changing to '%hexa' the characters that are not allowed in user part of SIP URI following RFC requirements.
1.11 {s.unescape.user}

Return unescaped string of variable's value, changing '%hexa' to character code. Reverse of above transformation.
1.12 {s.escape.param}

Return escaped string of variable's value, changing to '%hexa' the characters that are not allowed in the param part of SIP URI following RFC requirements.
1.13 {s.unescape.param}

Return unescaped string of variable's value, changing '%hexa' to character code. Reverse of above transformation.
1.14 {s.tolower}

Return string with lower case ASCII letters.
1.15 {s.toupper}

Return string with upper case ASCII letters.
1.16 {s.dec2hex}

Converts a decimal(base 10) number to hexadecimal (in base 16), represented as string.
1.17 {s.hex2dec}

Converts a hexadecimal number (base 16) represented as string to decimal (base 10).
1.18 {s.index}

Searches for one string within another starting at the beginning of the first string. Returns starting index of the string found or -1 if not found. The optional index specifies the offset to begin the search at in the string. Negative offsets are supported and will wrap.

$var(strtosearch) = 'onetwothreeone';
$var(str) = 'one';

# Search the string starting at 0 index
$(var(strtosearch){s.index, $var(str)}) # will return 0
$(var(strtosearch){s.index, $var(str), 0}) # Same as above
$(var(strtosearch){s.index, $var(str), 3}) # returns 11

# Negative offset
$(var(strtosearch){s.index, $var(str), -11}) # Same as above

# Negative wrapping offset
$(var(strtosearch){s.index, $var(str), -25}) # Same as above

#Test for existence of string in another
if ($(var(strtosearch){s.index, $var(str)}) >=0)
    xlog("found $var(sstr) in $var(strtosearch)");

1.19 {s.rindex}

Searches for one string within another starting at the end of the first string. Returns starting index of the string found or -1 if not found. The optional index specifies an offset to start the search before, e.g the start of the found string will be before the supplied offset. Negative offsets are supported and will wrap.

$(var(strtosearch){s.rindex, $var(str)}) # will return 11
$(var(strtosearch){s.rindex, $var(str), -3}) # will return 11
$(var(strtosearch){s.rindex, $var(str), 11}) # will return 11
$(var(strtosearch){s.rindex, $var(str), -4}) # will return 0

2. URI Transformations

The name of transformation starts with 'uri.'. The value of the variable is considered to be a SIP URI. This transformation returns parts of SIP URI (see struct sip_uri). If that part is missing, the returned value is an empty string.
Available transformations in this class:
2.1 {uri.user}

Returns the user part of the URI schema.
2.2 {uri.host}

(same as {uri.domain})
Returns the domain part of the URI schema.
2.3 {uri.passwd}

Returns the password part of the URI schema.
2.4 {uri.port}

Returns the port of the URI schema.
2.5 {uri.params}

Returns all the URI parameters into a single string.
2.6 {uri.param,name}

Returns the value of URI parameter with name "name"
2.7 {uri.headers}

Returns URI headers.
2.8 {uri.transport}

Returns the value of transport URI parameter.
2.9 {uri.ttl}

Returns the value of ttl URI parameter.
2.10 {uri.uparam}

Returns the value of user URI parameter
2.11 {uri.maddr}

Returns the value of maddr URI parameter.
2.12 {uri.method}

Returns the value of method URI parameter.
2.13 {uri.lr}

Returns the value of lr URI parameter.
2.14 {uri.r2}

Returns the value of r2 URI parameter.
3. VIA Transformations

These transformations parse Via headers and all starts with via.. The value of the variable is considered to be a SIP Via header. This transformation returns parts of the via header (see struct via_body). If the requested part is missing, the returned value is an empty string. Transformation will fail (with script error) if variable holding the Via header is empty. Unless otherwise specified in descriptions below, the result of transform is a string (not an integer).
Examples:
    $var(upstreamtransport) = $(hdr(Via)[1]{via.transport}{s.tolower});
    $var(upstreamip) = $(hdr(Via)[1]{via.param,received});
    $var(clientport) = $(hdr(Via)[-1]{via.param,rport});
Available transformations in this class:
3.1 {via.name}

Returns the protocol-name (of RFC3261 BNF), generally SIP.
3.2 {via.version}

Returns the protocol-version (of RFC3261 BNF), generally 2.0.
3.3 {via.transport}

Returns the transport (of RFC3261 BNF), e.g., UDP, TCP, TLS. This is the transport protocol used to send the request message.
3.4 {via.host}

(same as {via.domain})
Returns the host portion of the sent-by (of RFC3261 BNF). Typically this is the IP address of the sender of the request message, and is the address to which the response will be sent.
3.5 {via.port}

Returns the port portion of the sent-by (of RFC3261 BNF). Typically this is the IP port of the sender of the request message, and is the address to which the response will be sent. Result of transform is valid as both integer and string.
3.6 {via.comment}

The comment associated with the via header. The struct via_body contains this field, but it isn't clear that RFC3261 allows Via headers to have comments (see text at top of page 221, and the BNF doesn't explicit allow comment within Via). The comment is the text enclosed within parens.
3.7 {via.params}

Returns all the Via headers parameters (via-param of RFC3261 BNF) as single string. Result can be processed using the {param.*} transforms. This is essentially everything after the host and port.
3.8 {via.param,name}

Returns the value of Via header parameter with name name. Typical parameters include branch, rport and received.
3.9 {via.branch}

Returns the value of the branch parameter in the VIA header.
3.10 {via.received}

Returns the value of the received parameter in the VIA header, if any.
3.11 {via.rport}

Returns the value of the rport parameter in the VIA header, if any.
4. Parameters List Transformations

The name of the transformation starts with "param.". The value of the variable is considered to be a string like name1=value1;name2=value2;...". The transformations returns the value for a specific parameter, or the name of a parameter at a specific index.
Available transformations in this class:
4.1 {param.value,name}

Returns the value of parameter 'name'
Example:
"a=1;b=2;c=3"{param.value,c} = "3"
'name' can be a variable
4.2 {param.exist,name}

Returns 1 if the parameter name exists (with or without value), else 0. Returned value is both string and integer. name can be variable. This can be used to test existence of parameters that do not have values.
Example:
"a=0;b=2;ob;c=3"{param.exist,ob};         # returns 1
"a=0;b=2;ob;c=3"{param.exist,a};          # returns 1
"a=0;b=2;ob;c=3"{param.exist,foo};        # returns 0
4.3 {param.valueat,index}

Returns the value of parameter at position give by 'index' (0-based index)
Example:
"a=1;b=2;c=3"{param.valueat,1} = "2"
'index' can be a variable
4.4 {param.name,index}

Returns the name of parameter at position 'index'.
Example:
"a=1;b=2;c=3"{param.name,1} = "b"
4.5 {param.count}

Returns the number of parameters in the list.
Example:
"a=1;b=2;c=3"{param.count} = 3
5. Name-address Transformations

The name of the transformation starts with 'nameaddr.'. The value of the variable is considered to be a string like '[display_name] uri'. The transformations returns the value for a specific field.
Available transformations in this class:
5.1 {nameaddr.name}

Returns the value of display name
Example:
'"test" <sip:test@opensips.org>' {nameaddr.name} = "test"
5.2 {nameaddr.uri}

Returns the value of URI
Example:
'"test" <sip:test@opensips.org>' {nameaddr.uri} = sip:test@opensips.org
5.3 {nameaddr.len}

Returns the length of the entire name-addr part from the value.
5.4 {nameaddr.param,param_name}

Returns the value of the parameter with name param_name. Example:
'"test" <sip:test@opensips.org>;tag=dat43h' {nameaddr.param,tag} = dat43h
5.5 {nameaddr.params}

Returns all the parameters and their corresponding values. Example:
'"test" <sip:test@opensips.org>;tag=dat43h;private=yes' {nameaddr.params} = "tag=dat43h;private=yes"
6. IP Transformations

The name of the transformation starts with 'ip.'. Available transformations in this class:
6.1 {ip.pton}

Returns a binary representation of a string represented IP. Example:
"192.168.2.134" {ip.pton} returns a 4 byte binary representation of the IP provided
6.2 {ip.ntop}

Returns a string representation of the binary IP provided Example:
"192.168.2.134"{ip.pton}{ip.ntop} = "192.168.2.134"
6.3 {ip.isip}

Returns 1 or 0, if the string provided is a valid IP or not. Example:
"192.168.2.134" {ip.isip} = 1
"192.168.2.134.1" {ip.isip} = 0
6.4 {ip.family}

Returns INET or INET6 if the binary IP representation provided is IPv4 or IPv6. Example:
"192.168.2.134" {ip.pton}{ip.family} = "INET"
6.5 {ip.resolve}

Returns the resolved IP address coresponding to the string domain provided. Transformation has no effect if a string IP is provided. Example:
"opensips.org" {ip.resolve} = "78.46.64.50"
7. CSV Transformations

The name of the transformation starts with "csv.". The value of the variable is considered to be a string like "field1,field2,...". The transformations return the number of entries in the provided CSV, or the field at a specified position in the CSV.
Available transformations in this class:
7.1 {csv.count}

Returns the number of entries in the provided CSV. Example:
"a,b,c" {csv.count} = 3
7.2 {csv.value}

Returns the entry at the specified positions. Indexing starts from 0. Example:
"a,b,c" {csv.value,2} = c
8. SDP Transformations

The name of the transformation starts with "sdp.". The value of the variable is considered to be a valid SDP body. The transformation returns a specific line in the SDP body.
Available transformations in this class:
8.1 {sdp.line}

Returns the specified line in the SDP body. The transformations also accepts a second parameter, that specifies the line number of the first parameter's type to get from the SDP body. Indexing starts from 0. If the second parameter is missing, it is assumed to be 0. Example:
if (is_method("INVITE"))
   {
      $var(aline) = $(rb{sdp.line,a,1});
      xlog("The second a line in the SDP body is $var(aline)\n");
   }

if (is_method("INVITE"))
   {
      $var(mline) = $(rb{sdp.line,m});
      xlog("The first m line in the SDP body is $var(mline)\n");
   }
9. Regular Expression Transformations

The name of the transformation starts with "re.". The input can be any string.
9.1 {re.subst,reg_exp}

The reg_exp parameter can either be a plain string or a variable. The format of the reg_exp is :
    /posix_match_expression/replacement_expression/flags
The flags can be
    i - match ignore case
    s - match within multi-lines strings
    g - replace all matches
Example:
$var(reg_input)="abc";
$var(reg) = "/a/A/g";
xlog("Applying reg exp $var(reg) to $var(reg_input) : $(var(reg_input){re.subst,$var(reg)})\n");

...
...
xlog("Applying reg /b/B/g to $var(reg_input) : $(var(reg_input){re.subst,/b/B/g})\n");
10. Examples

Within a variable, many transformation can be applied, being executed from left to right.
The length of the value of parameter at postion 1 (remember 0 is first position, 1 is second position)
$var(x) = "a=1;b=22;c=333";
$(var(x){param.value,$(var(x){param.name,1})}{s.len}) = 2
Test if whether is un-registration or not
if(is_method("REGISTER") && is_present_hf("Expires") && $(hdr(Expires){s.int})==0)
    xlog("This is an un-registrationn");


如果在有疑问或需要沟通的地方,可以QQ:1354608370 或 加FreeSWITCH+Kamailio+Opensips QQ群: 293697898 沟通交流!