FreeSWITCH 1.0.6 - Michael S. Collins - E-Book

FreeSWITCH 1.0.6 E-Book

Michael S. Collins

0,0
31,19 €

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

Mehr erfahren.
Beschreibung

FreeSWITCH is an open source telephony platform designed to facilitate the creation of voice and chat-driven products scaling from a soft-phone to a PBX and even up to an enterprise-class soft-switch. It is always exciting to design and build your own telephony system to suit your needs, but the task is time consuming and involves a lot of technical skills.This book comes to your rescue, helping you to set up a telephony system fast and easily using FreeSWITCH. It will take you from being a novice to creating a fully-functional telephony system of your own. It is rich with practical examples and will give you all of the information and skills needed to implement your own PBX system.The book begins by introducing the architecture and working of FreeSWITCH before detailing how to plan a telephone system and moving on to the installation, configuration, and management of a feature-packed PBX. You will learn about maintaining a user directory, XML dial plan and advanced dial plan concepts, call routing, and the extremely powerful Event Socket. You will finally learn about the online community and history of FreeSWITCH.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 429

Veröffentlichungsjahr: 2010

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

FreeSWITCH 1.0.6
Credits
About the Authors
About the Reviewer
Preface
What this book covers
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Architecture of FreeSWITCH
A revolution has begun and secrets have been revealed
The FreeSWITCH design: modular, scalable, and stable
Important modules: Endpoint and Dialplan
Complex applications made simple
Voicemail
Multi-party conferencing
The FreeSWITCH API (FSAPI)
The XML registry
Language modules
The default configuration
Summary
2. Building and Installation
Setting up the FreeSWITCH environment
Operating system
Operating system prerequisites
Linux/Unix
Mac OS X
Windows
Text editors and XML
Downloading the source
Building from the latest code
Compiling FreeSWITCH for Linux/Unix/Mac OS X
Compiling FreeSWITCH
Step 1: Edit modules.conf
Step 2: Run configure script
Step 3: Run make and make install
Step 4: Edit modules.conf.xml
Step 5: Install sound and music files
Compiling FreeSWITCH for Windows
Building the solution with MSVC/MSVCEE
Starting FreeSWITCH
Running FreeSWITCH in the background
Summary
3. Test Driving the Default Configuration
Important concepts to understand
Putting FreeSWITCH to work
Controlling FreeSWITCH with the CLI
Configuring a SIP phone to work with FreeSWITCH
SIP settings
X-Lite softphone
Hard phones
Aastra phones
Polycom phones
Snom phones
Testing the default Dialplan
Test calls for a single phone
The "Tetris" extension
Echo test
Music on hold
Demonstration IVR
The "Information" application
Test calls for two or more phones
Calling another telephone
Parking a call
Calling a conference
Summary
4. SIP and the User Directory
Understanding the FreeSWITCH user directory
Working with the FreeSWITCH user directory
User features
Adding a user
Testing voicemail
Groups of users
Connecting to the world with gateways
Setting up a new gateway
Making calls
Receiving calls
Making calls without a gateway
SIP profiles and user agents
Summary
5. Understanding the XML Dialplan
FreeSWITCH XML Dialplan elements
Call legs and channel variables
Accessing channel variables
Regular expressions
Contexts
Default
Public
Features
Extensions
Conditions
Actions and anti-actions
How Dialplan processing works
Creating a new extension
Important Dialplan applications
bridge
playback
say
play_and_get_digits
ivr
sleep
answer
hangup
set
Dialstring formats
Summary
6. Using the Built-in XML IVR Engine
IVR engine overview
IVR XML configuration file
IVR menu definitions
greet-long
greet-short
invalid-sound
exit-sound
timeout
inter-digit-timeout
max-failures
max-timeouts
digit-len
tts-voice
tts-engine
confirm-key
IVR menu destinations
menu-exec-app
menu-exec-api
menu-play-sound
menu-back
menu-top
Routing calls to your IVR
Nesting IVRs
Using phrases with IVRs
Calling Phrase Macros
Phrase Macro examples: voicemail
Advanced routing
Summary
7. Building IVR Applications with Lua
Getting started with Lua
Running Lua scripts from the Dialplan
Basic Lua syntax
Building voice applications
Simple IVR—interacting with the caller
Conditions and looping
Advanced IVR concepts
Connecting to a database with LuaSQL
Making a web call with curl
Lua patterns versus regular expressions
Scripting tips
Summary
8. Advanced Dialplan Concepts
Dialplan overview
General Dialplan concepts
Contexts
Conditions
Actions
Putting it all together
XML Dialplan module review
Extensions
Conditions
Special condition variables
Inline execution
Actions and anti-actions
Pitfalls to avoid
XML Dialplan commands
Hunting versus executing
Utilizing variables
Testing variables with regular expressions
Caller profile fields
Channel variables
Channel variables and call setup
Global variables
Dialplan functions
Real-time condition evaluation
String conditioning
Database queries
SIP contact parameters
Set, export, and legs
Set versus export
Passing variables via call headers
XML Dialplan cookbook
Match by IP address and call a number
Match IP address and Caller ID
Match number and strip digits
Match number, strip digits, and add prefix
Call registered device
Try party A, then party B
Check for authenticated user
Route DIDs to extensions
Try a local extension, failback to voicemail
Alternate outbound gateways
Alternatives to XML
YAML
Asterisk Dialplan
Summary
9. Controlling FreeSWITCH Externally
General overview
Event system architecture
Event-based modules
mod_event_socket
Configuring event socket settings
Reading events
Minimum event information
Sending events
Events from the Dialplan
mod_event_multicast
Port/address
Bindings
TTL
mod_erlang_event
FreeSWITCH event system commands
auth <password>
api
bgapi
event
divert_events
filter
filter delete
sendevent
sendmsg <uuid>
execute
hangup
nomedia
log <level>
nolog
noevents
Event-based applications

