Freeswitch PBX system


This article talks about setting up an in-house hosted Enterprise PBX system for sure and private communication within enterprise communication.

IP PBX

A PBX acts as the central switching system for phone calls within a business.

  • Cloud Hosted IP PBX Systems
  • On-premise IP PBX

An IP PBX is a PBX system with IP connectivity and may provide additional audio, video, or instant messaging communication utilizing the TCP/IP protocol stack. 

Wikipedia

Essentially an IP PBX is a telecommunication device( on IP Interface) that provides voice connectivity to IP phones within an organization/internal office network. 

Enterprise applications, media servers, presence servers, and the VoIP/SIP PBX are interconnected through a company intranet.SIP clients can be SIP hard-phones or soft-phones on PCs, PDAs etc. A PSTN gateway links the enterprise SIP PBX to the public PSTN.

A soft switch (SIP PBX) can be a combination of several SIP entities, such as SIP registrar, proxy server, redirect server, forking server, Back-To-Back User Agent (B2BUA) etc.

FreeSWITCH is free and open source communications software licensed under Mozilla Public License. It if often the core of voice core to provider call routing and media control . Its core library, libfreeswitch, is capable of being embedded into other projects, as well as being used as a stand-alone application. Read more about FreeSwitch SIP and Media Server.

Just a network-switch is hardware that controls network traffic by receiving and forwarding data to the destination device, a soft-switch is a software that controls traffic and call routing in a voIP communication network.

Class 4 switchClass 5 switch
Class 4 switches route calls between communication providers such as
– between telco and enterprise PBX
Class 5 switches connect communication provider with real clients (or end users) caller and callee.
– can provide platform + user agent such as diallers

Freeswitch setup as hosted IP PBX

Fetching source code

apt-get install git
git clone https://stash.freeswitch.org/scm/fs/freeswitch.git

Verify installation by checking version

freeswitch -version
FreeSWITCH version: 1.9.0-742-8f1b7e0~64bit (-742-8f1b7e0 64bit)

Steps post installation

optional arguments you can pass to freeswitch:

 -nf                    -- no forking
 -reincarnate           -- restart the switch on an uncontrolled exit
 -reincarnate-reexec    -- run execv on a restart (helpful for upgrades)
 -u [user]              -- specify user to switch to
 -g [group]             -- specify group to switch to
 -core                  -- dump cores
 -help                 -- this message
 -version        -- print the version and exit
 -rp             -- enable high(realtime) priority settings
 -lp             -- enable low priority settings
 -np             -- enable normal priority settings
 -vg             -- run under valgrind
 -nosql          -- disable internal sql scoreboard
 -heavy-timer    -- Heavy Timer, possibly more accurate but at a cost
 -nonat          -- disable auto nat detection
 -nonatmap       -- disable auto nat port mapping
 -nocal          -- disable clock calibration
 -nort           -- disable clock clock_realtime
 -stop           -- stop freeswitch
 -nc             -- do not output to a console and background
 -ncwait         -- do not output to a console and background but wait until the system is ready before exiting (implies -nc)
 -c              -- output to a console and stay in the foreground

Options to control locations of files:

 -base [basedir]         -- alternate prefix directory
 -cfgname [filename]     -- alternate filename for FreeSWITCH main configuration file
 -conf [confdir]         -- alternate directory for FreeSWITCH configuration files
 -log [logdir]           -- alternate directory for logfiles
 -run [rundir]           -- alternate directory for runtime files
 -db [dbdir]             -- alternate directory for the internal database
 -mod [moddir]           -- alternate directory for modules
 -htdocs [htdocsdir]     -- alternate directory for htdocs
 -scripts [scriptsdir]   -- alternate directory for scripts
 -temp [directory]       -- alternate directory for temporary files
 -grammar [directory]    -- alternate directory for grammar files
 -certs [directory]      -- alternate directory for certificates
 -recordings [directory] -- alternate directory for recordings
 -storage [directory]    -- alternate directory for voicemail storage
 -cache [directory]      -- alternate directory for cache files
 -sounds [directory]     -- alternate directory for sound files

Freeswitch as B2BUA

Tracing SIP messages and Freeswitch processing for call from external user to internal user.

Receives incoming Call INVITE from Caller

recv 823 bytes from tcp/[caller_ip]:35365 at 09:55:07.936234:
   ------------------------------------------------------------------------
   INVITE sip:to_number@sometelco.com:5060 SIP/2.0
   Via: SIP/2.0/TCP 192.168.1.23:55934;branch=z9hG4bK-524287-1---cc11593581af6519;rport
   Max-Forwards: 70
   Contact: <sip:from_number@192.168.1.23:55934;transport=tcp>
   To: <sip:to_number@sometelco.com:5060>
   From: "from_number"<sip:from_number@sometelco.com:5060>;tag=47a61272
   Call-ID: 94385YTY3ODNlNzE1YjE5MmY4NmQ3ZWUyZDAzM2E0YzBkM2I
   CSeq: 1 INVITE
   Allow: OPTIONS, SUBSCRIBE, NOTIFY, INVITE, ACK, CANCEL, BYE, REFER, INFO
   Content-Type: application/sdp
   Supported: replaces
   User-Agent: X-Lite release 5.4.0 stamp 94385
   Content-Length: 208

   v=0
   o=- 1553248503383592 1 IN IP4 192.168.1.23
   s=X-Lite release 5.4.0 stamp 94385
   c=IN IP4 192.168.1.23
   t=0 0
   m=audio 49874 RTP/AVP 8 101
   a=rtpmap:101 telephone-event/8000
   a=fmtp:101 0-15
   a=sendrecv
   ------------------------------------------------------------------------

checks with ACL for permission and set NAT. Isolate SDP for processing.

New Channel sofia/internal/from_number@sometelco.com:5060 [a8a2003f-5755-40fe-ab63-aab2f5264886]

Running State Change CS_NEW (Cur 1 Tot 274)
receiving invite from caller_ip:35365 version: 1.9.0 -742-8f1b7e0 64bit
IP caller_ip Approved by acl "domains[]". Access Granted.
Setting NAT mode based on nat.auto
Channel sofia/internal/from_number@sometelco.com:5060 entering state [received][100]
Remote SDP:
v=0
o=- 1553248503383592 1 IN IP4 192.168.1.23
s=X-Lite release 5.4.0 stamp 94385
c=IN IP4 192.168.1.23
t=0 0
m=audio 49874 RTP/AVP 8 101
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-15

mainatin and Updates call-state (switch_core_state_machine ) CS_NEW -> CS_INIT -> CS_ROUTING -> RINGING and send 100 trying to caller

State Change CS_NEW -> CS_INIT
State NEW
Running State Change CS_INIT (Cur 1 Tot 274)
State INIT
SOFIA INIT
Standard INIT
State Change CS_INIT -> CS_ROUTING
State INIT going to sleep
Running State Change CS_ROUTING (Cur 1 Tot 274)
Change DOWN -> RINGING
State ROUTING
send 413 bytes to tcp/[caller_ip]:35365 at 09:55:07.937474:
   ------------------------------------------------------------------------
   SIP/2.0 100 Trying
   Via: SIP/2.0/TCP 192.168.1.23:55934;branch=z9hG4bK-524287-1---cc11593581af6519;rport=35365;received=caller_ip
   From: "from_number"<sip:from_number@sometelco.com:5060>;tag=47a61272
   To: <sip:to_number@sometelco.com:5060>
   Call-ID: 94385YTY3ODNlNzE1YjE5MmY4NmQ3ZWUyZDAzM2E0YzBkM2I
   CSeq: 1 INVITE
   User-Agent: FreeSWITCH-mod_sofia/1.9.0-742-8f1b7e0~64bit
   Content-Length: 0
   ------------------------------------------------------------------------

Checks dialplan to route incoming call. In this case action is to bridge the incoming call to internal user

mod_sofia.c:154 sofia/internal/from_number@sometelco.com:5060 SOFIA ROUTING
switch_core_state_machine.c:236 sofia/internal/from_number@sometelco.com:5060 Standard ROUTING

mod_dialplan_xml.c:637 Processing from_number <from_number>->to_number in context public
Dialplan: sofia/internal/from_number@sometelco.com:5060 parsing [public->dialplan_cutsom] continue=false
Dialplan: sofia/internal/from_number@sometelco.com:5060 Regex (PASS) [dialplan_cutsom] destination_number(to_number) =~ /^(\d+)$/ break=on-false
Dialplan: sofia/internal/from_number@sometelco.com:5060 Action log(INFO ***** Forwarding calls to gateway ****** ) 
Dialplan: sofia/internal/from_number@sometelco.com:5060 Action bridge({sip_auth_username=user,sip_auth_password=pass,sip_route_uri=sip:to_number@ip_addr;transport=tls,sip_invite_req_uri=sip:to_number@sometelco.com;transport=tls}sofia/external/to_number@ip_addr) 

update call state CS_ROUTING -> CS_EXECUTE

State Change CS_ROUTING -> CS_EXECUTE
State ROUTING going to sleep
Running State Change CS_EXECUTE (Cur 1 Tot 274)
State EXECUTE
SOFIA EXECUTE

set the crypto and codecs for the new call

