Login | Register

Documentation

Documentation -> Manuals -> Manual 1.8 -> Core functions

Pages for other versions: devel 1.11 1.10 1.9 old versions: 1.8 1.7 1.6 1.5 1.4


Core functions v1.8
PrevNext

Table of Content (hide)

  1. 1. add_local_rport()
  2. 2. append_branch()
  3. 3. cache_store( storage_id, attribute_name, attribute_name [,timeout])
  4. 4. cache_remove( storage_id, attribute_name)
  5. 5. cache_fetch( storage_id, attribute_name, result_avp)
  6. 6. cache_add( storage_id, attribute_name,increment_value,expire)
  7. 7. cache_sub( storage_id, attribute_name,increment_value,expire)
  8. 8. break()
  9. 9. construct_uri(proto,user,domain,port,extra,result_avp)
  10. 10. drop()
  11. 11. exit()
  12. 12. force_rport()
  13. 13. force_send_socket([proto:]address[:port])
  14. 14. force_tcp_alias()
  15. 15. forward(destination)
  16. 16. get_timestamp(sec_avp,usec_avp)
  17. 17. isdsturiset()
  18. 18. isflagset(int)
  19. 19. isbflagset([branch_idx,] flag_idx)
  20. 20. issflagset(flag_idx)
  21. 21. log([level,] string)
  22. 22. next_branches()
  23. 23. prefix(string)
  24. 24. pv_printf(pv, string)
  25. 25. raise_event(string[, avp[, avp)]]
  26. 26. remove_branch(pv|int)
  27. 27. return(int)
  28. 28. resetdsturi()
  29. 29. resetflag(int)
  30. 30. resetbflag([branch_idx,] flag_idx)
  31. 31. resetsflag(flag_idx)
  32. 32. revert_uri()
  33. 33. rewritehost() / sethost()
  34. 34. rewritehostport() / sethostport()
  35. 35. rewriteuser(string) / setuser(string)
  36. 36. rewriteuserpass() / setuserpass()
  37. 37. rewriteport() / setport()
  38. 38. rewriteuri(str) / seturi(str)
  39. 39. send(destination [, headers])
  40. 40. serialize_branches(clear)
  41. 41. set_advertised_address(ip|string)
  42. 42. set_advertised_port(int)
  43. 43. setdebug([level])
  44. 44. setdsturi(string)
  45. 45. setflag(int)
  46. 46. setbflag([branch_idx,] flag_idx)
  47. 47. setsflag(flag_idx)
  48. 48. strip(int)
  49. 49. strip_tail(int)
  50. 50. subscribe_event(string, string [, int])
  51. 51. use_blacklist(string)
  52. 52. xlog([log_level, ]format_string)

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_avp)

This function fetches from a memory-cache-like-storage system the value of an attribute. The attribute name may contain pseudo-variables. The result (if any) will be stored in the result_avp AVP variable.

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_add( storage_id, attribute_name,increment_value,expire)

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.


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.

7. cache_sub( storage_id, attribute_name,increment_value,expire)

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.


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.

8. 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.

9. 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");

10. 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();
        }
    }

11. 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;
    };
  }

12. 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();

13. 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);

14. 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.

15. 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();

16. 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));

17. isdsturiset()

Test if the dst_uri field (next hop address) is set.

Example of usage:

    if(isdsturiset()) {
        log("dst_uri is set\n");
    };

18. 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");
    };

19. 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");
    };

20. 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");
    };

21. log([level,] string)

Write text message to standard error terminal or syslog. You can specify the log level as first parameter.

For more see: http://www.voice-system.ro/docs/ser-syslog/

Example of usage:

    log("just some text message\n");

22. 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();

23. prefix(string)

Add the string parameter in front of username in R-URI.

Example of usage:

    prefix("00");

24. 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");

25. 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));

26. 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;
   }
}

27. 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);
  };
}

28. 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();

29. 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);

30. 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)

31. 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);

32. 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();

33. 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");

34. 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");

35. rewriteuser(string) / setuser(string)

Rewrite the user part of the R-URI with the value of function's parameter.

Example of usage:

    rewriteuser("newuser");

36. rewriteuserpass() / setuserpass()

Rewrite the password part of the R-URI with the value of function's parameter.

Example of usage:

    rewriteuserpass("my_secret_passwd");

37. rewriteport() / setport()

Rewrites/sets the port part of the R-URI with the value of function's parameter.

Example of usage:

    rewriteport("5070");

38. rewriteuri(str) / seturi(str)

Rewrite the request URI.

Example of usage:

    rewriteuri("sip:test@opensips.org");

39. 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");

40. 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);

41. 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");

42. 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);

43. 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
      .......
    }

44. 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");

45. setflag(int)

Set a flag for current processed message. The value of the parameter can be in range of 0..31. The flags are used to mark the message for special processing (e.g., accounting) or to keep some state (e.g., message authenticated).

For more see http://www.voice-system.ro/docs/ser-flags/ .

Example of usage:

    setflag(3);

46. 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)

47. 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);

48. 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);

49. 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);

50. 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);
}

51. 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");

52. 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");

Page last modified on September 12, 2014, at 03:04 PM