FreeSWITCH Console application
PHP Socket connections
Perl Socket connections
Event Socket Library
Supported libraries
ESLObject
eslSetLogLevel($loglevel)
ESLevent object
serialize([$format])
setPriority([$number])
getHeader($header_name)
getBody()
getType()
addBody($value)
addHeader($header_name, $value)
delHeader($header_name)
firstHeader()
nextHeader()
ESLconnection object
new($host, $port, $password)
new($fd)
socketDescriptor()
connected()
getInfo()
send($command)
sendRecv($command)
api($command[, $arguments])
bgapi($command[, $arguments])
sendEvent($send_me)
recvEvent()
recvEventTimed($milliseconds)
filter($header, $value)
events($event_type,$value)
execute($app[, $arg][, $uuid])
executeAsync($app[, $arg][, $uuid])
setAsyncExecute($value)
setEventLock($value)
disconnect()
Events in practice
Event Socket Library example: running a command
Examples of sending events to FreeSWITCH
Setting phone lights
Turn lights on
Turn lights off
Rebooting a phone
Requesting phone reconfiguration
Custom notify messages
Summary
10. Advanced Features and Further Reading
Multi-user conferencing
Configuration
Conference profiles
Caller controls
Advertise
Sending and receiving XMPP events
Connecting callers to the conference
Controlling active conferences
Nibblebill
Use cases
Billing (pre-pay)
Billing (post-pay)
Pay-per-call service billing
Maximum credit and/or fraud prevention
Design goals
Installation and configuration
Database tables
Creating the database table for PostgreSQL
Creating the database table for MySQL
Billing a call
Nibble method (default)
Alternative to nibble billings
Examples
Different rates per user
Single rate for all users
Different rates per area code
Different rates per service delivery
Hang up the call when the balance is depleted
Application/CLI/API commands
Check
Flush
Pause
Resume
Reset
Adding and deducting funds
Enabling session heartbeat
Bill based on B leg only
XML/Curl
Installation
Configuration
Bindings
HTTP requests
HTTP response
Optimization
Order of requests
Request/response examples
mod_sofia
ACL
Authorization
Voicemail request
Dialplan bindings
Request
Reply
Other bindings
General "Not found" reply
Debugging
Failing back
Alternative endpoints
Skype and GSM endpoints
Skype with mod_skypopen
GSM with mod_gsmopen
TDM with OpenZAP and FreeTDM
Configuration tools and related projects
Web GUIs
WikiPBX
FreePBX v3
FusionPBX
2600hz
Supporting libraries
Liverpie (Ruby)
FreeSWITCHeR (Ruby)
Librevox (Ruby)
EventSocket (Python/Twisted)
FSSocket (Perl)
Summary
A. The FreeSWITCH Online Community
The FreeSWITCH mailing lists
Talking in real-time via IRC
The FreeSWITCH main website and wiki
The main FreeSWITCH page—www.freeswitch.org
The FreeSWITCH Wiki page—wiki.freeswitch.org
The annual ClueCon open source developer conference
B. The History Of FreeSWITCH
Index

FreeSWITCH 1.0.6

FreeSWITCH 1.0.6

Copyright © 2010 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: July 2010

Production Reference: 1190710

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847199-96-6

www.packtpub.com

Cover Image by Leisha Bryant (<[email protected]>)

Credits

Authors

Anthony Minessale

Michael S. Collins

Darren Schreiber

Reviewer

Justin Zimmer

Acquisition Editor

Usha Iyer

Development Editors

Neha Patwari

Tarun Singh

Technical Editors

Rupal J

Charumathi Sankaran

Copy Editors

Neha Shetty

Leonard D'Silva

Indexer

Tejal Daruwale

Editorial Team Leader

Aanchal Kumar

Project Team Leader

Priya Mukherji

Project Coordinator

Prasad Rai

Proofreader

Lynda Sliwoski

Graphics

Geetanjali Sawant

Production Coordinator

Shantanu Zagade

Cover Work

Shantanu Zagade

About the Authors

Anthony Minessale has been involved in telephony since 2003. Prior to that, he had spent over ten years as a CTO and platform designer for various companies during the height of the Internet revolution. He has spent over half a decade working as the creator and lead developer of the FreeSWITCH open source project and several years before that as a volunteer developer for the Asterisk open source PBX, and is a noted contributor of several features on that project as well.

Anthony is the creator and owner of FreeSWITCH Solutions LLC, responsible for the popular annual VoIP conference, ClueCon, held every summer in Chicago. Anthony also works for Barracuda Networks as the director of Engineering for the CudaTEL PBX appliance, a product he and his team handcrafted to work with FreeSWITCH as the telephony engine.

I would like to thank the awesome FreeSWITCH community for their dedication to our project and the invaluable feedback they provide on a daily basis. A really big thank you to Michael Collins and Darren Schreiber for helping to put this book together. I would also like to thank Brian West and Michael Jerris for helping make FreeSWITCH even possible with all the time they devote to making it work. Finally I would like to thank the original Asterisk community who inspired us all to relentlessly push forward in open source telephony.

