Category Archives: Session Initiation Prot. (SIP)


Asterisk is a framework or toolkit designed for VOIP systems . It can support Enterprise communication systems like PBXs, call distributors, VoIP gateways , conference bridges etc . It is open source and free to use . It is developed in C and runs in linux .

Technically , Asterisk has protocol support for many telephony technologies and protocols such as SIP , H323 .
It can connect old PSTN or copper line and VOIP .

Asterisk is a framework for building multi-protocol, real-time communications applications and solutions. Asterisk is to realtime voice and video applications as what Apache is to web applications


Combine the SIP channel, the PSTN interface channel and some Dialplan script and you have a gateway.
Change the Dialplan to drop calls into a ConfBridge session and you have a conference server.
Alter it once more to route calls into voice mailboxes and you have a voicemail server.
Tie it all together and you have an amazingly powerful phone system.



goto /usr/src and download the preferred the version of asterisk code from

I am using the latest release candidate at the time writing this article

Some external Dependencies
apt-get install subversion

Then install the source dependencies

 sudo su

This will install mp3 related programs such as

A addons/mp3
A addons/mp3/decode_ntom.c
A addons/mp3/interface.c
A addons/mp3/MPGLIB_README
A addons/mp3/common.c
A addons/mp3/huffman.h
A addons/mp3/tabinit.c
A addons/mp3/Makefile
A addons/mp3/README
A addons/mp3/decode_i386.c
A addons/mp3/dct64_i386.c
A addons/mp3/MPGLIB_TODO
A addons/mp3/mpg123.h
A addons/mp3/layer3.c
A addons/mp3/mpglib.h
Exported revision 202.

Actual dependencies will be installed via install_prereq script

contrib/scripts/install_prereq install

Output snippet

The following NEW packages will be installed:
autoconf{a} automake{a} autopoint{a} autotools-dev{a} binutils{a} binutils-common{a} binutils-dev binutils-x86-64-linux-gnu{a} bison build-essential comerr-dev{a} cpp{a} cpp-7{a} debhelper{a}
dh-autoreconf{a} dh-strip-nondeterminism{a} doxygen dpkg-dev{a} fakeroot{a} flex fontconfig{a} fontconfig-config{a} fonts-dejavu-core{a} fonts-liberation{a} freetds-common{a} freetds-dev g++{a}
g++-7{a} gcc{a} gcc-7{a} gcc-7-base{a} gettext{a} gir1.2-gmime-2.6{a} gir1.2-harfbuzz-0.0{a} graphviz icu-devtools{a} intltool-debian{a} krb5-multidev{a} libalgorithm-diff-perl{a}
libalgorithm-diff-xs-perl{a} libalgorithm-merge-perl{a} libann0{a} libarchive-cpio-perl{a} libarchive-zip-perl{a} libasan4{a} libasound2{a} libasound2-data{a} libasound2-dev libatomic1{a}
libbinutils{a} libbison-dev{a} libbluetooth-dev libbluetooth3{a} libbsd-dev{a} libc-client2007e{a} libc-client2007e-dev libc-dev-bin{a} libc6-dev{a} libcairo2{a} libcc1-0{a} libcdt5{a} libcfg-dev
libcfg6{a} libcgraph6{a} libcilkrts5{a} libclang1-6.0{a} libcodec2-0.7{a} libcodec2-dev libcorosync-common-dev libcorosync-common4{a} libcpg-dev libcpg4{a} libcroco3{a} libct4{a}
libcurl4-openssl-dev libdatrie1{a} libdb-dev{a} libdb5.3-dev{a} libdpkg-perl{a} libedit-dev libexpat1-dev{a} libfakeroot{a} libfftw3-bin{a} libfftw3-dev libfftw3-double3{a} libfftw3-long3{a}
libfftw3-quad3{a} libfftw3-single3{a} libfile-fcntllock-perl{a} libfile-stripnondeterminism-perl{a} libfl-dev{a} libfl2{a} libflac-dev{a} libflac8{a} libfontconfig1{a} libgcc-7-dev{a} libgd3{a}
libglib2.0-bin{a} libglib2.0-dev{a} libglib2.0-dev-bin{a} libgmime-2.6-0{a} libgmime-2.6-dev libgomp1{a} libgpgme11{a} libgraphite2-3{a} libgraphite2-dev{a} libgsm1{a} libgsm1-dev libgssrpc4{a}
libgts-0.7-5{a} libgts-bin{a} libgvc6{a} libgvpr2{a} libharfbuzz-dev{a} libharfbuzz-gobject0{a} libharfbuzz-icu0{a} libharfbuzz0b{a} libical-dev libical3{a} libice6{a} libicu-dev{a}
libicu-le-hb-dev{a} libicu-le-hb0{a} libiculx60{a} libiksemel-dev libiksemel3{a} libisl19{a} libitm1{a} libjack-jackd2-0{a} libjack-jackd2-dev libjansson-dev libjansson4{a} libjbig-dev{a}
libjbig0{a} libjpeg-dev{a} libjpeg-turbo8{a} libjpeg-turbo8-dev{a} libjpeg8{a} libjpeg8-dev{a} libkadm5clnt-mit11{a} libkadm5srv-mit11{a} libkdb5-9{a} liblab-gamut1{a} libldap2-dev libllvm6.0{a}
liblsan0{a} libltdl-dev{a} libltdl7{a} liblua5.2-0{a} liblua5.2-dev liblzma-dev{a} libmail-sendmail-perl{a} libmpc3{a} libmpx2{a} libmysqlclient-dev libmysqlclient20{a} libncurses5-dev{a}
libneon27{a} libneon27-dev libnewt-dev libodbc1{a} libogg-dev libogg0{a} libosptk-dev libosptk4{a} libpam0g-dev{a} libpango-1.0-0{a} libpangocairo-1.0-0{a} libpangoft2-1.0-0{a} libpathplan4{a}
libpcap0.8-dev{a} libpci-dev{a} libpcre16-3{a} libpcre3-dev{a} libpcre32-3{a} libpcrecpp0v5{a} libpixman-1-0{a} libpng-dev{a} libpng-tools{a} libpopt-dev libportaudio2{a} libportaudiocpp0{a}
libpq-dev libpq5{a} libpython-dev{a} libpython-stdlib{a} libpython2.7{a} libpython2.7-dev{a} libpython2.7-minimal{a} libpython2.7-stdlib{a} libqb-dev{a} libqb0{a} libquadmath0{a} libradcli-dev
libradcli4{a} libreadline-dev{a} libresample1{a} libresample1-dev libsamplerate0{a} libsensors4{a} libsensors4-dev{a} libslang2-dev{a} libsm6{a} libsndfile1{a} libsndfile1-dev libsnmp-base{a}
libsnmp-dev libsnmp30{a} libspandsp-dev libspandsp2{a} libspeex-dev libspeex1{a} libspeexdsp-dev libspeexdsp1{a} libsqlite3-dev libsrtp0{a} libsrtp0-dev libsrtp2-1{a} libsrtp2-dev libssl-dev
libssl-doc{a} libstdc++-7-dev{a} libsybdb5{a} libsys-hostname-long-perl{a} libthai-data{a} libthai0{a} libtiff-dev{a} libtiff5{a} libtiff5-dev{a} libtiffxx5{a} libtinfo-dev{a} libtool{a}
libtool-bin{a} libtsan0{a} libubsan0{a} libudev-dev{a} libunbound-dev libunbound2{a} liburiparser-dev liburiparser1{a} libvorbis-dev libvorbis0a{a} libvorbisenc2{a} libvorbisfile3{a} libvpb-dev
libvpb1{a} libwebp6{a} libwrap0-dev{a} libxaw7{a} libxcb-render0{a} libxcb-shm0{a} libxml2-dev libxmu6{a} libxpm4{a} libxrender1{a} libxslt1-dev libxt6{a} linux-libc-dev{a} m4{a} make{a}
manpages-dev{a} mlock{a} module-assistant{a} mysql-common{a} odbcinst{a} odbcinst1debian2{a} pkg-config pkgconf{b} po-debconf{a} portaudio19-dev python{a} python-dev python-minimal{a} python2.7{a}
python2.7-dev{a} python2.7-minimal{a} python3-distutils{a} python3-lib2to3{a} unixodbc-dev uuid-dev vpb-driver-source{a} x11-common{a} xmlstarlet zlib1g-dev
The following packages will be upgraded:
gcc-8-base libcom-err2 libcurl4 libglib2.0-0 libgssapi-krb5-2 libk5crypto3 libkrb5-3 libkrb5support0 libldap-2.4-2 libldap-common libpython3-stdlib libpython3.6-minimal libpython3.6-stdlib
libssl1.1 libudev1 libuuid1 python3 python3-minimal python3.6 python3.6-minimal

Current status: 127 (-25) upgradable.
# ###########################
install completed successfully
# ############################

Run configure which will create scripts for next processes


Build third party scripts

make -j2

After build , to run the installation

make install

Asterisk PBX setup

make basic-pbx

The output should be

Installing basic-pbx config files…
Installing file configs/basic-pbx/README
Installing file configs/basic-pbx/asterisk.conf
Installing file configs/basic-pbx/cdr.conf
Installing file configs/basic-pbx/cdr_custom.conf
Installing file configs/basic-pbx/confbridge.conf
Installing file configs/basic-pbx/extensions.conf
Installing file configs/basic-pbx/indications.conf
Installing file configs/basic-pbx/logger.conf
Installing file configs/basic-pbx/modules.conf
Installing file configs/basic-pbx/musiconhold.conf
Installing file configs/basic-pbx/pjsip.conf
Installing file configs/basic-pbx/voicemail.conf
Updating asterisk.conf

Also run make config to make pbx configs

make config 

start asterisk

systemctl start asterisk

connect to asterisk tool for cli

asterisk -vvvr
Asterisk 16.2.0-rc1, Copyright (C) 1999 - 2018, Digium, Inc. and others.
Created by Mark Spencer
Asterisk comes with ABSOLUTELY NO WARRANTY; type 'core show warranty' for details.
This is free software, with components licensed under the GNU General Public
License version 2 and other licenses; you are welcome to redistribute it under

certain conditions. Type 'core show license' for details.

Connected to Asterisk 16.2.0-rc1 currently running on ip-172-31-45-26 (pid = 13388)

SIP and PJSIP modules

module show like sip
Module Description Use Count Status Support Level PJSIP Channel Driver 0 Running core Get information about a PJSIP endpoint 0 Running core Basic SIP resource 38 Running core PJSIP ACL Resource 0 Running core PJSIP authentication resource 0 Running core PJSIP Caller ID Support 1 Running core PJSIP Extension State Dialog Info+XML Pr 0 Running core PJSIP Add Diversion Header Support 0 Running core PJSIP DTMF INFO Support 0 Running core PJSIP Anonymous endpoint identifier 0 Running core PJSIP IP endpoint identifier 0 Running core PJSIP username endpoint identifier 0 Running core PJSIP Extension State Notifications 0 Running core PJSIP Header Functions 0 Running core PJSIP Packet Logger 0 Running core PJSIP Messaging Support 0 Running core PJSIP MWI resource 0 Running core PJSIP MWI resource 0 Running core PJSIP NAT Support 0 Running core CLI/AMI PJSIP NOTIFY Support 0 Not Running core PJSIP INFO One Touch Recording Support 0 Running core PJSIP authentication resource 0 Running core PJSIP Outbound Publish Support 2 Running core PJSIP Outbound Registration Support 0 Running core PJSIP Path Header Support 0 Running core PJSIP Extension State PIDF Provider 0 Running core PJSIP PIDF Digium presence supplement 0 Running core PJSIP PIDF Eyebeam supplement 0 Running core PJSIP Asterisk Event PUBLISH Support 0 Running core PJSIP event resource 11 Running core PJSIP Blind and Attended Transfer Suppor 1 Running core PJSIP Registrar Support 0 Running core PJSIP RFC3326 Support 0 Running core PJSIP SDP RTP/AVP stream handler 0 Running core PJSIP REFER Send to Voicemail Support 0 Running core PJSIP Session resource 14 Running core PJSIP T.38 UDPTL Support 0 Running core PJSIP WebSocket Transport Support 0 Not Running core PJSIP Extension State PIDF Provider 0 Running core
39 modules loaded

Register sip phones with asterisk PBX and make / receive calls

To make calls among users, we need to configure channel driver with sip support . Using the sip protcol the phones within the enterprise will be able to send call signals out to one another. Open pjsip.conf

Take any endpoint from template , such as