switch_ivr_originate.c:2159 Parsing global variables
switch_channel.c:1104 New Channel sofia/external/to_number@ip_addr [cc1ae238-9efd-4f51-93e9-05abd48bea4d]
mod_sofia.c:5026 (sofia/external/to_number@ip_addr) State Change CS_NEW -> CS_INIT
switch_core_state_machine.c:584 (sofia/external/to_number@ip_addr) Running State Change CS_INIT (Cur 2 Tot 275)
switch_core_state_machine.c:627 (sofia/external/to_number@ip_addr) State INIT
mod_sofia.c:93 sofia/external/to_number@ip_addr SOFIA INIT
Set Local audio crypto Key [1 AEAD_AES_256_GCM_8 inline:ZbEHd76sP6FZSO9AYcqryybaA4HY3O5p2Uo+e1gmmfVaZCEic6cvKyArhMU]
Set Local video crypto Key [1 AEAD_AES_256_GCM_8 inline:Ehr3LoDR8Ur+wtNAMqoqIDn3S7V2inE2/n++awxS6/1P2ijcqfk12+LM/Pc]
Set Local text crypto Key [1 AEAD_AES_256_GCM_8 inline:NVSfjOmSS5BaP/5yqg+SOXcqvEFTHHrC8R5AYkkClXLuNOXYoaUYlrIWeW0]
Set Local audio crypto Key [2 AEAD_AES_128_GCM_8 inline:ePH/F2Qw5+zi8c7tkBb6Y2AQE5uevp+jWUkjgQ]
Set Local video crypto Key [2 AEAD_AES_128_GCM_8 inline:YWdfNLSx6MqG9WQ3TmsV/cSBDqjRUAbHE0rRCg]
Set Local text crypto Key [2 AEAD_AES_128_GCM_8 inline:DFXOP2V2Ep6FoHNz5HIMrm0cu6Za8I5wOI/hUw]
Set Local audio crypto Key [3 AES_CM_256_HMAC_SHA1_80 inline:SG5rYx3GSR2imutYQ+LzqHufG9UkG3n/SfmFHFOG/r75v2pwf2lG7Qpup+J0mw]
Set Local video crypto Key [3 AES_CM_256_HMAC_SHA1_80 inline:LkU3i9MD25k2wtTfSXUvhlxo66GtMWnXkKoxSdgRZyANoeOhufYnXzbXDo+7+w]
Set Local text crypto Key [3 AES_CM_256_HMAC_SHA1_80 inline:AUgUOVmFunzotvwZ6KuMDnBRR2XKk1DsX2qg465MsT6OAxHc2qKBFpeQEpxrqA]
Set Local audio crypto Key [4 AES_CM_192_HMAC_SHA1_80 inline:2PVBBJEp4QcTzTf4Th8Ag/7KiVPmrYb/FCowiRb6yAuTO/kxQLc]
Set Local video crypto Key [4 AES_CM_192_HMAC_SHA1_80 inline:OiFbZQ6mWuf5sHJT1pFPU6EWxEvQAO/0rcp8uGMf79k7RSR3IQA]
Set Local text crypto Key [4 AES_CM_192_HMAC_SHA1_80 inline:XyednWJmzRfsWQOgdhKaMeOeE/OLmnwo6hVEZWl4OJdKdgK6TVc]
Set Local audio crypto Key [5 AES_CM_128_HMAC_SHA1_80 inline:Yd4L5Qi7A/8xay5ZHWR1jKk9j5Kvy9s2Zo3NOES2]
Set Local video crypto Key [5 AES_CM_128_HMAC_SHA1_80 inline:ImgbbD6cnhnH19O1knP5SSIUULsZTaNJJIUepxt0]
Set Local text crypto Key [5 AES_CM_128_HMAC_SHA1_80 inline:V7+IbSZmTdQNjh/upUZ5TFDSlgarhDTVfV+AcUA+]
Set Local audio crypto Key [6 AES_CM_256_HMAC_SHA1_32 inline:JI+s9uFdZ3JfZmRRfwHr0OrpyZdtUXmMC0WRIZow1EuXRB9xKFRBk6KmSWomqQ]
Set Local video crypto Key [6 AES_CM_256_HMAC_SHA1_32 inline:MX6CGCrMEioUCJsIOCxRqlHOx4mUYRw4DslpY25njZQAkH6MgG/9hp7G8xr44A]
Set Local text crypto Key [6 AES_CM_256_HMAC_SHA1_32 inline:ikCz2sYLGoMO+dlrZj+znlQ3djAkGSYzSLLu6Az8u2THWPgnkFJXVgXSxHOaHw]
Set Local audio crypto Key [7 AES_CM_192_HMAC_SHA1_32 inline:5JzlrMywFZhHuNLWPG/HBrUi/Zcg414Q7ZfSaJQnUF5N9APy+GQ]
Set Local video crypto Key [7 AES_CM_192_HMAC_SHA1_32 inline:K0dZtwH1Q7AuSMBPPUesy047c4nAF+QuFsVvGdf3fYJDOD0Uwxo]
Set Local text crypto Key [7 AES_CM_192_HMAC_SHA1_32 inline:96SwyWAdV1a+BU3UbiX1PHdkRlSS4RtmwPWNPbCR3NDm1MyBh58]
Set Local audio crypto Key [8 AES_CM_128_HMAC_SHA1_32 inline:/RLYPhZs07WCCBRY8tWNTJemT/IFq1VPHGHmGvnG]
Set Local video crypto Key [8 AES_CM_128_HMAC_SHA1_32 inline:mQlgScFq1iMKEW8vobzwhmN9TWSmVblAv9u7c1/c]
Set Local text crypto Key [8 AES_CM_128_HMAC_SHA1_32 inline:WAQveMfrQkPBcfqH2qLmuzY63VLfT+N30/YLyuqE]
Set Local audio crypto Key [9 AES_CM_128_NULL_AUTH inline:f2fx2ekxPG3GTwTYARtquNJ87qO0Q5ei47KYlo9K]
Set Local video crypto Key [9 AES_CM_128_NULL_AUTH inline:qpAkfc1bWnZ0Y/1ql+dNvhIGgxxWZoVltnRD5kqn]
Set Local text crypto Key [9 AES_CM_128_NULL_AUTH inline:LyhSlzI3X38WKPwZ83035Ddvse4J/2KnKoydo2FD]

set proxy route and create SDP for sending invite to bridged client

sofia_glue.c:1268 sip:to_number@ip_addr;transport=tls Setting proxy route to sofia/external/to_number@ip_addr
sofia_glue.c:1299 sofia/external/to_number@ip_addr sending invite version: 1.9.0 -742-8f1b7e0 64bit
Local SDP:
v=0
o=FreeSWITCH 1553228435 1553228436 IN IP4 via_addr
s=FreeSWITCH
c=IN IP4 via_addr
t=0 0
m=audio 20072 RTP/SAVP 8 101
a=rtpmap:8 PCMA/8000
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-16
a=crypto:1 AEAD_AES_256_GCM_8 inline:ZbEHd76sP6FZSO9AYcqryybaA4HY3O5p2Uo+e1gmmfVaZCEic6cvKyArhMU
a=crypto:2 AEAD_AES_128_GCM_8 inline:ePH/F2Qw5+zi8c7tkBb6Y2AQE5uevp+jWUkjgQ
a=crypto:3 AES_CM_256_HMAC_SHA1_80 inline:SG5rYx3GSR2imutYQ+LzqHufG9UkG3n/SfmFHFOG/r75v2pwf2lG7Qpup+J0mw
a=crypto:4 AES_CM_192_HMAC_SHA1_80 inline:2PVBBJEp4QcTzTf4Th8Ag/7KiVPmrYb/FCowiRb6yAuTO/kxQLc
a=crypto:5 AES_CM_128_HMAC_SHA1_80 inline:Yd4L5Qi7A/8xay5ZHWR1jKk9j5Kvy9s2Zo3NOES2
a=crypto:6 AES_CM_256_HMAC_SHA1_32 inline:JI+s9uFdZ3JfZmRRfwHr0OrpyZdtUXmMC0WRIZow1EuXRB9xKFRBk6KmSWomqQ
a=crypto:7 AES_CM_192_HMAC_SHA1_32 inline:5JzlrMywFZhHuNLWPG/HBrUi/Zcg414Q7ZfSaJQnUF5N9APy+GQ
a=crypto:8 AES_CM_128_HMAC_SHA1_32 inline:/RLYPhZs07WCCBRY8tWNTJemT/IFq1VPHGHmGvnG
a=crypto:9 AES_CM_128_NULL_AUTH inline:f2fx2ekxPG3GTwTYARtquNJ87qO0Q5ei47KYlo9K
a=ptime:20
a=sendrecv
m=audio 20072 RTP/AVP 8 101
a=rtpmap:8 PCMA/8000
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-16
a=ptime:20
a=sendrecv

attach the SDP to INVITE and proceed forwarding INVITE to callee

send 1988 bytes to tls/[ip_addr]:5061 at 09:55:07.939831:
   ------------------------------------------------------------------------
   INVITE sip:to_number@sometelco.com;transport=tls SIP/2.0
   Via: SIP/2.0/TLS via_addr:5080;rport;branch=z9hG4bK21Qm9U3eHX0Nc
   Max-Forwards: 69
   From: "from_number" <sip:from_number@via_addr>;tag=8jByBXa2pF1Fj
   To: <sip:to_number@ip_addr>
   Call-ID: 6a827514-c72b-1237-8aab-02a933b32da0
   CSeq: 2070461 INVITE
   Contact: <sip:mod_sofia@via_addr:5080>
   User-Agent: FreeSWITCH-mod_sofia/1.9.0-742-8f1b7e0~64bit
   Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, INFO, UPDATE, REGISTER, REFER, NOTIFY
   Supported: timer, path, replaces
   Allow-Events: talk, hold, conference, refer
   Content-Type: application/sdp
   Content-Disposition: session
   Content-Length: 1162
   X-FS-Support: update_display,send_info
   Remote-Party-ID: "from_number" <sip:from_number@via_addr>;party=calling;screen=yes;privacy=off

   v=0
   o=FreeSWITCH 1553228435 1553228436 IN IP4 via_addr
   s=FreeSWITCH
   c=IN IP4 via_addr
   t=0 0
   m=audio 20072 RTP/SAVP 8 101
   a=rtpmap:8 PCMA/8000
   a=rtpmap:101 telephone-event/8000
   a=fmtp:101 0-16
   a=crypto:1 AEAD_AES_256_GCM_8 inline:ZbEHd76sP6FZSO9AYcqryybaA4HY3O5p2Uo+e1gmmfVaZCEic6cvKyArhMU
   a=crypto:2 AEAD_AES_128_GCM_8 inline:ePH/F2Qw5+zi8c7tkBb6Y2AQE5uevp+jWUkjgQ
   a=crypto:3 AES_CM_256_HMAC_SHA1_80 inline:SG5rYx3GSR2imutYQ+LzqHufG9UkG3n/SfmFHFOG/r75v2pwf2lG7Qpup+J0mw
   a=crypto:4 AES_CM_192_HMAC_SHA1_80 inline:2PVBBJEp4QcTzTf4Th8Ag/7KiVPmrYb/FCowiRb6yAuTO/kxQLc
   a=crypto:5 AES_CM_128_HMAC_SHA1_80 inline:Yd4L5Qi7A/8xay5ZHWR1jKk9j5Kvy9s2Zo3NOES2
   a=crypto:6 AES_CM_256_HMAC_SHA1_32 inline:JI+s9uFdZ3JfZmRRfwHr0OrpyZdtUXmMC0WRIZow1EuXRB9xKFRBk6KmSWomqQ
   a=crypto:7 AES_CM_192_HMAC_SHA1_32 inline:5JzlrMywFZhHuNLWPG/HBrUi/Zcg414Q7ZfSaJQnUF5N9APy+GQ
   a=crypto:8 AES_CM_128_HMAC_SHA1_32 inline:/RLYPhZs07WCCBRY8tWNTJemT/IFq1VPHGHmGvnG
   a=crypto:9 AES_CM_128_NULL_AUTH inline:f2fx2ekxPG3GTwTYARtquNJ87qO0Q5ei47KYlo9K
   a=ptime:20
   m=audio 20072 RTP/AVP 8 101
   a=rtpmap:8 PCMA/8000
   a=rtpmap:101 telephone-event/8000
   a=fmtp:101 0-16
   a=ptime:20
   ------------------------------------------------------------------------

