Building Telephony Systems with OpenSIPS - Second Edition - Flavio E. Goncalves - E-Book

Building Telephony Systems with OpenSIPS - Second Edition E-Book

Flavio E. Goncalves

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Build high-speed and highly scalable telephony systems using OpenSIPS

About This Book

  • Install and configure OpenSIPS to authenticate, route, bill, and monitor VoIP calls
  • Gain a competitive edge using the most scalable VoIP technology
  • Discover the latest features of OpenSIPS with practical examples and case studies

Who This Book Is For

If you want to understand how to build a SIP provider from scratch using OpenSIPS, then this book is ideal for you. It is beneficial for VoIP providers, large enterprises, and universities. This book will also help readers who were using OpenSER but are now confused with the new OpenSIPS.

Telephony and Linux experience will be helpful to get the most out of this book but is not essential. Prior knowledge of OpenSIPS is not assumed.

What You Will Learn

  • Learn to prepare and configure a Linux system for OpenSIPS
  • Familiarise yourself with the installation and configuration of OpenSIPS
  • Understand how to set a domain and create users/extensions
  • Configure SIP endpoints and make calls between them
  • Make calls to and from the PSTN and create access control lists to authorize calls
  • Install a graphical user interface to simplify the task of provisioning user and system information
  • Implement an effective billing system with OpenSIPS
  • Monitor and troubleshoot OpenSIPS to keep it running smoothly

In Detail

OpenSIPS is a multifunctional, multipurpose signalling SIP server. SIP (Session Initiation Protocol) is nowadays the most important VoIP protocol and OpenSIPS is the open source leader in VoIP platforms based on SIP. OpenSIPS is used to set up SIP Proxy servers. The purpose of these servers is to receive, examine, and classify SIP requests. The whole telecommunication industry is changing to an IP environment, and telephony as we know it today will completely change in less than ten years. SIP is the protocol leading this disruptive revolution and it is one of the main protocols on next generation networks. While a VoIP provider is not the only kind of SIP infrastructure created using OpenSIPS, it is certainly one of the most difficult to implement.

This book will give you a competitive edge by helping you to create a SIP infrastructure capable of handling tens of thousands of subscribers.

Starting with an introduction to SIP and OpenSIPS, you will begin by installing and configuring OpenSIPS. You will be introduced to OpenSIPS Scripting language and OpenSIPS Routing concepts, followed by comprehensive coverage of Subscriber Management. Next, you will learn to install, configure, and customize the OpenSIPS control panel and explore dialplans and routing. You will discover how to manage the dialog module, accounting, NATTraversal, and other new SIP services. The final chapters of the book are dedicated to troubleshooting tools, SIP security, and advanced scenarios including TCP/TLS support, load balancing, asynchronous processing, and more.

A fictional VoIP provider is used to explain OpenSIPS and by the end of the book, you will have a simple but complete system to run a VoIP provider.

Style and approach

