Asterisk PBX Notes

Contents

Introduction to these notes

This is nowhere near an exhaustive treatise on Asterisk. I wrote these notes while learning enough about Asterisk to do something that FreePBX doesn’t seem to do: whitelisting callers. I needed a handler that would allow me to send calls from known CIDs directly to an extension, and send calls from unknown CIDs to an AVR (automated voice response) script.

As such these notes are incomplete in many areas because I didn’t see the need to learn much about them, being as they were outside the scope of the whitelist project. For example, I have some detail on Dialplan and AGI (Asterisk Gateway Interface) because those are what I used, but I merely mention ARI (Asterisk REST Interface) because it didn’t need it.

I’m also an experienced programmer, so I made only enough notes to get an understanding of how Asterisk Dialplan works. For complete reference information you’ll need to visit the Asterisk Documentation Wiki.

These notes are based on Asterisk 16. As of January 2020, Asterisk 17 is available but was not part of FreePBX.

Dialplan notes

The original idea behind the Asterisk dialplan was a channel would be linked to a context. Within that context there would be extension numbers requested by the caller using the channel. Depending on the extension and a priority, Asterisk would run an application. The order of matching within a context is always exact extensions (with the special extension s getting top priority,) pattern match extensions, “include” statements, and “switch” statements (a switch statement permits a server to share the dialplan with another server.)

The original concept has expanded to the point where contexts are now like subroutines and extensions within a context are now akin to statements in a progamming language.

Contexts are introduced as follows:

[context-name]

Statements use a format as follows:

exten => text,priority,application(parameter[,parameter ...])
 same => n,application(parameter[,parameter ...])
 same => n,application(parameter[,parameter ...])
 ...
  • exten is typically required, but same can be used on subsequent lines
  • text was originally an extension number, but it can also be arbitrary text or one of the following:
    • a - assistant extension
    • e - exception catchall
    • h - hangup
    • i - invalid entry, when the dialled digits aren’t understood or an invalid target was specified in a Goto or Gosub
    • o - operator extension
    • s - start extension, originally used when a call came in on an analogue line, now often used in subroutine-like contexts
    • t - response timeout extension
    • T - Absolute timeout extension
    • fax - used if Asterisk determines a call is an incoming fax
    • A pattern match starting with _ and consisting of the digits 0-9, the telephone keypad symbols # and *, and the characters X, Z, and N: X means 0-9, Z is 1-9, and N is 2-9
    • _.! - Wildcard extension; matches everything
    • Arbitrary text. Because Asterisk can’t match text to an extension number, these statements will not be executed unless jumped to by a “Goto”.
  • application is (typically) a function exported from one of the modules described later in these notes:
    • Dialplan Application Modules
    • Dialplan Function Modules
    • Resource Modules
    • AGI (Asterisk Gateway Interface, for user written functions)

Flow control within a context is handled by the priority. Every time an extension and priority is executed and completes, Asterisk searches for the next best match in priority sequence.

  • The first extension (statement) in any context gets priority 1
  • Following extensions (statemnts) typically get priority n (“next”)
  • A priority like n(word) applies the label word to the priroity
  • Regular dialplan flow can be altered using Gosub and Goto. There is also a Macro keyword, but it’s considered deprecated and should not be used,

Contexts can include other contexts for the dialplan to search by using:

include => context-name

Includes are considered only after Asterisk has exhausted exact extension numbers and wildcard numbers, so it doesn’t matter where in the context the include statement is placed.

Dialplan language notes

  • Variables are declared and given a value using Set
      exten => 1,n,Set(vaname=value)
      exten => 1,n,Set(TextVar="This is a test")
  • Like C, variable names are case-sensitive. COUNT and Count are different variables.
  • There are global variables and channel variables. As the name implies, channel variables are scoped to the channel (not to the context.) So a variable like COUNT in a given context can have different values for two calls being handled on a trunk, in the same way a variable can have two different values in a subroutine running in separate threads.
  • Most channel variables disappear when a new channel is created from an existing one. There are two exceptions to this:
    • _VAR will be seen in the new channel as VAR (the leading “_” is removed)
    • __VAR will be seen in the new channel as __VAR
  • Like the shell, a $ prefix is used to get a variable’s value, but uses the ${VAR} syntax and not the simpler $VAR syntax.
  • Also like the shell, \${VAR} does not expand VAR, it’s seen by Asterisk as “dollar-sign open-brace V A R close-brace”
  • Similar to the shell, Asterisk variables can be associative arrays; these are referenced using ${VAR(key-name)} (note that “–” is valid here)
  • Asterisk sometimes strips quote marks; this may have side-effects like an expansion suddenly happening when you don’t expect it to.
  • More or less like the bash shell:
    • ${VAR:i:j} returns a substring of VAR starting at i (zero-based) for length j
    • ${VAR:-4} returns the last 4 characters
    • ${VAR:0:-1} removes the last character from VAR
    • ${VAR:-7,3} returns 3 characters from VAR starting at 7 from the end
  • Other string operations can be done using one of the dialplan operators or an AGI script
  • Similar to the shell’s eval "text", $[TEXT] evaluates TEXT and returns the result. This syntax is seen mostly in the following places:
    • String and numeric tests
    • Calls to applications and functions within ExecIf/GosubIf/GotoIf that return true or false
  • Like the shell, enclosing a variable reference in double quotes ("${VAR}") within a $[ ... ] evaluation protects against expansion errors cause by spaces in the value of VAR
  • ExecIf/GosubIf/GotoIf equality tests use “=” and not==
  • Targets for Gosub/Goto/GosubIf/GotoIf can be one of the following:
    • priority - jump to the numbered or named priority in the current context
    • context,priority - jump to the numbered or named priority in the specified context
    • context,extension,priority - jump to the numbered or named priority in the extension named in the specified context
  • Be careful when specifying targets. If Asterisk can’t find a target, it will do one of the following:
    • Go to the i (invalid) extension in the current context
    • Failing that, go to the h (hangup) extension in the current context
    • Failing that, hang up the channel

Dialplan operators

In addtion to calling applications and functions exported the function and resource modules, text inside the $[ ... ] evaluation function can contain the following operators:

Operator Description
expr1 | expr2 Return the evaluation of expr1 if it is neither an empty string nor zero, else return the evaluation of expr2
expr1 & expr2 Return the evaluation of expr1 if neither expression evaluates to an empty string or zero, else return zero
expr1 {=, >, >=, <, <=, !=} expr2 Comparisons; expressions that return a value consisting only of digits are compared as double-precision values, else they are compared as strings
expr1 {+, |, *, /, %} expr2 Add, subtract, multiply, divide, remainder
- expr Subtract value from zero
! expr Negate. ! empty-string returns 1 (true)
expr1 : expr2 Match expr1 against PCRE-style regular expression expr2 anchored at the start of expr1. On success returns 1 or the value of the first parenthesized sub-expression. Strips double-quotes from expr1.
expr1 ~= expr2 Same as “:” but without the anchor at start
expr1 ? expr2 : expr3 Ternary operation. Note that expr3 is always evaluated, so even if expr1 is true expr3 will be evaluated, which may cause issues if expr3 does a variable assignment (so don’t to that!)
expr1 ~~ expr2 concatenation: returns expr1 and expr2 joined together
Math functions COS(x) SIN(x) TAN(x) ACOS(x) ASIN(x) ATAN(x) ATAN2(x,y) POW(x,y) SQRT(x) FLOOR(x) CEIL(x) ROUND(x) RINT(x) TRUNC(x) REMAINDER(x,y) EXP(x) EXP2(x) LOG(x) LOG2(x) LOG10(x)

Standard Dialplan channel variables

In the following table, (ro) indicates a read-only variable.

