Monday, June 4, 2012

OpenSIPS as Load-Balancer for FreeSWITCH

With reference to my older posts in which I talked about increasing VoIP services capacity (with failover for load-balanced media-servers), then I tested the whole scenario using Kamailio and RTPproxy.This post, however, is replica of the above scenario but using OpenSIPS and RTPproxy.

I wanted to use MediaProxy  instead of RTPprxoy but media-Proxy unfortunately is not used for bridging RTPs from Public Internet to Private subnets and vice-versa [For details: See this forum discussion]

Following is the topology I wanted to achieve.

OpenSIPS+RTPproxy in Action
I used FreeSWITCH as my Media-Server layer. Asterisk servers can be used alternatively as well.
Now moving quickly to the opensips.cfg file changes required in order to make this work.

First add,

mhomed=yes

in Global Parameters, This will tell opensips that server has multiple interfaces to send/receive and relay traffic in-between subnets, so modify headers wisely and accordingly.

Then following modules needs to be declared.

(click on underlined modules to read their documentation)

loadmodule "rtpproxy.so"
loadmodule "nathelper.so"
loadmodule "dialog.so"
loadmodule "load_balancer.so"
loadmodule "avpops.so"

Then parameters for each modules:


# ------ RTP-proxy Parameters
#RTPproxy instance to be used: 9901 
#172.16.31.102<<=Transform=>> 192.168.30.3
modparam("rtpproxy", "rtpproxy_sock", "udp:127.0.0.1:9901") 

In my case, since using Virt.Environment, I consider 172.16.31.102 to be my Public IP and transform into the internal Private subnet 192.168.30.x.

NOTE[1]: My assumption  of 172.16.31.102 as Public IP has serious complications, as I understand, because the NAT-HELPER functions will always consider traffic from this subnet as Private rather public and this may've effect on OpenSIPS behavior, if used in production.
NOTE[2]: Please reply back in case if there is any discrepancy or suggestion in the configurations. This is a work in progress, so I apologize in case if you find anything incorrect. Changes and Suggestions are always welcome.


# ------ AVPOPS params --------
modparam("avpops","db_url", "mysql://opensips:opensipsrw@localhost/opensips")
modparam("avpops","avp_table","usr_preferences")
modparam("avpops","use_domain",1)

# ------ NAT-Helper params ------
modparam("nathelper", "ping_nated_only", 1)
modparam("nathelper", "received_avp", "$avp(i:42)")
modparam("nathelper", "sipping_bflag", 7)
modparam("nathelper", "sipping_from", "sip:pinger@saevolgo.com")

# ----- LOAD BALANCER MODULE -----
modparam("load_balancer", "probing_interval", 30) 
modparam("load_balancer", "probing_reply_codes", "501, 404") 
modparam("load_balancer", "probing_from","sip:opensips@saevolgo.com")
modparam("load_balancer", "db_url","mysql://opensips:opensipsrw@localhost/opensips")



Now main routing logic:

Add Highlighted NAT test just at the start of main route. I put that just under the Max-FWD header validation check.

      if (!mf_process_maxfwd_header("10")) {
  sl_send_reply("483","Too Many Hops");
  exit;
 }
      if (nat_uac_test("19")) {
xlog("L_INFO","[$pr:$fU@$si:$sp]: NAT Detection Test-19 Passed Now Fixing-Nat for '$rm' \n");
  if (is_method("REGISTER")) {
   fix_nated_register();
  } else {
   fix_nated_contact();
  }
xlog("L_INFO","[$pr:$fU@$si:$sp]: NAT Fixed for '$rm' \n");
  setflag(5);
 };
