Category Archives: Session Initiation Prot. (SIP)

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 – http://www.brekeke.com/sip/ .

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 http://www.brekeke.com/sip/ and run the setup file .

brekeke0

brekeke01

brekeke1

brekeke8

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 127.0.0.1 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 http://www.brekeke.com/downloads/sip-server-trial-license.phpbrekeke12_001

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

Advertisements

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.

The first set 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

Parameters:

nat_bflag
user_column
domain_column
contact_column
expires_column
q_column
callid_column
cseq_column
methods_column
flags_column
cflags_column
user_agent_column
received_column
socket_column
path_column
ruid_column
instance_column
server_id_column
connection_id_column
keepalive_column
partition_column
use_domain
desc_time_order
timer_interval
db_url
db_mode
db_load
db_insert_update
matching_mode
cseq_delay
fetch_rows
hash_size
preload
db_update_as_insert
db_check_update
timer_procs
xavp_contact
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.dump
ul.lookup table AOR
ul.rm table AOR
ul.rm_contact table AOR contact
ul.flush
ul.add
ul.db_users
ul.db_contacts
ul.db_expired_contacts

Statistics

users
contacts
expires
registered_users

Functions

ul_register_domain(name)
ul_insert_urecord(domain, aor, rec)
ul_delete_urecord(domain, aor)
ul_delete_urecord_by_ruid(domain, ruid)
ul_get_urecord(domain, aor)
ul_lock_udomain(domain)
ul_unlock_udomain(domain)
ul_release_urecord(record)
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)
ul_get_num_users()

Registrar

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 :

default_expires
default_expires_range
expires_range
min_expires
max_expires
default_q
realm_prefix
append_branches
aor_avp (str)
case_sensitive
received_avp (str)
received_param
max_contacts
retry_after
sock_flag
sock_hdr_name
method_filtering
use_path
path_mode
path_use_received
path_check_local
reg_callid_avp
xavp_cfg
xavp_rcd
gruu_enabled
outbound_mode
regid_mode
flow_timer
contact_max_size

Functions :

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

Event Routes :

event_route[usrloc:contact-expired]

Statistics :

max_expires
max_contacts
default_expires
accepted_regs
rejected_regs

http://kamailio.org/docs/modules/stable/modules/registrar.html

Dialog

Dialog support module

Parameters :

enable_stats
hash_size
rr_param
dlg_flag
timeout_avp
default_timeout
early_timeout
noack_timeout
end_timeout
dlg_extra_hdrs
dlg_match_mode
detect_spirals
db_url
db_mode
db_update_period
db_fetch_rows
db_skip_load
table_name
call_id_column
from_uri_column
from_tag_column
to_uri_column
to_tag_column
from_cseq_column
to_cseq_column
from_route_column
to_route_column
from_contact_column
to_contact_column
from_sock_column
to_sock_column
h_id_column
h_entry_column
state_column
start_time_column
timeout_column
sflags_column
toroute_name_column
vars_table_name
vars_h_id_column
vars_h_entry_column
vars_key_column
vars_value_column
profiles_with_value
profiles_no_value
bridge_controller
bridge_contact
initial_cbs_inscript
send_bye
wait_ack
ka_timer
ka_interval
ka_failed_limit
timeout_noreset
timer_procs
enable_dmq
track_cseq_updates
lreq_callee_headers
event_callback (str)

Functions :

set_dlg_profile(profile,[value])
unset_dlg_profile(profile,[value])
is_in_profile(profile,[value])
get_profile_size(profile,[value],size)
dlg_isflagset(flag)
dlg_setflag(flag)
dlg_resetflag(flag)
dlg_bye(side)
dlg_refer(side, address)
dlg_manage()
dlg_bridge(from, to, op)
dlg_get(callid, ftag, ttag)
is_known_dlg()
dlg_set_timeout(timeout [, h_entry, h_id])
dlg_set_timeout_by_profile(profile, [value], timeout)
dlg_set_property(attr)
dlg_remote_profile(cmd, profile, value, uid, expires)
dlg_set_ruri()

Statistics :

active_dialogs
early_dialogs
processed_dialogs
expired_dialogs
failed_dialogs

RPC Commands :

dlg.list
dlg.list_ctx
dlg.dlg_list
dlg.dlg_list_ctx
dlg.terminate_dlg
dlg.end_dlg
dlg.profile_get_size
dlg.profile_list
dlg.bridge_dlg

Exported Variables :

$DLG_count
$DLG_status
$DLG_lifetime
$dlg(…)
$dlg_ctx(…)
$dlg_var(key)

Event Routes :

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

 


 

The second 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 .

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

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())
t_on_reply("1");
} else {
t_on_reply("2");
}
}
if (is_method("ACK") && has_body("application/sdp"))
rtpproxy_answer();
...
}

onreply_route[1]
{
if (has_body("application/sdp"))
rtpproxy_answer();
}

onreply_route[2]
{
if (has_body("application/sdp"))
rtpproxy_offer();
}


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

unforce_rtp_proxy()

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")) {
rtpproxy_offer();
if (is_audio_on_hold()) {
rtpproxy_stream2uas("/var/rtpproxy/prompts/music_on_hold", "-1");
} else {
rtpproxy_stop_stream2uas();
};
};

rtpproxy_stream2uas(prompt_name, count)

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

rtpproxy_stop_stream2uas()

start_recording()
Exported Pseudo Variables

$rtpstat
RPC Commands

rtpproxy.enable
rtpproxy.list

RTP Engine

media streams to be proxied via an RTP proxy.

Parameters

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

set_rtpengine_set(setid[, setid])
rtpengine_offer([flags])
rtpengine_answer([flags])
rtpengine_delete([flags])
rtpengine_query([flags])
rtpengine_manage([flags])
start_recording([flags])
stop_recording([flags])
Exported Pseudo Variables
$rtpstat
RPC Commands

rtpengine.reload
rtpengine.enable proxy_url/all 0/1
rtpengine.show proxy_url/all
rtpengine.ping proxy_url/all
rtpengine.get_hash_total


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