Channel variable Description
{AGIEXITONHANGUP} Set to 1 to force the behavior of a call to AGI to behave as it did in 1.4, where the AGI script would exit immediately on detecting a channel hangup
{BLINDTRANSFER} The name of the channel on the other side of a blind transfer
{BRIDGEPEER} Bridged peer
{BRIDGEPVTCALLID} Bridged peer PVT call ID (SIP Call ID if a SIP call)
{CALENDAR_SUCCESS} (ro) Status of the CALENDAR_WRITE function. Set to 1 if the function completed successfully; 0 otherwise.
{CALLERID(all)} Caller ID
{CALLERID(ani2)} (ro) ANI2 (Info digits) also called Originating line information or OLI
{CALLERID(ani)} (ro) Caller ANI (PRI channels)
{CALLERID(dnid)} (ro) Dialed Number Identifier
{CALLERID(name)} Caller ID Name only
{CALLERID(num)} Caller ID Number only
{CALLERID(rdnis)} (ro) Redirected Dial Number ID Service
{CALLINGANI2} (ro) Caller ANI2 (PRI channels)
{CALLINGPRES} (ro) Caller ID presentation for incoming calls (PRI channels)
{CALLINGTNS} (ro) Transit Network Selector (PRI channels)
{CALLINGTON} (ro) Caller Type of Number (PRI channels)
{CDR(accountcode)} (ro) Account code (if specified)
{CHANNEL} (ro) Current channel name
{CONTEXT} (ro) Current context
{DATETIME} (ro) Current date time in the format: DDMMYYYY-HH:MM:SS (Deprecated; use {STRFTIME(${EPOCH},,%d%m%Y-%H:%M:%S)} instead)
{DB_RESULT} Result value of DB_EXISTS() dial plan function
{DYNAMIC_FEATURENAME} The name of the last triggered dynamic feature
{DYNAMIC_PEERNAME} The name of the channel on the other side when a dynamic feature is used (removed)
{DYNAMIC_WHO_ACTIVATED} Gives the channel name that activated the dynamic feature
{ENTITYID} (ro) Global Entity ID set automatically, or from asterisk.conf
{ENV(VAR)} Environment variable VAR
{EPOCH} (ro) Current unix style epoch
{EXTEN} (ro) Current extension
{FORWARD_CONTEXT} Context for forwarded calls
{GOTO_ON_BLINDXFR} Transfer to the specified context/extension/priority after a blind transfer (use ^ characters in place of
{HANGUPCAUSE} (ro) Asterisk cause of hangup (inbound/outbound)
{HINTNAME} (ro) Suggested Caller*ID name for this extension
{HINT} (ro) Channel hints for this extension
{INVALID_EXTEN} The invalid called extension (used in the “i” extension)
{LANGUAGE} (ro) Current language (Deprecated; use {CHANNEL(language)})
{LEN(VAR)} String length of VAR (integer)
{PRIORITY} (ro) Current priority in the dialplan
{PRIREDIRECTREASON} Reason for redirect on PRI, if a call was directed
{SIP_RECVADDR} (ro) the address a SIP MESSAGE request was received from
{SYSTEMNAME} (ro) value of the systemname option of asterisk.conf
{TIMESTAMP} (ro) Current date time in the format: YYYYMMDD-HHMMSS (Deprecated; use {STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)})
{TRANSFER_CONTEXT} Context for transferred calls
{UNIQUEID} (ro) Current call unique identifier
{VOICEMAIL_PLAYBACKSTATUS} (ro) Status of the VoiceMailPlayMsg application. SUCCESS if the voicemail was played back successfully,
{<app>STATUS} (ro) Many dialplan applications return a status in the form of appnameSTATUS; see wiki page for details

In addition to the above list, several Asterisk modules supply their own variables. See the Wiki page for details.

Dialplan Applications