manage and update call state for this call leg too CS_INIT -> CS_ROUTING -> CS_CONSUME_MEDIA

Standard INIT
State Change CS_INIT -> CS_ROUTING
State INIT going to sleep
Running State Change CS_ROUTING (Cur 2 Tot 275)
Channel sofia/external/to_number@ip_addr entering state [calling][0]
State ROUTING
SOFIA ROUTING
State Change CS_ROUTING -> CS_CONSUME_MEDIA
State ROUTING going to sleep
Running State Change CS_CONSUME_MEDIA (Cur 2 Tot 275)
State CONSUME_MEDIA
State CONSUME_MEDIA going to sleep
recv 365 bytes from tls/[ip_addr]:5061 at 09:55:07.940977:
   ------------------------------------------------------------------------
   SIP/2.0 100 trying -- your call is important to us
   Via: SIP/2.0/TLS via_addr:5080;rport=59774;branch=z9hG4bK21Qm9U3eHX0Nc;received=via_addr
   From: "from_number" <sip:from_number@via_addr>;tag=8jByBXa2pF1Fj
   To: <sip:to_number@ip_addr>
   Call-ID: 6a827514-c72b-1237-8aab-02a933b32da0
   CSeq: 2070461 INVITE
   Server: XYZ
   Content-Length: 0

   ------------------------------------------------------------------------

Callee from PBX throws auth challenge

recv 483 bytes from tls/[ip_addr]:5061 at 09:55:08.046934:
   ------------------------------------------------------------------------
   SIP/2.0 407 Proxy Authentication Required
   Via: SIP/2.0/TLS via_addr:5080;received=via_addr;rport=59774;branch=z9hG4bK21Qm9U3eHX0Nc
   From: "from_number" <sip:from_number@via_addr>;tag=8jByBXa2pF1Fj
   To: <sip:to_number@ip_addr>;tag=f1cff938000510c1d9006e5a2a4e240b-5736
   Call-ID: 6a827514-c72b-1237-8aab-02a933b32da0
   CSeq: 2070461 INVITE
   Proxy-Authenticate: Digest realm="domain.com", nonce="XJSyI1yUsPf0w1bAocvH4IOCayfWt3bX", qop="auth"
   Content-Length: 0

   ------------------------------------------------------------------------
send 387 bytes to tls/[ip_addr]:5061 at 09:55:08.047056:
   ------------------------------------------------------------------------
   ACK sip:to_number@sometelco.com;transport=tls SIP/2.0
   Via: SIP/2.0/TLS via_addr:5080;rport;branch=z9hG4bK21Qm9U3eHX0Nc
   Max-Forwards: 69
   From: "from_number" <sip:from_number@via_addr>;tag=8jByBXa2pF1Fj
   To: <sip:to_number@ip_addr>;tag=f1cff938000510c1d9006e5a2a4e240b-5736
   Call-ID: 6a827514-c72b-1237-8aab-02a933b32da0
   CSeq: 2070461 ACK
   Content-Length: 0

   ------------------------------------------------------------------------

Freeswitch IP PBX B2BUA acting as caller sends re-invite with auth details

Authenticating 'altanai' with 'Digest:"doamin.com":altanai:pass'.
send 2273 bytes to tls/[ip_addr]:5061 at 09:55:08.047387:
   ------------------------------------------------------------------------
   INVITE sip:to_number@sometelco.com;transport=tls SIP/2.0
   Via: SIP/2.0/TLS via_addr:5080;rport;branch=z9hG4bK3aHDBQmje6p8Q
   Max-Forwards: 69
   From: "from_number" <sip:from_number@via_addr>;tag=8jByBXa2pF1Fj
   To: <sip:to_number@ip_addr>
   Call-ID: 6a827514-c72b-1237-8aab-02a933b32da0
   CSeq: 2070462 INVITE
   Contact: <sip:mod_sofia@via_addr:5080>
   User-Agent: FreeSWITCH-mod_sofia/1.9.0-742-8f1b7e0~64bit
   Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, INFO, UPDATE, REGISTER, REFER, NOTIFY
   Supported: timer, path, replaces
   Allow-Events: talk, hold, conference, refer
   Proxy-Authorization: Digest username="altanai", realm="domain.com", nonce="XJSyI1yUsPf0w1bAocvH4IOCayfWt3bX", cnonce="apLWcMcrEjerigKpM7MtoA", algorithm=MD5, uri="sip:to_number@sometelco.com;transport=tls", response="0044b00a4d5026252b32eed619d70f9d", qop=auth, nc=00000001
   Content-Type: application/sdp
   Content-Disposition: session
   Content-Length: 1162
   X-FS-Support: update_display,send_info
   Remote-Party-ID: "from_number" <sip:from_number@via_addr>;party=calling;screen=yes;privacy=off

   v=0
   o=FreeSWITCH 1553228435 1553228436 IN IP4 via_addr
   s=FreeSWITCH
   c=IN IP4 via_addr
   t=0 0
   m=audio 20072 RTP/SAVP 8 101
   a=rtpmap:8 PCMA/8000
   a=rtpmap:101 telephone-event/8000
   a=fmtp:101 0-16
   a=crypto:1 AEAD_AES_256_GCM_8 inline:ZbEHd76sP6FZSO9AYcqryybaA4HY3O5p2Uo+e1gmmfVaZCEic6cvKyArhMU
   a=crypto:2 AEAD_AES_128_GCM_8 inline:ePH/F2Qw5+zi8c7tkBb6Y2AQE5uevp+jWUkjgQ
   a=crypto:3 AES_CM_256_HMAC_SHA1_80 inline:SG5rYx3GSR2imutYQ+LzqHufG9UkG3n/SfmFHFOG/r75v2pwf2lG7Qpup+J0mw
   a=crypto:4 AES_CM_192_HMAC_SHA1_80 inline:2PVBBJEp4QcTzTf4Th8Ag/7KiVPmrYb/FCowiRb6yAuTO/kxQLc
   a=crypto:5 AES_CM_128_HMAC_SHA1_80 inline:Yd4L5Qi7A/8xay5ZHWR1jKk9j5Kvy9s2Zo3NOES2
   a=crypto:6 AES_CM_256_HMAC_SHA1_32 inline:JI+s9uFdZ3JfZmRRfwHr0OrpyZdtUXmMC0WRIZow1EuXRB9xKFRBk6KmSWomqQ
   a=crypto:7 AES_CM_192_HMAC_SHA1_32 inline:5JzlrMywFZhHuNLWPG/HBrUi/Zcg414Q7ZfSaJQnUF5N9APy+GQ
   a=crypto:8 AES_CM_128_HMAC_SHA1_32 inline:/RLYPhZs07WCCBRY8tWNTJemT/IFq1VPHGHmGvnG
   a=crypto:9 AES_CM_128_NULL_AUTH inline:f2fx2ekxPG3GTwTYARtquNJ87qO0Q5ei47KYlo9K
   a=ptime:20
   m=audio 20072 RTP/AVP 8 101
   a=rtpmap:8 PCMA/8000
   a=rtpmap:101 telephone-event/8000
   a=fmtp:101 0-16
   a=ptime:20
   ------------------------------------------------------------------------
2019-03-22 09:55:08.041945 [DEBUG] sofia.c:7291 Channel sofia/external/to_number@ip_addr entering state [calling][0]
recv 365 bytes from tls/[ip_addr]:5061 at 09:55:08.048255:
   ------------------------------------------------------------------------
   SIP/2.0 100 trying -- your call is important to us
   Via: SIP/2.0/TLS via_addr:5080;rport=59774;branch=z9hG4bK3aHDBQmje6p8Q;received=via_addr
   From: "from_number" <sip:from_number@via_addr>;tag=8jByBXa2pF1Fj
   To: <sip:to_number@ip_addr>
   Call-ID: 6a827514-c72b-1237-8aab-02a933b32da0
   CSeq: 2070462 INVITE
   Server: XYZ
   Content-Length: 0
   ------------------------------------------------------------------------

Call is accepted by callee, 200 OK is received by Freeswitch PBX

recv 1451 bytes from tls/[ip_addr]:5061 at 09:55:14.223460:
   ------------------------------------------------------------------------
   SIP/2.0 200 OK
   Via: SIP/2.0/TLS via_addr:5080;received=via_addr;rport=59774;branch=z9hG4bK3aHDBQmje6p8Q
   Record-Route: <sip:ip_addr1:5060;lr;ftag=8jByBXa2pF1Fj>
   Record-Route: <sip:ip_addr2;lr;ftag=8jByBXa2pF1Fj;did=fd.0971>
   Record-Route: <sip:ip_addr:5060;r2=on;lr;ftag=8jByBXa2pF1Fj;nat=yes>
   Record-Route: <sip:ip_addr:5061;transport=tls;r2=on;lr;ftag=8jByBXa2pF1Fj;nat=yes>
   From: "from_number" <sip:from_number@via_addr>;tag=8jByBXa2pF1Fj
   To: <sip:to_number@ip_addr>;tag=D0r5K6pp80Ujm
   Call-ID: 6a827514-c72b-1237-8aab-02a933b32da0
   CSeq: 2070462 INVITE
   Contact: <sip:to_number@34.201.27.78:5080;transport=udp>
   User-Agent: FreeSWITCH-mod_sofia/1.9.0-742-8f1b7e0~64bit
   Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, INFO, UPDATE, REGISTER, REFER, NOTIFY
   Supported: timer, path, replaces
   Allow-Events: talk, hold, conference, refer
   Content-Type: application/sdp
   Content-Disposition: session
   Content-Length: 380
   Remote-Party-ID: "to_number" <sip:to_number@34.201.27.78>;party=calling;privacy=off;screen=no

   v=0
   o=FreeSWITCH 1553215954 1553215955 IN IP4 <FS_IPADDR>
   s=FreeSWITCH
   c=IN IP4 <FS_IPADDR>
   t=0 0
   m=audio 33516 RTP/SAVP 8 101
   a=rtpmap:8 PCMA/8000
   a=rtpmap:101 telephone-event/8000
   a=fmtp:101 0-16
   a=sendrecv
   a=crypto:3 AES_CM_256_HMAC_SHA1_80 inline:/itE1k5BLMoTNzo7YEv6hCyM6R6wyHem3Coc5jjYVlKR2L3tEzBG5zx1QHgVSg==
   a=ptime:20
   m=audio 0 RTP/SAVP 19
   a=rtpmap:19 
   ------------------------------------------------------------------------

send ACK to callee