Soon after this I could see code Logic for "BYE" method. There I need to tell (on call hangup) RTPproxy to dis-engage its ports for this particular call. if (loose_route()) {
 if (is_method("BYE")) {
  setflag(1); # do accounting ...
  setflag(3); # ... even if the transaction fails
  unforce_rtp_proxy();

Then scrolling down at the end of the main route I could see this piece of code.
# do lookup with method filtering
xlog("L_NOTICE","[$pr:$fU@$si:$sp]: Call from '$fu' to '$ru' LOOKUP in 'Location' table\n");
 if (!lookup("location","m")) {
  switch ($retcode) {
   case -1:
   case -3:
    t_newtran();
    #t_reply("404", "Not Found");
xlog("L_NOTICE","[$pr:$fU@$si:$sp]: Call from '$fu' to '$ru' User Not Found - try Dialing Media-Server\n");
    route(3);
    route(1);
   case -2:
    sl_send_reply("405", "Method Not Allowed");
    exit;
  }
 }
I added the highlighted lines. Basically at this point the opensips default configuration searches its online sip users and if the dialed destination string is an online user it sends the call out to that user.

If that user is offline, or the dialed string don't matches any user it sends "404 Not Found" back to the caller.

Now, What I'm doing over here is that once I find out that a user is offline,or is not a defined user then route the call to route(3) which is where I'll call in Load-Balancer and select a LB'd destination Media-Server and record a VoiceMail or do some other call routing.

 Just after route(3); I've called route(1);. Route[1] is the default route already defined which only relays the call towards the destination. So here are these routes: Add these lines just after your main route ends.
# Media-Server Route, Engage Load-Balancer and Select Server here.
route[3] 
{
 xlog("L_NOTICE","[$pr:$fU@$si:$sp]: This is Media-Server Route Use Load-balancer NOW!!\n");
 if (!load_balance("1","calls")) {
  sl_send_reply("500","Service full");
        exit;
   }
 xlog("L_NOTICE","[$pr:$fU@$si:$sp]: Selected destination Media-Server : $du\n");
}
See as simple as this to use Load-Balancer. But the real game for RTPproxy is handled in route[1] where I test if the selected destination of this call is one of my Media-Server defined in loadbalancer DB-table or not.

If results in True I engage RTPproxy using flags sequence IE, if not and call is coming in from my Media-Servers to outside use RTPproxy flags in EI sequence.

See this post for more information on making RTPproxy work for you.

Now, in route[1] I added the following Highlighted code and RTPproxy started working for me.

route[1]{
# for INVITEs enable some additional helper routes
 xlog("L_INFO","[$pr:$fU@$si:$sp]: SET flags for '$rm' & Relay the Message\n");
 if (is_method("INVITE")) {
  t_on_branch("2");
  t_on_reply("2");
  t_on_failure("1");
  if (isflagset(5)) {
xlog("L_NOTICE","[$pr:$fU@$si:$sp]: Engage Media-Proxy here\n");
xlog("L_NOTICE","[$pr:$fU@$si:$sp]: InBound-OR-OutBound Call Check!!\n");
   if(avp_db_query("select dst_uri from load_balancer where dst_uri like '%$dd%'")){
#INCOMING CALL NEEDS TO GOTO PRIVATE-IP FreeSWITCH USE - IE
    engage_rtp_proxy("rie");
 
   }
   else if(avp_db_query("select dst_uri from load_balancer where dst_uri='sip:$si:$sp'")){
#INCOMING CALL FROM PRIVATE-IP FreeSWITCH USE - EI
    engage_rtp_proxy("rei");

   }
   else
   {
    engage_rtp_proxy("r");

   }

  }
  
 }
Now opensips.cfg is all done.  Don;t forget to add FreeSWITCH server IPs in the loadbalancer table.

# mysql -uopensips -popensipsrw opensips
mysql>INSERT INTO load_balancer (group_id,dst_uri,resources,probe_mode,description) VALUES (1,'sip:192.168.30.4:5090','calls=50',2,'FreeSWITCH-B Server');
mysql>INSERT INTO load_balancer (group_id,dst_uri,resources,probe_mode,description) VALUES (1,'sip:192.168.30.4','calls=100',2,'FreeSWITCH-B Server');


Quit MySQL, now you can use the following commands to reload Load-balancer servers list in opensips on the fly and see the status of each FS server in opensips.

#opensipsctl fifo lb_reload
#opensipsctl fifo lb_list
This is not all done!!

FreeSWITCH SIDE CONFIGURATIONS

You need to define a gateway for OpenSIPS in your FreeSWITCH external or itnernal profile per your settings.

FreeSWITCH-A:~# cd /usr/local/freeswitch/conf/sip_profiles/external/
FreeSWITCH-A:~# vim opensips.xml
Insert these Lines in this file:
<include>
  <gateway name="OpenSIPS">
  <param name="username" value="192.168.30.3"/>
  <param name="from-user" value="192.168.30.3"/>
  <param name="password" value="2007"/>
  <param name="proxy" value="192.168.30.3"/>
  <param name="register" value="false"/>
  <param name="retry-seconds" value="10"/>
  <param name="caller-id-in-from" value="true"/>
  <param name="extension-in-contact" value="true"/>
  <param name="ping" value="25"/>
  <param name="inbound-late-negotiation" value="true"/>
  <param name="context" value="default"/>
  </gateway>
</include>
Reload Sofia files in FreeSWITCH. I did a whole sofia module reload.

freeswitch@internal> reload mod_sofia

I also had to tell FreeSWITCH to allow my LAN IPs in acl.conf.xml located at 
/usr/local/freeswitch/conf/autoload_configs/acl.conf.xml 

<list name="lan" default="allow">
      <node type="deny" cidr="192.168.30.0/24"/>
    </list>

Save changes in that file and reload acl.

freeswitch@internal> reloadacl

Now make calls and see that calls are landing in your Public context, there take control of your incoming calls and land to your own context/xml files.

Thats all folks ! Hope you guys were really bored uptill here ;)

Wednesday, May 23, 2012

FreeSWITCH Installation on Citrix XenServer

This is one of the easiest posts I've ever made. I'll show how to install FreeSWITCH which is only 5~7 lines of work but first we need to declare and install the prerequisite OS, UBUNTU 1.04 Server and even before that need to create a new Virtual Machine on my XENSERVER using XENCLIENT.

ADDING NEW VM USING XENCENTER ON XENSERVER

Simple Click on "NEW VM"
Next Step will give lots of predefined templates which come with xenserver and include multiple OSs like windows and linux servers. But I wanted to install an Operating System of my own choice and my own settings so I selected Other Install Media from the templates.
Using Other Install Media as Template
Once we continue from the last step we'll be given option to Install OS from an ISO library or Physical DVD drive of the xen-server. Since we can't have access to physical server's DVD ROM all the time so using an ISO library is the best idea. I had already created an "New ISO Library" which pointed to a CIFS directory ( Uses Windows network shared folder in simple words)

I've Ubuntu Server 11.04 server ISO placed in my windows shared folder

Select which XENSERVER to create this Virtual Machine
 Using XENCENTER we can have multiple xenservers under our control so we may select which xenserver to create this new VM on. Since I've only one experimental xenserver, so I selected that one.
Assign CPUs and Memory to VM
 Easy step, just tell XENSERVER how much memory and how manay CPUs to assign to this new VM.
Create a Disk Storage [HDD} for VM
 Another standard step of assigning HDD capacity to this VM on xenserver.

Select Capacity and Storage Space for VM-HDD
 The important point and good to note here is that XENSERVER/XENCENTER gives us the capability to not only use the internal Harddisk of thexen-server but instead we can use Network Storage systems as well like NAS or SAN or FC(Fiber Channel)
Selecting xenserver's storage as storage space of new VM
Next steps are easier as well, just create a new NIC for our virtual machine and assign it to default network-0 or any other network created  on the xenserver. This means that we can define multiple switches and create separate networks within the xen-server. Managing traffic is easier if we use Virtual Routers like vyatta. See my previous post on how I control internet traffic between VMs using vyatta.


 Finally everything is setup just press the finish button and ta-da, another server is ready and now time to install Operating System on this new server.



INSTALL UBUNTU ON NEW Vitual Machine

Follow this post by one of my senior senior friend on step-by-step Ubuntu Server installation guide to install OS on the newly created Virtual Machine.

SETTING UP SSH ACCESS TO NEW VM

Since I assigned this new Virtual machine a private network with Private IP: 192.168.30.4. According to my virtual router's configurations in this post This IP can access internet but I definitely need to add another Destination NAT rule in my router to gain SSH access from outside world to this server.

Now when I SSH on 172.16.31.101 port 22304 it gets translated to internal address 192.168.30.4 port 22.

GW-Vyatta#set nat destination rule 10 inbound-interface eth0
GW-Vyatta#set nat destination rule 10 destination port 22304
GW-Vyatta#set nat destination rule 10 translation address 192.168.30.4
GW-Vyatta#set nat destination rule 10 translation port 22
GW-Vyatta#set nat destination rule 10 protocol tcp
GW-Vyatta#commit


This is How it looks like now


INSTALLING FREESWITCH on UBUNTU SERVER

Now the final phase of this post, installing our favorite VoIP Server FreeSWITCH. SSH into the FS server and on console execute these commands.

Download pre-requisite libraries and packages for FreeSWITCH.

FS-Server:#apt-get update
FS-Server:#apt-get install gcc bison flex make openssl libmysqlclient15-dev libradiusclient-ng-dev mysql-server libxmlrpc-c3-dev subversion subversion-tools automake1.9 gcc-4.1 autoconf make wget libtool g++ debhelper automake1.9 autoconf libtool unixodbc-dev libasound2-dev libssl-dev libogg-dev libvorbis-dev libperl-dev libgdbm-dev libdb-dev libgnutls-dev libspandsp-dev libtiff4-dev libncurses5 libncurses5-dev screen bridge-utils libmysql++-dev libconfuse-dev libpcre3-dev curl libxml2-dev libmemcache-dev build-essential git-core
Download freeswitch source code. This takes a long time downloading almost 80~100 MB of data on slower network.
FS-Server:#cd /usr/local/src
FS-Server:#git clone git://git.freeswitch.org/freeswitch.git
Build configurations file required for compiling FreeSWITCH.
FS-Server:#cd freeswitch
FS-Server:#./bootstrap.sh
./configure sets compilation options
FS-Server:#./configure

At this point you can edit the file "modules.conf" to include any modules you like to be installed with your freeswitch setup.
Now execute make and make install commands to compile and create binary files.


FS-Server:#make && make install
Now Sit back and do something usefull (:P), hopefully if no errors are encountered then it'll take approximately 7~15 minutes.
Once it completes you can follow the printed instructions to install any additional sound files if you like.

At the end just put symoblic Links:

FS-Server:#ln -s /usr/local/src/freeswitch/bin/freeswitch /usr/sbin/
FS-Server:#ln -s /usr/local/src/freeswitch/bin/fs_cli /usr/sbin/
Now, Start FreeSWITCH server for the first time.
FS-Server:#cd /
FS-Server:#freeswitch -nc
FS-Server:#fs_cli -r
Thats it You're now connected to FreeSWITCH console. 

Next thing I'm going to do is setup my virtual topology such that SIP Users registering on OpenSIPS can make calls to FreeSWITCH and they get a two-way audio. I'll be using Media-Proxy (hopefully) and echo application in FreeSWITCH to test this. Till then bye-bye.

Saturday, May 19, 2012

OpenSIPS DB-Authentication with Multi-Domain Support

OpenSIPS DB-Authentication with Multi-Domain Support

Starting from the basics, I'm going to show how to use the factory default opensips.cfg file and make it use MySQL DB to authenticate any incoming SIP REGISTER attempt. The default file without any changes will successfully register any user with any password, which in most of the cases is obviously not required.

open up the opensips.cfg file

root@Osips-SBC:~#vim /etc/opensips/opensips.cfg


Starting from enabling the required modules to be loaded

Un-comment  (remove the #)  this line to load the MySQL DB connector module
#loadmodule "db_mysql.so"

Uncomment these modules to load the authentication mechanism
#loadmodule "auth.so"
#loadmodule "auth_db.so"
#loadmodule "alias_db.so"

Uncomment the domain module to enable multi-domain support
#loadmodule "domain.so"

Enable the presence modules

#loadmodule "presence.so"
#loadmodule "presence_xml.so"

Set "usrloc" module parameters to save the SIP user-locations into MySQL DB persistently.

#modparam("usrloc", "db_mode",   2)
#modparam("usrloc", "db_url",
#     "mysql://opensips:opensipsrw@localhost/opensips")

Set the authentication_db modules parameters to point to the desired Database.  

#modparam("auth_db", "calculate_ha1", yes)
#modparam("auth_db", "password_column", "password")
#modparam("auth_db", "db_url",
#     "mysql://opensips:opensipsrw@localhost/opensips")
#modparam("auth_db", "load_credentials", "")


Uncomment DB parameters of Aliases_DB module

#modparam("alias_db", "db_url",
#     "mysql://opensips:opensipsrw@localhost/opensips")

Uncomment DB parameters of Domain module

#modparam("domain", "db_url",
#     "mysql://opensips:opensipsrw@localhost/opensips")
#modparam("domain", "db_mode", 1)   # Use caching


Enable modules to differentiate between different domains.
#modparam("auth_db|usrloc|uri", "use_domain", 1)

Set presence modules parameters.


#modparam("presence|presence_xml", "db_url",
#     "mysql://opensips:opensipsrw@localhost/opensips")
#modparam("presence_xml", "force_active", 1)
#modparam("presence", "server_address", "sip:192.168.30.3:5060")


Now in the main route uncomment the following code blocks so that whenever we receive a REGISTER request it verifies its credentials (from DB). If you let these blocks commented any SIP REGISTER request will be successful without any verification.

This is required to authenticate the incoming methods except REGISTER, this is useful in case any undefined user(hacker) tries to make calls from your SIP-Proxy.

       ##if (!(method=="REGISTER") && is_from_local())  /*multidomain version*/
       ##{
       ##      if (!proxy_authorize("", "subscriber")) {
       ##              proxy_challenge("", "0");
       ##              exit;
       ##      }
       ##      if (!db_check_from()) {
       ##              sl_send_reply("403","Forbidden auth ID");
       ##              exit;
       ##      }
       ##
       ##      consume_credentials();
       ##      # caller authenticated
       ##}

NOTE: Don't uncomment the "# caller authenticated" line.

And this block needs to be uncommented to Authenticate REGISTER requests.

 ##if (!www_authorize("", "subscriber"))
               ##{
               ##      www_challenge("", "0");
               ##      exit;
               ##}
               ##
               ##if (!db_check_to())
               ##{
               ##      sl_send_reply("403","Forbidden auth ID");
               ##      exit;
               ##}
  

Once done, Save and Exit. Optionally its Always good to add few extra log lines to see whats going on inside your OpenSIPS. logs lines are important to debug and troubleshoot the configuration file.

xlog("L_NOTICE","[$pr:$fU@$si:$sp]: Processing '$rm' \n");

Put this line Just before the if conditions we uncommented above then save the file.

next thing is define SIP users in OpenSIPS DB
For this first edit the follwoing file.


root@Osips-SBC:~# vim /etc/opensips/opensipsctlrc


Set the SIP DOMAIN and OpenSIPS Database Username/Password.
## your SIP domain
SIP_DOMAIN=192.168.30.3
This will be default domain used if no domain at user definition time is given.

## database read/write user
DBRWUSER=opensips

## password for database read/write user
DBRWPW="opensipsrw"

Save and Exit

Add domains to be used by opensips


root@Osips-SBC:~#mysql -uopensips -popensipsrw opensips


mysql>insert into domain(domain,last_modified) VALUES ("192.16.30.3", now())
mysql>insert into domain(domain,last_modified) VALUES ("saevolgo.com", now())


Restart OpenSIPS

root@Osips-SBC:~#/etc/init.d/opensips restart

Now Add SIP Users.

root@Osips-SBC:~# opensipsctl add 10022 pass10022word
new user '10022' added

root@Osips-SBC:~# opensipsctl add 10022@saevolgo.com passw0rd
new user '10022@saevolgo.com' added

Now try registering both users changing realm and password for both and make sure that 10022 user defined for realm "saevolgo.com" works with only its defined passw0rd and not with "pass10022word".