Realtime Integration Of Asterisk With OpenSER

http://www.voip-info.org/wiki/view/Realtime+Integration+Of+Asterisk+With+OpenSER

 

 

 

valid for openser 1.1.x and asterisk 1.2.x



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.

Requirements


 

UnixODBC Installation



Get the sources from http://www.unixodbc.org, compile and install them on your system

cd /usr/local/src
wget http://www.unixodbc.org/unixODBC-2.2.11.tar.gz
tar xvfz unixODBC-2.2.11.tar.gz
cd unixODBC-2.2.11
./configure –enable-gui=no
make
make install


NOTE: if you get error during compilation in 'sqp/lex.l', the line 240, related to 'YY_FLUSH_BUFFER', you can safely comment/remove that line.

NOTE: you must have /usr/local/lib in your /etc/ld.so.conf file or LD_LIBRARY_PATH environment variable.

MySQL Installation



You can install MySQL using the packaging system from you Linux distribution. The only requirements is to be MySQL 5.0+. For example, http://dotdeb.org provides packages for Debian stable.

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 http://www.asterisk.org. At this moment Asterisk 1.2.9.1 is the latest stable version.

cd /usr/local/src
wget http://ftp.digium.com/pub/asterisk/releases/asterisk-1.2.9.1.tar.gz
tar xvfz asterisk-1.2.9.1.tar.gz
cd asterisk-1.2.9.1



Edit 'apps/Makefile' and uncomment lines:

CFLAGS+=-DUSE_ODBC_STORAGE
CFLAGS+=-DEXTENDED_ODBC_STORAGE



Edit 'apps/app_voicemail.c' and change the size of memeber 'uniqueid' in 'struct ast_vm_user' to 64:

/* Structure for linked list of users */
struct ast_vm_user {
       char context[AST_MAX_CONTEXT];  /* Voicemail context */
       char mailbox[AST_MAX_EXTENSION];/* Mailbox id, unique within vm context
       char password[80];              /* Secret pin code, numbers only */
       char fullname[80];              /* Full name, for directory app */
       char email[80];                 /* E-mail address */
       char pager[80];                 /* E-mail address to pager (no attachme
       char serveremail[80];           /* From: Mail address */
       char mailcmd[160];              /* Configurable mail command */
       char language[MAX_LANGUAGE];    /* Config: Language setting */
       char zonetag[80];               /* Time zone */
       char callback[80];
       char dialout[80];
       char uniqueid[64];              /* Unique integer identifier */ 
       char exit[80];
       unsigned int flags;             /* VM_ flags */
       int saydurationm;
       int maxmsg;                     /* Maximum number of msgs per folder fo
       struct ast_vm_user *next;
};



Proceed with usual Asterisk installation:

make
make install


OpenSER Installation



You can download latest stable version via CVS snapshots. For branch 1.0.0 (latest release in this branch is 1.0.1) you can do:

cd /usr/local/src
wget http://www.openser-project.org/downloads/snapshots/openser-1.0.0/openser-1.0.0-cvs-latest.tgz
tar xvfz openser-1.0.0-cvs-latest.tgz
cd openser-1.0.0
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 OpenSER Database



To create the database needed by OpenSER:

/usr/local/sbin/openser_mysql.sh 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/sbin/openser_mysql.sh) 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 `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,
  PRIMARY KEY  (`id`),
  KEY `dir` (`dir`)
) ENGINE=InnoDB;

CREATE VIEW vmusers AS
SELECT phplib_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;

CREATE VIEW sipusers AS
SELECT username as name,
  username,
  '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:

[MySQL]
Description = MySQL driver
Driver = /usr/lib/odbc/libmyodbc.so
Setup = /usr/lib/odbc/libodbcmyS.so
CPTimeout =
CPReuse =
UsageCount = 1



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

[MySQL-asterisk]
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':

[asterisk]
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.

checkmwi=10



Guidelines about configuring the SIP channel you find at http://www.voip-info.org/wiki-Asterisk+config+sip.conf. 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 http://www.voip-info.org/wiki/index.php?page=Asterisk+config+voicemail.conf

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 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)
children=4
fifo="/tmp/openser_fifo"

listen=udp:10.10.10.10:5060

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

# Uncomment this if you want to use SQL database
mpath="/usr/local/lib/openser/modules"
loadmodule "mysql.so"

loadmodule "xlog.so"
loadmodule "sl.so"
loadmodule "tm.so"
loadmodule "rr.so"
loadmodule "maxfwd.so"
loadmodule "usrloc.so"
loadmodule "registrar.so"
loadmodule "textops.so"
loadmodule "avpops.so"
loadmodule "auth.so"
loadmodule "auth_db.so"
loadmodule "group.so"
loadmodule "uri.so"

# ----------------- setting module-specific parameters ---------------
modparam("usrloc|auth_db|avpops|group",
    "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

route{

	# 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");
		exit;
	};

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

	# 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")
		record_route();

	# 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"); 
		route(1);
	};

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

	# 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("openser.org", "subscriber")) {
				www_challenge("openser.org", "0");
				exit;
			};

			save("location");
			exit;
		};

		# requests for Media server
		if(is_method("INVITE") && !has_totag() && uri=~"sip:/*9") {
			route(3);
			exit;
		}

		# 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");
			setflag(2);
		};
		# native SIP destinations are handled using our USRLOC DB
		if (!lookup("location")) {
			if(isflagset(2)) {
				# route to Asterisk Media Server
				prefix("1");
				rewritehostport("10.10.10.11:5060");
				route(1);
			} else {
				sl_send_reply("404", "Not Found");
				exit;
			}
		};
		append_hf("P-hint: usrloc applied/r/n"); 
	};

	route(1);
}


route[1] {
	
	if(isflagset(2))
		t_on_failure("1");

	if (!t_relay()) {
		sl_reply_error();
	};
	exit;
}


# 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@" ) {
        	rewriteuser("1");
		xdbg("voicemail access/n");
	} else if (uri =~ "sip:/*981@" ) {
 		strip(4);
		rewriteuser("11");
	} else if (uri =~ "sip:/*98.+@" ) {
 		strip(3);
		prefix("1");
	} else {
		xlog("unknown media extension $rU/n");
		sl_send_reply("404", "Unknown media service");
		exit;
	}

	# route to Asterisk Media Server
	rewritehostport("10.10.10.11:5060");
	route(1);
}

failure_route[1] {
	if (t_was_cancelled()) {
		xdbg("transaction was cancelled by UAC/n");
		return;
	}
	# restore initial uri
	avp_pushto("$ruri", "i:10");
	prefix("1");
	# route to Asterisk Media Server
	rewritehostport("10.10.10.11:5060");
	resetflag(2);
	route(1);
}


See also

<think>好的,我需要帮助用户了解如何在Asterisk Realtime中使用SQLite进行配置。首先,我需要确认自己对Asterisk Realtime的理解是否正确。Asterisk Realtime允许动态地从数据库读取配置,而不是传统的静态文件。用户提到使用SQLite,所以我需要专注于SQLite作为数据库的情况。 接下来,我应该考虑用户可能的背景。他们可能已经熟悉Asterisk的基本配置,但想转向使用数据库管理配置,特别是SQLite。因此,我需要从基础开始解释,确保他们理解必要的步骤,包括配置Asterisk以连接SQLite,创建数据库结构,以及配置Asterisk模块使用Realtime。 首先,我需要说明如何在Asterisk中启用SQLite支持。通常这涉及到编辑modules.conf文件,确保加载必要的模块,比如res_config_sqlite3.so。然后,配置res_sqlite3.conf文件,设置数据库的路径和其他参数。这里需要注意路径的正确性,以及权限设置,确保Asterisk进程有权限读写数据库文件。 接下来是创建数据库表结构。不同的模块(如SIP、拨号计划)需要不同的表结构。例如,sip_users表可能需要包含id、name、secret等字段。我需要给出具体的SQL示例,帮助用户创建正确的表结构。同时,提醒用户注意字段的命名和类型,避免错误。 然后是配置Asterisk模块使用Realtime。例如,在sip.conf中设置realtime=yes,并指定数据库前缀。这里需要解释realtime参数的作用,以及如何通过数据库前缀来区分不同的配置部分。 此外,需要提到动态注册的情况,如果用户希望终端动态注册到Asterisk,则需要在数据库中设置相应的字段,如ipaddr和port。同时,要说明如何通过CLI命令验证配置是否正确加载,比如检查SIP对等体的状态。 安全方面,需要提醒用户注意数据库文件的权限,避免使用root用户运行Asterisk,以及配置中的敏感信息如密码应妥善处理。可能还需要提到备份和恢复数据库的重要性,以及如何通过SQLite命令行工具进行管理。 用户可能遇到的常见问题包括数据库连接失败、表结构错误、权限问题等,因此需要给出一些故障排除的建议,比如检查日志文件中的错误信息,确认模块是否加载,以及测试数据库连接是否正常。 最后,总结使用SQLite作为Asterisk Realtime后端的优缺点,比如轻量级、适合小规模部署,但在高并发或大规模环境下可能需要更强大的数据库系统。同时,提供进一步学习的资源或文档链接,帮助用户深入理解。</think>以下是关于 **Asterisk Realtime 使用 SQLite 配置**的分步解析: --- ### 一、Asterisk Realtime 核心概念 - **Realtime 架构**:Asterisk 从数据库(而非配置文件)动态加载配置和状态信息。 - **SQLite 适配**:轻量级嵌入式数据库,适合单机或小规模部署。 - **核心用途**:动态管理 SIP 用户、拨号规则、设备状态等,无需重启服务。 --- ### 二、配置步骤详解 #### **1. 启用 SQLite 支持** - **编辑 `modules.conf`**: ```ini [modules] autoload=yes preload => res_config_sqlite3.so ; 加载 SQLite 模块 ``` - **配置 `res_sqlite3.conf`**: ```ini [global] dbfile=/var/lib/asterisk/astdb.sqlite3 ; 指定 SQLite 文件路径 ``` #### **2. 创建 SQLite 数据库表** - **SIP 用户表示例**: ```sql CREATE TABLE sip_users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(80) NOT NULL, secret VARCHAR(80) NOT NULL, context VARCHAR(80) DEFAULT 'default', host VARCHAR(40) DEFAULT 'dynamic', ipaddr VARCHAR(40), port INTEGER ); ``` - **拨号方案表**: ```sql CREATE TABLE dialplan ( context VARCHAR(80) NOT NULL, exten VARCHAR(80) NOT NULL, priority INTEGER NOT NULL, app VARCHAR(80) NOT NULL, appdata VARCHAR(255) ); ``` #### **3. 配置 Asterisk 使用 Realtime** - **`sip.conf` 配置**: ```ini [general] realtime=yes ; 启用 Realtime rtcachefriends=yes ; 缓存数据提升性能 rtsavesysname=yes ; 保存系统名称到数据库 ``` - **定义数据库映射**(在 `extconfig.conf` 中): ```ini [settings] sippeers => sqlite,asterisk,sip_users ; 格式: 模块类型 => 驱动,数据库名,表名 dialplan => sqlite,asterisk,dialplan ``` --- ### 三、动态操作示例 #### **1. 添加 SIP 用户** ```sql INSERT INTO sip_users (name, secret, context) VALUES ('1001', 'mypassword', 'office_phones'); ``` #### **2. 动态拨号规则** ```sql INSERT INTO dialplan (context, exten, priority, app, appdata) VALUES ('office_phones', '_1XXX', 1, 'Dial', 'SIP/${EXTEN}'), ('office_phones', '1001', 1, 'Answer', ''); ``` --- ### 四、验证与调试 #### **1. CLI 命令验证** ```bash asterisk -rx "sip show peers" # 查看 SIP 用户是否加载 asterisk -rx "dialplan show" # 检查拨号方案 asterisk -rx "database show" # 显示 SQLite 连接状态 ``` #### **2. 日志监控** ```bash tail -f /var/log/asterisk/full | grep REAL_TIME ``` --- ### 五、高级配置技巧 #### **1. 动态注册处理** - 在 `sip_users` 表中设置 `host=dynamic`,允许终端动态注册: ```sql UPDATE sip_users SET ipaddr='192.168.1.100', port=5060 WHERE name='1001'; ``` #### **2. 性能优化** - **启用缓存**(减少数据库查询): ```ini ; 在 extconfig.conf 中 sippeers => sqlite,asterisk,sip_users,cache ``` - **索引优化**: ```sql CREATE INDEX idx_sip_name ON sip_users(name); CREATE INDEX idx_dialplan_context ON dialplan(context); ``` --- ### 六、安全注意事项 1. **文件权限**: ```bash chown asterisk:asterisk /var/lib/asterisk/astdb.sqlite3 chmod 600 /var/lib/asterisk/astdb.sqlite3 ``` 2. **SQL 注入防护**:通过 Asterisk 内置参数过滤(如 `${SQL_ESC(...)}`)。 3. **备份策略**: ```bash sqlite3 /var/lib/asterisk/astdb.sqlite3 ".backup /backup/astdb-$(date +%F).sqlite3" ``` --- ### 七、常见问题排查 | **问题现象** | **解决方法** | |---------------------------|---------------------------------------| | 数据库连接失败 | 检查 `res_sqlite3.conf` 路径和权限 | | SIP用户未加载 | 确认 `extconfig.conf` 映射是否正确 | | 拨号规则未生效 | 检查 `dialplan` 表字段是否完整 | | 性能低下 | 添加索引或启用缓存 | --- ### 八、生产环境建议 - **适用场景**:小型办公系统、测试环境。 - **替代方案**:高并发场景建议使用 MySQL/PostgreSQL。 - **版本控制**:通过 `sqlite3` 命令行工具管理数据库版本: ```bash sqlite3 astdb.sqlite3 ".dump" > version_20231001.sql ``` 通过 SQLite 实现 Asterisk Realtime,可显著提升配置灵活性,但需注意数据一致性和性能调优。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值