Michael S. Collins is a telephony and open source software enthusiast. He is a PBX veteran, having worked as a PBX technician for five years and as the head of IT for a call center for more than nine years. Michael is an active member of the FreeSWITCH community. He currently works for Barracuda Networks, Inc.

I would like to thank, first and foremost, my wife, Lisa, my daughter, Katherine, and my son, Sean, who keep me going each day. I would also like to thank the many FreeSWITCH experts around the world who are so willing to answer technical questions: Michael Jerris, Moises Silva, Raymond Chandler, Mathieu Réné and more. I would especially like to thank Brian K. West for taking me under his wing and educating me in the ways of VoIP. Finally, I would like to say thank you to Anthony Minessale for authoring an amazing piece of software and inviting me to work with the core FreeSWITCH development team.

Darren A. Schreiber is helping pioneer the way to distributed cloud telephony solutions. He is the founder of the 2600hz Project, the TCAI project, and is the author of the latest version of FreePBX, a popular open source telephony management system. He has worked in Enterprise IT for over 15 years and has lead teams in successful projects in telecom, marketing, and web-based SaaS spaces. He has been a serious telephony enthusiast from a young age and has been working extensively with VoIP technologies for the past seven years. Darren graduated from Rensselaer with a degree in Computer Science and Business Entrepreneurship.

About the Reviewer

Justin Zimmer has worked in the contact center technology field for over twelve years. During that time, he has performed extensive software and computer telephony integrations using both PSTN and IP telephony. His current projects include system designs utilizing open source softswitches over more traditional proprietary hardware-based telephony, and the integration of these technologies into market-specific CRM products.

As the Technical Partner of Unicore Technologies out of Phoenix, AZ, Justin is developing hosted contact center solutions for the low-end market. Unicore's solutions present contact centers with low startup costs in a turbulent economy, and allows those centers to scale their business while maintaining a consistent and familiar user interface.

I'd like to thank the countless community contributors that have provided enough online documentation to make this book as accurate and helpful as possible. And I'd like to thank my wife Nicole for putting up with the extra hours spent reviewing this book, as well as my boys Micah, Caden, and daughter Keira for giving up some of their daddy-time for this project.

Preface

In 1999, the first shot of the telephony revolution was fired when the Asterisk PBX was released to the world. In the ensuing decade, open source telephony took the world by storm, lead by Asterisk and a host of other software packages such as OpenSER and YATE.

In 2006, an Asterisk developer named Anthony Minessale announced an ambitious project: a new telephony software engine, built from the ground up. Some thought this was crazy considering the wild success of the Asterisk platform. However, Anthony's vision was to create a telephony platform unlike any in existence—open source or proprietary. In May 2008, this new project reached a critical milestone with the release of FreeSWITCH 1.0.0.

Now that FreeSWITCH has been available for several years, some developers have migrated from Asterisk to FreeSWITCH. Others have added FreeSWITCH to an existing environment, having it work together with Asterisk, OpenSER, OpenSIPS, Kamailio, and other telephony applications.

Is FreeSWITCH right for you? The correct answer is, of course: It depends. When people ask the FreeSWITCH developers which telephony software they should use, the developers always reply with another correct answer: Use what works for your situation. To know the answer you will need to investigate further.

What FreeSWITCH is and what it is not

FreeSWITCH is a scalable softswitch. In practical terms this means that it can do anything a traditional PBX can do and much more. It can (and does) act as the core switching software for commercial carriers. It can scale up to handle thousands of simultaneous calls. It can also scale down to act as a simple softphone for your laptop or personal computer. It can also work in a cluster of servers.

FreeSWITCH is not a proxy server. If you need proxy server functionality, then consider OpenSIPS, Kamailio, or other similar software. FreeSWITCH is a back-to-back user agent or B2BUA. In this regard, it is similar to Asterisk and other IP PBX software.

Version and licensing

At the time of this writing this book, the FreeSWITCH developers were putting the finishing touches on FreeSWITCH version 1.2. While the examples presented in this book were specifically tested with version 1.0.6, they have also been confirmed to work with the latest FreeSWITCH development versions that form the basis of version 1.2. Do not be concerned about the fact that this material does not cover version 1.2—it certainly does. The FreeSWITCH user interface is very stable between versions; therefore, this text will be applicable for years to come.

FreeSWITCH is released under the Mozilla Public License (MPL) version 1.1. Since FreeSWITCH is a library that can be implemented in other software applications and projects, the developers felt it important to strike a balance between the extremely liberal BSD license and the so-called "viral" GPL. The MPL fits this paradigm well and allows businesses to create commercial products based on FreeSWITCH without licensing concerns.

However, what about using FreeSWITCH with GPL-based software? It should suffice if we said that the developers wanted to make sure that anyone, including proprietary and GPL-based software users, could use FreeSWITCH. The powerful event socket gives us this functionality—a simple TCP socket-based interface that allows an external program to control FreeSWITCH. Regardless of the license you may be using for your own software, you can still connect to a FreeSWITCH server without any licensing issues.

What this book covers

Chapter 1, Architecture of FreeSWITCH gives a brief, but thorough introduction to the underlying architecture of FreeSWITCH.

Chapter 2, Building and Installation shows how to download and install FreeSWITCH on Windows and Unix-like operating systems.

