Realtime Integration Of Asterisk 1.4 With OpenSER 1.3

valid for kamailio (openser) 1.3.x and asterisk 1.4.x — work in progress — updating from older version Realtime Integration Of Asterisk With OpenSER

  • latest release in 1.3 series of Kamailio (OpenSER) is v1.3.3
  • latest release in 1.4 series of Asterisk is v1.4.22

OpenSER is a pure VoIP signaling server using Session Initiation Protocol - SIP. It is flexible and highly configurable but cannot be used to provide media services as voicemail, anounncements or conferencing. For such services, Asterisk is the most suitable open source product. In this document we present how to configure Asterisk to use OpenSER's subscribers database to provide voicemail service. A basic configuration file for OpenSER is posted down the page, allowing to have a functional system by following the steps in this tutorial.


UnixODBC Installation

Install unixodbc-dev package via your package manager. Alternative is to get the sources from, compile and install them on your system, but Asterisk will have hard time to detect them and enable ODBC option for Voicemail application.

In Debian:

apt-get install unixodbc-dev

MySQL Installation

You can install MySQL using the packaging system from you Linux distribution. The only requirements is to be MySQL 5.0+. Most of the distributions deliver v5.0+ by default now.

After installation, you can set the MySQL root password with a command like:
/usr/bin/mysqladmin -u root password 'your-new-password'

Asterisk Installation

Get Asterisk sources from At this moment Asterisk 1.4.22 is the latest stable version.

cd /usr/local/src
tar xvfz asterisk-1.4.22.tar.gz
cd asterisk-1.4.22

Run make menuselect to enable ODBC storage for Voicemail, choose option 9. Voicemail Build Options, enable option 1. ODBC_STORAGE. Save and exit.

There is no longer need for patching Asterisk sources.

Proceed with usual Asterisk installation:

make install

Kamailio (OpenSER) Installation

You can download latest stable version via SVN snapshots. For branch 1.3 (latest release in this branch is 1.3.3) you can do:

cd /usr/local/src
tar xvfz openser-1.3.x-svn-latest.tgz
cd openser-1.3.x
make all include_modules="mysql"
make install include_modules="mysql"

UnixODBC MySQL Driver Installation

Simply install the package using the tools from your linux distribution. For example, for Debian:

apt-get install libmyodbc

Create Kamailio (OpenSER) Database

To create the database needed by OpenSER:

/usr/local/sbin/openserdbctl create

This will create a database named 'openser' and will add a MySQL user 'openser' with full access to it. The default password is 'openserrw', do change it before (by editing /usr/local/etc/openserctlrc) or immediately after you create the database.

Once you create the database, you need to add a new column to the 'subscriber' table to store the PIN for voicemail access:

ALTER TABLE subscriber ADD vmail_password varchar(32);

Create Asterisk Database

The database needed by Asterisk will contain two views ('vmusers' and 'sipusers') of tables from OpenSER database, therefore it is required to have MySQL 5.0+ since the views were introduced in this version. There is a real MySQL table ('voicemessages') which will store the voice messages.

Log in as root in MySQL server:

create database asterisk;

use asterisk;

CREATE TABLE `bit_voicemessages` (
`id` int(11) NOT NULL auto_increment,
`msgnum` int(11) NOT NULL default '0',
`dir` varchar(80) default '',
`context` varchar(80) default '',
`macrocontext` varchar(80) default '',
`callerid` varchar(40) default '',
`origtime` varchar(40) default '',
`duration` varchar(20) default '',
`mailboxuser` varchar(80) default '',
`mailboxcontext` varchar(80) default '',
`recording` longblob,
KEY `dir` (`dir`)

SELECT id as uniqueid,
username as customer_id,
'default' as context,
username as mailbox,
vmail_password as password,
CONCAT(first_name,' ',last_name) as fullname,
email_address as email,
NULL as pager,
datetime_created as stamp
FROM openser.subscriber;

SELECT username as name,
'friend' as type,
NULL as secret,
domain as host,
CONCAT(rpid, ' ','<',username,'>') as callerid,
'default' as context,
username as mailbox,
'yes' as nat,
'no' as qualify,
username as fromuser,
NULL as authuser,
domain as fromdomain,
NULL as insecure,
'no' as canreinvite,
NULL as disallow,
NULL as allow,
NULL as restrictcid,
domain as defaultip,
domain as ipaddr,
'5060' as port,
NULL as regseconds
FROM openser.subscriber;

Add a MySQL user which will have full access right to 'asterisk' database.

GRANT ALL ON asterisk.* to asterisk@localhost IDENTIFIED BY 'some_password';

Configure UnixODBC

In the file /usr/local/etc/odbcinst.ini you must add:

Description = MySQL driver
Driver = /usr/lib/odbc/
Setup = /usr/lib/odbc/
CPTimeout =
CPReuse =
UsageCount = 1

In the file '/usr/local/etc/odbc.ini' you must add:

Description = MySQL Asterisk database
Trace = Off
TraceFile = stderr
Driver = MySQL
SERVER = localhost
USER = asterisk
PASSWORD = some_password
PORT = 3306
DATABASE = asterisk

Configure Asterisk

In '/etc/asterisk/res_odbc.conf':

enabled => yes
dsn => MySQL-asterisk
username => asterisk
password => asterisk
pre-connect => yes

In '/etc/asterisk/extconfig.conf':

sipusers => odbc,asterisk,sipusers
sippeers => odbc,asterisk,sipusers
voicemail => odbc,asterisk,vmusers

In '/etc/asterisk/sip.conf':

If you want to enable MWI, do not forget to set checkmwi attribute and rtcachefriends=yes


Guidelines about configuring the SIP channel you find at You do not need to add any SIP user or peer in the configuration file, they will be loaded from database.

In ‘/etc/asterisk/voicemail.conf’ you do not need to add any mailbox. They will be loaded from database. The general configuration part of voicemail application is presented at

For our tutorial, we consider that the users will have 4-digit ID. To implement a clear dialing plan in Asterisk which allow extensibility and clear extentions for different services, the calls to voicemail will be prefixed with '1' in OpenSER proxy. This prefix will be transpartent for users. If voice mailbox does not exist, Asterisk will play "invalid extension" message.

In '/etc/asterisk/extensions.conf':

exten => 1,1,Ringing
exten => 1,2,VoicemailMain(${CALLERIDNUM})
exten => 1,3,Hangup

exten => 11,1,Ringing
exten => 11,2,VoicemailMain()
exten => 11,3,Hangup

exten => _1XXXX,1,Ringing
exten => _1XXXX,2,MailboxExists(${EXTEN:1})
exten => _1XXXX,3,Playback(invalid)
exten => _1XXXX,4,Hangup
exten => _1XXXX,103,Voicemail(u${EXTEN:1})
exten => _1XXXX,104,Hangup

Configure Kamailio (OpenSER)

Dialing plan:
- local users have 4-digit extension
- to listen its voice messages from its SIP phone, the user has to dial *98 (Asterisk will prompt only for PIN)
- to listen its voice messages from another SIP phone, the user has to dial *981 (Asterisk will prompt for mailbox ID and PIN)
- to call directly to leave voice message to user XXXX, the user has to dial *89XXXX

In '/usr/local/etc/openser/openser.cfg':

# $Id$

# ----------- global configuration parameters ------------------------

debug=3           # debug level (cmd line: -dddddddddd)
fork=yes          # daemonize
log_stderror=no   # (cmd line: -E)

check_via=no      # (cmd. line: -v)
dns=no            # (cmd. line: -r)
rev_dns=no        # (cmd. line: -R)


# ------------------ module loading ----------------------------------

# Uncomment this if you want to use SQL database
loadmodule ""

loadmodule ""
loadmodule ""
loadmodule ""
loadmodule ""
loadmodule ""
loadmodule ""
loadmodule ""
loadmodule ""
loadmodule ""
loadmodule ""
loadmodule ""
loadmodule ""
loadmodule ""

# ----------------- setting module-specific parameters ---------------
    "db_url", "mysql://openser:openserrw@localhost/openser")