This book is a step-by-step guide based on the example of a VoIP provider. You will start with OpenSIPS installation and gradually, your knowledge depth will increase.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 395

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Building Telephony Systems with OpenSIPS Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Introduction to SIP
Understanding the SIP architecture
The SIP registration process
Types of SIP servers
The proxy server
The redirect server
The B2BUA server
SIP request messages
The SIP dialog flow
SIP transactions and dialogs
Locating the SIP servers
SIP services
The SIP identity
The RTP protocol
Codecs
DTMF-relay
Session Description Protocol
The SIP protocol and OSI model
The VoIP provider's big picture
The SIP proxy
The user administration and provisioning portal
The PSTN gateway
The media server
The media proxy or RTP proxy for NAT traversal
Accounting and CDR generation
Monitoring tools
Additional references
Summary
2. Introducing OpenSIPS
Understanding OpenSIPS
OpenSIPS capabilities
An overview of the OpenSIPS project
OpenSIPS knowledge transfer and support
Usage scenarios for OpenSIPS
The ingress side
The core side
The egress side
Who's using OpenSIPS?
The OpenSIPS design
The OpenSIPS core
The OpenSIPS modules
Summary
3. Installing OpenSIPS
Hardware and software requirements
Installing Linux for OpenSIPS
Downloading and installing OpenSIPS v2.1.x
Generating OpenSIPS scripts
Running OpenSIPS at the Linux boot time
The OpenSIPS v2.1.x directory structure
The configuration files
Modules
Working with the log files
Startup options
Summary
4. OpenSIPS Language and Routing Concepts
An overview of OpenSIPS scripting
The OpenSIPS configuration file
Global parameters
The modules section
Scripting routes
The request route
The branch route
The failure route
The reply route
The local route
The start up route
The timer route
The event route
The error route
Scripting capabilities
The scripting functions
The scripting variables
The reference variables
The AVP variables
The script variables
Scripting transformations
Scripting flags
Scripting operators
Script statements
SIP routing in OpenSIPS
Mapping SIP traffic over the routing script
Stateless and stateful routing
In-dialog SIP routing
Summary
5. Subscriber Management
Modules
The AUTH_DB module
The REGISTER authentication sequence
The REGISTER sequence
The INVITE authentication sequence
The INVITE sequence packet capture
The INVITE code snippet
Digest authentication
The authorization request header
Quality of protection
Plaintext or prehashed passwords
Installing MySQL support
Analysis of the opensips.cfg file
The REGISTER requests
The non-REGISTER requests
The opensipsctl shell script
Configuring the opensipsctl utility
Using OpenSIPS with authentication
The registration process
Enhancing the opensips.cfg routing script
Managing multiple domains
Using aliases
Handling the CANCEL requests and retransmissions
Lab – multidomain support
Lab – using aliases
IP authentication
Summary
6. OpenSIPS Control Panel
The OpenSIPS control panel
Installation of OpenSIPS-CP
Configuring the OpenSIPS-CP
Installing Monit
Configuring administrators
Adding and removing domains
Manage the access control lists or groups
Managing aliases
Managing subscribers
Verifying the subscriber registration
Managing permissions and IP authentication
Sending commands to the management interface
A generic table viewer
Summary
7. Dialplan and Routing
The dialplan module
PSTN routing
Receiving calls from PSTN
Gateway authentication
The permissions module
Caller identification
Sending calls to PSTN
Identifying PSTN calls
Authorizing PSTN calls
The group module
Access Control Lists
Caller ID in PSTN calls
Routing to PSTN GWs
The dynamic routing module
Routing entities
The selection algorithm
Probing and disabling gateways
Advanced features
Script samples
Summary
8. Managing Dialogs
Enabling the dialog module
Creating a dialog
Dialog matching
Dialog states
Dialog timeout and call disconnection
Dialog variables and flags
Setting and reading the dialog variables
Setting and reading the dialog flags
Profiling a dialog
Counting calls from the MI interface
Disconnecting calls
Disconnecting a call using the MI interface
Topology hiding
Initial request before topology hiding
Initial request after topology hiding
Sequential request before topology hiding
Sequential request after topology hiding
Topology hiding limitations
Validating a dialog and fixing broken dialogs
Displaying the dialog statistics
Description of the statistics
SIP session timers
How the SIP session timer works
Summary
9. Accounting
Progress check
Selecting a backend
The accounting configuration
Automatic accounting
Manual accounting
Extra accounting
Multi-leg accounting
Lab - accounting using MySQL
Using the dialog module to obtain the duration
Call end reason
Generating CDRs
Lab – generating CDRs
CDRviewer and extra accounting
Accounting using RADIUS
Lab – accounting using a FreeRADIUS server
Package and dependencies
FreeRADIUS client and server configuration
Configuring the OpenSIPS server
Missing BYEs and CDRs
Summary
10. SIP NAT Traversal
Port address translation
Where does NAT break SIP?
Types of NAT
Full cone
Restricted cone
Port-restricted cone
Symmetric
The NAT firewall table
Solving the SIP NAT traversal challenge
A solution proposed for the NAT issue
The solution's topology
Building the solution
Installing STUN
Why STUN does not work with symmetric NAT devices
Solving SIP signaling
Implementing NAT detection
Solving the Via header using rport
Fixing the Contact header for requests and replies
Handling the REGISTER requests and pings
Handling the responses
Handling sequential requests
Using a media relay server
Solving the traversal of the RTP packets
Understanding the solution flow
(1) First INVITE
(2) INVITE relayed by the server
(3) Reply 200 OK with SDP
Acknowledgements (ACK packets)
Summary
11. Implementing SIP Services
Where to implement SIP services
Explaining RFC 5359 with SIP service examples
Playing announcements
Playing demo-thanks
Call forwarding
Implementing blind call forwarding
Loading the AVPops module and its parameters
Lab – implementing blind call forwarding
Implementing call forward on busy or unanswered
Debugging the routing script
Lab – testing the call forwarding feature
Implementing an integrated voicemail
User integration
Integrating Asterisk Realtime with OpenSIPS
Call transfer
An unattended transfer
Tips for call transfer
Summary
12. Monitoring Tools
Built-in tools
Trace tools
SIPTRACE
Configuring SIPTRACE
Script trace
Troubleshooting routing scripts
A system crash
Benchmarking segments of code
Stress testing tools
The sipsak tool
SIPp
Installing SIPp
Stress testing
Packet capturing tools
Ngrep
Sipgrep
Wireshark
Summary
13. OpenSIPS Security
Configuring a firewall for OpenSIPS
Blocking multiple unsuccessful authentication attempts
Preventing DOS using the PIKE module
PIKE in manual mode
PIKE in automatic mode
Preventing DNS and registration poisoning
Enabling Transport Layer Security
Generating a script for TLS
Creating the root certificate authority
Creating the server certificate
Installing the root certificate authority in your softphone
Enabling Secure Real-time Protocol
SRTP-SDES
DTLS-SRTP
ZRTP
Enabling SRTP
Enabling the anti-fraud module
Event generation
Script integration
Summary
14. Advanced Topics with OpenSIPS 2.1
Asynchronous operations
Asynchronous support in the OpenSIPS script
Available asynchronous functions
Binary replication
Dialog replication
The usrloc replication
TCP handling
Enabling TCP
Summary
Index