XHTTP

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:

tcp_accept_no_cl=yes

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)
KSR.info(“===== xhttp module triggered event: ” .. evname .. “\n”);
return 1;
end

Function

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

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

Event Routes

xhttp:request
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.

Features

  • 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
    • I-CSCF, P-CSCF, S-CSCF
    • 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

Scalability:

  • 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

Logs

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/kamailio.pid -m 4096 -M 128 -u root -g root

 

 

Configuration

Kamctlrc

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
 SIP_DOMAIN=13.126.169.58
## chrooted directory
# $CHROOT_DIR="/path/to/chrooted/directory"
## database type: MYSQL, PGSQL, ORACLE, DB_BERKELEY, DBTEXT, or SQLITE
# by default none is loaded

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

 DBENGINE=MYSQL
## 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)
# DBACCESSHOST=192.168.0.1

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

# DBROOTUSER="root"
## 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)
#CHARSET="latin1"
## user name column
# USERCOL="username"
# SQL definitions

# If you change this definitions here, then you must change them
# in db/schema/entities.xml too.

 

# FIXME
# 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.

# INSTALL_EXTRA_TABLES=ask
# If to install presence related tables.
# INSTALL_PRESENCE_TABLES=ask
# If to install uid modules related tables.
# INSTALL_DBUID_TABLES=ask

 

 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_MODULES="
standard acc lcr domain group permissions registrar usrloc msilo
alias_db uri_db speeddial avpops auth_db pdt dialog dispatcher
dialplan"

 

extra modules

# 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
 CTLENGINE="RPCFIFO"

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

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

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

# VERIFY_USER=1

## verbose - debug purposes - default '0'
# VERBOSE=1

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

# STORE_PLAINTEXT_PW=0

 

Kamailio START Options

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

# PID_FILE=/var/run/kamailio/kamailio.pid

 

Extra start options – default is: not set

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

 

Kamailio.cfg

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 services
    To 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
#!define WITH_USRLOCDB
  • 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
define WITH_USRLOCDB

To enable presence server execute:
enable mysql
define WITH_PRESENCE

To enable nat traversal execute:
define WITH_NAT

install RTPProxy: http://www.rtpproxy.org
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
define WITH_ALIASDB

To enable speed dial lookup execute:
enable mysql
define WITH_SPEEDDIAL

To enable multi-domain support execute:
enable mysql
define WITH_MULTIDOMAIN

To enable TLS support execute:
adjust CFGDIR/tls.cfg as needed
define WITH_TLS

To enable XMLRPC support execute:
define WITH_XMLRPC
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)
define WITH_ANTIFLOOD

To block 3XX redirect replies execute:
define WITH_BLOCK3XX

To enable VoiceMail routing execute:
define WITH_VOICEMAIL
set the value of voicemail.srv_ip
adjust the value of voicemail.srv_port

To enhance accounting execute:
enable mysql
define WITH_ACCDB
add following columns to database
define WITH_MYSQL
define WITH_AUTH
define WITH_USRLOCDB
#!ifdef ACCDB_COMMENT
ALTER TABLE acc ADD COLUMN src_user VARCHAR(64) NOT NULL DEFAULT ”;
ALTER TABLE acc ADD COLUMN src_domain VARCHAR(128) NOT NULL DEFAULT ”;
ALTER TABLE acc ADD COLUMN src_ip varchar(64) NOT NULL default ”;
ALTER TABLE acc ADD COLUMN dst_ouser VARCHAR(64) NOT NULL DEFAULT ”;
ALTER TABLE acc ADD COLUMN dst_user VARCHAR(64) NOT NULL DEFAULT ”;
ALTER TABLE acc ADD COLUMN dst_domain VARCHAR(128) NOT NULL DEFAULT ”;
ALTER TABLE missed_calls ADD COLUMN src_user 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_ouser VARCHAR(64) NOT NULL DEFAULT ”;
ALTER TABLE missed_calls ADD COLUMN dst_user VARCHAR(64) NOT NULL DEFAULT ”;
ALTER TABLE missed_calls ADD COLUMN dst_domain VARCHAR(128) NOT NULL DEFAULT ”;
#!endif

####### Include Local Config If Exists #########
import_file “kamailio-local.cfg”

####### Defined Values #########

# *** 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"
#!endif
#!endif
#!ifdef WITH_MULTIDOMAIN
# - the value for 'use_domain' parameters
#!define MULTIDOMAIN 1
#!else
#!define MULTIDOMAIN 0
#!endif
# - 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
#!substdef "!MY_IP_ADDR!172.31.26.179!g"
#!substdef "!MY_DOMAIN!13.126.169.58!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"

#!define WITH_WEBSOCKETS
####### Global Parameters #########

LOG Levels: 3=DBG, 2=INFO, 1=NOTICE, 0=WARN, -1=ERR

#!ifdef WITH_DEBUG
debug=4
log_stderror=yes
#!else
debug=2
log_stderror=no
#!endif

memdbg=5
memlog=5

log_facility=LOG_LOCAL0

fork=yes
children=4

disable TCP (default on)

#disable_tcp=yes
enable_sctp = 0

 

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"

bind on a specific interface/port/proto (default bind on all available)

#listen=udp:10.0.0.10:5060

port to listen to – can be specified more than once if needed to listen on many ports

port=5060

#!ifdef WITH_TLS
enable_tls=yes
#!endif

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

tcp_connection_lifetime=3605

 

listen=MY_IP_ADDR
#!ifdef WITH_WEBSOCKETS
listen=MY_WS_ADDR
#!ifdef WITH_TLS
listen=MY_WSS_ADDR
#!endif
#!endif

tcp_connection_lifetime=3604
tcp_accept_no_cl=yes
tcp_rd_buf_size=16384
#And comment line:
#tcp_connection_lifetime=3605
####### Custom Parameters #########

These parameters can be modified runtime via RPC interface ,  see the documentation of ‘cfg_rpc’ module.