# -- usrloc params --
# persistent storage
modparam("usrloc", "db_mode", 2)

# -- auth params --
# Uncomment if you are using auth module
modparam("auth_db", "calculate_ha1", yes)
# If you set "calculate_ha1" parameter to yes (which true in this config), 
# uncomment also the following parameter)
modparam("auth_db", "password_column", "password")

# -- rr params --
# add value to ;lr param to make some broken UAs happy
modparam("rr", "enable_full_lr", 1)

modparam("avpops", "avp_table", "usr_preferences")

# -------------------------  request routing logic -------------------

# main routing logic


	# initial sanity checks -- messages with
	# max_forwards==0, or excessively long requests
	if (!mf_process_maxfwd_header("10")) {
		sl_send_reply("483","Too Many Hops");

	if (msg:len >=  2048 ) {
		sl_send_reply("513", "Message too big");

	# we record-route all messages -- to make sure that
	# subsequent messages will go through our proxy; that's
	# particularly good if upstream and downstream entities
	# use different transport protocol
	if (!method=="REGISTER")

	# subsequent messages withing a dialog should take the
	# path determined by record-routing
	if (loose_route()) {
		# mark routing logic in request
		append_hf("P-hint: rr-enforced\r\n"); 

	if (!uri==myself) {
		# mark routing logic in request
		append_hf("P-hint: outbound\r\n"); 

	# if the request is for other domain use UsrLoc
	# (in case, it does not work, use the following command
	# with proper names and addresses in it)
	if (uri==myself) {

		if (method=="REGISTER") {
			if (!www_authorize("", "subscriber")) {
				www_challenge("", "0");


		# requests for Media server
		if(is_method("INVITE") && !has_totag() && uri=~"sip:\*9") {

		# mark transaction if user is in voicemail group
		if(is_method("INVITE") && !has_totag()
			&& is_user_in("Request-URI","voicemail"))
			xdbg("user [$ru] has voicemail redirection enabled\n");
			# backup R-URI
			avp_write("$ruri", "i:10");
		# native SIP destinations are handled using our USRLOC DB
		if (!lookup("location")) {
			if(isflagset(2)) {
				# route to Asterisk Media Server
			} else {
				sl_send_reply("404", "Not Found");
		append_hf("P-hint: usrloc applied\r\n"); 


route[1] {

	if (!t_relay()) {

# voicemail access
# - *98 - listen caller's voice messages, being prompted for pin
# - *981 - listen voice messages, being promted for mailbox and pin
# - *98XXXX - leave voice message to XXXX
route[3] {
  	# direct voicemail
	if (uri =~ "sip:\*98@" ) {
		xdbg("voicemail access\n");
	} else if (uri =~ "sip:\*981@" ) {
	} else if (uri =~ "sip:\*98.+@" ) {
	} else {
		xlog("unknown media extension $rU\n");
		sl_send_reply("404", "Unknown media service");

	# route to Asterisk Media Server

failure_route[1] {
	if (t_was_cancelled()) {
		xdbg("transaction was cancelled by UAC\n");
	# restore initial uri
	avp_pushto("$ruri", "i:10");
	# route to Asterisk Media Server

See also

Created by: miconda, Last modification: Thu 30 of Oct, 2008 (20:07 UTC) by festr
Please update this page with new information, just login and click on the "Edit" or "Discussion" tab. Get a free login here: Register Thanks! - Find us on Google+