# Kamailio Perl API

## Kamailio

This module provides access to a limited number of Kamailio core functions. As the most interesting functions deal with SIP messages, they are located in the Kamailio::Message class below.

### log(level,message)

Logs the message with Kamailio's logging facility. The logging level is one of the following:

    * L_ALERT
    * L_CRIT
    * L_ERR
    * L_WARN
    * L_NOTICE
    * L_INFO
    * L_DBG

Please note that this method is NOT automatically exported, as it collides with the perl function log (which calculates the logarithm). Either explicitly import the function (via `use Kamailio qw ( log );`), or call it with its full name:

    Kamailio::log(L_INFO, "foobar");

## Kamailio::Message

This package provides access functions for a Kamailio `sip_msg` structure and its sub-components. Through its means it is possible to fully configure alternative routing decisions.

### getType()

Returns one of the constants SIP_REQUEST, SIP_REPLY, SIP_INVALID stating the type of the current message.

### getStatus()

Returns the status code of the current Reply message. This function is invalid in Request context!

### getReason()

Returns the reason of the current Reply message. This function is invalid in Request context!

### getVersion()

Returns the version string of the current SIP message.

### getRURI()

This function returns the recipient URI of the present SIP message:

`my $ruri = $m->getRURI();`

getRURI returns a string. See getParsedRURI() below how to receive a parsed structure.

This function is valid in request messages only.

### getMethod()

Returns the current method, such as `INVITE`, `REGISTER`, `ACK` and so on.

`my $method = $m->getMethod();`

This function is valid in request messages only.

### getFullHeader()

Returns the full message header as present in the current message. You might use this header to further work with it with your favorite MIME package.

`my $hdr = $m->getFullHeader();`

### getBody()

Returns the message body.

### getMessage()

Returns the whole message including headers and body.

### getHeader(name)

Returns the body of the first message header with this name.

`print $m->getHeader("To");`

`"John" <sip:john@doe.example>`

### getHeaderNames()

Returns an array of all header names. Duplicates possible!

### moduleFunction(func,string1,string2)

Search for an arbitrary function in module exports and call it with the parameters self, string1, string2.

`string1` and/or `string2` may be omitted.

As this function provides access to the functions that are exported to the Kamailio configuration file, it is autoloaded for unknown functions. Instead of writing

    $m->moduleFunction("sl_send_reply", "500", "Internal Error");
    $m->moduleFunction("xlog", "L_INFO", "foo");

you may as well write

    $m->sl_send_reply("500", "Internal Error");
    $m->xlog("L_INFO", "foo");

WARNING

In Kamailio 1.2, only a limited subset of module functions is available. This restriction will be removed in a later version.

Here is a list of functions that are expected to be working (not claiming completeness):

    * alias_db_lookup
    * consume_credentials
    * is_rpid_user_e164
    * append_rpid_hf
    * bind_auth
    * avp_print
    * cpl_process_register
    * cpl_process_register_norpl
    * load_dlg
    * ds_next_dst
    * ds_next_domain
    * ds_mark_dst
    * ds_mark_dst
    * is_from_local
    * is_uri_host_local
    * dp_can_connect
    * dp_apply_policy
    * enum_query (without parameters)
    * enum_fquery (without parameters)
    * is_from_user_enum (without parameters)
    * i_enum_query (without parameters)
    * imc_manager
    * jab_* (all functions from the jabber module)
    * load_gws (without parameters)
    * next_gw
    * from_gw (without parameters)
    * to_gw (without parameters)
    * load_contacts
    * next_contacts
    * sdp_mangle_ip
    * sdp_mangle_port
    * encode_contact
    * decode_contact
    * decode_contact_header
    * fix_contact
    * use_media_proxy
    * end_media_session
    * m_store
    * m_dump
    * fix_nated_contact
    * unforce_rtp_proxy
    * force_rtp_proxy
    * fix_nated_register
    * add_rcv_param
    * options_reply
    * checkospheader
    * validateospheader
    * requestosprouting
    * checkosproute
    * prepareosproute
    * prepareallosproutes
    * checkcallingtranslation
    * reportospusage
    * mangle_pidf
    * mangle_message_cpim
    * add_path (without parameters)
    * add_path_received (without parameters)
    * prefix2domain
    * allow_routing (without parameters)
    * allow_trusted
    * pike_check_req
    * handle_publish
    * handle_subscribe
    * stored_pres_info
    * bind_pua
    * send_publish
    * send_subscribe
    * pua_set_publish
    * loose_route
    * record_route
    * load_rr
    * sip_trace
    * sl_reply_error
    * sms_send_msg
    * sd_lookup
    * sstCheckMin
    * append_time
    * has_body (without parameters)
    * is_peer_verified
    * t_newtran
    * t_release
    * t_relay (without parameters)
    * t_flush_flags
    * t_check_trans
    * t_was_cancelled
    * t_load_contacts
    * t_next_contacts
    * uac_restore_from
    * uac_auth
    * has_totag
    * tel2sip
    * check_to
    * check_from
    * radius_does_uri_exist
    * ul_* (All functions exported by the usrloc module for user access)
    * xmpp_send_message