Format: group.id = value ‘desc’ description
Access: $sel(cfg_get.group.id) or @cfg_get.group.id

#!ifdef WITH_PSTN
# PSTN GW Routing
# - pstn.gw_ip: valid IP or hostname as string value, example:
# pstn.gw_ip = "10.0.0.101" 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"
#!endif

 

#!ifdef WITH_VOICEMAIL
# 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"
#!endif

 

####### Modules Section ########

# set paths to location of modules (to sources or installation folders)
#!ifdef WITH_SRCPATH
    mpath="modules/"
#!else
    mpath="/usr/lib/x86_64-linux-gnu/kamailio/modules/"
#!endif

#!ifdef WITH_MYSQL
loadmodule "db_mysql.so"
#!endif

loadmodule "mi_fifo.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 "usrloc.so"
loadmodule "registrar.so"
loadmodule "textops.so"
loadmodule "siputils.so"
loadmodule "xlog.so"
loadmodule "sanity.so"
loadmodule "ctl.so"
loadmodule "cfg_rpc.so"
loadmodule "mi_rpc.so"
loadmodule "acc.so"

#!ifdef WITH_AUTH
loadmodule "auth.so"
loadmodule "auth_db.so"
#!ifdef WITH_IPAUTH
loadmodule "permissions.so"
#!endif
#!endif

#!ifdef WITH_ALIASDB
loadmodule "alias_db.so"
#!endif

#!ifdef WITH_SPEEDDIAL
loadmodule "speeddial.so"
#!endif

#!ifdef WITH_MULTIDOMAIN
loadmodule "domain.so"
#!endif

#!ifdef WITH_PRESENCE
loadmodule "presence.so"
loadmodule "presence_xml.so"
#!endif

#!ifdef WITH_NAT
loadmodule "nathelper.so"
loadmodule "rtpproxy.so"
#!endif

#!ifdef WITH_TLS
loadmodule "tls.so"
#!endif

#!ifdef WITH_ANTIFLOOD
loadmodule "htable.so"
loadmodule "pike.so"
#!endif

#!ifdef WITH_XMLRPC
loadmodule "xmlrpc.so"
#!endif

#!ifdef WITH_DEBUG
loadmodule "debugger.so"
#!endif

#!ifdef WITH_WEBSOCKETS
loadmodule "xhttp.so"
#loadmodule "websocket.so"
loadmodule "nathelper.so"
#!endif

 

setting module-specific parameters

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

 

# ----- ctl params -----
#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)

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)

 

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)
/
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”,
“src_user=$fU;src_domain=$fd;src_ip=$si;”
“dst_ouser=$tU;dst_user=$rU;dst_domain=$rd”)
#!endif
usrloc params – enable DB persistency for location entries
#!ifdef WITH_USRLOCDB
modparam(“usrloc”, “db_url”, DBURL)
modparam(“usrloc”, “db_mode”, 2)
modparam(“usrloc”, “use_domain”, MULTIDOMAIN)
#!endif
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
#!ifdef WITH_IPAUTH
modparam(“permissions”, “db_url”, DBURL)
modparam(“permissions”, “db_mode”, 1)
#!endif

#!endif

alias_db params
#!ifdef WITH_ALIASDB
modparam(“alias_db”, “db_url”, DBURL)
modparam(“alias_db”, “use_domain”, MULTIDOMAIN)
#!endif

speeddial params
#!ifdef WITH_SPEEDDIAL
modparam(“speeddial”, “db_url”, DBURL)
modparam(“speeddial”, “use_domain”, MULTIDOMAIN)
#!endif

domain params
#!ifdef WITH_MULTIDOMAIN
modparam(“domain”, “db_url”, DBURL)

register callback to match myself condition with domains list

modparam(“domain”, “register_myself”, 1)
#!endif

 

#!ifdef WITH_PRESENCE
presence params
modparam(“presence”, “db_url”, DBURL)

presence_xml params
modparam(“presence_xml”, “db_url”, DBURL)
modparam(“presence_xml”, “force_active”, 1)
#!endif

 

#!ifdef WITH_NAT

rtpproxy params
modparam(“rtpproxy”, “rtpproxy_sock”, “udp:127.0.0.1:7722”)

nathelper params
modparam(“nathelper”, “natping_interval”, 30)
modparam(“nathelper”, “ping_nated_only”, 1)
modparam(“nathelper”, “sipping_bflag”, FLB_NATSIPPING)
modparam(“nathelper”, “sipping_from”, “sip:pinger@kamailio.org”)

params needed for NAT traversal in other modules

modparam(“nathelper|registrar”, “received_avp”, “$avp(RECEIVED)”)
modparam(“usrloc”, “nat_bflag”, FLB_NATB)
#!endif

tls params
#!ifdef WITH_TLS
modparam(“tls”, “config”, “/etc/kamailio/tls.cfg”)
#!endif

pike params

#!ifdef WITH_ANTIFLOOD
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=>size=8;autoexpire=300;”)
#!endif

xmlrpc params

#!ifdef WITH_XMLRPC
modparam(“xmlrpc”, “route”, “XMLRPC”);
modparam(“xmlrpc”, “url_match”, “^/RPC”)
#!endif

debugger params

#!ifdef WITH_DEBUG
modparam(“debugger”, “cfgtrace”, 1)
modparam(“debugger”, “log_level_name”, “exec”)
#!endif

nathelper params

#!ifdef WITH_WEBSOCKETS
modparam(“nathelper|registrar”, “received_avp”, “$avp(RECEIVED)”)
Note: leaving NAT pings turned off here as nathelper is only being used for WebSocket connections. NAT pings are not needed as WebSockets have their own keep-alives.
#!endif

Routing Logic

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

