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?

Which environment to choose?

To set up Asterisk, several solutions are available:

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

There are two solutions:

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.

Installing from packages

Here's how to install Asterisk on Ubuntu from packages.

Asterisk and dahdi

  1. apt-get install asterisk
  2. apt-get install asterisk-config

Installing "asterisk" takes care of installing configuration files and Dahdi

Sound files

Those files are encoded in GSM.

  1. apt-get install asterisk-sounds-main
  2. apt-get install asterisk-sounds-extra

Localized Sound Files

Voice prompts are available for a few languages:

asterisk-prompt-fr-armelle - French voice prompts for Asterisk by Armelle Desjardins

asterisk-prompt-fr-proformatique - French voice prompts for Asterisk

http://downloads.asterisk.org/pub/telephony/sounds/

Post-install tweaking

The following changes included some needed to use Dahdi, ie. with a PCI interface.

  1. cd /etc/asterisk
  2. cp modules.conf modules.conf.orig
  3. vi modules:

    noload => pbx_ael.so
    noload => pbx_lua.so

    noload => app_cdr.so
    noload => app_fax.so
    noload => app_festival.so
    noload => app_followme.so
    noload => app_forkcdr.so
    noload => app_mp3.so
    noload => app_meetme.so

    noload => res_ldap.conf
    noload => res_phoneprov.so

  4. mv features.conf features.conf.orig
  5. mv users.conf users.conf.orig
  6. mv sip.conf sip.conf.orig
  7. mv extensions.conf extension.conf.orig
  8. mv say.conf say.conf.orig
  9. vi chan_dahdi.conf:
    language=fr
  10. vi cdr.conf: enable=no
  11. cd /etc/dahdi
  12. vi modules
  13. vi system.conf
  14. vi etc/modprobe.d/dahdi.conf: options wctdm opermode=FRANCE 
  15. /etc/init.d/asterisk restart

Basic Asterisk server with Dahdi from source

Dependencies

  1. Update the host with the latest of installed apps + kernel/kernel-dev. If the kernel was updated, reboot to use the latest version
  2. Download the dependencies:

    ncurses ncurses-devel
    openssl openssl-devel
    libssl-dev
    zlib zlib-devel zlib1g-dev
    bison bison-devel
    libnewt-dev
    initrd-tools
    procps
    wget
    libusb-dev (to avoid "waitfor_xpds: Missing astribank_is_starting")

    For CentOS:
    yum install kernel-devel kernel bison openssl-devel gcc gcc-c++ libtermcap libtermcap-devel ncurses ncurses-devel zlib zlib-devel newt newt-devel wget

    On a Debian/Ubuntu server, I've seen this recommended:
    apt-get install build-essential libncurses5-dev libcurl3-dev libvorbis-dev libspeex-dev unixodbc unixodbc-dev libiksemel-dev linux-headers-`uname -r` libnewt-dev wget

Asterisk

  1. cd /usr/src
  2. wget -c http://downloads.digium.com/pub/asterisk/asterisk-1.4-current.tar.gz
  3. tar xzvf asterisk-1.4-current.tar.gz
  4. cd asterisk-1.4.????
  5. ./configure
  6. make menuselect (UI OK from Putty, BAD from SecureCRT) > Core Sound Packages, Music On Hold File Packages, and Extras Sound Packages
  7. make
  8. make install
  9. make samples
  10. make config

Asterisk add-on's

Includes MySQL support for call detail records and MP3 support for MOH.

  1. cd /usr/src
  2. wget -c http://downloads.digium.com/pub/asterisk/asterisk-addons-1.4-current.tar.gz
  3. tar xzvf asterisk-addons-1.4-current.tar.gz
  4. cd asterisk-addons-1.4.11
  5. ./configure
  6. make
  7. make install
  8. make samples

Dadhi

  1. lspci -vv (Check that the hardware is detected)
  2. cd /usr/src
  3. wget -c http://downloads.asterisk.org/pub/telephony/dahdi-linux-complete/dahdi-linux-complete-current.tar.gz
  4. tar xzvf dahdi-linux-complete-current.tar.gz
  5. cd dahdi-linux-complete-2.3.0.1+2.3.0
  6. make
  7. make install
  8. make config
  9. (Not needed) vi /etc/modprobe.conf
  10. vi /etc/modprobe.d/dahdi.conf ("You should place any module parameters for your DAHDI modules here")

    options wctdm opermode=FRANCE
     
  11. (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.")
     
    1. Comment out modules you do NOT want to blacklist
    2. Add "blacklist netjet"
    3. 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
       
  12. vi /etc/dahdi/modules

    wctdm
     
  13. vi /etc/dahdi/system.conf
    loadzone = fr
    defaultzone = fr
    fxsks = 1
    echocanceller=mg2,1
  14. vi /etc/asterisk/indications.conf

    [general]
    country=fr

    [fr]
    description = France
    ; Reference: http://www.itu.int/ITU-T/inr/forms/files/tones-0203.pdf
    ringcadence = 1500,3500
    ; Dialtone can also be 440+330
    dial = 440
    busy = 440/500,0/500
    ring = 440/1500,0/3500
    ; CONGESTION - not specified
    congestion = 440/250,0/250
    callwait = 440/300,0/10000
    ; DIALRECALL - not specified
    dialrecall = !350+440/100,!0/100,!350+440/100,!0/100,!350+440/100,!0/100,350+440
    ; RECORDTONE - not specified
    record = 1400/500,0/15000
    info = !950/330,!1400/330,!1800/330
    stutter = !440/100,!0/100,!440/100,!0/100,!440/100,!0/100,!440/100,!0/100,!440/100,!0/100,!440/100,!0/100,440
  15. vi /etc/asterisk/chan_dahdi.conf

    [trunkgroups]

    [channels]
    signalling = fxs_ks
    usecallerid = yes
    hidecallerid = no
    callwaiting = yes
    callwaitingcallerid = yes
    threewaycalling = yes
    transfer = yes
    canpark = yes
    cancallforward = yes
    callreturn = yes
    echocancel = yes
    echocancelwhenbridged = yes
    relaxdtmf = yes
    rxgain = 0.0
    txgain = 0.0
    busydetect=yes
    ;busycount=6
    answeronpolarityswitch=yes
    hanguponpolarityswitch=yes
    context = from-pstn
    channel => 1
  1. vi extensions.conf

    [from-pstn]
    exten => s,1,NoOp(Incoming call)
     
  2. /etc/init.d/dahdi start, tail /var/log/messages, and check LED on PCI card
  3. Restart Asterisk

In case of trouble, try to put the card into another slot, or even in a difference computer. Take a look at OpenVox's Troubleshooting of Analog cards.

If you get "driver should be 'wctdm' but is actually 'netjet'" when starting dahdi: 

Commands

dahdi_cfg -vv to configure

dahdi_hardware to check hardware

dahdi_scan to display channels

CLI> dahdi show status

Troubleshooting

# dmesg

# lspci -vv

# dahdi_hardware

# dahdi_cfg -vv

SIP accounts

  1. Create SIP accounts and a basic dialplan:

    cd /etc/asterisk
    mkdir orig
    mv sip.conf ./orig
    mv extensions.conf ./orig

    vim sip.conf:
    [general]
    port = 5060
    bindaddr = 0.0.0.0
    context = others

    disallow=all
    allow=ulaw
    allow=alaw
    allow=gsm

    nat=no
    qualify=yes
    host=dynamic

    [2000]
    type=friend
    context=my-phones
    secret=1234

    [2001]
    type=friend
    context=my-phones
    secret=1234

    vim extensions.conf:
    [others]

    [my-phones]
    exten => 2000,1,Dial(SIP/2000)
    exten => 2001,1,Dial(SIP/2001)

    exten => s,1,Verbose(Yes!)

    exten => 9999,1,Goto(s,1)

  2. Launch Asterisk, and connect to its console:

    safe_asterisk
    asterisk -r ("quit" to exit)

  3. Configure two SIP phones to connect to Asterisk with the above accounts, and use one phone to ring the other

Once installed, Asterisk files can be located in the following directories:

Modules are located under /lib/modules/'uname -r'/misc (eg. wcfxo.o, zaptel.o, ztdummy.o, etc.)

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

  1. Install Cygwin. You may need to manually install/upgrade tools like autoconf, automake etc depending on your Cygwin installation
  2. Install build essentials in Cygwin
  3. 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)
  4. Run bootstrap it will report any missing or lower version libs, prerequisite or tools
  5. You manually need to download and compile termcap, ncurses
  6. Run configure
  7. Make menuselect and disable all non-required modules as it will save to resolve lot of not needed dependencies
  8. Run make
  9. Resolve any missing reported by make
  10. After successful make run make install
  11. 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:

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:

Trimming it down

Remove unneeded modules: /etc/asterisk/modules.conf

There are different types of modules:

In sip.conf, make use of templates:

[common](!)
context=my-phones
type=friend
host=dynamic
qualify=yes
 
[9000](common)
secret=1234
 
[9001](common)
secret=1234

Voicemail

  1. Add this kind of stuff in voicemail.conf:

    [general]
    format = wav

    [default]
    2000 => 4711,Joe Bloggs,joeb@megacorp.biz
    2001 => 0815,Darlene Doe

  2. Update extensions.conf

    [others]

    [my-phones]
    exten => 2000,1,Dial(SIP/2000,20)
    exten => 2000,2,VoiceMail(2000,u)

    exten => 2001,1,Dial(SIP/2001,20)
    exten => 2001,2,VoiceMail(2001,u)

    exten => 2999,1,VoiceMailMain(${CALLERID(num)},s)
  3. In the console, type "reload"

Adding an FXO card with Zaptel

  1. 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
  2. Download the Linux source code and headers for the kernel version you are currently using (cat /proc/version)
  3. Download and untar the Zaptel source code:

    wget http://downloads.digium.com/pub/zaptel/zaptel-1.4-current.tar.gz
    tar xzvf zaptel-1.4-current.tar.gz

  4. Compile the Zaptel module:

    cd zaptel-1.4.5.1
    make clean
    ./configure
    # make menuselect
    make
    make install
    make config

  5. Edit /etc/default/zaptel to match your hardware
  6. Create a user "asterisk" to run Zaptel, or you'll get "udevd : lookup_user : specified user 'asterisk' unknown" when rebooting:

    useradd asterisk
    edit /etc/password and /etc/shadow to disable login for this system account

  7. Create Zaptel's configuration file /etc/zaptel.conf:

    fxsks=1
    loadzone=fr
    defaultzone=fr

    Alternatively use the script genzaptelconf to generate a zaptel.conf that should work with your system

  8. Activate Zaptel: ztcfg -vv
  9. Edit /etc/asterisk/zapata.conf:

    [channels]
    language=fr
    context=my-phones ;Must match section in extensions.conf
    usecallerid=yes
    hidecallerid=no
    immediate=no

    signalling=fxs_ks
    echocancel=yes
    echocancelwhenbridged=yes
    group=1
    channel=>1 ;Must match channel # in zaptel.conf
  10. /etc/rc.d/init.d/zaptel start
  11. lsmod if you want to check that the modules were indeed loaded
  12. 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"
  13. Recompile and reinstall Asterisk
  14. 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.

is ztdummy automatically loaded when loading either zaptel or wcfxo? Zaptel timers for Asterisk, How to compile ztdummy

if ztcfg -vv = 0 channels configured. -> /etc/zaptel.conf

Asterisk Installation

Practical Asterisk

Asterisk (voip-info.org)

Asterisk Installation Guide

How to install asterisk from source on Debian

What do I do if I can't compile Zaptel package on my system ?

What is fxotune and how do I use 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:

[general]
;Basic protection
context=invalid
 
;Default for clients
bindport=5060
 
bindaddr=0.0.0.0
srvlookup=yes
 
;Your public IP address
externip=1.2.3.4
externrefresh=10
fromdomain=test.localhost.com
 
;rewrite source IP address in SDP packets
nat=yes
localnet=192.168.0.0/24
 
;keep firewall ports open
qualify=yes
 
;RTP packets must all through Asterisk server
; Asterisk by default tries to redirect
canreinvite=no
 
dtmfmode=auto
disallow=all
allow=ulaw
allow=alaw
 
register => mylogin:test@voip.com
[VoIPProvider]
nat=yes
qualify=yes
 
[200]
;username=200
type=friend
secret=test
qualify=yes
nat=no
host=dynamic
context=myinternal

How to Configure SIP and NAT By Sean Walberg

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

http://www.atcom.cn/AG188N.html

Adding a Linksys 3102 VoIP gateway

See this.

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.

First, extensions.conf where the call will be handled:

;Loop until Zap/1 is available or INDEX < 10
exten => 1111,1,Set(INDEX=0)
exten => 1111,n,While(1)
exten => 1111,n,ChanIsAvail(Zap/1)
exten => 1111,n,GotoIf($["${AVAILORIGCHAN}" != "" | ${INDEX} > 10]?exit)
exten => 1111,n,Wait(5)
exten => 1111,n,Set(INDEX=$[${INDEX} + 1])
exten => 1111,n,EndWhile()
 
;how did we exit loop?
exten => 1111,n(exit),GotoIf($["${AVAILORIGCHAN}" = ""]?na:ok)
 
exten => 1111,n(na),NoOp(Channel still N.A.)
exten => 1111,n,Goto(end)
 
exten => 1111,n(ok),NoOp(Channel OK)
;give */Zaptel time to recover
exten => 1111,n,Wait(5)
exten => 1111,n,Hangup()
 
exten => 1111,n(end),Hangup

Other ways to check the content of AVAILORIGCHAN:

exten => 7777,n,GotoIf($[!${ISNULL(${AVAILORIGCHAN})}]?available:not_available)
 
exten => 7777,n,GotoIf($[${EXISTS(${AVAILORIGCHAN})}]?available:not_available)

Next, place a call from the CLI:

originate Zap/1/5551234 extension 7777@internal

An alternative way to check if a Zaptel port is available and wait until the channel is available:

exten => 7777,1,Set(INDEX=0)
;j = Add 101 to priority to jump when N.A.
exten => 7777,n(check),ChanIsAvail(Zap/1,j)
 
exten => 7777,n,NoOp(Channel is available)
exten => 7777,n,Hangup
 
exten => 7777,103,NoOp(Channel N.A.)
exten => 7777,n,Wait(5)
exten => 7777,n,Set(INDEX=$[${INDEX} + 1])
exten => 7777,n,GotoIf($[${INDEX} < 10]?check)
exten => 7777,n,NoOp(Giving up)
exten => 7777,n,Hangup

Note that ChanIsAvail simply says if the port is available: In case you're trying to dial a remote end through a landline, the remote line might (still) be busy.

Also note that DEVICE_STATE (1.6, backported to 1.4) doesn't work with FXO modules:

;Dahdi doesn't support DEVICE_STATE
;CLI> core show channeltypes
exten => 2222,1,NoOp(${DEVICE_STATE(Dahdi/1)})
exten => 2222,n,Hangup()

Play message and wait for confirmation