Update Callee ID to "to_number" <to_number>
Channel sofia/external/to_number@ip_addr entering state [completing][200]
sofia.c:7301 Remote SDP:
v=0
o=FreeSWITCH 1553215954 1553215955 IN IP4 <FS_IPADDR>
s=FreeSWITCH
c=IN IP4 <FS_IPADDR>
t=0 0
m=audio 33516 RTP/SAVP 8 101
a=rtpmap:8 PCMA/8000
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-16
a=crypto:3 AES_CM_256_HMAC_SHA1_80 inline:/itE1k5BLMoTNzo7YEv6hCyM6R6wyHem3Coc5jjYVlKR2L3tEzBG5zx1QHgVSg==
a=ptime:20
m=audio 0 RTP/SAVP 19

send 953 bytes to tls/[ip_addr]:5061 at 09:55:14.224320:
   ------------------------------------------------------------------------
   ACK sip:to_number@34.201.27.78:5080;transport=udp SIP/2.0
   Via: SIP/2.0/TLS via_addr:5080;rport;branch=z9hG4bK4Ka6cj5NBFDUK
   Route: <sip:ip_addr:5061;transport=tls;r2=on;lr;ftag=8jByBXa2pF1Fj;nat=yes>
   Route: <sip:ip_addr:5060;r2=on;lr;ftag=8jByBXa2pF1Fj;nat=yes>
   Route: <sip:ip_addr2;lr;ftag=8jByBXa2pF1Fj;did=fd.0971>
   Route: <sip:ip_addr3:5060;lr;ftag=8jByBXa2pF1Fj>
   Max-Forwards: 70
   From: "from_number" <sip:from_number@via_addr>;tag=8jByBXa2pF1Fj
   To: <sip:to_number@ip_addr>;tag=D0r5K6pp80Ujm
   Call-ID: 6a827514-c72b-1237-8aab-02a933b32da0
   CSeq: 2070462 ACK
   Contact: <sip:mod_sofia@via_addr:5080>
   Proxy-Authorization: Digest username="altanai", realm="domain.com", nonce="XJSyI1yUsPf0w1bAocvH4IOCayfWt3bX", cnonce="apLWcMcrEjerigKpM7MtoA", algorithm=MD5, uri="sip:to_number@sometelco.com;transport=tls", response="0044b00a4d5026252b32eed619d70f9d", qop=auth, nc=00000001
   Content-Length: 0
   ------------------------------------------------------------------------

set audio codecs, update call state CS_CONSUME_MEDIA -> CS_EXCHANGE_MEDIA

entering state [ready][200]
looking for crypto suite [AEAD_AES_256_GCM_8] in [3 AES_CM_256_HMAC_SHA1_80 inline:/itE1k5BLMoTNzo7YEv6hCyM6R6wyHem3Coc5jjYVlKR2L3tEzBG5zx1QHgVSg==]
looking for crypto suite [AEAD_AES_128_GCM_8] in [3 AES_CM_256_HMAC_SHA1_80 inline:/itE1k5BLMoTNzo7YEv6hCyM6R6wyHem3Coc5jjYVlKR2L3tEzBG5zx1QHgVSg==]
looking for crypto suite [AES_CM_256_HMAC_SHA1_80] in [3 AES_CM_256_HMAC_SHA1_80 inline:/itE1k5BLMoTNzo7YEv6hCyM6R6wyHem3Coc5jjYVlKR2L3tEzBG5zx1QHgVSg==]
Found suite AES_CM_256_HMAC_SHA1_80
Set Remote Key [3 AES_CM_256_HMAC_SHA1_80 inline:/itE1k5BLMoTNzo7YEv6hCyM6R6wyHem3Coc5jjYVlKR2L3tEzBG5zx1QHgVSg==]
Audio Codec Compare [PCMA:8:8000:20:64000:1]/[PCMA:8:8000:20:64000:1]
Audio Codec Compare [PCMA:8:8000:20:64000:1] ++++ is saved as a match
Set telephone-event payload to 101@8000
Set Codec sofia/external/to_number@ip_addr PCMA/8000 20 ms 160 samples 64000 bits 1 channels
sofia/external/to_number@ip_addr Original read codec set to PCMA:8
Set telephone-event payload to 101@8000
sofia/external/to_number@ip_addr Set 2833 dtmf send payload to 101 recv payload to 101
AUDIO RTP [sofia/external/to_number@ip_addr] 10.130.74.15 port 20072 -> <FS_IPADDR> port 33516 codec: 8 ms: 20
Starting timer [soft] 160 bytes per 20ms
Set 2833 dtmf send payload to 101
Set 2833 dtmf receive payload to 101
Set rtp dtmf delay to 40
Activating audio Secure RTP SEND
srtp:sdes:AES_CM_256_HMAC_SHA1_80
Activating audio Secure RTP RECV
srtp:sdes:AES_CM_256_HMAC_SHA1_80
has been answered
Callstate Change DOWN -> ACTIVE
Audio Codec Compare [PCMA:8:8000:20:64000:1]/[PCMU:0:8000:20:64000:1]
Audio Codec Compare [PCMA:8:8000:20:64000:1]/[PCMA:8:8000:20:64000:1]
Audio Codec Compare [PCMA:8:8000:20:64000:1] ++++ is saved as a match
Set telephone-event payload to 101@8000
Set Codec sofia/internal/from_number@sometelco.com:5060 PCMA/8000 20 ms 160 samples 64000 bits 1 channels
sofia/internal/from_number@sometelco.com:5060 Original read codec set to PCMA:8
Set telephone-event payload to 101@8000
sofia/internal/from_number@sometelco.com:5060 Set 2833 dtmf send payload to 101 recv payload to 101

Send early media/ RTP to Callee

 Pre-Answer sofia/internal/from_number@sometelco.com:5060!
 Callstate Change RINGING -> EARLY
 2019-03-22 09:55:14.221933 [DEBUG] switch_core_media.c:8147 Audio params are unchanged for sofia/internal/from_number@sometelco.com:5060.
 2019-03-22 09:55:14.221933 [DEBUG] mod_sofia.c:881 Local SDP sofia/internal/from_number@sometelco.com:5060:
 v=0
 o=FreeSWITCH 1553219088 1553219089 IN IP4 via_addr
 s=FreeSWITCH
 c=IN IP4 via_addr
 t=0 0
 m=audio 29426 RTP/AVP 8 101
 a=rtpmap:8 PCMA/8000
 a=rtpmap:101 telephone-event/8000
 a=fmtp:101 0-16
 a=ptime:20
sedn a=sendrecv

Send 200 OK to Caller

send 1254 bytes to tcp/[caller_ip]:35365 at 09:55:14.232934:
   ------------------------------------------------------------------------
   SIP/2.0 200 OK
   Via: SIP/2.0/TCP 192.168.1.23:55934;branch=z9hG4bK-524287-1---cc11593581af6519;rport=35365;received=caller_ip
   From: "from_number"<sip:from_number@sometelco.com:5060>;tag=47a61272
   To: <sip:to_number@sometelco.com:5060>;tag=NjvKFKQaHp52e
   Call-ID: 94385YTY3ODNlNzE1YjE5MmY4NmQ3ZWUyZDAzM2E0YzBkM2I
   CSeq: 1 INVITE
   Contact: <sip:to_number@via_addr:5060;transport=tcp>
   User-Agent: FreeSWITCH-mod_sofia/1.9.0-742-8f1b7e0~64bit
   Accept: application/sdp
   Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, INFO, UPDATE, REGISTER, REFER, NOTIFY, PUBLISH, SUBSCRIBE
   Supported: timer, path, replaces
   Allow-Events: talk, hold, conference, presence, as-feature-event, dialog, line-seize, call-info, sla, include-session-description, presence.winfo, message-summary, refer
   Session-Expires: 120;refresher=uas
   Content-Type: application/sdp
   Content-Disposition: session
   Content-Length: 220
   Remote-Party-ID: "to_number" <sip:to_number@sometelco.com>;party=calling;privacy=off;screen=no

   v=0
   o=FreeSWITCH 1553219088 1553219089 IN IP4 via_addr
   s=FreeSWITCH
   c=IN IP4 via_addr
   t=0 0
   m=audio 29426 RTP/AVP 8 101
   a=rtpmap:8 PCMA/8000
   a=rtpmap:101 telephone-event/8000
   a=fmtp:101 0-16
   a=ptime:20
   ------------------------------------------------------------------------
entering state [completed][200]
Channel [sofia/internal/from_number@sometelco.com:5060] has been answered
Callstate Change EARLY -> ACTIVE
Originate Resulted in Success: [sofia/external/to_number@ip_addr]
State Change CS_CONSUME_MEDIA -> CS_EXCHANGE_MEDIA
Running State Change CS_EXCHANGE_MEDIA (Cur 2 Tot 275)
State EXCHANGE_MEDIA
SOFIA EXCHANGE_MEDIA

Receive ACK from Caller

recv 507 bytes from tcp/[caller_ip]:35365 at 09:55:14.459247:
   ------------------------------------------------------------------------
   ACK sip:to_number@via_addr:5060;transport=tcp SIP/2.0
   Via: SIP/2.0/TCP 192.168.1.23:55934;branch=z9hG4bK-524287-1---104aee5ed0b7ca66;rport
   Max-Forwards: 70
   Contact: <sip:from_number@192.168.1.23:55934;transport=tcp>
   To: <sip:to_number@sometelco.com:5060>;tag=NjvKFKQaHp52e
   From: "from_number"<sip:from_number@sometelco.com:5060>;tag=47a61272
   Call-ID: 94385YTY3ODNlNzE1YjE5MmY4NmQ3ZWUyZDAzM2E0YzBkM2I
   CSeq: 1 ACK
   User-Agent: X-Lite release 5.4.0 stamp 94385
   Content-Length: 0
   ------------------------------------------------------------------------

Sounds

apt-get install python-software-properties
add-apt-repository ppa:freeswitch-drivers/freeswitch-nightly-drivers
apt-get update
apt-get install freeswitch freeswitch-lang-en freeswitch-sounds-en-us-callie-8000

User Registeration

List existing users

freeswitch@altanai-Inspiron-15-5578> list_users

userid|context|domain|group|contact|callgroup|effective_caller_id_name|effective_caller_id_number
1000|default|192.168.0.121|default|error/user_not_registered|techsupport|Extension 1000|1000
1001|default|192.168.0.121|default|error/user_not_registered|techsupport|Extension 1001|1001

There are many ways to register users for call

1. Add users to be registered

Goto folder /usr/local/freeswitch/conf/directory/ and vim default.xml