request_route {

# per request initial checks
route(REQINIT);

#!ifdef WITH_WEBSOCKETS
if (nat_uac_test(64)) {
    force_rport();
    if (is_method("REGISTER")) {
        fix_nated_register();
    } else {
        fix_nated_contact();
        if (!add_contact_alias()) {
            xlog("L_ERR", "Error aliasing contact <$ct>\n");
            sl_send_reply("400", "Bad Request");
            exit;
        }
    }
}
#!endif

# NAT detection
route(NATDETECT);

# CANCEL processing
if (is_method("CANCEL")) {
    if (t_check_trans()) {
        route(RELAY);
    }
    exit;
}

# handle requests within SIP dialogs
route(WITHINDLG);

### only initial requests (no To tag)

# handle retransmissions
if(t_precheck_trans()) {
t_check_trans();
exit;
}
t_check_trans();

# authentication
route(AUTH);

# 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
}

# dispatch requests to foreign domains
route(SIPOUT);

### requests for my local domains

# handle presence related requests
route(PRESENCE);

# handle registrations
route(REGISTRAR);

if ($rU==$null) {
    # request with no Username in RURI
    sl_send_reply("484","Address Incomplete");
    exit;
}

# 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|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;
}

 

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

#sequential request within a dialog should  take the path determined by record-routing
    if (loose_route()) {
        route(DLGURI);
        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
            route(NATMANAGE);
        }
        else if ( is_method("NOTIFY") ) {
            # Add Record-Route for in-dialog NOTIFY as per RFC 6665.
            record_route();
        }
        route(RELAY);
        exit;
    }

    if (is_method("SUBSCRIBE") && uri == myself) {
    # in-dialog subscribe requests
        route(PRESENCE);
        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;
}


 

Handle SIP registrations

route[REGISTRAR] {
    if (!is_method("REGISTER")) return;

    if(isflagset(FLT_NATS)) {
        setbflag(FLB_NATB);
        #!ifdef WITH_NATSIPPING do SIP NAT pinging
        setbflag(FLB_NATSIPPING);
        #!endif
    }

    if (!save("location"))
        sl_reply_error();
    exit;
}

 

User location service

route[LOCATION] {

#!ifdef WITH_SPEEDDIAL
# search for short dialing - 2-digit extension
if($rU=~"^[0-9][0-9]$")
    if(sd_lookup("speed_dial"))
    route(SIPOUT);
#!endif

#!ifdef WITH_ALIASDB
# search in DB-based aliases
    if(alias_db_lookup("dbaliases"))
    route(SIPOUT);
#!endif

$avp(oexten) = $rU;
if (!lookup("location")) {
    $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;
    }
}

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

route(RELAY);
exit;
}

Presence server processing

route[PRESENCE] {

if(!is_method("PUBLISH|SUBSCRIBE"))
return;

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

#!ifdef WITH_PRESENCE
if (!t_newtran()) {
    sl_reply_error();
    exit;
}

if(is_method("PUBLISH")) {
    handle_publish();
    t_release();
} else if(is_method("SUBSCRIBE")) {
    handle_subscribe();
    t_release();
}
exit;
#!endif

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

 

IP authorization and user authentication

route[AUTH] {
#!ifdef WITH_AUTH

#!ifdef WITH_IPAUTH
if((!is_method("REGISTER")) && allow_source_address()) {
    # source IP allowed
    return;
}
#!endif

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

    # user authenticated - remove auth header
    if(!is_method("REGISTER|PUBLISH"))
        consume_credentials();
    }

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

#!endif
return;
}

 

Caller NAT detection

route[NATDETECT] {
#!ifdef WITH_NAT
force_rport();

if (nat_uac_test("19")) {
    if (is_method("REGISTER")) {
        fix_nated_register();
    } else {
        if(is_first_hop())
            set_contact_alias();
    }
    setflag(FLT_NATS);
}
#!endif
return;
}

 

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")) {
            setbflag(FLB_NATB);
        }
     }
}
if (!(isflagset(FLT_NATS) || isbflagset(FLB_NATB)))
return;

rtpproxy_manage("co");

if (is_request()) {
    if (!has_totag()) {
        if(t_is_branch_route()) {
            add_rr_param(";nat=yes");
        } 
    }
}

if (is_reply()) {
    if(isbflagset(FLB_NATB)) {
        if(is_first_hop())
        set_contact_alias();
    }
}

#!endif
return;
}

 

URI update for dialog requests

route[DLGURI] {
#!ifdef WITH_NAT
if(!isdsturiset()) {
    handle_ruri_alias();
}
#!endif
return;
}

 

Routing to foreign domains

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

append_hf("P-hint: outbound\r\n");
route(RELAY);
exit;
}

 

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

# route to PSTN dialed numbers starting with '+' or '00'
# (international format)
# - update the condition to match your dialing rules for PSTN routing
if(!($rU=~"^(\+|00)[1-9][0-9]{3,20}$"))
return;

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

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

route(RELAY);
exit;
#!endif

return;
}

 

XMLRPC routing

#!ifdef WITH_XMLRPC
route[XMLRPC] {
# allow XMLRPC from localhost
if ((method=="POST" || method=="GET")
&& (src_ip==127.0.0.1)) {
# 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")
set_reply_close();
set_reply_no_connect();
dispatch_rpc();
exit;
}
send_reply("403", "Forbidden");
exit;
}
#!endif

 

Routing to voicemail server

route[TOVOICEMAIL] {
#!ifdef WITH_VOICEMAIL
if(!is_method("INVITE|SUBSCRIBE"))
return;

# 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");
return;
}
if(is_method("INVITE")) {
if($avp(oexten)==$null)
return;
$ru = "sip:" + $avp(oexten) + "@" + $sel(cfg_get.voicemail.srv_ip)
+ ":" + $sel(cfg_get.voicemail.srv_port);
} else {
if($rU==$null)
return;
$ru = "sip:" + $rU + "@" + $sel(cfg_get.voicemail.srv_ip)
+ ":" + $sel(cfg_get.voicemail.srv_port);
}
route(RELAY);
exit;
#!endif

return;
}

Manage outgoing branches

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

Manage incoming replies

onreply_route[MANAGE_REPLY] {
xdbg("incoming reply\n");
if(status=~"[12][0-9][0-9]")
route(NATMANAGE);
}

Manage failure routing cases