Chapter 3, Test Driving the Default Configuration provides a hands-on look at the powerful and feature-rich default FreeSWITCH configuration.

Chapter 4, SIP and the User Directory offers an introduction to the concept of users and the directory as well as brief look at SIP user agents.

Chapter 5, Understanding the XML Dialplan explains the basics of creating and editing Dialplan extensions to add advanced functionality to a FreeSWITCH install.

Chapter 6, Using the Built-In XML IVR Engine discusses how to create menus and sound phrases for interacting with callers.

Chapter 7, Building IVR Applications with Lua introduces the concept of advanced call handling using the lightweight scripting language Lua.

Chapter 8, Advanced Dialplan Concepts builds upon the foundation laid in Chapter 5 and shows how to handle more challenging routing scenarios.

Chapter 9, Controlling FreeSWITCH Externally introduces the incredibly powerful Event Socket and the Event Socket library that can be used to access and control a FreeSWITCH server.

Chapter 10, Advanced Features and Further Reading highlights some of the more powerful FreeSWITCH features like conferencing and offers some ideas on where to learn more about FreeSWITCH.

Appendix A, The FreeSWITCH Online Community gives a brief introduction to the worldwide online community and the tools used to stay in contact.

Appendix B, The History Of FreeSWITCH is a description of how FreeSWITCH came to be from one of the authors, Anthony Minessale.

Who this book is for

This book is for prospective FreeSWITCH administrators as well as enthusiasts who wish to learn more about how to set up, configure, and extend a FreeSWITCH installation. If you are already using FreeSWITCH, you will find that the information in this book compliments what you have already learned from your personal experience.

A solid understanding of basic networking concepts is very important. Previous experience with VoIP is not required, but will certainly make the learning process go faster.

Conventions

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

Code words in text are shown as follows:"If there is a match, (and there always will be), then this macro plays the vm-goodbye.wav file."

A block of code is set as follows:

<action application="playback"data="phrase:myphrase:arg1:arg2:arg3"/> <action application="play_and_get_digits" data="2 5 3 7000 #phrase:myphrase:arg1 /invalid.wav my_var \d+"/>

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

<input pattern="^(1):(.*)$" break_on_match="true"> <match> <action function="play-file" data="voicemail/vm-you_have.wav"/> <action function="say" data="$1" method="pronounced"type="items"/> <action function="play-file" data="voicemail/vm-$2.wav"/> <action function="play-file" data="voicemail/vm-message.wav"/> </match> </input>

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

freeswitch@localhost>versionFreeSWITCH Version 1.0.6 (exported)

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "New users should join only the FreeSWITCH-users list, until they are comfortable with the project."

Note

Warnings or important notes appear in a box like this.

Note

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 may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

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

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.

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

Note

Downloading the example code for the book

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

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 would 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/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright 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

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Architecture of FreeSWITCH

Welcome to FreeSWITCH! If you are reading this, then, undoubtedly, you are interested in things like telecommunications and Voice over Internet Protocol (VoIP). FreeSWITCH is revolutionary software created during a telephony revolution. Before looking at the architecture of this powerful software, let's take a look at the colorful world of telecommunications. This will help to put FreeSWITCH into perspective.

In this chapter, we cover:

A telephony revolutionAdvantages of FreeSWITCHEndpoint and Dialplan modulesHow FreeSWITCH simplifies complex applications like Voicemail

A revolution has begun and secrets have been revealed

How and why the telephone works is a mystery to most people. It has been kept secret for years. We just plugged our phones into the wall and they worked, and most people do just that and expect it to work. The telephony revolution has begun, and we have begun to pry the secrets from the clutches of the legacy of the telephony industry. Now, everyday individuals like you and me are able to build phone systems that outperform traditional phone services and offer advanced features for relatively low cost. Some people even use FreeSWITCH to provide telephone services for making a profit. FreeSWITCH has been designed to make all of this easier, so we will go over the architecture to get a better understanding of how it works.

Do not be concerned if some of these concepts seem unnaturally abstract. Learning telephony takes time, especially VoIP. In fact, we recommend that you read this chapter more than once. Absorb as much as you can on the first pass, then come back after you complete Chapter 5, Understanding the XML Dialplan. You will be surprised at how much your understanding of VoIP and FreeSWITCH has improved. Then come back and skim it a third time after you have completed Chapter 9, Controlling FreeSWITCH Externally, at this point, you will have a firm grasp of VoIP and FreeSWITCH concepts. Give yourself plenty of time to digest all of these strange new concepts, and soon you will find that you are a skilled FreeSWITCH administrator. If you keep at it, you will be rewarded with a meaningful understanding of this strange and wonderful world we call telephony.

Telephones and the systems are very complicated and have evolved over the years into several varieties. The most popular type of phone in the U.K. and the U.S. is the traditional analog phone, which we affectionately refer to as POTS lines or Plain Old Telephone Service. From the traditional Ma Bell phone up to the long-range cordless phones that most of us have today, one thing has remained the same—the underlying technology. In the last 10-15 years, there has been a convergence of technology between computers and telephones that has produced a pair of affordable alternatives to POTS lines—Mobile phones and VoIP phones (also called Internet Phones).

FreeSWITCH fits into this big tangled mess of various telephone technologies by bridging them together, so that they can communicate despite being otherwise completely incompatible. FreeSWITCH also bridges telephone calls with computer programs that you can write yourself, and controls what happens in ways like never before. FreeSWITCH is software that runs on Windows and several UNIX varieties such as Mac OS X, Linux, Solaris, and BSD. This means you can install FreeSWITCH on your home PC or even a high-end server and use it to process phone calls. Installing FreeSWITCH is discussed in detail in Chapter 2, Building and Installation. We will be doing this as soon as we review the basic architecture.