Building Telephony Systems with OpenSIPS Second Edition

Building Telephony Systems with OpenSIPS Second Edition

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: January 2010

Second edition: January 2016

Production reference: 1250116

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-061-0

www.packtpub.com

Credits

Authors

Flavio E. Goncalves

Bogdan-Andrei Iancu

Reviewers

Saúl Ibarra Corretgé

Vyacheslav Kobzar

Mfawa Alfred Onen

Ali Pey

Commissioning Editor

Neil Alexander

Acquisition Editor

Kevin Colaco

Content Development Editor

Amey Varangaonkar

Technical Editor

Pranil Pathare

Copy Editor

Tasneem Fatehi

Project Coordinator

Suzanne Coutinho

Proofreader

Safis Editing

Indexer

Monica Ajmera Mehta

Graphics

Disha Haria

Production Coordinator

Conidon Miranda

Cover Work

Conidon Miranda

About the Authors

Flavio E. Goncalves was born in 1966 in Brazil. Having a strong interest in computers, he got his first personal computer in 1983, and since then, it has been almost an addiction. He received his degree in engineering in 1989 with a focus on computer-aided designing and manufacturing.

He is also the CTO of SipPulse Routing and Billing Solutions in Brazil—a company dedicated to the implementing of small-to-medium telephone companies, VoIP providers, and large-scale new generation telephony systems. Since 1993, he has participated in a series of certification programs and been certificated as Novell MCNE/MCNI, Microsoft MCSE/MCT, Cisco CCSP/CCNP/CCDP, Asterisk dCAP, and some others.

He started writing about open source software because he thinks that the way certification programs have worked is very good for learners. Some books are written by strictly technical people who sometimes do not have a clear idea on how people learn. He tried to use his 15 years of experience as an instructor to help people learn about the open source telephony software. Together with Bogdan, he created the OpenSIPS boot camp followed by the e-learning program, OpenSIPS eBootcamp.

His experience with networks, protocol analyzers, and IP telephony combined with his teaching experience gave him an edge to write this book. This is the fourth book written by him. The first one was Configuration Guide for Asterisk PBX, by BookSurge Publishing, the second was Building Telephony Systems with OpenSER, by Packt Publishing, and the third was Building Telepopny Systems With OpenSIPS 1.6, by Packt Publishing.

As the CTO of SipPulse, Flavio balances his time between family, work, and fun. He is the father of two children and lives in Florianopolis, Brazil—one of the most beautiful places in the world. He dedicates his free time to water sports such as surfing and sailing.

Bogdan-Andrei Iancu entered the SIP world in 2001, right after graduating in computer science from the Politehnica University of Bucharest, Romania. He started as a researcher at the FOKUS Fraunhofer Institute, Berlin, Germany. For almost four years, Bogdan accumulated a quick understanding and experience of VoIP/SIP, being involved in research and industry projects and following the evolution of the VoIP world closely.

In 2005, he started his own company, Voice System. The company entered the open source software market by launching the OpenSER/OpenSIPS project—a free GPL-SIP proxy implementation. As the CEO of Voice System, Bogdan pushes the company in two directions: developing and supporting.

The OpenSIPS public project (Voice System being the major contributor and sponsor of the project) creates professional solutions and platforms (OpenSIPS-based) for the industry. In other words, Bogdan's interest was to create knowledge (through the work with the project) and to provide the knowledge where needed (embedded in commercial products or raw format as consultancy services). In the effort of sharing the knowledge of the SIP/OpenSIPS project, he started to run the OpenSIPS Bootcamp in 2008 together with Flavio E. Goncalves, which is intensive training dedicated to people who want to learn and get hands-on experience on OpenSIPS from experienced people. Bogdan's main concern is to research and develop new technologies or software for SIP-based VoIP (this is the reason for his strong involvement with the OpenSIPS project) and pack all these cutting-edge technologies as professional solutions for the industry.

About the Reviewers

Saúl Ibarra Corretgé started working in the VoIP industry over a decade ago. He has worked in many different areas and projects, from development and configuration to deployment.

In 2006, when OpenSER 1.0.0 (the project where OpenSIPS was forked from) was released, Saúl began to experiment with it. Several years later, he started using it heavily and contributing with code until he became an OpenSIPS core team member in 2010. His contributions to the project have been diverse but mainly focused on improving the presence part.