failure_route[MANAGE_FAILURE] {
route(NATMANAGE);

if (t_is_canceled()) {
    exit;
}

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

#!ifdef WITH_VOICEMAIL
# serial forking
# - route to voicemail on busy or no answer (timeout)
if (t_check_status("486|408")) {
    $du = $null;
    route(TOVOICEMAIL);
    exit;
}
#!endif
}

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

 

Tools

kamctl

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.

kamdbctl

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

Valid values are: MYSQL, PGSQL, ORACLE, DB_BERKELEY, DBTEXT.

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.

kamcmd

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

siremis

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

kamcli

cmd line client written Python

 

Modules

Registrar

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.

Benefits:

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

Timeline

  • 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

Architecture

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 .

—————————————————————

OfficeSIP

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

officesip0

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

officesip1

3.Installation screen appears as follows

officesip2

4. Terms and conditions

officesip3

5. Destination folder for installation

officesip4

6. Installing

officesip5

7. Validating install

officesip6

8. Installation completed

officesip7

9. Launch icon on dekstop

officesip8

10 . Office SIP web login screen

officesip9

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

officesip10

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

officesip11

13. add users that will be registering to officeSIP server

officesip13

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

officesip14_001

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 startweblogic.sh script

4. Open Web console on url : http://127.0.0.1:7001/console. 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
src
build
src
web
build.xml

The SIP servlet are put side directory structure of src

For example : sample application for Call screening

package com.altanai.voice;
import java.io.IOException;
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”);
super.init(config);
}
protected void doInvite(SipServletRequest req) throws java.lang.IllegalArgumentException,java.lang.IllegalStateException,javax.servlet.ServletException,java.io.IOException
{
System.out.println(“Received an Invite Request”);
if(req.getFrom().toString().indexOf(“alice”)!=-1)
{
req.createResponse(406).send();
System.out.println(“User is blocked”);
}
else
{
req.createResponse(200).send();
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
Watcher

Image source  : http://msdn.microsoft.com/en-us/library/bb896003.aspx

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 http://download.oracle.com/docs/cd/B32110_01/ocms.1013/b31497/about_sdp.htm#BABDHHCJ

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

subscribe request

SUBSCRIBE sip:presentity@example.com SIP/2.0
      Via: SIP/2.0/UDP host.example.com;branch=z9hG4bKnashds7
      To: <sip:presentity@example.com>
      From: <sip:watcher@example.com>;tag=12341234
      Call-ID: 12345678@host.example.com
      CSeq: 1 SUBSCRIBE
      Max-Forwards: 70
      Expires: 3600
      Event: presence
      Contact: sip:user@host.example.com
      Content-Length: 0
 

200 OK to subscribe request

SIP/2.0 200 OK
      Via: SIP/2.0/UDP host.example.com;branch=z9hG4bKnashds7
       ;received=192.0.2.1
      To: <sip:presentity@example.com>;tag=abcd1234
      From: <sip:watcher@example.com>;tag=12341234
      Call-ID: 12345678@host.example.com
      CSeq: 1 SUBSCRIBE
      Contact: sip:pa.example.com
      Expires: 3600
      Content-Length: 0
 

Notify Request

NOTIFY sip:user@host.example.com SIP/2.0
      Via: SIP/2.0/UDP pa.example.com;branch=z9hG4bK8sdf2
      To: <sip:watcher@example.com>;tag=12341234
      From: <sip:presentity@example.com>;tag=abcd1234
      Call-ID: 12345678@host.example.com
      CSeq: 1 NOTIFY
      Max-Forwards: 70
      Event: presence
      Subscription-State: active; expires=3599
      Contact: sip:pa.example.com
      Content-Type: application/pidf+xml
      Content-Length: …
 

200 OK success response to notify

SIP/2.0 200 OK
      Via: SIP/2.0/UDP pa.example.com;branch=z9hG4bK8sdf2
       ;received=192.0.2.2
      To: <sip:watcher@example.com>;tag=12341234
      From: <sip:presentity@example.com>;tag=abcd1234
      Call-ID: 12345678@host.example.com
      CSeq: 1 NOTIFY
 

PUBLISH Request

PUBLISH sip:presentity@example.com SIP/2.0
Via: SIP/2.0/UDP pua.example.com;branch=z9hG4bK652hsge
To: <sip:presentity@example.com>
From: <sip:presentity@example.com>;tag=1234wxyz
Call-ID: 81818181@pua.example.com
CSeq: 1 PUBLISH
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 pua.example.com;branch=z9hG4bK652hsge
;received=192.0.2.3
To: <sip:presentity@example.com>;tag=1a2b3c4d
From: <sip:presentity@example.com>;tag=1234wxyz
Call-ID: 81818181@pua.example.com
CSeq: 1 PUBLISH
SIP-ETag: dx200xyz
Expires: 1800

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

presence subscribe notify

Image source http://www.cisco.com/en/US/i/100001-200000/190001-200000/190001-191000/190463.jpg

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
    TLS
    Digest Authentication
    S/MIME

References :

Rfc 3856 http://www.ietf.org/rfc/rfc3856.txt
Rfc 3265 http://www.ietf.org/rfc/rfc3265.txt
Rfc 2778 http://www.ietf.org/rfc/rfc2778.txt
Rfc 3261 http://www.ietf.org/rfc/rfc3261.txt
Rfc 3903 http://www.ietf.org/rfc/rfc3903.txt
http://en.wikipedia.org/wiki/Session_Initiation_Protocol

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 : stun:stun.l.google.com:19302 and  turn:user@numb.viagenie.ca

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

calltakenoffhold

Telestax WebRTC client

2014-06-11_2215

SIPJS with flash network support

windows_IE_1

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

Linphone

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

Linphone

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

Description

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

Code

Category

Description

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 host.domain.com:5060
  • From: Bob <sip:bob@domain.com>
  • To: Altanai <sip:domain@wcom.com>
  • Call-ID: 163784@host.domain.com
  • CSeq: 1 INVITE

session description in SDP

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)

TYPICAL SIP INVITE :


INVITE sip:01150259917040@67.135.76.4 SIP/2.0

Via: SIP/2.0/UDP 69.7.163.154:5060;branch=z9hG4bK400fc6e6

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

To: <sip:01150259917040@67.135.76.4>

Contact: <sip:8069664170@69.7.163.154>

Call-ID: 2485823e63b290b47c042f20764d990a@69.7.163.154

CSeq: 102 INVITE

User-Agent: MatrixSwitch

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

Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER

Content-Type: application/sdp

Content-Length: 268

v=0

o=root 14040 14040 IN IP4 69.7.163.154

s=session

c=IN IP4 69.7.163.154

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 host.domain.com:5060
  • From: Bob<sip:bob@domain.com>
  • To: Altanai<sip:altanai@domain.com>
  • Call-ID: 163784@host.domain.com
  • CSeq: 1 INVITE
Note : – 

Via, From, To, Call-ID 

, and  

CSeq  

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 )

