7. Outside Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131The Basics of Trunkin
done with the following command, but before doing that look at the current menuse-lect.makeopts (after disabling all the modules) and locate a
The basic steps are:$ cd ~/src/asterisk-complete/asterisk/1.8.<your version number>/$ ./configure$ make$ make installYou don’t need to run sudo
$ cd ~/src/asterisk-complete/$ mkdir thirdparty/$ mkdir thirdparty/1.8/Downloading third-party modules into this directory allows you to easily reinst
make: gcc: command not foundThis means that the Asterisk configure script is unable to find your C compiler, whichtypically means you have not yet ins
You do not appear to have the sources for the 2.6.18-164.6.1.el5 kernelinstalled.You will get this error when attempting to build DAHDI without having
Another thing to consider when performing an upgrade is whether you really need toperform the upgrade in the first place. If you’re using a long-term
how to connect devices to our Asterisk system in order to start placing calls internallyand how to connect Asterisk to outside services in order to pl
CHAPTER 4Initial Configuration TasksCareful. We don’t want to learn from this.—Calvin & HobbesIn the last chapter, we covered how to install Aster
The default directory locations and the options you can use to modify them are listedin Table 4-1. For additional information about the usage of these
Option Value/Example Notesquiet yes Quiet mode reduces the amount of output seen at the console when Asterisk isrun in the foreground. This option is
Conclusion—Easy Reference Cheat Sheet 19410. Deeper into the Dialplan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Option Value/Example Notesminmemfree 1 Sets the minimum number of megabytes of free memory required for Asteriskto continue accepting calls. If Asteri
The [files] SectionThis section of asterisk.conf includes options related to the Asterisk control socket. Itis primarily used by remote consoles (aste
Although most modules do not use much in the way of resources, and they all loadvery quickly, it just seems cleaner to our minds to load only those mo
Table 4-5. modules.conf [modules] sectionOption Value/Example Notesautoload yes Instead of explicitly listing which modules to load, you can use this
Hacking indications.conf for Fun and ProfitIf you have too much time on your hands, you can do all sorts of pointless but enter-taining things with yo
For more information about using Asterisk in different countries, see Chapter 9.musiconhold.confIf you plan on selling Asterisk-based telephone system
CentOS PrerequisiteSince CentOS does not have MP3 capability installed with sox, you will have to installmpg123 before you can convert MP3 files for u
In newer versions of sox (e.g., version 14.3.0, which shipped withUbuntu 10.10), the -w option has changed to -2.Completing file conversionT
CHAPTER 5User Device ConfigurationI don’t always know what I’m talking about,but I know I’m right.—Muhammad AliIn this chapter we’ll delve into the us
Conclusion 23612. Internet Call Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237DNS a
While most devices will have a web-based interface for defining parameters, if you’reputting more than one or two phones into production we recommend
on any number of variables that are programmed into the system. This is especiallyrelevant in the context of features such as hot-desking.Hot-desking
Hardphones, Softphones, and ATAsThere are three types of endpoints you would typically provide your users with thatcould serve as a telephone set. The
a webcam for video calling, or perhaps an ability to load files from your desktop forfaxing.Some of the disadvantages of softphones are the not-always
Asterisk allows devices using many different protocols to speak to it(and therefore to each other). However, the SIP and IAX2 protocols arethe most po
the relevant channel configuration file and the extensions.conf file play a role in mostcalls routed through the system. Figure 5-1 provides a graphic
has taken over the VoIP/telecom industry and been implemented in thousands of de-vices and PBXs. If you look through the sip.conf.sample file in the .
wanted, and also that there needs to be an identically named context in exten-sions.conf to define the call flow for unauthenticated call
IPv6 in sip.confAs of version 1.8, Asterisk supports IPv6 for both SIP and RTP traffic. All of the con-figuration options in /etc/asterisk/sip.conf re
In the [office-phone] template we’ve defined several options required for authentica-tion and control of calls to and from devices that use that templ
Using Local Channels 293Queue Statistics: The queue_log File 296Conclusion 29914. Device States . . . . . . . . . . . . . . . . . . . . . . . . . . .
Name Purpose Popularity/Statusfunc_sprintf Performs string format functions similar to C function of same name Usefulfunc_srv Perform SRV lookups in t
Hardphones, Softphones, and ATAsThere are three types of endpoints you would typically provide your users with thatcould serve as a telephone set. The
Running make samples on a system that already has configuration fileswill overwrite the existing files.Using make samples to Create SampleConfiguratio
This icon indicates a warning or caution.Using Code ExamplesThis book is here to help you get your job done. In general, you may use the code inthis b
Asterisk™: The Definitive Guide
The Asterisk CLIThe best way to see what is happening with your Asterisk system is through the AsteriskCLI. This interface provides various levels of
Typing the following command returns a listing of all the peers that Asterisk knowsabout (regardless of their state):*CLI> sip show peersName/usern
The init script uses the /etc/dahdi/modules file to determine which modules should beloaded to support the hardware in the system. The installation of
modules/. If it is there, edit /etc/asterisk/modules.conf to load chan_dahdi.so. If the mod-ule is not present on disk, DAHDI was not installed before
You can verify that Asterisk has loaded your configuration by running the dahdi showchannels CLI command:*CLI> dahdi show channels Chan Extension
16. Relational Database Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341Installing and Configuring Po
or from the Asterisk CLI:*CLI> dialplan reloadYou should now be able to dial between your two new extensions. Open up the CLIin order to see the ca
Figure 5-2. SIP dialogsConclusionIn this chapter we learned best practices for device naming by abstracting the conceptsof users, extension numbers, a
CHAPTER 6Dialplan BasicsEverything should be made as simple as possible,but not simpler.—Albert EinsteinThe dialplan is the heart of your Asterisk sys
Sample Configuration FilesIf you installed the sample configuration files when you installed Asterisk, you will mostlikely have an existing extensions
Context names have a maximum length of 79 characters (80 characters– 1 terminating null).All of the instructions placed after a context definition are
The Asterisk wiki at https://wiki.asterisk.org/wiki/display/AST/Important+Security+Considerations outlines several steps you should take tokeep yo
Each step in an extension is composed of three components:• The name (or number) of the extension• The priority (each extension can include multiple s
changes to your dialplan, as you don’t have to keep renumbering all your steps. Forexample, your dialplan might look something like this:exten => 1
A very common mistake when writing labels is to insert a comma be-tween the n and the (, like this:exten => 123,n,(label),application() ;<-- THI
A Prompt-Recording Application 394Speech Recognition and Text-to-Speech 395Text-to-Speech 395Speech Recognition 396Conclusion 39618. External Services
The Playback() application is used for playing a previously recorded sound file over achannel. Input from the user is ignored, which means that you wo
As we work through the book, we will be introducing you to many more Asteriskapplications.A Simple DialplanOK, enough theory. Open up the file /etc/
or from the shell with:$ sudo /usr/sbin/asterisk -rx "dialplan reload"Calling extension 200 from either of your configured phones should rew
We used the extension start in this example, but we could have usedanything we wanted as an extension name, either numeric or alpha. Weprefer to use a
Both Background() and WaitExten() allow the caller to enter DTMF digits. Asterisk thenattempts to find an extension in the current context that matche
Handling Invalid Entries and TimeoutsNow that our first voice menu is starting to come together, let’s add some additionalspecial extensions. First, w
Argument 1: DestinationThe first argument is the destination you’re attempting to call, which (in its simplestform) is made up of a technology (or tra
Argument 2: TimeoutThe second argument to the Dial() application is a timeout, specified in seconds. If atimeout is given, Dial() will attempt to call
Updating the dialplanLet’s modify extensions 1 and 2 in our menu to use the Dial() application:[TestMenu]exten => start,1,Answer() same => n,B
of the variable, and a closing curly brace (in the case of LEIF, we would reference thevalue of the variable with ${LEIF}). Here’s how we might use a
Disabling Digium FFA (Should You Want to Test spandsp) 446Incoming Fax Handling 447Fax to TIFF 447Fax to Email 447Fax Detection 448Outgoing Fax Handli
There are many predefined channel variables available for use within the dialplan,which are explained in the Asterisk wiki at https://wiki.aster
exten => i,1,Playback(pbx-invalid) same => n,Goto(incoming,123,1)exten => t,1,Playback(vm-goodbye) same => n,Hangup()You’ll notice we’
NMatches any single digit from 2 to 9.[15-7]Matches a single character from the range of digits specified. In this case, the pat-tern matches a single
Pattern-matching examplesThis pattern matches any seven-digit number, as long as the first digit is 2 or higher:_NXXXXXXThe preceding pattern would be
And finally this one:_011.Note the period on the end. This pattern matches any number that starts with 011 andhas at least one more digit. In the NANP
More Advanced Digit ManipulationThe ${EXTEN} variable properly has the syntax ${EXTEN:x:y}, where x is the starting po-sition and y is the number of d
ConclusionAnd there you have it—a basic but functional dialplan. There is still much we have notcovered, but you’ve got all of the fundamentals. In th
CHAPTER 7Outside ConnectivityYou cannot always control what goes on outside. Butyou can always control what goes on inside.—Wayne DyerIn the previous
perspective, the definition of a trunk is not as clear as it used to be (PBX trunks usedtotally different technology from station circuits), but as a
The [globals] section contains two variables, named LOCAL and TOLL.‡ The purpose ofthese variables is to simplify management of your dialplan should y
22. Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489Traditional
Traditional PSTN TrunksThere are two types of fundamental technology that phone carriers use to deliver tel-ephone circuits: analog and digital.Analog
The station is responsible for:• Providing a ringer (or at least being able to handle ringing voltage in some manner)• Providing a dialpad (or some wa
• Richer signaling information (especially if using ISDN)• Lower cost for carriers• Lower cost for customers (at higher densities)In an Asterisk syste
As of DAHDI 2.3.0, the requirement to load dahdi_dummy for a timinginterface no longer exists. The same functionality has now been in-tegrated into th
You can then restart your DAHDI process to unload any existing drivers that wereloaded, and load just the dahdi_dummy module with the init script:$ su
When installing telephony hardware, be sure you update the /etc/dahdi/modules file to enable the appropriate modules for your hardware andthen reload
signalling = pri_cpechannel => 1-23Some carriers will use Nortel’s DMS switch, which commonly uses the DMS100 pro-tocol instead of National ISDN 2.
America (we don’t recommend using it for any reason), but in some countries in Europeit is widely used and has almost completely replaced analog.BRI s
Additionally, OpenR2 contains some sample configuration files for connecting Asteriskto networks in various countries. To read information about some
When installing telephony hardware, be sure you update the /etc/dahdi/modules file to enable the appropriate modules for your hardware andthen reload
Backends 540Example Channel Events 546SNMP 551Installing the SNMP Module for Asterisk 551Configuring SNMP for Asterisk Using OpenNMS 552Monitoring Ast
[incoming], because we have decided that all incoming calls should start in thiscontext§:[incoming]exten => s,1,Answer() same => n
Calls from the VoIP network will arrive in the dialplan in whatever context you assignedto the incoming SIP channels, and the dialplan will relay the
such as a PRI circuit, you will normally be able to order DID numbers to be deliveredwith that circuit.In order to accept a call from a circuit you ar
VoIP to VoIPEventually, the need for the PSTN will likely vanish, and most voice communicationswill take place over network connections.The original t
over SIP. In our example, we will creatively refer to the two servers as serverA andserverB.The first file that must be modified is /etc/asterisk/sip.
Now put the following entry in /etc/asterisk/sip.conf on serverB. It is nearly identical tothe contents of the entry we put on serverA, but the name o
Next, you will need to create a peer entry in sip.conf for your service provider. Here isa sample peer entry:[myprovider]type = peerhost = your.provid
certificates. The first invocation of ast_tls_cert will generate the CA cert and the servercert for serverA. The second invocation of ast_tls_cert wil
to modify that configuration so that Asterisk knows that the calls between the twoservers should be encrypted. The only change required is to add the
-- Executing [1234@incoming:1] Answer("SIP/serverA-00000000", "") in new stack -- Executing [1234@incoming:2] GotoIf("
Passionate Community 582Some Things That Are Now Possible 582The Future of Asterisk 586Speech Processing 587High-Fidelity Voice 588Video 588Wireless 5
One of the more unique features of the IAX protocol is IAX trunking.Trunking an IAX connection could be useful on any network link that wi
place for playing around. The [emergency-services] section of your dialplan might looksomething like this:[emergency-services]exten => 911,Goto(dia
ConclusionEventually, we believe that the PSTN will disappear entirely. Before that happens,however, a distributed mechanism that is widely use
CHAPTER 8VoicemailJust leave a message, maybe I’ll call.—Joe WalshBefore email and instant messaging became ubiquitous, voicemail was a popu
And that’s just the tip of the iceberg!The default version of the /etc/asterisk/voicemail.conf file requires a few tweaks in orderto provide a configu
Option Value/Example Noteswon’t appreciate it if you cut her off after three minutes. A settingsomewhere between 600 seconds (10 minutes) and 3600 sec
Option Value/Example Notesuserscontext default If you use the users.conf file (we don’t), you can define here thecontext where entries are registered.
Option Value/Example Notesemailsubject [PBX]: Newmessage ${VM_MSGNUM} inmailbox ${VM_MAILBOX}When Asterisk sends an email, you can use this setting to
Option Value/Example Notesthe mailboxes for changes, which will trigger proper message wait-ing indication (MWI) updates.pollfreq 30 Used in concert w
Asterisk comes with a simple script that will greatly improve the security of your voi-cemail system. It is located in the source code under the folde
Option Value/Example Notesa second level of password in the dialplan where another password isspecified. Even so, this is not a safe practice.sendvoic
Option Value/Example Notesforcegreetings yes, no As above, but for greetings.hidefromdir no, yes If you wish, you can hide specific mailboxes from the
Option Value/Example Noteslisten-control-stop-key13456789 You can use this setting to customize the interrupt playback key.backupdeleted 0 This settin
The Contexts SectionAll the remaining sections in the voicemail.conf file will be the voicemail contexts, whichallow you to segregate groups of mailbo
serveremail, tz, saycid, review, operator, callback, dialout, and exitcontext.These options should be in option = value pairs, separated by th
[zonemessages]eastern=America/New_York|'vm-received' Q 'digits/at' IMpcentral=America/Chicago|'vm-received' Q 'digi
Table 8-4. VoiceMail() optional argumentsArgument Purposeb Instructs Asterisk to play the busy greeting for the mailbox (if no busy greeting is found,
The VoiceMailMain() Dialplan ApplicationUsers can retrieve their voicemail messages, change their voicemail options, and recordtheir voicemail greetin
If callers press 8, they’ll get a directory by first name. If they dial 9, they’ll get thedirectory by last name.Using a JitterbufferWhen using Asteri
as WAV and GSM), depending on what you specified as the format in the [general]section of your voicemail.conf file. Your greetings will also be stored
Foreword“There’s more than one way to do it.” I’ve been working with Asterisk for nine years,and this motto becomes more true with each release, each
Using Asterisk As a Standalone Voicemail ServerIn a traditional telecom environment, the voicemail server was typically a standaloneunit (provided eit
Figure 8-1. Simplified SIP enterprise environmentInstead you can statically define an entry for each mailbox in the voicemail server’ssip.conf file, i
Note that Asterisk’s dynamic realtime will not work with this configu-ration, as a peer’s information is only loaded into memory when thereis an actua
The voicemail server will need an extensions.conf file containing the following:[voicemailbox]; direct incoming calls to a mailboxexten => Deliver
The following is not a detailed explanation of how to configure SMDI for Asterisk, butrather an introduction to the concepts, with some basic examples
ConclusionWhile the Asterisk voicemail system is quite old in terms of Asterisk code, it is never-theless a powerful application that can (and does) c
CHAPTER 9InternationalizationDavid DuffettI traveled a good deal all over the world, and I got alongpretty good in all these foreign countries, for I
Quite a few of the chapters in this book contain information that will help you inter-nationalize* or (perhaps more properly) localize your Asterisk i
really fundamental differences in order to throw light on the next explanation, whichcovers the settings we might need to change on devices external t
to install the package, open up some of the configuration files, and start looking atexamples.From the basic beginnings of a PBX that Mark Spencer cod
usually dial the IP address of the other phone just by using the * key for the dots inthe address.Figure 9-2 points to the fact that on an IP phone, w
The prior discussion of IP phone configuration also applies to any analog telephoneadaptors (ATAs) you plan to use—specifically, to those supporting a
Figure 9-3. A balunAnalog connections vary massively from place to place—you will know what kind ofconnector is used in your locality. The important t
a primary rate interface (PRI), this will be a T1 in North America, a J1 in Japan, or anE1 in pretty much the rest of the world.Once you have establis
The /etc/dahdi/system.conf file uses the hash symbol (#) to indicate acomment instead of a semicolon (;) like the files in /etc/asterisk/.Although it
The relationship between Linux, DAHDI, and Asterisk (and therefore /etc/dahdi/sys-tem.conf and /etc/asterisk/chan_dahdi.conf) is shown in Figure 9-5.F
Again, Asterisk defaults to the North American caller ID format (no entries in /etc/asterisk/chan_dahdi.conf describe this, it’s just the default), an
The default directory used is /var/lib/asterisk/sounds/en, so how do you change that?There are two ways. One is to set the language in the channel con
ordered month, day, year and times are specified in 12-hour clock format (e.g.,2:54 P.M.).In contrast, in the UK, dates are ordered day, m
UK24=Europe/London|'vm-received' q 'digits/at' H N 'hours'UK12=Europe/London|'vm-received' Q 'digits/at&a
If you’re an experienced Asterisk developer or integrator, I’m sure this book will havea few “Hey, that’s a neat way to do it!” moments for you, which
Conclusion—Easy Reference Cheat SheetAs you can now see, there are quite a few things to change in order to fully localize yourAsterisk-based telepho
CHAPTER 10Deeper into the DialplanFor a list of all the ways technology has failed to improvethe quality of life, please press three.—Alice KahnAlrigh
When Asterisk encounters an expression in a dialplan, it replaces the entire expressionwith the resulting value. It is important to note that this tak
expr1 & expr2This operator (called “and”) returns the evaluation of expr1 if both expressionsare true (i.e., neither expression evaluates to an em
This would have assigned the variable TEST to the string “2+1”, instead of the value 3.In order to remedy that, we would put spaces around the operato
exten => 123,1,Set(TEST=example) same => n,SayNumber(${LEN(${TEST})})This example will first evaluate $TEST as example. The string “example”
Either of the destinations may be omitted, but not both. If the omitted destination isto be followed, Asterisk simply goes on to the next priority in
exten => iguanas,1,Playback(office-iguanas) same => n,Hangup()By changing the value assigned to TEST in the first line, you should be able to
Time-Based Conditional Branching with GotoIfTime()Another way to use conditional branching in your dialplan is with the GotoIfTime()application. Where
monthsThis is a list of one or more months of the year. The months should be written asjan-apr for a range, and separated with ampersands when wanting
MacrosMacros§ are a very useful construct designed to avoid repetition in the dialplan. Theyalso help in making changes to the dialplan. To illustrate
Macro definitions look a lot like contexts. (In fact, you could argue that they really aresmall, limited contexts.) You define a macro by placing macr
[macro-voicemail]exten => s,1,Dial(${JOHN},10) same => n,GotoIf($["${DIALSTATUS}" = "BUSY"]?busy:unavail) same => n(u
Since we know how to use dialplan functions now as well, here is an-other way of controlling which voicemail prompt (unavailable vs. busy)is played
same => n(busy),VoiceMail(101@default,b) same => n,Hangup()If we were going to convert this to be used for a subroutine, it might look like
Using Arguments in SubroutinesThe ability to use arguments is one of the major features of using Macro() or GoSub(),because it allows you to abstract
Returning from a SubroutineUnlike Macro(), the GoSub() dialplan application does not return automatically once itis done executing. In order to
exten => start,1,VoiceMail(${ARG1}@${ARG2},${ARG3}) same => n,Hangup()In this version we’ve made just the one change: Return() to Return(${DIA
box, like we’ve done for other portions of the dialplan. We’ll be building the dialplanto match the time starts and stops described in Figure 10-1.Fig
Time period(in seconds)channel_1 channel_2 channel_325 30 Hangup()35 40 In this table, we can see that channel_1 started dialing lo
PrefaceThis is a book for anyone who uses Asterisk.Asterisk is an open source, converged telephony platform, which is designed primarilyto run on Linu
Additional scenarios and information about Local channels and the modifier flags(/n, /j, /m, /b) are available at https://wiki.asterisk.org/
exten => 456,1,Set(DB(test/count)=1) same => n,Set(COUNT=${DB(test/count)}) same => n,SayNumber(${COUNT})You may also check the value of
same => n(continue),NoOp() same => n,SayNumber(${COUNT}) same => n,Set(COUNT=$[${COUNT} + 1])Now that we’ve incremented COUNT, let’s p
Handy Asterisk FeaturesNow that we’ve gone over some more of the basics, let’s look at a few popular functionsthat have been incorporated into Asteris
Also note that because the user needs to be able to transfer the calls to the parking lotextension, you should make sure you’re using the t and/or T o
the conference room (as defined in meetme.conf), a set of options, and the passwordthe user must enter to join this conference. Let’s set up a simple
CHAPTER 11Parking and PagingI don’t believe in angels, no. But I do have a wee parkingangel. It’s on my dashboard and you wind it up. Thewings flap an
signals in the audio channel triggered by the users dialing the required digits on theirdialpads).*Transfers on SIP channels (for example from a SIP t
Option Value/Example Notesparkedcallhangup caller Controls which side of a call has the ability to execute a DTMF-basedhangup in the call that results
OrganizationThe book is organized into these chapters:Chapter 1, A Telephony RevolutionThis is where we chop up the kindling and light the fire. Welco
Handling Timed-Out Parked Calls with the comebacktoorigin OptionThis option configures the behavior of call parking when the parked call times out (se
The [featuremap] SectionThis section allows you to define specific DTMF sequences, which will trigger variousfeatures on channels that have been bridg
3. Defining which channel the feature will be activated on, and (optionally) whichparticipant is allowed to activate the feature (the default is to al
Inheriting Channel VariablesChannel variables are always associated with the original channel that set them, andare no longer available once the chann
If you want to specify a custom key mapping to a feature in an applica-tion map grouping, simply follow the => with the key mapping you want.If you
better for each successive page to assign the next slot, since you will often have morethan one call parked at a time. Your users will get used to lis
Table 11-3. Page() optionsOption Description Discussiond Enables full-duplex audio Sometimes referred to as “talkback paging,” the use of this option
is connected to a paging interface such as a Bogen UTI1,§ which then connects to thepaging amplifier.‖In your dialplan, paging to an external amplifie
Beyond a certain size, your Asterisk system will be unable to page mul-tiple sets. For example, in an office with 200 telephones, using SIP topage eve
Fortunately, many of these sets support IP multicast, which is a far better way to senda page to multiple sets (read on for details). Still, if you on
Chapter 14, Device StatesIntroduces the concept of device states and how they can be used as presenceindicators.Chapter 15, The Automated Atte
Multicast Paging on Cisco SPA TelephonesThe multicast paging feature on Cisco SPA phones is a bit strange, but once configuredit works fine. The trick
this is fairly simple to accomplish. When you call the Page() application, you simplyspecify the various resources you want to page, separated by the
zone controller answers, and then an additional digit is sent to select which zone thepage is to be sent to. Most zone controllers will allow for a pa
CHAPTER 12Internet Call RoutingThere ain’t no such thing as a free lunch (TANSTAAFL).—Robert HeinleinOne of the attractions of VoIP is the concept of
handled through numerical IP addresses, it can be very helpful to associate a name(such as www.google.com) with what may in fact be multiple IP addres
(SIP being one of them). If you want to support SIP lookups on your domain, you willrequire a relevant SRV record in order to properly respond.When a
Any SIP requests to your domain will be referred to your Asterisk server, which will beresponsible for handling incoming SIP connections.‖If your dial
A dialplan entry on the pbx.shifteight.org system might look like this:[unauthenticated]exten => leif,1,Goto(PublicExtensions,100,1)exten => jim
If the call does not explicitly match our named extensions, the pattern match will beutilized. Our pattern match of _[A-Za-z0-9]. matches any string s
We’ve written this as a subroutine, which is invoked something like this:; where 'name' is the username as found in the email addressGoSub(s
we felt that it might still be useful to some readers, so we’ve left it in the book asan appendix.Appendix B, Protocols for VoIPDelves into all the pa
If ${Result} is not null, the next steps will clean up ${Result} in order to extract theextension number* of the user with the name passed in ${ARG1}:
Table 12-2. NameMapping tableName Extension Contextleif 100 publicExtensionsleif.madsen 100 publicExtensionslmadsen 100 publicExtensionsjim 101 public
Details on how to handle all of this in your dialplan are beyond the scope of this book.Suffice it to say that in your dialplan you will still need to
ENUM and E.164Although the SIP protocol really doesn’t think in terms of phone numbers, the realityis that phone numbers are not going away any time s
In the UK, you might need something more like this:_0[123789]XXXXXXXXX_0[123789]XXXXXXXXAnd in Australia, your dialplan might have these pattern match
ENUM has not taken off. The reasons appear to be mostly political in nature. Theproblem stems from the fact that there is no one organization that con
An ENUM lookup in the dialplan might look like this:exten => _X.,1,Set(CurrentExten=${FILTER(0-9,${EXTEN})}) same => n,Set(LookupResult=${ENUM
Got ISN?The heart of the freenum.org concept is the ITAD Subscriber Number (ISN). The ISNis a numeric string that is composed of an extension number o
There are many other numbering schemes that have been created as a result of an RFC.Other IANA-managed numbers include MAC addresses—specifically, the
Your application will be reviewed by a Real Human Being™, and within a few days youshould be assigned an ITAD by IANA. A few days later, you will also
This icon indicates a warning or caution.Using Code ExamplesThis book is here to help you get your job done. In general, you may use the code inthis b
John Todd notes: “For those sites which have extremely complex configurations or geo-graphically diverse offices with different SIP servers handling d
[subFreenum]exten => start,1,Verbose(2,Performing ISN lookup) same => n,Set(ISN=${FILTER(0-9*,${ARG1})}) same => n,Set(Result=${ENUMLOOKU
Our code for performing the lookup then looks like this:exten => start,n,Set(Result=${ENUMLOOKUP(${ISN},sip,s,,freenum.org)})Following the lookup
Toll FraudToll fraud is by far the biggest risk to your phone system in terms of the potential forruinous cost. It is not unheard of for fraudsters to
Spam over Internet Telephony (SPIT)VoIP spam has not yet taken off, but rest assured, it will. Spammers all over the worldare drooling at the prospect
Security Is an Ongoing ProcessIn contrast to previous editions, throughout this book we have tried to provide exam-ples and best practices that take s
Downloa d f r o m W o w ! e B o o k < w w w.woweb o o k . c o m >
CHAPTER 13Automatic Call Distribution (ACD)QueuesAn Englishman, even if he is alone, forms an orderlyqueue of one.—George MikesAutomatic Call Distribu
We’ve all been frustrated by poorly designed and managed queues: enduring hold mu-sic from a radio that isn’t in tune, mind-numbing wait times, and po
look into how to create a dialplan that allows us to dynamically add and remove queuemembers (as well as pause and unpause them).The first step is to
Asterisk™: The Definitive GuideDownloa d f r o m W o w ! e B o o k < w w w.woweb o o k . c o m >
We have a web page for this book, where we list errata, examples, and any additionalinformation. You can access this page at:http://oreilly.com/catalo
was wrapping up a call from the support queue might still get a call from the salesqueue. This option should also always be set to yes (the default).T
Once you’ve finished configuring your queues.conf file, you can save it and reload theapp_queue.so module from your Asterisk CLI:$ asterisk -r*CLI>
You don’t join the queue at this point, as there are no agents in the queue to answercalls. Because we have joinempty=no and leavewhenempty=yes
Adding a queue member to the support queue can be done with the queue add mem-ber command:*CLI> queue add member SIP/0000FFFF0001 to supportAdded i
Controlling Queue Members with Dialplan LogicIn a call center staffed by live agents, it is most common to have the agents themselveslog in and log ou
In short, agents who are not sitting at their desks and planning to be available to takecalls in the next few minutes should log out. Pause/unpause sh
; ${UPQMSTATUS}:; UNPAUSED; NOTFOUNDAutomatically Logging Into and Out of Multiple QueuesIt is quite common for an agent to be a member of mor
; if there are no queues assigned to this agent we'll handle it in the ; no_queues_available extension same => n,GotoIf($[${ISNULL(${Availab
same => n,Playback(silence/1&channel¬-yet-assigned) same => n,Hangup(); -------------------------; Used for logging agents out o
You could further refine these login and logout routines to take into account that theAQMSTATUS and RQMSTATUS channel variables are set each time
on Asterisk, OpenSER, and OpenSIPS; J. Oquendo, Security Guru; Tzafrir Cohen, fontof knowledge about security and lots of other stuff; Jeff Gehlbach,
*CLI> queue show supportsupport has 0 calls (max unlimited) in 'rrmemory' strategy (0s holdtime, 0s talktime), W:0, C:0, A:0, SL:0.0
The queues.conf FileWe’ve mentioned the queues.conf file already, but there are many options in this file,and we figured it would be right and proper
Options Available values Description• random: rings a random interface• rrmemory: rings members in a round-robin fashion,remembering where we left off
Options Available values Descriptionsetinterfacevar yes, no If set to yes, the following channel variables will be set justprior to connecting the cal
Options Available values Descriptionmembermacro Name of a macro de-fined in thedialplanDefines a macro to be executed just prior to bridging thecaller
Options Available values Descriptionqueue-callswaiting Filename of promptto playIf not defined, will play the default value (“calls waiting”).If set t
Options Available values Description• wrapup: members are considered unavailable ifthey are currently in the wrapup time after the com-pletion of a ca
The agents.conf FileIf you’ve browsed through the samples in the ~/src/asterisk-complete/1.8/configs/ di-rectory, you may have noticed the agents.conf
Options Available values Descriptionenddtmf Single DTMFcharacterUsed in conjunction with endcall, this option defines the DTMF char-acter to be used t
Advanced QueuesIn this section we’ll take a look at some of the finer-grained queue controls, such asoptions for controlling announcements and when ca
Finally, and most importantly, thanks go to Mark Spencer, the original author ofAsterisk and founder of Digium, for Asterisk, for Pidgin (
callers to. This can be done wherever you would normally place your dialplan logic toperform transfers. We’re going to use the LocalSets context, whic
Shaw and Danielle Roberts in the sales queue so Kay Madsen is preferred, and penalizeJames Shaw and Kay Madsen in the billing queue so Danielle Robert
are to be used for servicing callers. Let’s say we have a queue called support, and wehave five queue members with various penalties ranging from 1 th
With our rule now loaded into memory, we can modify our dialplan to make use of it.Just modify the Queue() line to include the new rule, like so:[Queu
Table 13-5. Options related to prompt control timing within a queueOptions AvailablevaluesDescriptionannounce-frequency Value insecondsDefines how oft
Options Available values Descriptionqueue-youarenext Filename of prompt toplayIf not defined, will play the default value (“You are now first in line”
We’ll now modify the StardardQueue template to control our announcements:[StandardQueue](!) ; template to provide common featuresmusicclass=defa
(lets say 30 seconds), it will appear as if it is being played every 15 seconds, rather thanevery 45 seconds as may be intended.How many times we anno
Of course, we could define a different destination, but the VoiceMail() application isas good as any. Just make sure that if you’re going to send call
For joinempty, prior to placing a caller into the queue, all the members are checked foravailability using the factors you list as criteria. If all me
Project (http://www.asteriskdocs.org), with the goal of writing an Asterisk book for thecommunity. That project became the basis of the first edition
; queues.conf[support](StandardQueue)member => Local/SIP-0000FFFF0001@MemberConnector ; pass the technology to dial over
; queues.conf[support](StandardQueue)member => Local/SIP-0000FFFF0001@MemberConnector,,,SIP/0000FFFF0001Only SIP channels are capable of sending ba
; assign the first field of QueueMember to Technology using the hyphen separator same => n,Set(Technology=${CUT(QueueMember,-,1)}) ; assign
queue_log_to_fileControls whether the queue log should be written to a file even when a real timebackend is present. Valid values are yes or no (defau
Table 13-9. Events in the Asterisk queue logEvent Information providedABANDON Written when a caller in a queue hangs up before his call is answered by
Event Information providedPENALTY Written when a member’s penalty is modified. The penalty can be changed through several means,such as the QUEUE_MEMB
CHAPTER 14Device StatesOut of clutter, find simplicity.—Albert EinsteinIt is often useful to be able to determine the state of the devices that are at
Virtual device DescriptionPark:<exten@context> The state of a spot in a call parking lot. The state information will reflect whether or not acal
Chapter 20 discusses the Asterisk Manager Interface (AMI). The GetVar manager action can be used to retrieve device state values in anexternal program
Asterisk has proven that open source telecom is a lasting idea, and the open sourcetelecom landscape is nowadays complemented by more than just Asteri
Typically, hints are simply defined along with the rest of the extension. This next ex-ample adds simple extension entries for what would happen if ea
[phones]exten => 7001,hint,SIP/0004F2060EB4When core show hints is executed at the Asterisk CLI, the following output is presentedwhen the device i
SIP PresenceAsterisk provides the ability for devices to subscribe to extension state using the SIPprotocol. This functionality is often referred to a
subscribecontextAllows you to set a specific context for subscriptions. Without this set, the contextdefined by the context option will be used. This
Custom device states can be used as a way to directly control the state shown on adevice that has subscribed to the state of an extension. Just map an
Example 14-1 shows the full example as it would appear in /etc/asterisk/extensions.conf.Example 14-1. Custom “do not disturb” functionality using cust
To accomplish distributed device state, some sort of messaging mechanism must beused for the servers to communicate with each other. Two such mechanis
After running the configure script, run the menuselect tool to ensure that Asterisk hasbeen told to build the res_ais module (this module can be found
To get started with testing out basic OpenAIS connectivity, try starting the aisexecapplication in the foreground and watching the output:$ sudo aisex
=== ---------------------------------------------------------================================================================Another useful Asterisk C
To my wife, Julie, I cannot thank you enough for all the love and support you havegiven me. Thank you for keeping my life balanced and happy. You are
If you would like to dive deeper into the processing of distributed device state changes,there are some useful debug messages that can be enabled. Fir
Asterisk has the ability to use XMPP PubSub to distribute device state information. Oneof the nice things about using XMPP to accomplish this is that
This is a pretty quick and crude set of instructions for compiling andinstalling Asterisk. For a much more complete set of instructions, pleasesee Cha
serverhost = jabber.shifteight.orgpubsub_node = pubsub.jabber.shifteight.orgusername = [email protected]/astvoip2secret = mypassworddistri
Next, start Asterisk on the second server and run jabber show buddies on that server.The output will contain more information, since the second server
these applications is the MeetMe() application. The SLA applications come with thesame module as the MeetMe() application, so you must install the app
phones that all have line keys directly associated with the analog lines. For the purposesof this example, we will say we have two analog lines and fo
[station3]type = stationdevice = SIP/station3trunk = line1trunk = line2[station4]type = stationdevice = SIP/station4trunk = line1trunk = line2The stat
extension (or station2, station3, etc., as appropriate). If the line1 key on the phone ispressed, a call should be sent to the station1_line1 extensio
• Ensure that if the Line 1 key on station1 is pressed a call is sent to the station1_line1 extension, and so on.Key System Example w
extensions.confAs in the last example, you will need line1 and line2 contexts to process incoming callson these trunks:[line1]exten => s,1,SLATrunk
complete the call. In this example, we use the DISA() application locally to provide adialtone and collect digits. Once a complete number has been dia
device = SIP/5001_phone2trunk = 5001extensions.confThe first part of the dialplan that is required is what will be executed when extension5001 is di
Additional ConfigurationThe /etc/asterisk/sla.conf file has some optional configuration parameters that were notused in any of the examples in this ch
ringtimeout = 20A timeout may be specified in seconds for how long this station will ring beforethe call is considered unanswered. There is no timeout
ConclusionThis chapter discussed many aspects of device state handling in Asterisk. We startedby discussing the core concepts of device states and ext
CHAPTER 15The Automated AttendantI don’t answer the phone. I get the feeling whenever I dothat there will be someone on the other end.—Fred CouplesIn
In this chapter we talk about building an automated attendant. In Chapter 17 we willdiscuss IVR.*Designing Your Auto AttendantThe most common mistake
Step or choice Sample prompt Notes Filenameaddress and fax in-formation, pleasepress 3. To repeatthese choices press9, or you can remainon the line or
CHAPTER 1A Telephony RevolutionFirst they ignore you, then they laugh at you,then they fight you, then you win.—Mahatma GandhiWhen we first set out—ne
a whole new menu. For example, for a few weeks each year you might want yourgreeting to say “Season’s greetings” or whatever, but your menu will not n
Selection #It’s good to have the option for the directory as close to the beginning of the recordingas possible. Many people will use a directory if t
Dial by ExtensionIf somebody calls your system and knows the extension she wants to reach, your au-tomated attendant should have code in place to hand
bit 8-kHz WAV files to be the easiest to work with and, most of the time, the best-possible quality.There are essentially two ways to get prompts into
have a maingreeting.wav and a maingreeting.gsm file in your sounds folder, Playback() will select the one that requires the least CPU to pl
exten => #,1,Verbose(1, same => n,Directory() ;exten => 0,1,Verbose(1, same => n,Dial(SIP/operator) ; Operator extension/queuee
IVRWe’ll cover Interactive Voice Response (IVR) in more depth in Chapter 17 but beforewe do that, we’re going to talk about something that is essentia
CHAPTER 16Relational Database IntegrationFew things are harder to put up with than the annoyanceof a good example.—Mark TwainIn this chapter we are go
Installing and Configuring PostgreSQL and MySQLIn the following sections we will show how to install and configure PostgreSQL andMySQL on both CentOS
Installing MySQL for CentOSTo install MySQL on CentOS, run the following command. You will be prompted toinstall several dependencies. Press Enter to
b) develop the required skills through instruction, practice, and a good book onthe subject.Asterisk and VoIP: Bridging the Gap Between Tr
Then run the following commands to create the asterisk user in the database and setup permissions:$ createuser -PEnter name of user to add: asteriskEn
Then restart the PostgreSQL server. On CentOS:$ sudo service postgresql restartYou need to restart the PostgreSQL service because you made changesto p
Then connect to the database console so you can create your asterisk user and set uppermissions:$ mysql -u root -pEnter password:After entering the pa
On CentOS:$ sudo yum install unixODBC unixODBC-devel libtool-ltdl libtool-ltdl-develIf you’re using a 64-bit installation, remember to add .x86_64 to
Driver = /usr/lib/libodbcpsql.soSetup = /usr/lib/libodbcpsqlS.soFileUsage = 1On Ubuntu, the /etc/odbcinst.ini file will be bl
Configuring ODBC for MySQLConfiguration for the MySQL ODBC driver is done in the /etc/odbcinst.ini file.On CentOS the default file already contains so
On Ubuntu 10.10, the socket location is /var/run/mysqld/mysqld.sock.Configuring ODBC for Microsoft SQLConnecting to Microsoft SQL (MS SQL) is similar
Once you’ve configured the drivers, you need to modify the /etc/odbc.ini file to controlhow to connect to the database:[asterisk-connector]Description
Almost everything in this chapter is turned on by default. You will wantto run make menuselect to verify that the ODBC-related modules areenabled. Th
Last connection attempt: 1969-12-31 19:00:00 Pooled: No Connected: YesManaging DatabasesWhile it isn’t within the scope of this book to teach yo
but it seemed unlikely that anyone was ever going to. At that point it was clear that ifhe wanted a revolution, he was going to have to start it himse
A Gentle Introduction to func_odbcThe very first use of func_odbc, which occurred while its author was still writing it, isalso a good introduction to
of ways in which this might be used, such as for managing users or allowing the sharingof dynamic information within a clustered set of Asterisk machi
Still, when they do get into the office, they’d like the system to know which desks theyare sitting at, so that their calls can be directed there. Als
pin int4, context text, status bool DEFAULT false, "location" text, CONSTRAINT ast_hotdesk_id_pk PRIMARY KEY (id))WITHOUT OIDS;For MyS
At the PostgreSQL console, run the following commands:asterisk=> INSERT INTO ast_hotdesk ('extension', 'first_name', 'last
We’re not done writing this extension yet, but let’s pause for a moment and see wherewe’re at so far.When a sales agent sits down at a desk, he logs i
This would return the value located in the database within the status column wherethe extension column equals 1101. The status and 1101 we p
A simple example follows. Suppose we have the following func_odbc.conf:[ALL_AVAIL_EXTENS]prefix=GETdsn=asterisk-connectormode=multirowreadsql=SELECT e
After the SQL statement is executed, the value returned (if any) is assigned to theRETURNED_VALUE channel variable.Using the ARRAY() FunctionIn o
Remember that in a traditional phone system all extensions must benumbers, but in Asterisk, extensions can have names as well. A possibleadvantage of
corporate risk-analysis process. While no one can seriously claim to have a completepicture of what this thing should look like, there is no shortage
; *** This line should have no line breaksreadsql=SELECT COUNT(status) FROM ast_hotdesk WHERE status = '1' AND location = '${ARG1}&apos
loop, but it’s a good example of how you might update or parse multiple rows in thedatabase.§The first part of our dialplan returns an ID num
variable, which is set by the HOTDESK_STATUS() function. This tells us how many rowswere affected in the SQL UPDATE, which we assume to be
[hotdesk_outbound]exten => _X.,1,NoOp() same => n,Set(LOCATION=${CUT(CHANNEL,/,2)}) same => n,Set(LOCATION=${CUT(LOCATION,-,1)}) same =
same => n,Playback(silence/2&pls-try-call-later) same => n,Hangup()Our service_provider might look something like this in sip.conf:[ser
from the Asterisk CLI, or reload the module associated with the configuration file (e.g.,using module reload chan_sip.so).When using static realtime,
A Word About MetricsThe metrics in static realtime are used to control the order in which objects are readinto memory. Think of the cat_metric and var
musiconhold.conf => odbc,asterisk,ast_configThen connect to the Asterisk console and perform a reload:*CLI> module reload res_musiconhold.soYou
You may have noticed we used the same table for both the sippeers and sipusers. Thisis because there will be a type field (just as if we were defining
Column name Column typesecret Varchar 128context Varchar 128host Varchar 128ipaddr Varchar 128port Varchar 5regseconds Bigintdefaultuser Varchar 128fu
the hackers will be able to quickly respond to changing trends in security and fine-tunethe telephone system in response to both corporate policy and
Additional options in sip.conf exist for realtime peers. These are defined in the[general] section and described in Table 16-5.Table 16-5.
There are many more options for that we can define for SIP friends, such as the callerID; adding that information is as simple as adding a callerid co
After creating your table in the database (which we’ll assume you’ve called cdr), youneed to configure the cdr_adaptive_odbc.conf file in the /etc/ast
After the alteration to your database and dialplan, you can place a call and then lookat your CDRs. You should see something like the following:+-----
In some situations you may specify a connection where you only want to log calls froma specific source, or to a specific destination. We can do this w
This section builds upon previous configuration sections in this chapter.If you have not already done so, be sure to follow the steps in the sections“
We’ll be making use of the PostgreSQL procedural language called pgSQL/PL to createa function. This function will be called from a trigger that gets e
context varchar(80), macrocontext varchar(80), callerid varchar(40), origtime varchar(40), duration varchar(20), mailboxuser varchar(80), mail
Configuring voicemail.conf for ODBC StorageThere isn’t much to add to the voicemail.conf file to enable the ODBC voicemail storage.In fact, it’s only
Then verify that your new mailbox loaded successfully:*CLI> voicemail show users for defaultContext Mbox User Zone N
Obviously, new users do not fit any particular kind of mold. While some will happilyspend hours experimenting and reading various blogs describing the
Then configure your phone or client with the username odbc_test_user and password<supersecret>, and place a call to extension 100 to leave a voi
Verifying binary data stored in PostgreSQLTo make sure the recording really did make it into the database, use the psql application:$ psql -h localhos
Verifying binary data stored in MySQLTo verify that your data is being written correctly, you can use the mysql applicationto log into your database a
might if you are going to use it for overhead paging), or copy the file to another systemand listen to it there:$ play /tmp/voicemail_recording.wav vo
CHAPTER 17Interactive Voice ResponseOne day Alice came to a fork in the road and saw aCheshire cat in a tree. “Which road do I take?”she asked.“Where
Components of an IVRThe most basic elements of an IVR are quite similar to those of an automated attendant,though the goal is different. We need at le
Argument Purposeattempts The number of times to play the prompt. If the caller fails to enter anything, the Read() application canautomatically re-pro
IVR Design ConsiderationsWhen designing your own IVR, there are some important things to keep in mind. We’veput together this list of some things to d
programmer but are very adept with Asterisk dialplans and databases, you’ll lovefunc_odbc just as much as we do. Check it out in Chapter 16
Asterisk-UsersThis is where most Asterisk users hang out. This list generates several hundredmessages per day and has over ten thousand subscribers. W
On Ubuntu:$ sudo apt-get install libcurl4-openssl-devThe DialplanThe dialplan for our example IVR is very simple. The CURL() function will retrieve ou
same => n,Background(${which}) same => n,Goto(s,step2)exten => 2,1,Set(step2count=0) same => n,Playback(prompt-waitforbeep) same
While on the surface, the idea of a speaking computer is very attractive, the reality isthat it has limited usefulness. More information about integra
CHAPTER 18External ServicesCorrect me if I’m wrong—the gizmo is connected to theflingflang connected to the watzis, watzis connected tothe doo-dad con
Calendar IntegrationAsterisk can be integrated with several different kinds of calendar formats, such as iCal,CalDAV, MS Exchange (Exchange 2003), and
If you are planning on compiling the res_calendar_ews module, you willneed to have a version of neon greater than or equal to 0.29. CurrentlyCentOS is
up and running far quicker. Of course, once you’re comfortable with configuring cal-endaring support in Asterisk, you can connect it to any calendarin
$ asterisk -r*CLI> module load res_calendar.so*CLI> module reloadAfter loading the modules we can check to make sure our calendar has connected
If you have not configured any of the Notify options but have an alarmset to remind you in the calendar, you may get a WARNING message suchas:WARNING[
When the event rolls around, Asterisk will generate a call to you and play back thesound file this-is-yr-wakeup-call. The output on the console would
The Asterisk Documentation ProjectThe Asterisk Documentation Project was started by Leif Madsen and Jared Smith, butseveral people in the community ha
When the event time arrives, our device will receive a call, and when that call is an-swered another call will be placed to the endpoint with which we
; *** This line should not have any line breaks same => n,Read(CheckMeetingAcceptance,to-confirm-wakeup&press-1&otherwise&press-2,,1)
been dialed and answered (or perhaps not answered), the organizer will be placed intothe call, at which point the meeting will start.This type of func
; same => n,MeetMe(${CalLocation},dA) same => n(hangup),Hangup()[MeetingOriginator]exten => _[A-Za-z0-9].,1,NoOp() same => n,Set(Pee
same => n(unavail),VoiceMail(${CurrentExten}@shifteight,u) same => n,Hangup()And here is a slightly more elaborate section of dialplan that
On the left side of the Google calendar interface will be a link labeled Add. Clicking onthis will open a new window where you can create the calendar
Now that we have our calendar configured, we need to load it into memory, which canbe done by reloading the res_calendar.so module:*CLI> module rel
Many possibilities exist for the CALENDAR_WRITE() function; this is just one that we’veimplemented and enjoy.ConclusionIn this section we’ve learned h
ability to listen to, forward, and mark voicemail messages with the same flexibility thatthe Asterisk VoiceMail() dialplan application gives. Asterisk
Compiling the IMAP libraryNow that we have our dependencies satisfied, we can compile the IMAP library thatAsterisk will use to connect to our IMAP se
CHAPTER 2Asterisk ArchitectureFirst things first, but not necessarily in that order.—Doctor WhoAsterisk is very different from other, more traditional
To compile for a 32-bit platform with OpenSSL support and a preference for connectingvia IPv4:$ make lnp EXTRACFLAGS="-I/usr/include/openssl"
web-based IMAP server such as that supplied by Google’s Gmail.‖ Our instructions aregoing to show how to connect Asterisk to a Gmail account with IMAP
We’re going to demonstrate how to connect to an IMAP-enabled Gmail account anduse that to store and retrieve our voicemail messages. If you haven’t al
Table 18-2 shows some of the other options available to us.Table 18-2. Additional IMAP voicemail optionsOption Descriptionimapfolder Provides the name
We’ve removed the email address from the third field because we’re not going to usesendmail to email us voicemails anymore: they are just going to be
Compiling Jabber Support into AsteriskThe res_jabber module contains various dialplan applications and functions that areuseful from the Asterisk
You must already have a Gmail account, which you can get at http://www.gmail.com.Our jabber.conf file should look like this:[general]debug=noautoprune
Option Descriptionstatus Defines our default connection status when signed into our account. Available options are: chat,available, away, xaway, and d
Here is a simple example to get us started:[LocalSets]exten => 104,1,Answer(); *** This line should not have any line breaks same => n,JabberS
same => n,JabberSend(asterisk,[email protected],Incoming call from${CALLERID(all)}. Press 1 to route to desk. Press 2 to send to voicemail.)
Figure 2-1. Asterisk vs. PBX architectureModulesAsterisk is built on modules. A module is a loadable component that provides a specificfunctionality,
much time to respond. However, if we set the response long enough to make itcomfortable for the user to send a response, we cause unnece
With the examples provided here serving as a springboard, you should be able to de-velop rich applications that make use of sending and receiving mess
channel drivers in Asterisk. For now chan_gtalk is fairly simple, but future versions ofAsterisk may add this feature.Our gtalk.conf file looks like t
specify which account calls will be coming from with the connection option, whichwe’ve set to the account created in jabber.conf.The chan_gtalk module
send the DTMF prior to ringing your device by adding the two boldface lines shownhere prior to performing the Dial():[gtalk_incoming]exten => s,1,V
Skype IntegrationSkype integration now exists with Asterisk through a commercial module from Digiumcalled Skype for Asterisk (SFA).‡ The SFA module lo
Users configured in chan_skype.conf must be created with the SkypeManager interface. Personal Skype IDs are not allowed.Our example Skype user wil
Our dialplan simply answers the call and attempts to place a call to vuc.me,§ wait 30seconds for that user to answer, and, if there is no answer, play
for 30 seconds, and then (if there is no answer or the device is busy or unavailable) playback a prompt that says the user is currently unavailable, f
the SkypeChatSend() and SKYPE_CHAT_RECEIVE() dialplan application and function,respectively:exten => 106,1,Answer() ; All text must be on
• Channel drivers• Codec translators• Format interpreters• Dialplan functions• PBX modules• Resource modules• Addons modules• Test modulesIn the follo
involved for text-to-speech to really make a lot of sense—otherwise, why not use pre-recorded prompts instead? However, an idea finally came to us, ba
Configuring OpenLDAPWhile a discussion of the installation and configuration of an LDAP server is beyondthe scope of this chapter, it is certainly app
We’ll insert the returned value (without the hyphen) into the following file within theuserPassword field, prefixed with {md5}:$ cat > astuser.ldif
With the file created, we can add the user to our LDAP server:$ sudo ldapadd -x -D cn=admin,dc=shifteight,dc=org -f astusers.ldif -WEnter LDAP Passwor
configure how Asterisk is going to connect to our LDAP server. Our first option isurl, which will determine how to connect to the server. We have defi
Configuring extconfig.confOur next step is to tell Asterisk what information to load via realtime and what tech-nology to use. Using the extconfig.con
To enable peer caching in Asterisk, use the rtcachefriends option in sip.conf:rtcachefriends=yesThere are additional realtime options as well, such as
This function name may be added to the server safe functions."(let ((wholeutt (utt.synth (eval (list 'Utterance 'Text string)))))(utt.w
Alternatively, if you’re having issues with the Festival server, you could use the follow-ing method to generate files with the text2wave application
CHAPTER 19FaxHave no fear of perfection. You’ll never reach it.—Salvador DaliThe concept of facsimile transmission has been around for over 100 years,
And now, without further ado, let’s take a look at the modules, grouped by moduletype.ApplicationsDialplan applications are used in extensions.conf to
Asterisk Fax cannot:• Print faxes• Accept documents for transmission in any format other than TIFFReceiving is relatively simple, since the format of
This will install the library in the /usr/local/lib/ folder. On many Linux systems thisfolder is not automatically part of the library path (libpath),
At this point the SendFAX() and ReceiveFAX() dialplan applications will be availableto you.Disabling spandsp (Should You Want to Test Digium Fax)The s
Incoming Fax HandlingReceived faxes are commonly encoded in Tagged Image File Format (TIFF). Thisgraphics file format, while not as well kn
software would have a difficult time making sense of). In other words, unless you ded-icate a DID to each user who might receive a fax, Asterisk isn’t
Table 19-1. Possible values for the faxdetect option in chan_dahdi.confValue Descriptionincoming Enables fax detection on inbound calls. When a fax is
Transmitting a Fax from AsteriskTo transmit a fax from Asterisk, you must have a TIFF file. How you generate this TIFFis important, and may involve ma
$ sudo yum -y install ghostscriptand in Ubuntu with:$ sudo apt-get install ghostscriptOnce installed, ghostscript can convert the PDF into an Asterisk
import sysimport osimport emailimport base64import shutilimport socketAMI_HOST = "localhost"AMI_PORT = 5038AMI_USER = "hello"AMI_P
\rAction: Originate\rChannel: Local/s@sendfax/n\rContext: receivefax\rExtension: s\rPriority: 1\rSetVar: SUBJECT=%s\r\rAction: Logoff\r\r""&
Name Purpose Popularity/Statusapp_echo Loops received audio back to source channel Usefulapp_exec Contains Exec(), TryExec(), and ExecIf(); executesa
Fax Pass-ThroughIn theory, it should be possible to connect a traditional fax machine to an FXS port ofsome sort and then pass incoming faxes to that
This would be placed in your /etc/asterisk/chan_dahdi.conf file and would causechan_dahdi to create a 96 ms buffer for fax calls and delay s
CHAPTER 20Asterisk Manager Interface (AMI)John Malkovich: I have seen a world thatNO man should see!Craig Schwartz: Really? Because for most people it
This sample configuration is set up to only allow local connections tothe AMI. If you intend on making this interface available over a network,it is s
Once you have this working, you have verified that AMI is accepting connections viaa TCP connection.AMI over HTTPIt is also possible to use the AMI ov
$ wget "http://localhost:8088/rawman?action=logoff" --load-cookies cookies.txt -O ---2010-08-31 12:34:23--Resolving localhost... 127.0.0.1Co
Option Value/Example Descriptiontlsbindaddr 0.0.0.0 Sets the address to listen on for TLS-based AMI con-nections. The default is to listen on all addr
The manager.conf configuration file also contains the configuration of AMI user ac-counts. An account is created by adding a section with the username
Table 20-3. Available values for AMI user account read/write optionsPermission identifier read writeall Shorthand way of specifying that this usershou
THIRD EDITIONAsterisk™: The Definitive GuideLeif Madsen, Jim Van Meggelen, and Russell BryantBeijing•Cambridge•Farnham•Köln•Sebastopol•Tokyo
Name Purpose Popularity/Statusapp_read Requests input of digits from callers and assigns input to avariableUsefulapp_readexten Requests input of digit
Permission identifier read writeaoc Lets user see Advice of Charge events gener-ated as AOC events are received.Allows user to execute the AOCMessage
Option Value/Example Descriptiontlscipher <cipherstring>Specifies a list of ciphers for OpenSSL to use. Setting this is optional. To see a listo
Message EncodingAll AMI messages, including manager events, manager actions, and manager actionresponses, are encoded in the same way. The messages ar
EventsManager events always have an Event header and a Privilege header. The Event headergives the name of the event, while the Privilege header lists
This is the method that was used in the quick-start example, as seen in “AMI overHTTP” on page 459. The second authentication option is HTTP digest au
/manager encodingThe manager encoding type provides a response in simple HTML form. This interfaceis primarily useful for experimenting with the AMI.
/mxml encodingThe mxml encoding type provides responses to manager actions encoded in XML. Hereis an example Login using the mxml encoding type:$ curl
<generic response='Success' message='Authentication accepted' /></response></ajax-response>$ wget --load-coo
Interesting ApplicationsMany useful applications have been developed that take advantage of the AMI. Hereare a couple of examples.AsteriskGUIThe Aster
Flash Operator PanelFlash Operator Panel is an application that runs in a web browser using Flash. It isprimarily used as an interface to see which ex
Name Purpose Popularity/Statusapp_while Includes While(), EndWhile(), ExitWhile(), andContinueWhile(); provides while-loop functionality inthe dialpla
CHAPTER 21Asterisk Gateway Interface (AGI)Caffeine. The gateway drug.—Eddie VedderThe Asterisk dialplan has evolved into a simple yet powerful program
echo 'SAY ALPHA "Hello World" ""'read RESPONSEexit 0Now, call extension 500 with AGI debugging turned on and listen to A
AGI VariantsThere are a few variants of AGI that differ primarily in the method used to communicatewith Asterisk. It is good to be aware of all of the
Pros of Enhanced AGIIt has the simplicity of process-based AGI, with the addition of a simple read-onlystream of the channel’s audio. This is the only
The default port number for a FastAGI connection is 4573. A different port number canbe appended to the URL after a colon. For example:exten => 123
Additional information on how to use async AGI over the AMI can be found in the nextsection.Pros of async AGIAn existing AMI application can be used t
Table 21-1. AGI environment variablesVariable Value / Example Descriptionagi_request hello-world.sh The first argument that was passed to the AGI() or
For an example of the variables that might be sent to an AGI application, see the AGIcommunication debug output in “Quick Start” on page 475. The end
A full list of available AGI commands can be retrieved from the Asterisk console byrunning the command agi show commands. These commands are desc
Table 2-3. Call detail recording modulesName Purpose Popularity/Statuscdr_adaptive_odbc Allows writing of CDRs through ODBC frame-work with ability to
AGI command DescriptionSAY DIGITS Say a string of digits. For example, 100 would be said as “one zero zero” if the channel’s languageis set to English
AGI command DescriptionSPEECH DEACTIVATEGRAMMARDeactivate a grammar.SPEECH RECOGNIZE Play a prompt and perform speech recognition, as well as wait for
Command: VERBOSE "Puppies like cotton candy." 1Response: SuccessActionID: my-action-idMessage: Added AGI command to queueEvent: AsyncAGIPri
will send a line containing the word HANGUP. If you would like to disable having Asterisksend the SIGHUP signal to your process-based AGI application
Table 21-3. AGI development frameworksFramework Language URLAdhearsion Ruby http://adhearsion.com/StarPy Python http://starpy.sourceforge.net/Asterisk
CHAPTER 22ClusteringYou cannot eat a cluster of grapes at once, but it is veryeasy if you eat them one by one.—Jacques RoumainThe word “clustering”
functions such as voicemail and conferencing being provided through external modulesthat may cost thousands of dollars. This topology is illustrated i
to or from the CO, either Asterisk will deliver calls from the PRI through itself and tothe existing PBX, or the existing PBX will send calls over the
over time, limiting interruptions to the business and taking a more gradual approachto training users.Pure Asterisk, NondistributedThe next step in ou
systems, electrical grids, and Internet connections, the company can save a significantamount of money by supporting remote employees. Additionally, t
Channel DriversWithout channel drivers, Asterisk would have no way to make calls. Each channeldriver is specific to the protocol or channel type it su
our data is abstracted outside of Asterisk, we can use applications such as unison(http://www.cis.upenn.edu/~bcpierce/unison/) or rsync t
Replicated DatabasesUsing a replicated database provides some redundancy in the backend to help limit theamount of downtime callers and agents e
specify the preferred order for database connections in case one fails. In func_odbc, youcan even specify different servers for reading data and writi
systems to live on low-latency links, which typically means they all need to reside inthe same physical location, attached to the same switch. That sa
wide area networks, we can now have Asterisk systems at different physical locationsdistribute device state information to each other (see Figure 22-7
The advantage to XMPP device state distribution is that it is possible to distribute stateto multiple physical locations, which is not possible with O
Asterisk system, and then another caller enters the sales queue on box two, no infor-mation will be distributed between those queues to indicate who i
ConclusionIn this chapter we explored how you can transition a traditional (non-Asterisk) teleph-ony system into a distributed call center. Along the
CHAPTER 23Distributed Universal NumberDiscovery (DUNDi)A community is like a ship; everyone ought to beprepared to take the helm.—Henrik IbsenDistribu
Codec TranslatorsThe codec translators (Table 2-6) allow Asterisk to convert audio stream formats be-tween calls. So if a call comes in on a PRI circu
Bob asks Sally if she knows how to reach the requested extension, and she respondswith, “You can reach that extension at IAX2/dundi:very_long_p
by requesting the extension numbers from the remote location when your local boxdoesn’t know how to reach them.Additionally, if one of the locations h
Option Descriptionautokill Used to control how long we wait for an ACK to our DPDISCOVER. Setting this timeout prevents thelookups from stalling due t
Option Descriptioninclude Used to control whether this peer is included in searches for the mapping defined. Can be set to the value ofall if used for
[email protected]=+14165551212;; Specify bind address and port number. Default is port 4520.;bindaddr=0.0.0.0port=4520
; Specify bind address and port number. Default port is 4520.;bindaddr=0.0.0.0port=4520entityid=00:00:00:00:00:00ttl=32autokill=yes;secretpath=dundiI
Vancouver server in /var/lib/asterisk/keys/ and place the vancouver.pub file on the Tor-onto server in the same location.After downloading the keys, w
When you create a peer, you need to define which mapping contexts you will allowthis peer to search. You do this with the permit statement (each peer
${NUMBER}The number being requested.${IPADDR}The IP address to connect to.It is generally safest to statically configure the hostname, rather thanmake
Since we only have a single mapping defined (extensions), we’re going to permit andinclude extensions within our peer definitions on both the Toronto
If you store a recording in several formats (such as WAV, GSM, etc.), Asterisk willdetermine the least costly format§ to use when a channel requires t
We’ve added the keyword bypass to the end of the lookup in order to bypass the cache(in case we wish to perform several tests):vancouver*CLI> dundi
toronto*CLI> sip reloadTo accept the incoming calls, define the [DUNDi_Incoming] context in extensions.confand add the following to the Toronto sys
Controlling ResponsesResponses are controlled with the dialplan. Whenever an incoming request matchesthe dialplan configured for the mapping (whether
We could also advertise a full or partial range of extensions using pattern matches:[RegisteredDevices]exten => _1[1-3]XX,1,NoOp() ; extensions 11
Because the other end is just going to request an extension number and won’t neces-sarily know the location of the device on our system, we
our example) using the DB() function. To determine which value the IF() function willreturn, we use the DB_EXISTS() function. This function checks whe
same => n,Verbose(2,The result of the lookup was ${DUNDi_Result})same => n,Hangup()The arguments passed to DUNDILOOKUP() are: extension,context,
; End of our loop same => n,EndWhile() same => n,Playback(silence/1) same => n,Playback(vm-goodbye) same => n,Hangup(); If no resu
same => n,Set(thisResult=${DUNDIRESULT(${DUNDI_ID},${ResultCounter})}); If the current value returned is not None, we have a resulting; location
CHAPTER 24System Monitoring and LoggingChaos is inherent in all compounded things.Strive on with diligence.—The BuddhaAsterisk comes with several subs
Name Purpose Popularity/Statusfunc_callcompletion Gets/sets call completion configuration parameters for the channel Newfunc_callerid Gets/sets Caller
There is a sample logger.conf file that comes with the Asterisk source, but rather thanjust copying over the sample file, we recommend that you use th
Type Descriptiondebug Debugging is only useful if you are troubleshooting a problem with the Asterisk code itself. You would not usedebug to troublesh
exited non-zero on 'Zap/1-1'[Mar 11 09:39:35] VERBOSE[2973] logger.c: -- Hungup 'Zap/1-1'[Mar 11 09:39:35] VERBOSE[3680] logge
Verifying LoggingYou can view the status of all your logger.conf settings through the Asterisk CLI byissuing the command:*CLI> logger show channels
Option Value/Example Noteslastdata SIP/0004F2046969,30,tT The arguments passed to the lastapp. This field is set automat-ically and is read-only.start
To view the built-in documentation for the CDR() function, run the following commandat the Asterisk console:*CLI> core show function CDRIn addition
Option Value/ExampleNotesbatch no Queue up CDRs to be logged in batches instead of logging synchronously at the endof every call. This prevents CDR lo
[mytable]connection = asterisktable = asterisk_cdrA more detailed example of setting up a database for logging CDRs can be found in“Storing Call Detai
cdr_csvThe cdr_csv module is a very simple CDR backend that logs CDRs into a CSV (commaseparated values) file. The file is /var/log/asterisk/cdr-csv/M
${CSV_QUOTE(${CDR(end)})},${CSV_QUOTE(${CDR(duration)})}, ${CSV_QUOTE(${CDR(billsec)})},${CSV_QUOTE(${CDR(disposition)})}, ${CSV_QUOTE(${CDR(am
Name Purpose Popularity/Statusfunc_sprintf Performs string format functions similar to C function of same name Usefulfunc_srv Perform SRV lookups in t
CallerID: Channel: Console/dspDestinationChannel: LastApplication: HangupLastData: StartTime: 2010-08-23 08:27:21AnswerTime: 2010-08-23 08:27:21EndTim
cdr_sqliteThis module allows posting of CDRs to a SQLite database using SQLite version 2.Unless you have a specific need for SQLite version 2 as oppos
The Asterisk module has a configuration file, as well. Add the following section to /etc/asterisk/cdr_syslog.conf:[cdr]facility = local4priority = inf
Here is the CDR that was logged to Master.csv as a result of this call:"""Console"" <2565551212>","2565551212
CEL event type DescriptionCHAN_END occurs after Asterisk has completed post-call cleanup and all resources associated withthat channel have been relea
Channel Event ContentsEach CEL event contains the fields listed in Table 24-9:Table 24-9. CEL event fieldsField name Value/Example Noteseventtype CHAN
Dialplan ApplicationsThe CEL system includes a single dialplan application that lives in the app_celgenu-serevent.so module. This application is used
cel.conf, which were described in the previous section, these modules require configu-ration to make them operate.cel_odbcThe cel_odbc.so module provi
• userfield• peerTable 24-11 shows the mapping between event types and their integer values that willbe inserted into the eventtype column of the data
Table 24-12 shows the options that can be specified in a table configuration section inthe cel_odbc.conf file.Table 24-12. cel_odbc.conf table configu
Table 2-10. Resource modulesName Purpose Popularity/Statusres_adsi Provides ADSI Essentialares_ael_share Provides shared routines for use with pbx_ael
The following example shows a sample configuration for cel_custom that enables asingle CEL log file, Master.csv. This file will be created as /var/log
With this configuration in place, CEL events will appear as events on the managerinterface. To generate example manager events, we will use the
cel_sqlite3_customThis CEL backend inserts CEL events into a SQLite database using SQLite version 3.The database created by this module lives at /var/
apps = Dial,Playbackevents = ALLSingle-party callIn this example, a single phone calls into an extension that plays back a prompt thatsays “Hello Worl
"APP_START","1282062455.574872","Julie Bryant","12565553333","12565553333","", "101
exten => 101,1,Dial(SIP/0000FFFF0001)exten => 102,1,Dial(SIP/0000FFFF0002)Here are the CEL events logged as a result of this call scenario:"
"3","","1282062488.21","1282062488.20","","""APP_END","1282062497.941415
SNMPThe Simple Network Management Protocol (SNMP) is a standardized protocol fornetwork management. It is very commonly used and implemented across ma
$ cd /usr/src/asterisk-complete/asterisk/1.8/$ ./configure$ make menuselect # verify that res_snmp is selected under Resource Modules $ sudo make ins
Editing /etc/asterisk/res_snmp.conf to work with your OpenNMS serverIn the /etc/asterisk/res_snmp.conf file that you’ve copied over from your source d
Name Purpose Popularity/Statusres_security_log Enables security logging Newres_smdi Provides voicemail notification using the SMDI protocol Limitedres
syscontact Leif Madsen [email protected] + DThe syslocation and syscontact lines are not necessary, but they canmake it easier to identify a
and have access to the Asterisk statistics. You should be able to click on ResourceGraphs after selecting the node you created and see a selection of
will clone the opennmsUser user from the initial user. We configured the passwordsetup_passphrase for the authentication and privacy settings when we
com2sec notConfigUser default public#group notConfigGroup v1 notConfigUser#group notConfigGroup v2c notConfigUsergroup
-x DES -X 0p3nNMSv3 \localhost .1.3.6.1.4.1.22736If all goes well, you should get lots of lines back, including:SNMPv2-SMI::enterprises.22736.1.5.4.1.
Figure 24-2 shows a graph of active channels of a specific type. In this case, we’relooking at how many DAHDI channels are active on the system. Monit
CHAPTER 25Web InterfacesA point of view can be a dangerous luxury whensubstituted for insight and understanding.—Marshall McLuhanBefore you get too ex
What we will do in this chapter is introduce a few projects that provide web interfacesinto other parts of the system, and a selection of web-driven a
Queue Status DisplayQueue status will often be displayed on a large, wall-mounted panel or a reader board.Here are some of the kinds of information th
Asterisk™: The Definitive Guide, Third Editionby Leif Madsen, Jim Van Meggelen, and Russell BryantCopyright © 2011 Leif Madsen, Jim Van Meggelen, and
Test ModulesTest modules are used by the Asterisk development team to validate new code. Theyare constantly changing and being added to, and are not u
want excellent reporting capabilities, you will find a huge industry with many experi-enced participants.For a simple interface to the call records, a
CHAPTER 26SecurityWe spend our time searching for security andhate it when we get it.—John SteinbeckSecurity for your Asterisk system is critical, esp
'"12345"<sip:[email protected]>' failed for '203.86.167.220:5061' - No matching peer found[Aug 22 15:17:15] NOTICE[2
These account scans take advantage of the fact that the response that comes back fromthe server for a registration attempt will differ depending on wh
InstallationFail2ban is available as a package in many distributions. Alternatively, you can installit from source by downloading it from the Fail2ban
$ sudo apt-get install postfixTo install Postfix on CentOS, use this command:$ sudo yum install postfixTo test the installation of your MTA, you can s
NOTICE.* .*: Registration from '.*' failed for '<HOST>' # - No matching peer found NOTICE.* .*: Regis
[DEFAULT]# Multiple addresses can be specified, separated by a space.ignoreip = 127.0.0.1 10.1.1.1destemail = [email protected] Medi
A call like this is an attempt at exploiting a dialplan injection vulnerability. In the pre-vious extension definition, once ${EXTEN} has been evaluat
an extension to the dialplan that runs the System() application, enabling it to run anycommand it wants. If it also has access to originate calls, it
The Resource LibraryThere are several resources that require external data sources. For example, music onhold (MOH) can’t happen unless you have some
192.168.1.0/255.255.255.0 = 1024[some_peer]; A dynamic peer's address is not known until that peer; registers. A call number limit can be specifi
good idea to set ACLs to ensure that only devices on your local network can use theaccounts for the phones. Here is an example of doing that in /etc/a
One of the most popular tools for SIP account scanning and password cracking isSIPVicious. We strongly encourage that you take a look at it and use
CHAPTER 27Asterisk: A Future for TelephonyNow this is not the end. It is not even the beginning ofthe end. But it is, perhaps, the end of the beginnin
It’s interesting to contrast the history of the telephone with the history of Linux andthe Internet. While the telephone was created as a commercial e
consistently. Each manufacturer desires a total monopoly, so the concept of intero-perability tends to take a back seat to being first to market with
is not familiar to the telecom industry, and very well might not be until open sourceproducts such as Asterisk begin to transform the fundamental natu
The fact that a customer might only need five out of five hundred features is ignored,and that customer’s desire to have five unavailable features tha
Standards ComplianceIn the past few years, it has become clear that standards evolve at such a rapid pacethat to keep up with them requires an ability
Here are some of the options you can implement:Keep your old PBX, but evolve to IPCompanies that have spent vast sums of money in the past few years b
HardwareAsterisk is capable of communicating with a vast number of different technologies. Ingeneral, these connections are made across a network conn
callers to be transferred to extensions, and it is built into most proprietary voicemailsystems—but IVR can be so much more.IVR systems are generally
Here are a few examples of relatively simple IVRs an Asterisk system could be used tocreate:Weather reportingUsing the Internet, you can obtain text-b
Home automationAsterisk is still too much of an über-geek’s tool to be able to serve in the average home,but with no more than average Linux and Aster
Speech ProcessingThe dream of having our technical inventions talk to us is older than the telephoneitself. Each new advance in technology spurs a new
Asterisk, you can make voice-driven menus and IVR systems in record time! For moreinformation, see http://www.lumenvox.com.High-Fidelity VoiceAs we ga
Why we love videoconferencingVideoconferencing promises a richer communications experience than the telephone.Rather than simply hearing a disembodied
Unified MessagingThis is a term that has been hyped by the telecom industry for years, but adoption hasbeen far slower than predicted.Unified messagin
Now that calls are hopping from PSTN to Internet to who-knows-what, some consid-eration must be given to E.164.ENUMIn response to this challenge, the
VoIP spamYes, it’s coming. There will always be people who believe they have the right to incon-venience and harass others in their pursuit of money.
identify its physical location, an emergency call from it will provide no clue as towhere the caller is. VoIP creates similar challenges.Call monitori
number increasing by one each time a new feature release was created. The goal wasto provide new feature releases every 3–4 months (which would be bra
ComplexityOpen systems require new approaches to solution design. Just because the hardwareand software are cheap doesn’t mean the solution will be. A
creative skills will now actually serve the needs of their customers, rather than beingfocused on managing kludge.Proper integration of communications
APPENDIX AUnderstanding TelephonyUtility is when you have one telephone, luxury is whenyou have two, opulence is when you have three—andparadise is wh
limited bandwidth means that some sound quality will be lost (as anyone who’s hadto listen to music on hold can attest to), especially in the higher f
Table A-1. DTMF digits 1209 Hz 1336 Hz 1477 Hz 1633 Hz a697 Hz 1 2 3 A770 Hz 4 5 6 B852 Hz 7 8 9 C941 Hz * 0 # DaNotice that this column contains let
Tip and RingIn an analog telephone circuit, there are two wires. In North America, these wires arereferred to as Tip and Ring.‡ This terminology comes
end. Then, at the far end, use the transmitted information to generate a completely newaudio signal that has the same characteristics as the original.
To digitally encode the wave, it must be sampled on a regular basis, and the amplitudeof the wave at each moment in time must be measured. The process
From this information, the waveform can be reconstructed (see Figure A-6).Figure A-6. Delineated signalAs you can see if you compare Figure A-2 with F
While the development team still wants to provide access to new features and corechanges on a more regular basis (every 12 months being the goal), the
important point: the quality of the digitally encoded waveform is affected by the reso-lution and rate at which it is sampled. At too low a sampling r
Figure A-8. The same waveform at double the resolutionFigure A-9. Five-bit plotted PCM signalDigital Telephony | 605
From this information, the waveform shown in Figure A-10 can then be generated.As you can see, the resultant waveform is a far more accurate represent
telephone network will not carry frequencies below 300 Hz and above 4,000 Hz, asampling frequency of 8,000 samples per second will be sufficient to re
Figure A-11. Five-bit companding608 | Appendix A: Understanding Telephony
Figure A-12. Quantized and companded at 5-bit resolutionDigital Telephony | 609
AliasingIf you’ve ever watched the wheels on a wagon turn backward in an old Western movie,you’ve seen the effects of aliasing. The frame rate of the
Even the ubiquitous analog circuit is sampled into a DS-0 as soon as possible. Some-times this happens where your circuit terminates at the central of
SONET and OC circuitsThe Synchronous Optical Network (SONET) was developed out of a desire to take theT-carrier system to the next technological level
supported) has to be sent as part of the audio stream. CAS is commonly used on theT1 link in channel banks.ISDNThe Integrated Services Digital Network
CHAPTER 3Installing AsteriskI long to accomplish great and noble tasks, but it is mychief duty to accomplish humble tasks as though theywere great and
uses a single DS-0 channel as a signaling link (the D-channel); the remaining channelsserve as B-channels.In North America, Primary Rate ISDN is commo
Packet-Switched NetworksIn the mid-1990s, network performance improved to the point where it became possibleto send a stream of media information in r
APPENDIX BProtocols for VoIPThe Internet is a telephone system that’s gotten uppity.—Clifford StollThe telecommunications industry spans over 100 year
• G.729A• GSM• iLBC• Speex• MP3We will then conclude the appendix with a discussion of how voice traffic can be routedreliably, what causes echo and h
thousands of packages, and then deliver each package in whatever way possible to thefar end. Clearly, some way of dealing with this is required.VoIP P
FutureSince IAX was optimized for voice, it has received some criticism for not better sup-porting video—but in fact, IAX holds the potential to carry
know today and contained only a single request type: a call setup request. In March1999, after 11 revisions, SIP RFC 2543 was born.At first, SIP was a
sell unless a migration path to SIP is offered. SIP is widely expected to deliver far morethan VoIP capabilities, including the ability to transmit vi
H.323This International Telecommunication Union (ITU) protocol was originally designedto provide an IP transport mechanism for videoconferencing. It h
We have chosen to install on CentOS and Ubuntu because they are the most popularoptions, but Asterisk is generally distribution-agnostic. Asterisk wil
Security considerationsH.323 is a relatively secure protocol and does not require many security considerationsbeyond those that are common to any netw
MGCP is defined in RFC 3435.* It was designed to make the end devices (such asphones) as simple as possible, and have all the call logic and processin
We’ve all seen optical illusions; likewise, voice-compression algorithms take advantageof our tendency to interpret what we believe we should hear,
G.711 imposes minimal (almost zero) load on the CPU.G.726This codec has been around for some time (it used to be G.721, which is now obsolete),and it
than that produced by G.729A, but much of this comes down to personal opinion; besure to try it out. GSM operates at 13 Kbps.iLBCThe Internet Low Bitr
MP3Sure thing, MP3 is a codec. Specifically, it’s the Moving Picture Experts Group AudioLayer 3 Encoding Standard.# With a name like that, it’s no won
The purpose of TCP is to guarantee the delivery of packets. In order to do this, severalmechanisms are implemented, such as packet numbering (for reco
By addressing the major shortcomings of TCP and UDP, SCTP’s developers hoped tocreate a robust protocol for the transmission of SS7 and other types of
dynamic by distributing control of labels to the routers. This enables the network tobecome more responsive to changing conditions, because it can be
If you hear echo, it’s not your phone that’s causing the problem; it’s the far end of thecircuit. Conversely, echo heard on the far end is being gener
Some of the most popular Asterisk-based projects include:AsteriskNOW http://www.asterisk.org/asterisknowTrixbox http://www.trixbox.orgElastix http://w
Asterisk and VoIPIt should come as no surprise that Asterisk loves to talk VoIP. But in order to do so,Asterisk needs to know which function it is to
it. If the remote end is another Asterisk box, the use of a register statement is required,as discussed in the next section.FriendsDefining a type as
Your service provider will have a definition in either its sip.conf or iax.conf configurationfile (depending on whether you are connecting with the SI
Encrypting Audio with Secure RTPIf you can sniff the packets coming out of an Asterisk system, you can extract the audiofrom the RTP streams. This dat
Placing your VoIP system in a demilitarized zone (DMZ) can provide an additionallayer of protection for your LAN, while still allowing connectivity fo
APPENDIX CPreparing a System for AsteriskVery early on, I knew that someday in some “perfect”future out there over the horizon, it would be common-pla
although the underlying causes will be different. As loads increase, the system will haveincreasing difficulty maintaining connections. For a PBX, suc
If you are sure that you need to set up a distributed Asterisk system, youwill want to study the DUNDi protocol, the Asterisk Realtime Archi-tecture (
Whether conferencing will be provided, and what level of conferencing activity is expectedWill the system be used heavily? Conferencing requires the s
support. The next section (“Choosing a Processor” on page 644) offers somegeneral guidelines for choosing a CPU that will meet the needs of
Some additional configuration of text files is required on Ubuntu.See “Enable NTP for accurate system time” on page 43.3. On CentOS, add a new system
Linux has historically had problems with its ability to service IRQsquickly; this problem has caused enough trouble for audio devel-opers that several
To attempt to provide you with a frame of reference from which you can contemplateyour platform decision, we have chosen to define three sizes of Aste
stressed. Users may begin to perceive quality problems without realizing that the systemis not faulty in any way, but simply exceeding its capacity. T
however, as APIC-enabled motherboards turn IRQ control over to the operatingsystem.• Server-class motherboards generally implement a different P
• If you need a modem, install an external unit that connects to a serial port. If youmust have an internal modem, you will need to ensure that it is
This oft-neglected component can turn an otherwise top-quality system into a poorperformer. By the same token, a top-notch power supply might enable a
One of the benefits of clean power is a reduction in heat, which means less stress oncomponents, leading to a longer life expectancy.Properly grounded
One of the authors recalls once frying a sound card he was trying toconnect to a friend’s stereo system. Even though both the computer andthe stereo w
It is also vital that each and every peripheral you connect to your system be connectedto the same electrical receptacle (or, more specifically, the s
TemperatureHeat is the enemy of electronics. The cooler you keep your system, the more reliablyit will perform, and the longer it will last. If you ca
$ make$ sudo make install$ sudo make config8. Install additional sound prompts from menuselect:$ cd ~/src/asterisk-complete/asterisk/1.8/$ make menuse
Because of Asterisk’s open architecture (and open source code), it is ultimately possibleto connect any standards-compliant interface hardware. The se
The Zapata Telephony Project originally produced a T1 card, the Tormenta, that is theancestor of most Asterisk-compatible T1 cards. The original Torme
eBay. Look for units from Adtran and Carrier Access Corp. (Rhino makes great channelbanks, and they are very competitively priced, but they may be har
of suffering later. Echo problems are not pleasant at all, and your users will hate thesystem if they experience it.Several software echo cancellers h
This section takes a brief look at the various user (or endpoint) devices you might wantto connect to your Asterisk system. We delve more deeply into
The chances of anyone ever making a proprietary digital phone directly compatiblewith Asterisk are slim, but companies such as Citel (http://www.citel
IP telephonesIP telephones are heralds of the most exciting change in the telecommunications in-dustry. Already, standards-based IP telephones are ava
Having thus muddied the waters, the best we can do at this point is to define what theterm softphone will refer to in relation to this book, with the
• If I use my PDA to connect to my voicemail and retrieve my voice messages (con-verted to text), does my PDA become a phone?• If I attach a video cam
IndexSymbols! (exclamation mark), in section name, 92# (hash symbol)comment, 188delimiter between map names, 226$[] (dollar sign square brackets)Aster
Table of ContentsForeword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
; PBX modules currently not needednoload => pbx_ael.sonoload => pbx_dundi.so; Channel modules currently not needednoload => chan_oss.sonoload
statistics: queue_log file, 296–299ackcall option (agents.conf), 281ACLs (access control lists), 574actions, AMI message encoding, 467adaptors, VoIP p
announce-position option (queues.conf), 278,288announce-position-limit option (queues.conf),278, 288announce-round-seconds option(queues.conf), 278, 2
astctlowner (asterisk.conf), 75astctlpermissions (asterisk.conf), 75astdatadir (asterisk.conf), 72AstDB (Asterisk Database), 214–216deleting data from
autokill option (dundi.conf), 506autokill option (sip.conf), 96autoload (modules.conf), 77autologoff option (agents.conf), 281autologoffunavail option
controlling calls based on calendarinformation, 407triggering calendar reminders, 402–406writing call information to a calendar, 408–411CALENDAR_BUSY(
two-party call, 547cel.conf, 540cel_custom, 543cel_custom module, 16cel_manager, 544cel_manager module, 16cel_odbc, 541cel_odbc module, 16cel_pgsql, 5
cidinternalcontexts option (voicemail.conf),163cidname, 539cidnum CEL event field, 539cidrdnis CEL event field, 539circuit types, 610Cisco SPAphones:
lsdahdi command, 142make menuselect command, 50, 352manager show command, 467manager show command AGI command,485manager show commands, 467md5sum comm
IAX trunks, 153iax.conf, 95–98, 514, 515, 573indications.conf, 77initial configuration, 52–59IP phones, 184jail.conf, 570LDAP support, 437loading new
cURL module, installing, 393CURL() dialplan function, 392, 394Custom:<custom name> virtual device, 301custom_beep option (agents.conf), 282Dd (P
15. Save your changes and your module configuration is done. Your system is readyto configure your dialplan and channels.Distribution InstallationBeca
external to the Asterisk server, 182–185state information, 295testing device registration, 99DEVICE_STATE() dialplan function, 302dial by extension, 3
DIDs (direct inward dialing numbers), 145differentiated service, 631digit 9, accessing external lines, 132digital circuit-switched telephone network,6
echo on DAHDi channels, 633dundi lookup command, 513dundi show peer command, 513dundi.conf, 505DUNDILOOKUP() function, 519DUNDIQUERY() function, 519,
extension numbers, DUNDi and Asteriskconfiguration, 517extension states, 303–305extensionsabout, 84adding special extensions, 119dialplan syntax, 110t
resource library, 25spool, 25FILTER() function, 242FilteredExtension channel variable, 242findslot (features.conf), 223findslot directive, 228Flash Op
g(#) (VoiceMailMain() application), 171G.711 codec, 626G.722 codec, 626, 628G.726 codec, 626, 627G.729A codec, 626, 627[general] sectionagents.conf, 2
ignoreip option (jail.conf), 570ignoreregexpire option (sip.conf), 374iLBC (Internet Low Bitrate Codec)about, 628quick reference, 626IMAP (Internet Me
ISNs, 254security and identity, 256–259distributed denial of service attacks,258phishing, 258security as an ongoing process, 259SPIT, 258toll fraud, 2
spandsp, 444LibSRTP, 150licensing, music on hold, 79lightbackground (asterisk.conf), 74Lightweight Directory Access Protocol (seeLDAP)limit option (re
membermacro option (queues.conf), 278memberspenalizing, 284menuselect, 59–64about, 59interfaces, 60scripting, 63using, 61menuselect command, 76menusel
Choose your language and make a keyboard selection.* If you’re in North America, youwill probably just select the defaults.If you’ve previously format
Network Time Protocol (see NTP)networksdigital circuit-switched telephone network,610–614packet-switched networks, 615nextaftercmd option (voicemail.c
PP (VoiceMail() application), 170p (VoiceMailMain() application), 171packages, Asterisk packages, 30packet-switched networksabout, 615hardware require
persistentmembers option (queues.conf), 275phishing, 258phone option (dundi.conf), 505phonesnaming, 85requirements, 657–662security, 586PHPAGI, 488phy
Queue() application, 291, 294, 499queue-callswaiting option (queues.conf), 279,289queue-holdtime option (queues.conf), 279,289queue-minutes option (qu
require (modules.conf), 77requirements, 639–662environment, 649–653hardware, 26Linux, 662phones, 657–662servers, 641–649telephony hardware, 653–657res
phishing, 258PSTN circuits and VoIP connections, 145scanning for valid accounts, 565servers, 653SIP, 622SPIT, 258test users, 383toll fraud, 257VoIP, 6
configuring chan_skype.conf, 429placing and receiving calls, 430sending and receiving messages, 432installing, 429SkypeChatSend() dialplan function, 4
storing data in, 214using in the dialplan, 215backends, 172–173IMAP, 173Linux filesystem, 172ODBC, 173storehistory option (dundi.conf), 506strategy op
toll fraud, 591unified messaging, 590video, 588VoIP spam, 592wireless, 589Asterisk community, 5–8Asterisk Documentation Project, 8IRC channels, 7maili
about, 257future of telephony, 591NANP and toll fraud, 127toll lines, accessing, 133tones, changing, 194tos option (dundi.conf), 505transcode_via_sln
At the Review and modify the partitioning layout screen, you can create a separate vol-ume for /var. Selecting Yes will bring up the Partitioning to
authentication, 634chan_skype.conf, 430users.conf, 84userscontext option (voicemail.conf), 160USER_DEFINED CEL event type, 538usesasl option (jabber.c
SPIT, 636spoofing, 637SIP, 620–622spam, 592telephony future, 2UNISTIM, 625VoIP to VoIP, 147volgain option (voicemail.conf), 164WWAIT FOR DIGIT AGI com
About the AuthorsLeif Madsen first got involved with the Asterisk community when he was looking fora voice conferencing solution. Once he learned that
Downloa d f r o m W o w ! e B o o k < w w w.woweb o o k . c o m >
Base system updateOnce you’ve rebooted your system, you need to run the yum update command to makesure you have the latest base packages. To do this,
Adding a system userThe Ubuntu server install process asks you to add a system user other than root, butCentOS does not. In order to be consistent in
Start by opening the hidden file .bash_profile located within the asteriskpbx home di-rectory with an editor. We’re then going to append :/usr/sbin:/s
You will be presented with a list of countries. Once you’ve found your country andhighlighted it, press Enter .You will then be asked if you would lik
After entering your username, you’ll be asked to supply a password, and then asked toconfirm the password you’ve entered. Ubuntu does a good job of pr
failed to detect that has information loaded into the MBR, it’s nice to be able to skipmodifying it. If this is the only operating system installed on
Resource Modules 21Addon Modules 23Test Modules 24File Structure 24Configuration Files 24Modules 24The Resource Library 25The Spool 25Logging 25The Di
The default on Ubuntu is to run a time sync server without ever changing the time onyour own machine. This won’t work for our needs, so we’l
dependencies; only the most commonly used modules will be built. If additionaldependencies are required for other modules used later in the
Third-Party RepositoriesFor certain software dependencies, a third-party repository may be necessary. Thisappears to be most often the case when usin
Getting the Latest VersionAsterisk is a constantly evolving project, and there are many different versions of thesoftware that you can implement.In Ch
How to Install ItWith the source files downloaded you can compile the software and install it. The orderfor installing is:1. LibPRI‡2. DAHDI§3. Asteri
DAHDIThe Digium Asterisk Hardware Device Interface, or DAHDI (formerly known as Zaptel),is the software Asterisk uses to interface with telephony hard
You will need to have Internet access when running the make all com-mand, as it will attempt to download the latest hardware firmware fromthe Digium s
Change the last line of the dahdi.rules file to the following:SUBSYSTEM=="dahdi", OWNER="asteriskpbx", GROUP="asteriskpbx&quo
To disable SELinux permanently, modify the /etc/selinux/config file:$ cd /etc/selinux/$ sudo vim configChange the SELINUX option from enforcing to dis
Running make samples on a system that already has configuration fileswill overwrite the existing files.Using make samples to Create SampleConfiguratio
The [files] Section 75The [compat] Section 75modules.conf 75The [modules] Section 76indications.conf 77musiconhold.conf 79Converting Music to a Format
Open the asterisk.conf file with an editor such as nano or vim: Uncomment the runuser and rungroup lines, and modify them so that they each contain as
The Asterisk Shell CommandAsterisk can be run either as a daemon or as an application. In general, you will wantto run it as an application when you a
-TThis option will add a timestamp to CLI output.-xThis command allows you to pass a string to Asterisk that will be executed as if ithad been typed a
Using cat to Quickly Create Files and Add Content to ThemThere are many cases in a Linux system where it is necessary to create a file, and thenadd so
; Channel modulesnoload => chan_oss.sonoload => chan_mgcp.sonoload => chan_skinny.sonoload => chan_phone.sonoload => chan_agent.sonoloa
we’ll just create a default music on hold class so that we have at a minimum some holdmusic when placing callers on hold:$ cd /etc/asterisk/$ cat >
We’re going to want extra sound prompts installed instead of just the default core soundprompts, and in a better-sounding format than GSM. We can do t
Figure 3-2. menuselect using the curses interfaceInstalling Dependencies for newt-Based menuselectTo get the newt-based menuselect working, you need t
You will be presented with a screen such as that in Figure 3-1 or Figure 3-2. You canuse the arrow keys on your keyboard to move up and down. The righ
Once you’ve completed selecting the sound files, press the x key to save and exitmenuselect. You then need to install your new prompts by dow
Commentaires sur ces manuels