### log(level,message) (deprecated type)

Logs the message with Kamailio's logging facility. The logging level is one of the following:

    * L_ALERT
    * L_CRIT
    * L_ERR
    * L_WARN
    * L_NOTICE
    * L_INFO
    * L_DBG

The logging function should be accessed via the Kamailio module variant. This one, located in Kamailio::Message, is deprecated.

### rewrite_ruri(newruri)

Sets a new destination (recipient) URI. Useful for rerouting the current message/call.

    if ($m->getRURI() =~ m/\@somedomain.net/) {
      $m->rewrite_ruri("sip:dispatcher\@organization.net");
    }

### setFlag(flag)

Sets a message flag. The constants as known from the C API may be used, when Constants.pm is included.

### resetFlag(flag)

Resets a message flag.

### isFlagSet(flag)

Returns whether a message flag is set or not.

### pseudoVar(string)

Returns a new string where all pseudo variables are substituted by their values. Can be used to receive the values of single variables, too.

Please remember that you need to escape the '$' sign in perl strings!

### append_branch(branch,qval)

Append a branch to current message.

### getParsedRURI()

Returns the current destination URI as a Kamailio::URI object.

## Kamailio::URI

This package provides functions for access to sip_uri structures.

### user()

Returns the user part of this URI.

### host()

Returns the host part of this URI.

### passwd()

Returns the passwd part of this URI.

### port()

Returns the port part of this URI.

### params()

Returns the params part of this URI.

### headers()

Returns the headers part of this URI.

### transport()

Returns the transport part of this URI.

### ttl()

Returns the ttl part of this URI.

### user_param()

Returns the user_param part of this URI.

### maddr()

Returns the maddr part of this URI.

### method()

Returns the method part of this URI.

### lr()

Returns the lr part of this URI.

### r2()

Returns the r2 part of this URI.

### transport_val()

Returns the transport_val part of this URI.

### ttl_val()

Returns the ttl_val part of this URI.

### user_param_val()

Returns the user_param_val part of this URI.

### maddr_val()

Returns the maddr_val part of this URI.

### method_val()

Returns the method_val part of this URI.

### lr_val()

Returns the lr_val part of this URI.

### r2_val()

Returns the r2_val part of this URI.

## Kamailio::AVP

This package provides access functions for Kamailio's AVPs. These variables can be created, evaluated, modified and removed through this package.

Please note that these functions do NOT support the notation used in the configuration file, but directly work on strings or numbers. See documentation of add method below.

### add(name,val)

Add an AVP.

Add a Kamailio AVP to its environment. name and val may both be integers or strings; this function will try to guess what is correct. Please note that

    Kamailio::AVP::add("10", "10")

is something different than

    Kamailio::AVP::add(10, 10)

due to this evaluation: The first will create _string_ AVPs with the name 10, while the latter will create a numerical AVP.

You can modify/overwrite AVPs with this function.

### get(name)

get a Kamailio AVP:

    my $numavp = Kamailio::AVP::get(5);
    my $stravp = Kamailio::AVP::get("foo");

### destroy(name)

Destroy an AVP.

    Kamailio::AVP::destroy(5);
    Kamailio::AVP::destroy("foo");

## Kamailio::Utils::PhoneNumbers

Kamailio::Utils::PhoneNumbers - Functions for canonical forms of phone numbers.

    use Kamailio::Utils::PhoneNumbers;

    my $phonenumbers = new Kamailio::Utils::PhoneNumbers(
         publicAccessPrefix => "0",
         internationalPrefix => "+",
         longDistancePrefix => "0",
         areaCode => "761",
         pbxCode => "456842",
         countryCode => "49"
       );

    $canonical = $phonenumbers->canonicalForm("07612034567");
    $number    = $phonenumbers->dialNumber("+497612034567");

A telephone number starting with a plus sign and containing all dial prefixes is in canonical form. This is usually not the number to dial at any location, so the dialing number depends on the context of the user/system.

The idea to canonicalize numbers were taken from hylafax.

Example: +497614514829 is the canonical form of my phone number, 829 is the number to dial at Pyramid, 4514829 is the dialing number from Freiburg are and so on.