Provisioning

  • · 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

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
Universal
– 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.

DukeJAINSLEE

 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

Service

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.

Profile

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.

Event

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

————————————————————————————————————————

SIP based architecture

SIP solutioning and architectures  is a subsequent article after SIP which can be found here .  A VOIP 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 network providers  , enterprise applications  ( Skype , Microsoft Lync  ) , Trunks etc .

The article outlines VOIP architecture  from 3 viewpoints :

  • from Infrastructure standpoint
  • from core voice engineering perspective
  • and accompanying 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 resiliency of data.
    WORM compliant NAS for storing voice archives over a retention period.
  • Racks, power supplies, battery backups, cages etc.
  • Networking
    DMZs ( Demilitarised Zones)  which are interfacing areas between internal servers in 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 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

sip entities

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

 

Detailing some of the protocols apart from SIP used in VOIP solution

RTP ( Real Time Transport Protocol )

RTP handles realtime multimedia transport between end to end network components . RFC 3550 .

Packet structure of RTP     Image result for RTP packet structure

RTP Header contain timestamp , name of media source , codec type and sequence number .

Image result for RTP header structure

RTCP

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.

SIP Gateways:

A SIP gateway is an application that interfaces a SIP network to a network utilizing another signaling 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 signaling 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


External components to setup a VOIP solution apart from Core voice Servers and gateways

  • 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

SIP ( Session Initiation Protocol )

Update :

At the time of writing this article on SIP and related VOIP technologies I a newbie in VOIP domain , probably just out college . However over the past decade , looking at the steady traffic to these articles , I have tried updating the same with new RFC standards and market trends .


SIP ( Session Initiation Protocol) negotiates session between 2 parties.  It primarily exchanges headers that are used for making a call session such as example of outgoing telephone call from SIP session invite . It is a L

Session Initiation Protocol (INVITE)
Request-Line: INVITE sip:altanai@telecomcompany.com;transport=tcp SIP/2.0
Method: INVITE
Request-URI: altanai@telecomcompany.com;transport=tcp
        Request-URI User Part: altanai
        Request-URI Host Part: telecomcompany.com
        [Resent Packet: False]

Message Header

Via: SIP/2.0/TCP 1.2.3.4:5080;rport;branch=z9hG4bKceX7a2H2866cN
        Transport: TCP
        Sent-by Address: 1.2.3.4
        Sent-by port: 5080
        RPort: rport
        Branch: z9hG4bKceX7a2H2866cN

Max-Forwards: 41

From: "+16014801797" <sip:+16014801797@1.2.3.4>;tag=7HKgjNQ6y2FSj
        SIP Display info: "+16014801797"
        SIP from address: sip:+16014801797@1.2.3.4
                SIP from address User Part: +16014801797
                E.164 number (MSISDN): 16014801797
                        Country Code: Americas (1)
                SIP from address Host Part: 1.2.3.4
        SIP from tag: 7HKgjNQ6y2FSj

To: <sip:altanai@telecomcompany.com;transport=tcp>
        SIP to address: sip:altanai@telecomcompany.com;transport=tcp
        SIP to address User Part: altanai
        SIP to address Host Part: telecomcompany.com
        SIP To URI parameter: transport=tcp

Call-ID: e10306be-0cfd-4b38-af3c-b2ada0827cef
CSeq: 126144925 INVITE
Contact: <sip:mod_sofia@1.2.3.4:5080;transport=tcp>
User-Agent: phone1
Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, INFO, UPDATE, REFER, NOTIFY
Supported: path, replaces
Allow-Events: talk, hold, conference, refer
Privacy: none
Content-Type: application/sdp
Content-Disposition: session
Content-Length: 249
SIP Display info: "+16014801797"
SIP PAI Address: sip:+16014801797@1.2.3.4

The SIP philosophy :

  • reuse Internet addressing (URLs, DNS, proxies)
  • utilize rich Internet feature set
  • reuse HTTP coding
  • text based
  • makes no assumptions about underlying protocol:
    TCP, UDP, X.25, frame, ATM, etc
  • support of multicast

SIP URI can either be in format of sip:altanai@telecomcompnay.com (RFC 2543 ) or sips:altanai@telecomcompany.com ( secure with TLS over TCP RFX 3261) . Additionally SIP URI resolution can either be

  • DNS SRV based such as altanai@telecomcompnay.com with SIP servers locating record for domain “telecomcompnay.com ” or
  • FQDN ( Fully qualified domain name ) / contact / ip address based such as altanai@2.2.2.2 or altanai@us-west1-prod-server . Both of which do not need any resolution for routing.

Tags are pseudo-random numbers inserted in To or From headers to uniquely identify a call leg

Max forwards  is a count decremented by each proxy
that forwards the request.When count goes to zero, request is discarded and 483
Too Many Hops response is sent.Used for stateless loop detection.

Content-Type indicates the type of message body attachment. In this case application /SDP but  others could be text/plain, application/cpl+xml, etc.)

Content-Length indicates the octet (byte) count of the message body

