Set up your own PBX with Asterisk

Introduction

Important: To log stuff to the console, either use Verbose(), or use NoOp()
but the latter will only work if you set "verbosity" to at least 3
(in the console, type "set verbose 3").

Why choose Asterisk to build a PBX over other open-source solutions?

"There are several SIP implementations that are OSS, but they are primarily
what are known as "call proxies" instead of more full-featured PBX
applications. This means that they function only to connect two endpoints together,
and are basically just large, fast, directory servers. Examples of SIP Proxies
are ser and Vocal."

Is Asterisk the only PBX that can rewrite CID name on the fly? Check
Freeswitch

Which environment to choose?

Install a bare Linux distribution that supports RPM or other packagers, and install the
required components through this package in binary form. Red Hat RPM packages for Asterisk and the driver
modules can be obtained from http://www.macvoip.com or from http://www.n2net.net

"Engineered by Digium in conjunction with rPath, Pound
Key includes all the Linux components necessary to run, debug and build
Asterisk, and only those components. You no longer have to worry about kernel
versions and package dependencies. Unlike other Linux distributions used to
deploy Asterisk, no unnecessary components that might compromise security or
performance are included." AstLinux
is also a bundled version of Linux and Asterisk, but optimized for small
format hardware platforms

(Important: You might want to take
a deep look at whether you want to use a commercial Asterisk) Use the TrixBox distribution (previously
Asterisk@Home) that aims to do the same thing as Pound Key. Ideal for newbies,
but requires a second host since, on purpose, it must be managed through
a web interface but doesn't have X (Lynx could do the job, I guess). I don't
like A@H because it hides the internals (hence, not a good tool to learn
how Asterisk works), and installs a lot of stuff that is probably useless
for a home solution (SugarCRM, etc.)

How to connect Asterisk to the POTS/PSTN (ie. regular, analog phone line)

There are two solutions:

A stand-alone PSTN gateway like the Linksys 3102 or the Minitar
MVA11A

Which branch to use?

As of Feb 2012, four branches are available: 1.4, 1.6, 1.8, and 10. I don't
know of a good source to know what the major changes are in each branch and
make an informed choice before upgrading, but some information are available
in UPGRADE*.txt files in tarballs
along with the CHANGES
file.