The following 200+ applications are made available to the Dialpan by the application modules listed below. This list is based on the Asterisk Wiki for Asterisk 16.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
AddQueueMember()                 Dynamically adds queue members.
ADSIProg()                       Load Asterisk ADSI Scripts into phone
AELSub()                         Launch subroutine built with AEL
AgentLogin()                     Login an agent.
AgentRequest()                   Request an agent to connect with the channel.
AGI()                            Executes an AGI compliant application.
AlarmReceiver()                  Provide support for receiving alarm reports from a burglar or fire alarm panel.
AMD()                            Attempt to detect answering machines.
Answer()                         Answer a channel if ringing.
AttendedTransfer()               Attended transfer to the extension provided and TRANSFER_CONTEXT
Authenticate()                   Authenticate a user
BackGround()                     Play an audio file while waiting for digits of an extension to go to.
BackgroundDetect()               Background a file with talk detect.
BlindTransfer()                  Blind transfer channel(s) to the extension and context provided
Bridge()                         Bridge two channels.
BridgeAdd()                      Join a bridge that contains the specified channel.
BridgeWait()                     Put a call into the holding bridge.
Busy()                           Indicate the Busy condition.
CallCompletionCancel()           Cancel call completion service
CallCompletionRequest()          Request call completion service for previous call
CELGenUserEvent()                Generates a CEL User Defined Event.
ChangeMonitor()                  Change monitoring filename of a channel.
ChanIsAvail()                    Check channel availability
ChannelRedirect()                Redirects given channel to a dialplan target
ChanSpy()                        Listen to a channel, and optionally whisper into it.
ClearHash()                      Clear the keys from a specified hashname.
ConfBridge()                     Conference bridge application.
Congestion()                     Indicate the Congestion condition.
ContinueWhile()                  Restart a While loop.
ControlPlayback()                Play a file with fast forward and rewind.
DAHDIAcceptR2Call()              Accept an R2 call if its not already accepted (you still need to answer it)
DAHDIRAS()                       Executes DAHDI ISDN RAS application.
DAHDIScan()                      Scan DAHDI channels to monitor calls.
DAHDISendCallreroutingFacility() Send an ISDN call rerouting/deflection facility message.
DAHDISendKeypadFacility()        Send digits out of band over a PRI.
DateTime()                       Says a specified time in a custom format.
DBdeltree()                      Delete a family or keytree from the asterisk database.
DeadAGI()                        Executes AGI on a hungup channel.
Dial()                           Attempt to connect to another device or endpoint and bridge the call.
Dictate()                        Virtual Dictation Machine.
Directory()                      Provide directory of voicemail extensions.
DISA()                           Direct Inward System Access.
DumpChan()                       Dump Info About The Calling Channel.
EAGI()                           Executes an EAGI compliant application.
Echo()                           Echo media, DTMF back to the calling party
EndWhile()                       End a while loop.
Exec()                           Executes dialplan application.
ExecIf()                         Executes dialplan application, conditionally.
ExecIfTime()                     Conditional application execution based on the current time.
ExitWhile()                      End a While loop.
ExtenSpy()                       Listen to a channel, and optionally whisper into it.
ExternalIVR()                    Interfaces with an external IVR application.
Festival()                       Say text to the user.
Flash()                          Flashes a DAHDI Trunk.
FollowMe()                       Find-Me/Follow-Me application.
ForkCDR()                        Forks the current Call Data Record for this channel.
GetCPEID()                       Get ADSI CPE ID.
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.
GotoIfTime()                     Conditional Goto based on the current time.
Hangup()                         Hang up the calling channel.
HangupCauseClear()               Clears hangup cause information from the channel that is available through
IAX2Provision()                  Provision a calling IAXy with a given template.
ICES()                           Encode and stream using 'ices'.
ImportVar()                      Import a variable from a channel into a new variable.
Incomplete()                     Returns AST_PBX_INCOMPLETE value.
IVRDemo()                        IVR Demo Application.
JabberJoin() - [res_xmpp]        Join a chat room
JabberLeave() - [res_xmpp]       Leave a chat room
JabberSend() - [res_xmpp]        Sends an XMPP message to a buddy.
JabberSendGroup() - [res_xmpp]   Send a Jabber Message to a specified chat room
JabberStatus() - [res_xmpp]      Retrieve the status of a jabber list member
JACK()                           Jack Audio Connection Kit
Log()                            Send arbitrary text to a selected log level.
Macro()                          Macro Implementation.
MacroExclusive()                 Exclusive Macro Implementation.
MacroExit()                      Exit from Macro.
MacroIf()                        Conditional Macro implementation.
MailboxExists()                  Check to see if Voicemail mailbox exists.
MeetMe()                         MeetMe conference bridge.
MeetMeAdmin()                    MeetMe conference administration.
MeetMeChannelAdmin()             MeetMe conference Administration (channel specific).
MeetMeCount()                    MeetMe participant count.
MessageSend()                    Send a text message.
Milliwatt()                      Generate a Constant 1004Hz tone at 0dbm (mu-law).
MinivmAccMess()                  Record account specific messages.
MinivmDelete()                   Delete Mini-Voicemail voicemail messages.
MinivmGreet()                    Play Mini-Voicemail prompts.
MinivmMWI()                      Send Message Waiting Notification to subscriber(s) of mailbox.
MinivmNotify()                   Notify voicemail owner about new messages.
MinivmRecord()                   Receive Mini-Voicemail and forward via e-mail.
MixMonitor()                     Record a call and mix the audio during the recording. Use of StopMixMonitor is
Monitor()                        Monitor a channel.
Morsecode()                      Plays morse code.
MP3Player()                      Play an MP3 file or M3U playlist file or stream.
MSet()                           Set channel variable(s) or function value(s).
MusicOnHold()                    Play Music On Hold indefinitely.
NBScat()                         Play an NBS local stream.
NoCDR()                          Tell Asterisk to not maintain a CDR for this channel.
NoOp()                           Do Nothing (No Operation).
ODBC_Commit()                    Commits a currently open database transaction.
ODBC_Rollback()                  Rollback a currently open database transaction.
ODBCFinish()                     Clear the resultset of a sucessful multirow query.
Originate()                      Originate a call.
OSPAuth()                        OSP Authentication.
OSPFinish()                      Report OSP entry.
OSPLookup()                      Lookup destination by OSP.
OSPNext()                        Lookup next destination by OSP.
Page()                           Page series of phones
Park()                           Park yourself.
ParkAndAnnounce()                Park and Announce.
ParkedCall()                     Retrieve a parked call.
PauseMonitor()                   Pause monitoring of a channel.
PauseQueueMember()               Pauses a queue member.
Pickup()                         Directed extension call pickup.
PickupChan()                     Pickup a ringing channel.
Playback()                       Play a file.
PlayTones()                      Play a tone list.
PrivacyManager()                 Require phone number to be entered, if no CallerID sent
Proceeding()                     Indicate proceeding.
Progress()                       Indicate progress.
Queue()                          Queue a call for a call queue.
QueueLog()                       Writes to the queue_log file.
QueueUpdate()                    Writes to the queue_log file for OutBound calls and updates Realtime Data. Is
RaiseException()                 Handle an exceptional condition.
Read()                           Read a variable.
ReadExten()                      Read an extension into a variable.
ReceiveFAX() - [app_fax]         Receive a Fax
ReceiveFAX() - [res_fax]         Receive a FAX and save as a TIFF/F file.
Record()                         Record to a file.
RemoveQueueMember()              Dynamically removes queue members.
ResetCDR()                       Resets the Call Data Record.
RetryDial()                      Place a call, retrying on failure allowing an optional exit extension.
Return()                         Return from gosub routine.
Ringing()                        Indicate ringing tone.
SayAlpha()                       Say Alpha.
SayAlphaCase()                   Say Alpha.
SayCountedAdj()                  Say a adjective in declined form in order to count things
SayCountedNoun()                 Say a noun in declined form in order to count things
SayDigits()                      Say Digits.
SayNumber()                      Say Number.
SayPhonetic()                    Say Phonetic.
SayUnixTime()                    Says a specified time in a custom format.
SendDTMF()                       Sends arbitrary DTMF digits
SendFAX() - [app_fax]            Send a Fax
SendFAX() - [res_fax]            Sends a specified TIFF/F file as a FAX.
SendImage()                      Sends an image file.
SendText()                       Send a Text Message on a channel.
SendURL()                        Send a URL.
Set()                            Set channel variable or function value.
SetAMAFlags()                    Set the AMA Flags.
SIPAddHeader()                   Add a SIP header to the outbound call.
SIPDtmfMode()                    Change the dtmfmode for a SIP call.
SIPRemoveHeader()                Remove SIP headers previously added with SIPAddHeader
SIPSendCustomINFO()              Send a custom INFO frame on specified channels.
SkelGuessNumber()                An example number guessing game
SLAStation()                     Shared Line Appearance Station.
SLATrunk()                       Shared Line Appearance Trunk.
SMS()                            Communicates with SMS service centres and SMS capable analogue phones.
SoftHangup()                     Hangs up the requested channel.
SpeechActivateGrammar()          Activate a grammar.
SpeechBackground()               Play a sound file and wait for speech to be recognized.
SpeechCreate()                   Create a Speech Structure.
SpeechDeactivateGrammar()        Deactivate a grammar.
SpeechDestroy()                  End speech recognition.
SpeechLoadGrammar()              Load a grammar.
SpeechProcessingSound()          Change background processing sound.
SpeechStart()                    Start recognizing voice in the audio stream.
SpeechUnloadGrammar()            Unload a grammar.
StackPop()                       Remove one address from gosub stack.
StartMusicOnHold()               Play Music On Hold.
Stasis()                         Invoke an external Stasis application.
StatsD()                         Allow statistics to be passed to the StatsD server from the dialplan.
StopMixMonitor()                 Stop recording a call through MixMonitor, and free the recording's file handle.
StopMonitor()                    Stop monitoring a channel.
StopMusicOnHold()                Stop playing Music On Hold.
StopPlayTones()                  Stop playing a tone list.
StreamEcho()                     Echo media, up to 'N' streams of a type, and DTMF back to the calling party
System()                         Execute a system command.
TestClient()                     Execute Interface Test Client.
TestServer()                     Execute Interface Test Server.
Transfer()                       Transfer caller to remote extension.
TryExec()                        Executes dialplan application, always returning.
TrySystem()                      Try executing a system command.
UnpauseMonitor()                 Unpause monitoring of a channel.
UnpauseQueueMember()             Unpauses a queue member.
UserEvent()                      Send an arbitrary user-defined event to parties interested in a channel (AMI
Verbose()                        Send arbitrary text to verbose output.
VMAuthenticate()                 Authenticate with Voicemail passwords.
VMSayName()                      Play the name of a voicemail user
VoiceMail()                      Leave a Voicemail message.
VoiceMailMain()                  Check Voicemail messages.
VoiceMailPlayMsg()               Play a single voice mail msg from a mailbox by msg id.
Wait()                           Waits for some time.
WaitDigit()                      Waits for a digit to be entered.
WaitExten()                      Waits for an extension to be entered.
WaitForNoise()                   Waits for a specified amount of noise.
WaitForRing()                    Wait for Ring Application.
WaitForSilence()                 Waits for a specified amount of silence.
WaitUntil()                      Wait (sleep) until the current time is the given epoch.
While()                          Start a while loop.

Functions

The following 180+ functions are exported to Asterisk by the function and resource modules listed below. This list is based on the Asterisk Wiki pages for Asterisk 16.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
AES_DECRYPT()                 Decrypt a string encoded in base64 with AES given a 16 character key.
AES_ENCRYPT()                 Encrypt a string with AES given a 16 character key.
AGC()                         Apply automatic gain control to audio on a channel.
AGENT()                       Gets information about an Agent
AMI_CLIENT()                  Checks attributes of manager accounts
ARRAY()                       Allows setting multiple variables at once.
AST_CONFIG()                  Retrieve a variable from a configuration file.
AST_SORCERY()                 Get a field from a sorcery object
BASE64_DECODE()               Decode a base64 string.
BASE64_ENCODE()               Encode a string in base64.
BLACKLIST()                   Check if the callerid is on the blacklist.
CALENDAR_BUSY()               Determine if the calendar is marked busy at this time.
CALENDAR_EVENT()              Get calendar event notification data from a notification call.
CALENDAR_QUERY()              Query a calendar server and store the data on a channel
CALENDAR_QUERY_RESULT()       Retrieve data from a previously run CALENDAR_QUERY() call
CALENDAR_WRITE()              Write an event to a calendar
CALLCOMPLETION()              Get or set a call completion configuration parameter for a channel.
CALLERID()                    Gets or sets Caller\*ID data on the channel.
CALLERPRES()                  Gets or sets Caller\*ID presentation on the channel.
CDR()                         Gets or sets a CDR variable.
CDR_PROP()                    Set a property on a channel's CDR.
CHANNEL()                     Gets/sets various pieces of information about the channel.
CHANNELS()                    Gets the list of channels, optionally filtering by a regular expression.
CHECKSIPDOMAIN()              Checks if domain is a local domain.
CONFBRIDGE()                  Set a custom dynamic bridge, user, or menu profile on a channel for the
CONFBRIDGE_INFO()             Get information about a ConfBridge conference.
CONNECTEDLINE()               Gets or sets Connected Line data on the channel.
CSV_QUOTE()                   Quotes a given string for use in a CSV file, escaping embedded quotes as
CURL()                        Retrieve content from a remote web or ftp server
CURLOPT()                     Sets various options for future invocations of CURL.
CUT()                         Slices and dices strings, based upon a named delimiter.
DB()                          Read from or write to the Asterisk database.
DB_DELETE()                   Return a value from the database and delete it.
DB_EXISTS()                   Check to see if a key exists in the Asterisk database.
DB_KEYS()                     Obtain a list of keys within the Asterisk database.
DEC()                         Decrements the value of a variable, while returning the updated value to the
DENOISE()                     Apply noise reduction to audio on a channel.
DEVICE_STATE()                Get or Set a device state.
DIALGROUP()                   Manages a group of users for dialing.
DIALPLAN_EXISTS()             Checks the existence of a dialplan target.
DUNDILOOKUP()                 Do a DUNDi lookup of a phone number.
DUNDIQUERY()                  Initiate a DUNDi query.
DUNDIRESULT()                 Retrieve results from a DUNDIQUERY.
ENUMLOOKUP()                  General or specific querying of NAPTR records for ENUM or ENUM-like DNS
ENUMQUERY()                   Initiate an ENUM query.
ENUMRESULT()                  Retrieve results from a ENUMQUERY.
ENV()                         Gets or sets the environment variable specified.
EVAL()                        Evaluate stored variables
EXCEPTION()                   Retrieve the details of the current dialplan exception.
EXISTS()                      Test the existence of a value.
EXTENSION_STATE()             Get an extension's state.
FAXOPT() - [res_fax]          Gets/sets various pieces of information about a fax session.
FEATURE()                     Get or set a feature option on a channel.
FEATUREMAP()                  Get or set a feature map to a given value on a specific channel.
FIELDNUM()                    Return the 1-based offset of a field in a list
FIELDQTY()                    Count the fields with an arbitrary delimiter
FILE()                        Read or write text file.
FILE_COUNT_LINE()             Obtains the number of lines of a text file.
FILE_FORMAT()                 Return the newline format of a text file.
FILTER()                      Filter the string to include only the allowed characters
FRAME_TRACE()                 View internal ast_frames as they are read and written on a channel.
GLOBAL()                      Gets or sets the global variable specified.
GROUP()                       Gets or sets the channel group.
GROUP_COUNT()                 Counts the number of channels in the specified group.
GROUP_LIST()                  Gets a list of the groups set on a channel.
GROUP_MATCH_COUNT()           Counts the number of channels in the groups matching the specified pattern.
HANGUPCAUSE()                 Gets per-channel hangupcause information from the channel.
HANGUPCAUSE_KEYS()            Gets the list of channels for which hangup causes are available.
HASH()                        Implementation of a dialplan associative array
HASHKEYS()                    Retrieve the keys of the HASH() function.
HINT()                        Get the devices set for a dialplan hint.
HOLD_INTERCEPT()              Intercepts hold frames on a channel and raises an event instead of passing the
IAXPEER()                     Gets IAX peer information.
IAXVAR()                      Sets or retrieves a remote variable.
ICONV()                       Converts charsets of strings.
IF()                          Check for an expresion.
IFMODULE()                    Checks if an Asterisk module is loaded in memory.
IFTIME()                      Temporal Conditional.
IMPORT()                      Retrieve the value of a variable from another channel.
INC()                         Increments the value of a variable, while returning the updated value to the
ISNULL()                      Check if a value is NULL.
JABBER_RECEIVE() - [res_xmpp] Reads XMPP messages.
JABBER_STATUS() - [res_xmpp]  Retrieves a buddy's status.
JITTERBUFFER()                Add a Jitterbuffer to the Read side of the channel. This dejitters the audio
KEYPADHASH()                  Hash the letters in string into equivalent keypad numbers.
LEN()                         Return the length of the string given.
LISTFILTER()                  Remove an item from a list, by name.
LOCAL()                       Manage variables local to the gosub stack frame.
LOCAL_PEEK()                  Retrieve variables hidden by the local gosub stack frame.
LOCK()                        Attempt to obtain a named mutex.
MAILBOX_EXISTS()              Tell if a mailbox is configured.
MASTER_CHANNEL()              Gets or sets variables on the master channel
MATH()                        Performs Mathematical Functions.
MD5()                         Computes an MD5 digest.
MEETME_INFO()                 Query a given conference of various properties.
MESSAGE()                     Create a message or read fields from a message.
MESSAGE_DATA()                Read or write custom data attached to a message.
MINIVMACCOUNT()               Gets MiniVoicemail account information.
MINIVMCOUNTER()               Reads or sets counters for MiniVoicemail message.
MIXMONITOR()                  Retrieve data pertaining to specific instances of MixMonitor on a channel.
MUTEAUDIO()                   Muting audio streams in the channel
ODBC()                        Controls ODBC transaction properties.
ODBC_FETCH()                  Fetch a row from a multirow query.
PARK_GET_CHANNEL()            Get the channel name of an occupied parking space in a parking lot.
PASSTHRU()                    Pass the given argument back as a value.
PERIODIC_HOOK()               Execute a periodic dialplan hook into the audio of a call.
PITCH_SHIFT()                 Pitch shift both tx and rx audio streams on a channel.
PJSIP_AOR()                   Get information about a PJSIP AOR
PJSIP_CONTACT()               Get information about a PJSIP contact
PJSIP_DIAL_CONTACTS()         Return a dial string for dialing all contacts on an AOR.
PJSIP_DTMF_MODE()             Get or change the DTMF mode for a SIP call.
PJSIP_ENDPOINT()              Get information about a PJSIP endpoint
PJSIP_HEADER()                Gets headers from an inbound PJSIP channel. Adds, updates or removes the
PJSIP_MEDIA_OFFER()           Media and codec offerings to be set on an outbound SIP channel prior to dialing.
PJSIP_MOH_PASSTHROUGH()       Get or change the on-hold behavior for a SIP call.
PJSIP_PARSE_URI()             Parse an uri and return a type part of the URI.
PJSIP_SEND_SESSION_REFRESH()  W/O: Initiate a session refresh via an UPDATE or re-INVITE on an established
POP()                         Removes and returns the last item off of a variable containing delimited text
PP_EACH_EXTENSION()           Execute specified template for each extension.
PP_EACH_USER()                Generate a string for each phoneprov user.
PRESENCE_STATE()              Get or Set a presence state.
PUSH()                        Appends one or more values to the end of a variable containing delimited text
QUEUE_EXISTS()                Check if a named queue exists on this server
QUEUE_GET_CHANNEL()           Return caller at the specified position in a queue.
QUEUE_MEMBER()                Provides a count of queue members based on the provided criteria, or updates a
QUEUE_MEMBER_COUNT()          Count number of members answering a queue.
QUEUE_MEMBER_LIST()           Returns a list of interfaces on a queue.
QUEUE_MEMBER_PENALTY()        Gets or sets queue members penalty.
QUEUE_VARIABLES()             Return Queue information in variables.
QUEUE_WAITING_COUNT()         Count number of calls currently waiting in a queue.
QUOTE()                       Quotes a given string, escaping embedded quotes as necessary
RAND()                        Choose a random number in a range.
REALTIME()                    RealTime Read/Write Functions.
REALTIME_DESTROY()            RealTime Destroy Function.
REALTIME_FIELD()              RealTime query function.
REALTIME_HASH()               RealTime query function.
REALTIME_STORE()              RealTime Store Function.
REDIRECTING()                 Gets or sets Redirecting data on the channel.
REGEX()                       Check string against a regular expression.
REPLACE()                     Replace a set of characters in a given string with another character.
SET()                         SET assigns a value to a channel variable.
SHA1()                        Computes a SHA1 digest.
SHARED()                      Gets or sets the shared variable specified.
SHELL()                       Executes a command using the system shell and captures its output.
SHIFT()                       Removes and returns the first item off of a variable containing delimited text
SIP_HEADER()                  Gets the specified SIP header from an incoming INVITE message.
SIP_HEADERS()                 Gets the list of SIP header names from an incoming INVITE message.
SIPPEER()                     Gets SIP peer information.
SMDI_MSG()                    Retrieve details about an SMDI message.
SMDI_MSG_RETRIEVE()           Retrieve an SMDI message.
SORT()                        Sorts a list of key/vals into a list of keys, based upon the vals.
SPEECH()                      Gets information about speech recognition results.
SPEECH_ENGINE()               Get or change a speech engine specific attribute.
SPEECH_GRAMMAR()              Gets the matched grammar of a result if available.
SPEECH_RESULTS_TYPE()         Sets the type of results that will be returned.
SPEECH_SCORE()                Gets the confidence score of a result.
SPEECH_TEXT()                 Gets the recognized text of a result.
SPRINTF()                     Format a variable according to a format string.
SQL_ESC()                     Escapes single ticks for use in SQL statements.
SRVQUERY()                    Initiate an SRV query.
SRVRESULT()                   Retrieve results from an SRVQUERY.
STACK_PEEK()                  View info about the location which called Gosub
STAT()                        Does a check on the specified file.
STRFTIME()                    Returns the current date/time in the specified format.
STRPTIME()                    Returns the epoch of the arbitrary date/time string structured as described by
STRREPLACE()                  Replace instances of a substring within a string with another string.
SYSINFO()                     Returns system information specified by parameter.
TALK_DETECT()                 Raises notifications when Asterisk detects silence or talking on a channel.
TESTTIME()                    Sets a time to be used with the channel to test logical conditions.
TIMEOUT()                     Gets or sets timeouts on the channel. Timeout values are in seconds.
TOLOWER()                     Convert string to all lowercase letters.
TOUPPER()                     Convert string to all uppercase letters.
TRYLOCK()                     Attempt to obtain a named mutex.
TXTCIDNAME()                  TXTCIDNAME looks up a caller name via DNS.
UNLOCK()                      Unlocks a named mutex.
UNSHIFT()                     Inserts one or more values to the beginning of a variable containing delimited
URIDECODE()                   Decodes a URI-encoded string according to RFC 2396.
URIENCODE()                   Encodes a string to URI-safe encoding according to RFC 2396.
VALID_EXTEN()                 Determine whether an extension exists or not.
VERSION()                     Return the Version info for this Asterisk.
VM_INFO()                     Returns the selected attribute from a mailbox.
VMCOUNT()                     Count the voicemails in a specified mailbox.

Modules

Note that you don’t call modules directly in any of the Asterisk interfaces (CLI, Dialplan, AMI, etc.) Each module can make one or more applications or functions (listed above) and/or variables available to Asterisk for use in the Dialplan. It’s possible some modules interact only with the AMI or ARI.

Channel drivers (11)

Channel drivers translate data from channels into something the core can use. The core of Asterisk is signaling agnostic. Therefore, Asterisk isn’t just a SIP or VOIP communications engine, it’s a multi-protocol engine.

Description                              Status      Support Level
---------------------------------------- ----------- -------------
Console Channel Driver                   Not Running      extended
DAHDI Telephony w/PRI & SS7 & MFC/R2     Running              core
Inter Asterisk eXchange (Ver 2)          Running              core
Bluetooth Mobile Device Channel Driver   Not Running      extended
Motif Jingle Channel Driver              Not Running          core
Objective Systems H323 Channel           Not Running      extended
PJSIP Channel Driver                     Running              core
RTP Media Channel                        Running              core
Session Initiation Protocol (SIP)        Running          extended
Skinny Client Control Protocol (Skinny)  Not Running      extended
UNISTIM Protocol (USTM)                  Not Running      extended

Dialplan Application Modules (65)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
app_xxx.so         Description                                        Status      Support Level
------------------ ----------------------------------------           ----------- -------------
alarmreceiver      Alarm Receiver for Asterisk                        Not Running      extended
amd                Answering Machine Detection Application            Running          extended
attended_transfer  Attended transfer to the given extension           Running              core
authenticate       Authentication Application                         Running              core
blind_transfer     Blind transfer channel to the given destination    Running              core
zapateller         Block Telemarketers with Special Info Tones        Running          extended
bridgeaddchan      Bridge Add Channel Application                     Running              core
agent_pool         Call centre agent pool applications                Not Running          core
chanisavail        Check channel availability                         Running          extended
voicemail          Comedian Mail (Voicemail System)                   Running              core
confbridge         Conference Bridge Application                      Running              core
controlplayback    Control Playback Application                       Running              core
userevent          Custom User Event Application                      Running              core
db                 Database Access Functions                          Running              core
dial               Dialing Application                                Running              core
speech_utils       Dialplan Speech Applications                       Running              core
stack              Dialplan subroutines (Gosub, Return, etc           Running              core
milliwatt          Digital Milliwatt (mu-law) Test Appl               Running              core
directed_pickup    Directed Call Pickup Application                   Running              core
disa               DISA (Direct Inward System Access) App             Running              core
cdr                Do not maintain a CDR for the current call         Running              core
dumpchan           Dump Info About The Calling Channel                Running              core
exec               Executes dialplan applications                     Running              core
directory          Extension Directory                                Running              core
externalivr        External IVR Interface Application                 Running          extended
followme           Find-Me/Follow-Me Application                      Not Running          core
flash              Flash channel application                          Running              core
forkcdr            Fork The CDR into 2 separate entities              Running              core
celgenuserevent    Generate an User-Defined CEL event                 Running              core
system             Generic System() application                       Running              core
fthangup           Hangs up the requested channel                     Running              core
test               Interface Test Application                         Running          extended
jack               JACK Interface                                     Running          extended
chanspy            Listen to the audio of an active channel           Running              core
meetme             MeetMe conference bridge                           Running          extended
mixmonitor         Mixed Audio Monitoring Application                 Running              core
morsecode          Morse code                                         Running          extended
originate          Originate call                                     Running              core
page               Page Multiple Phones                               Running              core
bridgewait         Place the channel into a holding bridge            Running              core
talkdetect         Playback with Talk Detection                       Running          extended
playtones          Playtones Application                              Running              core
readexten          Read and evaluate extension validity               Running              core
read               Read Variable Application                          Running              core
channelredirect    Redirects a given channel to a dialplan            Running              core
privacy            Require phone number to be entered, if no CID      Running              core
sayunixtime        Say time                                           Running              core
senddtmf           Send DTMF digits Application                       Running              core
sendtext           Send Text Applications                             Running              core
verbose            Send verbose output                                Running              core
mp3                Silly MP3 Application                              Running          extended
echo               Simple Echo Application                            Running              core
festival           Simple Festival Interface                          Not Running      extended
sms                SMS/PSTN handler                                   Running          extended
playback           Sound File Playback Application                    Running              core
stasis             Stasis dialplan application                        Running              core
stream_echo        Stream Echo Application                            Running              core
transfer           Transfers a caller to another extension            Running              core
record             Trivial Record Application                         Running              core
queue              True Call Queueing                                 Running              core
dictate            Virtual Dictation Machine                          Running          extended
waitforsilence     Wait For Silence/Noise                             Running          extended
waitforring        Waits until first ring after time                  Running          extended
waituntil          Wait until specified time                          Running              core
while              While Loops and Conditional Execution              Running              core

Dialplan Function Modules (52 functions)

Dialplan functions are somewhat similar to dialplan applications, but instead of doing work on a particular channel or call, they simply retrieve or set a particular setting on a channel, or perform text manipulation. For example, a dialplan function might retrieve the Caller ID information from an incoming call, filter some text, or set a timeout for caller input.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
func_xxx.so        Description                                        Status      Support Level
-----------------  ----------------------------------------           ----------- -------------
aes                AES dialplan functions                             Running              core
config             Asterisk configuration file variable access        Running              core
pitchshift         Audio Effects Dialplan Functions                   Running          extended
base64             base64 encode/decode dialplan functions            Running              core
callcompletion     Call Control Configuration Function                Running              core
cdr                Call Detail Record (CDR) dialplan functions        Running              core
groupcount         Channel group dialplan functions                   Running              core
channel            Channel information dialplan functions             Running              core
timeout            Channel timeout dialplan functions                 Running              core
iconv              Charset conversions                                Running              core
module             Checks if Asterisk module is loaded in memory      Running              core
shell              Collect output from a system shell command         Running              core
cut                Cut out information from a string                  Running              core
db                 Database (astdb) related dialplan functions        Running              core
dialgroup          Dialgroup dialplan function                        Running              core
dialplan           Dialplan Context/Extension/Priority Check          Running              core
lock               Dialplan mutexes                                   Running              core
enum               ENUM related dialplan functions                    Running              core
env                Environment/filesystem dialplan functions          Running              core
frame_trace        Frame Trace for internal ast_frame debug           Running          extended
sorcery            Get a field from a sorcery object                  Running              core
version            Get Asterisk Version/Build Info                    Running              core
pjsip_aor          Get information about a PJSIP AOR                  Running              core
pjsip_contact      Get information about a PJSIP contact              Running              core
pjsip_endpoint     Get information about a PJSIP endpoint             Running              core
extstate           Gets an extension's state in the dialplan          Running              core
devstate           Gets or sets a device state in the dialplan        Running              core
presencestate      Gets or sets a presence state in the dialplan      Running              core
hangupcause        HANGUPCAUSE related functions and application      Running              core
holdintercept      Hold interception dialplan function                Running              core
vmcount            Indicator for whether a voice mailbox has msgs     Running              core
jitterbuffer       Jitter buffer for read side of channel             Running              core
curl               Load external URL                                  Running              core
logic              Logical dialplan functions                         Running              core
blacklist          Look up Caller*ID name/number from blacklist       Running              core
math               Mathematical dialplan function                     Running              core
md5                MD5 digest dialplan functions                      Running              core
speex              Noise reduction and Automatic Gain Control         Running              core
odbc               ODBC lookups                                       Not Running          core
callerid           Party ID related dialplan functions                Running              core
periodic_hook      Periodic dialplan hooks.                           Running              core
rand               Random number dialplan function                    Running              core
realtime           RealTime Data store CRUD functions                 Running              core
sha1               SHA-1 computation dialplan function                Running              core
sprintf            SPRINTF dialplan function                          Running              core
srv                SRV related dialplan functions                     Running              core
strings            String handling dialplan functions                 Running              core
sysinfo            System information related functions               Running              core
talkdetect         Talk detection dialplan function                   Running              core
volume             Technology independent volume control              Running              core
uri                URI encode/decode dialplan functions               Running              core
global             Variable dialplan functions                        Running              core

Resource Modules (123 resourcss(!))

Resources provide functionality to Asterisk that may be called upon at any time during a call, even while another application is running on the channel. Resources are typically used as asynchronous events such as playing hold music when a call gets placed on hold, or performing call parking.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
res_xxx.so                           Description                                       Status      Support Level
-----------------                    ----------------------------------------          ----------- -------------
ari_model                            ARI Model validators                              Running              core
calendar_caldav                      Asterisk CalDAV Calendar Integration              Not Running      extended
calendar                             Asterisk Calendar integration                     Not Running      extended
agi                                  Asterisk Gateway Interface (AGI)                  Running              core
calendar_icalendar                   Asterisk iCalendar .ics file integration          Not Running      extended
calendar_ews                         Asterisk MS Exchange Web Service Calendar         Not Running      extended
calendar_exchange                    Asterisk MS Exchange Calendar Integration         Not Running      extended
ari                                  Asterisk RESTful Interface                        Running              core
rtp_asterisk                         Asterisk RTP Stack                                Running              core
xmpp                                 Asterisk XMPP Interface                           Not Running          core
pjsip                                Basic SIP resource                                Running              core
clioriginate                         Call origination and redirection from the CLI     Running              core
parking                              Call Parking Resource                             Running              core
format_attr_celt                     CELT Format Attribute Module                      Running              core
pjsip_notify                         CLI/AMI PJSIP NOTIFY Support                      Running              core
crypto                               Cryptographic Digital Signatures                  Running              core
curl                                 cURL Resource Module                              Running              core
timing_dahdi                         DAHDI Timing Interface                            Running              core
endpoint_stats                       Endpoint statistics                               Running          extended
chan_stats                           Example of how to use Stasis                      Running          extended
convert                              File format conversion CLI command                Running              core
format_attr_g729                     G.729 Format Attribute Module                     Running              core
fax                                  Generic FAX Applications                          Running              core
speech                               Generic Speech Recognition API                    Running              core
format_attr_h263                     H.263 Format Attribute Module                     Running              core
format_attr_h264                     H.264 Format Attribute Module                     Running              core
hep                                  HEPv3 API                                         Not Running      extended
http_media_cache                     HTTP Media Cache Backend                          Running              core
http_websocket                       HTTP WebSocket Support                            Running          extended
format_attr_ilbc                     iLBC Format Attribute Module                      Running              core
manager_devicestate                  Manager Device State Topic Forwarder              Running              core
manager_presencestate                Manager Presence State Topic Forwarder            Running              core
rtp_multicast                        Multicast RTP Engine                              Running              core
musiconhold                          Music On Hold Resource                            Running              core
mutestream                           Mute audio stream resources                       Running              core
mwi_devstate                         MWI Device State Subscriptions                    Running              core
config_mysql                         MySQL RealTime Configuration Driver               Running          extended
odbc                                 ODBC resource                                     Running              core
odbc_transaction                     ODBC transaction resource                         Running              core
format_attr_opus                     Opus Format Attribute Module                      Running              core
pjproject                            PJPROJECT Log and Utility Support                 Running              core
pjsip_acl                            PJSIP ACL Resource                                Running              core
pjsip_diversion                      PJSIP Add Diversion Header Support                Running              core
pjsip_endpoint_identifier_anonymous  PJSIP Anonymous endpoint identifier               Running              core
pjsip_publish_asterisk               PJSIP Asterisk Event PUBLISH Support              Running              core
pjsip_authenticator_digest           PJSIP authentication resource                     Running              core
pjsip_outbound_authenticator_digest  PJSIP authentication resource                     Running              core
pjsip_refer                          PJSIP Blind and Attended Transfer Support         Running              core
pjsip_caller_id                      PJSIP Caller ID Support                           Running              core
pjsip_config_wizard                  PJSIP Config Wizard                               Running              core
pjsip_dtmf_info                      PJSIP DTMF INFO Support                           Running              core
pjsip_empty_info                     PJSIP Empty INFO Support                          Running              core
pjsip_pubsub                         PJSIP event resource                              Running              core
pjsip_exten_state                    PJSIP Extension State Notifications               Running              core
pjsip_dialog_info_body_generator     PJSIP Extension State Dialog Info+XML Provider    Running              core
pjsip_pidf_body_generator            PJSIP Extension State PIDF Provider               Running              core
pjsip_xpidf_body_generator           PJSIP Extension State PIDF Provider               Running              core
pjsip_header_funcs                   PJSIP Header Functions                            Running              core
hep_pjsip                            PJSIP HEPv3 Logger                                Not Running      extended
pjsip_history                        PJSIP History                                     Running          extended
pjsip_one_touch_record_info          PJSIP INFO One Touch Recording Support            Running              core
pjsip_endpoint_identifier_ip         PJSIP IP endpoint identifier                      Running              core
pjsip_messaging                      PJSIP Messaging Support                           Running              core
pjsip_mwi                            PJSIP MWI resource                                Running              core
pjsip_mwi_body_generator             PJSIP MWI resource                                Running              core
pjsip_nat                            PJSIP NAT Support                                 Running              core
pjsip_outbound_publish               PJSIP Outbound Publish Support                    Running              core
pjsip_outbound_registration          PJSIP Outbound Registration Support               Running              core
pjsip_logger                         PJSIP Packet Logger                               Running              core
pjsip_path                           PJSIP Path Header Support                         Running              core
pjsip_pidf_digium_body_supplement    PJSIP PIDF Digium presence supplement             Running              core
pjsip_pidf_eyebeam_body_supplement   PJSIP PIDF Eyebeam supplement                     Running              core
pjsip_send_to_voicemail              PJSIP REFER Send to Voicemail Support             Running              core
pjsip_registrar                      PJSIP Registrar Support                           Running              core
pjsip_rfc3326                        PJSIP RFC3326 Support                             Running              core
pjsip_sdp_rtp                        PJSIP SDP RTP/AVP stream handler                  Running              core
pjsip_session                        PJSIP Session resource                            Running              core
pjsip_t38                            PJSIP T.38 UDPTL Support                          Running              core
pjsip_endpoint_identifier_user       PJSIP username endpoint identifier                Running              core
pjsip_transport_websocket            PJSIP WebSocket Transport Support                 Not Running          core
pktccops                             PktcCOPS manager for MGCP                         Not Running      extended
timing_pthread                       pthread Timing Interface                          Running          extended
config_curl                          Realtime Curl configuration                       Running              core
realtime                             Realtime Data Lookup/Rewrite                      Running              core
config_odbc                          Realtime ODBC configuration                       Running              core
limit                                Resource limits                                   Running              core
ari_events                           RESTful API module - WebSocket resource           Running              core
ari_sounds                           RESTful API module - Sound resources              Running              core
ari_bridges                          RESTful API module - Bridge resources             Running              core
ari_asterisk                         RESTful API module - Asterisk resources           Running              core
ari_channels                         RESTful API module - Channel resources            Running              core
ari_endpoints                        RESTful API module - Endpoint resources           Running              core
ari_playbacks                        RESTful API module - Playback control resources   Running              core
ari_recordings                       RESTful API module - Recording resources res      Running              core
ari_applications                     RESTful API module - Stasis application           Running              core
ari_device_states                    RESTful API module - Device state resour res      Running              core
hep_rtcp                             RTCP HEPv3 Logger                                 Not Running      extended
srtp                                 Secure RTP (SRTP)                                 Running              core
security_log                         Security Event Logging                            Running              core
ael_share                            share-able code for AEL                           Running          extended
format_attr_silk                     SILK Format Attribute Module                      Running              core
smdi                                 Simplified Message Desk Interface (SMDI)          Running          extended
pjsip_dlg_options                    SIP OPTIONS in dialog handler                     Running              core
format_attr_siren14                  Siren14 Format Attribute Module                   Running              core
format_attr_siren7                   Siren7 Format Attribute Module                    Running              core
sorcery_astdb                        Sorcery Astdb Object Wizard                       Running              core
sorcery_config                       Sorcery Configuration File Object Wizard          Running              core
sorcery_memory                       Sorcery In-Memory Object Wizard                   Running              core
sorcery_memory_cache                 Sorcery Memory Cache Object Wizard                Running              core
sorcery_realtime                     Sorcery Realtime Object Wizard                    Running              core
fax_spandsp                          Spandsp G.711 and T.38 FAX Technologies           Running          extended
stasis                               Stasis application support                        Running              core
stasis_snoop                         Stasis application snoop support                  Running              core
stasis_answer                        Stasis application answer support                 Running              core
stasis_playback                      Stasis application playback support               Running              core
stasis_recording                     Stasis application recording support              Running              core
stasis_device_state                  Stasis application device state support           Running              core
statsd                               Statsd client support                             Running          extended
stun_monitor                         STUN Network Monitor                              Not Running          core
timing_timerfd                       Timerfd Timing Interface                          Running              core
pjsip_sips_contact                   UAC SIPS Contact support                          Running              core
resolver_unbound                     Unbound DNS Resolver Support                      Running              core
format_attr_vp8                      VP8 Format Attribute Module                       Running              core

Call Detail Record (CDR) Drivers

cdr_xxx.so         Description                                        Status      Support Level
-----------------  ----------------------------------------           ----------- -------------
cdr_adaptive_odbc  Adaptive ODBC CDR backend                          Running              core
cdr_csv            Comma Separated Values CDR Backend                 Not Running      extended
cdr_manager        Asterisk Manager Interface CDR Backend             Not Running          core
cdr_odbc           ODBC CDR Backend                                   Not Running      extended

Call Event Log (CEL) Driver Modules

cel_xxx.so         Description                                        Status      Support Level
-----------------  ----------------------------------------           ----------- -------------
cel_manager        Asterisk Manager Interface CEL Backend             Running              core
cel_odbc           ODBC CEL backend                                   Running              core

Controlling Asterisk: CLI, AGI, AMI, AJAM, and ARI

Asterisk has been around for twenty years, and in that time a variety of ways to interact with it and control its operations have been developed.

CLI: Command Line Interface (asterisk -r)

Asterisk has a command line interface accessible using one of the following:

# shell-like command interface
asterisk -r

# Execute one command
asterisk -x "command [param ...]"

The Asterisk core has nearly 50 commands accessible using by typing core and the desired command. In addition, many Asterisk modules make their own commands available using the module’s name and the command; for example:

asterisk -x 'pjsip list endpoints'

The above command executes the list command of the pjsip module, passing it the parameter “endpoints”.

A few useful commands:

asterisk -x 'core show help'        # List all commands from all modules
asterisk -x 'core reload'           # Global reload
asterisk -x 'dialplan reload'       # Reload extensions (and *only* extensions)
asterisk -x 'database show'         # Show content of the internal Asterisk database 
asterisk -x 'agi set debug on'      # Write extra AGI informaton in /var/log/asterisk/full
asterisk -x 'agi set debug off'     # Turn AGI debugging off

AGI: Asterisk Gateway Interface

AGI provides an interface between the Asterisk dialplan and an external program that wants to manipulate a channel in the dialplan. In general, the interface is synchronous - actions taken on a channel from an AGI block and do not return until the action is completed.

An AGI script can be invoked from Dialplan using the AGI function:

same => n,AGI(command,[arg1[,arg2...]])

The command is implemented as script or program in any language. If no path is given on command, Asterisk looks for it in the directory named in astagidir in /etc/asterisk/asterisk.conf (usually /var/lib/asterisk/agi-bin.)

An example for where an AGI script might be useful:

If you need to do complicated things with strings, asterisk expressions is most likely NOT the best way to go about it. AGI scripts are an excellent option to this need, and make available the full power of whatever language you desire, be it Perl, C, C++, Cobol, RPG, Java, Snobol, PL/I, Scheme, Common Lisp, Shell scripts, Tcl, Forth, Modula, Pascal, APL, assembler, etc.

(I notice they didn’t mention awk or LOLCODE. It should be possible to write an AGI program in awk, although handlng stdin could be tricky.)

Interaction between an AGI script and Asterisk

A question I had when reading up on AGI in the Asterisk wiki was, “The wiki describes 46 AGICommand_ functions. Where do these fit in to this scheme?”

The answer is that as of January 2020 the wiki falls quite flat in its explanation of how AGI actually works. Other than fleeting mentions of stdin and stdout, it gives practically no information on how an AGI script interacts with Asterisk. In particular it fails to make clear two important facts:

  • AGI scripts receive information from Asterisk in a combination of environment variables and text the script reads on stdin
  • AGI scripts control Asterisk by writing one of the 46 commands to stdout, which Asterisk picks up and acts on

An additional complication in AGI is there is not one by three different ways for Asterisk to interact with an AGI script. These are nicey summarised by Randall Degges in his blog Random thoughts of a Happy Programmer. (The following text is abridged because the original entry referred to an AGI method that is now deprecated.)

The AGI actually has four three ways in which it can be used, each different from the other. There is the standard AGI, dead AGI, fast AGI, and enhanced AGI.

Standard AGI is the simplest, and most widely used form of AGI. Standard AGI scripts run on the local PBX and communicate with Asterisk through socket descriptors (namely STDIN and STDOUT). The standard AGI allows for usage of all AGI commands, and is what this article will be discussing.

(Removed reference to Dead AGI.)

Fast AGI is the AGI over TCP sockets protocol. It allows for all AGI functionality except EAGI, and is provided as a solution to developers who need to run resource intensive AGI programs. By running the bulk of the AGI logic on another server, the Asterisk server itself can process calls and not worry about handling complex computation for other services. This is the recommended protocol for large applications.

Last is the EAGI. The EAGI communications through file descriptors on the local machine using STDIN and STDOUT, and provides developers a way to access the audio channel directly for the calls being processed. This is rarely used, but gives developers a way to analyze raw audio data.

This article addresses standard AGI.

Environment variables

Asterisk puts the following into the environment when it starts a AGI script:

AST_AGI_DIR=/var/lib/asterisk/agi-bin
AST_BUILD_DATE='2019-11-22 00:56:40 UTC'
AST_BUILD_HOST=jenkins7
AST_BUILD_KERNEL=3.10.0-957.21.3.el7.x86_64
AST_BUILD_MACHINE=x86_64
AST_BUILD_OS=Linux
AST_BUILD_USER=mockbuild
AST_CONFIG_DIR=/etc/asterisk
AST_CONFIG_FILE=/etc/asterisk/asterisk.conf
AST_DATA_DIR=/var/lib/asterisk
AST_KEY_DIR=/var/lib/asterisk/keys
AST_LOG_DIR=/var/log/asterisk
AST_MODULE_DIR=/usr/lib64/asterisk/modules
AST_MONITOR_DIR=/var/spool/asterisk/monitor
AST_RUN_DIR=/var/run/asterisk
AST_SPOOL_DIR=/var/spool/asterisk
AST_SYSTEMNAME=
AST_VAR_DIR=/var/lib/asterisk
AST_VERSION=16.6.2
Startup parameters on stdin

When it starts the AGI script, Asterisk sends the following information, which the script is expected to read on stdin. Asterisk ends the list with an empty line, at which point the script can start doing its work:

agi_request: whitelist.sh
agi_channel: PJSIP/xxxxxxxx-00000030
agi_language: en
agi_type: PJSIP
agi_uniqueid: 1578056861.48
agi_version: 16.6.2
agi_callerid: 16915550112
agi_calleridname: YOUR NAME HERE
agi_callingpres: 0
agi_callingani2: 0
agi_callington: 0
agi_callingtns: 0
agi_dnid: 17395550172
agi_rdnis: unknown
agi_context: whitelist
agi_extension: s
agi_priority: 1
agi_enhanced: 0.0
agi_accountcode:
agi_threadid: 140093027530496
Commands

AGI scripts can send the following commands to Asterisk by writing them to stdout terminated with a nweline. The script should then read stdin for the response from Asterisk. In most cases it will be in the format 200 result=N EXTRA, where N is a numeric code and EXTRA is additional information. For example, on a READ VARIABLE request, the EXTRA contains value of the variable.

Command Synopsis
ANSWER Answer channel
ASYNCAGI BREAK Interrupts Async AGI
CHANNEL STATUS Returns status of the connected channel.
CONTROL STREAM FILE Sends audio file on channel and allows the listener to control the stream.
DATABASE DEL Removes database key/value
DATABASE DELTREE Removes database keytree/value
DATABASE GET Gets database value
DATABASE PUT Adds/updates database value
EXEC Executes a given Application
GET DATA Prompts for DTMF on a channel
GET FULL VARIABLE Evaluates a channel expression
GET OPTION Stream file, prompt for DTMF, with timeout.
GET VARIABLE Gets a channel variable.
GOSUB Cause the channel to execute the specified dialplan subroutine.
HANGUP Hangup a channel.
NOOP Does nothing.
RECEIVE CHAR Receives one character from channels supporting it.
RECEIVE TEXT Receives text from channels supporting it.
RECORD FILE Records to a given file.
SAY ALPHA Says a given character string.
SAY DATE Says a given date.
SAY DATETIME Says a given time as specified by the format given.
SAY DIGITS Says a given digit string.
SAY NUMBER Says a given number.
SAY PHONETIC Says a given character string with phonetics.
SAY TIME Says a given time.
SEND IMAGE Sends images to channels supporting it.
SEND TEXT Sends text to channels supporting it.
SET AUTOHANGUP Autohangup channel in some time.
SET CALLERID Sets callerid for the current channel.
SET CONTEXT Sets channel context.
SET EXTENSION Changes channel extension.
SET MUSIC Enable/Disable Music on hold generator
SET PRIORITY Set channel dialplan priority.
SET VARIABLE Sets a channel variable.
SPEECH ACTIVATE GRAMMAR Activates a grammar.
SPEECH CREATE Creates a speech object.
SPEECH DEACTIVATE GRAMMAR Deactivates a grammar.
SPEECH DESTROY Destroys a speech object.
SPEECH LOAD GRAMMAR Loads a grammar.
SPEECH RECOGNIZE Recognizes speech.
SPEECH SET Sets a speech engine setting.
SPEECH UNLOAD GRAMMAR Unloads a grammar.
STREAM FILE Sends audio file on channel.
TDD MODE Toggles TDD mode (for the deaf).
VERBOSE Logs a message to the asterisk verbose log.
Exit status

At exit Asterisk sets the variable AGISTATUS to one of the following values: SUCCESS, FAILURE, NOTFOUND, or HANGUP. Initially I assumed that SUCCESS meant the AGI script had exited with a zero return code and FAILURE indicated non-zero. But testing showed this not to be the case: I inevitably saw SUCCESS regardless of the script’s exit code. Becuase the AGI documentation is so spotty—not even Asterisk: The Definitive Guide covers it very well—I don’t know what causes Asterisk to set the value to FAILURE.

Note that a channel hangup does not automatically terminate an AGI script. If a channel hangs up while an AGI script is running, Asterisk sends it a SIGHUP. The script must trap the SIGHUP, and in the hander clean up as best it can and exit.

AMI: Asterisk Manager Interface: Manage Asterisk using TCP/IP

AMI runs on port 5038 (default). It accepts commands in the form Action: text; multiple lines can be sent, and an empty line indicates user input is complete and Asterisk should execute the request.

The Asterisk wiki currently documents over 150 actions supported by AMI, and 160 events reported by AMI.

  • AMI is configured in /etc/asterisk/manager.conf
  • FreePBX does a lot of its work using AMI
[asterisk@pbx ~]$ telnet 127.0.0.1 5038
Trying 192.168.1.7...
Connected to pbx.
Escape character is '^]'.
Asterisk Call Manager/5.0.1

Action: Login
ActionID: 1
Username: admin
Secret: ************

Response: Success
ActionID: 1
Message: Authentication accepted

Event: FullyBooted
Privilege: system,all
Uptime: 115343
LastReload: 111277
Status: Fully Booted

Action: ListCommands
ActionID: 2

Response: Success
ActionID: 2
AbsoluteTimeout: Set absolute timeout.  (Priv: system,call,all)
Atxfer: Attended transfer.  (Priv: call,all)
BlindTransfer: Blind transfer channel(s) to the given destination  (Priv: call,all)
Bridge: Bridge two channels already in the PBX.  (Priv: call,all)
BridgeDestroy: Destroy a bridge.  (Priv: <none>)
BridgeInfo: Get information about a bridge.  (Priv: <none>)
BridgeKick: Kick a channel from a bridge.  (Priv: <none>)
BridgeList: Get a list of bridges in the system.  (Priv: <none>)
BridgeTechnologyList: List available bridging technologies and their statuses.  (Priv: <none>)
BridgeTechnologySuspend: Suspend a bridging technology.  (Priv: <none>)
BridgeTechnologyUnsuspend: Unsuspend a bridging technology.  (Priv: <none>)
...
UserEvent: Send an arbitrary event.  (Priv: user,all)
VoicemailRefresh: Tell Asterisk to poll mailboxes for a change  (Priv: user,all)
VoicemailUsersList: List All Voicemail User Information.  (Priv: call,reporting,all)
VoicemailUserStatus: Show the status of given voicemail user's info.  (Priv: call,reporting,all)
WaitEvent: Wait for an event to occur.  (Priv: <none>)

Action: Logoff
ActionID: 3

Response: Goodbye
ActionID: 3
Message: Thanks for all the fish.

Connection closed by foreign host.

AJAM - Asynchronous Javascript Asterisk Manager

Web browsers can interact with Asterisk using JavaScript by talking to a mini-HTPP server running on port 8088 or (for TLS) 8089.

ARI: Asterisk REST Interface

ARI is a follow-on to AGI/AMI to allow better control of Asterisk by a web brower (or other HTTP based client) by using a RESTful interface over a WebSocket.