Firewalls can sometimes block SIP packets , change TCP to UDP or change IP address of the packets. Record-Route can be used , ensures Firewall proxy stays in path . Clients and Servers copy Record-Route and put in Route header for all messages

Message body is separated from SIP header fields by a blank line (CRLF).

sip arch

SIP transaction

A SIP transaction occurs between a UAC and a UAS. The SIP transaction comprises all messages from the first request sent from the UAC to the UAS up to a final response (non-1xx) sent from the UAS to the UAC

Branch

The branch parameter is a transaction identifier. Responses relating a request can be correlated because they will contain the same transaction identifier.

Dialog

The initiator of the session that generates the establishing INVITE generates the unique Call-ID and From tag. In the response to the INVITE, the user agent answering the request will generate the To tag. The combination of the local tag (contained in the From header field), remote tag (contained in the To header field), and the Call-ID uniquely identifies the established session, known as a dialog. This dialog identifier is used by both parties to identify this call because there could be multiple calls set up between them.

Components of SIP Solution

Screen Shot 2018-08-16 at 10.11.14 PM

SIP Request methods :

  1. INVITE : Initiates negotiation to establish a session ( dialog). Usually contains SDP payload. Another invite during an existing session ( dialog) is called an RE-INVITE. A RE-INVITE can be used for
    • hold / resume a call
    • change session parameters and codecs in mid of a call
  2. ACK : Acknowledge an INVITE request by completing the 3 way handshake . If an INVITE did not contain media contain then ACK must contain it .
  3. BYE : Ends a session ( dialog).
  4. CANCEL : Cancels a session( dialog)  before it establishes  .
  5. REGISTER : Registers a user location (host name, IP) on a registrar SIP server.
  6. OPTIONS : Communicates information about the capabilities of the calling and receiving SIP phones ( methods , extensions , codecs etc )
  7. PRACK : Provisional Acknowledgement for provisional response as 183 ( session in progress) . PRACK only application to 101- 199 responses .
  8. SUBSCRIBE : Subscribes for Notification from the notifier. Can use Expire=0 to unsubscribe.
  9. NOTIFY : Notifies the subscriber of a new event.
  10. PUBLISH : Publishes an event to the Server.
  11. INFO : Sends mid session information.
  12. REFER : Asks the recipient to issue call transfer.
  13. MESSAGE : Transports Instant Messages.
  14. UPDATE : Modifies the state of a session ( dialog).

Some SIP responses :

1xx = Informational SIP Responses
100 Trying
180 Ringing
183 Session Progress

2xx = Success Responses
200 OK – Shows that the request was successful

3xx = Redirection Responses

4xx = Request Failures
401 Unauthorized
404 Not Found
405 Method Not Allowed
407 Proxy Authentication Required
408 Request Timeout
480 Temporarily Unavailable
481 Call/Transaction Does Not Exist
486 Busy Here
487 Request Terminated
488 Not Acceptable Here
482 Loop Detected
483 Too Many Hops

5xx = Server Errors
500 Server Internal Error
503 Service Unavailable

6xx = Global Failures
600 Busy Everywhere
603 Decline
604 Does Not Exist Anywhere
606 Not Acceptable

SIP callflow diagram for a Call Setup and termination using RTP for media and RTCP for control.

Screen Shot 2018-08-16 at 10.17.57 PM

SIP Transport Layers

We know the ISO OSI layers  which servers as a standard model for data communications .

sip 3

  1. Physical Layer : Ethernet , USB , IEEE 802.11  WiFi, Bluetooth  , BLE
  2. Data Link Layer : ARP ( Address Resolution Protocol ) ,  PPP ( point to point protocol ) , MAC ( Media Access control ) , ATM , Frame Relay
  3. Network Layer :  IP (IPv4 / IPv6), ICMP, IPsec
  4. Transport : TCP , UDP , SCTP
  5. Session : PPTP ( Point to point tunnelling protocol) , NFS, SOCKS
  6. Presentation : Codecs such as JPEG , GIFF , SSL
  7. Application : Application level like Call -manager/ softphone  as HTTP , FTP , DNS , SIP  , RTSP , RTP , DNS

SDP ( Session Description Protocol)

SIP can bear many kinds of MIME attachments , one such is SDP. It uses RTP/AVP Profiles for common media types . Specified by RFC 3264 . It defines media information and capabilities such as codecs , termination points .

Contains connection headers used for establishing the session . Sample SDP payload for Invite SIP above :

Session Description Protocol Version (v): 0
Owner/Creator, Session Id (o): FreeSWITCH 1532932581 1532932582 IN IP4 1.2.3.4
        Owner Username: FreeSWITCH
        Session ID: 1532932581
        Session Version: 1532932582
        Owner Network Type: IN
        Owner Address Type: IP4
        Owner Address: 1.2.3.4
Session Name (s): FreeSWITCH
Connection Information (c): IN IP4 1.2.3.4
        Connection Network Type: IN
        Connection Address Type: IP4
        Connection Address: 1.2.3.4
Time Description, active time (t): 0 0
        Session Start Time: 0
        Session Stop Time: 0
Media Description, name and address (m): audio 29398 RTP/AVP 0 101
        Media Type: audio
        Media Port: 29398
        Media Protocol: RTP/AVP
        Media Format: ITU-T G.711 PCMU
        Media Format: DynamicRTP-Type-101
Media Attribute (a): rtpmap:0 PCMU/8000
        Media Attribute Fieldname: rtpmap
        Media Format: 0
        MIME Type: PCMU
        Sample Rate: 8000
Media Attribute (a): rtpmap:101 telephone-event/8000
        Media Attribute Fieldname: rtpmap
        Media Format: 101
        MIME Type: telephone-event
        Sample Rate: 8000
Media Attribute (a): fmtp:101 0-16
        Media Attribute Fieldname: fmtp
        Media Format: 101 [telephone-event]
        Media format specific parameters: 0-16
Media Attribute (a): silenceSupp:off - - - -
        Media Attribute Fieldname: silenceSupp
        Media Attribute Value: off - - - -