The FreeSWITCH design: modular, scalable, and stable

The design goal of FreeSWITCH is to provide a modular, scalable system around a stable switching core, and provide a robust interface for developers to add to and control the system. Various elements in FreeSWITCH are independent of each other and do not have much knowledge about how the other parts are working, other than what is provided in what are called ''exposed functions''. The functionality of FreeSWITCH can also be extended with loadable modules, which tie a particular external technology into the core.

FreeSWITCH has many different module types that revolve around the central core, much like satellites orbiting a planet. The list includes:

Module Type:

Purpose:

Endpoint

Telephone protocols like SIP/H.323 and POTS lines.

Dialplan

Parse the call details and decide where to route the call.

Codec

Translate between audio formats.

Application

Perform a task such as play audio or set data.

Application Programming Interface (API)

Export a function that takes text input and returns text output, which could be used across modules or from an external connection.

File

Provide an interface to extract and play sound from various audio file formats.

Text-To-Speech (TTS)

Interface with text-to-speech engines.

Automated Speech Recognition ASR

Interface with speech recognition systems.

Directory

Connect directory information services, such as LDAP, to a common core lookup API.

Chat

Bridge and exchange various chat protocols.

Say

String together audio files in various languages to provide feedback to say things like phone numbers, time of day, spell words, and so on.

By combining the functionality of the various module interfaces, FreeSWITCH can be configured to connect IP phones, POTS lines, and IP-based telephone service. It can also translate audio formats and interfaces with a custom menu system, which you can create by yourself. You can even control a running FreeSWITCH server from another machine. Let's start by taking a closer look at one of the more widely used modules, namely, the Endpoint module.

Important modules: Endpoint and Dialplan

Endpoint modules are critically important and add some of the key features which make FreeSWITCH the powerful platform it is today. The primary role of these modules is to take certain common communication technologies and normalize them into a common abstract entity which we refer to as a session. A session represents a connection between FreeSWITCH and a particular protocol. There are several Endpoint modules that come with FreeSWITCH, which implement several protocols such as SIP, H.323, Jingle (Google Talk), and some others. We will spend some time examining one of the more popular modules named mod_sofia.