<include>
  <!--the domain or ip (the right hand side of the @ in the addr-->
  <domain name="$${domain}">
... 
<users>
      <user id="altanai">
        <params>
          <param name="password" value="$${default_password}"/>
          <param name="vm-password" value="1000"/>
        </params>
        <variables>
          <variable name="toll_allow" value="domestic,international,local"/>
          <variable name="accountcode" value="987"/>
          <variable name="user_context" value="video-mcu-stereo"/>
          <variable name="effective_caller_id_name" value="altanai"/>
          <variable name="outbound_caller_id_name" value="altanai_outbound"/>
        </variables>
      </user>
 </users>
..
  </domain>
</include>

2. Blind Registeration

Allow users to register with any username and password

Goto /usr/local/freeswitch/conf/sip_profiles/internal.xml and uncomment below snippet

    <!-- this lets anything register -->
    <!--  comment the next line and uncomment one or both of the other 2 lines for call authentication -->
    <param name="accept-blind-reg" value="true"/> 

    <!-- accept any authentication without actually checking (not a good feature for most people) -->
    <param name="accept-blind-auth" value="true"/>

3. Set a profile

Goto folder for freeswitch conf such as /usr/local/freeswitch/conf/directory/default

vim altanai.xml

and edit the variable

<include>
  <user id="altanai">
    <params>
      <param name="password" value="$${default_password}"/>
      <param name="vm-password" value="6000"/>
    </params>
    <variables>
      <variable name="toll_allow" value="domestic,international,local"/>
      <variable name="accountcode" value="6000"/>
      <variable name="user_context" value="default"/>
      <variable name="effective_caller_id_name" value="Extension 6000"/>
      <variable name="effective_caller_id_number" value="6000"/>
      <variable name="outbound_caller_id_name" value="$${outbound_caller_name}"/>
      <variable name="outbound_caller_id_number" value="$${outbound_caller_id}"/>
      <variable name="callgroup" value="developer"/>
    </variables>
  </user>
</include>

Rescan the profile

 sofia profile internal rescan reloadxml

Log Levels

log <loglevel> and nolog are used to enable and disable logging

fs_ctl

 fsctl loglevel alert

sofia level

sofia tracelevel  

[             console]	[               alert]	[                crit]	[                 err]	
[             warning]	[              notice]	[                info]	[               debug]	

References :


Kamailio Call routing and Control

Kamailio SIP server evolved from SER and OpenSER. Written in ANSI C , primarily it is an open source proxy SIP server. RFC 3261 compliant and has support for various Operating system to install and run on as alpine , centos , deb , fedora , freebsd , netbsd , obs , openbsd , opensuse , oracle , rhel , solaris so on .

With modular design it already has 150 + modules and can have third party addons like Databases , RTP engines etc. Anyone can contribute to extensions and modules read here. Also contains cmd line tool kamcmd , kamcli and Web management interface SIREMIS .

It has provisions for complex routing logic development through scripts and programming languages interpreter support.

Over the years kamailio as proven a key component of a “carrier-grade” SIP service delivery platform. Either as SBC interfacing internal softswitch with public internet and handling complex operation as NAT, auth , flood control, topology hiding etc or even as the core SIP Server handling RTP relay as well.

Kamailio’s call routing log can be divided into:

  • Core functions
  • Core modules needed for almost any useful configuration like transaction module , Record route module etc ( read more https://telecom.altanai.com/2014/11/18/kamailio-modules/)
  • Ancillary modules to provide specific functionality (e.g. JANSSON , PIKE)
  • Pseudo-variables , which hold read/writeable attributes and
  • Transformations and custom logic definition.

Kamailio config

kamailio confguration file should be composed of
Core configuration directives as

!ifdef WITH_MULTIDOMAIN
!define MULTIDOMAIN 1
!else
!define MULTIDOMAIN 0
!endif

Global Parameters like

memdbg=5
memlog=5
log_facility=LOG_LOCAL0
fork=yes
children=4

Loading Modules

loadmodule "corex.so"
loadmodule "tm.so"
loadmodule "tmx.so"
loadmodule "sl.so"
loadmodule "rr.so"

Module parameters
For example considering for tm auto-discard branches from previous serial forking leg as failure_reply_mode ,30 sec as default retransmission timeout with 120 sec as invite retransmission timeout after 1xx

modparam("tm", "failure_reply_mode", 3)
modparam("tm", "fr_timer", 30000)
modparam("tm", "fr_inv_timer", 120000)

Subroutines (in essence, SIP event callbacks):
Request routes (request_route)
Reply routes (onreply_route)
Failure routes (failure_route)
Branch routes

For example consider main sip routing block

request_route {
    route(REQINIT);
    route(NATDETECT);
    if (is_method("CANCEL"))
    {
        if (t_check_trans()) {
            route(RELAY);
        }
        exit;
    }
    route(WITHINDLG);
    t_check_trans();
    route(AUTH);
    if (is_method("INVITE|SUBSCRIBE"))
        record_route();
    route(SIPOUT);
    route(PRESENCE);
    route(REGISTRAR);
    ...
}

Custom event routes (callbacks/event handlers exposed by modules).
Code for programming languages and runtimes:
String transformations
Variables
Ephemeral/scratch-pad variables ($var(…))
Transaction-persistent variables ($avp(…)/$xavp(…)) , extended AVP like AVP ar attached to transactions and not messages .
Dialog-persistent variables ($dlg_var(…))

$var(rc) = $rc;
route(TOVOICEMAIL);
t_newtran();
switch ($var(rc)) {
    case -1:
    case -3:
        send_reply("404", "Not Found");
        exit;
    case -2:
        send_reply("405", "Method Not Allowed");
        exit;
}

This article describes call routing config for Kamailio under following roles

  • SIP Proxy
  • Registrar
  • Accountant
  • Session border Controller

Kamailio as Proxy Server

Simple Kamailio configuration with basic features like alias , accounting , record routing , handling SIP requests like INVITE and its replies . Also failure and NAT handling . More samples of Kamailio config and call routing are at https://github.com/altanai/kamailioexamples

#!KAMAILIO

#Defined Values
!substdef "!MY_IP_ADDR!!g"
!substdef "!MY_EXTERNAL_IP!!g"
!substdef "!MY_UDP_PORT!!g"
!substdef "!MY_TCP_PORT!!g"
!substdef "!MY_UDP_ADDR!udp:MY_IP_ADDR:MY_UDP_PORT!g"
!substdef "!MY_TCP_ADDR!tcp:MY_IP_ADDR:MY_TCP_PORT!g"
!define MULTIDOMAIN 0

; - flags
; 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
!define FLB_NATSIPPING 7

# Global Parameters
; LOG Levels:3 = DBG, 2 = INFO, 1 = NOTICE, 0 = WARN, -1 = ERR
debug = 2
log_stderror = no
memdbg = 5
memlog = 5
log_facility = LOG_LOCAL0
log_prefix = "{$mt $hdr(CSeq) $ci} "

/* number of SIP routing processes */
children = 2
/* uncomment the next line to disable TCP (default on) */
disable_tcp = yes
/* uncomment the next line to disable the auto discovery of local aliases based on reverse DNS on IPs (default on) */
auto_aliases = no

/* add local domain aliases */
alias = "sip.mydomain.com"

/* listen addresses */
listen = udp:127.0.0.1:5060
listen = MY_UDP_ADDR advertise MY_EXTERNAL_IP:MY_UDP_PORT
listen = MY_TCP_ADDR advertise MY_EXTERNAL_IP:MY_TCP_PORT

# Modules Section
loadmodule "jsonrpcs.so"
loadmodule "kex.so"
loadmodule "corex.so"
loadmodule "tm.so"
loadmodule "tmx.so"
loadmodule "sl.so"
loadmodule "rr.so"
loadmodule "pv.so"
loadmodule "maxfwd.so"
loadmodule "textops.so"
loadmodule "siputils.so"
loadmodule "xlog.so"
loadmodule "sanity.so"
loadmodule "ctl.so"
loadmodule "cfg_rpc.so"
loadmodule "acc.so"
loadmodule "counters.so"

----------------- setting module-specific parameters --------------

----- jsonrpcs params -----
modparam("jsonrpcs", "pretty_format", 1)
/* set the path to RPC fifo control file */
modparam("jsonrpcs", "fifo_name", "/var/run/kamailio/kamailio_rpc.fifo")
/* set the path to RPC unix socket control file */
modparam("jsonrpcs", "dgram_socket", "/var/run/kamailio/kamailio_rpc.sock")

; ----- ctl params -----
/* set the path to RPC unix socket control file */
modparam("ctl", "binrpc", "unix:/var/run/kamailio/kamailio_ctl")

; ----- 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)

; ----- 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)

----- acc params -----
; /* what special events should be accounted ? / modparam("acc", "early_media", 0) modparam("acc", "report_ack", 0) modparam("acc", "report_cancels", 0) / by default ww do
; not adjust the direct of the sequential requests.
; if you enable this parameter, be sure the enable "append_fromtag"
; in "rr" module / 
modparam("acc", "detect_direction", 0) / account triggers (flags) */
modparam("acc", "log_flag", FLT_ACC)
modparam("acc", "log_missed_flag", FLT_ACCMISSED)
modparam("acc", "log_extra",
"src_user=$fU;src_domain=$fd;src_ip=$si;"
"dst_ouser=$tU;dst_user=$rU;dst_domain=$rd")
modparam("acc", "failed_transaction_flag", FLT_ACCFAILED)

# Routing Logic

/* Main SIP request routing logic*/
request_route {
;     per request initial checks
    route(REQINIT);
    ; CANCEL processing
    if (is_method("CANCEL")) {
        if (t_check_trans()) {
            route(RELAY);
        }
        exit;
    }
    
    ; handle retransmissions
    if (!is_method("ACK")) {
        if (t_precheck_trans()) {
            t_check_trans();
            exit;
        }
        t_check_trans();
    }

    ; handle requests within SIP dialogs
    route(WITHINDLG);
    ;     only initial requests (no To tag)
    ; record routing for dialog forming requests ( in case they are routed)
    ; - remove preloaded route headers
    remove_hf("Route");
    if (is_method("INVITE|SUBSCRIBE")) {
        record_route();
    }
    
    ;     account only INVITEs
    if (is_method("INVITE")) {
        setflag(FLT_ACC); # do accounting
    }
    
    if ($rU==$null) {
        # request with no Username in RURI
        sl_send_reply("484", "Address Incomplete");
        exit;
    }

    # update $du to set the destination address for proxying
    $du = "sip:" + $rd + ":9";
    route(RELAY);
    exit;
}

# Wrapper for relaying requests
route[RELAY] {
    if (is_method("INVITE|BYE|SUBSCRIBE|UPDATE")) {     
        if (!t_is_set("branch_route")) 
            t_on_branch("MANAGE_BRANCH");
    }

    if (is_method("INVITE|SUBSCRIBE|UPDATE")) {     
        if (!t_is_set("onreply_route")) 
            t_on_reply("MANAGE_REPLY");
    }

    if (is_method("INVITE")) {
        if (!t_is_set("failure_route")) 
            t_on_failure("MANAGE_FAILURE");
    }

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

#P er SIP request initial checks
route[REQINIT] {
    if ($ua = ~ "friendly-scanner|sipcli|VaxSIPUserAgent") {
        # sl_send_reply("200", "OK");
        exit;
    }
    
    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 (loose_route()) {
        if (is_method("BYE")) {
            setflag(FLT_ACC); # do accounting ...         
            setflag(FLT_ACCFAILED); # ... even if the transaction fails
        } else{
            if (is_method("NOTIFY")) {
                # Add Record-Route for in -dialog NOTIFY as per RFC 6665.         
                record_route();
            }
            route(RELAY);
            exit;
        }
    }   

    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         
            route(RELAY);
            exit;
        } else {
            # ACK without matching transaction, ignore and discard         
            exit;
        }
    } 
    
    sl_send_reply("404", "Not here"); exit;

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