He also maintains several projects on GitHub (https://github.com/saghul) and you can contact him through his website (http://bettercallsaghul.com) or on Twitter (@saghul).

When not in front of the computer, he likes to travel around the world.

Vyacheslav Kobzar is the chief of software development at Modulis.ca Inc. He graduated from Donetsk State Technical University in 2006, where he was studying software development. Right after graduation, he started to work as a freelance developer on different projects, mostly web development. Since 2008, he started to work remotely in the Canadian company, Modulis.ca Inc. He moved to Canada in 2009 where he continued working at Modulis.ca Inc as a developer on multiple web projects.

He started to work on VoIP in 2011, mostly with Asterisk. He has been working on AGI and AMI modules for different VoIP projects. He was certificated with Asterisk dCAP in 2012. In 2014, Vyacheslav participated in the OpenSIPS eBootcamp session. He has been an OpenSIPS's Foundation member since 2014.

In 2013, he participated in the designing and developing of the Modulis VoIP start-up project, which was later successfully deployed in multiple companies and organizations in Quebec. OpenSIPS is the core part of the project along with other VoIP technologies and protocols (UNIStim, Skinny, and others).

Being a Linux user for almost 10 years, Vyacheslav contributes to different open source projects on GitHub and also works on his own.

I'd like to thank OpenSIPS developers and contributors for this amazing project. I would also like to thank the Modulis team for sharing their knowledge and ideas and always being open for new challenges. Finally, I would like to thank my wife, Anna, for her support and patience.

Mfawa Alfred Onen is a system administrator with more than 6 years' experience in the field of UNIX/Linux system administration. He studied electrical and electronics engineering in his bachelor of engineering undergraduate program and has continued to venture into the area of telecommunications with a postgraduate certificate from Birmingham City University, UK. He currently resides in Nigeria and has worked with both private and education sectors, including numerous consulting jobs for clients at home and abroad.

Being a software developer and having an operations background, he is heavily involved with cloud computing (DevOps) using open source software such as OpenStack, OpenShift, Docker, Asterisk, OpenSIPS, and FreeSWITCH, to name a few. He also helps to manage a Google Developer Group (GDG Bingham University), where software developers and technology enthusiasts come to learn Google developer tools and services in the form of Developer Festivals (DevFest), Hackathons, and Code labs.

When Mfawa is not busy with technology, he is an avid gamer (Call of Duty, NFS, and Forza) and a blogger at http://www.maomuffy.com/ with much content on OpenShift, OpenStack, RADIUSDesk, Linux/UNIX system administration, and so on.

My special thanks goes to my family (Professor Alfred Ikpi Onen, Mrs. Jummai Alfred Onen, Dr. Eno Alfred Onen, Williams Alfred Onen, and Ikpi Alfred Onen Jnr.), friends (Aderogba Otunla, Alhamdu Bello, Suzanne Coutinho, and others) and well-wishers.

Ali Pey is a senior software engineer architect with more than 23 years experience in telephony, networking, and VoIP. He has an electronics engineering degree with a focus on telecommunication and software design. He has worked for companies such as Nortel, TalkSwitch, and j2 Global, and has been developing VoIP solutions since the start of the technology. He has developed software for proxy servers, registrar servers/clients, user agents, and other VoIP components in both SIP and H.323 protocols. Currently, Ali is an independent consultant and has successfully used OpenSIPS and other open source applications such as Asterisk and FreeSWITCH to provide global telephony cloud solutions.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Preface

This book will be your companion when working with OpenSIPS using a case study for an Internet Telephony Service Provider (ITSP). With the help of this book, you should be able to build a system that is able to authenticate, route, bill, and monitor VoIP calls. Topics and advanced scenarios such as TCP/TLS support, load balancing, asynchronous processing, and more are discussed in depth in this book. You will create dynamic dialplans, route calls using advanced routing, integrate OpenSIPS with a media server, account calls and generate CDRs, provision the system using a Web GUI, and use tools to monitor and check the health of your server. You will also learn some advanced topics such as support for TLS/TCP and the newest technology called asynchronous callbacks.

By the end of this book, you should be able to build a system that is able to authenticate, route, bill, and monitor VoIP calls. Whenever you are thinking big on telephony, OpenSIPS is your savior and this book is your friend!

What this book covers

Chapter 1, Introduction to SIP, introduces you to the SIP server. You will see how to recognize a SIP request and reply according to RFC 3261, identify the mandatory SIP headers, and describe the SIP routing process for initial and sequential requests.

Chapter 2, Introducing OpenSIPS, shows you how OpenSIPS is used in the market, the basic architecture of the system, use cases, and the main target market.

Chapter 3, Installing OpenSIPS, shows you how to download the OpenSIPS source and its dependencies, compile and install OpenSIPS with MySQL and Radius support, and configure the Linux system to start OpenSIPS at boot time.

Chapter 4, OpenSIPS Language and Routing Concepts, introduces you to the OpenSIPS scripting language and OpenSIPS routing concepts. After reading this chapter, you should be able to recognize the OpenSIPS script language, describe its mains commands, process initial requests, and drop or route requests.

Chapter 5, Subscriber Management, shows you how to manage subscribers in the system using the subscriber, location, group, and address databases. You will learn how to implement a multidomain system that is able to support multitenant implementations.

Chapter 6, OpenSIPS Control Panel, demonstrates how to install a web GUI to help with the provisioning of users, dialplan, routes, and other information that is required to run OpenSIPS. You will see how to install, use, configure, and customize the OpenSIPS control panel.

Chapter 7, Dialplan and Routing, enables you to integrate OpenSIPS with PSTN through gateways, selecting the best gateway, and failing over automatically if a response code is negative.

Chapter 8, Managing Dialogs, shows you how to activate the dialog module, limit the number of simultaneous calls, disconnect hanged calls, impose a maximum duration time for a call, and implement SIP session timers integrated with the dialog module.

Chapter 9, Accounting, demonstrates how account calls generate a CDR (Call Detail Record), account correctly forwarded calls, prevent calls without BYE, and add extra fields to the CDR.

Chapter 10, SIP NAT Traversal, helps you implement an OpenSIPS solution for clients behind NAT. You will see how to implement OpenSIPS in a data center such as Amazon AWS where all the servers are behind NAT.

Chapter 11, Implementing SIP Services, implements services such as call forward, forward on busy, and forward on no answer in cooperation with a media server and SIP phone.

Chapter 12, Monitoring Tools, enables you to detect performance issues using the built-in statistics. These include protocol issues using SIP trace, database issues using the benchmark module, script issues using the script trace, and software and hardware issues using GDB.

Chapter 13, OpenSIPS Security, shows you how to increase the security of your OpenSIPS installation.

Chapter 14, Advanced Topics with OpenSIPS 2.1, covers some advanced topics that can be important for specific installations. Topics such as asynchronous processing, TCP and TLS support, binary replication, and NoSQL integration for clusters are discussed.

What you need for this book

All you need for this book is a working installation of OpenSIPS on either Linux or Debian. We will go through the installation of OpenSIPS in detail in this book.

Who this book is for

System integrators who need to scale their VoIP projects, universities, and other entities who need to provide large-scale communication systems based on the SIP protocol can make the best use of this book.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "It also contains a parameter called branch that identifies this transaction."

A block of code is set as follows:

P-Asserted-Identity: "John" sip:[email protected] P-Asserted-Identity: tel:+554833328560

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

if (is_method("INVITE")) { setflag(ACC_DO); # Do accounting setflag(ACC_FAILED); # Account failed transactions }

Any command-line input or output is written as follows:

opensipsctl fifo psopensipsctl fifo debug 4

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "In the following Select your location screen, choose your location to be used in the installation process."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Introduction to SIP

Before we dive into OpenSIPS, it is very important to understand some important concepts related to Session Initiation Protocol (SIP). In this chapter, we will cover a brief tutorial regarding the concepts used later in this book. By the end of this chapter, we will have covered the following topics:

Understanding the basics of SIP and its usageDescribing the SIP architectureExplaining the meaning of its componentsUnderstanding and comparing main SIP messagesInterpreting the header fields' processing for the INVITE and REGISTER messagesLearning how SIP handles identity and privacyCovering the Session Description Protocol and Real-Time Protocol briefly

SIP was standardized by Internet Engineering Task Force (IETF) and is described in several documents known as Request for Comments (RFC). The RFC 3261 describes SIP version 2. SIP is an application layer protocol used to establish, modify, and terminate sessions or multimedia calls. These sessions can be audio and video sessions, e-learning, chatting, or screen sharing sessions. It is similar to Hypertext Transfer Protocol (HTTP) and designed to start, keep, and close interactive communication sessions between users. Nowadays, SIP is the most popular protocol used inInternet Telephony Service Providers (ITSPs), IP PBXs, and voice applications.

The SIP protocol supports five features to establish and close multimedia sessions:

User location: Determines the endpoint address used for communicationUser parameters negotiation: Determines the media and parameters to be usedUser availability: Determines if the user is available or not to establish a sessionCall establishment: Establishes parameters for caller and callee and informs about the call progress (such as ringing, busy, or not found) to both the partiesCall management: Facilitates session transfer and closing

The SIP protocol was designed as a part of a multimedia architecture containing other protocols such as Resource Reservation Protocol (RSVP), Real-Time Protocol (RTP), Real-Time Session Protocol (RTSP), Session Description Protocol (SDP), andSession Announcement Protocol (SAP). However, it does not depend on them to work.

Understanding the SIP architecture

SIP has borrowed many concepts from the HTTP protocol. It is a text-based protocol and uses the same Digest mechanism for authentication. You will also notice similar error messages such as 404 (Not found) and 301 (Redirect). As a protocol developed by the IETF, it uses an addressing scheme similar to Simple Mail Transfer Protocol (SMTP). The SIP address is just like an e-mail address. Another interesting feature used in SIP proxies are aliases; you can have multiple SIP addresses for a single subscriber such as the following:

In the SIP architecture, there are user agents and servers. SIP uses a peer-to-peer distributed model with a signaling server. The signaling server only handles the SIP signaling, while the user agent clients and servers handle signaling and media. This is depicted in the following figure:

In the traditional SIP model, a user agent, usually a SIP phone, will start communicating with its SIP proxy, seen here as the outgoing proxy (or its home proxy) to send the call using a message known as INVITE.

The outgoing proxy will see that the call is directed to an outside domain. According to RFC 3263, it will seek the DNS server for the address of the target domain and resolve the IP address. Then, the outgoing proxy will forward the call to the SIP proxy responsible for DomainB.

The incoming proxy will query its location table for the IP address of agentB if its address was inserted in the location table by a previous registration process. It will forward the call to agentB.

After receiving the SIP message, agentB will have all the information required to establish an RTP session (usually audio) with agentA sending a 200 OK response. Once agentA receives the response from agentB, a two-way media can be established. A BYE request message can terminate the session.

Here, you can see the main components of the SIP architecture. The entire SIP signaling flows through the SIP proxy server. On the other hand, the media is transported by the RTP protocol and flows directly from one endpoint to another. Some of the components will be briefly explained in the sequence.

In the preceding image, you can see the following components:

UAC (User Agent Client): A client or terminal that starts the SIP signalingUAS (User Agent Server): A server that responds to the SIP signaling coming from a UACUA (User Agent): A logical entity that can act as both UAC or UAS, such as a SIP endpoint (IP phones, ATAs, softphones, and so on)Proxy Server: Receives requests from a UA and transfers to another SIP proxy if this specific terminal is not under its domainRedirect Server: Receives requests and responds to the caller with a message containing data about the destination (302, Moved Temporarily)Registrar Server: Provides the callee's contact addresses to the proxy and redirect servers

The proxy, redirect, and registrar servers are usually available physically in the same computer and software.

The SIP registration process

The SIP registration process is shown as follows:

The SIP protocol employs a component called Registrar. It is a server that accepts REGISTER requests and saves the information received in these packets on the location server for their managed domains. The SIP protocol has a discovery capacity; in other words, if a user starts a session with another user, the SIP protocol has to discover an existent host where the user can be reached. The discovery process is done (among others) by a Registrar server that receives the request and finds the location to send it. This is based in a location database maintained by the Registrar server per domain. The Registrar server can accept other types of information, not only the client's IP addresses. It can receive other information such as Call Processing Language (CPL) scripts on the server.

Before a telephone can receive calls, it needs to be registered with the location database. In this database, we will have all the phones associated with their respective IP addresses. In our example, you will see the sip user, [email protected], registered with the IP address, 200.180.1.1.

RFC 3665 defines best practices to implement a minimum set of functionalities for a SIP IP communications network. In the following table, the flows are defined according to RFC 3665 for registration transactions. According to RFC 3665, there are five basic flows associated with the process of registering a user agent.

Message flow

Description

A successful new registration: After sending the Register request, the user agent will be challenged against its credentials. We will see this in detail in Chapter 5, Subscriber Management.

An update of the contact list: As it is not a new registration, the message already contains the Digest and a 401 message won't be sent. To change the contact list, the user agent just needs to send a new register message with the new contact in the CONTACT header field.

A request for the current contact list: In this case, the user agent will send the CONTACT header field empty, indicating that the user wishes to query the server for the current contact list. In the 200 OK message, the SIP server will send the current contact list in the CONTACT header field.

The cancellation of a registration: The user agent now sends the message with an EXPIRES header field of 0 and a CONTACT header field configured as * to apply to all the existing contacts.

Unsuccessful Registration: The UAC sends a REGISTER request and receives a 401 Unauthorized Message in exactly the same way as the successful registration. In the sequence, it produces a hash and tries to authenticate. The server, detecting an invalid password, sends a 401 Unauthorized message again. The process will be repeated for the number of retries configured in the UAC.

Types of SIP servers

There are a few different types of SIP servers. Depending on the application, you can use one or all of them in your solution. OpenSIPS can behave as a proxy, redirect, B2BUA, or Registrar server.

The proxy server

In the SIP proxy mode, all SIP signaling goes through the SIP proxy. This behavior will help in processes such as billing and is, by far, the most common choice. The drawback is the overhead caused by the server in the middle of all the SIP communications during the session establishment. Regardless of the SIP server role, the RTP packets will go directly from one endpoint to another even if the server is working as a SIP proxy.

The redirect server

The SIP proxy can operate in the SIP redirect mode. In this mode, the SIP server is very scalable because it doesn't keep the state of the transactions. Just after the initial INVITE, it replies to the UAC with a 302 Moved Temporarily and is removed from the SIP dialog. In this mode, a SIP proxy, even with very few resources, can forward millions of calls per hour. It is normally used when you need high scalability but don't need to bill the calls.

The B2BUA server

The server can also work as a Back-to-Back User Agent (B2BUA). B2BUAs are normally applied to hide the topology of the network. They are also useful to support buggy clients unable to route SIP requests correctly based on record routing. Many PBX systems such as Asterisk, FreeSwitch, Yate, and others work as B2BUAs.

SIP request messages

There are several types of message requests. SIP is transactional, communicating through requests and replies. The most important types of requests are described in the following table:

Message

Description

RFC

ACK

Acknowledges an INVITE

RFC 3261

BYE

Terminates an existing session

RFC 3261

CANCEL

Cancels a pending registration

RFC 3261

INFO

Provides mid-call signaling information

RFC 2976

INVITE

Session establishment

RFC 3261

MESSAGE

Instant message transport

RFC 3428

NOTIFY

Sends information after subscribing

RFC 3265

PRACK

Acknowledges a provisional response

RFC 3262

PUBLISH

Uploads the status information to the server

RFC 3903

REFER

Asks another UA to act onUniform Resource Identifier (URI)

RFC 3515

REGISTER

Registers the user and updates the location table

RFC 3261

SUBSCRIBE

Establishes a session to receive future updates

RFC 3265

UPDATE

Updates a session state information

RFC 3311

Most of the time, you will use REGISTER, INVITE, ACK, BYE, and CANCEL. Some messages are used for other features. For example, INFO is used forDual-tone Multi-frequency (DTMF) relay and mid-call signaling information. PUBLISH, NOTIFY, and SUBSCRIBE give support to the presence systems. REFER is used for call transfer and MESSAGE for chat applications. Newer requests can appear depending on the protocol standardization process. Responses to these requests are in the text format as in the HTTP protocol. Some of the most important replies are shown as follows:

The SIP dialog flow

Let's examine this message sequence between two user agents as shown in the following figure. You can see several other flows associated with the session establishment in RFC 3665:

The messages are labeled in sequence. In this example, userA uses an IP phone to call another IP phone over the network. To complete the call, two SIP proxies are used.

The userA calls userB using its SIP identity called the SIP URI. The URI is similar to an e-mail address, such as <sip:[email protected]>. A secure SIP URI can be used too, such as <sips:[email protected]>. A call made using sips: (Secure SIP) will use a secure transport, Transport Layer Security (TLS), between the caller and callee.

The transaction starts with userA sending an INVITE request addressed to userB. The INVITE request contains a certain number of header fields. Header fields are named attributes that provide additional information about the message and include a unique identifier, the destination, and information about the session.

The first line of the message contains the method name and request URI. The following lines contain a list of header fields. This example contains the minimum set required. The header fields have been described as follows:

Method and Request-URI: In the first line, you have the request URI also referred to as RURI. It contains the current destination of the message and is often manipulated by the proxies to route a request. It is the most important field in a SIP request.Via: This contains the address to which userA will be waiting to receive responses to this request. It also contains a parameter called branch that identifies this transaction. The Via header defines the last SIP hop as IP, transport, and transaction-specific parameters. Via is used exclusively to route back the replies. Each proxy adds an additional Via header. It is a lot easier for replies to find their route back using the Via header than to go again in the location server or DNS.To: This contains the name (display name) and SIP URI (that is, <sip:[email protected]>) in the destination originally selected. The To header field is not used to route the packets.From: This contains the name and SIP URI (that is, <sip:[email protected]>) that indicates the caller ID. This header field has a tag parameter containing a random string that was added to the URI by the IP phone. It is used for the purposes of identification. The tag parameter is used in the To and From fields. It serves as a general mechanism to identify the dialog, which is the combination of the Call-ID along with the two tags, one from each participant in the dialog. Tags can be useful in parallel forking.Call-ID: This contains a globally unique identifier for this call generated by the combination of a random string and it may contain the hostname or IP address of the UAC. A combination of the To, From, and Call-ID tags fully defines an end-to-end SIP relation known as a SIP dialog.CSeq: The CSeq or command sequence contains an integer and a method name. The CSeq number is incremented to each new request in a SIP dialog and is a traditional sequence number.Contact: This contains a SIP URI, which represents a direct route to contact userA, usually composed of a user name and fully qualified domain name (FQDN). It is usual to use the IP address instead of the FQDN in this field. While the Via header field tells the other elements where to send a response, the Contact tells the other elements where to send future requests.Max-Forwards: This is used to limit the number of allowed hops that a request can make in the path to their final destination. It consists of an integer decremented by each hop.Content-Type: This contains a body message description.Content-Length: This contains a byte count of the body message.

Session details such as the media type and codec are not described in SIP. Instead, it uses theSession Description Protocol (SDP) (RFC 2327). This SDP message is carried by the SIP message, similar to an e-mail attachment.

The phone does not know the location of userB or the server responsible for domainB. Thus, it sends the INVITE request to the server responsible for the domain, sipA. This address is configured in the phone of userA or can be discovered by DNS. The server sipA.com is also known as the SIP proxy for the domain sipA.com.

The sequence is as follows:

In this example, the proxy receives the INVITE request and sends a 100 Trying reply back to userA, indicating that the proxy received INVITE and is working to forward the request. The SIP reply uses a three-digit code followed by a descriptive phrase. This response contains the same To, From, Call-ID, and CSeq header fields and a branch parameter in the header field, Via. This allows for the userA's phone to correlate the INVITE request that is sent.ProxyA locates ProxyB consulting a DNS server (NAPTR and SRV records) to find which server is responsible for the SIP domain sipB and forwards the INVITE request. Before sending the request to proxyA, it adds a Via header field that contains its own address. The INVITE request already has the address of userA in the first Via header field.ProxyB receives the INVITE request and responds with a 100 Trying reply to ProxyA indicating that it is processing the request.ProxyB consults its own location database for userB's address and then it adds another Via header field with its own address to the INVITE request and forwards this to userB's IP address.The userB's phone receives the INVITE request and starts ringing. The phone responds to this condition by sending a 180 Ringing reply.This message is routed back through both the proxies in the reverse direction. Each proxy uses the Via header fields to determine where to send the response and removes its own Via header from the top. As a result, the message 180 Ringing can return to the user without any lookups to DNS or Location Service and without the need for stateful processing. Thus, each proxy sees all the messages resulting from the INVITE request.When userA's phone receives the 180 Ringing message, it starts to ring back in order to signal the user that the call is ringing on the other side. Some phones show this in the display.In this example, userB decides to attend the call. When they pick up the handset, the phone sends a response of 200 OK to indicate that the call was taken. The 200 OK message contains in its body a session description specifying the codecs, ports, and everything pertaining to the session. It uses the SDP protocol for this duty. As a result, an exchange occurs in two phases of messages from A to B (INVITE) and B to A (200 OK) negotiating the resources and capabilities used on the call in a simple offer/response model. If userB does not want to receive the call or is busy, the 200 OK won't be sent and a message signaling the condition (that is, 486 Busy Here) will be sent instead.

The first line contains the response code and a description (OK). The following lines contain the header fields. The Via, To, From, Call-ID, and CSeq fields are copied from the INVITE request and the To tag is attached. There are three Via fields: one added by userA, another by ProxyA, and finally, ProxyB. The SIP phone of userB adds a tag parameter for the To and From headers and will include this tag on all the future requests and responses for this call.

The Contact header field contains the URI by which userB can be contacted directly in its own IP phone.

The Content-Type and Content-Length header fields give some information about the SDP header. The SDP header contains media-related parameters used to establish the RTP session.

After answering the call, the following occurs:

The 200 OK message is sent back through both the proxies and received by userA and then the phone stops ringing, indicating that the call was accepted.Finally, userA sends an ACK message to userB's phone confirming the reception of the 200 OK message. When record routing is not involved, the ACK is sent directly from phoneA to phoneB avoiding both the proxies. ACK is the only SIP method that has no reply. The endpoints learn each other's addresses from the CONTACT header fields during the INVITE process. This ends the cycle, INVITE/200 OK/ACK, also known as the SIP three-way handshake.At this moment, the session between both the users starts and they send media packets to each other using a mutually agreed format established by the SDP protocol. Usually, these packets are end to end. During the session, the parties can change the session characteristics issuing a new INVITE request. This is called a reinvite. If the reinvite is not acceptable, a 488 Not Acceptable Here message will be sent, but the session will not fail.At the end of the session, userB disconnects the phone and generates a BYE message. This message is routed directly to userA's SIP phone, bypassing both the proxies.The userA confirms the reception of the BYE message with a 200 OK message ending the session. No ACK is sent. An ACK is sent only for INVITE requests.

In some cases, it can be important for the proxies to stay in the middle of the signaling to see all the messages between the endpoints during the whole session. If the proxy wants to stay in the path after the initial INVITE request, it has to add the Record-Route header field to the request. This information will be received by userB's phone and will send back the message through the proxies with the Record-Route header field included too. Record-routing is used in most scenarios. Without record-routing, it is not possible to account the calls and there is no control of the SIP dialog in the proxy.

The REGISTER request is the way that ProxyB learns the location of userB. When the phone initializes or in regular time intervals, the SIP phoneB sends a REGISTER request to a server on domain sipB known as SIP Registrar. The REGISTER messages associate a URI (<[email protected]>) to an IP address. This binding is stored in a database in the Location server. Usually the Registrar, Location, and Proxy servers are in the same computer and use the same software such as OpenSIPS. A URI can only be registered by a single device at a certain time.

SIP transactions and dialogs

It is important to understand the