Sofia-SIP(http://sofia-sip.sourceforge.net) is an open source project sponsored by Nokia, which is determined to make a programming interface to the Session Initiation Protocol or SIP. We use this library in FreeSWITCH in a module we call mod_sofia. This module registers to all the hooks in FreeSWITCH necessary to make an Endpoint module, and translates the native FreeSWITCH constructs into SIP constructs and back again. Configuration information is taken from the central FreeSWITCH configuration files, which allows mod_sofia to load user-defined preferences and connection details. This allows FreeSWITCH to accept registration from SIP phones and devices, register to other SIP Endpoints such as service providers, send notifications, and provide services to the phones such as voicemail.

When a SIP call is established between FreeSWITCH and another SIP device, it will show up in FreeSWITCH as an active session. If the call is inbound, it can be transferred or bridged to interactive voice response (IVR) menus, hold music, or one or more extensions, though numerous other options are available. Let's examine a typical scenario where a SIP phone registered as extension 2000 calls extension 2001, with the hope of establishing a call.

First, the SIP phone sends a call setup message to mod_sofia over the network (mod_sofia is ''listening'' for such messages). After receiving the message, mod_sofia in turn parses the relevant details and passes the call into the core state machine in FreeSWITCH. The state machine (in the FreeSWITCH core) then sends the call into the ROUTING state. The next step is to locate the Dialplan module, based on the configuration data for the calling Endpoint. The default and most widely used Dialplan module is the XML Dialplan module. This module is designed to look up a list of instructions from the central XML registry within FreeSWITCH. The XML Dialplan module will parse a series of XML extension objects using regular expression pattern-matching. As we are trying to call 2001, we hope to find an XML extension testing the destination_number field for something that matches ''2001'' and routes accordingly. The Dialplan is not limited to matching only a single extension. In fact, in Chapter 5, Understanding the XML Dialplan, you will get an expanded definition of the term ''extension''. The XML Dialplan module builds a sort of ''task list'' for the call. Each extension that matches it will have its actions added to the call's task list.

Assuming FreeSWITCH finds at least one extension, the XML Dialplan will insert instructions into the session object with the information it needs to try and connect the call to 2001. Once these instructions are in place, the state of the calling session changes from ROUTING to EXECUTE where the next handler drills down the list and executes the instructions obtained by the ROUTING state. This is where the application interface comes into the picture.

Each instruction is added to the session in the form of an application name and a data argument that will be passed to that application. The one we will use in this example is the bridge application. The purpose of this application is to create another session with an outbound connection, then connect the two sessions for direct audio exchange. The argument we will supply to bridge will be user/2001, which is the easiest way to generate a call to extension 2001. A Dialplan entry for ''2001'' might look like this:

<extension name="example"> <condition field="destination_number" expression="^2001$"> <action application="bridge" data="user/2001"/> </condition> </extension>

The extension is named ''example'', and it has a single condition to match. If the condition is matched, it has a single application to execute. In plain language, the mentioned extension could be expressed like this: If the caller dialed ''2001'', then this establishes a connection between the calling party and the endpoint (that is, telephone) at 2001. Consider how this happens.

Once we have inserted the instructions into the session, the session's state will change to EXECUTE, and the FreeSWITCH core will use the data collected to perform the desired action. First, the default execute state handler will parse the command to execute bridge on user/2001, then it will look up the bridge application and pass the user/2001 data in. This will cause the FreeSWITCH core to create a new outbound session of the desired type. User 2001 is also a SIP phone, so the user/2001 will resolve into a SIP dial string, which will be passed to mod_sofia to ask it to create a new outbound session.

If the setup for that new session is successful, there will now be two sessions in the FreeSWITCH core. The bridge application will take the new session and the original session (the caller's phone) and call the bridge function on it. This allows the audio to flow in both directions, once the person at extension 2001 actually answers the phone. If that user was unable to answer or was busy, a timeout (that is, a failure) would occur and send the corresponding message back to the caller's phone. If a call is unanswered or an extension is busy, many routing options are possible, including call forwarding or voicemail.

All of this happens from the simple action of picking up the phone handset and dialing 2 0 0 1. FreeSWITCH takes all of the complexity of SIP and reduces it to a common denominator. From there, it reduces the complexity further by allowing us to configure a single instruction in the Dialplan to connect the phone at 2000 to the phone at 2001. If we want to allow the phone at 2001 to be able to call the phone at 2000, we can add another entry in the Dialplan going the other way.

<extension name="example 2"> <condition field="destination_number" expression="^2000$"> <action application="bridge" data="user/2000"/> </condition> </extension>

In this scenario, the Endpoint module turned SIP into a FreeSWITCH session and the Dialplan module turned XML into an extension. The bridge application turned the complex code of creating an outbound call, and connecting the audio into a simple application/data pair. Both the Dialplan module and the application module interface are designed around regular FreeSWITCH sessions. Therefore, not only does the abstraction make life easier for us at the user level, it also simplifies the design of the application and the Dialplan because they can be made agnostic of the actual endpoint technology involved in the call. It is because of this abstraction, when we make up a new Endpoint module tomorrow for something like Skype (there is actually such a thing present, by the way), that we can reuse all the same application and Dialplan modules. The same principle applies to the Say, ASR, TTS, and other such modules.

It is possible that you may want to work with some specific data provided by the Endpoint's native protocol. In SIP, for instance, there are several arbitrary headers as well as several other bits of interesting data from the SIP packets. We solve this problem by adding variables to the channel. Using channel variables, mod_sofia can set these arbitrary values as they are encountered in the SIP data where you can retrieve them by name from the channel in your Dialplan or application. This way we share our knowledge of these special variables with the SIP Endpoint. However, the FreeSWITCH core just sees them as arbitrary channel variables, which the core can ignore. There are also several special reserved channel variables that can influence the behavior of FreeSWITCH in many interesting ways. If you have ever used a scripting language or configuration engine that uses variables, then you are at an advantage because channel variables are pretty much the same concept. There is simply a variable name and a value that is passed to the channel and the data is set.

There is even an application interface for this: the set application that lets you set your own variables from the Dialplan.

<extension name="example 3"> <condition field="destination_number" expression="^2000$"> <action application="set" data="foo=bar"/>data="foo=bar"/> <action application="bridge" data="user/2000"/> </condition> </extension>

The recent example is almost identical to the previous example, but instead of just placing the call, we first set the variable ''foo'' equal to the value ''bar''. This variable will remain set throughout the call and can even be referenced at the end of the call in the detail logs.

The more we build things in small pieces, the more the same underlying resources can be reused, making the system simpler to use. For example, the codec interface knows nothing else about the core, other than its own isolated world of encoding and decoding audio packets. Once a proper codec module has been written, it becomes usable by any Endpoint interface capable of carrying that codec in its audio stream. This means that if we get a Text-To-Speech module working, we can generate synthesized speech on any and all Endpoints that FreeSWITCH supports. It does not matter which one comes first as they have nothing to do with each other. However, the addition of either one instantly adds functionality to the other. The TTS module becomes more useful because it can use more codecs; the codecs have become more useful because we added a new function that can take advantage of them. The same idea applies to applications. If we write a new application module, the existing endpoints will immediately be able to run and use that application.

Complex applications made simple

FreeSWITCH removes much of the complexity of more advanced applications. Let's look at two examples of a more complex application.

Voicemail

The first application we will discuss is the voicemail application. The general purpose of this application is probably pretty easy to deduce. It provides voicemail service. This application is useful to add right after the bridge application as a second option, in case the call was not completed. We can do this with a careful combination of application choices, and one of those fancy ''special'' variables that we were discussing earlier. Let's look at a new version of our last extension that also allows us to leave a voicemail:

<extension name="example 4"> <condition field="destination_number" expression="^2000$"> <action application="set" data="hangup_after_bridge=true"/> <action application="bridge" data="user/2000"/> <action application="voicemail" data="default ${domain} 2000"/> </condition> </extension>

Here we see two uses of channel variables. First we set hangup_after_bridge=true telling the system to just hang up once we have had at least one successfully bridged call to another phone and to disregard the rest of the instructions. We are also using the domain variable as seen in brackets prefixed with a dollar sign, ${domain}. This is a special variable that defaults to the auto-configured domain name, which all the phones are using from the configuration.

In the example, we check if someone is dialing "2000". We then try to bridge the call to the phone registered to extension 2000. If the call fails or there is no answer, we will continue to the next instruction, which is to execute the voicemail application. We provide the information the application needs to know, and which extension the voicemail is for so it knows how to handle the situation. Next, the voicemail application plays the pre-recorded greeting or generates one for you using the Say module's interface we briefly discussed earlier. It strings together sound files to make a voice say ''The person at extension 2 0 0 0 is not available, please leave a message''. Next, mod_voicemail prompts you to record a message, and now is your chance to leave your mark in that person's inbox by leaving a voice message. As an additional feature, if you are not satisfied with your recording, you can repeat it as many times as you wish. Once you finally commit, a FreeSWITCH MESSAGE_WAITINGevent is fired into the core event system, which is picked up by mod_sofia by way of an event consumer, where the event information is translated into SIP. If everything goes as planned, the phone registered on extension 2000 will illuminate its message-waiting indicator light!

Again in this example, not only have we seen how to play a greeting, record a message, and send it to a user, we have also uncovered another unsung hero of the FreeSWITCH core—the event system. The FreeSWITCH event system is not a module interface like the other examples, it is a core engine that you can use to bind to named events and react accordingly when an event is received. In other words, throughout the FreeSWITCH core, there are events that are sent and received. Modules can bind to (that is ''listen'' for) various events. They can also ''fire'' events into the event engine; other modules can listen for those events. As we discussed, the Sofia SIP module binds or subscribes to the event designated for MESSAGE_WAITING information. This allows our mod_voicemail module to interact with mod_sofia, without either system having any knowledge about the other's existence. The event is fired by mod_voicemail, received by mod_sofia, and translated into the proper SIP message—all seemingly magical, courtesy of the event system.

There are several challenges with such a complex interactive system when considering all of the possible languages it may need to support as well as what files to play for the automated messages and how they are strung together. The Say module supplies a nice way to string files together, but it is somewhat limited to something specific like spelling a word, counting something, or saying a certain date. The way we overcome this is by defining a more complex layer on top of the Say module called Phrase Macros. Phrase Macros are a collection of XML expressions that pull out a list of arguments by matching a regular expression and executing a string of commands. This is very similar to how the XML Dialplan works, only custom-tailored for interactive voice response scenarios (IVR). For example, when mod_voicemail asks you to record your message, rather than coding in the string of files to make it say that, the code just calls a Phrase Macro called voicemail_record_message. This arbitrary string is shared between mod_voicemail and the Phrase Macro section in the configuration allowing us, the users, to edit the file without doing any fancy programming.

<macro name="voicemail_record_message"> <input pattern="^(.*)$"> <match> <action function="play-file" data="voicemail/vmrecord_message.wav"/> </match> </input> </macro>

When mod_voicemail executes the voicemail_record_message macro, it first matches the pattern, which, in this case, is just to match everything, as this particular macro has no input. If the macro did have input, the pattern matching could be used to perform different actions based on different input. Once a match is found, the match tag is parsed in the XML for action tags just like in our Dialplan example. This macro just plays the file vm_record_message.wav, but more complicated macros, like the ones for verifying your recording or telling you how many messages you have in your inbox, may use combinations of various say modules and playing of audio files. Phrase Macros are discussed in detail in Chapter 6, Using the Built-in XML IVR Engine and used extensively in Chapter 7, Building IVR Applications With Lua.

Once again, we have cooperation among the phrase system, the audio file, and the Say modules loaded by the core being joined together to enable powerful functionality. The Say modules are written specifically for a particular language or ''voice'' within a language. We can programmatically request to say a particular time and have it translated into the proper Say module based on input variables. The Phrase Macro system is a great way to put bigger variable concepts into your code, which can be easily tweaked later by everyday users. For example, if we wanted to make a small IVR that asks us to dial a four-digit number and then just read it back and hang up, we could make one macro called ''mypp_ask_for_digits'' and the other called ''myapp_read_digits''. In our code, we would execute these macros by name—the first one when it is time to ask for the digits and the other one to read back the

digits by passing in the value we entered. Once this is in place, a less-experienced individual could implement the XML files to play the proper sounds. He/she can use the Say modules to read back the number, and it could all be working in multiple languages with no further coding necessary. Voicemail is just one example of FreeSWITCH in use as an application server. There are endless possibilities when we use FreeSWITCH to connect phone calls with computers.

Multi-party conferencing

Another popular feature of FreeSWITCH is delivered by the mod_conference conferencing module. The mod_conference module provides dynamic conference rooms that can bridge together the audio from several audio channels. This can be used to hold meetings where there are several callers who want to interact on the same call. Each new session that connects to the same conference room will join the others, and instantly be able to talk to all of the other participants at the same time. By using a Dialplan example, similar to the one we used for bridging to another phone, we can make an extension to join a conference room:

<extension name="example 4"> <condition field="destination_number" expression="^3000$"> <action application="conference" data="3000@default"/> </condition> </extension>

This is just as simple as bridging a call, but what is special about this extension is that many callers can call extension 3000 and join the same conference. If three people joined this conference and one of them decides to leave, the other two would still be able to continue their conversation. The conference module also has other special features, such as the ability to play sound files or text to speech to the whole conference or even just to a single member of the conference. As you may have guessed, we are able to do this by using the TTS and sound file interfaces provided by their respective modules. Once again, the smaller pieces come together to extend the functionality without needing explicit knowledge of the other components in the system.

The conference module also uses the event system in a special way called custom events. A module such as mod_conference can reserve a special event namespace called a subclass when it first loads. When something interesting happens, such as when a caller joins or leaves a conference, it fires those events on the CUSTOM event channel in the core. When we are interested in receiving such events, all we have to do is subscribe to the CUSTOM event supplying an extra subclass string, which specifies the specific CUSTOM events we are interested in. In this case, it is conference::maintenance. This makes it possible to look out for important things such as when someone joins or leaves the conference or even when they start and stop talking. Conferencing is discussed in detail in Chapter 10, Advanced Features and Further Reading.

The FreeSWITCH API (FSAPI)

Another very powerful module interface in FreeSWITCH is the FSAPI module. The principle of this type of interface is very simple—it takes a single string of text as input, which may or may not be parsed, especially by the following code. The return value is also a string that can be of any size, from a single character up to several pages of text, depending on the function that was called. One major benefit of FSAPI functions is that a module can use them to call routines in another module, without directly linking into the actual code. The command-line interface of FreeSWITCH or CLI uses FSAPI functions to pass commands from your prompt.

Here is a small example of how we can execute the status FSAPI command from the FreeSWITCH CLI:

freeswitch> statusAPI CALL [status()] output:UP 0 years, 3 days, 23 hours, 31 minutes, 31 seconds, 524 milliseconds, 576 microseconds438 session(s) since startup6 session(s) 0/301000 session(s) max

What's really happening here is that when we type status and press the Enter key, the word ''status'' is used to look up the status FSAPI function from the module in which it was implemented. The underlying function is then called, and the core is queried for its status message. Once the status data is obtained, the output is written to a stream that comes back and prints as the result of the command.

We have already learned that a module can create and export FSAPI functions, which can be executed from anywhere such as the CLI. But wait, there's more! Modules can also be written to push commands into the FSAPI interface, and send the result over a specific protocol. There are two modules included in FreeSWITCH that do just that—mod_event_socket and mod_xml_rpc (mod_event_socket discussed in detail in Chapter 9, Controlling FreeSWITCH Externally.) Consider the example of mod_xml_rpc. This module implements the standardized XML-RPC protocol as a FreeSWITCH module. Clients using an XML-RPC interface can connect to FreeSWITCH and execute any FSAPI command they choose. So a remote client could execute an RPC call to status, and get a similar status message to the one we saw in the previous example. This same module also provides FreeSWITCH with a general web server, which allows FSAPI commands to be accessed with a direct URL hit. For example, one could point a browser to http://example.freeswitch.box:8080/api/status to access the status command directly over the World Wide Web. By using this technique, it's possible to create FSAPI commands that work similar to a CGI, providing a dynamic web application that has direct access to FreeSWITCH internals.

As we can see, the FSAPI interface is very versatile. Now we know it can be used to provide a CLI interface, a way for modules to call functions from each other and a way to export WWW or XML-RPC functions. There is still one more use for FSAPI functions that we have not covered. We touched slightly on the concept of channel variables earlier, noting that we can use the expression ${myvariable} to get the value of a certain variable. FSAPI functions can also be accessed this way in the format ${myfunction()}. This notation indicates that the FSAPI command ''myfunction'' should be called, and that the expression should be replaced with the output of that function call. Therefore, we can use ${status()} anywhere when variables are expanded to gain access to the status command. For example:

<action application="set" data="my_status=${status}"/>

The value placed in the my_status variable will be the output from the status command.

The drawback to all the versatility provided by a single module interface is that in order to achieve all of this, we have to ''loosely type'' the functionality. This means that there are several cases where a single FSAPI command could easily be accessed, using all of the ways we have discussed. In addition, there are also some other specific functions that are specifically designed for a particular access method. For instance, if we made an FSAPI command that produced HTML intended to be accessed with a web browser, we would not want to access it from the CLI or by referencing it as a variable. Similarly, if we made an FSAPI function that computed some kind of value based on call details, which was designed to be used from the Dialplan, it would not be very useful at the CLI or from the Web. So, with great power comes great responsibility, and this is one case where we need to use common sense to decide when and where to use the proper FSAPI functions to get the most out of them.

The XML registry

We have now discussed many of the fundamental components of the FreeSWITCH core and how they interact with each other. We have seen how the event system can carry information across the core, and how the XML Dialplan can query the XML registry for data. This would be a good time to explain the XML registry a bit more. The XML registry is a centrally managed XML document that holds all of the critical data, which FreeSWITCH needs to operate properly. The initial document is loaded from your hard drive and passed into a special pre-processor. This pre-processor can include other XML documents and other special operations, such as setting global variables, which can be resolved by the pre-processor further down in the document.

Once the entire document and all of the included files are parsed, replaced, and generated into a static XML document, this document is loaded into memory. The XML registry is divided into several sections—configuration, dialplan, directory, and phrases. The core and the modules draw their configuration from the configuration section. The XML Dialplan module draws its Dialplan data from the dialplan section. The SIP authentication, user lookup, and the voicemail module read their account information from the directory section. The Phrase Macros pull their configuration from the phrases section. If we make a change to any of the documents on the disk, we can reload the changes into memory by issuing the reloadxml command from the CLI. (This is an example of using the FSAPI interface to communicate with the FreeSWITCH core.)

Language modules

One distinct type of module that does not have a direct interface to FreeSWITCH-like files and Endpoints, but still offers an immensely powerful connection to existing technology, is the Language