Chapter 7. Outside Connectivity

You cannot always control what goes on outside. But you can always control what goes on inside.

Wayne Dyer

In the previous chapters, we have covered a lot of important information that is essential to a working Asterisk system. However, we have yet to discuss something that is vital to any useful PBX: namely, connecting it to the outside world. In this chapter we will discuss outside connectivity.

The groundbreaking architecture of Asterisk was significant due in large part to the fact that it treats all channel types as equal. This is in contrast to a traditional PBX, where trunks (which connect to the outside world) and extensions (which connect to users and resources) are logically separated. The fact that the Asterisk dialplan treats all channels in a similar manner means that in an Asterisk system you can accomplish very easily things that are much more difficult (or impossible) to achieve on a traditional PBX.

This flexibility does come with a price, however. Since the system does not inherently know the difference between an internal resource (such as a telephone set) and an external resource (such as a telco circuit), it is up to you to ensure that your dialplan handles each type of resource appropriately.

The Basics of Trunking

The purpose of trunking is to provide a shared connection between two entities. Trees have trunks, and everything that passes between the roots and the leaves happens through the trunk. Railroads use the term “trunk” to refer to a major line that connects feeder lines together.

In telecommunications, trunking connects two systems together. Carriers use trunks to connect their networks to each other. In a PBX, the circuits that connect the PBX to the outside world are (from the perspective of the PBX) usually referred to as trunks (although the carriers themselves do not generally consider these to be trunks). From a technical perspective, the definition of a trunk is not as clear as it used to be (PBX trunks used totally different technology from station circuits, but now both are usually SIP), but as a concept, trunks are still important. With SIP, everything is technically peer-to-peer, so from a technology perspective there isn’t really such a thing as a trunk anymore (... or perhaps it’s more accurate to say that everything is a trunk). From a functional perspective it is still useful to be able to differentiate between VoIP resources that connect to the outside world (trunks, lines, circuits, etc) and VoIP resources that connect to user endpoints (stations, sets, extensions, handsets, telephones, etc).

It’s probably easiest to think of a trunk as a collection of circuits that service a route. So, in an Asterisk PBX, you might have trunks that go to your VoIP provider for in-county long-distance calls, trunks for your overseas calls, and trunks that connect your various offices together. These trunks might actually run across the same network connection, but in your dialplan you could treat them quite differently. You can even have a trunk in Asterisk that simply loops back in on itself (which is usually some kludgy hack that solves some namespace or CDR problem that wasn’t getting solved any other way).

Fundamental Dialplan for Outside Connectivity

In a traditional PBX, external lines are generally accessed by way of an access code that must be dialed before the number.1 It is common to use the digit 9 for this purpose.

In Asterisk, it is similarly possible to assign 9 for routing of external calls, but since the Asterisk dialplan is so much more intelligent, it is not really necessary to force your users to dial 9 before placing a call. Typically, you will have an extension range for your system (say, 100–199), and a feature code range (*00 to *99). Anything outside those ranges that matches the dialing pattern for your country or region can be treated as an external call.

If you have one carrier providing all of your external routing, you can handle your external dialing through a few simple pattern matches. The example in this section is valid for the North American Numbering Plan (NANP). If your country is not within the NANP (which serves Canada, the US, and many Caribbean countries), you will need a different pattern match.

The [globals] section contains two variables, named LOCAL and TOLL.2 The purpose of these variables is to simplify management of your dialplan should you ever need to change carriers. They allow you to make one change to the dialplan that will affect all places where the specified channel is referenced:

[globals]
; These channels are the same to asterisk as
; any PJSIP enpoint, so they'll be configured
; similar to telephone sets.
; Each carrier will have their own configuration
; requirements (although they'll all be similar)
LOCAL=PJSIP/my-itsp
TOLL=PJSIP/my-other-itsp

The [external] section contains the actual dialplan code that will recognize the numbers dialed and pass them to the Dial() application:3

[external]
exten => _NXXNXXXXXX,1,Dial(${LOCAL}/${EXTEN}) ; 10-digit pattern match for NANP
exten => _NXXXXXX,1,Dial(${LOCAL}/${EXTEN})    ; 7-digit pattern match for NANP
exten => _1NXXNXXXXXX,1,Dial(${TOLL}/${EXTEN}) ; Long-distance pattern match 
                                               ; for NANP
exten => _011.,1,Dial(${TOLL}/${EXTEN})        ; International pattern match for 
                                               ; calls made from NANP

; This section is functionally the same as the above section. 
; It is for people who like to dial '9' before their calls
exten => _9NXXNXXXXXX,1,Dial(${LOCAL}/${EXTEN:1})
exten => _9NXXXXXX,1,Dial(${LOCAL}/${EXTEN:1})
exten => _91NXXNXXXXXX,1,Dial(${TOLL}/${EXTEN:1})
exten => _9011.,1,Dial(${TOLL}/${EXTEN:1})

In any context that would be used by sets or user devices, you would use an include=> directive to allow access to the external context:

[sets]
include => external
Warning

It is critically important that you do not include access to the external lines in any context that might process an incoming call. The risk here is that a phishing ‘bot could eventually gain access to your outgoing trunks (you’d be surprised at how common these phishing ‘bots are).

We cannot stress enough how important it is that you ensure that no external resource can access your toll lines.

The PSTN

The Public Switched Telephone Network (PSTN) has existed for over a century. It is the precursor to many of the technologies that shape our world today, from the Internet to MP3 players.

The use of old-school PSTN circuits in Asterisk systems is no longer common. The technical complexities, costs and limitations of obsolete technology are only justified in situations where a reliable internet connection is not available (and even then, traditional circuits will often be a problematic choice). Even the carriers themselves have largely switched to VoIP circuits for their internal backbones.

Where the PSTN might still hold sway for a few years more is in telephone numbers. If VoIP had been invented without the PSTN preceding it, it’s unlikely that something like a phone number would have ever been invented. Still, we’ve got them, and we use them, and the reason we do so is perhaps not so much due to any usefulness they provide, but rather due to the fact that they are managed by a complex, multinational consortium of standards-bodies and curators who ensure the integrity of the global call routing plan.

To put the value of this in perspective, it might be worth considering that if the internet had designed the telephone network (and phone calls were as free as email), all our SIP phones would likely be ringing all day long with one spammy call after another. That still happens, but it’s greatly reduced by the fact that a phone call costs money, and even if it costs just pennies, that’s enough to keep much of the exceedingly mindless spam out of the game.

Another feature the PSTN offers is standards-compliance and interoperability. If you look at any internet-based voice product, they are either proprietary walled-gardens, or they are community-driven and have failed to gain any useful traction. It is our belief that this will not change until some sort of trust mechanism exists that ensures the identity of incoming callers have been verified by some widely-recognized authority.

Traditional PSTN Trunks

Note

This section has been written as a nod to the telecommunications industry, and to the history of Asterisk itself. It is in part because Asterisk could talk to so many different sorts of old-school circuits that it achieved the early success it did. These days, the use of these old circuits has for the most part faded into history.

There are two types of fundamental technology that PSTN carriers have used to deliver telephone circuits: analog and digital.

Analog telephony

The first telephone networks were all analog. The audio signal that you generated with your voice was used to generate an electrical signal that was carried to the other end. The electrical signal had the same characteristics as the sound being produced.

Analog circuits have several characteristics that differentiate them from other circuits you might wish to connect to Asterisk:

  • No signaling channel exists—line state signaling is electromechanical, and addressing is done using in-band audio tones.

  • Disconnect supervision is usually delayed by several seconds, and is not completely reliable.

  • Far-end supervision is minimal (for example, answer supervision is lacking).

  • Differences in circuits means that audio characteristics will vary from circuit to circuit and will require tuning.

Incoming analog circuits that you wish to connect to your Asterisk system will need to connect to a Foreign eXchange Office (FXO) port. Since there is no such thing as an FXO port in any standard computer, an FXO port of some sort must be provided to the system before you can connect traditional analog lines. Companies such as Digium and Sangoma offer such cards, but you can also purchase a SIP device that provides such ports.

We do not recommend the use of analog trunks in an Asterisk system. Their configuration and use is outside of the scope of this book4.

Digital telephony

Digital telephony was developed in order to overcome many of the limitations of analog. Some of the benefits of digital circuits include:

  • No loss of amplitude over long distances

  • Reduced noise on circuits (especially long-distance circuits)

  • Ability to carry more than one call per physical circuit

  • Faster call setup and tear-down

  • Richer signaling information (especially if using ISDN)

  • Lower cost for carriers

  • Lower cost for customers (at higher densities)

There were several fundamental digital circuits that gained wide acceptance in the telecommunications industry:

T1 (24 channels)

Used in Canada and the United States (mostly for ISDN-PRI)5

E1 (32 channels)

Used in the rest of the world (ISDN-PRI or MFC/R2)

BRI (2 channels)

Used for ISDN-BRI circuits (Euro-ISDN)

Note that the physical circuit can be further defined by the protocol running on the circuit. For example, a T1 could be used for either ISDN-PRI or CAS, and an E1 could be used for ISDN-PRI, CAS, or MFC/R2.

It is difficult to justify these circuit types anymore. Relative to VoIP protocols, they have become expensive, complex, and somewhat inflexible. If you need to connect such circuits to an Asterisk system, we recommend some sort of gateway device to convert the circuit into SIP, and then connect via SIP to your Asterisk system. If you want a single-chassis system, companies such as Digium and Sangoma offer digital PSTN cards that can be installed directly into your Asterisk server; they are connected to Asterisk by way of the DAHDI channel driver. The use of this technology is outside of the scope of this book6.

VoIP

Compared to the lengthy history of the telecommunications industry7, VoIP is still a relatively new concept. For the century or so prior to VoIP, the only way to connect your site to the PSTN was through the use of circuits provided for that purpose by your local telephone company. VoIP now allows for connections between endpoints without the PSTN having to be involved at all (although in most VoIP scenarios, there will still be a PSTN component at some point, especially if there is a traditional E.164 phone number involved). The PSTN still controls the phone numbers, and we’ll be using those until somebody comes up with an internet-based addressing mechanism that is not subject to abuse the way email has been8.

Coping with Network Address Translation

If you are going to be using VoIP across any sort of wide-area network (such as the Internet), you will be dealing with firewalls, and quite frequently network address translation (NAT) as well.9 A basic understanding of how the SIP and RTP protocols work together to create a VoIP call can be helpful in understanding and debugging functional problems (such as the very common “one-way audio” issue, which NAT configuration issues will often create). NAT allows a single external IP address to be shared by multiple devices behind a router. Since NAT is typically handled in the firewall, it also forms part of the security layer between a private network and the Internet.

A VoIP call using SIP doesn’t consist just of the signaling messages to set up the call (the SIP part of the connection). It also requires the RTP streams (the media), which carry the actual audio connection,10 as shown in Figure 7-1.

Figure 7-1. SIP and RTP

The use of separate protocols to carry the audio is what can make NAT traversal troublesome for VoIP connections, especially if the remote phones are behind one NAT, and the PBX is behind a different NAT. The problem is caused by the fact that while the SIP signaling will typically be allowed to pass through the firewalls at both ends, the RTP streams may not be recognized as part of the SIP session taking place, and thus will be ignored or blocked, as shown in Figure 7-2. The effect of one or both of the RTP streams being blocked is that users will complain that they are seeing their calls happen, and can answer them, but cannot hear (or cannot be heard).

Figure 7-2. RTP blocked by firewall

In this section we will discuss some of the methods you may employ to alleviate issues caused by NAT. There are two different scenarios that need to be considered; each requiring you to define parameters within the sip.conf file. As long as you understand which scenario you are dealing with,11 most NAT issues become a thing of the past.

Devices behind NAT

First, let’s deal with devices behind a remote NAT connecting to your Asterisk box, as shown in Figure 7-3.

Figure 7-3. Remote devices behind NAT

When a device attempts to initiate a session, it will construct a SIP message that contains its IP address and some additional information. When Asterisk sees this information, it uses it to determine where to respond to. Since the device is behind NAT, the SIP message will have a reply address that is not routable across the internet (e.g., 192.168.1.104). However, we can tell Asterisk to ignore this SIP message address, and instead use what is supplied by the network stack. We enable this via the nat option in sip.conf. Table 7-1 lists the arguments we can set with the nat option.

Table 7-1. Arguments available to nat in sip.conf
ArgumentDescription
noPerform no special NAT handling other than what is specified in RFC 3581.
force_rportEven if no rport parameter was specified, act as if there had been.
comediaSend media back to the port it was received from and ignore the requested port in the SDP header.
auto_force_rportIf Asterisk can determine that the device is behind NAT, set the force_rport option. This is the default.
auto_comediaIf Asterisk can determine that the device is behind NAT, set the comedia option.

RFC 3581 allows a device to use the rport parameter to signal to the far end that it should respond to the source IP and port the request originated from, rather than using the address supplied in the SIP header. Supplying the rport parameter can happen when the device knows it is behind a NAT and can’t write the information that would be required to communicate bidirectionally in the SIP header. Asterisk will always honor the rport parameter if it is supplied, but since this isn’t as common as one would like, we can force Asterisk to assume that the device would have supplied an rport parameter if it had known better. By doing this, we instruct Asterisk to always respond to the source IP and port from which it received the request. If no nat setting is explicitly defined, Asterisk will default to auto_force_rport as the nat parameter setting. You can force this behavior by setting nat=force_rport.

The comedia (connection-oriented media) option can be used to instruct Asterisk to send media (RTP) to the address and port that the far-end media came from. This is used when a device is behind NAT and can’t tell Asterisk the correct location to send media to.

You can also specify multiple options to the nat setting by separating arguments with a comma. For example, it is common to set both force_rport and comedia as the NAT handling method (which is what we recommend you start with):

nat=force_rport,comedia
Warning

It is important to note that if the nat setting in the general section differs from that in the peer section, it then becomes possible to discover valid peers on the system. This is a security issue, and it is highly recommended that you only set the values for nat in the general section. The discovery of peers is done by performing a scan of the system, and those peers with different nat settings will respond differently, thereby allowing a potential attacker to discover which peers are valid on the system.

Another trick when dealing with devices behind NAT is to enable the qualify option. In many NAT systems, if a dialog isn’t maintained periodically, then the device providing the NAT may close the connection. By using qualify, Asterisk will send a request to the far end, which should then be responded to. By default, if you use qualify=yes on a peer, then the time for these transactions is every 2,000 milliseconds (2 seconds). You can also specify the time in milliseconds instead of using yes:

qualifyfreq=60 ; probe far end peer every 60 seconds
qualify=120000  ; allow 10 seconds for a reply (qualify)

Asterisk behind NAT

The second scenario is that Asterisk is behind NAT, as illustrated in Figure 7-4.

Figure 7-4. Asterisk behind NAT

In this case, we have a couple of ways to write the SIP headers in a manner friendly to the other end.

There are two primary options when Asterisk is behind NAT: externip and externhost. Use of these options is a one-or-the-other decision, since they effectively perform the same functionality: compose the SIP header using the external interface address. Since our Asterisk box will have a nonroutable IP address across the Internet (we’re behind NAT), we can tell Asterisk what its external routable address is, so that we can place that in the headers of our SIP message.

If our external IP address was something like 98.139.183.24, we could set externip like so:

externip=98.139.183.24

We can also specify the port number that should be responded to:

externip=98.139.183.24:9999

If no port number is provided, then the port number specified with the udpbindaddr option will be used.

Alternatively, you can use the externhost option, which is similar to the externip, but the IP address will be resolved whenever chan_sip.so is loaded into memory (or on subsequent reloads).13 The format is similar to externip except you use a hostname. You can also specify a port number. For example:

externhost=pbx.shifteight.org:9999

If you want the external hostname to be refreshed periodically, you can use the externrefresh option. The value specified is in seconds:

externhost=pbx.shifteight.org:5060
externrefresh=300

If you have deployed your Asterisk server behind NAT, it is likely that you will also have local telephone sets attached to it. We don’t want to mangle the headers of SIP messages we’re sending to our local sets, so we can specify which IP addresses are considered part of our local network. That way Asterisk will respond simply with the headers as they would be on an internal network. We use the localnet option to specify which networks are considered local to our Asterisk system.

Note

It’s also important to set the localnet parameter even if no local devices will be communicating with Asterisk, as the Asterisk system itself is part of the local network. Using the localnet option in combination with externip or externhost will help Asterisk understand what network addresses to look for in the SIP headers in order to rewrite.

The localnet option takes the format of an IP address and subnet mask. You can either use CIDR notation or dotted notation. Multiple entries are permitted:

externip=98.139.183.24
localnet=172.16.0.0/24
localnet=192.168.100.0/255.255.255.0

Media (RTP) handling

In this section we’ll explore how Asterisk handles media and outline some options available to you. If you have a simple network topology where your Asterisk box is connected directly to the PSTN via traditional hardware (analog or digital connections) and your peers are all on the same LAN as Asterisk, the default configuration is likely fine and you can move on to the next section. If you’re connecting to an Internet telephony service provider (ITSP) via SIP, you may want to start with setting directmedia=no in your sip.conf file. Unless you have a reason to direct media away from your Asterisk box, then use of directmedia=no typically makes the configuration a little easier to deal with:

  • Asterisk will always use the symmetric RTP mode as defined in RFC 4961,14 which means Asterisk will always send packets from the same port that it initially received the media on. The text in RFC 4961 is quite short and is a useful read about how Asterisk will handle the RTP media between endpoints. This knowledge should simplify your network design efforts should you expect to handle peers outside of your LAN environment at any point in the future.

  • If you need to override the IP address used for media, you can do that with the media_address option. This option will allow you to ignore the media address supplied in the SDP15 headers and direct the media somewhere else. Using the media_address option cannot be set per peer: it is a general (global) option only.

  • By default Asterisk will attempt to re-INVITE the media between the endpoints directly. The redirecting of the media happens when Asterisk determines it doesn’t need to stay in the media path. (Times when Asterisk needs to be in the media path include call recording and listening for DTMF.) When Asterisk is on the outside of a network where the endpoints are behind a NAT, redirecting of the media doesn’t work very well (or at all). In this case you should use the directmedia=no option to prevent redirection of the media.

    The default setting is directmedia=yes, so if you have endpoints behind a NAT that Asterisk is not a part of, you should set the option to directmedia=no.

    Note

    Changing the directmedia option only affects the re-INVITE of media streams, and not other instances of re-INVITE, such as during T.38 negotiation.

    There does exist an option that allows Asterisk to redirect media between endpoints on the same network as Asterisk, at least as best determined by the RTP core. Enabling redirection of media on the local LAN can be done with directmedia=nonat. If you want to perform an UPDATE instead of a re-INVITE when redirecting the media, you can do that with directmedia=update. If you combine update with nonat (e.g., directmedia=nonat,update), then you effectively are performing a directmedia=yes.

    If you have a peer that you know is itself going to send Asterisk a re-INVITE upon an incoming call, you can set directmedia=outgoing in order to instruct Asterisk to not bother attempting a re-INVITE for media from this peer (since the far end is expected to attempt it). Setting this option can help avoid glare situations, where both ends simultaneously attempt to redirect the media after initial call setup (see Figures 7-5 and 7-6).

    Figure 7-5. RTP without re-INVITE
    Figure 7-6. RTP with re-INVITE

    The SIP protocol was designed to enable endpoints to negotiate media capabilities and subsequently make direct connections to each other. The concept was that servers would not need to handle the media load for clients that had the capability to exchange media directly with each other (such as two telephones engaged in a phone call). However, due to the challenges inherent in NAT-enabled firewalls and other complex network topologies, coupled with the incredible processing power of modern servers, it is often simpler to always pass all media through the server, rather than deal with the complexity of sorting out re-INVITE issues across all sorts of different networks and topologies.

  • Asterisk can also attempt to set up media directly between peers without a re-INVITE by enabling directrtpsetup=yes. Usage of directrtpmedia comes with some caveats, though; it is considered experimental, and it will not work for video or cases where the callee sends RTP payloads and fmtp headers in the 200 OK that don’t match the caller’s INVITE. Additionally, this option can’t be used when the peers are behind NAT.

  • You can control which endpoints can attempt to send directmedia to each other with directmediadeny and directmediapermit. This is useful in situations where your networking topology doesn’t allow certain networks to pass media to each other, instead requiring the media to flow through Asterisk. An example of the usage would be to deny all media flowing between networks, then explicitly permit certain networks to send directmedia:

    directmediadeny=0.0.0.0/0
    directmediapermit=192.168.101.0/24
    directmediapermit=172.16.1.0/24

As you can see, there are several options that allow you to control how media is handled by Asterisk. This flexibility is what makes Asterisk so compelling to use in so many networks. WIth the right set of options (and lots of patience), you should be able to handle traversing almost any networking obstacle.

PSTN Termination and Origination

Passing calls between a VoIP environment and the PSTN requires some sort of gateway to convert the VoIP (typically SIP) signaling into something compatible with PSTN protocols. These processes are referred to as Origination and Termination.

The raw terms ‘Origination’ and ‘Termination’ often cause confusion for people as to which is which. For us, it’s useful to remember that since the PSTN was already there when VoIP came along, the terms evolved in relation to it. Ideally, the terms should probably be stated as ‘PSTN Origination', and ‘PSTN Termination', and we encourage you to remember them that way16.

PSTN Termination

Until VoIP totally replaces the PSTN, there will be a need to connect calls from VoIP networks to the public telephone network. This process is referred to as termination.

Figure 7-8. PSTN Termination

Although you can engineer an Asterisk system to act as a termination gateway (using some sort of PSTN interfaces), in practice you’re more likely to use an Internet Telephony Service Provider (ITSP, also sometimes called VoIP carrier) to terminate your phone calls. ITSPs typically have a massive investment in infrastructure, and you’d be hard-pressed to do better without spending a ton of money. ITSPs have made Termination inexpensive, so it’s tough to make a business case for doing it yourself.

In order to send your calls to an ITSP, your dialplan needs to look something like this:

; NANP-based systems
[to-pstn] ; Yes, we're going through an ITSP, but the PSTN is our destination
exten => _1NXXNXXXXXX.,1,Dial(${TOLL}/${EXTEN})  ; Country code plus phone number

; Add a '1' and send
exten => _NXXNXXXXXX.,1,Dial(${LOCAL}/1${EXTEN}) ; Country code plus phone number 

; Strip off the '011' and send
exten => _011X.,1,Dial(${TOLL}/${EXTEN:3})       ; Country code plus phone number

; Emergency dialing
exten => 911,1,Dial(${LOCAL}/911) ; You will need your carrier to tell you how to configure emergency dialing
; Most of the rest of the world
[to-pstn]
; Strip off NDD prefix, add country code, and send 
exten => _0X.,1,Dial(${TOLL}/<add your country code here>${EXTEN:1})  ; Country code plus phone number

; Strip off IDD prefix and send 
exten => _00X,1,Dial(${LOCAL}/${EXTEN:2}) ; Country code plus phone number 

; Emergency dialing (and other services)
exten => 11X,1,Dial(${LOCAL}/${EXTEN}) ; You will need your carrier to tell you how to configure emergency dialing

Warning

Given that most PSTN circuits will allow you to dial any number, anywhere in the world, and given that you will be expected to pay for all incurred charges, we cannot stress enough the importance of security on any gateway machine that is providing PSTN termination. Criminals put a lot of effort into cracking phone systems (especially poorly secured Asterisk systems), and if you do not pay careful attention to all aspects of security, you will be the victim of toll fraud. It’s only a matter of time.

Do not allow any unsecured VoIP connections into any context that contains PSTN termination.

Termination will tend to be more complex than we’ve outlined here—even if you’re using an ITSP as your carrier—but the basic concept is fairly straightforward: Match a pattern that your users might dial, prepare it for the carrier by removing or adding necessary digits, and send the call out the appropriate PSJIP endpoint (trunk). We’ve only discussed the dialplan here; in a later section we’ll discuss how to configure the SIP trunks to carry this traffic.

PSTN Origination

You might also want to be able to accept calls from the PSTN into your VoIP network. The process of doing this is commonly referred to as origination. This simply means that the call originated in the PSTN.

Figure 7-9. PSTN Origination

In order to provide origination, a phone number is required.

In the good old days, when VoIP and Asterisk were new, it was quite common for people to handle the circuit connection to the PSTN themselves, using analog or digital trunks provided by the local phone company. For the most part this type of connection is now handled by ITSPs, and you simply need to connect your system to your VoIP carrier across a SIP trunk.

Phone numbers—when used for the purpose of origination—are commonly called DIDs (Direct Inward Dialing numbers). Your carrier will send a call down the circuit to your system, and pass the DID, (or special received digits in some cases18), which the Asterisk dialplan will interpret. In other words, you will need a dialplan context that accepts incoming calls from your carrier, with extensions or patterns that will correlate to your DIDs.

In order to accept a call from a VoIP circuit, you will need to handle the digits the carrier will send you (the DID or phone number). The DNIS number and the DID do not have to match, but typically they will. In days gone by, the carrier would usually ask you in what format you wish to receive the digits. Nowadays, a VoIP carrier will typically tell you what format they will send, and you are expected to accommodate. Two common formats are: DNIS (which is essentially the digits of the DID that was called), or E.164, which means that they’ll be including the country code with the number.

In the dialplan, you associate the incoming circuit with a context that will know how to handle the incoming digits. As an example, it could look something like this:

[from-pstn] 

exten => 4165550100,1,Goto(sets,100,1)
exten => 4165550101,1,Goto(sets,101,1)
exten => 4165550102,1,Goto(sets,102,1)
exten => 4165550103,1,Goto(sets,103,1)
exten => 4165554321,1,Goto(main-menu,${EXTEN},1)
exten => 4165559876,1,VoiceMailMain() ; a handy back door for listening
                                      ; to voice messages

exten => i,1,Verbose(2,Incoming call to invalid number)

In the number-mapping context, you explicitly list all of the DIDs that you expect to handle, plus an invalid handler for any DIDs that are not listed (you could send invalid numbers to reception, or to an automated attendant, or to some context that plays an invalid prompt).

Now, we’re ready to discuss how to configure trunks to carry your external traffic.

Configuring SIP Trunks

SIP is far and away the most popular of the VoIP protocols—so much so that the terms VoIP and SIP have almost come to mean the same thing. In previous editions of this book, we’ve looked at some of the other protocols that were popular at the time (primarily IAX2 and H.323), however for this edition there’s no real reason anymore to discuss anything but SIP. The channel drivers for those older protocols are still available in Asterisk, but they’re no longer supported.

The SIP protocol is peer-to-peer and does not really have a formal trunk specification. This means that whether you are connecting a single phone to your server or connecting two servers together, the SIP connections will be similar. Having said that, there are some differences in the style of how these resources can be configured, and there will definitely be a difference in how your dialplan handles routing across trunks.

Connecting an Asterisk system to a SIP provider

It is quite common to use the same ITSP carrier for Termination and Origination, but be aware that the two processes are unrelated to each other. If calls going in one direction pass your testing, that doesn’t mean calls in the other direction are OK. If you change configuration, test routing both in and out, every time.

Many carriers will provide sample configurations for Asterisk. Unfortunately, these documents generally refer to the older chan_sip driver, which has been deprecated. Digium has designed a PJSIP wizard which is intended to greatly simplify carrier configuration. You can still configure ITSP trunks using the exact same methods we’ve shown before for configuring other endpoints (creating records in ps_endpoint, ps_aor, ps_auth, and so forth), but rather than hash over all that again, we are going to take a look at the wizard, since it consolidates several components into a single configuration file. We have found that since user endpoints change often, and carrier endpoints seldom do, it’s often useful to configure carriers in a configuration file rather than in the database.

Before any config can be created, however, it’s important to determine how the carrier will interact with your system. There are two fundamental models we have seen:

  1. Password-based authentication, including registration19. This is common in smaller carriers focused on the small business market. This is also the type of service you would get if you were simply registering a SIP phone directly to a service.

  2. IP-based authentication. No password; no registration. This is more common with carriers that provide bulk trunking services to larger enterprises and resellers. (typically these will also come with some sort of minimum commitment in terms of volume). You will be expected to have solid SIP and networking skills.

These are not hard-and-fast rules, but they are the most common in our experience.

So, there are two ways we might configure an ITSP in the /etc/asterisk/pjsip_wizard.conf file:

If the carrier uses an IP address-based authentication, they will expect you to send your traffic from a static IP address (and should your address change, you will need to inform them so they can reconfigure their equipment). Your pjsip_wizard.conf file could then look something like this:

; ITSP uses IP address-based authentication
[itsp-no-auth]
type=wizard
remote_hosts=itsp.example.com
endpoint/context=pstn-in 
endpoint/allow = !all,ulaw,g722
sends_registrations=no
accepts_registrations=no
sends_auth=no
accepts_auth=no

Alternatively, if your IP address changes frequently (or your carrier requires this method), you can have your system register to the carrier (which will require you to send authentication credentials to prove it’s really you). Your calls will typically also be required to authenticate:

[itsp-with-auth]
type=wizard
remote_hosts=itsp.example.com
endpoint/context=pstn-in
endpoint/allow = !all,ulaw,g722
sends_registration=yes
accepts_registrations=no
sends_auth=yes
accepts_auth=no
outbound_auth/username=itsp_provided_username
outbound_auth/password= itsp_provided_password

Note that the names [itsp-no-auth] and [itsp-auth] have no built-in meaning to Asterisk. They become the PJSIP channel names to which you send your calls.

Configure Trunks For Termination

The PJSIP wizard has created the channel definitions we require for our carrier. To send a call, we only need to make a minor change to the [globals] section of our extensions.conf file, as follows:

[globals]
UserA_DeskPhone=PJSIP/0000f30A0A01
UserA_SoftPhone=PJSIP/SOFTPHONE_A
UserB_DeskPhone=PJSIP/0000f30B0B02
UserB_SoftPhone=PJSIP/SOFTPHONE_B

TOLL=PJSIP/itsp-no-auth
LOCAL=${TOLL}
;OR
;TOLL=PJSIP/itsp-with-auth
;LOCAL=${TOLL}

Configuring Trunks For Origination

For your incoming calls, you’ll need a context in your /etc/asterisk/extensions.conf file that matches the context specified for the ITSP channel. Let’s assume we have two NANP DIDs 4169671111 and 4167363636, and place the required code above the [sets] context:

TOLL=PJSIP/itsp-no-auth
LOCAL=${TOLL}
;OR
;TOLL=PJSIP/itsp-with-auth
;LOCAL=${TOLL}

[pstn-in]
exten => 4169671111,1,Dial(sets,100,1)
exten => 4167363636,1,Dial(sets,101,1)

[sets]
exten => 100,1,Dial(${UserA_DeskPhone})

In a small system, this is fairly easy to administer. In a larger system, you’d want to put the DIDs into a table in your database, and have the dialplan look up the required target. We’ll be diving into databases a bit more later in the book20.

That’s the gist of it as far as carrier interconnection is concerned. It can seem very complicated to set this up because there are a lot of options, but at a high level it’s fairly straightforward. Problems are usually found to be minor configuration mismatches. Be methodical, and please please please be paranoid about security!

Emergency Dialing

In North America, people are used to being able to dial 911 in order to reach emergency services. Outside of North America, well-known emergency numbers are 112 and 999. If you make your Asterisk system available to people, you are obligated (in many cases regulated) to ensure that calls can be made to emergency services from any telephone connected to the system (even from phones that otherwise are restricted from making calls).

One of the essential pieces of information the emergency response organization needs to know is where the emergency is (i.e., where to send the fire trucks). In a traditional PSTN trunk, this information is already known by the carrier and is subsequently passed along to whatever local authority handles this tasks (in Canada and the US, these are called Public Safety Answering Points (PSAP). With VoIP circuits things can get a bit more complicated, by virtue of the fact that VoIP circuits are not physically tied to any geographical location.

You need to ensure that your system will properly handle emergency calls from any phone connected to it, and you need to communicate what is available, to your users. As an example, if you allow users to register to the system from softphones on their laptops, what happens if they are in a hotel room in another country, and somebody dials 911?21

The dialplan for handling emergency calls does not need to be complicated. In fact, it’s far better to keep it simple. People are often tempted to implement all sorts of fancy functionality in the emergency services portions of their dialplans, but if a bug in one of your fancy features causes an emergency call to fail, lives could be at risk. This is no place for playing around. The [emergency-services] section of your dialplan might look something like this:

[emergency-services]
exten => 911,1,Goto(dialpsap,1)
exten => 9911,1,Goto(dialpsap,1) ; some people will dial '9' because 
                                 ; they're used to doing that from the PBX
exten => 999,1,Goto(dialpsap,1)
exten => 112,1,Goto(dialpsap,1)

exten => dialpsap,1,Verbose(1,Call initiated to PSAP!)
    same => n,Dial(${LOCAL}/911) ; REPLACE 911 HERE WITH WHATEVER 
                                 ; IS APPROPRIATE TO YOUR AREA

[internal]
include => emergency-services   ; you have to have this in any context 
                                ; that has users in it

In contexts where you know the users are not on-site (for example, remote users with their laptops), something like this might be best instead:

[no-emergency-services]
exten => 911,1,Goto(nopsap,1)
exten => 9911,1,Goto(nopsap,1) ; for people who dial '9' before external calls
exten => 999,1,Goto(nopsap,1)
exten => 112,1,Goto(nopsap,1)

exten => nopsap,1,Verbose(1,Call initiated to PSAP!) 
    same => n,Playback(no-emerg-service) ; you'll need to record this prompt

[remote-users]
include => no-emergency-services

In North America, regulations have obligated many VoIP carriers to offer what is popularly known as E911.22 When you sign up for their services, they will require address information for each DID that you wish to associate with outgoing calls. This address information will then be sent to the PSAP appropriate to that address, and your emergency calls should be handled the same way they would be if they were dialed on a traditional PSTN circuit.

The bottom line is that you need to make sure that the phone system you create handles emergency calls in accordance with local regulations and user expectations.

Conclusion

Eventually, it is generally predicted that the PSTN will disappear entirely. Before that happens, however, a distributed mechanism that is widely used and trusted will be needed to allow organizations and individuals to publish addressing information so they can be found. Any voice technology that does not use the PSTN is currently either a walled-garden proprietary product, or is the playground of spammers and criminals. We suspect the PSTN may be around for a while yet, and if so, then origination and termination will need to be part of your Asterisk system.

1 In a key system, each line has a corresponding button on each telephone, and lines are accessed by pressing the desired line key.

2 You can name these anything you wish.

3 For more information on pattern matches, see Chapter 6.

4 We should note, however, that we’ve written extensively on the subject in the past, and that body of work has been released under Creative Commons licencing, and is freely available.

5 There’s also a circuit used in Japan called a J-1, which is most simply described as a 24-channel E1.

6 We would again like to note that we’ve written extensively about digital circuits and DAHDI in previous editions, and that body of work has been released under Creative Commons licencing, and is freely available. Also, Digium and Sangoma provide detailed instructions on how to install and configure their PSTN cards. If you are looking to deploy this technology, please enlist the services of a professional technical resource. This stuff is complex and nuanced, and is not something you’re going to enjoy playing with if you haven’t had some sort of previous experience. It is not necessary to learning or understanding Asterisk.

7 When we say “lengthy” we mean that in relation to other electronic technologies.

8 Just try to imagine if your telephone number could be spammed the way your email address is. The fact that the PSTN is regulated, costs money to use, and controls the telephone numbers, has served to limit the plague of spam that email has suffered.

9 The Wikipedia page on network address translation is actually quite good. For more information about different types of NAT, and how NAT operates in general, check it out!

10 SIP is not the only protocol to use RTP to carry media streams.

11 Yes, you could have both scenarios in effect at the same time, which is popularly termed a “double-NAT.”

12 Whether it is the best solution is something we have yet to debate.

13 The reason we highlight this fact is that if you do not have a reliable DNS service, you will experience all manner of unpleasant behavior in Asterisk, as it patiently waits for hostnames to resolve while you’re impatiently waiting for the SIP channel driver to start working (DNS resolution problems can cause all sorts of strange behavior in Asterisk).

14 http://www.ietf.org/rfc/rfc4961.txt

15 Session Description Protocol—a component of the SIP messaging that defines the media parameters.

16 and perhaps even use them that way in conversation, since many people are confused by these terms, and few will admit it when you’re talking to them.

17 Trust us, Jim Van Meggelen worked with this stuff for many years before getting into VoIP.

18 In traditional PBXs, the purpose of DIDs was to allow connection directly to an extension in the office. Many PBXs could not support concepts such as number translation or flexible digit lengths, and thus the carrier had to pass the extension number, rather than the number that was dialed (which was also referred to as the DNIS number, from Directory Number Information Service). For example, the phone number 416-555-1234 might have been mapped to extension 100, and thus the carrier would have sent the digits 100 to the PBX instead of the DNIS of 4165551234. If you ever replace an old PBX with an Asterisk system, you may find this translation in place, and you’ll need to obtain a list of mappings between the numbers that the caller dials and the numbers that are sent to the PBX. It was also common to see the carrier only pass the last four digits of the DNIS number, which the PBX then translates into an internal number. With VoIP trunks this will seldom be the case, but be aware that it is possible.

19 Remember that registration is simply a mechanism whereby a SIP endpoint tells a registrar server where it is located. This is useful if your IP address changes, as might be the case on a consumer or small-business type of internet connection (such as DSL or cable).

20 A table to handle this would simply need a field for the DID, and three more for the target context, extension and priority).

21 Don’t assume this can’t happen. When somebody calls 911, it’s because they have an emergency, and it’s not safe to assume that they’re going to be in a rational state of mind. A recording that tells your softphone users what address the system is going to be sending to the PSAP, may clue them in to the fact that the fire trucks aren’t going to be sent to where they’re needed. (“This telephone is registered to our Toronto system. Emergency services will be sent to our office at 301 Front St W. Press 1 to proceed with this call.”).

22 It’s not actually the carrier that’s offering this; rather it’s a capability of the PSAP. E911 is also used on PSTN trunks, but since that happens without any involvement on your part (the PSTN carriers handle the paperwork for you), you are generally not aware that you have E911 on your local lines.