Controlling Call Routing from command Line

To find the loaded flags while starting kamailio

kamailio -v
version: kamailio 5.1.8 (x86_64/linux) d8e930
flags: STATS: Off, USE_TCP, USE_TLS, USE_SCTP, TLS_HOOKS, USE_RAW_SOCKS, DISABLE_NAGLE, USE_MCAST, DNS_IP_HACK, SHM_MEM, SHM_MMAP, PKG_MALLOC, Q_MALLOC, F_MALLOC, TLSF_MALLOC, DBG_SR_MEMORY, USE_FUTEX, FAST_LOCK-ADAPTIVE_WAIT, USE_DNS_CACHE, USE_DNS_FAILOVER, USE_NAPTR, USE_DST_BLACKLIST, HAVE_RESOLV_RES
ADAPTIVE_WAIT_LOOPS=1024, MAX_RECV_BUFFER_SIZE 262144 MAX_URI_SIZE 1024, BUF_SIZE 65535, DEFAULT PKG_SIZE 8MB
poll method support: poll, epoll_lt, epoll_et, sigio_rt, select.
id: d8e930 
compiled on 09:47:09 May  3 2019 with gcc 4.8.4

kamdbctl

creates the database support for many kamailio modules such as auth , location , dispatcher , permission etc

make sure you load a DB engine , during kamailio installation and configuration . It can be either done though make command or though modules.lst file

 make include_modules="db_mysql" cfg
 make all
 make install

since json replaced all fifo command, ensure you do not get "json.h: No such file or directory” in server by install json either via libjson-c-dev or libjson-cpp-dev

apt-get install libjson-c-dev 

For uuid/uuid.h: No such file or directory install

apt-get install uuid-dev

For libpq-fe.h: No such file or directory install

apt-get install libpq-dev

kamdbctl command list

kamdbctl create <db name or db_path, optional> ...(creates a new database)
kamdbctl drop <db name or db_path, optional> .....(!entirely deletes tables!)
kamdbctl reinit <db name or db_path, optional> ...(!entirely deletes and than re-creates tables!)
kamdbctl backup <file> ...........................(dumps current database to file)
kamdbctl restore <file> ..........................(restores tables from a file)
kamdbctl copy <new_db> ...........................(creates a new db from an existing one)
kamdbctl presence ................................(adds the presence related tables)
kamdbctl extra ...................................(adds the extra tables)
kamdbctl dbuid ...................................(adds the uid tables)
kamdbctl dbonly ..................................(creates empty database)
kamdbctl grant ...................................(grant privileges to database)
kamdbctl revoke ..................................(revoke privileges to database)
kamdbctl add-tables <gid> ........................(creates only tables groupped in gid)

if you want to manipulate database as other database user than
root, want to change database name from default value "kamailio",
or want to use other values for users and password, edit the
"config vars" section of the command kamdbctl.

kamdbctl pframework create .......................(creates a sample provisioning framework file)