As a work-around, instead of just using Wait() and start playing a message blindly, you can play a message asking the callee to hit a DTFM to confirm that they're ready to proceed:

[callback]
exten => s,1,Wait(2)
exten => s,n,Answer
 
;expects 1 key,4 tries, wait 5 seconds between tries
exten => s,n(read),Read(key,please-type,1,,4,5)
 
exten => s,n,GotoIf($[${LEN(${key})} == 0]?end)
 
;callee is alive
exten => s,n,Playback(auth-thankyou)
 
exten => s,n(end),Wait(1)
exten => s,n,Hangup()

CHANNEL()

Theoretically, using CHANNEL(), it should be possible to use a While loop to force Asterisk to pause until the callee has answered, but it doesn't work:

;Down, Rsrvd, OffHook, Dialing, Ring, Ringing, Up, Busy, Dialing Offhook, Pre-ring, Unknown
exten => start,n,Set(INDEX=0)
 
exten => start,n,While($["${CHANNEL(state)}" != "OffHook" & ${INDEX} < 10])
 
exten => start,n,NoOp(Channel still ringing: ${CHANNEL(state)})
exten => start,n,Wait(1)
exten => start,n,Set(INDEX=$[${INDEX} + 1])
 
exten => start,n,EndWhile()

Detecting a remote BUSY

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

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:

CLI> originate SIP/voip-out/5551234 extension start@callback
CLI> originate Zap/1/5551234 extension start@callback 

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

Files common to Zaptel and Dahdi

Files specific to Zaptel

Files specific to Dahdi

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.

Tips & tricks

Tones

Here is a list of the different call-progress tones, including Ringback, Ringtone, and Busy. International line settings can be found at www.3amsystems.com.

Closing channel

If you need to hang up a Zaptel channel in the Asterisk console: "soft hangup Zap/1-1" or "soft hangup Dahdi/1-1"

Reloading Zaptel/Dahdi

If you changed a channel's configuration in zapata.conf/chan_dahdi.conf, type "module reload chan_zap.so" or "module reload chan_dahdi.so", respectively.

Wait() in h

If you need to wait in the "h" extension, Wait() won't work. A work-around is to use system(/bin/sleep 10) to use the system's command instead.

Repeating a phone number

Here's how to have Asterisk repeat a phone number the French way:

  1. Put localized sound files in /var/lib/asterisk/sounds/fr/
  2. Edit /etc/asterisk/asterisk.conf thusly:

    [options]
    ;Layout requires Asterisk 1.4+
    languageprefix = yes

  3. Edit /etc/asterisk/say.conf:
    [general]
    ; method for playing numbers and dates
    ; old - using asterisk core function
    ; new - using this configuration file
    mode=new
    ...
    [fr](date-base,digit-base)
    ;BAD _[n]um:0. => num:${SAY:1}
    _[n]um:X => digits/${SAY}
    _[n]um:1X => digits/${SAY}
    _[n]um:[2-9]0 =>  digits/${SAY}
    _[n]um:[2-6]1 => digits/${SAY:0:1}0, vm-and, digits/${SAY:1}
    _[n]um:71 => digits/60, vm-and, num:1${SAY:1}
    _[n]um:7X => digits/60, num:1${SAY:1}
    _[n]um:9X => digits/80, num:1${SAY:1}
    _[n]um:[2-9][1-9] =>  digits/${SAY:0:1}0, num:${SAY:1}
    _[n]um:100 => digits/hundred
    _[n]um:1XX => digits/hundred, num:${SAY:1}
    _[n]um:[2-9]00 => num:${SAY:0:1}, digits/hundred
    _[n]um:[2-9]XX => num:${SAY:0:1}, digits/hundred, num:${SAY:1}

    _[n]um:1000 => digits/thousand
    _[n]um:1XXX => digits/thousand, num:${SAY:1}
    _[n]um:[2-9]000 => num:${SAY:0:1}, digits/thousand
    _[n]um:[2-9]XXX => num:${SAY:0:1}, digits/thousand, num:${SAY:1}
    _[n]um:XX000 => num:${SAY:0:2}, digits/thousand
    _[n]um:XXXXX => num:${SAY:0:2}, digits/thousand, num:${SAY:2}
    _[n]um:XXX000 => num:${SAY:0:3}, digits/thousand
    _[n]um:XXXXXX => num:${SAY:0:3}, digits/thousand, num:${SAY:3}

    _[n]um:1000000 => num:${SAY:0:1}, digits/million
    _[n]um:1XXXXXX => num:${SAY:0:1}, digits/million, num:${SAY:1}
    _[n]um:[2-9]000000 => num:${SAY:0:1}, digits/million
    _[n]um:[2-9]XXXXXX => num:${SAY:0:1}, digits/million, num:${SAY:1}
    _[n]um:XX000000 => num:${SAY:0:2}, digits/million
    _[n]um:XXXXXXXX => num:${SAY:0:2}, digits/million, num:${SAY:2}
    _[n]um:XXX000000 => num:${SAY:0:3}, digits/million
    _[n]um:XXXXXXXXX => num:${SAY:0:3}, digits/million, num:${SAY:3}

    _datetime::. => date:AdBY 'digits/at' H 'hours' M 'perc':${SAY}
    _date::. => date:AdBY:${SAY}
    _time::. => date:H 'hours' M 'perc':${SAY}

    ;800 numbers
    _pho[n]e:08XXXXXXXX => num:${SAY:0:1}, num:${SAY:1:3},num:${SAY:4:2}, num:${SAY:6:2},num:${SAY:8:2}


    _pho[n]e:XXXX => num:${SAY:0:2}, num:${SAY:2:2}

    _pho[n]e:0[1-9]XXXXXXXX => num:${SAY:0:1}, num:${SAY:1:1}, num:${SAY:2:2}, num:${SAY:4:2}, num:${SAY:6:2}, num:${SAY:8:2}

    _pho[n]e:. => digit:${SAY}
     
  4.  Edit /etc/asterisk/extensions.conf:

    exten => 1000,1,Playback(phone:0123456789,say)

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:

More information:

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
ENV                   ENV(<envname>)                       Gets or sets the environment variable specified
EVAL                  EVAL(<variable>)                     Evaluate stored variables.
EXISTS                EXISTS(<data>)                       Existence Test: Returns 1 if exists, 0 otherwise
FIELDQTY              FIELDQTY(<varname>|<delim>)          Count the fields, with an arbitrary delimiter
FILTER                FILTER(<allowed-chars>|<string>)     Filter the string to include only the allowed characters
GLOBAL                GLOBAL(<varname>)                    Gets or sets the global variable specified
IF                    IF(<expr>?[<true>][:<false>])        Conditional: Returns the data following '?' if true else the data following ':'
ISNULL                ISNULL(<data>)                       NULL Test: Returns 1 if NULL or 0 otherwise
LANGUAGE              LANGUAGE()                           Gets or sets the channel's language.
LEN                   LEN(<string>)                        Returns the length of the argument given
MATH                  MATH(<number1><op><number 2>[,<type  Performs Mathematical Functions
MD5                   MD5(<data>)                          Computes an MD5 digest
QUOTE                 QUOTE(<string>)                      Quotes a given string, escaping embedded quotes as necessary
RAND                  RAND([min][|max])                    Choose a random number in a range
REGEX                 REGEX("<regular expression>" <data>  Regular Expression
SET                   SET(<varname>=[<value>])             SET assigns a value to a channel variable
SHA1                  SHA1(<data>)                         Computes a SHA1 digest
SORT                  SORT(key1:val1[...][,keyN:valN])     Sorts a list of key/vals into a list of keys, based upon the vals
SPRINTF               SPRINTF(<format>|<arg1>[|...<argN>]  Format a variable according to a format string
STAT                  STAT(<flag>,<filename>)              Does a check on the specified file
STRFTIME              STRFTIME([<epoch>][|[timezone][|for  Returns the current date/time in a specified format.
STRPTIME              STRPTIME(<datetime>|<timezone>|<for  Returns the epoch of the arbitrary date/time string structured as described in the format.
TIMEOUT               TIMEOUT(timeouttype)                 Gets or sets timeouts on the channel.

Applications

                   AGI: Executes an AGI compliant application
                Answer: Answer a channel if ringing
            BackGround: Play an audio file while waiting for digits of an extension to go to.
      BackgroundDetect: Background a file with talk detect
                  Busy: Indicate the Busy condition
            Congestion: Indicate the Congestion condition
         ContinueWhile: Restart a While loop
                 DBdel: Delete a key from the database
             DBdeltree: Delete a family or keytree from the database
                  Dial: Place a call and connect to the current channel
                  Echo: Echo audio, video, or DTMF back to the calling party
              EndWhile: End a while loop
                  Exec: Executes dialplan application
                ExecIf: Executes dialplan application, conditionally
             ExitWhile: End a While loop
              ExtenSpy: Listen to a channel, and optionally whisper into it
              FollowMe: Find-Me/Follow-Me application
                 Gosub: Jump to label, saving return address
               GosubIf: Conditionally jump to label, saving return address
                  Goto: Jump to a particular priority, extension, or context
                GotoIf: Conditional goto
                Hangup: Hang up the calling channel
       HasNewVoicemail: Conditionally branches to priority + 101 with the right options set
          HasVoicemail: Conditionally branches to priority + 101 with the right options set
       LookupBlacklist: Look up Caller*ID name/number from blacklist database
         LookupCIDName: Look up CallerID Name from local database
                 Macro: Macro Implementation
        MacroExclusive: Exclusive Macro Implementation
             MacroExit: Exit From Macro
               MacroIf: Conditional Macro Implementation
         MailboxExists: Check to see if Voicemail mailbox exists
                  NoOp: Do Nothing
              Playback: Play a file
        PrivacyManager: Require phone number to be entered, if no CallerID sent
                Random: Conditionally branches, based upon a probability
                  Read: Read a variable
              ReadFile: ReadFile(varname=file,length)
                Record: Record to a file
                Return: Return from gosub routine
                   Set: Set channel variable(s) or function value(s)
           SetCallerID: Set CallerID
         SetCallerPres: Set CallerID Presentation
          SetGlobalVar: Set a global variable to a given value
                System: Execute a system command
               TryExec: Executes dialplan application, always returning
             TrySystem: Try executing a system command
               Verbose: Send arbitrary text to verbose output
             VoiceMail: Leave a Voicemail message
         VoiceMailMain: Check Voicemail messages
                  Wait: Waits for some time
             WaitExten: Waits for an extension to be entered
        WaitForSilence: Waits for a specified amount of silence
                 While: Start a while loop

Handling busy/N.A.

(Source)

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:

exten => 888,1,Set(CALLERIDNUM=111)
exten => 888,n,Verbose(${IF($["${DB(friends/${CALLERIDNUM})}"!=""]?good:bad)})
exten => 888,n,GotoIf($["${DB(friends/${CALLERIDNUM})}"!=""]?fred)
exten => 888,n,Verbose(Bad)
exten => 888,n,Hangup()
exten => 888,n(fred),Verbose(Good)

Here's how to check if a file exists, and branch to the right location:

exten => 888,1,Set(WAV_FILE=/root/asterisk/zapata.conf)
exten => 888,n,Set(WAV_FILE=${IF($["${STAT(e,${WAV_FILE})}" = "1"]?${WAV_FILE}:"")})
exten => 888,n,GotoIf($["${STAT(e,${WAV_FILE})}" = "1"]?next)
exten => 888,n,Verbose(Not found)
exten => 888,n,Hangup
exten => 888,n(next),Verbose(Found)

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]

; run AGI on a hung-up channel:

exten => h,1,DeadAGI(agi-test)

asterisk*CLI> agi show

get variable   Gets a channel variable

set callerid   Sets callerid for the current channel

a reminder: 0: stdin, 1: stdout, 2:stderr. File descriptor 3 is freely assignable.

As an alternative you may execute PHP scripts using System(). See also. the section called “System()”, the section called “AGI()”

exten => 777,1,Set(CALLERIDNUM=1234567890)

exten => 777,n,ExecIf($[${LEN(${CALLERIDNUM})} = 10],AGI,/root/dummy.php,${CALLERIDNUM},param2)

; Retrieve http://example.com/page.php?id=1&action=view :

exten => 123,1,Set(foo=${CURL(http://example.com/page.php?id=1&action=view)})

(As of Asterisk 1.2.8, use a pipe ("|") character instead of commas as a parameter delimiter.)

; set HOME:

exten => 123,1,Set(ENV(HOME)=/myAst)

Here's an example of a Python script that can be called from Asterisk through AGI:

#! /usr/bin/env python
>  import posix
>  posix.close(1)
>  posix.open("/dev/null", posix.O_WRONLY)
 
import os
import sys
import time
print os.getpid()
null = os.open(os.devnull,os.O_RDWR)
os.dup2(null, sys.stdin.fileno())
os.dup2(null, sys.stdout.fileno())
os.dup2(null, sys.stderr.fileno())
os.close(null)
print "You won't see this"
print >>sys.stderr, "Or this"
time.sleep(60)
 
>>  import os,sys,time
>>  print "pre:", os.getpid()
>>  sys.stdout = open(os.devnull, 'w')
>>  print "post:", os.getpid()
>>  time.sleep(60)
 
sys.stdout = open(os.devnull, 'w')
 
if os.fork():
   sys.exit(0)

Here's an example of a command-line PHP script (the -q switch tells PHP not to return HTML headers) using an SQLite database and being called from Asterisk through the AGI application:

#!/usr/bin/php -q
<?php
//myscript.php 123
 
try {
    $dbh = new PDO("sqlite:mydata.db");
    $dbh->exec("CREATE table customers (id INTEGER NOT NULL PRIMARY KEY, tel CHAR(10))");
    $dbh->exec("INSERT INTO customers VALUES (NULL, '" . $argv[1] . "')");
    $sql = 'SELECT tel FROM customers WHERE id=1';
    $result = $dbh->query($sql);
    $return = $result->fetch();
    echo "Result = " . $return['tel'];
    $dbh = null;
    }
catch(PDOException $e)
    {
    die($e->getMessage());
    #How to tell AGI that it bombed?
    }
?>

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.

Tips & Tricks

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

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
 
;__ast_request_and_dial: Unable to request channel Zap/1/123456
;attempt_thread: Call failed to go through, reason (0) Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)
exten => h,1,DeadAGI(callback.lua)

callback.lua

-- read input
while true do
        local line = io.read()
        if line == "" then break end
        io.write("NOOP ",line,"\n")
end
 
-- read number to call back
cid = arg[1]
io.write(string.format("NOOP CID is %s\n",cid))
response=io.read()
 
-- create and move callfile
file = io.open ("/var/tmp/callback.call","w")
channel = string.format("Channel: Zap/1/%s\n",cid)
file:write(channel)
file:write("Context: callback\n")
file:write("Extension: start\n")
file:close()
 
os.execute("mv /var/tmp/callback.call /var/tmp/asterisk/outgoing")

AGI + cron

Here, we'll use an AGI script to stop/edit/start cron to load a second script the next minute is up. The second script will take care of stopping/editing/starting cron and creating a callfile.

extensions.conf

[from_fxo]
exten => s,1,Wait(2)
exten => s,n,Set(CID=${CALLERID(num)})
exten => s,n,Wait(2)
exten => s,n,Hangup
 
exten => h,1,DeadAGI(/var/tmp/cron.lua,${CID})

cron.lua

#!/var/tmp/lua
 
CRONTAB="/etc/config/crontab"
CRONTAB_COPY="/etc/config/crontab.orig"
 
--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
 
-- read CID number from args
cid = arg[1]
io.write("NOOP After CID ",cid,"\n")
line = io.read()
 
-- stop cron
os.execute("/etc/init.d/cron stop")
 
--  cp original crontab, and add script to copy
command = string.format("cp %s %s",CRONTAB,CRONTAB_COPY)
io.write("NOOP ",command,"\n")
line = io.read()
os.execute(command)
 
local file = assert(io.open (CRONTAB,"a"))
file:write("* * * * * root /var/tmp/callback.lua ",cid,"\n")
file:close()
 
-- start cron
os.execute("/etc/init.d/cron start")
 
io.write("NOOP End of cron.lua\n")
line = io.read()

callback.lua

#!/var/tmp/lua
 
CRONTAB="/etc/config/crontab"
CRONTAB_COPY="/etc/config/crontab.orig"
 
-- read CID number from args
cid = arg[1]
 
-- stop cron
os.execute("/etc/init.d/cron stop")
 
file = io.open ("/var/tmp/callback.log","w")
 
-- remove job from crontab by deleting current and renaming original
command = string.format("rm %s",CRONTAB)
file:write(command,"\n")
os.execute(command)
 
command = string.format("mv %s %s",CRONTAB_COPY,CRONTAB)
file:write(command,"\n")
os.execute(command)
 
-- start cron
os.execute("/etc/init.d/cron start")
 
-- create callfile
callback = io.open ("/var/tmp/callback.call","w")
channel = string.format("Channel: Zap/1/%s\n",cid)
callback:write(channel)
callback:write("Context: callback\n")
callback:write("Extension: start\n")
callback:close()
 
command = "mv /var/tmp/callback.call /var/tmp/asterisk/outgoing"
file:write(command,"\n")
os.execute(command)
 
file:write("Done @ ",os.date("%H:%M"),"\n")
file:close()

Doesn't work :-/

    -- Attempting call on Zap/1/123465 for start@callback:1 (Retry 1)

channel.c:2863 __ast_request_and_dial: Unable to request channel Zap/1/123456

pbx_spool.c:341 attempt_thread: Call failed to go through, reason (0) Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)

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"):

  1. Use "language=fr" in zapata.conf and sip.conf
  2. Edit asterisk.conf

    ...
    [options]
    ;Layout requires Asterisk 1.4+
    languageprefix = yes
     
  3. Download the free FR voice files from the Asterisk site. Ulaw files are smaller than WAV
  4. Make sure say.conf is available in /etc/asterisk and contains the patterns for FR. If not, download this style from Asterisk's site
  5. Make those changes so that number couples that start with a leading zero are read including the zero, eg. "01" is read as "zero-one":

    [fr](date-base,digit-base)
    _[n]um:0X => num:${SAY:0:1}, num:${SAY:1:1}

    ...

    ;800 numbers: 0800, 0811... 0899
    _pho[n]e:08XXXXXXXX => num:${SAY:0:1}, num:${SAY:1:3},num:${SAY:4:2}, num:${SAY:6:2},num:${SAY:8:2}

    ;regular phone numbers : landlines and cellphones
    _pho[n]e:0[1-79]XXXXXXXX => num:${SAY:0:1}, num:${SAY:1:1}, num:${SAY:2:2}, num:${SAY:4:2}, num:${SAY:6:2}, num:${SAY:8:2}
     
  6. Either restart Asterisk or type "reload" in the CLI
  7. Edit extensions.conf to include something like this:

    [internal]
    exten => 2222,1,Playback(phone:0123456789,say)
    exten => 2222,n,Hangup

More information on using say.conf:

More information

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

  1. 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
  2. Next, they should be able to leave a voice message to explain what their problem is
  3. Next, Asterisk should send an e-mail to an alias that includes all the people involved with the software
  4. 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:

  -- Executing [s@default:2] Playback("SIP/2000-0871d000", "/usr/local/lib/asterisk/test.wav") in new stack
 
WARNING[37390]: file.c:563 ast_openstream_full: File /usr/local/lib/asterisk/test.wav does not exist in any format
 
WARNING[37390]: file.c:866 ast_streamfile: Unable to open /usr/local/lib/asterisk/test.wav (format 0x4 (ulaw)): No suchfile or directory

Just use "test" instead of "test.wav", make sure this file is available in the different codecs supported by the caller as specified in sip.conf, and let Asterisk pick the right version.

Useful CLI commands:

Adding Music on Hold

Free sound files are available at http://downloads.asterisk.org/pub/telephony/sounds/

Here's how to download and extract FR files:

cd /var/lib/asterisk/sound
 
wget -c http://downloads.asterisk.org/pub/telephony/sounds/asterisk-core-sounds-fr-ulaw-current.tar.gz
 
wget -c http://downloads.asterisk.org/pub/telephony/sounds/asterisk-extra-sounds-fr-ulaw-current.tar.gz
 
wget -c http://downloads.asterisk.org/pub/telephony/sounds/asterisk-moh-opsound-ulaw-current.tar.gz
 
mkdir /var/lib/asterisk/sounds/fr
 
tar -C fr -xzvf asterisk-core-sounds-fr-ulaw-current.tar.gz
tar -C fr -xzvf asterisk-extra-sounds-fr-ulaw-current.tar.gz
tar -C fr -xzvf asterisk-moh-opsound-ulaw-current.tar.gz

Here's how to convert a WAV file into PCM (µ/A-Law), and have it played by Asterisk as music on hold:

  1. mkdir /var/lib/asterisk/mohwav
  2. cd /var/lib/asterisk/mohwav
  3. wget http://www.acme.com/myfile.wav
  4. sox myfile.wav -t ul -r 8000 -b -c 1 myfile.pcm
  5. Edit /etc/asterisk/musiconhold.conf:

    [default]
    mode=files
    directory=/var/lib/asterisk/mohwav
    random=yes
     
  6. Edit /etc/asterisk/extensions.conf:

    exten => 9000,1,Answer
    exten => 9000,n,SetMusicOnHold(default)
    exten => 9000,n,WaitMusicOnHold(15)
    exten => 9000,n,Hangup

  7. asterisk -rx "restart gracefully"
  8. 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

  1. 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.
  2. 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=200
    type=friend
    secret=test
    qualify=yes ; Qualify peer is no more than 2000 ms away
    nat=no ; This phone is not natted
    host=dynamic ; This device registers with us
    canreinvite=no ; Asterisk by default tries to redirect
    context=internal

    [201]
    ;username=201
    type=friend
    secret=test
    qualify=yes ; Qualify peer is no more than 2000 ms away
    nat=no ; This phone is not natted
    ;host=192.168.0.234
    host=dynamic ; This device registers with us
    canreinvite=no ; Asterisk by default tries to redirect
    dtmfmode=rfc2833
    mailbox=1000
    callerid="Denise"
    context=internal

    ;------------------------------ extensions.conf
    [general]
    static=yes
    writeprotect=no
    autofallthrough=yes
    clearglobalvars=no
    priorityjumping=no

    [globals]

    [internal]
    ;BAD exten => ${EXTEN},1,Dial(SIP/${EXTEN})
    exten => 200,1,Dial(SIP/200)
    exten => 201,1,Dial(SIP/201)
    exten => 202,1,Dial(SIP/202)

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.

Quotes from Kevin Fleming of Digium on Asterisk Mailing list Dec 23, 2005:

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

(French) Utiliser Free comme passerelle SIP/RTC

Si la plupart des gens connectent un combiné sur leur Freebox pour passer des appels (gratuits vers des fixes, payant vers des portables), Free propose également un mode SIP pour se connecter à leur serveur de téléphonie. Voici comment configurer les choses (source: http://www.freephonie.org/doku/tutoriel:asterisk):

  1. Via le serveur web de Free, se connecter sur la console d'administration du compte, choisir un mot de passer pour le compte SIP et l'activer (http://adsl.free.fr/admin/tel/adminsip.pl)
  2. Editer sip.conf:

    [general]
    context=default
    bindaddr=0.0.0.0
    bindport=5060
    srvlookup=yes
    qualify=yes

    externip=82.224.X.X
    nat=yes
    localnet=192.168.0.0/24
    canreinvite=no
    rtptimeout=60
    rtpholdtimeout=300
    dtmfmode=auto
    disallow=all
    allow=ulaw
    allow=alaw
    register => 087077XXXX:mypasswd@freephonie.net
    defaultexpirey=1800

    ...
    [freephonie-out]
    type=peer
    host=freephonie.net
    username=087077XXXX
    fromuser=087077XXXX
    secret=mypasswd
    nat=yes

    [freephonie-in]
    type=peer
    context=fromfree
    host=freephonie.net
    ;Le qualify=yes ne semble pas une bonne idee. Le serveur de free ne reconnait pas la commande sip OPTIONS.
    ;qualify=yes
    allow=all
    deny=0.0.0.0/0
    permit=212.27.52.5/32
    insecure=invite

  3. Editer extensions.conf:

    ;Ajouter cette ligne au contexte utilisé par les clients SIP locaux
    ;pour qu'ils puissent appeler des numéros externes via Free
    exten => _0.,1,Dial(SIP/freephonie-out/${EXTEN})

    ;variante
    ;exten => _0.,1,Dial(SIP/${EXTEN}@freephonie-out)

    [fromfree]
    exten => s,1,Dial(SIP/200&SIP/201) ;Appel entrant Free fait sonner postes 200 et 201
    exten => s,n,Congestion 

Securing Asterisk

  1. Make sure all extensions use a strong password
  2. 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
  3. 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
  4. 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
  5. In sip.conf, consider the following options:
    1. 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
    2. Use permit/deny to limit which user can be reached from the Net 
    3. Don't use extensions for usernames, so as to make it harder for hackers to guess a username to register:

      [xlite]
      context=internal
       
    4. Use alwaysauthreject=yes to make it harder to guess which users exist
  6. Disable international calling, or prompt for a PIN
  7. Configure Asterisk to run as non-root:
    1. Create a user account that will be used to run Asterisk: adduser --system --no-create-home --home /var/lib/asterisk --shell /bin/false asterisk
    2. vim /etc/init.d/asterisk

      #Uncomment those lines
      AST_USER="asterisk"
      AST_GROUP="asterisk"
       
    3. mkdir /var/run/asterisk
    4. chown asterisk.asterisk /var/run/asterisk 
    5. vim /etc/asterisk/asterisk.conf

      astrundir => /var/run/asterisk
       
    6. chown -R asterisk.asterisk /etc/asterisk
    7. chown -R asterisk.asterisk /usr/lib/asterisk
    8. chown -R asterisk.asterisk /var/log/asterisk
    9. chown -R asterisk.asterisk /var/spool/asterisk
    10. chown -R asterisk.asterisk /var/lib/asterisk
    11. chown -R asterisk.asterisk /dev/zap/pseudo
    12. Launch Asterisk in debug mode to check that it loads OK:

      asterisk -U asterisk -G asterisk -cvv
       
    13. CTRL-C to close, and relaunch Asterisk through its init script.
  8. Start asterisk with /usr/sbin/safe_asterisk
  9. Consider installing SunshineNetworks knock to open ports dynamically
  10. Check your logs every day
  11. Check your server with sipvicious and SIPp
  12. Consider TLS (Transport Layer Security) and SRTP (Secure RTP)

peer vs. user vs. friend?

how to allow road warriors while locking down purely local extensions?

"If you have a mix of POTS and VoIP lines, don't put the POTS lines in the default outbound pool for toll calls. This could potentially save you lots of money."

road warriors : require PIN for dialing international numbers

OpenVPN vs. Hamachi VPN?

More information:

iptables

http://unicorn.drogon.net/firewall

http://blog.elphel.com/2011/03/hardening-the-asterisk-based-phone-system

iptables -A INPUT -p udp --dport 5060 -m state --state NEW -m recent --set --name SIP

iptables -A INPUT -p udp --dport 5060 -m state --state NEW -m recent --rcheck --name SIP --seconds  600 --hitcount  20 --rttl -j DROP

iptables -A INPUT -p udp --dport 5060 -m state --state NEW -m recent --rcheck --name SIP --seconds  300 --hitcount  10 --rttl -j DROP

iptables -A INPUT -p udp --dport 5060 -m state --state NEW -m recent --rcheck --name SIP --seconds  180 --hitcount   5 --rttl -j DROP

iptables -A INPUT -p udp --dport 5060 -m state --state NEW -m recent --rcheck --name SIP --seconds   60 --hitcount   3 --rttl -j DROP

iptables -A INPUT -p udp --dport 5060 -j ACCEPT

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:

  1. Remove useless modules like CAPI, Celliax, IAX, MGCP, TAPI, SKYPE by deleting/move those files in /asterisk/modules
  2. In extensions.conf, don't use [internal] for your own use: Some module(s) seem(s) to expect their own, and will complain
  3. After making changes to configuration files, in *Win32 GUI > PBX Tools > Reload
  4. To send commands to the GUI console, PBX Manager & Console
  5. Once *Win32 is installed as a Service, add a watchdog to restart it if it crashes

Here's the sip.conf and extensions.conf to create three SIP extensions (two for users, one for a Linksys VoIP gateway), and add a remote VoIP account for calling out:

;sip.conf
[general]
context=invalid        ;Protection against someone calling in from the Net to use the PSTN line...
bindport=5060
bindaddr=0.0.0.0
srvlookup=yes
 
;VoIP provider
externip=1.2.3.4
nat=yes
localnet=192.168.0.0/24
qualify=yes
canreinvite=no
rtptimeout=60
rtpholdtimeout=300
dtmfmode=auto
disallow=all
allow=ulaw
allow=alaw
register => mylogin:test@voip.com
defaultexpirey=1800
 
[voip-out]
type=peer
host=voip.com
username=mylogin
fromuser=mylogin
secret=test
nat=yes
 
[200]
;username=200
type=friend
secret=test
qualify=yes ; Qualify peer is no more than 2000 ms away
nat=no ; This phone is not natted
host=dynamic ; This device registers with us
canreinvite=no ; Asterisk by default tries to redirect
context=myinternal
 
[201]
;username=201
type=friend
secret=test
qualify=yes ; Qualify peer is no more than 2000 ms away
nat=no ; This phone is not natted
;host=192.168.0.234
host=dynamic ; This device registers with us
canreinvite=no ; Asterisk by default tries to redirect
;dtmfmode=rfc2833
mailbox=1000
;callerid="Denise"
context=myinternal
 
;VoIP gateway box
[fxo]
type=friend
secret=fxo
qualify=yes ; Qualify peer is no more than 2000 ms away
nat=no ; This phone is not natted
host=dynamic ; This device registers with us
canreinvite=no ; Asterisk by default tries to redirect
context=myinternal
 
;extensions.conf
[general]
static=yes
;writeprotect=no
writeprotect=yes
autofallthrough=yes
clearglobalvars=no
;priorityjumping=no
priorityjumping=yes
 
[globals]
 
[invalid]
;Used for unauthorized attempts to use our PSTN line from the Net
 
[myinternal]
;Call out through VoIP provider
exten => _0.,1,Dial(SIP/voip-out/${EXTEN})
 
;200 = X-Lite
;database put cidname 200 "XL Rewritten"
exten => 200,1,Dial(SIP/200)
 
exten => 201,1,LookupCIDName
exten => 201,n,Dial(SIP/201)
 
exten => 202,1,Dial(SIP/202)
 
;group is called by VoIP gateway
exten => group,1,LookupCIDName
exten => group,n,Dial(SIP/200&SIP/201)

 

=> Every minute, or so, server does this:

May 16 02:16:31 DEBUG[632] chan_sip.c: Stopping retransmission on '3dd817065abd672c0f18f87e5decf14b@192.168.0.2' of Request 102: Match Found

 

=> Every hour, this : remote X-Lite?

May 16 01:43:59 DEBUG[632] chan_sip.c: Auto destroying call 'OWUzMGJiMWZhZDJhOGQ2MTZjNTFkMmNmNjhkNDI0MDc.'

 

=> Every hour, Linksys 3102 and Linksys 921 do this:

May 15 20:01:21 DEBUG[632] chan_sip.c: Auto destroying call '52d3dd8a-437ae2bd@192.168.0.253'

May 15 19:03:25 DEBUG[632] chan_sip.c: Auto destroying call 'ae36c08a-f73d5d98@192.168.0.3'

 

=> Tried to call a Perl script when a call comes in, but...

exten => group,n,AGI(notify.agi|${CALLERID(num)}|${CALLERID(name)})

May 15 15:49:00 DEBUG[632] res_agi.c: winconsole 687308 agi script 20 stdin stdout 21 stderr 0 pid 392

 

 

AsteriskWin32 as Service : Crashed while doing nothing:

May 16 04:53:10 DEBUG[632] chan_sip.c: Stopping retransmission on '6a452a3560580aa22a1089646cbfe33d@192.168.0.2' of Request 102: Match Found

May 16 04:53:10 DEBUG[632] chan_sip.c: Stopping retransmission on '5e42a7b90a539f6232a98f0d689a0a78@192.168.0.2' of Request 102: Match Found

May 16 04:53:10 DEBUG[632] chan_sip.c: Stopping retransmission on '4598d2f5495119071812c6b7170d667c@192.168.0.2' of Request 102: Match Found

May 16 04:53:25 DEBUG[632] chan_sip.c: Auto destroying call '0E7C0C26D9CE4EE58C22B3716205D0450xc0a80034'

 

May 16 06:06:22 WARNING[632] channel.c: PTHREAD_KILL(SIGURG) softhangup_nolock on SIP/202-006a3470 !

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

May 16 06:06:22 DEBUG[632] channel.c: Bridge stops bridging channels SIP/203-0069df40 and SIP/202-006a3470

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:

"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:

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:

//Will dial 555-1212 through channel Zap/4 when the caller chooses extension 123
exten => 123,1,Dial(Zap/4/5551212)
 
exten => 123,1,Dial(SIP/1234)
exten => 124,1,Dial(IAX2/john@asteriskdocs.org)

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:

[internal]
exten => 101,1,Dial(Zap/1,,r)
exten => john,1,Dial(Zap/1,,r)
exten => 102,1,Dial(SIP/jane,,r)
exten => jane,1,Dial(SIP/jane,,r)

A VoIP transport lets you dial names instead of numbers, hence the "john" and "jane" extensions above.

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:

[globals]
JOHN=Zap/1
JANE=SIP/jane
OUTBOUNDTRUNK=Zap/4

[internal]
include => outbound-local
include => outbound-long-distance

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

[outbound-local]
exten => _9NXXXXXX,1,Dial(${OUTBOUNDTRUNK}/${EXTEN:1})
exten => _9NXXXXXX,2,Congestion( ) //Plays a fast busy signal if call failed for some reason
exten => _9NXXXXXX,102,Congestion( ) //Also play signal if got a busy signal

exten => 911,1,Dial(${OUTBOUNDTRUNK}/911) //Allow outgoing emergency calls
exten => 9911,1,Dial(${OUTBOUNDTRUNK}/911)

[outbound-long-distance]
exten => _91NXXNXXXXXX,1,Dial(${OUTBOUNDTRUNK}/${EXTEN:1})
exten => _91NXXNXXXXXX,2,Congestion( )
exten => _91NXXNXXXXXX,102,Congestion( )

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:

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:


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.

To broadcast caller ID from Asterisk to all hosts on the LAN (and beyond) http://www.voip-info.org/wiki/view/Asterisk+call+notification

Installation d'Asterisk sur un système Linux

"Il y a AMP (Asterisk Management Portal) qui est devenu maintenant FreePBX (http://asteriskvoip.blogspot.com/2006/03/freepbx-201-released.html)."

"Est-ce que qq a acheté récemment une vraie X100P (Chip Motorola) livrée avec les drivers ?"

" Dans le cas d'un systeme telephonique personnel, je conseillerai donc un asterisk VoIP pure avec un Sipura / Linksys SPA-3000 qui numerisera la ligne France Telecom avant de la renvoyer sur asterisk, et qui fait aussi office d'ATA 1 port. "

"Le PAP2 (comme le SPA-3000) n'est pas a considerer pour une utilisation professionel. C'est par contre un bon moyen de brancher des lignes qui servent peu a moindre cout ( 70 EUR pour 2 lignes )."

"Ces cartes ne sont plus produites par digium, et ont été remplacées par les cartes "TE", qui comme leur nom l'indique font T (US&Canada), E (EUR) et J (Japon).

T100P : Carte pour brancher un T1  E100P : Carte pour bancher un E1  T400P : Carte pour 4 T1  E400P : Carte pour 4 E1"

Windows versions: AsteriskWin32 and AstWind

AstLinux, a live CD built specifically for Asterisk (World's smallest VoIP PBX?)

Some kits are available:

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:

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:

file convert <file_in.format> <file_out.format>

To convert from a shell script can you do like this:

#!/bin/bash
# Converts a audio file from alaw to a ulaw
rasterisk -x "file convert /tmp/file_in.alaw /tmp/file_out.ulaw"

DLink DIR-825

http://wiki.openwrt.org/toh/d-link/dir-825

Buffalo WZR-HP-G300h

http://wiki.openwrt.org/toh/buffalo/wzr-hp-g300h

Asus WL500GP

http://wiki.openwrt.org/toh/asus/wl500gp

Asus WL600G

http://wiki.openwrt.org/toh/asus/wl600g

Netgear WNR3500

PCEngines Alix

http://www.pcengines.ch/alix.htm

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

The 2d3/2d13 are very nice for the price.

Intel D201GLY(2)

Intel D201GLY motherboard

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

Digium Asterisk Appliance

http://linuxdevices.com/news/NS5862403213.html

http://linuxdevices.com/news/NS6530620277.html

Pika Warp

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.

Through USB port, add an SD Card/Memory Key/USB Hard Drive. Check the Mitsubishi Diamond R100 (rebranched Asus WL-500g)

Linksys nslu2 NAS

"I've been using a Linksys nslu2 (slug) as a lightweight asterisk server. It isn't a broadband router, but it is cheap and works well. Add a usb flash/hdd"

http://www.voip-info.org/wiki/view/Asterisk+Linksys+NSLU2
http://en.wikipedia.org/wiki/NSLU2

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?"

http://www.voip-info.org/wiki/view/Asterisk+hardware+Soekris

Gumstix

Asterisk on Gumstix SBC

Mini-ITX Via board

About 500E for a full host (motherboard, RAM, IDE hard disk, DVD drive, case).

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. 

http://www.limeylinux.org

AstLinux

Moved here.

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.

Here's how to install Askozia on a Compact Flash card:

  1. Check which drive+partition the CF card uses: fdisk -l
  2. # wget http://askozia.com/downloads/pbx-generic-pc-pb12.2.img
  3. (On Linux) To copy the image to the CF card, run the following:

    gunzip -c pbx-platform-xxx.img | dd of=/dev/hd[x] bs=16k

    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
     
  4. You can now boot the host with the CF card
  5. In the Askozia menu, assign an Ethernet interface, and let the system reboot
  6. 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
  7. Aim your browser at http://askozia/, and logon as admin/askozia
  8. The first sections you want to check are System > General Setup, System > Interfaces, Phones > SIP

Extra Stuff

Troubleshooting

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

AMI requires two tries to login

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

action: Login
username: admin
secret: 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

Fails compiling zaptel

Asterisk doesn't hang up FXO calls

Resolving hangup detection problems with fxo cards

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.

www.voip-info.org/wiki/view/Asterisk+SIP+user+vs+peer

What's the difference between a B2BUA and a register/proxy server?

Dialing SIP URI's with a keyboard-less telephone?

Calling SIP URI's (ie. sip:user@domain) is easy when using an SIP application running on a computer, but not very practical with regular IP phones.

A solution is to map the URI with a number from eg. Freenum.

Connecting to PSTN/ISDN: PCI or appliance?

There are two options when connecting Asterisk directly to the telephone network, whether through an analog line or an ISDN line:

The main brands are: Digium, Patton, Audiocodes, Rhino Equipment, and Sangoma.

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.

In extensions.conf, a script fails to fork

;BAD exten => _[1-4],n,AGI(netcid.py|${CALLERID(num)}|${CALLERID(name)})
exten => _[1-4],n,System(netcid.py ${CALLERID(num)} ${CALLERID(name)})

What are recommended IAX (soft|hard)phones?

Softphones

Hardphones

Can I use SQLite instead of BerkeleyDB?

As of Jan 2008, either use the func_odbc() application, call a script with AGI(), or try the recent Asterisk cmd MYSQL add-on.

Playback(/tmp/myfile.wav) fails

WARNING[622]: file.c:568 ast_openstream_full: File /tmp/myfile.wav does not exist in any format
WARNING[622]: file.c:871 ast_streamfile: Unable to open /tmp/myfile.wav (format 0x4 (ulaw)): No such file or directory
WARNING[622]: app_playback.c:437 playback_exec: ast_streamfile failed on SIP/2000-0868d000 for /tmp/myfile.wav

Remove the file extension:

exten => 1,1,Playback(/tmp/myfile)

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):

  1. cd /var/lib/asterisk/agi-bin
  2. vi ncid.agi, and copy the contents shown above
  3. chmod 755 ./ncid.agi
  4. Add a reference to it your dialplan, eg. exten => cid,n,AGI(ncid.agi|${CALLERIDNUM}|${CALLERIDNAME})
  5. 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().

Here's the Python version of the above Perl ncid.agi script:

#TODO
# - Unicast to list of remote users
# - STDOUT and STDERR
# - Add Perl' open STDOUT, '>/dev/null'; fork and exit; to avoid waiting
 
#!/usr/bin/python
 
import socket,sys,time,os
 
def sendstuff(data):
        s.sendto(data,(ipaddr,portnum))
        return
 
#BAD?
#import posix
#posix.close(1)
#posix.open("/dev/null", posix.O_WRONLY)
 
#BAD?
sys.stdout = open(os.devnull, 'w')
if os.fork():
    sys.exit(0)
 
try:
        cidnum = sys.argv[1]
except:
        print "Format: netcid.py cidnum cidname"
        sys.exit(1)
 
try:
        cidname = sys.argv[2]
except:
        print "Format: netcid.py cidnum cidname"
        sys.exit(1)
 
now = time.localtime(time.time())
dateandtime = time.strftime("%d/%m/%y   %H:%M", now)
 
myarray = []
myarray.append("STAT Rings: 1")
myarray.append("RING")
myarray.append("NAME " + cidname)
myarray.append("TTSN Call from " + cidname)
myarray.append("NMBR " + cidnum)
myarray.append("TYPE K")
 
#First, let's broadcast to the LAN
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,True)
 
portnum = 42685
#ipaddr = "192.168.0.255"
ipaddr = "localhost"
 
for i in myarray:
    sendstuff(i)
#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?

  1. 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:

    asterisk -rx 'database put cidname 1234567 "My cellphone"'
    asterisk -rx 'database put cidname 7896543 "My home"'

    Note: Whatch out for embedded characters in the CID name such as ', ?, !, and extendend ASCII characters like é, è, etc. (non-ASCII chars showed OK in NetCID, but not X-Lite)
     
  2. Edit the context in extensions.conf that handles incoming calls:

    [incoming]
    exten => group,1,LookupCIDName
    exten => group,n,Dial(SIP/200&SIP/201&SIP/202)

  3. Reload Asterisk, and call into it.

This works because LookupCIDName looks for numbers in families cidname (and blacklisted numbers from the blacklist family). More information on using the database here.

Here are some useful commands that you can use while in an Asterisk console:

How to update a list of calls on the web?

Here's how to call a PHP script from an AGI Perl script each time a call comes in:

#!/usr/bin/perl
 
#Save this script as /var/lib/asterisk/agi-bin/web.agi
 
#use LWP::Simple;
use URI::Escape;
use LWP 5.64;
 
open STDOUT, '>/dev/null';
#Let Asterisk go back to work and let the script run its life
fork and exit;
 
my $cidnum = $ARGV[0];
my $cidname = $ARGV[1];
 
#CID name may contain spaces and other no-no characters
$safe_cidname = uri_escape($cidname);
 
my $browser = LWP::UserAgent->new;
 
my $url = "http://www.acme.com/input.php?";
$url .= "name=" . $safe_cidname . "&";
$url .= "number=" . $cidnum . "&";
 
($min, $hrs, $day, $month, $year) = (localtime) [1,2,3,4,5];
$currentdate = sprintf("%02d/%02d/%02d", $day, $month+1, $year);
$currenttime = sprintf("%02d:%02d", $hrs,$min);
$url .= "date=" . $currentdate . "&";
$url .= "time=" . $currenttime;
 
my $response = $browser->get( $url );
die "Can't get $url -- ", $response->status_line unless $response->is_success;

And here's how to tell Asterisk to call the script:

exten => group,1,LookupCIDName
;Important: The script must be called before dialing extensions
exten => group,n,AGI(web.agi|${CALLERID(num)}|${CALLERID(name)})
exten => group,n,Dial(${EXT200}&${EXT201})

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")

Which FXO card?

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:

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

Tools

Books

Sites and articles

Temp

Install a SIP softphone, and dial out through Zap/2

http://www.experts-exchange.com/Networking/VoIP_Voice_over_IP/Q_21820311.html

http://www.asteriskguru.com/tutorials/resolving_hangup_detection_problems_fxo_tdm_voicemail.html

CLI > zap show channels


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


http://forums.digium.com/viewtopic.php?t=7356