Set up your own PBX with Asterisk

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

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

  • "There are several SIP implementations that are OSS, but they are primarily what are known as "call proxies" instead of more full-featured PBX applications. This means that they function only to connect two endpoints together, and are basically just large, fast, directory servers. Examples of SIP Proxies are ser and Vocal."
  • Is Asterisk the only PBX that can rewrite CID name on the fly? Check Freeswitch

Which environment to choose?

To set up Asterisk, several solutions are available:

  • Install a bare Linux distro, and install the whole shebang from source code (recommended)
  • Install a bare Linux distribution that supports RPM or other packagers, and install the required components through this package in binary form. Red Hat RPM packages for Asterisk and the driver modules can be obtained from http://www.macvoip.com or from http://www.n2net.net
  • "Engineered by Digium in conjunction with rPath, Pound Key includes all the Linux components necessary to run, debug and build Asterisk, and only those components. You no longer have to worry about kernel versions and package dependencies. Unlike other Linux distributions used to deploy Asterisk, no unnecessary components that might compromise security or performance are included." AstLinux is also a bundled version of Linux and Asterisk, but optimized for small format hardware platforms
  • (Important: You might want to take a deep look at whether you want to use a commercial Asterisk) Use the TrixBox distribution (previously Asterisk@Home) that aims to do the same thing as Pound Key. Ideal for newbies, but requires a second host since, on purpose, it must be managed through a web interface but doesn't have X (Lynx could do the job, I guess). I don't like A@H because it hides the internals (hence, not a good tool to learn how Asterisk works), and installs a lot of stuff that is probably useless for a home solution (SugarCRM, etc.)

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

Like a lot of people, I had very bad experience with clone X101P (glorified voice softmodems). Some have got them working OK (check www.x100p.com), but they're probably very country-specific (impendance.)

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

Some experienced people say that external boxes (ie. SIP gateways) that do FXO/SIP aren't always that great either, especially lower-end models. They recommend against Digium hardware, and use Sangoma instead. Bottom line: Make sure you can return the product in case it doesn't work OK with your setup.

10mn Guide to a basic, private server