;Laverne Roberts
;Software Engineer
[1113 (endpoint-internal-d70)
auth = 1113
aors = 1113
callerid = Laverne Roberts <1113>
[1113 (auth-userpass)
password = xxxxxxxx
username = xxxxxxxx
[1113 (aor-single-reg)
mailboxes = 1113@example

and set the values in sip softphone like zoiper , register with provided creds

registering sip phone zoiper with newly created asterisk PBX

If the registration creds used are not matching with the ones defines in pjsip.conf then REGISTER request failed message is displayed

Request 'REGISTER' from '' failed for 'x.x.x.x:18475' (callid: hp8iN6oWLRdER4zvEBdiUg..) - No matching endpoint found

On correct creds used the server prints traces such as

-- Added contact 'sip:1113@x.x.x.x:44312;transport=UDP;rinstance=b8aceff08623b51e' to AOR '1113' with expiration of 60 seconds
== Endpoint 1113 is now Reachable
-- Removed contact 'sip:1113@x.x.x.x:44312;transport=UDP;rinstance=b8aceff08623b51e' from AOR '1113' due to request
== Contact 1113/sip:1113@x.x.x.x:44312;transport=UDP;rinstance=b8aceff08623b51e has been deleted
== Endpoint 1113 is now Unreachable
-- Added contact 'sip:1113@x.x.x.x:18475;transport=UDP;rinstance=5af431512ae0af3a' to AOR '1113' with expiration of 60 seconds
== Endpoint 1113 is now Reachable

Alternatively one can also create new sip endpoints


core show help
! -- Execute a shell command
acl show -- Show a named ACL or list all named ACLs
aoc set debug -- enable cli debugging of AOC messages
bridge kick -- Kick a channel from a bridge
bridge show all -- List all bridges
bridge show -- Show information about a bridge
bridge technology show -- List registered bridge technologies
bridge technology {suspend|unsuspend} -- Suspend/unsuspend a bridge technology
cc cancel [core|all] -- Kill a CC transaction
cc report status -- Reports CC stats
cdr set debug [on|off] -- Enable debugging in the CDR engine
cdr show active -- Display active CDRs for channels
cdr show status -- Display the CDR status
cdr submit -- Posts all pending batched CDR data
cel show status -- Display the CEL status
channel request hangup -- Request a hangup on a given channel
cli check permissions -- Try a permissions config for a user
cli reload permissions -- Reload CLI permissions config
cli show permissions -- Show CLI permissions
confbridge kick -- Kick participants out of conference bridges.
confbridge list -- List conference bridges and participants.
confbridge lock -- Lock a conference.
confbridge mute -- Mute participants.
confbridge record start -- Start recording a conference
confbridge record stop -- Stop recording a conference.
confbridge show menu -- Show a conference menu
confbridge show menus -- Show a list of conference menus
confbridge show profile bridge -- Show a conference bridge profile.
confbridge show profile bridges -- Show a list of conference bridge profiles.
confbridge show profile user -- Show a conference user profile.
confbridge show profile users -- Show a list of conference user profiles.
confbridge unlock -- Unlock a conference.
confbridge unmute -- Unmute participants.
config list -- Show all files that have loaded a configuration file
config reload -- Force a reload on modules using a particular configuration file
config show help -- Show configuration help for a module
core abort shutdown -- Cancel a running shutdown
core clear profile -- Clear profiling info
core ping taskprocessor -- Ping a named task processor
core reload -- Global reload
core restart gracefully -- Restart Asterisk gracefully
core restart now -- Restart Asterisk immediately
core restart when convenient -- Restart Asterisk at empty call volume
core set debug channel -- Enable/disable debugging on a channel
core set debug -- Set level of debug chattiness
core set verbose -- Set level of verbose chattiness
core show applications [like|describing] -- Shows registered dialplan applications
core show application -- Describe a specific dialplan application
core show calls [uptime] -- Display information on calls
core show channels [concise|verbose|count] -- Display information on channels
core show channel -- Display information on a specific channel
core show channeltypes -- List available channel types
core show channeltype -- Give more details on that channel type
core show codecs [audio|video|image|text] -- Displays a list of registered codecs
core show codec -- Shows a specific codec
core show config mappings -- Display config mappings (file names to config engines)
core show file formats -- Displays file formats
core show functions [like] -- Shows registered dialplan functions
core show function -- Describe a specific dialplan function
core show hanguphandlers all -- Show hangup handlers of all channels
core show hanguphandlers -- Show hangup handlers of a specified channel
core show help -- Display help list, or specific help on a command
core show hints -- Show dialplan hints
core show hint -- Show dialplan hint
core show image formats -- Displays image formats
core show license -- Show the license(s) for this copy of Asterisk
core show profile -- Display profiling info
core show settings -- Show some core settings
core show sounds -- Shows available sounds
core show sound -- Shows details about a specific sound
core show switches -- Show alternative switches
core show sysinfo -- Show System Information
core show taskprocessors -- List instantiated task processors and statistics
core show threads -- Show running threads
core show translation -- Display translation matrix
core show uptime [seconds] -- Show uptime information
core show version -- Display version info
core show warranty -- Show the warranty (if any) for this copy of Asterisk
core stop gracefully -- Gracefully shut down Asterisk
core stop now -- Shut down Asterisk immediately
core stop when convenient -- Shut down Asterisk at empty call volume
core waitfullybooted -- Wait for Asterisk to be fully booted
database del -- Removes database key/value
database deltree -- Removes database keytree/values
database get -- Gets database value
database put -- Adds/updates database value
database query -- Run a user-specified query on the astdb
database show -- Shows database contents
database showkey -- Shows database contents
devstate change -- Change a custom device state
devstate list -- List currently known custom device states
dialplan add extension -- Add new extension into context
dialplan add ignorepat -- Add new ignore pattern
dialplan add include -- Include context in other context
dialplan debug -- Show fast extension pattern matching data structures
dialplan reload -- Reload extensions and only extensions
dialplan remove context -- Remove a specified context
dialplan remove extension -- Remove a specified extension
dialplan remove ignorepat -- Remove ignore pattern from context
dialplan remove include -- Remove a specified include from context
dialplan set chanvar -- Set a channel variable
dialplan set extenpatternmatchnew false -- Use the Old extension pattern matching algorithm.
dialplan set extenpatternmatchnew true -- Use the New extension pattern matching algorithm.
dialplan set global -- Set global dialplan variable
dialplan show -- Show dialplan
dialplan show chanvar -- Show channel variables
dialplan show globals -- Show global dialplan variables
dnsmgr refresh -- Performs an immediate refresh
dnsmgr reload -- Reloads the DNS manager configuration
dnsmgr status -- Display the DNS manager status
features show -- Lists configured features
group show channels -- Display active channels with group(s)
http show status -- Display HTTP server status
indication add -- Add the given indication to the country
indication remove -- Remove the given indication from the country
indication show -- Display a list of all countries/indications
local show channels -- List status of local channels
logger add channel -- Adds a new logging channel
logger mute -- Toggle logging output to a console
logger reload -- Reopens the log files
logger remove channel -- Removes a logging channel
logger rotate -- Rotates and reopens the log files
logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off} -- Enables/Disables a specific logging level for this console
logger show channels -- List configured log channels
malloc trim -- Return excess memory to the OS
manager reload -- Reload manager configurations
manager set debug [on|off] -- Show, enable, disable debugging of the manager code
manager show command -- Show a manager interface command
manager show commands -- List manager interface commands
manager show connected -- List connected manager interface users
manager show eventq -- List manager interface queued events
manager show events -- List manager interface events
manager show event -- Show a manager interface event
manager show settings -- Show manager global settings
manager show users -- List configured manager users
manager show user -- Display information on a specific manager user
media cache create -- Create an item in the media cache
media cache delete -- Remove an item from the media cache
media cache refresh -- Refresh an item in the media cache
media cache show all -- Show all items in the media cache
media cache show -- Show a single item in the media cache
module load -- Load a module by name
module reload -- Reload configuration for a module
module show [like] -- List modules and info
module unload -- Unload a module by name
moh reload -- Reload MusicOnHold
moh show classes -- List MusicOnHold classes
moh show files -- List MusicOnHold file-based classes
no debug channel -- Disable debugging on channel(s)
pjproject set log level {default|0|1|2|3|4|5|6} -- Set the maximum active pjproject logging level
pjproject show buildopts -- Show the compiled config of the pjproject in use
pjproject show log level -- Show the maximum active pjproject logging level
pjproject show log mappings -- Show pjproject to Asterisk log mappings
pjsip dump endpt -- Dump the res_pjsip endpt internals
pjsip list aors -- List PJSIP Aors
pjsip list auths -- List PJSIP Auths
pjsip list channels -- List PJSIP Channels
pjsip list ciphers -- List available OpenSSL cipher names
pjsip list contacts -- List PJSIP Contacts
pjsip list endpoints -- List PJSIP Endpoints
pjsip list identifies -- List PJSIP Identifies
pjsip list registrations -- List PJSIP Registrations
pjsip list subscriptions {inbound|outbound} [like] -- List active inbound/outbound subscriptions
pjsip list transports -- List PJSIP Transports
pjsip qualify -- Send an OPTIONS request to a PJSIP endpoint
pjsip reload qualify aor -- Synchronize the PJSIP Aor qualify options
pjsip reload qualify endpoint -- Synchronize the qualify options for all Aors on the PJSIP endpoint
pjsip send register -- Registers an outbound registration target
pjsip send unregister -- Unregisters outbound registration target
pjsip set logger {on|off|host} -- Enable/Disable PJSIP Logger Output
pjsip show aors -- Show PJSIP Aors
pjsip show aor -- Show PJSIP Aor
pjsip show auths -- Show PJSIP Auths
pjsip show auth -- Show PJSIP Auth
pjsip show channels -- Show PJSIP Channels
pjsip show channel -- Show PJSIP Channel
pjsip show channelstats -- Show PJSIP Channel Stats
pjsip show contacts -- Show PJSIP Contacts
pjsip show contact -- Show PJSIP Contact
pjsip show endpoints -- Show PJSIP Endpoints
pjsip show endpoint -- Show PJSIP Endpoint
pjsip show identifiers -- List registered endpoint identifiers
pjsip show identifies -- Show PJSIP Identifies
pjsip show identify -- Show PJSIP Identify
pjsip show qualify aor -- Show the PJSIP Aor current qualify options
pjsip show qualify endpoint -- Show the current qualify options for all Aors on the PJSIP endpoint
pjsip show registrations -- Show PJSIP Registrations
pjsip show registration -- Show PJSIP Registration
pjsip show scheduled_tasks -- Show all scheduled tasks
pjsip show settings -- Show global and system configuration options
pjsip show subscription {inbound|outbound} -- Show active subscription details
pjsip show subscriptions {inbound|outbound} [like] -- Show active inbound/outbound subscriptions
pjsip show transports -- Show PJSIP Transports
pjsip show transport -- Show PJSIP Transport
pjsip show unidentified_requests -- Show PJSIP Unidentified Requests
pjsip show version -- Show the version of pjproject in use
rtcp set debug {on|off|ip} -- Enable/Disable RTCP debugging
rtcp set stats {on|off} -- Enable/Disable RTCP stats
rtp set debug {on|off|ip} -- Enable/Disable RTP debugging
say load [new|old] -- Set or show the say mode
stun set debug {on|off} -- Enable/Disable STUN debugging
timing test -- Run a timing test
udptl set debug {on|off|ip} -- Enable/Disable UDPTL debugging
udptl show config -- Show UDPTL config options
voicemail reload -- Reload voicemail configuration
voicemail show aliases -- List mailbox aliases
voicemail show users [for] -- List defined voicemail boxes
voicemail show zones -- List zone message formats
xmldoc dump -- Dump the XML docs to the specified file

*CLI> core show settings

PBX cores settings 
Version: 16.2.0-rc1
Maximum calls: Not set
Maximum open file handles: 1024
Root console verbosity: 5
Current console verbosity: 5
Debug level: 0
Maximum load average: 0.000000
Minimum free memory: 0 MB
Startup time: 10:27:35
Last reload time: 10:27:35
System: Linux/4.15.0-1021-aws built by root on x86_64 2019-02-11 11:48:29 UTC
System name:
Entity ID: 0e:28:c0:44:39:5e
PBX UUID: a2df96bb-6d1a-4f64-a953-cf02030e9851
Default language: en
Language prefix: Enabled
User name and group: /
Executable includes: Disabled
Transcode via SLIN: Enabled
Transmit silence during rec: Disabled
Generic PLC: Disabled
Generic PLC on equal codecs: Disabled
Min DTMF duration:: 80
Cache media frames: Enabled
RTP use dynamic payloads: 1
RTP dynamic payload types: 35-63,96-127

Manager (AMI): Disabled
Web Manager (AMI/HTTP): Disabled
Call data records: Enabled
Realtime Architecture (ARA): Disabled

Configuration file: /etc/asterisk/asterisk.conf
Configuration directory: /etc/asterisk
Module directory: /usr/lib/asterisk/modules
Spool directory: /var/spool/asterisk
Log directory: /var/log/asterisk
Run/Sockets directory: /var/run/asterisk
PID file: /var/run/asterisk/
VarLib directory: /var/lib/asterisk
Data directory: /var/lib/asterisk
ASTDB: /var/lib/asterisk/astdb
IAX2 Keys directory: /var/lib/asterisk/keys
AGI Scripts directory: /var/lib/asterisk/agi-bin



It is an multi-functional, multi-purpose SIP server especially used in VoIP landscape as standalone SIP server or SBC ( Session Border Controller ) for inbound and outbound traffic by carriers, telecoms backend layers or ITSPs for call routing and trunking solutions. It can be deployed with Class4/5 Platforms, SIP Trunking , hosted or IP PBX setup , existing gateways/ Session Border Controllers, Application Servers, proxy server, Front-End Load Balancers, IMS Platforms, Call Center etc.


Due to its very flexible and customisable routing engine it can be used in number of scenarios such as an SIP proxy or a  router and due to its high throughput it is widely recommended as an enterprise grade inbound/outbound proxy server. Some of the prominent features are,

  • Registrar
  • Router / proxy (lcr, dynamic routing, dialplan features)
  • Redirect server
  • Presence agent
  • Back-to-back User Agent
  • IM server
  • SIP to SMS gateway (bidirectional)
  • SIP to XMPP gateway for presence and IM (bidirectional)
  • Load-balancer or dispatcher
  • Inbound/front end for gateways/asterisk
  • SIP NAT traversal unit
  • Application server with custom logic

I have explained the usage of these server components in my previous article on  SIP entities and Server here

Modular Arhitecture

Opensips has majorly 2 parts core and addon-modules.

Opensips Core part is only a proxy stateless SIP server . It contains

  • SIP transport layer which supports UDP, TCP, TLS and WS for SIP. As per the listener in routing script transport protocols is selected .
  • SIP factory — the message parser and builder which can be used to add new headers or remove existing ones.
  • Routing script parser and interpreter for the routing script which loads it to the memory at the startup time. To load a new script server restart is required.
  • Memory and locking manager for the memory allocation and locking to prevent deadlocks and starvation. Although these arn’t accesible by route scripting, it can be configured at compile time.
  • Core script functions and variables which can be used in routing scripts in addition to the functions exported by add-on modules.


Events Interface

Used to notify external applications about events triggered internal to OpenSIPS such as
core events – E_CORE_THRESHOLD ,E_CORE_PKG_THRESHOLD , E_CORE_SHM_THRESHOLD , modules events , or even a custom event using raise_event() command

Statistics Interface

Provide insights to statistics of opensips in numerical results which could be used for services like  monitoring, load evaluation, realtime integration etc. The statictsics can be of two kinds :
1. counter like – variables that keep counting things that happened in OpenSIPS, like received requests, processed dialogs, failed DB queries, etc
2. computed values – variables that are calculated in realtime, like how much memory is used, the current load, active dialogs, active transactions, etc

These variable would reset form 0 at start sometimes even during runtime.

Binary Internal Interface

Provider communication between individual OpenSIPS instances. Used in cases such as failovers where dialogs needs to persist for service continuity. Hence with this interface one can replicate all the events related to the runtime data (creation / updating / deletion) to a backup OpenSIPS instance.

SQL interface and NoSQL interface

SQL interfaces provides interaction with Sql DB drivers and services such as MySQL, Postgres, Oracle, Berkeley, unixODBC etc , while NoSQL interface provides access to Redis, CouchBase, Cassandra, MongoDB, Memcached, and other databases which are more frequently implemented as external caches.

AAA interface definition

Currently, OpenSIPS supports the RADIUS driver for the AAA interface with upcoming support for DIAMETER.

Management interface

Allows the external applications to trigger predefined commands
Push data like setting a debug level, registering a contact etc
Fetch data like registered users, ongoing calls, get statistics etc
Trigger an internal action as reloading the data, sending a message so on

1. Functional SIP modules

SIP signalling modules such as B2B_ENTITIES , B2B_LOGIC , CALL CENTER ( for Inbound call center system ) , DIALOG , NAT_TRAVERSAL , NATHELPER
TM (Transaction/stateful module) , SL (Stateless replier ) , SMS (SIP-to-SMS IM gateway)

SIP Routing modules such as CARRIERROUTE ( routing extension suitable for carriers) , CPL_C ( Call Processing Langugage interpreter ) ,
JABBER (JABBER IM and PRESENCE interconnection ) , IMC ( Instant Messaging Conferencing ),
LOAD_BALANCER , MSILO (SIP message silo) , RR ( Record-Route) , SCRIPT_HELPER ( Embedded SIP routing logic and dialog management) , OSP ( Open Settlement Protocol )

URI , SST ( SIP Session Timer support )

B2B_SCA ( Back-to-Back Shared Call ), RLS ( Resource List Server )

2. Scripting modules

Script helper modules such as JSON , CFGUTILS , EXEC , TEXTOPS , AVPOPS , REGEX, MATHOPS , BENCHMARK ,
CARRIERROUTE , GFLAGS (Global shared flags )

Auth modules such as AUTH , AUTH_AAA ,AUTH_DB , PERMISSIONS

Accounting & Billing modules aas ACC ,CALL CONTROL

Dialplan Modules like ALIAS_DB , DIALPLAN , DOMAIN ( Multi-domain support ) , DOMAINPOLICY ,


Traffic shaping module as PIKE ( Flood detector module ), QOS ,RATELIMIT ,FRAUD_DETECTION

3. Database modules



4. External Integration modules

EVENT_VIRTUAL ( Aggregator of event backends failover & balancing), EVENT_XMLRPC
MI_DATAGRAM ( DATAGRAM unix and network support for Management Interface )
HTTPD , PI_HTTP ( Provisioning Interface ) , STATISTICS

Media Relays
MEDIAPROXY – NAT traversal module
RTPENGINE – Connector to RTPengine external RTP relay
RTPPROXY – Connector to RTPproxy external RTP relay

non-SIP protocols modules such as AAA_RADIUS , H350 , LDAP – LDAP connector , stable
REST_CLIENT , SEAS ( Sip Express Application Server interface module), SIPCAPTURE , SIPTRACE ,
SNGTC ( Voice Transcoding in OpenSIPS using Sangoma hardware ),
SNMPStats , STUN , XMPP ( SIP-to-XMPP Gateway )

5. OpenSIPS protocols and infrastructure

CLUSTERER , TLS_MGM , PROTO_BIN ( Binary INterface protocol module to implements inter-OPENSIPS communication )

How to Install and use Opensips on your VoIP platform

Install from git repo

git clone opensips_head
install gcc
make all

Install from apt

apt-key adv --keyserver --recv-keys 049AD65B
echo "deb trusty 2.4-releases" >/etc/apt/sources.list.d/opensips.list

check if opensips is running

ps -uax|grep opensips

Configuration ( opensips.cfg )

It has 3 main logical parts :

global parameters – network listeners, available transport protocols, forking (and number of processes), the logging

modules section – the modules that are to be loaded  with path to their .so file

routing logic – logic for routing sip traffic


OpenSIPS routing logic uses several types of routes. Each type of route is triggered by a certain event and allows you to process a certain type of message (request or reply).

  1. route
    SIP requests routing. The main ‘route’ block identified by ‘route{…}’ or ‘route[0]{…}’ is executed for each SIP request.
    To send a reply or forward the request, explicit actions must be called inside the route block. in example below which sends 200 ok reply for each options request.
route {
if(is_method("OPTIONS")) {
sl_send_reply("200", "ok");
route[1] {
  1. branch_route
    Handles different branches of a SIP request. if the branch is not dropped the branch will be automatically sent out. It is executed only by TM module after it was armed via t_on_branch(“branch_route_index”).
if(!t_is_set("branch_route")) t_on_branch("MANAGE_BRANCH");
branch_route[MANAGE_BRANCH] {
xdbg("new branch [$T_branch_idx] to $ru\n");

or lookup location and discard branches where uri matches ip by using drop()

route {
if(!t_relay()) {
sl_send_reply("500", "relaying failed");
branch_route[op3] {
if(uri=~"1\.2\.3\.4") {
  1. failure_route
    Failed transaction routing block. It contains a set of actions to be taken each transaction that received only negative replies (>=300) for all branches which completes the transaction. The ‘failure_route’ is executed only by TM module after it was armed via t_on_failure(“failure_route_index”).
if (is_method("INVITE")) {
if(!t_is_set("failure_route")) t_on_failure("MANAGE_FAILURE");

failure_route[MANAGE_FAILURE] {
if (t_is_canceled()) {

or on failure relay to voice mail

route {
if(!t_relay()) {
sl_send_reply("500", "relaying failed");
failure_route[op1] {
if(is_method("INVITE")) {
  1. onreply_route
    Reply routing block. It can be stateful (if bound to a transaction) or stateless (if global reply route).
    If the reply is not dropped (only provisional replies can be), it will be injected and processed by the transaction engine. There are three types of onreply routes:

global – catches all replies and uses simple definition ‘onreply_route {…}’ or ‘onreply_route[0] {…}’.
Exmaple for “global” reply route set the whole transaction

route {
seturi("");  first branch
append_branch("");  second branch

onreply_route {
xlog("OpenSIPS received a reply from $si\n");

onreply_route[global] {
if (t_check_status("1[0-9][0-9]")) {
log("provisional reply received\n");
if (t_check_status("183"))

per request/transaction – it catches all received replies belonging to a certain transaction and uses “t_on_reply()” at request time, in REQUEST ROUTE – named ‘onreply_route[N] {…}’.

per branch – it catches only the replies that belong to a certain branch from a transaction via “t_on_reply()” ) at request time, but in BRANCH ROUTE, when a certain outgoing branch is processed – named ‘onreply_route[N] {…}’.
Certain ‘onreply_route’ blocks can be executed by TM module for special replies. For this, the ‘onreply_route’ must be armed for the SIP requests whose replies should be processed within it, via t_on_reply(“onreply_route_index”).

Exmaple of reply route set for this branch only

branch_route[1] {
if ($rU=="alice")

onreply_route[alice] {
xlog("received reply on the branch from alice\n");

5. error_route

executed automatically on meeting and error such as parsing error in SIP request processing, script assert failure. Performs error handling . The Default action is to discard request. In error_route, the following pseudo-variables are available to get access to error details:

$(err.class) - the class of error (now is '1' for parsing errors)
$(err.level) - severity level for the error
$( - text describing the error
$(err.rcode) - recommended reply code
$(err.rreason) - recommended reply reason phrase
error_route {
xlog("--- error route class=$(err.class) level=$(err.level)
info=$( rcode=$(err.rcode) rreason=$(err.rreason) ---\n");
xlog("--- error from [$si:$sp]\n+++++\n$mb\n++++\n");
sl_send_reply("$err.rcode", "$err.rreason");
  1. local_route

executed automatically as TM created a new request, internally (no UAC side). This is a route intended to be used for message inspection, accounting and for applying last changes on the message headers. Routing and signaling functions are not allowed.

local_route {
if (is_method("INVITE") && $ru=~"") {
append_hf("P-hint: foreign request\r\n");
if (is_method("BYE") ) {
acc_log_request("internally generated BYE");
  1. startup_route
    Executed only once when OpenSIPS is started and before the processing of SIP messages begins. Used in initilization cases cases such as loading some data in the cache.
startup_route {
avp_db_query("select gwlist where ruleid==1",$avp(i:100));
cache_store("local", "rule1", "$avp(i:100)");
  1. timer_route
    Route executed periodically at a configured interval of time specified next to the name(in seconds).
timer_route[gw_update, 300] {
avp_db_query("select gwlist where ruleid==1",$avp(i:100));
$shv(i:100) =$avp(i:100);
  1. event_route
    execute script code when an event is triggered. If no way to handle the event specified, default will be synchronously.
    Triggered by the event_route module when an event is raised by the OpenSIPS Event Interface such as event raised by the pike module when it decides an ip should be blocked called E_PIKE_BLOCKED or E_SCRIPT_EVENT etc ( checke events interface for more events)
event_route[E_PIKE_BLOCKED] {
xlog("The E_PIKE_BLOCKED event was raised\n");
event_route[E_PIKE_BLOCKED, async] {
xlog("The E_PIKE_BLOCKED event was raised\n");

Scripting Language

Opensips scripting provided more advanced controls

1. Core Keywords

Keywords specific to SIP messages which can be used mainly in ‘if’ expressions.
af – address family of the received SIP message. It is INET if the message was received over IPv4 or INET6 if the message was received over IPv6.

if(af==INET6) {
log("Message received over IPv6 link\n");

dst_ip – IP of the local interface where the SIP message was received.

if(dst_ip== {
log("message received on loopback interface\n");

dst_port – local port where the SIP packet was received

log("message was received on port 5061\n");

from_uri – reference to the URI of ‘From’ header.

if(is_method("INVITE") &amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp; from_uri=~".*")
log("the caller is from\n");

method – SIP method of the message.

log("this SIP request is a REGISTER message\n");

msg:len – the size of the message

sl_send_reply("413", "message too large");

$retcode – value returned by last function executed like $?. If tested after a call of a route, it is the value retuned by that route.

route {
log("The request is an INVITE\n");

route[1] {

proto – transport protocol of the SIP message.

log("SIP message received over UDP\n");

status – status code of the reply.

log("this is a 200 OK reply\n");

1.10 src_ip – source IP address

log("the message was sent from localhost!\n");

1.11 src_port – source port of the SIP message (from which port the message was sent by previous hop).

log("message sent from port 5061\n");

1.12 to_uri – URI from To header.

log("this is a request for users\n");

1.13 uri – request URI.

log("this is a request for users\n");

2. Core Values

Values that can be used in ‘if’ expressions to check against Core Keywords

2.1 INET – IPv4 connection.

2.2 INET6 – IPv6 connection.

2.3 TCP

2.4 UDP

2.5 max_len – test message’s size.

sl_send_reply("413", "message too large to be forwarded over UDP without fragmentation");

2.6 myself – reference to the list of local IP addresses, hostnames and aliases that has been set in OpenSIPS configuration file. This lists contain the domains served by OpenSIPS.

if(uri==myself) {
log("the request is for local processing\n");

2.7 null – reset the value of a per-script variable or to delete an avp.

$avp(i:12) = null;
$var(x) = null;

3. Core parameters

3.1 abort_on_assert – Set to true in order to make OpenSIPS shut down immediately in case a script assert fails.

abort_on_assert = true // default is false

3.2 advertised_address – address advertised in Via header and other destination lumps (e.g RR header).

3.3 advertised_port – port advertised in Via header and other destination lumps (e.g. RR).

3.4 alias – set alias hostnames for the server

3.5 auto_aliases – to control if aliases should be automatically discovered from DNS lookup and added during fixing listening sockets.

auto_aliases=no // default value is no

3.8 cfg_file – Returns the name of the corresponding OpenSIPS config file

3.9 cfg_line – corresponding line inside the OpenSIPS config file.
3.10 check_via – Check if the address in top most via of replies is local.

check_via=1 // Default value is 0 (check disabled)

3.11 children – Number of worker processes (children) to be created for each UDP or SCTP interface you have defined.

children=16 // Default value is 8
3.12 chroot – If set, OpenSIPS will chroot (change root directory) to this valid path in the system value.


3.13 debug_mode – This option will automatically force:

staying in foreground
set logging level to 4 (debug)
set logging to standard error
enable core dumping
set UDP worker processes to 2
set TCP worker processes to 2
Default value is false/0 (disabled).
3.14 db_version_table
The name of the table version to be used by the DB API to check the version of the used tables. Default value is “version”


3.15 db_default_url – default DB URL to be used by modules if no per-module URL is given.


3.16 db_max_async_connections – Maximum number of TCP connections opened from a single OpenSIPS worker to each individual SQL backend. Default value is 10.
Individual backends are determined from DB URLs as follows: [ scheme, user, pass, host, port, database ]

3.18 disable_503_translation – If ‘yes’, OpenSIPS will not translate the received 503 replies into 500 replies .
Default value is ‘no’ (do translation as per RFC 3261).
3.19 disable_core_dump – By default core dump limits are set to unlimited or a high enough value. Set this config variable to ‘yes’ to disable core dump-ing (will set core limits to 0).

disable_core_dump=yes //Default value is ‘no’.

3.20 disable_dns_blacklist
The DNS resolver, when configured with failover, can automatically store in a temporary blacklist the failed destinations. This will prevent (for a limited period of time) OpenSIPS to send requests to destination known as failed. So, the blacklist can be used as a memory for the DNS resolver.

The temporary blacklist created by DNS resolver is named “dns” and it is by default selected for usage (no need use the use_blacklist()) function. The rules from this list have a life time of 4 minutes – you can change it at compile time, from resolve.c . Can be ‘yes’ or ‘no’. By default the blacklist is disabled (Default value is ‘yes’).

3.21 disable_dns_failover – By default DNS-based failover is enabled. Set this config variable to ‘yes’ to disable the DNS-based failover. This is a global option, affecting the core and the modules also.


3.22 disable_stateless_fwd
Can be ‘yes’ or ‘no’. This parameter controls the handling of stateless replies:

yes – drop stateless replies if stateless fwd functions (like forward) are not used in script
no – forward stateless replies
Default value is ‘yes’.

3.23 dns – controls if the SIP server should attempt to lookup its own domain name in DNS. Default is no.

3.24 dns_retr_time – Time in seconds before retrying a dns request. Default value is system specific, depends also on the ‘/etc/resolv.conf’ content (usually 5s).


3.25 dns_retr_no – Number of dns retransmissions before giving up.


3.26 dns_servers_no – How many dns servers from the ones defined in ‘/etc/resolv.conf’ will be used. Default value is to use all of them.


3.27 dns_try_ipv6 – If it is set to ‘yes’ and a DNS lookup fails, it will retry it for ipv6 (AAAA record). Default value is ‘no’.


3.28 dns_try_naptr – Disables the NAPTR lookups when doing DNS based routing for SIP requests – if disabled, the DNS lookup will start with SRV lookups. By default it is enabled, value ‘yes’.


3.29 dns_use_search_list


3.30 dst_blacklist – static (read-only) IP/destination blacklist. These lists can be selected from script (at runtime) to filter the outgoing requests, based on IP, protocol, port, etc.

filter out requests going to ips of my gws
dst_blacklist = gw:{( tcp , , 5060 , “” ),( any , , 0 , “” )}

block requests going to “evil” networks
dst_blacklist = net_filter:{ ( any , , 0 , “” )}

block message requests with nasty words
dst_blacklist = msg_filter:{ ( any , , 0 , “MESSAGE*ugly_word” )}

block requests not going to a specific subnet
dst_blacklist = net_filter2:{ !( any , , 0 , “” )}

Each rule is defined by:

protocol : TCP, UDP, TLS or “any” for anything
port : number or 0 for any
test patter – is a filename like matching (see “man 3 fnmatch”) applied on the outgoing request buffer (first_line+hdrs+body)

3.31 enable_asserts – Set to true in order to enable the assert script statement.

enable_asserts = true

3.32 event_pkg_threshold – A number representing the percentage threshold above which the E_CORE_PKG_THRESHOLD event is raised, warning about low amount of free private memory. It accepts integer values between 0 and 100. Default value is 0 ( event disabled ).

event_pkg_threshold = 90

3.33 event_shm_threshold
A number representing the percentage threshold above which the E_CORE_SHM_THRESHOLD event is raised, warning about low amount of free shared memory. It accepts integer values between 0 and 100.
Default value is 0 ( event disabled ).

event_shm_threshold = 90

3.34 exec_dns_threshold – A number representing the maximum number of microseconds a DNS query is expected to last. Anything above the set number will trigger a warning message to the logging facility. Default value is 0 ( logging disabled ).
exec_dns_threshold = 60000

3.35 exec_msg_threshold – A number representing the maximum number of microseconds the processing of a SIP msg is expected to last. Anything above the set number will trigger a warning message to the logging facility. Aside from the message and the processing time, the most time consuming function calls from the script will also be logged.

Default value is 0 ( logging disabled ).

exec_msg_threshold = 60000
3.38 include_file – load additional routes/blocks with file path

include_file “proxy_regs.cfg”

3.39 import_file – Same as include_file but will not throw an error if file is not found.

import_file “proxy_regs.cfg”

3.40 listen – Set the network addresses the SIP server should listen to. Its syntax is protocol:address[:port], where:

protocol: should be one of the transport modules loaded in the config file (e.g., udp, tcp, tls)
address: can be an IP address, a hostname, a network interface id, or the * wildcard which makes OpenSIPS listen on all possible interfaces for that protocol
port: optional, the port used by the listener – if absent, the default port exported by the transport module is used.
This parameter can be set multiple times in same configuration file, the server listening on all addresses specified.

The listen definition may accept several optional parameters for:

configuring an advertised IP and port only for an interface. Syntax “AS”
setting a different number of children for this interface only (for UDP, SCTP and HEP_UDP interfaces only). This will override the global “children” parameter. Syntax “use_children 5”
Remember that the above parameters only affect the interface they are configured for; if they are not defined for a given interface, the global values will be used instead.

listen = udp:*
listen = udp:eth1
listen = tcp:eth1:5062
listen = tls:localhost:5061
listen = hep_udp:
listen = ws: use_children 5
listen = sctp: as use_children 3
On startup, OpenSIPS reports all the interfaces that it is listening on. The TCP engine processes will be created regardless if you specify only UDP interfaces here.
3.41 log_facility – control the facility for logging in syslog. Default value is LOG_DAEMON.


3.42 log_level – logging level (how verbose OpenSIPS should be). Higher values make OpenSIPS to print more messages.

log_level=1 — print only important messages (like errors or more critical situations) recommended for running proxy as daemon
log_level=4 — print a lot of debug messages use it only when doing debugging sessions

Actual values are:

-3 – Alert level
-2 – Critical level
-1 – Error level
1 – Warning level
2 – Notice level
3 – Info level
4 – Debug level
The ‘log_level’ parameter is usually used in concordance with ‘log_stderror’ parameter.

Value of ‘log_level’ parameter can also be get and set dynamically using log_level Core MI function or $log_level script variable.
3.43 log_name – Set the id to be printed in syslog. The value must be a string and has effect only when OpenSIPS runs in daemon mode (fork=yes), after daemonize. Default value is argv[0].


3.44 log_stderror – write log messages to standard error. Possible values are:
– “yes” – write the messages to standard error
– “no” – write the messages to syslog , also the default
3.45 max_while_loops – maximum loops that can be done within a “while”. Comes as a protection to avoid infinite loops in config file execution. Default is 100.


3.46 maxbuffer – size in bytes not to be exceeded during the auto-probing procedure of discovering the maximum buffer size for receiving UDP messages. Default value is 262144.


3.47 mem-group – Defines a group of modules (by name) to get separate memory statistics.In order for the feature to work you have to run “make generate-mem-stats” and complile with the variable SHM_EXTRA_STATS defined and complile with the variable SHM_SHOW_DEFAULT_GROUP definedwill generate the statistics for the default group

mem-group = “interest”: “core” “tm”
mem-group = “runtime”: “dialog” “usrloc” “tm”
3.48 mem_warming – Only relevant when the HP_MALLOC compile flag is enabled. If set to “on”, on each startup, OpenSIPS will attempt to restore the memory fragmentation pattern it had before the stop/restart.
Default value: off
Memory warming is useful when dealing with high volumes of traffic (thousands of cps on multi-core machines – the more cores, the more useful), because processes must mutually exclude themselves when chopping up the initial big memory chunk. By performing fragmentation on startup, OpenSIPS will also behave optimally in the first minute(s) after a restart. Fragmentation usually lasts a few seconds (e.g. ~5 seconds on an 8GB shm pool and 2.4Ghz CPU) – traffic will not be processed at all during this period.

mem_warming = on

3.49 mem_warming_percentage – How much of OpenSIPS’s memory should be fragmented with the pattern of the previous run, upon a restart.

mem_warming_percentage = 50 //Default value: 75

3.50 mem_warming_pattern_file – Default value: “CFG_DIR/mem_warming_pattern”.The memory fragmentation pattern of a previous OpenSIPS run. Used at startup, if mem_warming is enabled.

mem_warming_pattern_file = “/var/tmp/my_memory_pattern”

3.51 memdump | mem_dump – Log level to print memory status information (runtime and shutdown). Default: memdump=L_DBG (4)


3.52 memlog | mem_lo- Log level to print memory debug info. It has to be less than the value of ‘log_level’ parameter if you want memory info to be logged. Default: memlog=L_DBG (4)


3.53 mcast_loopback – If set to ‘yes’, multicast datagram are sent over loopback. Default value is ‘no’.


3.54 mcast_ttl – Set the value for multicast ttl. Default value is OS specific (usually 1).


3.55 mhomed – Set the server to try to locate outbound interface on multihomed host. By default is not (0) – it is rather time consuming.


3.56 mpath – Set the module search path. This can be used to simplify the loadmodule parameter

mpath="/usr/local/lib/opensips/modules"<br> loadmodule ""<br> loadmodule ""<br> loadmodule ""<br> loadmodule ""<br> loadmodule ""<br> ...

3.57 open_files_limit – If set and bigger than the current open file limit, OpenSIPS will try to increase its open file limit to this number. Note: OpenSIPS must be started as root to be able to increase a limit past the hard limit (which, for open files, is 1024 on most systems).


3.58 poll_method – The poll method to be used by the I/O internal reactor – by default the best one for the current OS is selected. The available types are: poll, epoll_lt, sigio_rt, select, kqueue, /dev/poll.

Starting with version 2.2, epoll_et is deprecated and if it is used in the script, it will be automatically replaced by epoll_lt.


3.59 port – port the SIP server listens to. The default value for it is 5060.

3.60 reply_to_via – If it is set to 1, any local reply is sent to the address advertised in top most Via of the request. Default value is 0 (off).


3.61 query_buffer_size -If set to a value greater than 1, inserts to DB will not be flushed one by one. Rows to be inserted will be kept in memory until until they gather up to query_buffer_size rows, and only then they will be flushed to the database.


3.62 query_flush_time – If query_buffer_size is set to a value greater than 1, a timer will trigger once every query_flush_time seconds, ensuring that no row will be kept for too long in memory.


3.63 rev_dns – should the SIP server attempt to lookup its own IP address in DNS. If this parameter is set to yes and the IP address is not in DNS a warning is printed on syslog and a “received=” field is added to the via header. Default is no.

3.64 server_header – The body of Server header field generated by OpenSIPS when it sends a request as UAS. It defaults to “OpenSIPS (<version> (<arch>/<os>))”.

server_header=”Server: My Company SIP Proxy”

3.65 server_signature – control “Server” header in any locally generated message. If it is enabled (default=yes) a header is generated as Server: OpenSIPS (0.9.5 (i386/linux))

3.66 shm_hash_split_percentage – Only relevant when the HP_MALLOC compile flag is enabled. It controls how many memory buckets will be optimized. (e.g. setting it to 2% will optimize the first 81 most used buckets as frequency). The default value is 1.

3.67 shm_secondary_hash_size – Only relevant when the HP_MALLOC compile flag is enabled. It represents the optimization factor of a single bucket (e.g. setting it to 4 will cause the optimized buckets to be further split into 4). The default value is 8.

3.68 sip_warning – Can be 0 or 1. If set to 1 (default value is 0) a ‘Warning’ header is added to each reply generated by OpenSIPS. The header contains several details that help troubleshooting using the network traffic dumps.


3.69 tcp_children – Number of children processes to be created for reading from TCP connections. If no value is explicitly set, the same number of TCP children as UDP children (see “children” parameter) will be used.


3.70 tcp_accept_aliases – If enabled, OpenSIPS will enforce RFC 5923 behaviour when detecting an “;alias” Via header field parameter and will reuse any TCP (or TLS, WS, WSS) connection opened for such SIP requests (source IP + Via port + proto) when sending other SIP requests backwards, towards the same (source IP + Via port + proto) pair. Default value 0 (disabled).

3.71 tcp_listen_backlog – maximum length for the queue of pending connections for the TCP listeners. Default configured value is 10.

3.72 tcp_connect_timeout – Time in milliseconds before an ongoing blocking attempt to connect will be aborted. Default value is 100ms.

tcp_connect_timeout = 5

3.73 tcp_connection_lifetime – Lifetime in seconds for TCP sessions. Default value is defined in tcp_conn.h: define DEFAULT_TCP_CONNECTION_LIFETIME 120.

tcp_connection_lifetime = 3600

3.74 tcp_max_connections – maximum number of tcp connections. Default is defined in tcp_conn.h: define DEFAULT_TCP_MAX_CONNECTIONS 2048

tcp_max_connections = 4096

3.75 tcp_max_msg_time – maximum number of seconds that a SIP message is expected to arrive via TCP. Default value is 4

tcp_max_msg_time = 8

3.76 tcp_no_new_conn_bflag -A branch flag to be used as marker to instruct OpenSIPS not to attempt to open a new TCP connection when delivering a request, but only to reuse an existing one (if available). If no existing conn, a generic send error will be returned.

This is intended to be used in NAT scenarios, where makes no sense to open a TCP connection towards a destination behind a NAT (like TCP connection created during registration was lost, so there is no way to contact the device until it re-REGISTER). Also this can be used to detect when a NATed registered user lost his TCP connection, so that opensips can disable his registration as useless.

 tcp_no_new_conn_bflag = TCP_NO_CONNECT<br> ...<br> route {<br> ...<br> if (isflagset(DST_NATED) &amp;&amp; $proto == "TCP")<br>     setbflag(TCP_NO_CONNECT);<br>     ...<br>     t_relay("0x02"); // no auto error reply<br>     $var(retcode) = $rc;<br>     if ($var(retcode) == -6) {<br>         xlog("unable to send request to destination");<br>         send_reply("404", "Not Found");<br>         exit;<br>     } else if ($var(retcode) &lt; 0) {<br>         sl_reply_error();<br>         exit;<br>     }<br> } 

3.77 tcp_threshold – A number representing the maximum number of microseconds sending of a TCP request is expected to last. Anything above the set number will trigger a warning message to the logging facility. Default value is 0 ( logging disabled ).

tcp_threshold = 60000

3.78 tcp_keepalive – Enable or disable TCP keepalive (OS level). Enabled by default.

tcp_keepalive = 1

3.79 tcp_keepcount -Number of keepalives to send before closing the connection (Linux only).

Default value: 0 (not set). Setting tcp_keepcount to any value will enable tcp_keepalive.

tcp_keepcount = 5

3.80 tcp_keepidle – Amount of time before OpenSIPS will start to send keepalives if the connection is idle (Linux only).
Default value: 0 (not set)

tcp_keepidle = 30

3.81 tcp_keepinterval – Interval between keepalive probes, if the previous one failed (Linux only).Default value: 0 (not set). Setting tcp_keepinterval to any value will enable tcp_keepalive.

tcp_keepinterval = 10

3.82 tls_ca_list

3.83 tls_certificate

3.84 tls_ciphers_list

3.85 tls_domain

3.86 tls_handshake_timeout

3.87 tls_log

3.88 tls_method

3.89 tls_port_no

3.90 tls_private_key

3.91 tls_require_certificate

3.92 tls_send_timeout

3.93 tls_verify

3.94 tos – The TOS (Type Of Service) to be used for the sent IP packages (both TCP and UDP).


3.96 user_agent_header – The body of User-Agent header field generated by OpenSIPS when it sends a request as UAC. It defaults to “OpenSIPS (<version> (<arch>/<os>))”.

user_agent_header=”User-Agent: My Company SIP Proxy”

3.97 wdir – working directory used by OpenSIPS at runtime.


3.98 xlog_buf_size – Default value: 4096

Size of the buffer used to print a single line on the chosen logging facility of OpenSIPS. If the buffer is too small, an overflow error will be printed, and the concerned line will be skipped.

xlog_buf_size = 8388608 #given in bytes

3.99 xlog_force_color

xlog_force_color = true //Default value: false

3.100 xlog_default_level -Default value for the logging level of the xlog core function, when the log_level parameter is omitted.

xlog_default_level = 2 #L_NOTICE // Default value: -1


OpenSIPS routing logic uses several types of routes. Each type of route is triggered by a certain event and allows you to process a certain type of message (request or reply).

  • route
    SIP requests routing. The main ‘route’ block identified by ‘route{…}’ or ‘route[0]{…}’ is executed for each SIP request.
    To send a reply or forward the request, explicit actions must be called inside the route block. in example below which sends 200 ok reply for each options request.
route {
if(is_method("OPTIONS")) {
sl_send_reply("200", "ok");
route[1] {
  • branch_route
    Handles different branches of a SIP request. if the branch is not dropped the branch will be automatically sent out. It is executed only by TM module after it was armed via t_on_branch(“branch_route_index”).
if(!t_is_set("branch_route")) t_on_branch("MANAGE_BRANCH");
branch_route[MANAGE_BRANCH] {
xdbg("new branch [$T_branch_idx] to $ru\n");

or lookup location and discard branches where uri matches ip by using drop()

route {
if(!t_relay()) {
sl_send_reply("500", "relaying failed");
branch_route[op3] {
if(uri=~"1\.2\.3\.4") {
  • failure_route
    Failed transaction routing block. It contains a set of actions to be taken each transaction that received only negative replies (>=300) for all branches which completes the transaction. The ‘failure_route’ is executed only by TM module after it was armed via t_on_failure(“failure_route_index”).
if (is_method("INVITE")) {
if(!t_is_set("failure_route")) t_on_failure("MANAGE_FAILURE");

failure_route[MANAGE_FAILURE] {
if (t_is_canceled()) {

or on failure relay to voice mail

route {
if(!t_relay()) {
sl_send_reply("500", "relaying failed");
failure_route[op1] {
if(is_method("INVITE")) {
  • onreply_route
    Reply routing block. It can be stateful (if bound to a transaction) or stateless (if global reply route).
    If the reply is not dropped (only provisional replies can be), it will be injected and processed by the transaction engine. There are three types of onreply routes:

global – catches all replies and uses simple definition ‘onreply_route {…}’ or ‘onreply_route[0] {…}’.
Exmaple for “global” reply route set the whole transaction

route {
seturi("");  first branch
append_branch("");  second branch

onreply_route {
xlog("OpenSIPS received a reply from $si\n");

onreply_route[global] {
if (t_check_status("1[0-9][0-9]")) {
log("provisional reply received\n");
if (t_check_status("183"))

per request/transaction – it catches all received replies belonging to a certain transaction and uses “t_on_reply()” at request time, in REQUEST ROUTE – named ‘onreply_route[N] {…}’.

per branch – it catches only the replies that belong to a certain branch from a transaction via “t_on_reply()” ) at request time, but in BRANCH ROUTE, when a certain outgoing branch is processed – named ‘onreply_route[N] {…}’.
Certain ‘onreply_route’ blocks can be executed by TM module for special replies. For this, the ‘onreply_route’ must be armed for the SIP requests whose replies should be processed within it, via t_on_reply(“onreply_route_index”).

Exmaple of reply route set for this branch only

branch_route[1] {
if ($rU=="alice")

onreply_route[alice] {
xlog("received reply on the branch from alice\n");
  • error_route

executed automatically on meeting and error such as parsing error in SIP request processing, script assert failure. Performs error handling . The Default action is to discard request. In error_route, the following pseudo-variables are available to get access to error details:

$(err.class) - the class of error (now is '1' for parsing errors)
$(err.level) - severity level for the error
$( - text describing the error
$(err.rcode) - recommended reply code
$(err.rreason) - recommended reply reason phrase
error_route {
xlog("--- error route class=$(err.class) level=$(err.level)
info=$( rcode=$(err.rcode) rreason=$(err.rreason) ---\n");
xlog("--- error from [$si:$sp]\n+++++\n$mb\n++++\n");
sl_send_reply("$err.rcode", "$err.rreason");
  • local_route

executed automatically as TM created a new request, internally (no UAC side). This is a route intended to be used for message inspection, accounting and for applying last changes on the message headers. Routing and signaling functions are not allowed.

local_route {
if (is_method("INVITE") && $ru=~"") {
append_hf("P-hint: foreign request\r\n");
if (is_method("BYE") ) {
acc_log_request("internally generated BYE");
  • startup_route
    Executed only once when OpenSIPS is started and before the processing of SIP messages begins. Used in initilization cases cases such as loading some data in the cache.
startup_route {
avp_db_query("select gwlist where ruleid==1",$avp(i:100));
cache_store("local", "rule1", "$avp(i:100)");
  • timer_route
    Route executed periodically at a configured interval of time specified next to the name(in seconds).
timer_route[gw_update, 300] {
avp_db_query("select gwlist where ruleid==1",$avp(i:100));
$shv(i:100) =$avp(i:100);
  • event_route
    execute script code when an event is triggered. If no way to handle the event specified, default will be synchronously.
    Triggered by the event_route module when an event is raised by the OpenSIPS Event Interface such as event raised by the pike module when it decides an ip should be blocked called E_PIKE_BLOCKED or E_SCRIPT_EVENT etc ( checke events interface for more events)
event_route[E_PIKE_BLOCKED] {
xlog("The E_PIKE_BLOCKED event was raised\n");
event_route[E_PIKE_BLOCKED, async] {
xlog("The E_PIKE_BLOCKED event was raised\n");

Ref :

Sip server Brekeke

We used Brekeke SIP server to run our SIP applications . Although there are newer versions of Brekeke SIP server out now . More awesome than before , we prefer using the old one for the sake of not messing with legacy SIP applications . The official site for brekeke is – .

A general architecture of Brekeke SIP server is . brekeke

Here are the steps of installing and configuring a Brekeke SIP server .

Step 1: Download the Server form and run the setup file .





brekek2 brekek3 brekek6

brekeke4 brekeke5 brekeke7  brekeke9

Step 2: It is always good to give a look to README file . brekeke11

Step 3: Run the local implementation of SIP server at localhost or at port 8080brekeke12

Step 4: Important is to get the license which will help us activate the SIP server . One can obtain a free license from

Step 5 : Once the license is activates , we can goto the console screen after loggin with default username and password sa . brekeke13

Step 6 : Once we are at console , we could add/ delete / modify parameters like port , start/shutdown status etc . brekeke14 brekeke14_001Step 7 : Once the server is all setup , just add the IP and port of SIP server to SIP clients server filed . Now all the SIP request and response will be catered by this SIP Server

Kamailio Modules

Post has been edited after publishing with updated content and Kamailio modules .

Since kamailio has a modular architecture with core components and modules to extend the functionality  , this article will be discussing few of the essential modules in Kamailio.

Few categories of modules discoverable via apt-cache search kamailio

  • kamailio – very fast and configurable SIP proxy
  • kamailio-autheph-modules – authentication using ephemeral credentials module for Kamailio
  • kamailio-berkeley-bin – Berkeley database module for Kamailio – helper program
  • kamailio-berkeley-modules – Berkeley database module for Kamailio
  • kamailio-carrierroute-modules – carrierroute module for Kamailio
  • kamailio-cnxcc-modules – cnxcc modules for Kamailio
  • kamailio-cpl-modules – CPL module (CPL interpreter engine) for Kamailio
  • kamailio-dbg – very fast and configurable SIP proxy [debug symbols]
  • kamailio-dnssec-modules – contains the dnssec module
  • kamailio-erlang-modules – earlang modules for Kamailio
  • kamailio-extra-modules – extra modules for Kamailio
  • kamailio-geoip-modules – contains the geoip module
  • kamailio-ims-modules – IMS module for Kamailio
  • kamailio-java-modules – contains the app_java module
  • kamailio-json-modules – Json parser and jsonrpc modules for Kamailio
  • kamailio-kazoo-modules – kazoo modules for Kamailio
  • kamailio-ldap-modules – LDAP modules for Kamailio
  • kamailio-lua-modules – contains the app_lua module
  • kamailio-memcached-modules – interface to memcached server
  • kamailio-mono-modules – contains the app_mono module
  • kamailio-mysql-modules – MySQL database connectivity module for Kamailio
  • kamailio-outbound-modules – Outbound module for Kamailio
  • kamailio-perl-modules – Perl extensions and database driver for Kamailio
  • kamailio-postgres-modules – PostgreSQL database connectivity module for Kamailio
  • kamailio-presence-modules – SIMPLE presence modules for Kamailio
  • kamailio-purple-modules – Provides the purple module, a multi-protocol IM gateway
  • kamailio-python-modules – contains the app_python module
  • kamailio-radius-modules – RADIUS modules for Kamailio
  • kamailio-redis-modules – Redis database connectivity module for Kamailio
  • kamailio-sctp-modules – sctp module for Kamailio
  • kamailio-snmpstats-modules – SNMP AgentX subagent module for Kamailio
  • kamailio-sqlite-modules – SQLite database connectivity module for Kamailio
  • kamailio-tls-modules – contains the TLS kamailio transport module
  • kamailio-unixodbc-modules – unixODBC database connectivity module for Kamailio
  • kamailio-utils-modules – Provides a set utility functions for Kamailio
  • kamailio-websocket-modules – Websocket module for kamailio
  • kamailio-xml-modules – XML based extensions for Kamailio’s Management Interface
  • kamailio-xmpp-modules – XMPP gateway module for Kamailio

The first set under explanation is Usrloc and Register module which take care of user persistance in Database and handling an incoming register request with authentication and validation.

Usrloc Module


db_ops_ruid (int)
handle_lost_tcp (int)
close_expired_tcp (int)
expires_type (int)
db_raw_fetch_type (int)
db_insert_null (int)
skip_remote_socket (int)
db_timer_clean (int)
server_id_filter (int)

RPC Commands

ul.lookup table AOR
ul.rm table AOR
ul.rm_contact table AOR contact




ul_insert_urecord(domain, aor, rec)
ul_delete_urecord(domain, aor)
ul_delete_urecord_by_ruid(domain, ruid)
ul_get_urecord(domain, aor)
ul_insert_ucontact(record, contact, expires, q, callid, cseq, flags, cont, ua, sock)
ul_delete_ucontact (record, contact)
ul_get_ucontact(record, contact)
ul_get_all_ucontacts (buf, len, flags)
ul_update_ucontact(contact, expires, q, callid, cseq, set, res, ua, sock)
ul_bind_ursloc( api )
ul_register_ulcb(type ,callback, param)


SIP registration processing logic can be defined here .

Path support – off , lazy , strict ( RFC 3327)

GRU ( Globally Routbale User agent URIs)  support –  public , temporary ( RFC 5627)

Dependencies :

  • usrloc – User Location Module.
  • sl – Stateless Replies.

Parameters :

aor_avp (str)
received_avp (str)

Functions :

save(domain, [, flags [, uri]])
lookup(domain [, uri])
registered(domain [, uri [, match_option [, match_action]]])
unregister(domain, uri[, ruid])
reg_fetch_contacts(domain, uri, profile)

Event Routes :


Statistics :



Dialog support module

Parameters :

event_callback (str)

Functions :

dlg_refer(side, address)
dlg_bridge(from, to, op)
dlg_get(callid, ftag, ttag)
dlg_set_timeout(timeout [, h_entry, h_id])
dlg_set_timeout_by_profile(profile, [value], timeout)
dlg_remote_profile(cmd, profile, value, uid, expires)

Statistics :


RPC Commands :

  • dlg.list

Exported Variables :


Event Routes :

  • event_route[dialog:start]
  • event_route[dialog:end]
  • event_route[dialog:failed]

UAC module

This set deals with RTP proxy and RTP engine which are used for proxing media streams via kamailio server .

RTP Proxy

Used to proxy the media stream . Example : Sippy RTPproxy , ngcp-rtpproxy-ng . Multiple RTP proxies can be used for load distribution and balancing . RTP proxy can also operated in bridging mode to setup bridge signalling between multiple network interfaces. It does not support transcoding.

Parameters :

  • rtpproxy_sock – binds a ip and port for rtp proxy
    modparam(“rtpproxy”, “rtpproxy_sock”, “udp:localhost:12221”)
  • rtpproxy_disable_tout – when rtp proxy is disabled then timeout till when it doesnt connect
  • rtpproxy_tout – timeout to wait for reply
  • rtpproxy_retr – num of retries after timeout
  • nortpproxy_str – sets the SDP attribute used by rtpproxy to mark the message’s SDP attachemnt with information that it have already been changed
    default value is “a=nortpproxy:yes\r\n” and others like “a=sdpmangled:yes\r\n”
  • timeout_socket (string)
  • ice_candidate_priority_avp (string)
  • extra_id_pv (string)
  • db_url (string)
  • table_name (string)
  • rtp_inst_pvar (string)


set_rtp_proxy_set(setid) – Sets the Id of the rtpproxy set to be used for the next unforce_rtp_proxy(), rtpproxy_offer(), rtpproxy_answer() or rtpproxy_manage() command

rtpproxy_offer([flags [, ip_address]]) – to make the media pass through RTP the SDP is altered. Value of flag can be
1 – append first Via branch to Call-ID when sending command to rtpproxy.
2 – append second Via branch to Call-ID when sending command to rtpproxy. See flag ‘1’ for its meaning.
3 – behave like flag 1 is set for a request and like flag 2 is set for a reply
a – flags that UA from which message is received doesn’t support symmetric RTP. (automatically sets the ‘r’ flag)
b – append branch specific variable to Call-ID when sending command to rtpproxy
l – force “lookup”, that is, only rewrite SDP when corresponding session already exists in the RTP proxy
i, e – direction of the SIP message when rtpproxy is running in bridge mode. ‘i’ is internal network (LAN), ‘e’ is external network (WAN). Values ie , ei , ee and ii
x – shortcut for using the “ie” or “ei”-flags, to do automatic bridging between IPv4 on the “internal network” and IPv6 on the “external network”. Differentiated by IP type in the SDP, e.g. a IPv4 Address will always call “ie” to the RTPProxy (IPv4(i) to IPv6(e)) and an IPv6Address will always call “ei” to the RTPProxy (IPv6(e) to IPv4(i))
f – instructs rtpproxy to ignore marks inserted by another rtpproxy in transit to indicate that the session is already gone through another proxy. Allows creating a chain of proxies
r – IP address in SDP should be trusted. Without this flag, rtpproxy ignores address in the SDP and uses source address of the SIP message as media address which is passed to the RTP proxy
o – flags that IP from the origin description (o=) should be also changed.
c – flags to change the session-level SDP connection (c=) IP if media-description also includes connection information.
w – flags that for the UA from which message is received, support symmetric RTP must be forced.
zNN – perform re-packetization of RTP traffic coming from the UA which has sent the current message to increase or decrease payload size per each RTP packet forwarded if possible. The NN is the target payload size in ms, for the most codecs its value should be in 10ms increments, however for some codecs the increment could differ (e.g. 30ms for GSM or 20ms for G.723).
ip_address denotes the address of new SDP

such as : rtpproxy_offer(“FRWOC+PS”) is
rtpengine_offer(“force trust-address symmetric replace-origin replace-session-connection ICE=force RTP/SAVPF”);

route {
if (is_method("INVITE")) {
if (has_body("application/sdp")) {
if (rtpproxy_offer())
} else {
if (is_method("ACK") && has_body("application/sdp"))

if (has_body("application/sdp"))

if (has_body("application/sdp"))

rtpproxy_answer([flags [, ip_address]])- reqrite SDP to proxy media , it can be used from REQUEST_ROUTE, ONREPLY_ROUTE, FAILURE_ROUTE, BRANCH_ROUTE.

rtpproxy_destroy([flags]) – tears down RTP proxy session for current call. Flags are ,
1 – append first Via branch to Call-ID
2 – append second Via branch to Call-ID
b – append branch specific variable to Call-ID
t – do not include To tag to “delete” command to rtpproxy thus causing full call to be deleted


rtpproxy_manage([flags [, ip_address]]) – Functionality is to use predfined logic for handling requests
If INVITE with SDP, then do rtpproxy_offer()
If INVITE with SDP, when the tm module is loaded, mark transaction with internal flag FL_SDP_BODY to know that the 1xx and 2xx are for rtpproxy_answer()
If ACK with SDP, then do rtpproxy_answer()
If BYE or CANCEL, or called within a FAILURE_ROUTE[], then call unforce_rtpproxy().
If reply to INVITE with code >= 300 do unforce_rtpproxy()
If reply with SDP to INVITE having code 1xx and 2xx, then do rtpproxy_answer() if the request had SDP or tm is not loaded, otherwise do rtpproxy_offer()
This function can be used from ANY_ROUTE.

rtpproxy_stream2uac(prompt_name, count) – stream prompt/announcement pre-encoded with the makeann command. The uac/uas suffix selects who will hear the announcement relatively to the current transaction – UAC or UAS. Also used for music on hold (MOH).
Params : prompt_name – path name of the prompt to stream
count – number of times the prompt should be repeated. When count is -1, the streaming will be in loop indefinitely until the appropriate rtpproxy_stop_stream2xxx is issued.
Example rtpproxy_stream2xxx usage

if (is_method("INVITE")) {
if (is_audio_on_hold()) {
rtpproxy_stream2uas("/var/rtpproxy/prompts/music_on_hold", "-1");
} else {

rtpproxy_stream2uas(prompt_name, count)

rtpproxy_stop_stream2uac()- Stop streaming of announcement/prompt/MOH


Exported Pseudo Variables

RPC Commands


RTP Engine

media streams to be proxied via an RTP proxy.

source :


rtpengine_sock (string)
rtpengine_disable_tout (integer)
rtpengine_tout_ms (integer)
rtpengine_allow_op (integer)
queried_nodes_limit (integer)
rtpengine_retr (integer)
extra_id_pv (string)
setid_avp (string)
force_send_interface (string)
read_sdp_pv (string)
write_sdp_pv (string)
rtp_inst_pvar (string)
hash_table_size (integer)
hash_table_tout (integer)
db_url (string)
table_name (string)
setid_col (string)
url_col (string)
weight_col (string)
disabled_col (string)
setid_default (integer)
mos_min_pv (string)
mos_min_at_pv (string)
mos_min_packetloss_pv (string)
mos_min_jitter_pv (string)
mos_min_roundtrip_pv (string)
mos_max_pv (string)
mos_max_at_pv (string)
mos_max_packetloss_pv (string)
mos_max_jitter_pv (string)
mos_max_roundtrip_pv (string)
mos_average_pv (string)
mos_average_packetloss_pv (string)
mos_average_jitter_pv (string)
mos_average_roundtrip_pv (string)
mos_average_samples_pv (string)
mos_A_label_pv (string)
mos_min_A_pv (string)
mos_min_at_A_pv (string)
mos_min_packetloss_A_pv (string)
mos_min_jitter_A_pv (string)
mos_min_roundtrip_A_pv (string)
mos_max_A_pv (string)
mos_max_at_A_pv (string)
mos_max_packetloss_A_pv (string)
mos_max_jitter_A_pv (string)
mos_max_roundtrip_A_pv (string)
mos_average_A_pv (string)
mos_average_packetloss_A_pv (string)
mos_average_jitter_A_pv (string)
mos_average_roundtrip_A_pv (string)
mos_average_samples_A_pv (string)
mos_B_label_pv (string)
mos_min_B_pv (string)
mos_min_at_B_pv (string)
mos_min_packetloss_B_pv (string)
mos_min_jitter_B_pv (string)
mos_min_roundtrip_B_pv (string)
mos_max_B_pv (string)
mos_max_at_B_pv (string)
mos_max_packetloss_B_pv (string)
mos_max_jitter_B_pv (string)
mos_max_roundtrip_B_pv (string)
mos_average_B_pv (string)
mos_average_packetloss_B_pv (string)
mos_average_jitter_B_pv (string)
mos_average_roundtrip_B_pv (string)
mos_average_samples_B_pv (string)

set_rtpengine_set(setid[, setid])
Exported Pseudo Variables
RPC Commands

rtpengine.enable proxy_url/all 0/1 proxy_url/all proxy_url/all

This set deals with HTTP and Websocket adapters to handle web pone based ( such as webRTC) calls on kamailio


Provides basic HTTP/1.0 server functionality .

SIP requires a Content-Length header for TCP transport. But most HTTP clients do not set the content length for normal GET requests. Therefore, the core must be configured to allow incoming requests without content length header:


Parameters :

url_skip : if there is a match , event route is not executed
modparam(“xhttp”, “url_skip”, “^/RPC2”)

url_match : if there is no match , event route is not executed
modparam(“xhttp”, “url_match”, “^/sip/”)

event_Callback : function in the kemi configuration file (embedded scripting language such as Lua, Python) to be executed instead of event_route[xhttp:request] block
Example :
modparam(“xhttp”, “event_callback”, “ksr_xhttp_event”)
and the event callback function implemented in Lua
function ksr_xhttp_event(evname)“===== xhttp module triggered event: ” .. evname .. “\n”);
return 1;


xhttp_reply(code, reason, ctype, body) – Send back a reply with content-type and body.

event_route[xhttp:request] {
xhttp_reply("200", "OK", "" , "");
xhttp_reply("403", "Forbidden", "", "");

Event Routes

The event route is executed when a new HTTP request is received.

event_route[xhttp:request] {
xhttp_reply(“200”, “OK”, “text/html”, “<html><body>OK – [$si:$sp]</body></html>”);

Websocket Module

provide websocket ( ws and wss) support to kamailio ( RFC 6455). Handles handshaking, management (including connection keep-alive), and framing for the SIP and MSRP WebSocket sub-protocols (RFC 7118 and RFC 7977).

IPTV ( Internet Based Television )

We know the power of Internet protocol suit as it takes on the world of telecom . Alreday half of Communication has been transferred from legacy telecom signalling protocols like SS7 to IP based communication ( Skype , Hangouts , whatsapp , facebook call ) . The TV service providers too are largely investing in IP based systems like SIP and IMS to deliver their content over Telecom’s IP based network ( Packet switched ).

A consumer today wants HD media content anytime anywhere . The traditional TV solutions just dont match upto the expectations anymore . The IPTV provider in todays time must make investments to deliver content that is media-aware, and device-aware. Not only this it should be  personal, social, and interactive . after all its all about user  experience.

Few popular applications for IPTV solutions developers are

  • Menu overlay with detailed description of channels , categories , programs , movies
  • Replay option also referred to as timeshift . It allows a user to pause , resume and  record the show in his absence and view it later
  • Video on demand which concerns paying and viewing music albums , movies etc on demand
  • Live streaming of events such as president speech , tennis match etc .

Application that can be build around the IPTV context

  • Record and Playback content
  • Information overlay on streaming content
  • Social networking services integrated with IPTV content
  • Parental Control to realtime view , monitor and control what your child is watching on the IPTV
  • Watch the surveillance  footage from IP cameras anywhere
  • Real time communication on IPTV  with advanced features like call continuity , content sync .

Telephony Solutions with Kamailio

Kamailio™ (former OpenSER) is an Open Source SIP Server released under GPL.

Kamailio primarily acts as a SIP server for VOIP and telecommunications platforms under various roles and can handle load of hight CPS ( Calls per second ) with custom call routing logic with the help of scripts .

IMS extensions for VoLTE; ENUM; DID and least cost routing; load balancing; routing fail-over; Json and XMLRPC control interface, SNMP monitoring.


  • SIP (RFC3261) support

It can work as Registrar or Location server. For SIP call logic it can become a Proxy or SIP Application server . Can also act like an Redirect , Dispatcher or simply a SIP over websocket server.

  • Kamailio is Customisable to suit business requirement and scale .

It can be embedded to devices as the binary file is small size. Additional modules can be appended for more functions with the same core.

Due to its modular architecture – core, internal libraries , module interface and ability to extend functionality with scripts such as LUA , Kamailio can be readily integrated to a VOIP ecosystem.

  • Call routing and control functionality 

Offers stateless and transactional stateful SIP Proxy processing ( suited for inbound gateways ) and serial and parallel forking.

Also NAT traversal support for SIP and RTP traffic ( suited to be WebRTC server )

Among other features it offers load balancing with many distribution algorithms and failover support , flexible least cost routing , routing failover and replication for High Availability (HA).

Can be readily integrated with external databases , caches, notification system ( SNS , APNS , GCM ), voip monitors , CDR processors, API systems etc for  efficient call processing.

  • Transport Layers supported 

    • UDP, TCP, TLS and SCTP
    • IPv4 and IPv6
    • gateways via (IPv4 to IPv6, UDP to TLS, a.s.o.)
    • SCTP multi-homing and multi-streaming
    • WebSocket for WebRTC 
  • Asynchronous TCP, UDP and SCTP,

asynchronous SIP message processing and  inter-process message queues communication system

  • Secure Communication ( TLS  + AAA)

    • Digest SIP User authentication
    • Authorization via ACL or group membership
    • IP and Network authentication
    • TLS support for SIP signaling
    • transparent handling of SRTP for secure audio
    • TLS domain name extension support
    • authentication and authorization against database (MySQL, PostgreSQL, UnixODBC, BerkeleyDB, Oracle, text files), RADIUS and DIAMETER
  • IP and DNS

    • support for SRV and NAPTR DNS lookups
    • SRV DNS failover
    • DNSsec support
    • ENUM support
    • internal DNS caching system – avoid DNS blocking
    • IP level Blacklists
    • multi-homed and multi-domain support
    • topology hiding – hide IP addresses in SIP headers to protect your network architecture
  • Accounting

Kamailio gives event based and configurable accounting data details. Can show multi-leg call accounting ( A leg to B leg ). It can store to database, Radius or Diameter based on module used . Has a prepaid engine.

  • External Interaction

text-based management interface via FIFO file, udp, xmlrpc and unix sockets.

RPC control interface – via XMLRPC, UDP or TCP

  • Rich Communication Services (RCS)

    • SIP SIMPLE Presence Server (rich presence)
    • Presence User Agent ( SUBSCRIBE , NOTIFY and PUBLSH)
    • XCAP client capabilities and Embedded XCAP Server
    • Presence DialogInfo support – SLA/BLA
    • Instant Messaging ( IM) 
    • Embedded MSRP relay
  • Monitoring and Troubleshooting

Support for SNMP – interface to Simple Network Management Protocol.  For Debugging it has config debugger , remote control via XMLRPC and error message logging system .Provides internal statistics exported via RPC and SNMP.

  • Extensibility APIs

The supported  one are Perl  , Java SIP Servlet Application Interface  , Lua  , Managed Code (C#) , Python

  • Multiple Database Backends

(MySQL, PostgreSQL, SQLite, UnixODBC, BerkeleyDB, Oracle, text files) and other database types which have unixodbc drivers. ‘

It can have connections pool and different backends  be used at same time (e.g., accounting to Oracle and authorization against MySQL).

Has connectors for Memcached, Redis , MongoDB and Cassandra no-SQL backends

  • Interconnectivity

Acts as SIP to PSTN gateway and gateway to sms or xmpp and other IM services. Has Interoperability with SIP enabled devices and applications such as SIP phones (Snom, Cisco, etc.), Media Servers (Asterisk, FreeSwitch, etc.)

  • IMS

    • diameter support and authentication
    • charging, QOS, ISC
  • Miscellaneous

    • CPL – Call Processing Language (RFC3880)
    • Internal generic caching system
    • Memcached connector
    • Redis NoSQL database connector
    • CLI – kamctl and sercmd
    • Web Management Interface: Siremis
    • SIP-T and SIP-I
    • music on hold queue
    • message body compression/decompression (gzip-deflate)
  • Extensive documentation for both administrators and developers


  • Kamailio can run on embedded systems, with limited resources – the performances can be up to hundreds of call setups per second
  • used as load balancer in stateless mode, Kamailio can handle over 5000 call setups per second
  • on systems with 4GB memory, Kamailio can serve a population over 300 000 online subscribers
  • system can easily scale by adding more Kamailio servers
  • Kamailio can be used in geographic distributed VoIP platforms
  • Kamailio least-cost-routing scales up to millions of routing rules
  • straightforward failover and redundancy

Start Kamalio

service kamailo start


tail -f /var/log/kamailio

To Check if Kamailio instance is running

>ps -ax | grep “kamailio”

57411 ?        S      0:01 /usr/sbin/kamailio -f /etc/kamailio/kamailio.cfg -P /var/run/kamailio/ -m 4096 -M 128 -u root -g root

Installation and Configuration

Installing kammlio from git repo

clone kamailio from their github

goto desired branch

The contents of clonned folder are

COPYING ChangeLog INSTALL ISSUES Makefile README doc etc misc pkg test utils

run ‘make cfg’ which compiles using gcc abd created ‘src’ folder with contents

make cfg

Makefile Makefile.defs Makefile.groups Makefile.modules Makefile.rules Makefile.sources Makefile.utils core main.c modules.lst Makefile.cfg Makefile.dirs Makefile.libs Makefile.radius Makefile.shared Makefile.targets config.mak lib modules

Edit modules.lst to enable db_mysql and dialplan module

vim src/modules.lst

//the list of extra modules to compile

include_modules= db_mysql

Use ‘make’ command followed by make all . Make sure to have gcc bison and flex installed

make cfg

make all

Alternativey on debian system , use readymade measures like

apt install mysql-server

apt install kamailio kamailio-mysql-modules

To validate and verify the location of kamillio use ‘which kamailio’ which returns /usr/sbin/kamailio

For Modules installation , check all avaible modules with command ‘apt search kamailio’and to install a new module such as websockt module use ‘apt install kamailio-websocket-modules’

Database access
After installaing kamailio , edit the kamailio.cfg file in /etc/kamailio to set the reachabe SIP domain, database engine, username/password etc to connect to databaseand enable the kamdbctl script to run and create users and tables, etc.


chrooted directory


database type: MYSQL, PGSQL, ORACLE, DB_BERKELEY, DBTEXT, or SQLITE by default none is loaded


Run kamdbctl to create users and database now

kamdbctl create

the databa created is name kamailio and its tables are

  • +———————+
  • | Tables_in_kamailio  |
  • +———————+
  • | acc                 |
  • | acc_cdrs            |
  • | active_watchers     |
  • | address             |
  • | aliases             |
  • | carrier_name        |
  • | carrierfailureroute |
  • | carrierroute        |
  • | cpl                 |
  • | dbaliases           |
  • | dialog              |
  • | dialog_vars         |
  • | dialplan            |
  • | dispatcher          |
  • | domain              |
  • | domain_attrs        |
  • | domain_name         |
  • | domainpolicy        |
  • | globalblacklist     |
  • | grp                 |
  • | htable              |
  • | imc_members         |
  • | imc_rooms           |
  • | lcr_gw              |
  • | lcr_rule            |
  • | lcr_rule_target     |
  • | location            |
  • | location_attrs      |
  • | missed_calls        |
  • | mohqcalls           |
  • | mohqueues           |
  • | mtree               |
  • | mtrees              |
  • | pdt                 |
  • | pl_pipes            |
  • | presentity          |
  • | pua                 |
  • | purplemap           |
  • | re_grp              |
  • | rls_presentity      |
  • | rls_watchers        |
  • | rtpproxy            |
  • | sca_subscriptions   |
  • | silo                |
  • | sip_trace           |
  • | speed_dial          |
  • | subscriber          |
  • | trusted             |
  • | uacreg              |
  • | uid_credentials     |
  • | uid_domain          |
  • | uid_domain_attrs    |
  • | uid_global_attrs    |
  • | uid_uri             |
  • | uid_uri_attrs       |
  • | uid_user_attrs      |
  • | uri                 |
  • | userblacklist       |
  • | usr_preferences     |
  • | version             |
  • | watchers            |
  • | xcap                |
  • +———————+


The Kamailio configuration file for the control tools. Can set variables used in the kamctl and kamdbctl setup scripts. Per default all variables here are commented out, the control tools will use their internal default values. This file lets to edit  SIP domain, the database engine, username/password/ to connect to database, etc.

## your SIP domain
## chrooted directory
# $CHROOT_DIR="/path/to/chrooted/directory"
# by default none is loaded

# If you want to setup a database with kamdbctl, you must at least specify this parameter.

## database host
# DBHOST=localhost
## database host
# DBPORT=3306
## database name (for ORACLE this is TNS name)
# DBNAME=kamailio
# database path used by dbtext, db_berkeley or sqlite
# DB_PATH="/usr/local/etc/kamailio/dbtext"
database read/write user
# DBRWUSER="kamailio"
## password for database read/write user
# DBRWPW="kamailiorw"

database read only user

# DBROUSER="kamailioro"
## password for database read only user
# DBROPW="kamailioro"
## database access host (from where is kamctl used)

database super user (for ORACLE this is ‘scheme-creator’ user)

## password for database super user
## - important: this is insecure, targeting the use only for automatic testing
## - known to work for: mysql
# DBROOTPW="dbrootpw"
## database character set (used by MySQL when creating database)
## user name column
# USERCOL="username"
# SQL definitions

# If you change this definitions here, then you must change them
# in db/schema/entities.xml too.
# FOREVER="2030-05-28 21:32:15"
# DEFAULT_Q="1.0"
# Program to calculate a message-digest fingerprint
# MD5="md5sum"
# awk tool
# AWK="awk"
# gdb tool
# GDB="gdb"

# If you use a system with a grep and egrep that is not 100% gnu grep compatible,
# e.g. solaris, install the gnu grep (ggrep) and specify this below.

grep tool
# GREP="grep"
# egrep tool
# EGREP="egrep"
# sed tool
# SED="sed"
# tail tool
# LAST_LINE="tail -n 1"
# expr tool
# EXPR="expr"

Describe what additional tables to install. Valid values for the variables below are yes/no/ask. With ask (default) it will interactively ask the user for an answer, while yes/no allow for automated, unassisted installs.

#If to install tables for the modules in the EXTRA_MODULES variable.

# If to install presence related tables.
# If to install uid modules related tables.

 Define what module tables should be installed.

If you use the postgres database and want to change the installed tables, then you must also adjust the STANDARD_TABLES or EXTRA_TABLES variable accordingly in the kamdbctl.base script.

standard modules

standard acc lcr domain group permissions registrar usrloc msilo
alias_db uri_db speeddial avpops auth_db pdt dialog dispatcher

extra modules

imc cpl siptrace domainpolicy carrierroute userblacklist htable purple sca"
 type of aliases used: DB - database aliases; UL - usrloc aliases
- default: none , ALIASES_TYPE="DB"
control engine: RPCFIFO
 - default RPCFIFO

## path to FIFO file for engine RPCFIFO
# RPCFIFOPATH="/var/run/kamailio/kamailio_rpc_fifo"

## check ACL names; default on (1); off (0)

## ACL names - if VERIFY_ACL is set, only the ACL names from below list are accepted
# ACL_GROUPS="local ld int voicemail free-pstn"

## check if user exists (used by some commands such as acl);
## - default on (1); off (0)


## verbose - debug purposes - default '0'

## do (1) or don't (0) store plaintext passwords
## in the subscriber table - default '1'


Kamailio START Options

PID file path – default is: /var/run/kamailio/

# PID_FILE=/var/run/kamailio/

Extra start options – default is: not set

# example: start Kamailio with 64MB share memory: STARTOPTIONS="-m 64"


config files are used to customize and deploy SIP services since each and every SIP packet is route based on policies specified in conf file ( routing blocks ). Location when installed from source – /usr/local/etc/kamailio/kamailio.cfg , when installed from package – /etc/kamailio/kamailio.cfg

The features in config file :-

  • User authentication

Kamailio doesn’t have user authentication by default , so to enable it one must

#!define WITH_MYSQL
#!define WITH_AUTH

kamdbctl tool is to be used for creating and managing the database.

kamdbctl create

Kamctl is used for adding subscriber information and password.

kamctl add altanai1 123
mysql: [Warning] Using a password on the command line interface can be insecure.
MySQL password for user 'kamailio@localhost': 
mysql: [Warning] Using a password on the command line interface can be insecure.
new user 'altanai1' added

More details in Tools section below .

  • IP authorization
  • accounting
  • registrar and location servicesTo have persisant location enabled so that records are not lost once kamailio are restarted , we need to save it to database and reload when restarting
  • attacks detection and blocking (anti-flood protection)
  • NAT traversal

requires RTP proxy for RTP relay . NAT traversal support can be set by

#!define WITH_NAT
  • short dialing on server
  • multiple identities (aliases) for subscribers
  • multi-domain support
  • routing to a PSTN gateway
  • routing to a voicemail server
  • TLS encryption
  • instant messaging (pager mode with MESSAGE requests)
  • presence services

Kamailio (OpenSER) SIP Server v4.3- default configuration script

Several features can be enabled using ‘#!define WITH_FEATURE’ directives:

To run in debug mode: define WITH_DEBUG

To enable mysql: define WITH_MYSQL

To enable authentication execute: enable mysql and  define WITH_AUTH

To enable IP authentication execute: enable mysql ,  enable authentication ,  define WITH_IPAUTH and  add IP addresses with group id ‘1’ to ‘address’ table

To enable persistent user location execute:

enable mysql


To enable presence server execute:

enable mysql


To enable nat traversal execute:

define WITH_NAT

Install RTPProxy:

start RTPProxy:

rtpproxy -l your_public_ip -s udp:localhost:7722

option for NAT SIP OPTIONS keepalives: WITH_NATSIPPING

To enable PSTN gateway routing execute:

define WITH_PSTN

set the value of pstn.gw_ip

check route[PSTN] for regexp routing condition

To enable database aliases lookup execute:

enable mysql


To enable speed dial lookup execute:

enable mysql


To enable multi-domain support execute:

enable mysql


To enable TLS support execute:

adjust CFGDIR/tls.cfg as needed

define WITH_TLS

To enable XMLRPC support execute:


adjust route[XMLRPC] for access policy

To enable anti-flood detection execute:

adjust pike and htable=>ipban settings as needed (default is block if more than 16 requests in 2 seconds and ban for 300 seconds)


To block 3XX redirect replies execute:


To enable VoiceMail routing execute:


set the value of voicemail.srv_ip

adjust the value of voicemail.srv_port

To enhance accounting execute:

enable mysql


add following columns to database


define WITH_AUTH





ALTER TABLE acc ADD COLUMN src_ip varchar(64) NOT NULL default '';





ALTER TABLE missed_calls ADD COLUMN src_domain VARCHAR(128) NOT NULL DEFAULT '';

ALTER TABLE missed_calls ADD COLUMN src_ip varchar(64) NOT NULL default '';



ALTER TABLE missed_calls ADD COLUMN dst_domain VARCHAR(128) NOT NULL DEFAULT '';


Include Local Config If Exists

import_file “kamailio-local.cfg”

Value defines – IDs used later in config #!ifdef WITH_MYSQL # – database URL – used to connect to database server by modules such # as: auth_db, acc, usrloc, a.s.o.

 #!ifndef DBURL 
 #!define DBURL "mysql://kamailio:kamailiorw@localhost/kamailio" 
  #!define DBURL "mysql://kamailio:kamailiorw@localhost/kamailio" 
# !endif

 #!ifdef WITH_MULTIDOMAIN# - the value for 'use_domain' paramete
 #!define MULTIDOMAIN 1
 #!define MULTIDOMAIN 0

 # FLT_ - per transaction (message) flags 
 # FLB_ - per branch flags
 #!define FLT_ACC 1
 #!define FLT_ACCMISSED 2
 #!define FLT_ACCFAILED 3
 #!define FLT_NATS 5
 #!define FLB_NATB 6

 !substdef "!MY_IP_ADDR!!g"
 #!substdef "!MY_DOMAIN!!g" 
 #!substdef "!MY_WS_PORT!8080!g"
 #!substdef "!MY_WSS_PORT!4443!g"
 #!substdef "!MY_WS_ADDR!tcp:MY_IP_ADDR:MY_WS_PORT!g"
 #!substdef "!MY_WSS_ADDR!tls:MY_IP_ADDR:MY_WSS_PORT!g"</pre>
 #!ifdef WITH_DEBUG


disable TCP (default on)
enable_sctp = 0
// disable the auto discovery of local aliases based on reverse DNS on IPs (default on)

add local domain aliases

// port to listen to can be specified more than once if needed to listen on many ports
#!ifdef WITH_TLS

life time of TCP connection when there is no traffic – a bit higher than registration expires to cope with UA behind NAT

#!ifdef WITH_PSTN
# PSTN GW Routing
# - pstn.gw_ip: valid IP or hostname as string value, example:
# pstn.gw_ip = "" desc "My PSTN GW Address"
# - by default is empty to avoid misrouting
pstn.gw_ip = "" desc "PSTN GW Address"
pstn.gw_port = "" desc "PSTN GW Port"

# VoiceMail Routing on offline, busy or no answer
# - by default Voicemail server IP is empty to avoid misrouting
voicemail.srv_ip = "" desc "VoiceMail IP Address"
voicemail.srv_port = "5060" desc "VoiceMail Port"

Modules Section

set paths to location of modules (to sources or installation folders)


#!ifdef WITH_MYSQL
loadmodule ""

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

#!ifdef WITH_AUTH
loadmodule ""
loadmodule ""
loadmodule ""

loadmodule ""

loadmodule ""

loadmodule ""

loadmodule ""
loadmodule ""

#!ifdef WITH_NAT
loadmodule ""
loadmodule ""

#!ifdef WITH_TLS
loadmodule ""

loadmodule ""
loadmodule ""

loadmodule ""

#!ifdef WITH_DEBUG
loadmodule ""

loadmodule ""
#loadmodule ""
loadmodule ""

----- mi_fifo params -----
#modparam("mi_fifo", "fifo_name", "/var/run/kamailio/kamailio_fifo")</pre>

----- ctl params -----
#modparam("ctl", "binrpc", "unix:/var/run/kamailio/kamailio_ctl")</pre>

----- tm params -----
# auto-discard branches from previous serial forking leg
modparam("tm", "failure_reply_mode", 3)
# default retransmission timeout: 30sec
modparam("tm", "fr_timer", 30000)
# default invite retransmission timeout after 1xx: 120sec
modparam("tm", "fr_inv_timer", 120000)</pre>

----- rr params -----
# set next param to 1 to add value to ;lr param (helps with some UAs)
modparam("rr", "enable_full_lr", 0)
# do not append from tag to the RR (no need for this script)
modparam("rr", "append_fromtag", 0)

registrar params

modparam("registrar", "method_filtering", 1)
/* uncomment the next line to disable parallel forking via location */
# modparam("registrar", "append_branches", 0)
/* uncomment the next line not to allow more than 10 contacts per AOR */
#modparam("registrar", "max_contacts", 10)
# max value for expires of registrations
modparam("registrar", "max_expires", 3600)
# set it to 1 to enable GRUU
modparam("registrar", "gruu_enabled", 0)</pre>

enhanced DB accounting

#!ifdef WITH_ACCDB

modparam("acc", "db_flag", FLT_ACC)

modparam("acc", "db_missed_flag", FLT_ACCMISSED)

modparam("acc", "db_url", DBURL)

modparam("acc", "db_extra",




usrloc params – enable DB persistency for location entries


modparam("usrloc", "db_url", DBURL)

modparam("usrloc", "db_mode", 2)

modparam("usrloc", "use_domain", MULTIDOMAIN)


auth_db params

#!ifdef WITH_AUTH

modparam("auth_db", "db_url", DBURL)

modparam("auth_db", "calculate_ha1", yes)

modparam("auth_db", "password_column", "password")

modparam("auth_db", "load_credentials", "")

modparam("auth_db", "use_domain", MULTIDOMAIN)

permissions params


modparam("permissions", "db_url", DBURL)

modparam("permissions", "db_mode", 1)



alias_db params


modparam("alias_db", "db_url", DBURL)

modparam("alias_db", "use_domain", MULTIDOMAIN)


speeddial params


modparam("speeddial", "db_url", DBURL)

modparam("speeddial", "use_domain", MULTIDOMAIN)


domain params


modparam("domain", "db_url", DBURL)

modparam("domain", "register_myself", 1)



presence params

modparam("presence", "db_url", DBURL)

presence_xml params

modparam("presence_xml", "db_url", DBURL)
modparam("presence_xml", "force_active", 1)


rtpproxy params
modparam("rtpproxy", "rtpproxy_sock", "udp:")

nathelper params

modparam("nathelper", "natping_interval", 30)
modparam("nathelper", "ping_nated_only", 1)
modparam("nathelper", "sipping_bflag", FLB_NATSIPPING)
modparam("nathelper", "sipping_from", "")

params needed for NAT traversal in other modules

modparam("nathelper|registrar", "received_avp", "$avp(RECEIVED)")
modparam("usrloc", "nat_bflag", FLB_NATB)

tls params

#!ifdef WITH_TLS

modparam("tls", "config", "/etc/kamailio/tls.cfg")


pike params


modparam("pike", "sampling_time_unit", 2)
modparam("pike", "reqs_density_per_unit", 16)
modparam("pike", "remove_latency", 4)

htable params

ip ban htable with autoexpire after 5 minutes

modparam("htable", "htable", "ipban=&gt;size=8;autoexpire=300;")


xmlrpc params

modparam("xmlrpc", "route", "XMLRPC");
modparam("xmlrpc", "url_match", "^/RPC")

debugger params

#!ifdef WITH_DEBUG

modparam("debugger", "cfgtrace", 1)
modparam("debugger", "log_level_name", "exec")


nathelper params


modparam("nathelper|registrar", "received_avp", "$avp(RECEIVED)")


Note: leaving NAT pings turned off here as nathelper is <em>only</em> being used for&nbsp;WebSocket connections. NAT pings are not needed as WebSockets have&nbsp;their own keep-alives.

Routing Logic

Main SIP request routing logic processing of any incoming SIP request starts with this route

request_route { 
# per request initial checks 
    if (nat_uac_test(64)) {     
        if (is_method("REGISTER")) {          
        } else {         
            if (!add_contact_alias()) {  
                   xlog("L_ERR", "Error aliasing contact \n");             
                   sl_send_reply("400", "Bad Request");                    exit;         }     } } 
# NAT detection 
# CANCEL processing 
if (is_method("CANCEL")) {     
    if (t_check_trans()) {         

# handle requests within SIP dialogs 
### only initial requests (no To tag) 
# handle retransmissions 
if(t_precheck_trans()) { 

# authentication 

# record routing for dialog forming requests (in case they are routed) - remove preloaded route headers 

if (is_method("INVITE|SUBSCRIBE")) 

# account only INVITEs 
if (is_method("INVITE")) {     
    setflag(FLT_ACC); # do accounting 
# dispatch requests to foreign domains 

### requests for my local domains 
# handle presence related requests 

# handle registrations 
if ($rU==$null) {     
# request with no Username in RURI     sl_send_reply("484","Address Incomplete");     
# dispatch destinations to PSTN route(PSTN); 

# user location service 
route(LOCATION); }

Wrapper for relaying requests

enable additional event routes for forwarded requests – serial forking, RTP relaying handling, a.s.o.

route[RELAY] {
if (is_method(“INVITE|SUBSCRIBE|UPDATE”)) {
if (is_method(“INVITE”)) {
if (!t_relay()) {

Per SIP request initial checks

route[REQINIT] { #!ifdef WITH_ANTIFLOOD # flood detection from same IP and traffic ban for a while # be sure you exclude checking trusted peers, such as pstn gateways – local host excluded (e.g., loop to self) if(src_ip!=myself) { if($sht(ipban=>$si)!=$null) { # ip is already blocked xdbg(“request from blocked IP – $rm from $fu (IP:$si:$sp)\n”); exit; } if (!pike_check_req()) { xlog(“L_ALERT”,”ALERT: pike blocking $rm from $fu (IP:$si:$sp)\n”); $sht(ipban=>$si) = 1; exit; } } if($ua =~ “friendly-scanner”) { sl_send_reply(“200”, “OK”); exit; } #!endif if (!mf_process_maxfwd_header(“10”)) { sl_send_reply(“483″,”Too Many Hops”); exit; } if(is_method(“OPTIONS”) && uri==myself && $rU==$null) { sl_send_reply(“200″,”Keepalive”); exit; } if(!sanity_check(“1511”, “7”)) { xlog(“Malformed SIP message from $si:$sp\n”); exit; } }

Handle requests within SIP dialogs

route[WITHINDLG] {
    if (!has_totag()) return;

    if (has_totag()) {

#sequential request withing a dialog should take the path determined by record-routing

        if (loose_route()) {
            #!ifdef WITH_WEBSOCKETS
            if ($du == "") {
                if (!handle_ruri_alias()) {
                    xlog("L_ERR", "Bad alias <$ru>\n");
                    sl_send_reply("400", "Bad Request");

#sequential request within a dialog should  take the path determined by record-routing
    if (loose_route()) {
        if (is_method("BYE")) {
            setflag(FLT_ACC); # do accounting ...
            setflag(FLT_ACCFAILED); # ... even if the transaction fails
        else if ( is_method("ACK") ) {
            # ACK is forwarded statelessy
        else if ( is_method("NOTIFY") ) {
            # Add Record-Route for in-dialog NOTIFY as per RFC 6665.

    if (is_method("SUBSCRIBE") && uri == myself) {
    # in-dialog subscribe requests

if ( is_method("ACK") ) {
    if ( t_check_trans() ) {
        # no loose-route, but stateful ACK;
        # must be an ACK after a 487
        # or e.g. 404 from upstream server
    } else {
        # ACK without matching transaction ... ignore and discard

sl_send_reply("404","Not here");

Handle SIP registrations

User location service

route[LOCATION] {

# search for short dialing - 2-digit extension

# search in DB-based aliases

$avp(oexten) = $rU;
if (!lookup("location")) {
    $var(rc) = $rc;
    switch ($var(rc)) {
        case -1:
        case -3:
           send_reply("404", "Not Found");
        case -2:
           send_reply("405", "Method Not Allowed");

# when routing via usrloc, log the missed calls also
if (is_method("INVITE")) {


Presence server processing

route[PRESENCE] {


if(is_method("SUBSCRIBE") && $hdr(Event)=="message-summary") {
    # returns here if no voicemail server is configured
    sl_send_reply("404", "No voicemail service");

if (!t_newtran()) {

if(is_method("PUBLISH")) {
} else if(is_method("SUBSCRIBE")) {

# if presence enabled, this part will not be executed
if (is_method("PUBLISH") || $rU==$null) {
    sl_send_reply("404", "Not here");

IP authorization and user authentication

route[AUTH] {
#!ifdef WITH_AUTH

if((!is_method("REGISTER")) && allow_source_address()) {
    # source IP allowed

if (is_method("REGISTER") || from_uri==myself)
    # authenticate requests
    if (!auth_check("$fd", "subscriber", "1")) {
        auth_challenge("$fd", "0");

    # user authenticated - remove auth header

# if caller is not local subscriber, then check if it calls
# a local destination, otherwise deny, not an open relay here
    if (from_uri!=myself && uri!=myself) {
        sl_send_reply("403","Not relaying");


Caller NAT detection

route[NATDETECT] {
#!ifdef WITH_NAT

if (nat_uac_test("19")) {
    if (is_method("REGISTER")) {
    } else {

RTPProxy control and signaling updates for NAT traversal

route[NATMANAGE] {

#!ifdef WITH_NAT
if (is_request()) {
    if(has_totag()) {
        if(check_route_param("nat=yes")) {
if (!(isflagset(FLT_NATS) || isbflagset(FLB_NATB)))


if (is_request()) {
    if (!has_totag()) {
        if(t_is_branch_route()) {

if (is_reply()) {
    if(isbflagset(FLB_NATB)) {


URI update for dialog requests

route[DLGURI] {
#!ifdef WITH_NAT
if(!isdsturiset()) {

Routing to foreign domains

route[SIPOUT] {
if (uri==myself) return;

append_hf("P-hint: outbound\r\n");

PSTN GW routing

route[PSTN] {
#!ifdef WITH_PSTN
# check if PSTN GW IP is defined
if (strempty($sel(cfg_get.pstn.gw_ip))) {
xlog("SCRIPT: PSTN routing enabled but pstn.gw_ip not defined\n");

# route to PSTN dialed numbers starting with '+' or '00'
# (international format)
# - update the condition to match your dialing rules for PSTN routing

# only local users allowed to call
if(from_uri!=myself) {
sl_send_reply("403", "Not Allowed");

if (strempty($sel(cfg_get.pstn.gw_port))) {
$ru = "sip:" + $rU + "@" + $sel(cfg_get.pstn.gw_ip);
} else {
$ru = "sip:" + $rU + "@" + $sel(cfg_get.pstn.gw_ip) + ":"
+ $sel(cfg_get.pstn.gw_port);



XMLRPC routing

route[XMLRPC] {
# allow XMLRPC from localhost
if ((method=="POST" || method=="GET")
&& (src_ip== {
# close connection only for xmlrpclib user agents (there is a bug in
# xmlrpclib: it waits for EOF before interpreting the response).
if ($hdr(User-Agent) =~ "xmlrpclib")
send_reply("403", "Forbidden");

Routing to voicemail server


# check if VoiceMail server IP is defined
if (strempty($sel(cfg_get.voicemail.srv_ip))) {
xlog("SCRIPT: VoiceMail routing enabled but IP not defined\n");
if(is_method("INVITE")) {
$ru = "sip:" + $avp(oexten) + "@" + $sel(cfg_get.voicemail.srv_ip)
+ ":" + $sel(cfg_get.voicemail.srv_port);
} else {
$ru = "sip:" + $rU + "@" + $sel(cfg_get.voicemail.srv_ip)
+ ":" + $sel(cfg_get.voicemail.srv_port);


Manage outgoing branches

branch_route[MANAGE_BRANCH] {
xdbg("new branch [$T_branch_idx] to $ru\n");

Manage incoming replies

onreply_route[MANAGE_REPLY] {
xdbg("incoming reply\n");

Manage failure routing cases

failure_route[MANAGE_FAILURE] {

if (t_is_canceled()) {

# block call redirect based on 3xx replies.
if (t_check_status("3[0-9][0-9]")) {
    t_reply("404","Not found");

# serial forking
# - route to voicemail on busy or no answer (timeout)
if (t_check_status("486|408")) {
    $du = $null;

Supports pseudo-variables to access and manage parts of the SIP messages and attributes specific to users and server.  Transformations to modify existing pseudo-variables, accessing only the wanted parts of the information. 

Already has over 1000 parameters, variables and functions exported to config file. Supports runtime update framework – to avoid restarting the SIP server when needing to change the config parameters



Manage kamailio from command line, providing lots of operations, such as adding/removing/updating SIP users, controlling the ACL for users, managing the records for LCR or load balancing, viewing registered users and internal statistics, etc.

When needed to interact with Kamailio, it does it via FIFO file created by mi_fifo module.


Helps to configure and database needed by kamailio . First we need to select a database engine in the kamctlrc file by DBENGINE parameter .


The tool can be used to create and manage the database structure needed by Kamailio, therefore it should be immediately after Kamailio installation, in case you plan to run Kamailio with a database backend.


send RPC commands to Kamailio from command line , requires  ctl module


web management interface for Kamailio, written in PHP , AJAX , web 2.0 using MVC architecture

  • system and database administration tools for Kamailio SIP Server
  • subscriber, database aliases and speed dial management
  • location table view
  • dispatcher (load balancer), prefix-domain translation and least cost routing (lcr) management
  • access control lists (user groups) and permissions management
  • accounting records and missed calls vies
  • manage call data records (generated from acc records)
  • hash table, dial plan table and user preferences table management
  • offline message storage, presence service and sip trace views
  • communication with Kamailio SIP Server via XMLRPC ,  JSONRPC
  • communication with FreeSWITCH via event socket
  • create and display charts from statistic data stored by Kamailio
  • user location statistics charts
  • SIP traffic load charts
  • memory usage charts
  • accounting records charts and summary table
  • SQL-based CDR generation and rating billing engine


cmd line client written Python



SIP registration processing logic can be defined here .

Path support – off , lazy , strict

Things covered in this article

  • Internal architecture
  • Configuration language
  • least cost routing
  • load balancing
  • traffic dispatching
  • DID routing
  • prefix based routing
  • SIP trunks and peering
  • traffic shaping
  • topology hiding
  • flood detection
  • scanning attacks prevention
  • anti-fraud policies

SQL and noSQL connectors

enum and DNS based routing

authentication and authorization

secure communication (TLS)

registration and location services

accounting and call data records

call control – redirect, forward, baring

redundancy and scalability

high availability and failover

websockets and webrtc

References :

Henning Westerholt – Kamailio project-1&1 Internet AG ( 2009 )

Service Creation Environment (SCE ) for SIP Applications

I hoped of making a SIP application Development environment a year back and worked towards it earnestly . Sadly I wasn’t able to complete the job yet I have decided to share a few things about it here .

Aim :

Develop  a SCE ( Service Creation Environment ) to addresses all aspects of lifecycle of a Service, right from creation/development, orchestration, execution/delivery, Assurance and Migration/Upgrade of services.

Similar market products :

  • Open/cloud Rhino
  • Mobicents and Telestax

Limitations of open source/other market products:

  • Free versions of the Service Creation Environments do not offer High Availability.
  • High Cost of Deployment grade versions.

Solution Description

I propose a in-house Java based Service Creation Environment “SLC SCE”. The SLC SCE will enable creation of JAINSLEE based SIP  services. It can be used to develop and deploy carrier-grade applications that use SS7 and IMS based protocols such as INAP, CAP, Diameter and SIP as well as IT / Web protocols such as HTTP and XML.


  • Service Agility
  • Significantly Lower price points
  • Open Standards eliminate Legacy SCP Lock-in


  • Java-based service creation environment (SCE) – 1.5 Months
  • Graphical User Interface (GUI) and schematic representations to help in the design, maintenance and support of applications – 1.5 months
  • SIP Resource Adapter – 1 month


Service Creation Environment (SCE) for SIP Applications

Service Creation Environment (SCE) for SIP Applications

In essence it encompasses the idea of developing the following

  1. SIP stack
  2. Javascript API’s
  3. Java Libraries for calling SIP stack
  4. Eclipse plugin to work with the SIP application development process
  5. Visual Interface to view the logic of application and possible errors / flaws
  6. SDKs (  Service Development Kit) , which are development Environment themselves

Extra Effort required to put in to make the venture successful

  1. Demo applications for basic SIP logic like Call screening , call rerouting .
  2. tutorial to create , deploy and run application from scratch . Aimed at all sections ie web developer , telecom engineer , full stack developer etc .
  3. Some opensource implementation on public repositories like Github , Google code , SourceForge
  4. Perform active problem solving on Stackoverflow , CodeRanch , Google groups and  other forums .



This post describes the installation , setup and configuration of Office SIP server to provide a registrar to our SIP based WebRTC application .

1. Get office SIP from this website


2. Downloaded office sip executable on windows looks like this . double click on it to start installation .


3.Installation screen appears as follows


4. Terms and conditions


5. Destination folder for installation


6. Installing


7. Validating install


8. Installation completed


9. Launch icon on dekstop


10 . Office SIP web login screen


11. create account ( also known as realm or domain ) for users to register in their SIP and webrtc sip agents


12. Fill in account details for every account added to officeSIP


13. add users that will be registering to officeSIP server


14.Office SIP settings file can be modified for changing server parameters like ip and port


15 . Office SIP can now be used by sip agents like softphones , webRTC pages , etc to register with OfficeSIP server

BEA Weblogic SIP server

Bea server is a old SIP servlet container ie application server which is used to embed control logic in a program . It is supported on jdk1.5 hence the system’s environment variables must match . Otherwise in later stages deploying applications throw class version error .

1. Install Bea Weblogic

2. Follow the Installation steps

Make domain

3. Goto the installation directory . Usually C:/bea/user_projects/mydomain/ .

click on startweblogic.cmd in windows. In case the system is linux run script

4. Open Web console on url : Enter username password

default username password weblogic , weblogic .

It can also be customized for example my username and password are altanai , tcs@1234

5.  Make Converged SIP Servlet Application in any editor such as notepad , edit+ etc .

The project structure looks like

Call screening

The SIP servlet are put side directory structure of src

For example : sample application for Call screening

package com.altanai.voice;
import javax.servlet.*;
import javax.servlet.sip.*;
import javax.servlet.sip.Proxy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.*;
public class CallScreening extends SipServlet
private static SipFactory factory;
private static SipApplicationSession sas;
private static Proxy proxy;
public void init(ServletConfig config) throws ServletException
System.out.println(“Call screening SIP servlet initiated”);
protected void doInvite(SipServletRequest req) throws java.lang.IllegalArgumentException,java.lang.IllegalStateException,javax.servlet.ServletException,
System.out.println(“Received an Invite Request”);
System.out.println(“User is blocked”);
System.out.println(“User is not blocked”);

6. Build it with ant . For this go inside the application folder and run ant. Output will either be “failed to build “ or “build successfully” .

The ant  command generates the war file from SIP servlet Web application .

7. Incase of successful build . Add the application to Weblogic web console install section and activate it .

I will demonstrate this process in step by step manner . First  click on “ Lock and Edit “ Button on the left panel . Then goto Install button in the centre area and browser to the location of application war or sar we have build through ant ,

8. We can delete an application in exactly the same way . click on “ Lock and Edit “ Button on the left panel . Then goto the delete button after selecting the radio button alongside the application we want to delete.

8. For enhanced application building we can also refer to sample provided along with bea weblogic . file:///C:/bea/sipserver30/samples/sipserver/examples/src/index.html

SIP Presence

We have already learned about Sip user agent and sip network server. SIP clients initiates a call and SIP server routes the call . Registrar is responsible for name resolution and user location. Sip proxy receives calls and send it to its destination or next hop.

Presence is user’s reachability and willingness to communicate its current status information . User subscribe to an event and receive notification . The components in presence are :

Presence user agentpresence components
Presence agent
Presence server

Image source  :

Sip was initially introduced as a signaling protocol but there were Lack of method to emulate constant communication and update status between entity
Three more method was introduced namely – Publish , Subscribe and Notify

Subscribe request should be send by watchers to presence server
Presence agent should authenticate and send acknowledgement
State changes should be notified to subscriber
Agents should be able to allow or terminate subscription

presence flow

Image source

Traces of various SIP requetss and response in presence are are follows :

subscribe request

      Via: SIP/2.0/UDP;branch=z9hG4bKnashds7
      To: <>
      From: <>;tag=12341234
      CSeq: 1 SUBSCRIBE
      Max-Forwards: 70
      Expires: 3600
      Event: presence
      Content-Length: 0

200 OK to subscribe request

SIP/2.0 200 OK
      Via: SIP/2.0/UDP;branch=z9hG4bKnashds7
      To: <>;tag=abcd1234
      From: <>;tag=12341234
      CSeq: 1 SUBSCRIBE
      Expires: 3600
      Content-Length: 0

Notify Request

      Via: SIP/2.0/UDP;branch=z9hG4bK8sdf2
      To: <>;tag=12341234
      From: <>;tag=abcd1234
      CSeq: 1 NOTIFY
      Max-Forwards: 70
      Event: presence
      Subscription-State: active; expires=3599
      Content-Type: application/pidf+xml
      Content-Length: …

200 OK success response to notify

SIP/2.0 200 OK
      Via: SIP/2.0/UDP;branch=z9hG4bK8sdf2
      To: <>;tag=12341234
      From: <>;tag=abcd1234
      CSeq: 1 NOTIFY


Via: SIP/2.0/UDP;branch=z9hG4bK652hsge
To: <>
From: <>;tag=1234wxyz
Max-Forwards: 70
Expires: 3600
Event: presence
Content-Type: application/pidf+xml
Content-Length: …

200 OK success response to PUBLISH

SIP/2.0 200 OK
Via: SIP/2.0/UDP;branch=z9hG4bK652hsge
To: <>;tag=1a2b3c4d
From: <>;tag=1234wxyz
SIP-ETag: dx200xyz
Expires: 1800

A call flow depicting presence in action is as given below :

presence subscribe notify

Image source

security considerations for Presence service include:

  • Access control.
  • Notifier privacy mechanism.
  • Denial of service attacks.
  • Replay Attacks.
  • Man-in-the-middle attacks.
  • Confidentiality.

some solutions for security implementation are

  • Sip registration
    Digest Authentication

References :

Rfc 3856
Rfc 3265
Rfc 2778
Rfc 3261
Rfc 3903

Summary :

Presence is a way to have sustained stateful communication. The SIP User agents can use presence service to know about others user’s online status . Presnece deployment must confirm to security standards .

Interoperability between WebRTC , SIP phones and others

WebRTC SIP clients

What is the role of SIP server ?

SIP Server convert the SIP transport from WebSocket protocol to UDP, TCP or TLS which are supported by all legacy networks. It also facilitates the use of rich serves such as phonebook synchronisation , file sharing , oauth in client .

How does WebRTC Solution traverse through FireWalls ?

NAT traversal across Firewalls is achieved via TURN/STUN through ICE candidates gathering .Current ice_servers are : and

What audio and video codecs are supported by WebRTC client side alone ?

Without the role of Media Server WebRTC solution supports Opus , PCMA , PCMU for audio and VP8 for video call.

RTCBreaker if enabled provides a third party B2BUA agent that performs certain level of codec conversion to H.264, H.263, Theora or MP4V-ES for non WebRTC supported agents.

What video resolution is supported by WebRTC solution ?

The browser will try to find the best video size between max and min based on the camera capabilities.

Options are : sqcif | qcif | qvga | cif | hvga | vga | 4cif | svga | 480p | 720p | 16cif | 1080p

We can also predefine the video size such as minWidth, minHeight, maxWidth, maxHeight.

What bandwidth is required to run WebRTC solution ?

We can set maximum audio and video bandwidth to use or use the browser’s ability to set it hy default at runtime . This will change the outgoing SDP to include a “b:AS=” attribute. Browser negotiates the right value using RTCP-REMB and congestion control.

SIPML5 client by dubango


Telestax WebRTC client


SIPJS with flash network support


JSSIP – MIT license 2014-02-09_1444

SIP phones in Ubuntu ( Linux system)

SFL phone

linux sfl 2 linux sfl 1

Yate SIP phone

linux yate 2 linux yate 1


ubuntulinphon4 linuxlinphone2

Windows Operating system SIP software

Xlite is well known SIP softphone for windows dessktop

xlite 1

Xlite new version

windows_xlite_7 windows_xlite_6_001 windows_xlite_6 windows_xlite_3

Kapanga SIP softphone . It is also runnable on Linux desktop through windows compatibility softwares like wine

windows_kapanga_3 windows_kapanga_2

FreeSwitch Communicator , comes along with the Freeswitch Media Server .

windows_freeswitchcomm__2 windows_freeswitch_comm_3

Boghe SIP RCS client

windows_boghe_5 windows_boghe_4 windows_boghe_2 windows_boghe_1

Jitsi SIP phone

jitsi 2 jitsi 1

MAC SIP software

idoubs desktop SIP RCS client for Mac

Screen shot 2014-06-13 at 4.03.27 PM

iOS SIP phone applications


IMG-20140703-WA0003  IMG-20140703-WA0006 IMG-20140703-WA0007  IMG-20140710-WA0001 IMG-20140710-WA0002

Android SIP applications

Sipdroid , opensource

Screenshot_2014-07-01-19-36-47 Screenshot_2014-07-01-19-37-00 Screenshot_2014-07-01-19-37-44 Screenshot_2014-07-01-19-37-54 Screenshot_2014-07-01-19-38-46

SIP Messages Explanied

1. Request Message

Request Message


REGISTER A Client use this message to register an address with a SIP server
INVITE A User or Service use this message to let another user/service participate in a session. The body of this message would include a description of the session to which the callee is being invited.
ACK This is used only for INVITE indicating that the client has received a final response to an INVITE request
CANCEL This is used to cancel a pending request
BYE A User Agent Client use this message to terminate the call
OPTIONS This is used to query a server about its capabilities

2. Response Message




1xx Provisional The request has been received and processing is continuing
2xx Success An ACK, to indicate that the action was successfully received, understood, and accepted.
3xx Redirection Further action is required to process this request
4xx Client Error The request contains bad syntax and cannot be fulfilled at this server
5xx Server Error The server failed to fulfill an apparently valid request
6xx Global Failure The request cannot be fulfilled at any server

, based on RFC 3261

SIP headers :

Display names are described in RFC 2822
From also contains a display name and a SIP URI that indicate the originator of the request.  The From also contains a tag parameter which is used for identification purposes.
Call-ID contains a globally unique identifier for this call. Mandatory
CSeq or Command Sequence contains an integer and a method name. The CSeq number is incremented for each new request within a dialog and is a traditional sequence number.
Contact contains a SIP URI that represents a direct route to the originator usually composed of a username at a fully qualified domain name (FQDN). While an FQDN is preferred, many end systems do not have registered domain names, so IP addresses are permitted.  The Contact header field tells other elements where to send future requests.
Max-Forwards serves to limit the number of hops a request can make on the way to its destination. It consists of an integer that is decremented by one at each hop.
Content-Type contains a description of the message body.
Content-Length contains an octet (byte) count of the message body.
sip headers 1 sip headers 2 sip headers 3

Mandatory SIP headers

  • INVITE sip:altanai@domain.comSIP/2.0
  • Via: SIP/2.0/UDP
  • From: Bob <>
  • To: Altanai <>
  • Call-ID:
  • CSeq: 1 INVITE

session description in SDP


  • v=  (protocol version)  Mandatory
  • o=  (owner/creator and session identifier).   Mandatory
  • s=  (session name)   Mandatory
  • t=  (time the session is active)   Mandatory
  • i=* (session information)
  • u=* (URI of description)
  • e=* (email address)
  • p=* (phone number)
  • c=* (connection information – not required if included in all media)
  • b=* (bandwidth information)
  • z=* (time zone adjustments)
  • k=* (encryption key)
  • a=* (zero or more session attribute lines)
  • r=* (zero or more repeat times)Media description
  • m=  (media name and transport address)  Mandatory
  • i=* (media title)


INVITE sip:01150259917040@ SIP/2.0

Via: SIP/2.0/UDP;branch=z9hG4bK400fc6e6

From: "8069664170" <sip:8069664170@>;tag=as42e2ecf6

To: <sip:01150259917040@>

Contact: <sip:8069664170@>

Call-ID: 2485823e63b290b47c042f20764d990a@

CSeq: 102 INVITE

User-Agent: MatrixSwitch

Date: Thu, 22 Dec 2005 18:38:28 GMT


Content-Type: application/sdp

Content-Length: 268


o=root 14040 14040 IN IP4


c=IN IP4

t=0 0

m=audio 26784 RTP/AVP 0 8 18 101

a=rtpmap:0 PCMU/8000

a=rtpmap:8 PCMA/8000

a=rtpmap:18 G729/8000

a=rtpmap:101 telephone-event/8000

a=fmtp:101 0-16

a=fmtp:18 annexb=no - - - -

c=* (connection information - optional if included at session-level)

b=* (bandwidth information)

a=* (zero or more media attribute lines)

SIP Responses

sip resp

1xx—Provisional Responses
100 Trying
180 Ringing
181 Call is Being Forwarde
182 Queued
183 Session in Progress199 Early Dialog Terminated

2xx—Successful Responses
200 OK
202 Accepted
204 No Notification

3xx—Redirection Responses
300 Multiple Choices
301 Moved Permanently
302 Moved Temporarily
305 Use Proxy
380 Alternative Service

4xx—Client Failure Responses
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Conditional Request Failed
413 Request Entity Too Large
414 Request-URI Too Long
415 Unsupported Media Type
416 Unsupported URI Scheme
417 Unknown Resource-Priority
420 Bad Extension
421 Extension Required
422 Session Interval Too Small
423 Interval Too Brief
424 Bad Location Information
428 Use Identity Header
429 Provide Referrer Identity
430 Flow Failed
433 Anonymity Disallowed
436 Bad Identity-Info
437 Unsupported Certificate
438 Invalid Identity Header
439 First Hop Lacks Outbound Support
470 Consent Needed
480 Temporarily Unavailable
481 Call/Transaction Does Not Exist
482 Loop Detected.
483 Too Many Hops
484 Address Incomplete
485 Ambiguous
486 Busy Here
487 Request Terminated
488 Not Acceptable Here
489 Bad Event
491 Request Pending
493 Undecipherable
494 Security Agreement Required

5xx—Server Failure Responses
500 Server Internal Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Server Time-out
505 Version Not Supported
513 Message Too Large
580 Precondition Failure

6xx—Global Failure Responses
600 Busy Everywhere
603 Decline
604 Does Not Exist Anywhere
606 Not Acceptable

Mandatory Headers in SIP Response 
  • SIP/2.0 200 OK
  • Via: SIP/2.0/UDP
  • From: Bob<>
  • To: Altanai<>
  • Call-ID:
  • CSeq: 1 INVITE
Note : – 

Via, From, To, Call-ID 

, and  


are copied exactly from Request. 
You can read more about SIP based Architecture here : SIP based architecture

RCS ( Rich Communication Suite )

What is this fuss about RCS ? For the past few weeks I’ve been trying to find the answer to this one .

After much information gathering i made myself understand that  :-

The Rich Communication Services programme is a global initiative to deploy inter-operator services within an industry ecosystem.

Marketed by the GSMA under the brand name joyn,  RCS is an upgrade that marks the transition of messaging and voice capabilities from Circuit Switched technology to an all-IP world.

Wider and large scale IMS deployment, interoperability between different terminal vendor RCS clients and RCS service interworking between operators are the key aims of the RCS Initiative.

Whats special about RCS ?

  • Enhanced Phonebook: service capabilities and enhanced contacts information such as presence and service discovery.
  • Enhanced Messaging: enables a large variety of messaging options including chat, emoticons, location share and file sharing.
  • Enriched Calls: enables multimedia content sharing during a voice call, video call and video sharing (see what I see).

RCS releases

Five releases of the RCS specifications have been made to date. Each release expanded the scope of its predecessor.

lRelease 1 : Offered the first definitions for the enrichment of voice and chat with content sharing, driven from an RCS enhanced address book.
lRelease 2 : Added broadband access to RCS features: enhancing the messaging and enabling sharing of files.
lRelease 3: Focused on the broadband device as a primary device.
lRelease 4: Included support for LTE.
lRelease 5: The most recent release, global interoperability is a key aspect of these specifications.

As the team developed a web client for making and receiving SIP calls over websockets through a proxy SIP server , I felt its an  achievement big enough. To integrate it with RCS ( Rich Communication Suite ) stack appeared as a very complicated job .

I began by adding RCS specific standards modules one by one instead of importing the whole stack / library all together  .

So the modules for XCAP for buddylist  , MSRP for file transfer , geolocation  mapping , cloud sync of phonebook and message book have begun taking shape . In essence following features set are expected out of a RCS enabled Client  ( short outline )


  • · OAUTH integration with operator customer portal
  • · RCS HTTP Auto-Configuration 
  • · Manual IMS credentials, typically reserved for testing / troubleshooting RCS Services

RCS services:

  • · Service Discovery
    • OPTIONS and Presence supported
    • Address book polling
  • · 1-1 Chat
    • IMDN
    • Is-Composing
    • Store & forward / deferred message and notification delivery
    • Hotfixes compliant
  • · Group Chat
    • Hotfixes compliant
    • Is-Composing
    • IMDN
    • Geo-location Push
  • · File Transfer
    • MSRP based
    • HTTP based
    • Store & forward
    • Geo-location push via FT
    • vCard sharing
    • Thumbnail support
  • · Voice & video
    • Best effort voice
    • Transcode 
  • · Network Address Book Support
    • Synchronization to SyncML based network address book
    • Contact import from Google, Facebook etc.


At this stage i will also put in a bit more about RCS e


What is the difference between RCS-e and RCS?

RCS-enhanced (RCS-e) is the currently available version of RCS, developed to speed time to market. It offers enhanced features such as instant messaging, live video sharing, and file transfer across any device on any network operator.

RCS e Benefits :

Focus on advanced communication
– chat , file transfer , video sharing
Easy to Use
-zero touch from end user perspective
-minimal setup for subscribers
-Interoperability across devices , infrastructure components and service providers
Low barrier to entry / simplify networks
– Capability discovery using SIP OPTIONS
– Less impact on network elements and handset battery
– Lack of presence server reduces cost and time to market
– Allows implementation in lower range devices
– One common device specification

RCS-e Customer Value Proposition

 New IP Communication Services , Profile Sharing , Native Device Integration
rcs5 rcs6

RCS e Characteristics

Dynamic Capability Discovery
User Perspective
network detects when user attaches with RCs e device
detection triggers network provisioning and client configuration
authentication by network
SSO / GIBA in 3G coverage
SIP Digest in Wifi
Encryption for Wifi access
TLS for SIP and TCP media or IPsec
SRTP for UDP or IPsec
NAT traversal and Keep-alives

JAINSLEE – Developer and business benefits

JAIN SLEE is the Java open standard for a SLEE ( Service Logic Execution Environment ). It is a  Java programming language API for developing and deploying network services.


 Evolution of Open- Standard Platform (JAINSLEE)

There is a strong evolution being seen in CSP space. Now operators are looking forward to implement the open standard for intelligent networks. It reduces their dependency on proprietary platforms and on vendor’s road maps. Open –source platform gives operator flexibility to develop their own applications without being dependent on vendor. An open, standards based, service logic execution environment (SLEE) that integrates with current and future networks is the key to providing innovative and revenue generating services. Providing one (standards based) carrier grade execution environment that integrates SS7, SIP, OSA/Parlay, OSS/BSS and J2EE environments offers significant benefits to operator.

Business benefits of SIP JAINSLEE based platform

  1. Network Independence: The JAIN SLEE framework is independent of any particular network protocol, API or network topology. This is supported through the resource adaptor architecture
  2. Portable Services: Application components can be developed and then deployed on JAIN SLEE compliant platforms from different vendors without recompilation or source code modification.
  3. Supports Complex Applications: JAIN SLEE application components can have state, can be composed from other components, can create and destroy other application components, can invoke other application components both synchronously and asynchronously, and can invoke resource adaptors.
  4. Industry Standard: JAIN SLEE is specified via the Java Community Process which allows multiple companies and individuals to collaborate in developing Java technology specifications.
  5. In order to reduce the operating cost of legacy infrastructure more and more operators are investing and implementing open source platform. These new platforms bring agility and new service delivery capability to CSP.
  6. The JAINSLEE based platform can be used to develop and deploy carrier-grade applications that use SS7-based protocols such as INAP and CAP, IP protocols such as SIP and Diameter, and IT / Web protocols, such as HTTP Servlet, XML and Service Orientated Architectures (SOA).

Fundamental Concepts :

  • Application can be written once and run on many different implementations of JAIN SLEE.
  • Applications can access resources and protocols across multiple networks from within the JAIN SLEE environment.
  • Follows the ACID transaction .
  • component model for structuring the application logic of communications applications as a collection of reusable
  • object-orientated components, and for  composing these components into higher level and more sophisticated services.
  • SLEE specification also defines the management interfaces used to administer the application environment and also
  • defines set of standard Facilities (such as the Timer Facility, Trace Facility, and Alarm Facility so on  )
  •  Extension framework to allow new external protocols and systems (such as MSCs, MMSCs, SMSCs, Softswitchs, CSCFs, HLRs) to be integrated.

Characteristics of SLEE specification

• Event based model, asynchronous, support for composition

• Container manages component state

• Container manages garbage collection of components

• Transaction boundaries for demarcation and semantics of state replication

• Strongly typed event handling signatures

• 3rd party event driven components

• Management of lifecycle of Server, Services, Provisioned state

• Versioned services, upgrade of services, existing activities stay on existing service instances, new activities are directed to instances of upgraded services

• Independent of network technology/ protocols/elements through resource adaptor architecture

Entities :

jianslee environment


A service in JAIN SLEE terminology is a managed field replaceable unit.

The system administrator of a JAIN SLEE controls the life cycle (including deployment, undeployment and on-line upgrade) of a service. The program code can include Java classes Profiles, and Service Building Blocks.


A JAIN SLEE Profi le contains provisioned service or subscriber data.

Service Building Blocks running inside the JAINSLEE may access profiles as part of their application logic.

Service Building Block

The element of re-use defined by JAINSLEE is the Service Building Block (SBB).

An SBB is a software component that sends and receives events and performs computational logic based on the receipt of events and its current state. SBBs are stateful.

The program code for an SBB is comprised of Java classes.


An event represents an occurrence that may require application processing.

An event may originate from a number of different sources, for example, an external resource such as a communications protocol stack, from the SLEE itself, or from application components within the SLEE.

Resources and Resource ADAPTERS

Resources are external entities that interact with other systems outside of the SLEE, such as network elements (HLR, MSC, etc), protocol stacks, directories and databases.

A Resource Adaptor implements the interfacing of a Resource into the JAINSLEE environment.


•Jain SLEE :- JAIN is a Sun Java standards initiative and part of the Java Community Process.
JAIN specifies a comprehensive range of APIs that target converged IP and PSTN networks, including APIs for

– High-level application development (such as service provider APIs and the Service Logic Execution Environment (SLEE))

– call control

– signalling at the protocol level (such as SIP, MGCP and SS7)

•For telephony, data and wireless communications networks, the Java APIs defined through.

– service portability

– network independence

– open development

•A Service Logic Execution Environment (SLEE) is high-throughput, low-latency, event-processing application environment.
•JAIN SLEE  is designed specifically to allow implementations of a standard to meet the stringent requirements of communications applications (such as network-signaling applications).

Goals of JAIN SLEE are:

– Portable services and network independence.

– Hosting on an extensible platform.

– services and SLEE platform available from many vendors.

Key Features are  :

•Industry standard :- JSLEE is the industry-agreed standard for an application server that meets the specific needs of telecommunications networks.
•Network independence:-The JSLEE programming model enables network independence for the application developer. The model is independent of any particular network protocol, API or network topology.
•Converged services:- JSLEE provides the means to create genuinely converged services, which can run across multiple network technologies.
•Network migrations :-As JSLEE provides a generic, horizontal platform across many protocols, independent of the network technology, it provides the ideal enabler technology for smooth transition between networks.
•Global market—global services:-JSLEE-compliant applications, hosted on a JSLEE application server are network agnostic. A single platform can be used across disparate networks
•Robust and reliable:- As with the enterprise application server space, deploying applications on a standard application server that has been tested and deployed in many other networks reduces logic errors, and produces more reliable applications
•Standard object orientated component  architecture

Scope of JAINSLEE applications

•The principal features of the JSLEE programming model are :

– programs written in Java

-asynchronous programming paradigm

-well-defined event-delivery semantics

-component-based, object-oriented approach

-transactional model

-“profiles” of information, which represent provisioned data

-usage interfaces that support gathering service statistics

-support for standard Java APIs (such as JNDI and JDBC), and optionally, support integration with J2EE

-standard facilities for traces, alarms and timers, for use by the applications that are hosted on the SLEE

Resource adaptors

-The JSLEE provides integration capabilities using a plug-in architecture known as the resource adapter

architecture. Resource adaptors (RAs) provide interconnection with the “outside” world, for example,

interfaces to communication protocol stacks, directory services or external systems.

•SLEE management

-The JSLEE specification also defines the management capabilities of the SLEE. It adopts the Java standard

in this area, Java for Management Extensions (JMX).