Media Attribute (a): ptime:20
        Media Attribute Fieldname: ptime
        Media Attribute Value: 20

 v=0  indicates the start of the SDP content.

o=FreeSWITCH 1532932581 1532932582 IN IP4 1.2.3.4 , is session origin and owner’s name

c=IN IP4 1.2.3.4 is connect information Specifies the IP address of a session.  

m= is Media type – audio, port – 29398, RTP/AVP Profile – 0 and 101

Attribute profile – 0, codec – PCMU, sampling rate – 8000 Hz and Attribute profile – 101, telephone-event

SIP Authorization

authentication , security , confidentiality and integrity form the basic requirement for any communication system .

To protect against hacking a user account and Denial of service attacks  , SIP uses HTTP digest authentication mechanism. Here the SIP request is responded with challenge and nonce . The sender has to resend the request with MD5 hash of nonce and password ( password id never send in clear ) . Thus preventing man-in-middle attacks.

Challenge / Response Scheme :

  • Sends REGISTER   and receives 407 Challenge + nonce                           
  • Again sends REGISTER + MD-5 hash (pw + nonce) get a 200 OK

To prevent spoofing ie impersonating as server , SIP provides server authentication too. Required by ITSP’s  ( Internet telephony service providers ) .

Mobility

To provide session mobility SIP endpoints send Register request to their respective registrar as they move and update their location.

As User changes terminals , they registers themselves to the appropriate server
Location server tracks the location of user
Redirect servers prioritize the possible locations of the user
Users keep same services as located at home server, while mobile
Call is processed by home servers using RECORD-ROUTE

NAT

National Address Translator , defined by RFC 3022 to conserve network space as most packets are exchanged inside a private network itself .

All internet users whether they are using Wifi , 3G/LTE,  home AP, any other telecom data packet network  by TSP or ISP , are assigned a private IP address , which is unreachable from out side world .Addresses are assigned by Internet Assigned Numbers Authority (IANA). Private address blocks are in format of 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16.

Therefore when they access the Internet , this address is converted into a  globally unique public IP address through a NAT for external communication

Screen Shot 2018-08-18 at 4.33.06 PM

SIP Issues around NAT

NATs modify IP addresses (Layer 3)- SIP/SDP are Layer 7 protocols – transparent to NAT

SIP Via:, From: and Contact: headers use not-routable private addresses
SDP states that originator wishes to receive media at not-routable private addresses
If destination on the public internet tries to send SIP or RTP traffic to those private address
Traffic will be dumped by first router

Solution are to use  either Application level gateway (ALG) or STUN or Universal Plug and Pray (UPnP)

To rewrite all SIP/SDP source addresses

  • SIP Via:, From: and Contact: headers use public NAT address
  • SDP addresses use NAT public address
  • Use SIP over TCP

Use draft-ietf-sip-symmetric-response-00 and “Symmetric” SIP/RTP
Use same UDP port number for incoming/outgoing
Hold ports open for call duration
Send UDP packet typically every 30 seconds
SIP over UDP uses 30 second re-INVITE, REGISTER or OPTIONs
RTP sends at much higher frequency by default

NAPT ( Network Address Port Translator )

  • Can map multiple private IP addresses and ports to one public IP address and ports

SIP Flows

Registration

Localization Server  –Used by the Proxy Server and Redirect Server to obtain the location of the called user (one or more addresses)

Registration Server- Accept registration requests from the client applications . Generally, the service is offered by the Proxy Server or Redirect Server

DNS Server – Used to locate the Proxy Server or Redirect Server

Screen Shot 2018-08-18 at 12.46.14 PM

Call Redirection

Sending Call invite but as Redirect Server responded with 302 moved temporary , a new destination address is returned. The invite is forwarded to another proxy server which connects the sip endpoints again after consultation with Redirect server .

Screen Shot 2018-08-18 at 10.37.38 AM

In this stage of we see the call getting connected to sip endpoint via 2 proxy servers . The redirect server doesnt get into path once the initial sip request is send.

Screen Shot 2018-08-18 at 11.12.17 AM

After communication the endpoints send BYE to terminate the session

Screen Shot 2018-08-18 at 11.13.59 AM

 

Forking

This callflow deals with the use-case when a user maybe registered from multiple SIP phones ( perhaps one home phone , one car and one office desk etc ) and wants to receive a ring on all registered phone ie fork a call to multiple endpoints .

Screen Shot 2018-08-18 at 11.17.19 AM

In the above diagram we can see a forked invite going to both the sip phones . Both of them reply with 100 trying and 180 ringing, but only 1 gets answered by the user .

Screen Shot 2018-08-18 at 11.17.26 AM

After one endpoint sends 200 ok and connects with session , the other receiver a cancel from the sip server .

Screen Shot 2018-08-18 at 11.17.33 AM

Click to Dial

A web or desktop application which has HTTP can fire a API call which is interpreted by the controller or SIP server  and call is fired .

Screen Shot 2018-08-18 at 1.23.36 PM

The API can contain params for to and from sip addresses as well as any authentication  token that is required for api authentication and validation .

Source code for some of the SIP application can be found on github 

https://github.com/altanai/sip-servlets

 

SIPMLE

SIP for Instant Messaging and Presence Leveraging Extensions (SIMPLE)

  • several vendors who intend to implement SIMPLE
  • provides for presence and buddy lists
  • Instant Messaging in the enterprise
  • telephony enabled user lists

 

Using SIP based Call routing algorithms and flows , one can build carrier grade communication solution . SIP solutions can hook up with existing telecom networks and service providers to be backward compatible . Also has untapped unlimited potential to integrate with any external IP application or service to provide converged , customised control both for signalling and media planes.

References :

  1. SIP by Henning Schulzrinne Dept. of Computer Science Columbia University New York
  2. International Institute of Telecommunications 2000-2004
  3. Introduction to SIP by Patrick Ferriter from ZULTYS
  4. Internet Draft, IETF, RFC 2543
  5. NTU – Internet Telephony based on SIP