To canonicalize any number, we strip off any dial prefix we find and then add the prefixes for the location. So, when the user enters the number 04514829 in context pyramid, we remove the publicAccessPrefix (at Pyramid this is 0) and the pbxPrefix (4514 here). The result is 829. Then we add all the general dial prefixes - 49 (country) 761 (area) 4514 (pbx) and 829, the number itself => +497614514829

To get the dialing number from a canonical phone number, we subtract all general prefixes until we have something

As said before, the interpretation of a phone number depends on the context of the location. For the functions in this package, the context is created through the `new` operator.

The following fields should be set:

    'longDistancePrefix'
    'areaCode'
    'pbxCode'
    'internationalPrefix'
    'publicAccessPrefix'
    'countryCode'

This module exports the following functions when `use`ed:

### new(publicAccessPrefix,internationalPrefix,longDistancePrefix,countryCode,areaCode,pbxCode)

The new operator returns an object of this type and sets its locational context according to the passed parameters. See Kamailio::Utils::PhoneNumbers above.

### canonicalForm( number [, context] )

Convert a phone number (given as first argument) into its canonical form. When no context is passed in as the second argument, the default context from the systems configuration file is used.

### dialNumber( number [, context] )

Convert a canonical phone number (given in the first argument) into a number to to dial. WHen no context is given in the second argument, a default context from the systems configuration is used.

## Kamailio::LDAPUtils::LDAPConf

Kamailio::LDAPUtils::LDAPConf - Read openldap config from standard config files.

    use Kamailio::LDAPUtils::LDAPConf;
    my $conf = new Kamailio::LDAPUtils::LDAPConf();

This module may be used to retrieve the global LDAP configuration as used by other LDAP software, such as `nsswitch.ldap` and `pam-ldap`. The configuration is usually stored in `/etc/openldap/ldap.conf`

When used from an account with sufficient privileges (e.g. root), the ldap manager password is also retrieved.

### Constructor new()

Returns a new, initialized `Kamailio::LDAPUtils::LDAPConf` object.

### Method base()

Returns the servers base-dn to use when doing queries.

### Method host()

Returns the ldap host to contact.

### Method port()

Returns the ldap servers port.

### Method uri()

Returns an uri to contact the ldap server. When there is no ldap_uri in the configuration file, an `ldap:` uri is constructed from host and port.

### Method rootbindpw()

Returns the ldap "root" password.

Note that the `rootbindpw` is only available when the current account has sufficient privileges to access `/etc/openldap/ldap.secret`.

### Method rootbinddn()

Returns the DN to use for "root"-access to the ldap server.

### Method binddn()

Returns the DN to use for authentication to the ldap server. When no bind dn has been specified in the configuration file, returns the `rootbinddn`.

### Method bindpw()

Returns the password to use for authentication to the ldap server. When no bind password has been specified, returns the `rootbindpw` if any.

## Kamailio::LDAPUtils::LDAPConnection

Kamailio::LDAPUtils::LDAPConnection - Perl module to perform simple LDAP queries.

OO-Style interface:

    use Kamailio::LDAPUtils::LDAPConnection;
    my $ldap = new Kamailio::LDAPUtils::LDAPConnection;
    my @rows = $ldap-search("uid=andi","ou=people,ou=coreworks,ou=de");

Procedural interface:

    use Kamailio::LDAPUtils::LDAPConnection;
    my @rows = $ldap->search(
          new Kamailio::LDAPUtils::LDAPConfig(), "uid=andi","ou=people,ou=coreworks,ou=de");

This perl module offers a somewhat simplified interface to the `Net::LDAP` functionality. It is intended for cases where just a few attributes should be retrieved without the overhead of the full featured `Net::LDAP`.

### Constructor new( [config, [authenticated]] )

Set up a new LDAP connection.

The first argument, when given, should be a hash reference pointing to to the connection parameters, possibly a `Kamailio::LDAPUtils::LDAPConfig` object. This argument may be `undef` in which case a new (default) `Kamailio::LDAPUtils::LDAPConfig` object is used.

When the optional second argument is a true value, the connection will be authenticated. Otherwise an anonymous bind is done.

On success, a new `LDAPConnection` object is returned, otherwise the result is `undef`.

### Function/Method search( conf, filter, base, [requested_attributes ...])

perform an ldap search, return the dn of the first matching directory entry, unless a specific attribute has been requested, in which case the values(s) for this attribute are returned.

When the first argument (conf) is a `Kamailio::LDAPUtils::LDAPConnection`, it will be used to perform the queries. You can pass the first argument implicitly by using the "method" syntax.