vi /etc/modprobe.d/dahdi.conf ("You should place any module parameters
for your DAHDI modules here")

options wctdm opermode=FRANCE

(optional) vi /etc/modprobe.d/blacklist ("blacklist all the drivers
by default in order to ensure that /etc/init.d/dahdi installs them in the
correct order so that the spans are ordered consistently.")

Comment out modules you do NOT want to blacklist

Add "blacklist netjet"

Reboot to get rid of the NetJet module that is loaded instead of the
Wctdm module, and run "lsmod | grep -i netjet" to check that netjet/ISDN are gone

By default, Asterisk loads a lot of stuff, and must be told explicitely not
to load them through /etc/asterisk/modules.conf, using eg. noload => pbx_ael.so.
Modules usually live under /usr/lib/asterisk/modules/.

IAX accounts

Compiling Asterisk for Windows

Download Asterisk source (I used 1.4.x) and unzip it using tar (You
may need to install tar manually as it is missing in some Cygwin default
installations. Don't use windows unzip for as it will create some abnormal
character in source and will make unexpected compile time errors)

Run bootstrap it will report any missing or lower version libs, prerequisite
or tools

You manually need to download and compile termcap, ncurses

Run configure

Make menuselect and disable all non-required modules as it will save
to resolve lot of not needed dependencies

Run make

Resolve any missing reported by make

After successful make run make install

Once make install okey you can run asterisk on Cygwin console and also
directly run by double clicking on asterisk.exe in c:/Cygwin/usr/sbin/.

Once you have compiled it you can copy asterisk.exe to any other system not
having Cygwin installed but you have to care about following:

You must have to create required directories structure like Cygwin on
system drive.

You must need to copy required Cygwin DLLs to new systems \windows\system32\
folder. You can identify required DLLs by trying to run asterisk.exe and
it will report missing DLLs one by one.

I did just for my experiment and fun and was able to make successful SIP
calls using static files configuration. However I suggest to use SIPx, Yate
or FreeSWITCH if you want to stick with windows as that have native windows
ports and have all required features you need in a PABX or VoIP switch.

One more thing previously there was a project named as AstWin which was maintaining
asterisk's port to windows and providing an installable package of Asterisk
for windows. I am not aware about current state of project but, I have
installation package of Asterisk for windows version 1.2. If anyone need it
contact me direct at email imfanee@gmail.com I will send the software as attachment.

Tips to compile Asterisk

Since Asterisk is often updated, packages found on the Net are usually a
bit stale, and it's better to learn how to compile it yourself. Here are some
tips I gathered:

Set a hostname, eg. "sip" or "sip.acme.com" (but
make sure it can actually be resolved)

Zaptel is only needed if you have a PCI Analog card, ie. to connect
the PC to an analog telephone line through an FXO port

Check that your motherboard supports at least PCI 2.2, and that it lets
you assign an IRQ to a given PCI slot. These cards generate huge amounts
of interrupts during use, and any conflict with other devices will result
in jittery voice and overall poor performance (Why
is my card getting an IRQ miss?)

Look in /proc/interrupts to ensure
that wcfxo has an IRQ all to itself. If it is sharing an IRQ, move the card
to a different PCI slot and see if that resolves the conflict. Read Asterisk PCI bus Troubleshooting

Once the board is installed, boot up, and run "dmesg" and
"lspci -v" to check that Linux detected it

The Zapata channel module, chan_zap.so, is used by to communicate with
the Linux kernel, where the drivers for the hardware are loaded. The Zaptel
interface is a kernel loadable module that presents an abstraction layer between
the hardware drivers (eg. wctdm, wcfxo) and the Zapata module in Asterisk (ie.
chan_zap.so -> Zaptel module /dev/zap -> wcfxo -> FXO card.) While Asterisk
itself compiles on a variety of platforms, the Zaptel drivers are Linux-specific
— they
are written to interface directly with the Linux kernel

Newer distros rely on devfs and the udev daemon to create device nodes
dynamically. If yours uses those tools, check its documentation on how to
add Zaptel (eg. editing /etc/udev/rules.d/50-udev.rules)

cat /proc/zaptel/*

ztcfg reads /etc/zaptel.conf to configure channel(s)

to load zaptel, you just need to edit zaptel.conf, load wcfxo, and run ztcfg
: modprobe wcfxo ; ztcfg -vv

wcfxo and zaptel modules: The order of execution of these commands is important, because voice channels
are numbered in the same order their interface cards are enabled. For instance,
if you had two
X100P cards installed or a TDM400P with two FXO modules, you would have two
logical voice channels. To check that those two modules were loaded successfully,
run "lsmod | grep (zaptel|wcfxo)" (or wctdm instead of wcfxo).

"One other package you may want to install is asterisk-sounds. While
Asterisk comes with many sound prompts in the main source distribution, the
asterisk-sounds package will give you even more. If you would like to expand
the number of professionally recorded prompts for use with your Asterisk system,
this package is essential."

The asterisk-addons package contains code to allow the storage of Call Detail
Records (CDRs) to a MySQL database and to natively play MP3s, as well as an
interpreter for loading Perl code into memory for the life of an Asterisk process.
Programs are placed into asterisk-addons when there are licensing issues preventing
them from being implemented directly into the Asterisk source code, or when
they are not yet ready for primetime.

/var/log/asterisk/messages

"zap show channels" in the Asterisk console

Reloading after making changes:

zaptel.conf: run "ztcfg
-vv"zapata.conf: "reload" from the Asterisk console (or use asterisk
-rx "reload" to execute the command directly)sip.conf and iax.conf: "reload chan_sip.so" and "reload
chan_iax2.so" from the Asterisk consoleextensions.conf: "reload" from the Asterisk console

If you have problems
using SIP phones, make sure that your SIP client is using the G.711 codec (either
alaw or ulaw) as that is a codec that is known to work with Asterisk

"The s extension will only be selected when a call enters a context
without a target extension defined. Imagine a ZAP channel (regular phone line),
it rings, asterisk answers but it has no idea what the target extension will
be so it throws it into s. Why doesn't this work with SIP? When a SIP
packet comes in, it has the target extension in the packet so instead of sending
it to s it tries to send the call to the target extension. If the target extension
can't be matched it sends a not found back to the SIP phone, basically telling
you you dialed a wrong number."

In extensions.conf, add NoOp() in context to know where it fails

Optimization can be done through the Zaptel and Asterisk configuration
files (eg. CONFIG_ZAPTEL_MMX is not AMD-friendly, etc.)

Before recompiling Asterisk, remove all files under /usr/lib/asterisk/modules

Adding an FXO card with Zaptel

Insert the PCI card, boot up, and type 'lspci -v' to check that Linux
did detect it (eg. "Communication controller: Tiger Jet Network Inc.
Tiger3XX Modem/ISDN interface"). It should not share an IRQ with another
card

Download the Linux source code and headers for the kernel version you
are currently using (cat /proc/version)

Run zttool:
If an analog line is plugged into the card and the card was configured with
ztcfg, zttool should say OK; Otherwise, it should "Unconfigured"

Recompile and reinstall Asterisk

Edit extensions.conf so that Asterisk knows what to do when a call comes
in from the PSTN on the FXO card (context=my-phones above).

Here's
an example that just plays back what you say in the phone (Note: Must add
other stuff for a complete extensions.conf)

[my-phones]; incoming
calls from the FXO port are directed to this context from zapata.conf;Asterisk's
parser is so brain-dead that you can't use a comma, even with quotes;BAD
exten => s,1,Verbose("Hello, World!")exten
=> s,1,Verbose(Hello World!)

libpri even when not using an ISDN board? "Libpri provides the libraries
required for using Primary Rate ISDN (PRI) trunks, as well as a number of other
telephony interfaces. Even if we do not have a PRI line at this time, it is
a good idea to install it, as it will not create any conflicts. Parts of the
Asterisk code depend on the libraries included in the libpri package. Therefore,
any time we install libpri, we should recompile Asterisk."

If our system is configured to start the Zaptel hardware at boot time, we
can accomplish this by running:

$ /etc/init.d/zaptel stop

$ /etc/init.d/zaptel start

If, however, we elected not to start Zaptel interfaces at boot time, we can
implement our changes as we go by running:

$ ztcfg -vvv

Remember: Changes to the file will not take effect until we have zaptel.confrestarted
the drivers.

Zapata.conf is read by Asterisk. Therefore, to read changes made to this
file, we can issue a reload in the Asterisk console. Zaptel will NOT have to
be restarted to apply any changes we make in zapata.conf.

To test the card, run "zttest -c 10"

NEEDED? Load modules wcfxo (zaptel loaded automagically?)

NEEDED? echo "ztdummy" >> /etc/modules
: "Zaptel "ticks" once per millisecond (1000 times per
second). On each tick every active zaptel channel reads and 8 bytes of data.
Asterisk also uses this for timing, through a zaptel pseudo channel it opens.

However, not all PBX systems are connected to a telephony provider via a
T1 or similar connection. With an analog connection you are not synced to the
other party. And some systems don't have Zaptel hardware at all. Even a digital
card may be used for other uses or is simply not connected to a provider. Zaptel
cards are also capable of providing timing from a clock on card. Cheap x100P
clone cards are sometimes used for that pupose.

If all the above fail, you can use the module ztdummy to provide timing alone
without needing any zaptel hardware. It will work with most systems and kernels.

You can check the zaptel timing source with zttest, which is a small utility
that is included with zaptel. It runs in cycles. In each such cycle it tries
to read 8192 bytes, and sees how long it takes. If zaptel is not loaded or you
don't have the device files, it will fail immedietly. If you lack a timing device
it will hang forever in the first cycle. Eitherwise it will just give you in
each cycle the percent of how close it was. Also try running it with the option
-v for a verbose output."

NEEDED? modprobe ztdummy (modprobe = insmod, rmmod)

Do you actually have any zaptel kernel modules loaded ?

lsmod

how to unload/reload zaptel? rmmod?

ubuntu*CLI> zap show channels

No such command 'zap show' (type 'help' for help)

zap show status

ztmonitor

The main method to configure Zaptel devices is using the utility *ztcfg*.
ztcfg reads data from the configuration file /etc/zaptel.conf , figures out
what configuration to send to channels, and send it.

Asterisk behind a NAT firewall

Since Asterisk (1.8) still doesn't really support STUN, at the very least,
you must open a range of UDP ports on your firewall and forward them to Asterisk
to match RTP ports in rtp.conf.

In addition, if you intend to receive calls other than from a VoIP provider,
you must also forward UDP5060 which is the standard SIP port. The reason you
don't need this to register/receive calls to/from your VoIP provider, is that
in this case, Asterisk is just an SIP client and the use of "qualify"
will keep the port open.

Here's how to configure sip.conf when Asterisk and an XLite client when both are located on a private
LAN and need to make/receive calls from the Internet:

Testing Asterisk and NAT

IP used in REGISTER

When the Asterisk server and the SIP clients are all located on the same
LAN (with non-routable IP's), it appears that SIP clients are smart enough to
send their LAN IP instead of the WAN IP even when set to use STUN when REGISTERing
to the SIP server (Asterisk).

Opening SIP and RTP ports on NAT

Can Asterisk do it? If yes, 1.4, 1.6, 1.8?

Direct media mode and NAT

Can RTP packets flow directly between SIP clients when there are on either
side of the NAT (ie. one in the LAN, one on the Net)? If yes, are some features
lost?

How many ports does RTP need? 1 for RTP and 1 for RTSP?

How to use a port other than UDP 5060 on the router?

To avoid breaking attempts while still allowing remote SIP clients to REGISTER
and remote SIP clients/servers to INVITE: Create SRV record in DNS?

How to scan UDP ports from the Net?

How to monitor hacking attemps?

/tmp/asterisk/log/event_log is empty

/var/log/messages?

Hung up from remote Ekiga: XLite doesn't detect call ended

OK when XLite hangs up.

OK when ZoIPer hangs up.

-> Ekiga issue.

Using an Atcom AG-188N PSTN Gateway

Adding a Linksys 3102
VoIP gateway

Using a GSM cellphone with Asterisk

"OpenBTS is an open-source
Unix application that uses the Universal Software Radio Peripheral (USRP)
to present a GSM air interface to standard GSM handset and uses the Asterisk
software PBX to connect calls. The combination of the ubiquitous GSM air interface
with VoIP backhaul could form the basis of a new type of cellular network that
could be deployed and operated at substantially lower cost than existing technologies
in greenfields in the developing world.

In plain language, we are working on a new kind of cellular network that
can be installed and operated at about 1/10 the cost of current technologies,
but that will still be compatible with most of the handsets that are already
in the market. This technology can also be used in private network applications
(wireless PBX, rapid deployment, etc.) at much lower cost and complexity than
conventional GSM."

Zaptel and call progress

Ideally, you should connect Asterisk to the POTS through either an ISDN line
or SIP + VoIP provider, since, unlike analog on lines, they separate data and
signaling, which makes eg. disconnect
supervision very easy.

If you must use an analog line, professional-grade, PSTN
gateways are usually more reliable than entry-level Digium knock-offs and
the Zaptel/Dahdi driver + Zapata.

If you're lucky, your telco reverses line polarity or drops battery ("kewlstart",
an extension of "loopstart") to
indicate that the remote end has answered/hung up. To indicate a hangup, the
"loopstart" solution can reassert the dial-tone or give a busy/fast
busy signal.

Otherwise, if you are relying on Zaptel+PCI or the Linksys 3102 gateway,
Asterisk may not report that the callee is either BUSY or has picked up the
phone.

And even if Asterisk/Zaptel does detect an answer, automated calls can't
tell if the remote party is a human being or an answering machine.

So the only reliable solution if you need to automate calls (ie. "robocall")
is to loop through a voice message asking the callee to hit any key on their
dialpad to confirm that they did answer the call, and use a time-out if no DTMF
has been typed within a certain time-frame.

As for detecting that the callee has hung up, try "busydetect=yes"
in zapata.conf or chan_dahdi.conf.

Telco provides answer/hangup signal

If you are lucky, your telco uses the easier method of signalling answer/hangup,
through polarity reversal or open loop disconnect a.k.a. Calling
Party Control. In this case, edit zapata.conf thusly:

;tells chan_zap to monitor that line continuously for eg. pre-ring CID

;polarityevents=no

;how long (ms) to ignore Polarity Switch events after we answer a call

;polarityonanswerdelay=1

answeronpolarityswitch = yes

hanguponpolarityswitch = yes

If you are semi-lucky, you live in the US and Zaptel can be told to analyze
tones:

callprogress=yes

progzone=us

If none of the above applies, while Zaptel can detect a BUSY signal (which
should be sent when the callee is already online or has hung up your call),
it can't detect an offhook. Strangely enough, asterisk/indications.conf
is only used to play tones, not analyze them.

ChanIsAvail

When called with the name of the channel, ChanIsAvail()
returns the status in the AVAILORIGCHAN variable (AVAILSTATUS isn't reliable).
Here, we dial out from the CLI, and check the variable while the line is engaged.

Detecting a remote BUSY

When calling out, this is how to detect that the remote line is already engaged:

Make a call automatically through a callfile

Use Dial() manually and read the DIALSTATUS
variable to check how the call went. The problem with Dial() is that it's
a blocking application, so it won't work if you want to perform tasks after
the callee has answered. (try g/G)

Callfile

A callfile simply dials out and jumps to the context:

[callback]

exten => start,1,Answer()

exten => start,n,Playback(beep)

exten => start,n,Hangup

;0 - Failed (not busy or congested)

;1 - Hung up

;3 - Ring timeout

;5 - Busy

;8 - Congestion

exten => failed,1,NoOp(Reason call file failed is ${REASON})

An alternative:

[callback]

exten => start,1,GotoIf($[ "${DIALSTATUS}"="BUSY"]?end)

exten => start,n,Wait(2)

exten => start,n,Answer()

exten => start,n,Playback(some-important-message)

exten => start,n(end),HangUp

Dial()

exten => 123,1,Dial(Zap/1/5551234,10)

;just hangs up and doesn't proceed?

exten => 123,n,NoOp(Called ended with ${DIALSTATUS})

exten => 123,n,Hangup()

exten => h,1,NoOp(Called ended with ${DIALSTATUS})

Another example about the DIALSTATUS variable:

exten => s,n,Dial(Zap/1/5551234)

exten => s,n,Goto(s-${DIALSTATUS},1)

exten => s-ANSWER,1,Hangup

exten => s-CANCEL,1,Hangup

exten => s-NOANSWER,1,Hangup

exten => s-BUSY,1,Busy ;Only works with SIP calls

exten => s-CHANUNAVAIL,1,Verbose(Not available)

exten => s-CONGESTION,1,Congestion

exten => _s-.,1,Congestion

exten => s-,1,Congestion

RetryDialing

Doesn't work if remote end is busy: Simply hangs up and
ends there:

[redial]

;No difference

exten => start,1,Progress()

exten => start,n,RetryDial(pls-hold-while-try,10,3,Zap/1/5551234,30)

exten => start,n,NoOp(Result is ${DIALSTATUS})

exten => h,1,NoOp(In h, result is ${DIALSTATUS}

;no difference

exten => failed,1,NoOp(Reason call file failed is ${REASON})

[from_fxo]

exten => s,1,Wait(2)

exten => s,n,Hangup

exten => h,1,Goto(redial,start,1)

Testing

As a test, here's what to put in extensions.conf...

[callback]

exten => start,1,Answer()

exten => start,n,Wait(1)

exten => start,n,Playback(tt-monkeysintro)

exten => start,n,Wait(1)

exten => start,n,Hangup

... and here's how to make an outgoing call and check that Asterisk doesn't
jump to the [callback] context until the call has been answered:

Note that "originate" isn't very reliable, and sometimes drops
a call for no reason.

Files common to Zaptel and Dahdi

/etc/asterisk/indications.conf (Telephone
line signalling; call progress tones played to the callers with Playtones()
once they are within Asterisk)

CHECK /etc/modprobe.conf

Files specific to Zaptel

/etc/zaptel.conf

/etc/asterisk/zapata.conf

Files specific to Dahdi

/etc/dahdi/modules

/etc/dahdi/system.conf

/etc/asterisk/chan_dahdi.conf

modprobe.conf

options wctdm opermode=FRANCE

;options wctdm opermode=FRANCE debug=1

To actually see data in /var/log/messages, you must also edit /etc/asterisk/logger.conf.

asterisk/indications.conf

[general]

country=fr

[fr]

description = France

...

zaptel.conf

loadzone = fr

defaultzone=fr

fxsks=1

asterisk/zapata.conf

First, include your locale, eg.

language=fr

Next, tell Asterisk which signaling to use to match the one used in zaptel.conf:

fxs_ks=1

The better way to detect that the remote end has been disconnected is when
your telco performs a temporary polarity switch, ie. kewlstart/fxsks:

answeronpolarityswitch=yes

hanguponpolarityswitch=yes

;tells chan_zap to monitor that line continuously for eg. pre-ring CID

;polarityevents=yes

;how long (ms) to ignore Polarity Switch events after we answer a call

;polarityonanswerdelay=1

If this doesn't work, it could mean that your telco indicates a hangup with
a loop disonnect, a.k.a. Calling Party Control. I didn't find any settings in
any file to enable this.

If this is not available either from your telco, it means that your telco
plays tones to indicate call progress (eg. Disconnection Tone to signal a hangup).
Apparently, the only setting available in zapata.conf is to detect a BUSY signal:

busydetect=yes

busycount=4

I guess Asterisk knows how to handle other tone through the parameters set
in other files above.

"progzone" parameter: "This defines the timing and frequencies
for call progress detection, which are buried in the sources in asterisk/dsp.c.
This is DIFFERENT than the call progress timing defined in zaptel/zonedata.c
and in /etc/asterisk/indications.conf, and so far only options you can use (defined
in dsp.c) are us, ca, br, cr and uk."

"callprogress" parameter: "Highly experimental and can easily
detect false answers, so don't count on it being very accurate. Also, it is
currently configured only for standard U.S. phone tones". Enabling this
with non-US telcos may prevent Zaptel from working.

"flash" parameter: "used only with (non-PRI) T1 lines".

After editing zapata.conf, remember to stop Asterisk/restart Zaptel/start
Asterisk, or type the following in the CLI: module reload chan_zap.so

dahdi/modules

dahdi/system.conf

asterisk/chan_dahdi.conf

Q&A

Sometimes, "originate" doesn't actually ring a remote number

ip04*CLI> originate Zap/1/5551234 extension 8888@internal

Try with x86 Linux and check

Why dont call files trigger the "failed" extension?

If calling out through Zaptel+PCI or the Linksys 3102, try with a VoIP provider.

Recording a message

Asterisk only supports WAV files encoded in 16-bit, 8000Hz, mono. Here's
how to call Asterisk from XLite, and record a message in low- and high-quality
formats (source):

[context_for_my_handset]

exten => 101,1,Playback(vm-intro)

exten => 101,n,Record(maingreeting.wav)

exten => 101,n,Wait(2)

exten => 101,n,Playback(maingreeting)

exten => 101,n,Hangup

Alternatively, you can record a message in a more compact format such as
uLaw, which is a better option if this is the codec that is likely to be used
for incoming calls, as this will spare Asterisk from having to convert messages
to another format:

[context_for_my_handset]

exten => 101,1,Playback(vm-intro)

exten => 101,n,Record(maingreeting.ulaw)

exten => 101,n,Wait(2)

exten => 101,n,Playback(maingreeting)

exten => 101,n,Hangup

CLI> core show translation

Improving sound quality

To keep jitter/latency as low as possible, make sure the host running Asterisk
has enough hardware (CPU, RAM, network), only runs the minimal software required,
and has as few peripherals connected as possible.

Make sure all the routers within your control are configured to use QoS so
that VoIP traffic is favored over non-isochronous traffic.

Wireshark is a useful tool, as it can trace VoIP traffic and compute delay.

VAD (Voice Activity Detection)

VLAN, QoS

Codecs

Make sure all devices going through Asterisk use the same codec, so that
Asterisk doesn't have to perform transcoding.

How to get sound infos on a live conversation?

show translation

sip show channels

sip show channel <Call ID>

I'd recommend you get a hardware timer card for Asterisk. This will greatly
improve your audio quality since your test hardware is not powerful enough for
the software based timer to do it's job properly

Sangoma VoiceTime USB stick

Level too low

Choppy sound

Provided the issue occurs even with a single call, ie. bandwidth is plenty,
check the latency and round-trip time (RTT) between the two end-points.

Echo issues

Echo, heard either at your end or the remote end, can have two causes:

Impedance mismatch between the device (the IP-to-PSTN gateway), the
local loop to the telco, and the remote hybrid that turns this two-wire
cable into a four-wire cable before the voice signal is digitized by the
telco.

This mismatch causes some of your voice to be sent back to
you: The delay is too short for echo to be noticeable when using analog
equipments (so you'll just think of this as side-tone), but noticeable because
of the delay that VoIP adds to the process (analog-to-digital conversion
in the IP phone, DAC before setting your voice to the telco through the
POTS line, and back.)

Solution: If the device that you use to connect
to the POTS has some impedance settings, play with this setting. Also check
its in/out gain settings. If it still fails, try its own echo canceller,
if any, or a software echo canceller like the OSLEC
if your IP phone or IP PBX supports it

Cheap or badly-configured telephone where the voice coming from the
earpiece is picked up by the microphone, causing a loop-back.

Things
to try: Lower the incoming volume on your IP phone so the microphone doesn't
pick up the signal coming from the earpiece. Try a different IP phone. Use
a headset

Writing dialplans

The meat of Asterisk resides in extensions.conf, ie. the dialplan.

Application vs. function?

"An application is something that performs an action on a channel (such
as playing a sound prompt, gathering DTMF input, putting the call into a call
queue, etc.). A function, on the other hand, is used to get or set values, and
doesn't directly manipulate the channel. These values *might* have something
to do with the channel (such as is the case with the CDR function), but don't
necessarily have to (such as is the case with the CUT and LEN functions).

You could also think of it as the difference between a procedure and a function.
A procedure does something and returns nothing. A function may or
may not be doing something, but its primary function is to return a value. Unlike
other languages, in Asterisk, the return value of a function may not be directly
ignored (i.e. you HAVE to get it, even if you do nothing with it). Of course,
setting a dialplan function completely ruins this nice dichotomy. ;-)"

"An application is a "command" executed by a dialplan priority,
such as Record, Verbose, TrySystem, etc. A function needs to be evaluated inside
${ } and returns a string value that is substitued in place of the ${ }."

"In addition to dialplan applications, which have been part of Asterisk almost
from the very beginning, Asterisk also supports functions as of Asterisk 1.2.
This is part of a long-standing effort to make Asterisk behave more like a programming
environment.

In contrast to applications, functions may not be called directly.
Instead, they are called inside applications and return a value, or -- in a
departure from the classical definition of a function -- they may even be written
to using the application Set() (see the section called “Set()”). Function names
are always written in uppercase letters. Surprisingly, functions are written
in the same way as variables, inside curly braces and preceded by a $ character
( ${} ). This is necessary because strings are not always bounded by quotation
marks."

Functions

BLACKLIST BLACKLIST() Check if the callerid is on the blacklist

CUT CUT(<varname>,<char-delim>,<range-s Slices and dices strings, based upon a named delimiter.

DB DB(<family>/<key>) Read from or write to the Asterisk database

DB_DELETE DB_DELETE(<family>/<key>) Return a value from the database and delete it

DB_EXISTS DB_EXISTS(<family>/<key>) Check to see if a key exists in the Asterisk database

Handling busy/N.A.

u causes the "unavailable" message to be played. The pathname
for this message is /var/lib/asterisk/sounds/vm-isunavail.gsm[16]

b causes the "busy" to be played. The pathname for this message
is /var/lib/asterisk/sounds/vm-rec-busy.gsm.

s suppresses playback of the "unavailable" or "busy"
notifications, plays a beep, and begins recording.

If the caller presses "0" while listening to the prompt, the
application will jump to extension "o" (the small letter o) in
the specified context.

If the caller presses "*" while listening to the prompt, the
application will jump to extension "a" (the small letter a) in
the specified context.

Looping

Note: For a long time, priority jumping was a standard way of moving a call
about the dialplan. Specific applications (e.g. Dial()) would elevate
the priority by 101 under certain circumstances. This feature is now officially
deprecated. Basically, this means that while it is currently still supported,
eventually it will be removed. Anyone who continues to use it is making their
dialplans vulnerable to failure after an upgrade.

Here's an example of While/EndWhile:

exten => 1013,n,Set(i=1)

exten => 1013,n,While($[${i} < 10])

exten => 1013,n,SayNumber(${i})

exten => 1013,n,Wait(1)

exten => 1013,n,Set(i=$[${i} + 1])

exten => 1013,n,EndWhile()

Also look at ContinueWhile()

exten => 1015,1,Gosub(cid-set)

exten => 1015,n,Dial(SIP/${EXTEN})

exten => 1015,n(cid-set),Set(CALLERID(all)=Apfelmus GmbH <012345678>)

exten => 1015,n,Return()

Here's how to check if a CID number is in the database, and branch to the
right location depending on the result:

Calling external scripts with AGI

Important: AGI scripts dump error messages to the Asterisk ’console’ session.
If you started your session using normal init scripts, just attaching to it
normally won’t show you these messages. You need to launch asterisk with the
command ’asterisk -vvvvvvcr’. For debugging purposes you can type "agi debug" on the CLI.

(from some online source) New in Asterisk v1.2.11: GET VARIABLE can now retrieve
global variables (see bug 7609)

New in Asterisk v1.2: CallerID is reported with agi_callerid and agi_calleridname
instead of a single parameter holding both. The agi_callerid previously held
the value "Name"<Number> and the agi_calleridname was not present.
In v1.2, agi_callerid has Number and the agi_calleridname has Name.

Asterisk communicates with the AGI program over stdin and stdout. The arguments
are passed directly to the AGI program at execution time.

The AGI program must be flagged as executable in the filesystem. The path
is relative to the Asterisk AGI directory, which is at /var/lib/asterisk/agi-bin/
by default.

Returns -1 on hang-up or if the program requests a hang-up; returns 0 if
not.

This application sets the following channel variable upon completion:

AGISTATUS

The status of the attempt to the run the AGI script text string, one of SUCCESS
| FAILED | HANGUP

To run AGI programs on inactive channels (as in the case of an h-extension,
where the channel is on-hook), used DeadAGI() instead. Should your AGI program
need access to the incoming audio stream, use EAGI() instead of AGI(). The incoming
audio stream is provided on file descriptor 3[47]

Calling Lua scripts through AGI

An AGI script must always start with reading all the input sent by Asterisk
through stdin:

--Must first empty stdin

while true do

local line = io.read()

if line == ""
then break end

-- Without line below,
script never ends

io.write("NOOP
",line,"\n")

end

Using pbx_lua

In addition to calling the Lua interpreter through the AGI interface to make
it easier to write a diaplan application, Matt Nicholson from Digium added the
pbx_lua module (/usr/lib/asterisk/modules/*so) in 2008 so you can use /etc/asterisk/extensions.lua instead of
extensions.conf.

extensions.lua is more readable than extension.conf, but doesn't seem to
add more syntax, so calling Lua scripts through AGI seems like a more interesting
alternative.

Handling calls with Adhearsion

An alternative is to use Adhearsion,
wich is a framework written in Ruby that uses the AGI and AMI to manage calls.

Callback

In case you can make free calls from your broadband at home through an RJ11
plug in the modem, you can set up Asterisk to wait for calls from your cellphone,
and have Asterisk call you back through the FXO/Zaptel module before prompting
you for the number you want to call before bridging the two channels.

For some reason, Asterisk doesn't support reusing the same channel from which
the original call came, either within extensions.conf per se, or even by calling
an AGI script, even after calling Hangup() to make sure the channel is dead,
so either use a second channel or use SendDTMF() to dial the second number.

Direct callback

This solution simply waits for the channel to die, and then tries to dial
out:

[globals]

CID=""

[from_fxo]

exten => s,1,Wait(2)

exten => s,n,Set(CID=${CALLERID(num)})

;wait for cellphone to go back on-hook

exten => s,n,Wait(10)

exten => s,n,Hangup

;dial_exec_full: Unable to create channel
of type 'Zap' == Everyone is busy/congested at this time

exten => h,1,Dial(Zap/1/${CID})

Local channel

This code will wait for the channel to die, and then jump to another context
through a local channel:

[from_fxo]

exten => s,1,Wait(2)

exten => s,n,Set(CID=${CALLERID(num)})

;wait for cellphone to go back on-hook

exten => s,n,Wait(10)

exten => s,n,Hangup

;dial_exec_full: Unable to create channel
of type 'Zap' (cause 0 - Unknown) == Everyone is busy/congested at this
time

exten => h,1,Dial(Local/start@callback)

[callback]

exten => start,1,Dial(Zap/1/${CID})

AGI

This code will wait for the channel to die, and then call an AGI script which
will create a callfile and move it to Asterisk's outgoing/ directory

AGI + AMI

Since none of the above worked, here's how to call an AGI script from extensions.conf
that will connect to Asterisk's AMI interface and dial out.

extensions.conf

[from_fxo]

exten => s,1,Wait(2)

exten => s,n,Set(CID=${CALLERID(num)})

;wait for cellphone to go back on-hook

exten => s,n,Wait(10)

exten => s,n,Hangup

exten => h,1,DeadAGI(callback.lua)

AGI

Asterisk as an IVR

Simple script

Here's a simple script where Asterisk waits for a call, and asks the user
to hit the * key:

[ivr]

exten => s,1,Set(TIMEOUT(response)=5)

exten => s,n,Answer

exten => s,n(start),Background(please-type)

exten => *,1,Playback(thank-you)

exten => *,n,Hangup()

exten => i,1,Playback(wrong-key)

exten => i,1,Goto(start)

exten => t,1,Goto(time-out)

exten => t,n,Goto(start)

Reading a number back to the caller

Reading a phone number back to the user relies on the app_playback.so application,
its configuration file say.conf, and the use of Playback(...,say). Note that
SayNumber() is used to read a "real" number, not a phone number.

Here's how to configure Asterisk to read a phone number back to the caller,
and read it the French way (ie. 012345 is read "zero-one, "twenty-three",
"forty-five"):

More information

How does Asterisk know which file format a sound file is in? exten =>
9999,n,Playback(/root/asterisk_sound_files/test_asterisk)

What minimum configuration files does Asterisk to run?

Should I use extensions.conf or extensions.ael?

Here's the plan to use Asterisk as an Interactive Voice Response, ie. an
automated attendant:

When customers call in, they should hear a voice menu asking them which
software they're calling about. If caller ID didn't report their number,
the IVR should ask them to type a number where they can be called back

Next, they should be able to leave a voice message to explain what their
problem is

Next, Asterisk should send an e-mail to an alias that includes all the
people involved with the software

Finally, anyone involved should be able to listen to the voice message
and call the customer back. Some users are off-site, and will use SIP phones
through the Net.

CLI > database put cidname 12345 "John Smith"

CLI > database show cidname

Important: Do NOT add a file extension to specify the sound file format used
for a file; Otherwise, you'll get this type of cryptic error:

Either call extension 9000, or call a real extension, and put it on
hold to check that music is indeed played by Asterisk.

Alternatively, in the Asterisk console:

CLI> file convert myfile.wav myfile.ulaw

More information on SIP

Using (soft/hard)phones

Make sure phones don't use NAT if they are connected to the same LAN as
the Asterisk server. At best, you'll only get sound one way when calling an
extension, at worst the phone won't even register with Asterisk.

Edit sip.conf and extensions.conf thusly:

;------------------------------
sip.conf:[general]context=invalid ;Protection
against someone calling in from the Net to use the PSTN line...bindport=5060
;
UDP Port to bind to (SIP standard port is 5060)bindaddr=0.0.0.0 ;
IP address to bind to (0.0.0.0 binds to all)srvlookup=yes ;
Enable DNS SRV lookups on outbound calls

[200];username=200type=friendsecret=testqualify=yes
; Qualify peer is no more than 2000 ms awaynat=no ; This phone is not
nattedhost=dynamic ; This device registers with uscanreinvite=no
; Asterisk by default tries to redirectcontext=internal

[201];username=201type=friendsecret=testqualify=yes
; Qualify peer is no more than 2000 ms awaynat=no ; This phone is not
natted;host=192.168.0.234host=dynamic ; This device registers with
uscanreinvite=no ; Asterisk by default tries to redirectdtmfmode=rfc2833mailbox=1000callerid="Denise"context=internal

To debug SIP, either launch Asterisk in console mode, or connect to a running
Asterisk in console mode, and run either "sip debug" or "sip debug ip 192.168.0.1"
if you just want to read SIP messages sent/received to that specific host. To
disable debug mode, run "sip no debug". To see users and peers, run
"sip show users" and "sip show peers", respectively. To
tell Asterisk to reload its configuration files after you made changes, open
an Asterisk console (asterisk -r), and run "reload" followed by "stop
gracefully" (or "stop now" if there aren't ongoing calls.)

Some basic infos on how SIP works (from "Asterisk, the future of telephony"):

"The Session Initiation Protocol (SIP),often used in VoIP phones (either
hard phones or soft phones),takes care of the setup and teardown of calls,along
with any renegotiations during a call. Basically,it helps two endpoints talk
to each other (if possible, directly to each other). SIP does not carry media;
rather,it uses the Real-time Transport Protocol (RTP) to transfer the media
directly between phone A and phone B once the call has been set up. We use the
term media to refer to the data transferred between endpoints and used to reconstruct
your voice at the other end. It may also refer to music or prompts from the
PBX.

SIP is an application-layer signaling protocol that uses the well-known port
5060 for communications. SIP can be transported with either the UDP or TCP transport-layer
protocols. Asterisk does not currently have a TCP implementation for transporting
SIP messages,but it is possible that future versions may support it (and patches
to the code base are gladly accepted). SIP is used to “establish,modify,and
terminate multimedia sessions such as Internet telephony calls.” SIP does not
transport media between endpoints. RTP is used to transmit media (i.e.,voice)
between endpoints. RTP uses high-numbered, unprivileged ports in Asterisk (10,000
through 20,000, by default).

Domain Name System Service records (DNS SRV records) are a way of setting
up a logical,resolvable address where you can be reached. This allows calls
to be forwarded to different locations without the need to change the logical
address. By using SRV records,you gain many of the advantages of DNS,whereas
disabling them breaks the SIP RFC and removes the ability to place SIP calls
based on domain names. (Note that if multiple records are returned,Asterisk
will use only the first.) DNS SRV record lookups are disabled by default in
Asterisk,but it’s highly recommended that you turn them on. To enable them,set
srvlookup=yes in the [general] section of sip.conf.

Each connection is defined as a user,peer,or friend. A user type is used
to authenticate incoming calls,a peer type is used for outgoing calls,and a
friend type is used for both. The extension name is defined within square brackets
([]). In this case,we have defined the extension john as a friend.

If an extension is behind a device performing Network Address Translation
(NAT), such as a router or firewall,configure nat=yes to force Asterisk to ignore
the contact information for the extension and use the address from which the
packets are being received. Setting host=dynamic will require the extension
to register so that Asterisk knows how to reach the phone. To limit an endpoint
to a single IP address or fully qualified domain name (FQDN),replace dynamic
with the IP address or domain name. Note that this limits only where you place
calls to,as the user is allowed to place calls from anywhere (assuming she has
authenticated successfully). If you set host=static, the end device is not required
to register.

We’ve also set canreinvite=no. In SIP, invites are used to set up calls and
to redirect media. Any invite issued after the initial invite in the same dialog
is referred to as a reinvite. For example,suppose two parties are exchanging
media traffic. If one client goes on hold and Asterisk is configured to play
Music on Hold (MoH), Asterisk will issue a reinvite to the secondary client,telling
it to redirect its media stream toward the PBX. Asterisk is then able to stream
music or an announcement to the on-hold client. The primary client then issues
an off-hold command in a reinvite to the PBX,which in turn issues a reinvite
to the secondary party requesting that it redirect its media stream toward the
primary party,thereby ending the on-hold music and reconnecting the clients.

Normally,when two endpoints set up a call they pass their media directly
from one to the other. Asterisk generally breaks this rule by staying within
the media path, allowing it to listen for digits dialed on the phone’s keypad.
This is necessary because if Asterisk cannot determine the call length,inaccurate
billing can occur. Configuring canreinvite=no forces Asterisk to stay in the
media path,not allowing RTP messages to be exchanged directly between the endpoints."

Asterisk SIP 'users' and 'peers' are have been the source of much confusion
for Asterisk users. With newer versions of Asterisk the concept of SIP 'users'
will be phased out.

"As of Asterisk 1.2, there is no reason to actually use 'user'
entries any more at all; you can use 'type=peer' for everything and the
behavior will be much more consistent. All configuration options supported
under 'type=user' are also supported under 'type=peer'.

The difference between friend and peer is the same as defining _both_
a user and peer, since that is what 'type=friend' does internally.

The only benefit of type=user is when you _want_ to match on username
regardless of IP the calls originate from. If the peer is registering to
you, you don't need it. If they are on a fixed IP, you don't need it. 'type=peer'
is _never_ matched on username for incoming calls, only matched on IP address/port
number (unless you use insecure=port or higher)."

"SIP uses a challenge/response system to authenticate users. An initial
INVITE is sent to the proxy with which the end device wishes to communicate.
The proxy then sends back a 407 Proxy Authorization Request message, which contains
a random set of characters referred to as a “nonce.” This nonce is used along
with the password to generate an MD5 hash, which is then sent back in the subsequent
INVITE. Assuming the MD5 hash matches the one that the proxy generated, the
client is then authenticated.

Probably the biggest technical hurdle SIP has to conquer is the challenge
of carrying out transactions across a NAT layer. Because SIP encapsulates addressing
information in its data frames, and NAT happens at a lower network layer, the
addressing information is not modified, and thus the media streams will not
have the correct addressing information needed to complete the connection when
NAT is in place. In addition to this, the firewalls normally integrated with
NAT will not consider the incoming media stream to be part of the SIP transaction,
and will block the connection."

"To get started, Asterisk will need its SIP server module running so that it can
listen for SIP calls. By default, Asterisk's SIP server module listens on UDP
port 5060, the commonly used port number for SIP. If you use the SIP phone
(10.1.1.103) to dial the Asterisk server (10.1.1.10) by IP address, you should
get a 404 message on the phone's display: 404 is a SIP error code that means
"Not Found"just like the 404 message used on the Web. If you get this response
from the Asterisk server, it means the SIP module is listening and has responded
to you.

Now, in order to go from dialing only by IP address to dialing by extension, the
IP phone must be pointed to the SIP server.

Until you authorize a SIP phone to communicate with Asterisk using Asterisk's
SIP configuration file, you will always receive SIP error messages when trying
to dial to (or through) the Asterisk server. Asterisk refers to IP phones and other SIP devices as peers. SIP peers are defined
in Asterisk's configuration file, /etc/asterisk/sip.conf.

In its default configuration, Asterisk has an autoattendant that can route
calls using an automated attendant. To try it out, take the IP phone off hook
and dial 2. Then dial Send. You will hear a friendly voice saying, "Asterisk
is an open source, fully featured PBX and IVR platform..."

While listening to the automated attendant greeting, dial 500. This will
cause the Asterisk server to greet you; connect you to a server at Digium, Inc.,
using the Internet; and allow you to listen to another automated greetingthe
one being played back by a production Asterisk PBX at Digium's office. This
connection does not use the PSTN at all, but rather a Voice over IP "trunk"
that is set up on the fly by Asterisk.

The Voice over Internet demo requires UDP port 4569. If you're using a firewall
or NAT device, be sure it permits outbound traffic on this port. Most home-grade
firewalls will permit this type of traffic by default. The UDP port does not
need to be inwardly mapped or proxied.

The connection to Digium is established using IAX, not SIP. So the Asterisk
server is managing two different kinds of channels simultaneously in order to
facilitate this call. Listen to the sound quality. Do you notice any difference
between the quality of the autoattendant on your Asterisk server and the one
on Digium's? The difference in quality should be negligible, if even noticeable,
especially over a fast Internet connection.

You can also perform an echo test by dialing 600 and accessing Asterisk's
built-in voice mail service by dialing 8500. These are covered in greater detail
later.

The application responsible for providing music and messages for holding
callers is called Mpg123, but don't confuse it with the Mpg321 application that
ships with Red Hat Linux. Mpg321 doesn't work with Asterisk, so you must replace
it with Mpg123.

Along with Mpg123, Asterisk uses the configuration file called /etc/asterisk/musiconhold.conf
to define various "classes" of music-on-hold. Each class can be used
in different situations or contexts depending on how the Asterisk administrator
opts to handle each hold scenario. Mpg123 isn't required to deliver prerecorded
sounds; Asterisk can do that on its own using files in the GSM-encoded format
(and other telephony codec formats). What Mpg123 does is allow MP3 files to
be played back for holding callers to listen to while they wait."

Securing Asterisk

Make sure all extensions use a strong password

Install a firewall such as iptables, which can be configured to refuse
connections that look like intrusions, eg. too many failed attempts to REGISTER an extension.
Some add-on applications (Fail2Ban,
sshguard, adaptive-ban
(Arno's firewall), cron + BruteForceDetection,
etc.) can watch the log files and reconfigure iptables on the fly

It's also a good idea to use another port than UDP 5060 for SIP: Either
reconfigure Asterisk and all the SIP clients to connect to that port, or
add an SRV record in the DNS so clients can find which port to use

If you have no use of the Asterisk Manager Interface (AMI), disable
it through manager.conf. If you do use it, change the default password,
and consider only using it by first connecting in SSH, or give AstManProxy
a try

In sip.conf, consider the following options:

Only use "host=dynamic" for road warriors, who need to
register from the Net using a dynamic IP. Purely internal extensions
should use an IP address, ie. host=1.2.3.4

Use permit/deny to limit which user can be reached from the Net

Don't use extensions for usernames, so as to make it harder for
hackers to guess a username to register:

[xlite]context=internal

Use alwaysauthreject=yes to make it harder to guess which users
exist

Disable international calling, or prompt for a PIN

Configure Asterisk to run as non-root:

Create a user account that will be used to run Asterisk: adduser --system
--no-create-home --home /var/lib/asterisk --shell /bin/false asterisk

Monitoring

There are several ways to monitor Asterisk. Most notably, the Asterisk CLI
console application (asterisk -r) offers a real-time console log. When you launched
Asterisk with the -v option, this was enabled. The more v's, the more detail
goes into the console log. The same is true of the logfiles that Asterisk puts
out.

In addition to standard output and standard error, which you can redirect
using the shell, Asterisk has some important logfiles. They are stored in /var/log/asterisk
by default.

The Asterisk Manager is a text-based socket API that allows management applications
to monitor and control the Asterisk server. One such application is Astman,
which is included in the Asterisk distribution. Astman allows you to watch a
list of calls in progress and allows you to redirect calls and disconnect them.

Channels are logical pathways for voice connections at the application layer,
just as TCP and UDP provide logical pathways for data transfer and the transport
layer. Whenever an endpoint contacts the Asterisk server, a channel is established
that remains open for the duration of the connection. If one endpoint calls
another endpoint via the Asterisk softPBX, two channels are established one
to each endpoint. If one endpoint calls another endpoint that is hosted by a
completely separate Asterisk server, two channels on each server are established,
meaning that, between the two servers, it required four channels to connect
a single call. Astman can monitor the channels on only a single Asterisk server,
though.

If you want to develop a more advanced version of Astman or create your own
management or CTI (computer-telephony integration) applications, then the Asterisk
Management API is the way to go. It's a text-based protocol that provides you
with the ability to monitor the system, direct calls in progress, originate
calls, and add or remove extensions.

Trying AsteriskWin32

Here's what I learned while installing AsteriskWin32
release 0.60 on a host running Windows 2003 Server. To my knowledge, this is
the only port available for Windows. *Win32 is apparently managed by Patrick Deruel,
and is updated about once a year.

Here's how to set it up to have a couple of SIP accounts into a ring group
to be called by a VoIP gateway when a call comes in from the PSTN:

May 16 06:06:22 DEBUG[632] channel.c: Didn't get a frame from channel: SIP/202-00658810

Reading notes

Getting Started With Asterisk by Andy Powell

The order in which you do the modprobe’s IS important. If you modprobe the
FXO (modprobe wcfxo) card first then it will be channel 1, if you modprobe the
FXS (modprobe wcfxs) card first then its first port will be channel 1, the second
channel 2 and so on…

The order that the drivers are loaded will determine the channel assignments
of the drivers. You must load the drivers in the appropriate order:

modprobe zaptel

modprobe wcfxo

modprobe wcfxs //If you have an FXS card

Next, when editing /etc/zaptel.conf, the lines setting a protocol to a channel
(eg. fxsks=1) must match the order that the modules were modprobed:

fxsks=1 //we loaded wcfxo first

fxoks=2 //next came the wcfxs module

loadzone=nl

defaultzone=nl

Getting Started with Asterisk (2004/09/19)

A Useful Debugging Tip

The NoOp() application (No-Operation) is useful for debugging purposes. It
can be used to echo information to the Asterisk console. For example, Zap channels
don’t print the caller ID information on incoming calls, but we can do the following:

exten => s,1,Answer()

exten => s,2,NoOp(${CALLERID})

The CallerID information will then be output to the Asterisk console with
of the predefined channel variable ${CALLERID}.

The Hitchhiker’s Guide to Asterisk (2004/07/16)

VoIP Telephony with Asterisk (Paul Mahler; Published Jul 2004)

The Asterisk Handbook Version 2 (3/30/03)

Incoming Zap channels are labeled simply:

Zap/<channel>-<instance>

Where <channel> is the channel number and <instance> is a number
from 1 to 3 representing which of up to 3 logical channels associated with a
single physical channel this is.

Zap/1-1 : First call appearance on TDM channel 1

Running Asterisk is actually rather straight forward. Asterisk, if run with
no arguments, is launched as a daemon process. Often, it is useful to execute
Asterisk in a verbose, console mode, providing you with useful debugging and
state information, as well as access to the powerful Asterisk command line interface.

Some important console mode commands:

iax debug: Enable IAX debugging

mgcp debug: Enable MGCP debugging

reload: Reload configuration files

restart when convenient: Restarts Asterisk when all calls are gone

show agi: Displays AGI commands

show applications: Shows all Asterisk apps

show application <app>: Shows usage of a specific Asterik app

show channels: Shows all active channels

show channel <channel>: Shows information on a specific channel

sip debug: Enable SIP debugging

stop now: Stops Asterisk immediately

"Asterisk The Future of Telephony.pdf"

When a call comes in on an FXO interface,you will want to perform some action.
The action to be performed is configured inside a block of instructions called
a context. Incoming calls on the FXO interface are directed to the incoming
context with context=incoming. The instructions to perform inside the context
are defined within extensions.conf.

The Session Initiation Protocol (SIP),often used in VoIP phones (either hard
phones or soft phones),takes care of the setup and teardown of calls,along with
any renegotiations during a call. Basically,it helps two endpoints talk to each
other (if possible, directly to each other). SIP does not carry media; rather,it
uses the Real-time Transport Protocol (RTP) to transfer the media* directly
between phone A and phone B once the call has been set up.

SIP is an application-layer signaling protocol that uses the well-known port
5060 for communications. SIP can be transported with either the UDP or TCP transport-layer
protocols. Asterisk does not currently have a TCP implementation for transporting
SIP messages,but it is possible that future versions may support it (and patches
to the code base are gladly accepted).

RTP is used to transmit media (i.e.,voice) between endpoints. RTP uses high-numbered,
unprivileged ports in Asterisk (10,000 through 20,000, by default).

Domain Name System Service records (DNS SRV records) are a way of setting
up a logical,resolvable address where you can be reached. This allows calls
to be forwarded to different locations without the need to change the logical
address. By using SRV records,you gain many of the advantages of DNS,whereas
disabling them breaks the SIP RFC and removes the ability to place SIP calls
based on domain names. (Note that if multiple records are returned,Asterisk
will use only the first.) DNS SRV record lookups are disabled by default in
Asterisk,but it’s highly recommended that you turn them on. To enable them,set
srvlookup=yes in the [general] section of sip.conf.

The Inter-Asterisk eXchange (IAX) protocol is usually used for server-to-server
communication; more hard phones are available that talk SIP. However,there are
several soft phones that support the IAX protocol,and work is progressing on
several fronts for hard phone support in firmware. The primary difference between
the IAX and SIP protocols is the way media (your voice) is passed between endpoints.
With SIP,the RTP (media) traffic is passed using different ports than those
used by the signaling methods. For example,Asterisk receives the signaling of
SIP on port 5060 and the RTP (media) traffic on ports 10,000 through 20,000,
by default. The IAX protocol differs in that both the signaling and media traffic
are passed via a single port: 4569. An advantage to this approach is that the
IAX protocol tends to be better suited to topologies involving NAT.

The dialplan is truly the heart of any Asterisk system, as it defines how
Asterisk handles inbound and outbound calls. In a nutshell, it consists of a
list of instructions or steps that Asterisk will follow. The dialplan is made
up of four main parts: contexts, extensions, priorities, and applications.

Playing with /etc/asterisk/extensions.conf

The Asterisk dialplan is specified in the configuration file named extensions.conf.
The dialplan is made up of four main parts: contexts, extensions, priorities,
and applications.

Contexts

Dialplans are broken into sections called contexts. Contexts are named groups
of extensions. Simply put, they keep different parts of the dialplan from interacting
with one another. Contexts are denoted by placing the name of the context inside
square brackets ([]). Caution: Spaces are not allowed!

At the beginning of the dialplan, there are two special contexts named [general]
and [globals].

Extensions

Within each context, we define one or more extensions. An extension is an
instruction that Asterisk will follow, triggered by an incoming call or by digits
being dialed on a channel. Extensions specify what happens to calls as they
make their way through the dialplan.

The syntax for an extension is the word
exten, followed by an arrow formed by the equals sign and the greater-than sign,
like this: exten => . This is followed by the name of the extension.

When
dealing with telephone systems, we tend to think of extensions as the numbers
you would dial to make another phone ring. In Asterisk, you get a whole lot
more—for example, extension names can be any combination of numbers and letters.
Assigning names to extensions may seem like a revolutionary concept, but when
you realize that many Voice-over-IP transports support (or even actively encourage)
dialing by name or email address instead of by number, it makes perfect sense.
This is one of the features that make Asterisk so flexible and powerful.

A complete extension is composed of three components:

The name (or number)
of the extension,

The priority (each extension can include multiple steps; the
step number is called the “priority”), and

The application (or command) that
performs some action on the call.

These three components are separated by commas,
like this: exten => 123,1,Answer( ) . In this example, the extension name
is 123, the priority is 1, and the application is Answer( ).

Each extension can have multiple steps, called priorities. Each priority
is numbered sequentially, starting with 1. Each priority executes one specific
application. If you skip a priority, Asterisk will not continue past it.

Version 1.2 of Asterisk, however, adds a new twist to priority numbering.
It introduces the use of the n priority, which stands for “next.” Each time
Asterisk encounters a priority named n, it takes the number of the previous
priority and adds 1. This makes it easier to make changes to your dialplan,
as you don’t have to keep renumbering all your steps. For example, your dialplan
might look something like this:

exten => 123,1,Answer( )

exten => 123,n,do something

exten => 123,n,do something else

exten => 123,n,do one last thing

exten => 123,n,Hangup( )

When calls enter a context without a specific destination extension (for
example, a ringing FXO line), they are handled automatically by the s extension.
(The s stands for “start,” as most calls start in the s extension.)

Here's to answer the phone, play a sound file, and hang up:

[incoming]

exten => s,1,Answer()

exten => s,2,Playback(/home/john/sounds/filename)

exten => s,3,Hangup()

Here's how to tell the caller which digit was typed, or the number was invalid,
and loop back to the beginning of the context. If the caller doesn't answer
within 10 seconds (default), a sound file is played, and Asterisk hangs up:

[incoming]

exten => s,1,Answer( )

exten => s,2,Background(enter-ext-of-person)

exten => 1,1,Playback(digits/1)

exten => 1,2,Goto(incoming,s,1)

exten => 2,1,Playback(digits/2)

exten => 2,2,Goto(incoming,s,1)

exten => i,1,Playback(pbx-invalid)

exten => i,2,Goto(incoming,s,1)

exten => t,1,Playback(vm-goodbye)

exten => t,2,Hangup( )

... where the "i" priority stands of "invalid", and "t"
stands for "time-out".

Here's how to ring a phone connected to the Zap/1 channel when a call comes
in, play a sound file and hang up if the call times out (after 10 seconds in
this example), or play a sound file and hang up if the phone is busy. If the
extension is busy, Dial() jumps to priority n+101, ie. 102, here:

exten => 123,1,Dial(Zap/1,10)

exten => 123,2,Playback(vm-nobodyavail)

exten => 123,3,Hangup( )

exten => 123,102,Playback(tt-allbusy)

exten => 123,103,Hangup( )

Here's how to route calls to either extension 101 (a handset connect to an
FXS port) or 102 (an SIP phone):

[incoming]

exten => s,1,Answer()

exten => s,2,Background(enter-ext-of-person)

exten => 101,1,Dial(Zap/1,10)

exten => 101,2,Playback(vm-nobodyavail)

exten => 101,3,Hangup( )

exten => 101,102,Playback(tt-allbusy)

exten => 101,103,Hangup( )

exten => 102,1,Dial(SIP/Jane,10)

exten => 102,2,Playback(vm-nobodyavail)

exten => 102,3,Hangup( )

exten => 102,102,Playback(tt-allbusy)

exten => 102,103,Hangup( )

exten => i,1,Playback(pbx-invalid)

exten => i,2,Goto(incoming,s,1)

exten => t,1,Playback(vm-goodbye)

exten => t,2,Hangup( )

If you wish to dial an external phone (eg. your cellphone or an SIP phone
plugged into the Internet on the other side of the earth) when someone calls
an extension:

Here's an additional context for use in the internal network. It doesn't
matter what type of phone users use to make a call, whether it's a handset connect
to an FXS port on the Asterisk PBX, an IP phone, or a softphone; they can all
be configured to originate in this context:

Variables

Global variables should be declared in the [globals] context at the beginning
of the extensions.conf file:

exten => 101,1,Dial(${JOHN},10)

They can also be defined programmatically, using the SetGlobalVar( ) application.
Here is how both methods look inside of a dialplan:

[globals]

JOHN=Zap/1

[internal]

exten => 123,1,SetGlobalVar(JOHN=Zap/1)

A channel variable is a variable (such as the Caller*ID number) that is associated
only with a particular call. Unlike global variables, channel variables are
defined only for the duration of the current call and are available only to
the channel participating in that call.

Many predefined channel variables are available (see /doc/README.variables
in the Asterisk source.) Channel variables are set via the Set( ) application:

exten => 123,1,Set(MAGICNUMBER=42)

Environment variables are a way of accessing Unix environment variables from
within Asterisk. These are referenced in the formof ${ENV(var)}, where var is
the Unix environment variable you wish to reference.

Pattern matching

Pattern matching to allow you to use one section of code for many different
extensions. Patterns always start with an underscore _ . After the underscore,
you can use one or more of the following characters:

X Matches any digit from 0 to 9

Z Matches any digit from 1 to 9

N Matches any digit from 2 to 9

[15-7] Matches any digit or range of digits specified. In this case,
matches a 1, 5, 6, or 7

. (period) Wildcard match; matches one or more characters.

To use pattern matching in your dialplan, simply put the pattern in the place
of the extension name (or number):

exten => _NXX,1,Playback(auth-thankyou) //Any extension 200-999

Note that if Asterisk finds more than one pattern that matches the dialed
extension, it will use the most specific one.

If you need to know what digits were dialed, read the ${EXTEN} channel variable.
To have Asterisk read you the digits, you can use the SayDigits() application
:

exten => _XXX,1,SayDigits(${EXTEN})

exten => _XXX,1,SayDigits(${EXTEN:1}) //To skip the first digit

exten => _XXX,1,SayDigits(${EXTEN:-2)) //To read only the last two
digits

Here's how to let users dial internal extensions, as well as dial out by
prepending the number with the familiar 9:

Important: For security’s sake you should always make sure that your [inbound]
context never allows outbound dialing, as people could dial into your system,
and then make outbound toll calls that would be charged to you.

Expressions and functions

Use $[] to run expressions:

exten => 321,1,Set(COUNT=3)

exten => 321,2,Set(NEWCOUNT=$[${COUNT} + 1]) //NEWCOUNT = 4

Asterisk also supports operators like |, &, {=,>,<, etc.}:

exten => 234,1,Set(TEST=$[2 + 1])

In addition to applications, Asterisk supports functions:

exten => 123,1,Set(TEST=example)

exten => 123,2,SayNumber(${LEN(${TEST})})

Conditionnal branching:

exten => 123,1,GotoIf($[${CALLERIDNUM} = 8885551212]?20:10)

exten => 123,10,Dial(Zap/4)

exten => 123,20,Playback(abandon-all-hope)

exten => 123,21,Hangup( )

//context = open, s = extension, 1 = priority

exten => s,1,GotoIfTime(09:00-17:59,mon-fri,*,*?open,s,1)

Macros:

//macros are calle [macro-mymacroname] to be distinguished from regular
contexts

[macro-voicemail]

//macros only use s context

exten => s,1,Dial(${ARG1},20)

exten => s,2,Goto(s-${DIALSTATUS},1)

//if unavailable

exten => s-NOANSWER,1,Voicemail(u${MACRO_EXTEN})

exten => s-NOANSWER,2,Goto(incoming,s,1)

//if busy

exten => s-BUSY,1,Voicemail(b${MACRO_EXTEN})

exten => s-BUSY,2,Goto(incoming,s,1)

exten => _s-.,1,Goto(s-NOANSWER,1)

exten => 101,1,Macro(voicemail,${JOHN})

exten => 102,1,Macro(voicemail,${JANE})

exten => 103,1,Macro(voicemail,${JACK})

Voicemail

The voicemail configuration is defined in the configuration file called voicemail.conf.
Here's a couple of examples:

[default]

101 => 1234,John Doe,john@asteriskdocs.org,jdoe@pagergateway.tld

102 => 4444,Jane Doe

.. and add this to extensions.conf:

exten => 101,1,Dial(${JOHN},10,r)

exten => 101,2,VoiceMail(u101@default)

exten => 101,102,VoiceMail(b101@default)

//To check their voicemail, users dial 500, followed by their password

exten => 500,1,VoiceMailMain( )

Applications

Here's a list of applications available to include in a diaplan:

Answer()

Playback()

Hangup()

Background(): Plays a recorded sound, interrupts it when the caller
presses a key (or series of keys) on his telephone keypad to go to the extension
that corresponds with the pressed digit(s)

Goto(context,extension,priority): Sends the call to another context,
extension, and priority.

Dial(destination,timeout,r): The third argument stands for "ringback",
and forces Asterisk to play a ringing tone although it will always play
one while trying to establish a channel with the destination. The third
argument of Dial() actually modifies the behavior of this application; Check
the reference manual for a list of possible options. Some options can be
left out, eg. Dial(Zap/1,,r) to keep Asterisk ringing an extension with
no timeout

SayDigits(${EXTEN}): To have Asterisk read digits back

Congestion(): To play a fast busy signal

From "Asterisk: A Bare-Bones VoIP Example"

A call comes in on one of several channels (SIP in our case) and is "destined"
for a dialed number. The Asterisk process first deals with the call via whatever
channel it came in on, and learns what to do with it in that manner, and into
what context to send the call in extensions.conf.

Now that sip.conf has told our call what context to go to, the control is
handed over to the definitions created by the file extensions.conf. The extensions.conf
file works by defining various "contexts," which are clusters of dialed-number
matching statements. The context is the central building block of Asterisk,
and, loosely, is used as one might use a subroutine. Within a context are a
number of matching statements that perform match tests against the number being
processed. The call is passed through the comparison list until a match is found.

Each context has a set of extension matches, which determine what applications
should be triggered by the call, and how the call should be routed.

Wildcards can be used in extension mapping, and match strings beginning with
the underscore character (_), meaning that the following portions of the match
string include wildcard characters. Commonly used wildcards are N (digits 2-9),
X (any digit), . (any number of digits), and a variety of regular-expression
matching methods.

On an SIP-only setup, we only need to modify three files for our mini-PBX
two-line system: sip.conf (this defines the SIP peers, which are the software
or hardware SIP phones), extensions.conf (this is where the dialplans are kept
-- the meat of the system), and voicemail.conf (where we define the voice mailboxes
for each user).

Since only SIP channels are being used, we only need to modify three files
for our mini-PBX two-line system:

sip.conf (this defines the SIP peers, which are the software
or hardware SIP phones),

extensions.conf (this is where the dialplans are kept -- the
meat of the system), and

voicemail.conf (where we define the voice mailboxes for each
user).

Some users have reported successful use of voice modems instead of FXO cards,
but you should limit yourselves to the few hardware-based modems left instead
of win/softmodems, so that you won't be missing a Linux driver and save CPU
cycles (digitizing and compressing incoming voice calls is work better left
to peripherals.) For instance, an Asterisk user is happy with the Intel
56k Internal Modem, and recommends Intel-based hardware modems.

Softphones are software VoIP clients, while IP phones are stand-alone handsets
that connect to the LAN through an RJ45 cable without any need for a PC.

Asterisk consists of the following bits and pieces:

Asterisk: the core project to turn a PC into a PBX

Zaptel: Kernel interface device drivers for Analog and Digital interface
cards. If you are using Digium hardware you will need to download zaptel.
("The Zapata Telephony project led to the development of open source
device drivers for a range of telephony interfaces. Zaptel is Digium's revolutionary
Pseudo-TDM engine for Linux") Short for "Zapata Telephony".
Zaptel refers to Jim Dixon's open computer telephony hardware driver API.
Zaptel drivers were first released for BSD and Jim's Tormenta series of
DIY T1 interface cards. Digium later produced interface cards from Jim's
designs and improved the Zaptel drivers on the Linux platform. Digium then
added further drivers also following the Zaptel API for other telephony
hardware.

Asterisk-Addons: various modules and addons

Asterisk-Sounds: Default IVR files and miscellaneous sound files

Libiax: Library for the Inter-Asterisk eXchange (IAX) protocol. Libiax
provides a foundation for the development of IAX clients

Libpri: Primary Rate ISDN (PRI) library for T1/E1/J1 interfaces

Compact and/or Solid-state Asterisk

Here are the options I found if you want to build yourself a small form-factor
Asterisk server. As for using a Compact Flash card to hold the whole system,
ie. even logs and voice messages: "Just make sure your using an industrial
compact flash card. These support 1-2 million cycles where many of the retail
cards only support 100,000 cycles. We also greatly limit the logs being generated.
Writing logs files creates many times more write cycles than voicemail ever
could. If your concerned about logs use syslog to send them to an external system."

Since those hosts don't have much horse-power, avoid asking Asterisk to convert
from one sound format to another. "show translation" shows the time
needed to convert sound files, and gives an idea of performance.

To convert between different codec formats can you use the asterisk CLI command:

Asus WL500GP

Asus WL600G

Netgear WNR3500

PCEngines Alix

Besides the motherboards, you need a CF as main storage device (it is mounted
ro on /). You could also use a USB stick to mount /var in rw mode. Obviously
you need even a power supply (sold by Pcengines).

Intel D201GLY(2)

IP04 IP-PBX

"The IP04
is a 4 port IP-PBX that runs Asterisk and uClinux on a powerful embedded Blackfin
processor. To build an Asterisk IP-PBX you normally need a x86 PC plus a PCI
card for the analog ports. With the IP04 you get all of that functionality in
a tiny, low cost, low power, silent box. uCasterisk is in the process of being deprecated.
Astfin is the successor to uCasterisk, and where
most Blackfin Asterisk software development is now focused."

HP/Compaq T5700 XPE

PCI adaptor kit available for this thin client device.

Linksys WRT54 router

Linux/Asterisk OpenWRT on a Linksys
WRTGS54SL
router (or Asus WL-500g series). The exisisting implementations of both
run very poorly on a non-fpu cpu's, especialy if clock speed < 400 Mhz
I have run asterisk (and still do) on mips,ixp and powerpc (all without
fpu's) and i think that without modifications the codecs are not so usable

Apparently
you can add a SD card interface to a WRT54g relatively easily. You could
also use something like a Linksys NSLU2 network storage device with a USB
memory stick in it.

Soekris board

"I have purchased a couple of the soekris net4801 boards and have asterisk
up and running on them fine but they just don't quite cut it in the processing
power department. I've been able to get about 10 simultaneous SIP
calls with simple ulaw (no encoding decoding). While this might be OK for
a very small business or home I just don't think it leaves a lot of overhead
to do anything else.

Perhaps
the new Soekris net5501 that is about to be released will help you?"

Gumstix

Mini-ITX Via board

Via Epia motherboard: I've built several systems based on this motherboard
(the 1GHz fanless one) Compressed codecs are fine - as long as you aren't
transcoding ;-) I figured I could push 30 non transcoded calls through one,
but I've never had the ability to fully test it out. The max. I had going
on one system was 20 calls. 5 calls to music on hold (where it's transcoding
from the GSM moh file to G711 is causing my R&D box (wich has a 533MHz
VIA processor with 64Kb cache) is using between 5 and 12% CPU. I'd expect
one of my 1Ghz boxes to hardly notice this at all.Make sure you compile
asterisk in i586 mode - it's in the Makefile in 1.2.x. It'll crash otherwise
as the VIA processors are lacking some vital MMX instructions. Boot it off
flash and have it load an initrd.gz into RAM. Everything will run entirely
from RAM - no writes to the flash at all! I can get everything inside a
48MB flash drive, but I use 64MB ones which gives me space to store configs,
etc.. (of-course, I make it sound so simple ;-) but I'd already worked this
out some years back for a diskless router project). I keep voicemail on
a 2nd flash IDE device mounted as ext2 (not 3 as ext3 writes regularly!)

Get
a low end motherboard, like a VIA EPIA that doesn't use much power and a
solid state hard drive. a CompactFlash card can be connected to IDE with
a simple adapter and used as a 'drive'. It is recommended to store logs
and stuff on another flash drive as flash memory wears down over time, this
way you don't lose any config files if/as/when it dies.

AstLinux

Askorzia Appliance

Installing AskoziaPBX on a Compact Flash

AskoziaPBX is derived from m0n0wall,
is based on FreeBSD and, as of January 2008, runs Asterisk 1.4. Currently, it's
off-limit to any customization, ie. you can't change the dialplan, and can't
even get a login console when booting the CF card. Pretty much all you're allowed
to do is add phone extensions to it.

To modify an AskoziaPBX image, you'll need a FreeBSD system to decompress
and mount distribution images, and reflash the CF card.

Note: [x] is either
the whole card if you don't have a boot loader (eg. /dev/sdb), or just
a partition on the card (eg. /dev/sdb1). If you get a "Boot error",
it may mean that you copied the image to a partition but don't have a boot
loader on the card to actually boot the image

You can now boot the host with the CF card

In the Askozia menu, assign an Ethernet interface, and let the system
reboot

Back in the Askozia menu, if the IP address doesn't match your network
(192.168.1.0/24), assign an IP address and subnet mask so you can access
the embedded web server and configure Asterisk with a browser

Buy complete fanless system flash card ready unit with four ethernet
interfaces: http://www.ibt.ca/v2/items/fwa7204/index.html
It is very small, in an aluminium extrusion case, very robust. Install Astlinux
on 128 MB flash card - http://www.asterisk.org
Voila! - flash based firewall/asterisk machine capable of running 20+ extension
office. I have several installations like this. About $350.

You might want to check these guys out as well. Their communication
appliance boxes are nice and reasonably priced. I don't have any affiliation
with them. http://www.portwell.com

Troubleshooting

If you're having problems with Asterisk, here are some tricks to try:

Running a syslog-ng server, and have Asterisk and all SIP devices send
debug information to it

Running a packet sniffer on the Asterisk server: WireShark (ex-Ethereal)
is available in both GUI and text-mode versions, and undestands SIP, TCPDump
is a text-mode sniffer and can save dumps that can be analyzed by Wireshark

If you can't hear the voice, make sure that
either the IP phone is either set to use STUN, or that you forced it to
use a specific UDP port (eg. 5004, and 5005 for a GrandStream phone) and
opened those ports on the router.

Strings to look for when running "sip debug":Peer audio
RTPWe're at m=audio

"IP address or Domain name of Outbound Proxy, or Media Gateway,
or Session Border Controller. Used by ATA for firewall or NAT penetration
in different network environment. If symmetric NAT is detected, STUN will
not work and ONLY outbound proxy will provide solution for it."

Launch asterisk with maximum verbosity "asterisk -vvvvvgd &"

Commands you might need to investigate:

Either launch Asterisk in verbose mode with "-vvvvvvvvvvvv",
or type " core set verbose 3" in the CLI

If you have problems with a TDM card, "cat /proc/zaptel/*",
and "zap show channels" in the CLI

AMI requires two tries to login

Start by hitting the carriage return once, then type the following, and end
with another carriage return:

action: Loginusername: adminsecret: test

A phone is marked as UNREACHABLE

If Asterisk is sitting behind a NAT router, and the phone is living on the
outside, make sure sip.conf tells Asterisk that it's set up in a private network,
and that UDP5060 is statically open on the router to allow remote phones to
connect to Asterisk:

[general]

...

externip = the.router.s.public.address

localnet=192.168.0.0/255.255.0.0

nat=yes

canreinvite=yes

Hardware not detected

For PCI cards, make sure they're not sharing IRQs with other cards

Check that the power supply is strong enough

Start in runlevel 3, ie. no X

Recompile zaptel and asterisk

Use a more recent PC

Check length of cable between FXO and wall plug

Check signal level: ztmonitor <channel number> -v ("gives
you a visual representation of the sound strengths and makes it easy to
see if the receive or transmit signals are too high or out of balance")

try turning off call progress detection

try fxotune

adjust gain levels

Fails compiling zaptel

Check that the kernel sources match the kernel you are running (cat
/proc/version to check the kernel version; next, go to /usr/src/ to check
which version of the kernel sources are available, if any)

Check that the version of gcc installed is the same that was used to
compile the kernel (cat /proc/version to check which version was used to
compile it; gcc -v to check which version is installed)

Check that all the required dependencies are installed, and can be found

"You may have to do a "make prepare" in the kernel source
directory before you compile zaptel"

Fedora 5 ships with a bug in the kernel sources. You should run "yum
search kernel", and download (yum update) the latest kernel and kernel sources for your
architecture. Make sure both are for the same architecture: If you mix them
(eg. i586 and i686, you'll get an error when loading the zaptel module: "FATAL:
Error inserting zaptel (/lib/modules/2.6.17-1.2139_FC5/misc/zaptel.ko): Invalid
module format", along with this error in dmesg: "zaptel: disagrees
about version of symbol struct_module".) Reboot with the new kernel

Next, you'll need to update the /lib/modules/<kernel version>build
symlink to point to the new kernel sources, eg. "ln -s /usr/src/kernels/2.6
/lib/modules/`uname -r`build". If you don't, you'll get an error when compiling
zaptel.

Asterisk doesn't hang up FXO calls

Too much echo using an FXO card

"Hint: if you are experiencing problems with echo on your analog calls,
you may wish to uncomment the KFLAGS+=-DAGGRESSIVE_SUPPRESSOR line and run make
clean; make; make install -- this enforces a more rapid echo interceptor for
analog circuits."

"Failed to initailize [sic] DAA, giving up" with an FXO card

If modeprobing wcfxo says something like..

ZT_CHANCONFIG failed on channel 1: No such device or address (6)

FATAL: Error running install command for wcfxo

... and dmesg says:

Zapata Telephony Interface Registered on major 196

Zaptel Version: 1.2.5 Echo Canceller: MG2

Failed to initailize DAA, giving up...

wcfxo: probe of 0000:00:0e.0 failed with error -5

... this is most likely because the FXO card shares its interrupt with another
PCI card. Go into the BIOS, and configure the slot so that it has its own IRQ.
Run "lspci -v" to check if another card is sharing the IRQ.

Besides playing with the BIOS, you can launch Linux with the "pci=noacpi"
switch ("interrupt problems are more likely on Linux 2.6 than 2.4 since
the ACPI interface is more fully utilised. Try booting with acpi=off".)
When OK, the FXO card should show
up in /proc/zaptel/1 (or 2, etc.)

Zaptel can't access the card

If using a Linux distro that uses the udevd daemon to dynamically populate
/dev with device nodes, you must add some rules to /etc/udev/rules.d/50-udev.rules.

Freshmaker failed register test

This shows in "dmesg" when trying to use a PCI card + Zaptel. Make
sure the PCI card is OK hardware-wise, its golden edge is clean, and the card
is well seated in its slot.

If still NOK, try the card on another motherboard.

Caller ID

Note that you need to restart Asterisk to re-configure the Zap channel using "reload chan_zap.so".
This will reload the configuration file, but not all configuration options are re-configured during a reload.

Crappy sound when running echo test

Q&A

Freephonie: How to get rid of "determine_firstline_parts: Bad request
protocol Packet"?

This warning showing in the logs is due to some incompatibility between Asterisk
1.4 and Cirpack telephony servers. There are different ways to solve this:

Flash() doesn't work

By default, the hook flash is too long for European telcos. You'll need to
edit some include files before recompiling Zaptel/Dahdi.

Important: In case you already compiled Zaptel/Dahdi, make sure you start
from a clean plate by removing all object files (rm -f *\.o) from its source
directory.

Zaptel

zaptel.h

#define ZT_DEFAULT_FLASHTIME 100

zconfig.h

#define SHORT_FLASH_TIME

Dahdi

kernel.h

DAHDI_DEFAULT_FLASHTIME 100

dahdi_config.h.

#define SHORT_FLASH_TIME

After restarting the new Zaptel/Dadhi, run either "ztcfg -vv" or
"dahdi_cfg -vv" and "dmesg" to check that it loads OK.

How to reload Zaptela after editing zapata.conf?

CLI> module reload chan_zap.so

Why can't make callback?

Can't figure out why I had to use AGI to use a script to make a callback
instead of using this simpler way:

[from_fxo]

exten => s,1,Wait(2)

exten => s,n,Set(CID=${CALLERID(num)})

exten => s,n,Hangup()

;Wait for RINGs to stop

exten => h,1,Wait(10)

;DOESN'T WORK

;exten => h,n,Dial(Zap/1/${CID})

exten => h,n,Dial(Local/start@callback)

[callback]

exten => start,1,Verbose(In callback, CID is ${CID})

exten => start,n,Dial(Zap/1/${CID})

exten => start,n,Hangup

[sip.conf] Peer vs. friend?

This is used to handle incoming calls. The difference between the two is
that a "peer" is matched on its IP address (and possibly, its port
number) while a friend is identified by its entry name in sip.conf.

Note that confusingly, "sip show peers" in the CLI shows both peers
and friends, and that the third option "user" is pretty much deprecated.

How to trim the list of modules that Asterisk loads?

As specified in /etc/asterisk/asterisk.conf, modules are loaded from /etc/asterisk/modules.conf,
but the binary might have been compiled to either look for modules elsewhere
or (CHECK) have modules compiled directly in the asterisk binary.

Here's a working modules.conf:

[modules]

autoload=no

; Used applications

load => app_dial.so

load => app_playback.so

load => app_read.so

; Channel drivers

; probably you don't need chan_local, but it's nice

load => chan_local.so

load => chan_sip.so

; Codecs

load => codec_gsm.so

load => codec_ulaw.so

load => codec_alaw.so

load => codec_a_mu.so

load => format_gsm.so

load => format_pcm.so

; PBX - choose between AEL and .conf files

; load => pbx_config.so

load => pbx_ael.so

; use pbx_spool if you want to drop .call files

load => pbx_spool.so

; Functions

load => func_strings.so

load => func_rand.so

load => func_logic.so

load => func_cut.so

load => func_callerid.so

; Resources

; if you don't have agi, you may remove this

load => res_agi.so

load => res_musiconhold.so

; res_features is required by chan_sip

load => res_features.so

Can Asterisk fetch configuration files dynamically?

Yes, by compiling it with support for Curl:

[general]

static=yes

writeprotect=no

clearglobalvars=yes

[globals]

MYPHONE=SIP/2000

#exec /usr/bin/curl -s http://server/dialplan.txt

This can also be used to retrieve voicemail records. It's easier than using
a database, reloading app_voicemail.so, or when removing a voicemail box. All the passwords
are updated via the web server, so there is no need to update / write to
the voicemail.conf file.

Is ztdummy still needed?

Looks like recent versions of Linux no longer need the ztdummy kernel module
to provide a software timing source in the absence of a hardware timing
source.

In case it's still needed, and provided the "make install" or "make
config" didn't already take care of business:

//to load the thing right away

modprobe ztdummy

//to have it be loaded up at boot time

echo "ztdummy" >> /etc/modules

Which version am I running?

asterisk -V

Record's ${RECORDED_FILE} doesn't work

This channel variable is set by Record() only if you use the %d trick to
have it generate a new, sequential filename dynamically:

exten => 888,1,Playback(/root/asterisk/leave_msg)

;BAD exten => 888,n,Record(/tmp/wrong.wav,3,30)

;BAD exten => 888,n,Verbose(Recorded is ${RECORDED_FILE})

exten => 888,n,Record(/tmp/test%d.wav,3,30)

exten => 888,n,Verbose(Recorded is ${RECORDED_FILE})

exten => 888,n,Hangup()

NoOp() is not displaying anything

It apparently depends on the verbosity level. Use Verbose() instead.

WARNING: chan_zap.c: process_zap: Ignoring signalling

This is just due to the fact that chan_zap cannot change the signalling of
a channel when typing "reload" in the CLI. This parameter is ignored
on reload.

How to force using specific ports for RTP?

1.2.2.: rtp.conf

rtpstart=

Takes a numeric value, which is the first port of the port range that can
be used by asterisk to send and receive RTP.

rtpend=

Takes a numeric value, which is the last port of the port range that can
be used by asterisk to send and receive RTP.

How can all PC's be notified of a call?

This is useful when either using an IP hardphone that only displays CID numbers
(eg. the GrandStream BudgeTone 101), or when users simply don't have an extension
and simply want to see who's calling. A good and free that does just is NetCID,
the client-side of the great Identify caller ID application for Windows.

Here's how to configure Asterisk to broadcast a message when a call comes
in, so NetCID can pick it up through its default UDP 42685 (more
information):

From a remote PSTN phone, call into Asterisk, and check that NetCID
pops up

The only issue I found is when using characters > 128, ie. non-basic ASCII
characters: Show up OK in NetCID, but not in eg.X-Lite, but it's an issue with
code pages when importing data into Asterisk to rewrite CID data on the fly
through LookupCID().

#Must pause, and send IDLE for dialog box to close and call to be logged
in

time.sleep(5)

sendstuff("IDLE " + dateandtime)

#Next, let's unicast to the following remote hosts on the Net

How to (re)write caller ID name on the fly?

Add items in Asterisk's embedded database to match a name to a number.
If you only have a few entries, you can connect to the Asterisk server in
console mode and type eg. "database put cidname 123456 "My cellphone".
If you have a lot of entries, create an executable script to run this type
of instructions:

How to leave console mode without stopping Asterisk?

Just hit CTRL-C or type "exit". "stop now" stops the server as well.

Why two files, zaptel.conf and zapata.conf?

Because Zaptel cards actually predate Asterisk, so are not specifically built
to run with this software. Once configured through zaptel.conf, a Zaptel card
can be used by any application, not just Asterisk. Hence the need for zapata.conf
to act as a glue between the Zaptel card and Asterisk.

Zaptel hardware vs. Zapata hardware?

"Asterisk uses the zapata.conf file to determine the settings and configuration
for telephony hardware installed in the system. The zapata.conf file also controls
the various features and functionality associated with the hardware channels,such
as Caller ID, call waiting, echo cancellation, and a myriad of other options.

When you configure zaptel.conf and load the modules,Asterisk is not aware
of anything you’ve configured. The hardware doesn’t have to be used by Asterisk;
it could very well be used by another piece of software that interfaces with
the Zaptel modules. You tell Asterisk about the hardware and control the associated
features via zapata.conf."

What are devfs and udev?

"In the early days of Linux, the system’s /dev/ directory was populated
with a list of devices with which the system could potentially interact. At
the time, nearly 18,000 devices were listed. That all changed when devfs was
released, allowing dynamic creation of devices that are active within the system.
Some of the recently released distributions have incorporated the udev daemon
into their systems to dynamically populate /dev/ with device nodes." (from
"Asterisk, the future of telephony")

So-called Zaptel cards, ie. either the X100P or X101P cards, are cheaper
because they essentially are so-called voice winmodems, ie. they need a driver
to perform most of the work that real modems normally do themselves through
an on-board CPU. They're cheaper, and usable for a personal server, but shouldn't be considered
for a professional server.

"The older X100P card used a Motorola chipset,and the X101P (which Digium
sold before completely switching to the TDM400P) is based on the Ambient/Intel
MD3200 chipset. These cards are modems with drivers adapted to utilize the card
as a single FXO device (the telephone interface cannot be used as an FXS port).
Support for the X101P card has been dropped in favor of the TDM series of cards.
Use of these cards (or their clones) is not recommended in production environments."

"If you have a new 3.3v only motherboard then make very sure
that the brand that you buy supports this or your system will refuse to boot
with the card inserted. A lot of X100P clone cards have the 3.3v notch in their
PCI interface, but do not support 3.3v operation."

Here are the latest infos I gathered on the X100P/X101P cards to explain
why a lot of people have problems with this hardware:

The Zaptel driver generates about 1,000 interrupts per second, so it
should not be used on slow hardware, and you must make sure the card doesn't
share its interrupt with another PCI card

Analog line is a delicate environment where impedance, tension, and line
quality are some of the critical components. The original X100P made by
Digium as well as cheap knock-offs on eBay often use the Silicon Labs DAA
chips Si3012/Si3035 which is only good for use in countries that use the
FCC standard; Countries that use the CTR21 standard (Europe, and others)
require the Si3014/Si3034 chips, which support global line standards (more
information on www.x100p.com)

Echo issue: Using the the open-source OSLEC echo canceller and a bit
of hacking could solve this problem. A user reportes: "The OSLEC benchmark
tell me it can run 14 concurrent instances on a 550MHz VIA C3 processor.
On a 1.6GHz Atom, it tells me it can do 80 concurrent instances"

Stand-alone cards like
those from Digium cost ten times more but are much better quality, but even
those don't necessarily handle call information OK (caller ID, call progress),
at least in countries other than the US. OpenVox
makes cheaper clones of Digium cards.

Most of the clone cards don't support far-end disconnect supervision, so
you'll have problems where Asterisk can't tell that the other party has hung
up the phone.

FXO? FXS?

"An FXO interface is thus named because it connects to an Office , where
as an FXS interface, connects to a Station. The terms "FXO" and "FXS"
have their origins in an old telephone service called Foreign eXchange (FX).
The original purpose of an FX circuit was to allow an analog phone at a remote
location to be connected to a PBX somewhere else. An FX circuit has two ends
(the Station end, where the telephone is, and the Office end, where the PBX
is)."

STUN

STUN (Simple Traversal of UDP
over NATs): Used so clients can tell on which ports they're listening behind
a NAT firewall. Can be implemented in the firewall itself, or you can build
a STUN server (which just echos back this information to the client).

IAX vs. SIP

"The Inter-Asterisk eXchange (IAX) protocol is usually used for server-to-server
communication; more hard phones are available that talk SIP. However,there are
several soft phones that support the IAX protocol,and work is progressing on
several fronts for hard phone support in firmware.

The primary difference between the IAX and SIP protocols is the way media
(your voice) is passed between endpoints. With SIP,the RTP (media) traffic is
passed using different ports than those used by the signaling methods. For example,Asterisk
receives the signaling of SIP on port 5060 and the RTP (media) traffic on ports
10,000 through 20,000, by default. The IAX protocol differs in that both the
signaling and media traffic are passed via a single port: 4569. An advantage
to this approach is that the IAX protocol tends to be better suited to topologies
involving NAT."

Resources

Getting help

IRC:
You can connect to the irc.freenode.net server (Port: 6667) and talk to
Asterik users over the #asterisk channel. Note that this Asterisk channel
now requires that your nick be registered with the Freenode Nickerv in order
to participate. To do this, type "/msg NickServ register mypassword"
in your IRC client to register your password.

Tools

SmartCID ("A php script
to replace callerid information with lookup from a local mysql table, and
if that fails then reverse phone number lookup from 411.com.")

Flash Operator Panel (FOP; "Flash
Operator Panel is a switchboard type application for the Asterisk PBX. It
runs on a web browser with the flash plugin. It is able to display information
about your PBX activity in real time.")

<lesouvage> joe_acme: it must be something like exten => s,n,DIAL(ZAP/g1/mobilephonenumber,15,r)
in the extensions that handles the incoming call. You have to group the two
fxo ports into one group to make this work.

ring groups

hunt groups

To see errors produced by the modprobe command, use the command dmesg. Other
helpful error related information is avalable in any of the files created in
the directory /proc/zaptel. Thiscommand, an these files, can help you diagnose
errors in the zaptel configuration process, for example boards tha have not
been provided with power or drivers that are loading in the wrong order.

The program ztcfg reads the configuration information in zaptel.conf and
configures the drivers.You must run ztcfg each time zaptel driver are loaded,
for example after booting the machine.You can run ztcfg after you have made
any changes to zaptel.conf to reconfigure the drivers.