By "private", I mean that we will not use a VoIP gateway (as a PCI card, a stand-alone VoIP gateway like the Linksys SPA-3102, or an external VoIP provider), and just use two SIP phones instead:

  1. Download the dependencies:

    ncurses, and associated -devel
    openssl, and associated -devel
    libssl-dev (same as openssl?)
    zlib, and associated -devel
    bison, and associated -devel (1.0.X only)
    libnewt-dev (to compile Zaptel's zttool utility)
    zlib1g-dev
    initrd-tools
    procps

    On a Debian/Ubuntu server, I've seen this recommended:

    apt-get -y install build-essential libncurses5-dev libcurl3-dev libvorbis-dev libspeex-dev unixodbc unixodbc-dev libiksemel-dev linux-headers-`uname -r` libnewt-dev

  2. Download and untar the Asterisk and add-on source code (update the version number as needed):

    cd /usr/src
    wget http://downloads.digium.com/pub/asterisk/asterisk-1.4-current.tar.gz
    wget http://downloads.digium.com/pub/asterisk/asterisk-addons-1.4.3.tar.gz

    tar xzvf asterisk-1.4-current.tar.gz
    tar xzvf asterisk-addons-1.4.3.tar.gz

  3. Compile Asterisk:

    cd /usr/src/asterisk-1.4.2
    make clean
    ./configure
    make
    make install
    make samples
    make config

  4. Compile the add-on's

    cd /usr/src/asterisk-addons
    make clean
    ./configure
    make
    make install
    make samples

  5. Launch Asterisk to check that it works:

    cd /usr/sbin
    asterisk -vvvvc
    "stop now" to quit
     
  6. 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

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

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

    vim extensions.conf:
    [others]

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

  7. Launch Asterisk, and connect to its console:

    safe_asterisk
    asterisk -r ("quit" to exit)

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

http://downloads.digium.com/pub/telephony/sounds/ ?

modprobe ztdummy? Looks like not needed with Linux 2.6

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

  • /etc/asterisk/
  • /etc/zaptel.conf (not part of Asterisk, so located outside /etc/asterisk/)
  • /usr/lib/asterisk/modules/
  • /var/lib/asterisk/
  • /var/spool/asterisk/
  • /var/run/
  • /var/log/asterisk/

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

Important configuration files are:

  • zaptel.conf
  • zapata.conf
  • extensions.conf
  • sip.conf
  • iax.conf

Here's how to reload those files for changes to take effect:

  • zaptel.conf file: /sbin/ztcfg –vv
  • zapata.conf: requires a reload from the Asterisk console; however,changing signaling methods requires a restart.
  • chan_iax2.so: reload
  • chan_sip.so: reload

Tips to compile Asterisk

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

  • Set a hostname, eg. "sip" or "sip.acme.com" (but make sure it can actually be resolved)
  • Install Linux, including development tools (GCC, ncurses, openssl, zlib, bison, kernel sources)
  • Libpri is only needed if you have a PCI ISDN card
  • Zaptel is only needed if you have a PCI Analog card, ie. to connect the PC to an analog telephone line through an FXO port
  • Check that your motherboard supports at least PCI 2.2, and that it lets you assign an IRQ to a given PCI slot. These cards generate huge amounts of interrupts during use, and any conflict with other devices will result in jittery voice and overall poor performance (Why is my card getting an IRQ miss?)

    Look in /proc/interrupts to ensure that wcfxo has an IRQ all to itself. If it is sharing an IRQ, move the card to a different PCI slot and see if that resolves the conflict. Read Asterisk PCI bus Troubleshooting
  • Once the board is installed, boot up, and run "dmesg" and "lspci -v" to check that Linux detected it
  • The Zapata channel module, chan_zap.so, is used by to communicate with the Linux kernel, where the drivers for the hardware are loaded. The Zaptel interface is a kernel loadable module that presents an abstraction layer between the hardware drivers (eg. wctdm, wcfxo) and the Zapata module in Asterisk (ie. chan_zap.so -> Zaptel module /dev/zap -> wcfxo -> FXO card.) While Asterisk itself compiles on a variety of platforms, the Zaptel drivers are Linux-specific — they are written to interface directly with the Linux kernel
  • Newer distros rely on devfs and the udev daemon to create device nodes dynamically. If yours uses those tools, check its documentation on how to add Zaptel (eg. editing /etc/udev/rules.d/50-udev.rules)
  • cat /proc/zaptel/*
  • ztcfg reads /etc/zaptel.conf to configure channel(s)
  • to load zaptel, you just need to edit zaptel.conf, load wcfxo, and run ztcfg : modprobe wcfxo ; ztcfg -vv
  • wcfxo and zaptel modules: The order of execution of these commands is important, because voice channels are numbered in the same order their interface cards are enabled. For instance, if you had two X100P cards installed or a TDM400P with two FXO modules, you would have two logical voice channels. To check that those two modules were loaded successfully, run "lsmod | grep (zaptel|wcfxo)" (or wctdm instead of wcfxo).

    zaptel drivers are installed in  /lib/modules/'uname -r'/misc (eg. tor2.o torisa.o wcfxo.o wcfxs.o wcfxsusb.o wct1xxp.o wcusb.o zaptel.o ztd-eth.o ztdummy.o ztdynamic.o).
  • "One other package you may want to install is asterisk-sounds. While Asterisk comes with many sound prompts in the main source distribution, the asterisk-sounds package will give you even more. If you would like to expand the number of professionally recorded prompts for use with your Asterisk system, this package is essential."
  • The asterisk-addons package contains code to allow the storage of Call Detail Records (CDRs) to a MySQL database and to natively play MP3s, as well as an interpreter for loading Perl code into memory for the life of an Asterisk process. Programs are placed into asterisk-addons when there are licensing issues preventing them from being implemented directly into the Asterisk source code, or when they are not yet ready for primetime.
  • /var/log/asterisk/messages
  • "zap show channels" in the Asterisk console
  • Reloading after making changes:

    zaptel.conf: run "ztcfg -vv"
    zapata.conf: "reload" from the Asterisk console (or use asterisk -rx "reload" to execute the command directly)
    sip.conf and iax.conf: "reload chan_sip.so" and "reload chan_iax2.so" from the Asterisk console
    extensions.conf: "reload" from the Asterisk console
  • If you have problems using SIP phones, make sure that your SIP client is using the G.711 codec (either alaw or ulaw) as that is a codec that is known to work with Asterisk
  • "The s extension will only be selected when a call enters a context without a target extension defined. Imagine a ZAP channel (regular phone line), it rings, asterisk answers but it has no idea what the target extension will be so it throws it into s.  Why doesn't this work with SIP? When a SIP packet comes in, it has the target extension in the packet so instead of sending it to s it tries to send the call to the target extension. If the target extension can't be matched it sends a not found back to the SIP phone, basically telling you you dialed a wrong number."
  • In extensions.conf, add NoOp() in context to know where it fails
  • Optimization can be done through the Zaptel and Asterisk configuration files (eg. CONFIG_ZAPTEL_MMX is not AMD-friendly, etc.)
  • Before recompiling Asterisk, remove all files under /usr/lib/asterisk/modules

Trimming it down

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

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

  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
    ./configure
    make clean
    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. 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 //channel=>1? Must match channel # in zaptel.conf
  9. Activate Zaptel: ztcfg -vv
  10. 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"
  11. Recompile and reinstall Asterisk
  12. 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
    exten => s,1,Answer( )
    exten => s,2,Echo( )

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.

zttest?

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?

Adding a Linksys VoIP gateway

See this.

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 ${ }, such as STRFTIME in your second example."

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

 

Tips & Tricks

  • Do not put spaces before and/or after a "=" sign:

    exten => 999,1,Set(CALLERIDNUM=${CALLERID(num)})

    ;BAD exten => 999,n,Set(CALLERIDNAME = ${DB(cidname/${CALLERIDNUM})})
    exten => 999,n,Set(CALLERIDNAME=${DB(cidname/${CALLERIDNUM})})

    exten => 999,n,Verbose(CID is ${CALLERIDNAME})
     
  • GosubIf/Return: Pay attention to the fact that Return doesn't send us back to the GosubIf() line but rather the line that follows it:

    exten => 777,1,GosubIf($["${CALLERID(num)}" = "101"]?setcallerid,1:ok,1)
    exten => 777,n,Verbose(This is where Return sends us)
    exten => 777,n,Hangup

    exten => setcallerid,1,Set(CALLERID(num)=123)
    exten => setcallerid,n,Verbose(Before Return)
    exten => setcallerid,n,Return

    exten => ok,1,Verbose(We never see this...)
  • Different ways to generate a new filename dynamically

    exten => _[1_4],n,Set(RANDNAME=${RAND()});
    exten => _[1-4],n,Record(/tmp/msg${RANDNAME}.wav,3,30);

    ;${RECORDED_FILE} contains full path to file, eg. /tmp/msg1
    exten => _[1-4],n,Record(/tmp/msg%d.wav,3,30)
    exten => _[1-4],n,Verbose(Fichier = ${RECORDED_FILE}.wav)

    exten => _[1-4],n,Set(CALLTIME=${STRFTIME(${EPOCH},,%d-%b-%Y-%Hh%M)})
    exten => _[1-4],n,Record(/tmp/${CALLTIME}.wav,3,30)
  • WAV files must be converted to sample rate 8KHz in mono: In Linux, you can use sox to do this:

    sox input.wav -r 8000 -c 1 -s -w output.wav resample -ql

    Asterisk 1.4 added a CLI command to convert sound files from one format to another:

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

    Shell script equivalent:

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

Asterisk as an IVR

  • How does Asterisk know which file format a sound file is in? exten => 9999,n,Playback(/root/asterisk_sound_files/test_asterisk)
  • What minimum configuration files does Asterisk to run?
  • Should I use extensions.conf or extensions.ael?

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

  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:

  • core show file formats
  • core show translation ("Translation times between formats (in milliseconds) for one second of data")

Writing AGI scripts

In addition to internal commands like Answer or Hangup, the dialplan can also run external scripts through the AGI interface. Once Python is installed in Linux, here's how to write one in Python:

#! /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?
    }
?>

Adding Music on Hold

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.

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

"The Asterisk source contains a very important file named SECURITY, which outlines several steps you should take to keep your Asterisk systemsecure. It is vitally important that you read and understand this file. If you ignore the security precautions outlined there, you may end up allowing anyone and everyone to make long-distance or toll calls at your expense!"

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:

  • iax debug: Enable IAX debugging
  • mgcp debug: Enable MGCP debugging
  • reload: Reload configuration files
  • restart when convenient: Restarts Asterisk when all calls are gone
  • show agi: Displays AGI commands
  • show applications: Shows all Asterisk apps
  • show application <app>: Shows usage of a specific Asterik app
  • show channels: Shows all active channels
  • show channel <channel>: Shows information on a specific channel
  • sip debug: Enable SIP debugging
  • stop now: Stops Asterisk immediately

"Asterisk The Future of Telephony.pdf"

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

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

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

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

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

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

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

Playing with /etc/asterisk/extensions.conf

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

Contexts

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

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

Extensions

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

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

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

A complete extension is composed of three components:

  • The name (or number) of the extension,
  • The priority (each extension can include multiple steps; the step number is called the “priority”), and
  • The application (or command) that performs some action on the call.

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

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

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

exten => 123,1,Answer( )
exten => 123,n,do something
exten => 123,n,do something else
exten => 123,n,do one last thing
exten => 123,n,Hangup( )

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

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

[incoming]
exten => s,1,Answer()
exten => s,2,Playback(/home/john/sounds/filename)
exten => s,3,Hangup()

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

[incoming]
exten => s,1,Answer( )
exten => s,2,Background(enter-ext-of-person)
 
exten => 1,1,Playback(digits/1)
exten => 1,2,Goto(incoming,s,1)
 
exten => 2,1,Playback(digits/2)
exten => 2,2,Goto(incoming,s,1)
 
exten => i,1,Playback(pbx-invalid)
exten => i,2,Goto(incoming,s,1)
 
exten => t,1,Playback(vm-goodbye)
exten => t,2,Hangup( )

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

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

exten => 123,1,Dial(Zap/1,10)
 
exten => 123,2,Playback(vm-nobodyavail)
exten => 123,3,Hangup( )
 
exten => 123,102,Playback(tt-allbusy)
exten => 123,103,Hangup( )

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

[incoming]
exten => s,1,Answer()
exten => s,2,Background(enter-ext-of-person)
 
exten => 101,1,Dial(Zap/1,10)
exten => 101,2,Playback(vm-nobodyavail)
exten => 101,3,Hangup( )
exten => 101,102,Playback(tt-allbusy)
exten => 101,103,Hangup( )
 
exten => 102,1,Dial(SIP/Jane,10)
exten => 102,2,Playback(vm-nobodyavail)
exten => 102,3,Hangup( )
exten => 102,102,Playback(tt-allbusy)
exten => 102,103,Hangup( )
 
exten => i,1,Playback(pbx-invalid)
exten => i,2,Goto(incoming,s,1)
 
exten => t,1,Playback(vm-goodbye)
exten => t,2,Hangup( )

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

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

  • Answer()
  • Playback()
  • Hangup()
  • Background(): Plays a recorded sound, interrupts it when the caller presses a key (or series of keys) on his telephone keypad to go to the extension that corresponds with the pressed digit(s)
  • Goto(context,extension,priority): Sends the call to another context, extension, and priority.
  • Dial(destination,timeout,r): The third argument stands for "ringback", and forces Asterisk to play a ringing tone although it will always play one while trying to establish a channel with the destination. The third argument of Dial() actually modifies the behavior of this application; Check the reference manual for a list of possible options. Some options can be left out, eg. Dial(Zap/1,,r) to keep Asterisk ringing an extension with no timeout
  • SayDigits(${EXTEN}): To have Asterisk read digits back
  • Congestion(): To play a fast busy signal

From "Asterisk: A Bare-Bones VoIP Example"

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

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

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

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

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

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

  • sip.conf (this defines the SIP peers, which are the software or hardware SIP phones),
  • extensions.conf (this is where the dialplans are kept -- the meat of the system), and
  • voicemail.conf (where we define the voice mailboxes for each user).

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

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

  • ($100) Wildcard X100P: Single-Port FXO PCI interface card for interfacing with a standard analog phone line
  • Wildcard TDM400P: Quad-Station FXS half-length PCI card which supports standard analog and ADSI telephones for SOHO (Small Office Home Office) applications
  • FXO Module: FXO Module for use with the Wildcard TDM400P
  • FXS Module: FXS Module for use with the Wildcard TDM400P

Some kits are available:

  • Asterisk Developer's Kit (TDM) (Includes one FXO card to connect an analog line, and one single-port card to connect an analog phone; PC must run Linux since Asterisk is Linux-only)
  • Asterisk Dev Kit PCI (Same as above, but don't understand difference with the TDM version)
  • Asterisk Developer's Kit (LITE) (Same as above, except the single-port card is replaced with a USB device)

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

Asterisk consists of the following bits and pieces:

  • Asterisk: the core project to turn a PC into a PBX
  • Zaptel: Kernel interface device drivers for Analog and Digital interface cards. If you are using Digium hardware you will need to download zaptel. ("The Zapata Telephony project led to the development of open source device drivers for a range of telephony interfaces. Zaptel is Digium's revolutionary Pseudo-TDM engine for Linux") Short for "Zapata Telephony". Zaptel refers to Jim Dixon's open computer telephony hardware driver API. Zaptel drivers were first released for BSD and Jim's Tormenta series of DIY T1 interface cards. Digium later produced interface cards from Jim's designs and improved the Zaptel drivers on the Linux platform. Digium then added further drivers also following the Zaptel API for other telephony hardware.
  • Asterisk-Addons: various modules and addons
  • Asterisk-Sounds: Default IVR files and miscellaneous sound files
  • Libiax: Library for the Inter-Asterisk eXchange (IAX) protocol. Libiax provides a foundation for the development of IAX clients
  • Libpri: Primary Rate ISDN (PRI) library for T1/E1/J1 interfaces

Compact and/or Solid-state Asterisk

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

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

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

http://www.linuxdevices.com/news/NS3749020799.html

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

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:

  • Running a syslog-ng server, and have Asterisk and all SIP devices send debug information to it
  • Running a packet sniffer on the Asterisk server: WireShark (ex-Ethereal) is available in both GUI and text-mode versions, and undestands SIP, TCPDump is a text-mode sniffer and can save dumps that can be analyzed by Wireshark

    #192.168.0.253 is a VoIP gateway
    tcpdump host 192.168.0.253 not port 56051 #to filter out connections to syslog server
     
  • Launch the Asterisk console, and type "sip debug". To turn it off, "sip no debug"
  • If you're having problems calling into Asterisk from a remote location with firewalls in the way, add an extension that will echo back what you say:

    exten => 111,1,Answer()
    exten => 111,2,Playback(welcome)
    exten => 111,3,Playback(demo-echotest)
    exten => 111,4,Echo()
    exten => 111,5,Playback(demo-echodone)
    exten => 111,6,Playback(vm-goodbye)
    exten => 111,7,Hangup()

    If you can't hear the voice, make sure that either the IP phone is either set to use STUN, or that you forced it to use a specific UDP port (eg. 5004, and 5005 for a GrandStream phone) and opened those ports on the router.
  • Strings to look for when running "sip debug":
    Peer audio RTP
    We're at
    m=audio
  • "IP address or Domain name of Outbound Proxy, or Media Gateway, or Session Border Controller. Used by ATA for firewall or NAT penetration in different network environment. If symmetric NAT is detected, STUN will not work and ONLY outbound proxy will provide solution for it."
  • Launch asterisk with maximum verbosity "asterisk -vvvvvgd &"

A phone is marked as UNREACHABLE

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

[general]
...
externip = the.router.s.public.address
localnet=192.168.0.0/255.255.0.0
nat=yes
canreinvite=yes

Hardware not detected

  • For PCI cards, make sure they're not sharing IRQs with other cards
  • Check that the power supply is strong enough
  • Start in runlevel 3, ie. no X
  • Recompile zaptel and asterisk
  • Use a more recent PC
  • Check length of cable between FXO and wall plug
  • Check signal level: ztmonitor <channel number> -v ("gives you a visual representation of the sound strengths and makes it easy to see if the receive or transmit signals are too high or out of balance")
  • try turning off call progress detection
  • try fxotune
  • adjust gain levels

Fails compiling zaptel

  • Check that the kernel sources match the kernel you are running (cat /proc/version to check the kernel version; next, go to /usr/src/ to check which version of the kernel sources are available, if any)
  • Check that the version of gcc installed is the same that was used to compile the kernel (cat /proc/version to check which version was used to compile it; gcc -v to check which version is installed)
  • Check that all the required dependencies are installed, and can be found
  • "You may have to do a "make prepare" in the kernel source directory before you compile zaptel"
  • Fedora 5 ships with a bug in the kernel sources. You should run "yum search kernel", and download (yum update) the latest kernel and kernel sources for your architecture. Make sure both are for the same architecture: If you mix them (eg. i586 and i686, you'll get an error when loading the zaptel module: "FATAL: Error inserting zaptel (/lib/modules/2.6.17-1.2139_FC5/misc/zaptel.ko): Invalid module format", along with this error in dmesg: "zaptel: disagrees about version of symbol struct_module".) Reboot with the new kernel

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

    More information: http://forums.fedoraforum.org/showthread.php?t=115233,  http://forums.digium.com/viewtopic.php?t=7061 and Asterisk Zaptel Installation

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.

Caller ID

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

Q&A

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:

  • to display all entries for a family: database show cidname
  • to display the value that matches a key: database get cidname 1234567
  • to remove all entries in one "family" (ie. group): database deltree cidname

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.

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 part 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.For such servers, you should consider either...

  • full-fledged boards like those from Digium, Dialogic, etc.
  • FXO-SIP boxes like Sipura's SPA-3000, which connect to the POTS on one end, and to your LAN on the other end. This is the kind of connector that is required when using sipX, the other open-source PBX project. FYI, Sipura used to be an independent company, before being bought by Linksys, which is itself now part of Cisco
  • ISDN, either BRI or PRI. Users report having much less problems using an ISDN connection than an analog connection (caller ID, detecting remote-end hang-ups, etc.)
  • Don't use any connection to the POTS at all, and take a subscription to a VoIP provider. It is highly recommended that you still keep a connection to the phone network (either ISDN or analog) as a backup (911, etc.)

FXO or ISDN?

"En fait, evite a tout prix les x100p - la qualite est degeulasse sur le reseau Francais du a une difference d'impedance (et il ne faut pas oublier qu'a la base c'est un modem...).

Avec les TDM400P et autre cartes analogique comme celle cite ci dessus, la qualite est du niveau d'une ligne analogique, acceptable mais vu qu'en France les lignes numeris coutent pour les professionels le meme prix que les ligne analogiques, il ne faut pas s'en priver! (Ligne Analogique : 16.80 EUR H.T./Mois, Acces de base isole (2 lignes) : 33.60 EUR H.T./Mois, presentation du numero et du nom comprise - tu as aussi numeris duo qui est la meme chose que l'acces de base isole avec un numero en + et un adaptateur analogique (pratique pour le fax))

L'ISDN (Numeris) est parfait pour tout ce qui est suivi d'appel, on peut voir sans problemes le status de la ligne (100, 183 call in progess etc.) et gerer ca correctement, avec l'analogique, c'est une autre histoire. De plus la qualite est bien meilleur, sur une connection numerique de bout en bout (ISDN vers ISDN ou ISDN vers VoIP ou VoIP vers ISDN), la qualite est generalement excelente)."

Echo cancellation?

"Evite la x100p et desactive l'annulateur d'echo de la Freebox qui est une merde (prefix annulateur: 3699). Active l'annulateur d'echo au niveau d'asterisk."

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

X100P vs. X101P?

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

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

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

Which FXO PCI card?

> LOL!  I know that feeling... I actually thought I would save money with VOIP, what a joke!  Actually I am happy with my setup,  but spent an intial $75(us) thinking the HT-488 would provide an FXO for my PSTN connection, only to find it doesn't work well enough to actually use for that.

> I then spent an additional $200(us) for the Wellgate 3701a (1FXS+1FXO) which, although horribly documented is a HUGE improvement over the Grandstream garbage (HT-488).

> So yeah,  it gets expensive quickly.  It's annoying that so many of the products are marginal or straight up garbage,  but I guess we are still in the infancy of the standards based VOIP business, and many of the products are in search of a firmware update, or a decent manual.

 

I've gone through the same basic devices over the last three years, but  have also tested the Mediatrix 1204 box as well.


I've got four analog pstn lines here coming from two different central offices, both of which are on relatively long loops with somewhat unusual echo characteristics. I have also gone through the spa3000, ht488, x100p's, multiple h/w versions of the TDM04b, etc. Also have a TDM2400 here for testing, but testing has been held up due to delays in being able to run current trunk code on the test machine.


To date, the best devices from a "quality of audio" perspective are the Mediatrix 1204 and the Sangoma A200D. The last time I worked with the 1204 was about two years ago and the box had several compatibility and security issues that hopefully have been resolved since then. Its retail price is higher then the A200D (in the US). The A200D has been in use now for several months and has provided excellent audio (etc), supports

modem use (fax and POS), and just hasn't failed in any way.


Rumor has it that Digium will be announcing some new cards in the near future that should also help address the space for small numbers of analog pstn lines. Unknown as to what the current status happens to be.

The Echo can in the Wellgate 3701a is clearly much better then the Grandstream one,  but it still takes some number of seconds to train at the beginning of calls, which is kind of funky.

Resources

Tools

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

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值