Otherwise the `conf` argument should be a reference to a hash containing the connection setup parameters as contained in a `Kamailio::LDAPUtils::LDAPConf` object. In this mode, the `Kamailio::LDAPUtils::LDAPConnection` from previous queries will be reused.

#### Arguments:

conf

  configuration object, used to find host,port,suffix and use_ldap_checks

filter

  ldap search filter, eg '(mail=some@domain)'

base

  search base for this query. If undef use default suffix, concat base with default suffix if the last char is a ','

requested_attributes

  retrieve the given attributes instead of the dn from the ldap directory.

#### Result:

Without any specific `requested_attributes`, return the dn of all matching entries in the LDAP directory.

When some `requested_attributes` are given, return an array with those attributes. When multiple entries match the query, the attribute lists are concatenated.

## Kamailio::VDB

This package is an (abstract) base class for all virtual databases. Derived packages can be configured to be used by Kamailio as a database.

The base class itself should NOT be used in this context, as it does not provide any functionality.

## Kamailio::Constants

This package provides a number of constants taken from enums and defines of Kamailio header files. Unfortunately, there is no mechanism for updating the constants automatically, so check the values if you are in doubt.

## Kamailio::VDB::Adapter::Speeddial

This adapter can be used with the speeddial module.

## Kamailio::VDB::Adapter::Alias

This package is intended for usage with the alias_db module. The query VTab has to take two arguments and return an array of two arguments (user name/domain).

### query(conds,retkeys,order)

Queries the vtab with the given arguments for request conditions, keys to return and sort order column name.

## Kamailio::VDB::Adapter::AccountingSIPtrace

This package is an Adapter for the acc and siptrace modules, featuring only an insert operation.

## Kamailio::VDB::Adapter::Describe

This package is intended for debug usage. It will print information about requested functions and operations of a client module.

Use this module to request schema information when creating new adapters.

## Kamailio::VDB::Adapter::Auth

This adapter is intended for usage with the auth_db module. The VTab should take a username as an argument and return a (plain text!) password.

## Kamailio::VDB::ReqCond

This package represents a request condition for database access, consisting of a column name, an operator (=, <, >, ...), a data type and a value.

This package inherits from Kamailio::VDB::Pair and thus includes its methods.

### new(key,op,type,name)

Constructs a new Column object.

### op()

Returns or sets the current operator.

## Kamailio::VDB::Pair

This package represents database key/value pairs, consisting of a key, a value type, and the value.

This package inherits from Kamailio::VDB::Value and thus has the same methods.

### new(key,type,name)

Constructs a new Column object.

### key()

Returns or sets the current key.

## Kamailio::VDB::VTab

This package handles virtual tables and is used by the Kamailio::VDB class to store information about valid tables. The package is not intended for end user access.

### new()

    Constructs a new VTab object

### call(op,[args])

Invokes an operation on the table (insert, update, ...) with the given arguments.

## Kamailio::VDB::Value

This package represents a database value. Additional to the data itself, information about its type is stored.

### stringification

When accessing a Kamailio::VDB::Value object as a string, it simply returns its data regardless of its type. =cut

use strict;

package Kamailio::VDB::Value;

use overload '""' => \&stringify;

sub stringify { shift->{data} }

use Kamailio; use Kamailio::Constants;

our @ISA = qw ( Kamailio::Utils::Debug );

### new(type,data)

Constructs a new Value object. Its data type and the data are passed as parameters.

### type()

Returns or sets the current data type. Please consider using the constants from Kamailio::Constants

### data()

Returns or sets the current data.

## Kamailio::VDB::Column

This package represents database column definition, consisting of a column name and its data type.

### Stringification

When accessing a Kamailio::VDB::Column object as a string, it simply returns its column name regardless of its type. =cut

package Kamailio::VDB::Column;

use overload '""' => \&stringify;

sub stringify { shift->{name} }

use Kamailio; use Kamailio::Constants;

our @ISA = qw ( Kamailio::Utils::Debug );

### new(type,name)

Constructs a new Column object. Its type and the name are passed as parameters.

### type( )

Returns or sets the current type. Please consider using the constants from Kamailio::Constants

### name()

Returns or sets the current column name.

### Kamailio::VDB::Result

This class represents a VDB result set. It contains a column definition, plus an array of rows. Rows themselves are simply references to arrays of scalars.

### new(coldefs,[row, row, ...])

The constructor creates a new Result object. Its first parameter is a reference to an array of Kamailio::VDB::Column objects. Additional parameters may be passed to provide initial rows, which are references to arrays of scalars.

### coldefs()

    Returns or sets the column definition of the object.

### rows()

    Returns or sets the rows of the object.