For psql: received invalid response to SSL negotiation: [
ERROR: Creating database failed!
errors . Remember for mysql the defaul port is 3306, but for psql it is 5432 . Hence make the change in /etc/kamailio/kamctlrc

database port
DBPORT=3306
DBPORT=5432  

Kamctl

If kamctl isnt accessible from the machine installed with kamailio , just goto kamctl folder and compile it yourself . For example for me , I took the git pull of kamailio source code v 5.1.0 and went to util folder

cd  /kamailio_source_code/utils/kamctl 
make && make install 

some commands

‘start|stop|restart|trap’
‘acl’ – manage access control lists (acl)
‘lcr’ – manage least cost routes (lcr)
‘cr’ – manage carrierroute tables show|reload|dump
‘rpid’ – manage Remote-Party-ID (RPID)
‘add|passwd|rm’ – manage subscribers
‘add|dump|reload|rm|show’ – manage trusted
‘add|dump|reload|rm|show’ – manage address
‘add|dump|reload|rm|show’ – manage address
‘dispatcher’ – manage dispatcher

dispatcher add 1 sip:1.2.3.1:5050 1 5 'prefix=proxycall' 'gatewaye33'

‘dialog’ – manage dialog records
‘srv’ – server management commands
‘cisco_restart’ – restart CISCO phone (NOTIFY)
‘online’ – dump online users from memory
‘monitor’ – show internal status

[cycle #: 3; if constant make sure server lives]
Kamailio Runtime Details: 
kamailio 5.1.8 (x86_64/linux) d8e930
    now:  Fri May 24 13:39:19 2019
    up_since: Fri May 24 13:31:37 2019
    uptime: 462

Transaction Statistics: 
    tmx:UAS_transactions = 0        tmx:UAC_transactions = 0        tmx:active_transactions = 0     tmx:inuse_transactions = 0

Stateless Server Statistics: 
    sl:sent_replies = 0            sl:sent_err_replies = 0

UsrLoc Statistics: 
    usrloc:location-contacts = 0        usrloc:location-expires = 0         usrloc:location-users = 0           usrloc:registered_users = 0

Core Statistics: 
    core:rcv_requests = 0        core:fwd_requests = 0       core:rcv_replies = 0        core:fwd_replies = 0

Shared Memory Statistics: 
    shmem:fragments = 1                shmem:max_used_size = 2807640       shmem:total_size = 67108864
    shmem:free_size = 64301224            shmem:real_used_size = 2807640      shmem:used_size = 2566040

‘ping’ – ping a SIP URI (OPTIONS)
‘ul|alias’ – manage user location or aliases
‘ps’ – print details about running processes
‘ps’ – print details about running processes
‘stats’ – print internal statistics

{
  "jsonrpc":  "2.0",
  "result": [
    "core:bad_URIs_rcvd = 0",
    "core:bad_msg_hdr = 0",
    "core:drop_replies = 0",
    "core:drop_requests = 0",
    "core:err_replies = 0",
    "core:err_requests = 0",
    "core:fwd_replies = 0",
    "core:fwd_requests = 0",
    "core:rcv_replies = 0",
    "core:rcv_replies_18x = 0",
    "core:rcv_replies_1xx = 0",
    "core:rcv_replies_2xx = 0",
    "core:rcv_replies_3xx = 0",
    "core:rcv_replies_401 = 0",
    "core:rcv_replies_404 = 0",
    "core:rcv_replies_407 = 0",
    "core:rcv_replies_480 = 0",
    "core:rcv_replies_486 = 0",
    "core:rcv_replies_4xx = 0",
    "core:rcv_replies_5xx = 0",
    "core:rcv_replies_6xx = 0",
    "core:rcv_requests = 0",
    "core:rcv_requests_ack = 0",
    ...
}

‘rpc’ – send raw RPC commands

Kamcmd

unix tool for interfacing with Kamailio using exported RPCs. It uses binrpc (a proprietary protocol, designed for minimal packet size and fast parsing) over a variety of transports (unix stream sockets, unix datagram sockets, udp or tcp).

 cfg.add_group_inst
 cfg.commit
 cfg.del
 cfg.del_delayed
 cfg.del_group_inst
 cfg.diff
 cfg.get
 cfg.help
 cfg.list
 cfg.reset
 cfg.rollback
 cfg.set
 cfg.set_delayed
 cfg.set_delayed_int
 cfg.set_delayed_string
 cfg.set_now_int
 cfg.set_now_string
 cfg.seti
 cfg.sets
 cnt.get
 cnt.get_raw
 cnt.get_vars
 cnt.grp_get_all
 cnt.grps_list
 cnt.help
 cnt.list_groups
 cnt.list_vars
 cnt.reset
 cnt.var_list
 core.aliases_list
 core.arg
 core.echo
 core.flags
 core.info
 core.kill
 core.modules
 core.ppdefines
 core.printi
 core.prints
 core.ps
 core.psx
 core.pwd
 core.shmmem
 core.sockets_list
 core.tcp_info
 core.tcp_list
 core.tcp_options
 core.udp4_raw_info
 core.uptime
 core.version
 corex.debug
 corex.list_aliases
 corex.list_sockets
 corex.pkg_summary
 corex.shm_status
 corex.shm_summary
 ctl.connections
 ctl.listen
 ctl.who
 dns.add_a
 dns.add_aaaa
 dns.add_srv
 dns.debug
 dns.debug_all
 dns.delete_a
 dns.delete_aaaa
 dns.delete_all
 dns.delete_all_force
 dns.delete_cname
 dns.delete_ebl
 dns.delete_naptr
 dns.delete_ptr
 dns.delete_srv
 dns.delete_txt
 dns.lookup
 dns.mem_info
 dns.view
 dst_blacklist.add
 dst_blacklist.debug
 dst_blacklist.delete_all
 dst_blacklist.mem_info
 dst_blacklist.view
 jsonrpc.echo
 mod.stats
 pkg.stats
 pv.shvGet
 pv.shvSet
 sl.stats
 stats.clear_statistics
 stats.fetch
 stats.get_statistics
 stats.reset_statistics
 system.listMethods
 system.methodHelp
 system.methodSignature
 tm.cancel
 tm.clean
 tm.hash_stats
 tm.list
 tm.reply
 tm.reply_callid
 tm.stats
 tm.t_uac_start
 tm.t_uac_wait
 ul.add
 ul.db_contacts
 ul.db_expired_contacts
 ul.db_users
 ul.dump
 ul.flush
 ul.lookup
 ul.rm
 ul.rm_contact
 alias: ps
 alias: psx
 alias: list
 alias: ls
 alias: ver
 alias: version
 alias: who
 alias: listen
 alias: dns_mem_info
 alias: dns_debug
 alias: dns_debug_all
 alias: dst_blacklist_mem_info
 alias: dst_blacklist_debug
 builtin: ?
 builtin: help
 builtin: version
 builtin: quit
 builtin: exit
 builtin: warranty
 builtin: license

some examples of the kamcmd commands

stats

> kamctl kamcmd 
tm.stats 
{     
current: 0     
waiting: 0     
total: 0     
total_local: 0     
rpl_received: 0     
rpl_generated: 0     
rpl_sent: 0     
6xx: 0     
5xx: 0     
4xx: 0     
3xx: 0     
2xx: 0     
created: 0     
freed: 0     
delayed_free: 0 
}

Get info about TLS

kamcmd> tls.info
{
    max_connections: 2048
    opened_connections: 1
    clear_text_write_queued_bytes: 0
}

Get info about open sockets

kamcmd> core.sockets_list
{
    socket: {
        proto: udp
        address: 1.2.3.4
        port: 5060
        mcast: no
        mhomed: no
    }
    socket: {
        proto: tcp
        address:  1.2.3.4
        port: 5060
        mcast: no
        mhomed: no
    }
    socket: {
        proto: tcp
        address:  1.2.3.4
        port: 80
        mcast: no
        mhomed: no
    }
    socket: {
        proto: tls
        address:  1.2.3.4
        port: 5061
        mcast: no
        mhomed: no
    }
    socket: {
        proto: tls
        address:  1.2.3.4
        port: 443
        mcast: no
        mhomed: no
    }
}

get core info

kamcmd > core.info
{
    version: kamailio 5.2.3
    id: 4a4588 
    compiler: gcc 5.4.0
    compiled: 15:54:50 Jun 27 2019
    flags: STATS: Off, USE_TCP, USE_TLS, USE_SCTP, TLS_HOOKS, USE_RAW_SOCKS, DISABLE_NAGLE, USE_MCAST, DNS_IP_HACK, SHM_MEM, SHM_MMAP, PKG_MALLOC, Q_MALLOC, F_MALLOC, TLSF_MALLOC, DBG_SR_MEMORY, USE_FUTEX, FAST_LOCK-ADAPTIVE_WAIT, USE_DNS_CACHE, USE_DNS_FAILOVER, USE_NAPTR, USE_DST_BLACKLIST, HAVE_RESOLV_RES
}

SIP VoIP system architecture basics


A VOIP/CPaaS solution is designed to accommodate the signalling and media both along with integration leads to various external endpoints such as various SIP phones ( desktop, softphones, webRTC ), telecom carriers, different VoIP networks providers, enterprise applications ( Skype, Microsoft Lync ), Trunks etc.

A sufficiently capable SIP platform should have

  1. Audio calls ( optionally video ) service using SIP gateways
  2. Media services (such as recording , conferencing, voicemail, and IVR )
  3. Messaging and presence ( could be using SIP SIMPLE, SMS , messahing service from third parties)
  4. Developing SIP based applications : Programmable services through standardized APIs and development of new modules
  5. NAT and DNS near-end and far-end NAT traversal for signalling and media flows
  6. Telemetry for Sessions , Registry, Location and lookup service
  7. CDR Processing and Billing : Backend for CDR and accounts ( can use Redis, Kafka , MySQL, PostgreSQL, Oracle, Radius, LDAP, Diameter)
  8. Serial and parallel forking, load balancing , proxying
  9. Cross platform and integration to External Telecommunication provider landscape
    • Interconnectivity with other IP multimedia systems, VoLTE ( optional interconnection with other types of communications networks as GSM or PSTN/ISDN).
    • support for VoIP signalling protocols (SIP, H,323, SCCP, MGCP, IAX) and telephony signalling protocols ( ISDN/SS7, FXS/FXO, Sigtran ) either internally via pluggable modules or externally via gateways .
Performnace factors :Security considerations :
High availability using redundant servers in standby
Load balancing
IPv4 and IPv6 network layer support
TCP , UDP , SCTP transport layer protocol support
DNS lookups and hop by hop connectvity
authentication, authorization, and accounting (AAA)
Digest authentication and credentials fetched from backend
Media Encryption
TLS and SRTP support
Topology hidding to prevent disclosing IP form internal components in via and route headers
Firewalls , blacklist, filters , peak detectors to prevent Dos and Ddos attacks

The article only outlines SIP system architecture  from 3 viewpoints :

  1. Infrastructure standpoint
  2. Vore voice engineering perspective
  3. External components required to run and system

Infrastructure Requirements

  • Data Centers with BCP ( Business Continuity Planning ) and DR ( Disaster Recovery )
  • Servers and Clusters for faster and parallel calculating
  • Virtualization
    VMs to make a distributed computing environment with HA ( high availability ) and DRS ( Distributed Resource Scheduling )
  • Storage
    SAN with built-in redundancy for the resiliency of data.
    WORM compliant NAS for storing voice archives over a retention period.
  • Racks, power supplies, battery backups, cages etc.
  • Networking
    DMZs ( Demilitarized Zones)  which are interfacing areas between internal servers in the green zone and outside network
    VLANs for segregation between tenants.
    Connectivity through the public Internet as well as through VPN or dedicated optical fibre network for security.
  • Firewall configuration
  • Load Balancer ( Layer 7 )
  • Reverse Proxies for the security of internal IPs and port
  • Security controls In compliance with ISO/IEC 27000 family – Information security management systems
  • PKI Infrastructure to manage digital certificates
  • Key management with HSM ( hardware security module )
  • truster CA ( Certificate Authority ) to issue publicly signed certificate for TLS ( Https, wss etc)
  • OWASP ( Open Web Application Security Project )  rules compliance

Integral Components of a VOIP SIP based architecture

  • Call Controller
  • Media Manager
  • Recording
  • Softclients
  • logs and PCAP archives
  • CDR generators
  • Session Borer Controllers ( SBCs)

A SIP server can be moulded to take up any role based on the libraries and programs that run on it such as gateway server, call manager, load balancer etc. This in turn defines its placement in overall VoIP communication architecture. For example
– stateless proxy servers are placed on the border,
– application and B2BUA server at the core

sip entities
SIP platform components

SIP Gateways

A SIP gateway is an application that interfaces a SIP network to a network utilising another signalling protocol. In terms of the SIP protocol, a gateway is just a special type of user agent, where the user agent acts on behalf of another protocol rather than a human. A gateway terminates the signalling path and can also terminate the media path .

sip gaeways
To PSTN for telephony inter-working
To H.323 for IP Telephony inter-working
Client – originates message
Server – responds to or forwards message

Logical SIP entities are:

  • User Agent Client (UAC): Initiates SIP requests  ….
  • User Agent Server (UAS): Returns SIP responses ….
  • Network Servers ….

Registrar Server

A registrar server accepts SIP REGISTER requests; all other requests receive a 501 Not Implemented response. The contact information from the request is then made available to other SIP servers within the same administrative domain, such as proxies and redirect servers. In a registration request, the To header field contains the name of the resource being registered, and the Contact header fields contain the contact or device URIs.

regsitrar server

Proxy Server

A SIP proxy server receives a SIP request from a user agent or another proxy and acts on behalf of the user agent in forwarding or responding to the request. Just as a router forwards IP packets at the IP layer, a SIP proxy forwards SIP messages at the application layer.

Typically proxy server ( inbound or outbound) have no media capabilities and ignore the SDP . They are mostly bypassed once dialog is established but can add a record-route .
A proxy server usually also has access to a database or a location service to aid it in processing the request (determining the next hop).

proxy server

 1. Stateless Proxy Server
A proxy server can be either stateless or stateful. A stateless proxy server processes each SIP request or response based solely on the message contents. Once the message has been parsed, processed, and forwarded or responded to, no information (such as dialog information) about the message is stored. A stateless proxy never retransmits a message, and does not use any SIP timers

2. Stateful Proxy Server
A stateful proxy server keeps track of requests and responses received in the past, and uses that information in processing future requests and responses. For example, a stateful proxy server starts a timer when a request is forwarded. If no response to the request is received within the timer period, the proxy will retransmit the request, relieving the user agent of this task.

  3 . Forking Proxy Server
A proxy server that receives an INVITE request, then forwards it to a number of locations at the same time, or forks the request. This forking proxy server keeps track of each of the outstanding requests and the response. This is useful if the location service or database lookup returns multiple possible locations for the called party that need to be tried.

Redirect Server

A redirect server is a type of SIP server that responds to, but does not forward, requests. Like a proxy server, a redirect server uses a database or location service to lookup a user. The location information, however, is sent back to the caller in a redirection class response (3xx), which, after the ACK, concludes the transaction. Contact header in response indicates where request should be tried .

redirect server

Application Server

The heart of all call routing setup. It loads and executes scripts for call handling at runtime and maintains transaction states and dialogs for all ongoing calls . Usually the one to rewrite SIP packets adding media relay servers, NAT . Also connects external services like Accounting , CDR , stats to calls .

Adding Media Management

Media processing is usually provided by media servers in accordance to the SIP signalling. Bridges, call recording, Voicemail, audio conferencing, and interactive voice response (IVR) are commomly used. Read more about Media Architecture here

RFC 6230 Media Control Channel Framework decribes framework and protocol for application deployment where the application programming logic and media processing are distributed.

Any one such service could be a combination of many smaller services within such as Voicemail is a combitional of prompt playback, runtime controls, Dual-Tone Multi-Frequency (DTMF) collection, and media recording. RFC 6231 Interactive Voice Response (IVR) Control Package for the Media Control Channel Framework.

DTMF( Dual tone Multi Frequency )

delivery options:

  • Inband –  With Inband digits are passed along just like the rest of your voice as normal audio tones with no special coding or markers using the same codec as your voice does and are generated by your phone.
  • Outband  – Incoming stream delivers DTMF signals out-of-audio using either SIP-INFO or RFC-2833 mechanism, independently of codecs – in this case, the DTMF signals are sent separately from the actual audio stream.

TTS ( Text to Speech )

 Alexa Text-to-Speech (TTS) + Amazon Polly

Ivona – multiple language text to speech converter with ssml scripts such as below

      <speak>
          <p>
              <s><prosody rate="slow">IVONA</prosody> means highest quality speech
              synthesis in various languages.</s>
              <s>It offers both male and female radio quality voices <break/> at a
              sampling rate of 22 kHz <break/> which makes the IVONA voices a
              perfect tool for professional use or individual needs.</s>
          </p>
      </speak>

check ivona status

service ivona-tts-http status
 tail -f /var/log/tts.log

Developing SIP based applications

Basic SIP methods

SIP defines basic methods such as INVITE, ACK and BYE which can pretty much handle simple call routing with some more advanced processoes too like call forwarding/redirection, call hold with optional Music on hold, call parking, forking, barge etc.

Extending SIP headers

Newer SIP headers defined by more updated SIP RFC’s contina INFO, PRACK, PUBLISH, SUBSCRIBY, NOTIFY, MESSAGE, REFER, UPDATE. But more methods or headers can be added to baseline SIP packets for customization specific to a particular service provider. In case where a unrecognized SIP header is found on a SIP proxy which it either does not suppirt or doesnt understand, it will simply forward it to the specified endpoint.

Call routing Scripts

Interfaces for programming SIP call routing include :
– Call Processing Language—SIP CPL,
– Common Gateway Interface—SIP CGI,
– SIP Servlets,
– Java API for Integrated Networks—JAIN APIs etc .

Some known SIP stacks :

SailFin – SIP servlet container uses GlassFish open source enterprise Application Server platform (GPLv2), obsolete since merger from Sun Java to Oracle.

Mobicents – supports both JSLEE 1.1 and SIP Servlets 1.1 (GPLv2)

Cipango – extension of SIP Servlets to the Jetty HTTP Servlet engine thus compliant with both SIP Servlets 1.1 and HTTP Servlets 2.5 standards.

WeSIP – SIP and HTTP ( J2EE) converged application server build on OpenSER SIP platform

Additionally SIP stacks are supported on almost all popular SIP programming lanaguges which can be imported as lib and used for building call routing scripts to be mounted on SIP servers or endpoints such as :

PJSIP in C

JSSIP Javascript

Sofia in kamailio , Freswitch

Some popular SIP server also have proprietary scripting language such as –
Asterisk Gateway Interface (AGI) , application interface for extending the dialplan with your functionality in the language you choose – PHP, Perl, C, Java, Unix Shell and others

SIP platform Development

  • audio calls ( optionally video )
  • media services such as conferencing, voicemail, and IVR,
  • messaging as IM and presence based on SIMPLE,
  • programmable services through standardized APIs and development of new modules
  • near-end and far-end NAT traversal for signalling and media flows
  • interconnectivity with other IP multimedia systems, VoLTE ( optional interconnection with other types of communications networks as GSM or PSTN/ISDN)
  • Registry, location and lookup service
  • Serial and parallel forking

A sufficiently capable SIP platform shoudl consist of following features :

Performance factors :

  • High availability using redundant servers in standby
  • Load balancing
  • IPv4 and IPv6 support

Security considerations :

  • digest authentication and credentials fetched from backend
  • Media Encryption
  • TLS and SRTP support
  • Topology hiding to prevent disclosng IP form internal components in via and route headers
  • Firewalls , blacklist, filters , peak detectors to prevent Dos and Ddos attacks .

Collecting and Processing PCAPS

  • VoIP monitor – network packet sniffer with commercial frontend for SIP RTP RTCP SKINNY(SCCP) MGCP WebRTC VoIP protocols

it uses a passive network sniffer (like tcpdump or wireshark) to analyse packets in realtime and transforms all SIP calls with associated RTP streams into database CDR record which is sent over the TCP to MySQL server (remote or local). If enabled saving SIP / RTP packets the sniffer stores each VoIP call into separate files in native pcap format (to local storage).

voip monitor
  • sngrep
  • tcpdump
  • custom made pcap capture and uploader

NAT and DNS

To adapt SIP to modern IP networks with inter network traversal ICE, far and near-end NAT traversal solutions are used. Network Address traversal is crtical to traffic flow between private public network and from behind firewalls and policy controlled networks
One can use any of the VOVIDA-based STUN server, mySTUN , TurnServer, reStund , CoTURN , NATH (PJSIP NAT Helper), ReTURN, or ice4j

Near-end NAT traversal

STUN (session traversal utilities for NAT) – UA itself detect presence of a NAT and learn the public IP address and port assigned using Nating. Then it replaces device local private IP address with it in the SIP and SDP headers. Implemented via STUN, TURN, and ICE.
limitations are that STUN doesnt work for symmetric NAT (single connection has a different mapping with a different/randomly generated port) and also with situations when there are multiple addresses of a end point.

TURN (traversal using relay around NAT) or STUN relay – UA learns the public IP address of the TURN server and asks it to relay incoming packets. Limitatiosn since it handled all incoming and outgong traffic, it must scale to meet traffic requirments and should not become the bottle neck junction or single point of failure.

ICE (interactive connectivity establishment) – UA gathers “candidates of communication” with priorities offered by the remote party. After this client pairs local candidates with received peer candidates and performs offer-answer negotiating by trying connectivity of all pairs, therefore maximising success. The types of candidates :
– host candidate who represents clients’ IP addresses,
– server reflexive candidate for the address that has been resolved from STUN
– and a relayed candidate for the address which has been allocated from a TURN relay by the client.

Far-end NAT traversal

UA is not concerned about NAT at all and communicated using its local IP port. The border controller implies a NAT handling components such as an application layer gateway (ALG) or universal plug and play (UPnP) etc which resolves the private and public network address mapping by act as a back to back user agent (B2BUA).
Far end NAT can also be enabled by deploying a public SIP server which performs media relay (RTP Proxy/Media proxy).

Limitations of this approach
(-) security risks as they are operating in the public network
(-) enabling reverse traffic from UAS to UAC behind NAT.

A keep-alive mechanism is used to keep NAT translations of communications between SIP endpoint and its serving SIP servers opened , so that this NAT translation can be reused for routing. It contains client-to-server “ping” keep-alive and corresponding server-to-client “pong” messages. The 2 keep-alive mechanisms: a CRLF keep-alive and a STUN keep-alive message exchange.

The 3 types of SIP URIs,

  • address of record (AOR)
  • fully qualified domain name (FQDN)
  • globally routable user agent (UA) URI
    SIP uniform resource identifiers (URIs) are identified based on DNS resolution since the URI after @ symbol contains hostname , port and protocl for the next hop.

Adding record route headers for locating the correct SIP server for a SIP message can be done by :
– DNS service record (DNS SRV)
– naming authority pointer (NAPTR) DNS resource record

Steps for SIP endpoints locating SIP server

  1. From SIP packet get the NAPTR record to get the protocl to be used
  2. Inspect SRV record to fetch port to use
  3. Inspect A/AAA record to get IPv4 or IPv6 addresses
    ref : RFC 3263 – Locating SIP Servers
    Can use BIND9 server for DNS resolution supports NAPTR/SRV, ENUM, DNSSEC, multidomains, and private trees or public trees.

CDR Processing and Billing

CDR store call detail records along with proof of call with tiemstamps, orignation, destination, duaration, rate etc. At the end of month or any other term, the aggregated CDR are cumulatively processed to generate the bill for a user. This heavy data stream needs to be accurately processed and this can be achived by using data-pipelines like AWS kinesis or Kafka eventstore.

The prime requirnment for the system is to handle enormous amount of call records data in relatime , cater to a number of producers and consumers.

For security the data is obfuscated into blob using base 64 encoding.

For good consistency only a single shard should be rsponsible to process one user account’s bill.

Data Streams for billing service

AWS Kinesis – Kinesis Data Streams is sued for for rapid and continuous data intake and aggregation. The type of data used can include IT infrastructure log data, application logs, social media, market data feeds, and web clickstream data. It supports data sharding (ie number of call records grouped) and uses a partition Key ( string MD5 hash) to determine which shard the record goes to. 

(+) This system can handle high volume of data in realtime and produce call uuid specfic reults which can be consumed by consumers waiting for the processed results

(-) If not consumed with a pre-specified time duration the processed results expire and are irretrivable . Self implement publisher to store teh processed reults from kisesis stream to data stores like Redis / RDBMS or other storge locations like s3 , dynamo DB. If pieline crashes during operation , data is lost

(-) Data stream should have low latency igesting contnous data from producer and presenting data to consumer.

Call Rate and Accounting

Generally data streams proecssing are used for crtical and voluminious service usage like for
– metering/billing
– server activity,
– website clicks,
– geo-location of devices, people, and physical goods

Call Rates are very crticial for billing and charging the calls . Any updates from the customer or carriers or individuals need to propagate automatically and quickly to avoid discrpencies and neagtive margins. CDRs need to be processed sequentially and incrementally on a record-by-record basis or over sliding time windows, and used for a wide variety of analytics including correlations, aggregations, filtering, and sampling.

To acheieve this the follow setup is ideal to use the new input rate sheet values via web UI console or POST API and propagate it quickly to main DB via AWS SQS which is a queing service and AWS lamda which is a serverless trigger based system . This ensures that any new input rates are updates in realtime and maintin fallback values in s3 bucket too

Call Rate and Accounting using task pipes , lambda serverless and qiueing service. Uses s3 buckets , AWS lambda, AWS SQS and AWS RDS.
Call Rate and Accounting using task pipes , lambda serverless and qiueing service

Cross platform and integration to External Telecommunication provider landscape

It is an advantage to plan for ahead for connection with IMS such as openIMS, support for Voip signalling protocols (SIP, H,323, SCCP, MGCP, IAX) and telephony signalling protocls ( ISDN/SS7, FXS/FXO, Sigtran ) either internally via pluggable modules or externally via gateways or for SIP trunking integration via OTT providers/ cloud telephony.

Adhere to Standard

The obvious starting milestone before making a full-scale carrier-grade, SIP-based VoIP system is to start by building a PBX for intra-enterprise communication. There are readily available solutions to make an IP telephony PBX Kamailio, FreeSWITCH, asterisk, Elastix, SipXecs. It is important to use the standard protocol and widely acceptable media formats and codecs to ensure interoperability and reduce compute and delay involved in protocol or media transcoding.

Database Integration

Need backend , cache , databse integration to npt only store routing rules with temporary varaible values but also aNeed backend, cache, database integration to not only store routing rules with temporary variable values but also account details, call records details, access control lists etc. Should therefore extend integration with text-based DB, Redis, MySQL, PostgreSQL, OpenLDAP, and OpenRadius.

Consistency of Call Records and duplicated charging records at various endpoints

In current Voip scenarios a call may be passing thorugh various telco providers , ISP and cloud telephony serviIn current VoIP scenarios, a call may be passing through various telco providers, ISP and cloud telephony service providers where each system maintains its own call records and billing. This in my opinion is duplication and can be avoided by sharing a consistent data store possible in the blockchain. This is an experimental idea that I have further explored in this article


There are other external components to setup a VOIP solution apart from Core voice Servers and gateways like the ones listed below, I will try to either add a detailed overall architecture diagram here or write about them in an seprate article. Keep watching this space for updates

  • Payment Gateways
  • Billing and Invoice
  • Fraud Prevention
  • Contacts Integration
  • Call Analytics
  • API services
  • Admin Module
  • Number Management ( DIDs ) and porting
  • Call Tracking
  • Single Sign On and User Account Management with Oauth and SAML
  • Dashboards and Reporting
  • Alert Management
  • Continuous Deployment
  • Automated Validation
  • Queue System
  • External cache

References :

SIP solutioning and architectures is a subsequent article after SIP introduction, which can be found here.

Read about VoIP/ OTT / Telecom Solution startup’s strategy for Building a scalable flexible SIP platform which includes :

  • Scalable and Flexible SIP platform building
  • Cluster SIP telephony Server for High Availability
  • Failure Recovery
  • Multi-tier cluster architecture
  • Role Abstraction / Micro-Service based architecture
  • Distributed Event management and Event-Driven architecture
  • Containerization
  • Autoscaling Cloud Servers
  • Open standards and Data Privacy
  • Flexibility for inter-working – NextGen911 , IMS , PSTN
  • security and Operational Efficiencies