res_resolver_unbound: Fix config documentation.
[asterisk/asterisk.git] / res / res_agi.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief AGI - the Asterisk Gateway Interface
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  */
26
27 /*** MODULEINFO
28         <support_level>core</support_level>
29  ***/
30
31 #include "asterisk.h"
32
33 ASTERISK_REGISTER_FILE()
34
35 #include <math.h>
36 #include <signal.h>
37 #include <sys/time.h>
38 #include <sys/wait.h>
39 #include <sys/stat.h>
40 #include <pthread.h>
41
42 #include "asterisk/paths.h"     /* use many ast_config_AST_*_DIR */
43 #include "asterisk/network.h"
44 #include "asterisk/file.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/pbx.h"
47 #include "asterisk/module.h"
48 #include "asterisk/astdb.h"
49 #include "asterisk/callerid.h"
50 #include "asterisk/cli.h"
51 #include "asterisk/image.h"
52 #include "asterisk/say.h"
53 #include "asterisk/app.h"
54 #include "asterisk/dsp.h"
55 #include "asterisk/musiconhold.h"
56 #include "asterisk/utils.h"
57 #include "asterisk/lock.h"
58 #include "asterisk/strings.h"
59 #include "asterisk/manager.h"
60 #include "asterisk/ast_version.h"
61 #include "asterisk/speech.h"
62 #include "asterisk/manager.h"
63 #include "asterisk/term.h"
64 #include "asterisk/xmldoc.h"
65 #include "asterisk/srv.h"
66 #include "asterisk/test.h"
67 #include "asterisk/netsock2.h"
68 #include "asterisk/stasis_channels.h"
69 #include "asterisk/stasis_message_router.h"
70 #include "asterisk/format_cache.h"
71
72 #define AST_API_MODULE
73 #include "asterisk/agi.h"
74
75 /*** DOCUMENTATION
76         <agi name="answer" language="en_US">
77                 <synopsis>
78                         Answer channel
79                 </synopsis>
80                 <syntax />
81                 <description>
82                         <para>Answers channel if not already in answer state. Returns <literal>-1</literal> on
83                         channel failure, or <literal>0</literal> if successful.</para>
84                 </description>
85                 <see-also>
86                         <ref type="agi">hangup</ref>
87                         <ref type="application">AGI</ref>
88                 </see-also>
89         </agi>
90         <agi name="asyncagi break" language="en_US">
91                 <synopsis>
92                         Interrupts Async AGI
93                 </synopsis>
94                 <syntax />
95                 <description>
96                         <para>Interrupts expected flow of Async AGI commands and returns control to previous source
97                         (typically, the PBX dialplan).</para>
98                 </description>
99                 <see-also>
100                         <ref type="agi">hangup</ref>
101                         <ref type="application">AGI</ref>
102                 </see-also>
103         </agi>
104         <agi name="channel status" language="en_US">
105                 <synopsis>
106                         Returns status of the connected channel.
107                 </synopsis>
108                 <syntax>
109                         <parameter name="channelname" />
110                 </syntax>
111                 <description>
112                         <para>Returns the status of the specified <replaceable>channelname</replaceable>.
113                         If no channel name is given then returns the status of the current channel.</para>
114                         <para>Return values:</para>
115                         <enumlist>
116                                 <enum name="0">
117                                         <para>Channel is down and available.</para>
118                                 </enum>
119                                 <enum name="1">
120                                         <para>Channel is down, but reserved.</para>
121                                 </enum>
122                                 <enum name="2">
123                                         <para>Channel is off hook.</para>
124                                 </enum>
125                                 <enum name="3">
126                                         <para>Digits (or equivalent) have been dialed.</para>
127                                 </enum>
128                                 <enum name="4">
129                                         <para>Line is ringing.</para>
130                                 </enum>
131                                 <enum name="5">
132                                         <para>Remote end is ringing.</para>
133                                 </enum>
134                                 <enum name="6">
135                                         <para>Line is up.</para>
136                                 </enum>
137                                 <enum name="7">
138                                         <para>Line is busy.</para>
139                                 </enum>
140                         </enumlist>
141                 </description>
142                 <see-also>
143                         <ref type="application">AGI</ref>
144                 </see-also>
145         </agi>
146         <agi name="control stream file" language="en_US">
147                 <synopsis>
148                         Sends audio file on channel and allows the listener to control the stream.
149                 </synopsis>
150                 <syntax>
151                         <parameter name="filename" required="true">
152                                 <para>The file extension must not be included in the filename.</para>
153                         </parameter>
154                         <parameter name="escape_digits" required="true" />
155                         <parameter name="skipms" />
156                         <parameter name="ffchar">
157                                 <para>Defaults to <literal>#</literal></para>
158                         </parameter>
159                         <parameter name="rewchr">
160                                 <para>Defaults to <literal>*</literal></para>
161                         </parameter>
162                         <parameter name="pausechr" />
163                         <parameter name="offsetms">
164                                 <para>Offset, in milliseconds, to start the audio playback</para>
165                         </parameter>
166                 </syntax>
167                 <description>
168                         <para>Send the given file, allowing playback to be controlled by the given
169                         digits, if any. Use double quotes for the digits if you wish none to be
170                         permitted. If offsetms is provided then the audio will seek to offsetms
171                         before play starts. Returns <literal>0</literal> if playback completes without a digit
172                         being pressed, or the ASCII numerical value of the digit if one was pressed,
173                         or <literal>-1</literal> on error or if the channel was disconnected. Returns the
174                         position where playback was terminated as endpos.</para>
175
176                         <para>It sets the following channel variables upon completion:</para>
177                         <variablelist>
178                                 <variable name="CPLAYBACKSTATUS">
179                                         <para>Contains the status of the attempt as a text string</para>
180                                         <value name="SUCCESS" />
181                                         <value name="USERSTOPPED" />
182                                         <value name="REMOTESTOPPED" />
183                                         <value name="ERROR" />
184                                 </variable>
185                                 <variable name="CPLAYBACKOFFSET">
186                                         <para>Contains the offset in ms into the file where playback
187                                         was at when it stopped. <literal>-1</literal> is end of file.</para>
188                                 </variable>
189                                 <variable name="CPLAYBACKSTOPKEY">
190                                         <para>If the playback is stopped by the user this variable contains
191                                         the key that was pressed.</para>
192                                 </variable>
193                         </variablelist>
194                 </description>
195                 <see-also>
196                         <ref type="agi">get option</ref>
197                         <ref type="agi">control stream file</ref>
198                         <ref type="application">AGI</ref>
199                 </see-also>
200         </agi>
201         <agi name="database del" language="en_US">
202                 <synopsis>
203                         Removes database key/value
204                 </synopsis>
205                 <syntax>
206                         <parameter name="family" required="true" />
207                         <parameter name="key" required="true" />
208                 </syntax>
209                 <description>
210                         <para>Deletes an entry in the Asterisk database for a given
211                         <replaceable>family</replaceable> and <replaceable>key</replaceable>.</para>
212                         <para>Returns <literal>1</literal> if successful, <literal>0</literal>
213                         otherwise.</para>
214                 </description>
215                 <see-also>
216                         <ref type="agi">database get</ref>
217                         <ref type="agi">database put</ref>
218                         <ref type="agi">database deltree</ref>
219                         <ref type="application">AGI</ref>
220                 </see-also>
221         </agi>
222         <agi name="database deltree" language="en_US">
223                 <synopsis>
224                         Removes database keytree/value
225                 </synopsis>
226                 <syntax>
227                         <parameter name="family" required="true" />
228                         <parameter name="keytree" />
229                 </syntax>
230                 <description>
231                         <para>Deletes a <replaceable>family</replaceable> or specific <replaceable>keytree</replaceable>
232                         within a <replaceable>family</replaceable> in the Asterisk database.</para>
233                         <para>Returns <literal>1</literal> if successful, <literal>0</literal> otherwise.</para>
234                 </description>
235                 <see-also>
236                         <ref type="agi">database get</ref>
237                         <ref type="agi">database put</ref>
238                         <ref type="agi">database del</ref>
239                         <ref type="application">AGI</ref>
240                 </see-also>
241         </agi>
242         <agi name="database get" language="en_US">
243                 <synopsis>
244                         Gets database value
245                 </synopsis>
246                 <syntax>
247                         <parameter name="family" required="true" />
248                         <parameter name="key" required="true" />
249                 </syntax>
250                 <description>
251                         <para>Retrieves an entry in the Asterisk database for a given <replaceable>family</replaceable>
252                         and <replaceable>key</replaceable>.</para>
253                         <para>Returns <literal>0</literal> if <replaceable>key</replaceable> is not set.
254                         Returns <literal>1</literal> if <replaceable>key</replaceable> is set and returns the variable
255                         in parenthesis.</para>
256                         <para>Example return code: 200 result=1 (testvariable)</para>
257                 </description>
258                 <see-also>
259                         <ref type="agi">database put</ref>
260                         <ref type="agi">database del</ref>
261                         <ref type="agi">database deltree</ref>
262                         <ref type="application">AGI</ref>
263                 </see-also>
264         </agi>
265         <agi name="database put" language="en_US">
266                 <synopsis>
267                         Adds/updates database value
268                 </synopsis>
269                 <syntax>
270                         <parameter name="family" required="true" />
271                         <parameter name="key" required="true" />
272                         <parameter name="value" required="true" />
273                 </syntax>
274                 <description>
275                         <para>Adds or updates an entry in the Asterisk database for a given
276                         <replaceable>family</replaceable>, <replaceable>key</replaceable>, and
277                         <replaceable>value</replaceable>.</para>
278                         <para>Returns <literal>1</literal> if successful, <literal>0</literal> otherwise.</para>
279                 </description>
280                 <see-also>
281                         <ref type="agi">database get</ref>
282                         <ref type="agi">database del</ref>
283                         <ref type="agi">database deltree</ref>
284                         <ref type="application">AGI</ref>
285                 </see-also>
286         </agi>
287         <agi name="exec" language="en_US">
288                 <synopsis>
289                         Executes a given Application
290                 </synopsis>
291                 <syntax>
292                         <parameter name="application" required="true" />
293                         <parameter name="options" required="true" />
294                 </syntax>
295                 <description>
296                         <para>Executes <replaceable>application</replaceable> with given
297                         <replaceable>options</replaceable>.</para>
298                         <para>Returns whatever the <replaceable>application</replaceable> returns, or
299                         <literal>-2</literal> on failure to find <replaceable>application</replaceable>.</para>
300                 </description>
301                 <see-also>
302                         <ref type="application">AGI</ref>
303                 </see-also>
304         </agi>
305         <agi name="get data" language="en_US">
306                 <synopsis>
307                         Prompts for DTMF on a channel
308                 </synopsis>
309                 <syntax>
310                         <parameter name="file" required="true" />
311                         <parameter name="timeout" />
312                         <parameter name="maxdigits" />
313                 </syntax>
314                 <description>
315                         <para>Stream the given <replaceable>file</replaceable>, and receive DTMF data.</para>
316                         <para>Returns the digits received from the channel at the other end.</para>
317                 </description>
318                 <see-also>
319                         <ref type="application">AGI</ref>
320                 </see-also>
321         </agi>
322         <agi name="get full variable" language="en_US">
323                 <synopsis>
324                         Evaluates a channel expression
325                 </synopsis>
326                 <syntax>
327                         <parameter name="variablename" required="true" />
328                         <parameter name="channel name" />
329                 </syntax>
330                 <description>
331                         <para>Returns <literal>0</literal> if <replaceable>variablename</replaceable> is not set
332                         or channel does not exist. Returns <literal>1</literal> if <replaceable>variablename</replaceable>
333                         is set and returns the variable in parenthesis. Understands complex variable names and builtin
334                         variables, unlike GET VARIABLE.</para>
335                         <para>Example return code: 200 result=1 (testvariable)</para>
336                 </description>
337                 <see-also>
338                         <ref type="agi">get variable</ref>
339                         <ref type="agi">set variable</ref>
340                         <ref type="application">AGI</ref>
341                 </see-also>
342         </agi>
343         <agi name="get option" language="en_US">
344                 <synopsis>
345                         Stream file, prompt for DTMF, with timeout.
346                 </synopsis>
347                 <syntax>
348                         <parameter name="filename" required="true" />
349                         <parameter name="escape_digits" required="true" />
350                         <parameter name="timeout" />
351                 </syntax>
352                 <description>
353                         <para>Behaves similar to STREAM FILE but used with a timeout option.</para>
354                 </description>
355                 <see-also>
356                         <ref type="agi">stream file</ref>
357                         <ref type="agi">control stream file</ref>
358                         <ref type="application">AGI</ref>
359                 </see-also>
360         </agi>
361         <agi name="get variable" language="en_US">
362                 <synopsis>
363                         Gets a channel variable.
364                 </synopsis>
365                 <syntax>
366                         <parameter name="variablename" required="true" />
367                 </syntax>
368                 <description>
369                         <para>Returns <literal>0</literal> if <replaceable>variablename</replaceable> is not set.
370                         Returns <literal>1</literal> if <replaceable>variablename</replaceable> is set and returns
371                         the variable in parentheses.</para>
372                         <para>Example return code: 200 result=1 (testvariable)</para>
373                 </description>
374                 <see-also>
375                         <ref type="agi">get full variable</ref>
376                         <ref type="agi">set variable</ref>
377                         <ref type="application">AGI</ref>
378                 </see-also>
379         </agi>
380         <agi name="hangup" language="en_US">
381                 <synopsis>
382                         Hangup a channel.
383                 </synopsis>
384                 <syntax>
385                         <parameter name="channelname" />
386                 </syntax>
387                 <description>
388                         <para>Hangs up the specified channel. If no channel name is given, hangs
389                         up the current channel</para>
390                 </description>
391                 <see-also>
392                         <ref type="application">AGI</ref>
393                 </see-also>
394         </agi>
395         <agi name="noop" language="en_US">
396                 <synopsis>
397                         Does nothing.
398                 </synopsis>
399                 <syntax />
400                 <description>
401                         <para>Does nothing.</para>
402                 </description>
403                 <see-also>
404                         <ref type="application">AGI</ref>
405                 </see-also>
406         </agi>
407         <agi name="receive char" language="en_US">
408                 <synopsis>
409                         Receives one character from channels supporting it.
410                 </synopsis>
411                 <syntax>
412                         <parameter name="timeout" required="true">
413                                 <para>The maximum time to wait for input in milliseconds, or <literal>0</literal>
414                                 for infinite. Most channels</para>
415                         </parameter>
416                 </syntax>
417                 <description>
418                         <para>Receives a character of text on a channel. Most channels do not support
419                         the reception of text. Returns the decimal value of the character
420                         if one is received, or <literal>0</literal> if the channel does not support
421                         text reception. Returns <literal>-1</literal> only on error/hangup.</para>
422                 </description>
423                 <see-also>
424                         <ref type="agi">receive text</ref>
425                         <ref type="application">AGI</ref>
426                 </see-also>
427         </agi>
428         <agi name="receive text" language="en_US">
429                 <synopsis>
430                         Receives text from channels supporting it.
431                 </synopsis>
432                 <syntax>
433                         <parameter name="timeout" required="true">
434                                 <para>The timeout to be the maximum time to wait for input in
435                                 milliseconds, or <literal>0</literal> for infinite.</para>
436                         </parameter>
437                 </syntax>
438                 <description>
439                         <para>Receives a string of text on a channel. Most channels
440                         do not support the reception of text. Returns <literal>-1</literal> for failure
441                         or <literal>1</literal> for success, and the string in parenthesis.</para>
442                 </description>
443                 <see-also>
444                         <ref type="agi">receive char</ref>
445                         <ref type="agi">send text</ref>
446                         <ref type="application">AGI</ref>
447                 </see-also>
448         </agi>
449         <agi name="record file" language="en_US">
450                 <synopsis>
451                         Records to a given file.
452                 </synopsis>
453                 <syntax>
454                         <parameter name="filename" required="true" />
455                         <parameter name="format" required="true" />
456                         <parameter name="escape_digits" required="true" />
457                         <parameter name="timeout" required="true" />
458                         <parameter name="offset samples" />
459                         <parameter name="BEEP" />
460                         <parameter name="s=silence" />
461                 </syntax>
462                 <description>
463                         <para>Record to a file until a given dtmf digit in the sequence is received.
464                         Returns <literal>-1</literal> on hangup or error.  The format will specify what kind of file
465                         will be recorded. The <replaceable>timeout</replaceable> is the maximum record time in
466                         milliseconds, or <literal>-1</literal> for no <replaceable>timeout</replaceable>.
467                         <replaceable>offset samples</replaceable> is optional, and, if provided, will seek
468                         to the offset without exceeding the end of the file. <replaceable>silence</replaceable> is
469                         the number of seconds of silence allowed before the function returns despite the
470                         lack of dtmf digits or reaching <replaceable>timeout</replaceable>. <replaceable>silence</replaceable>
471                         value must be preceded by <literal>s=</literal> and is also optional.</para>
472                 </description>
473                 <see-also>
474                         <ref type="application">AGI</ref>
475                 </see-also>
476         </agi>
477         <agi name="say alpha" language="en_US">
478                 <synopsis>
479                         Says a given character string.
480                 </synopsis>
481                 <syntax>
482                         <parameter name="number" required="true" />
483                         <parameter name="escape_digits" required="true" />
484                 </syntax>
485                 <description>
486                         <para>Say a given character string, returning early if any of the given DTMF digits
487                         are received on the channel. Returns <literal>0</literal> if playback completes
488                         without a digit being pressed, or the ASCII numerical value of the digit if one
489                         was pressed or <literal>-1</literal> on error/hangup.</para>
490                 </description>
491                 <see-also>
492                         <ref type="agi">say digits</ref>
493                         <ref type="agi">say number</ref>
494                         <ref type="agi">say phonetic</ref>
495                         <ref type="agi">say date</ref>
496                         <ref type="agi">say time</ref>
497                         <ref type="agi">say datetime</ref>
498                         <ref type="application">AGI</ref>
499                 </see-also>
500         </agi>
501         <agi name="say digits" language="en_US">
502                 <synopsis>
503                         Says a given digit string.
504                 </synopsis>
505                 <syntax>
506                         <parameter name="number" required="true" />
507                         <parameter name="escape_digits" required="true" />
508                 </syntax>
509                 <description>
510                         <para>Say a given digit string, returning early if any of the given DTMF digits
511                         are received on the channel. Returns <literal>0</literal> if playback completes
512                         without a digit being pressed, or the ASCII numerical value of the digit if one
513                         was pressed or <literal>-1</literal> on error/hangup.</para>
514                 </description>
515                 <see-also>
516                         <ref type="agi">say alpha</ref>
517                         <ref type="agi">say number</ref>
518                         <ref type="agi">say phonetic</ref>
519                         <ref type="agi">say date</ref>
520                         <ref type="agi">say time</ref>
521                         <ref type="agi">say datetime</ref>
522                         <ref type="application">AGI</ref>
523                 </see-also>
524         </agi>
525         <agi name="say number" language="en_US">
526                 <synopsis>
527                         Says a given number.
528                 </synopsis>
529                 <syntax>
530                         <parameter name="number" required="true" />
531                         <parameter name="escape_digits" required="true" />
532                         <parameter name="gender" />
533                 </syntax>
534                 <description>
535                         <para>Say a given number, returning early if any of the given DTMF digits
536                         are received on the channel.  Returns <literal>0</literal> if playback
537                         completes without a digit being pressed, or the ASCII numerical value of
538                         the digit if one was pressed or <literal>-1</literal> on error/hangup.</para>
539                 </description>
540                 <see-also>
541                         <ref type="agi">say alpha</ref>
542                         <ref type="agi">say digits</ref>
543                         <ref type="agi">say phonetic</ref>
544                         <ref type="agi">say date</ref>
545                         <ref type="agi">say time</ref>
546                         <ref type="agi">say datetime</ref>
547                         <ref type="application">AGI</ref>
548                 </see-also>
549         </agi>
550         <agi name="say phonetic" language="en_US">
551                 <synopsis>
552                         Says a given character string with phonetics.
553                 </synopsis>
554                 <syntax>
555                         <parameter name="string" required="true" />
556                         <parameter name="escape_digits" required="true" />
557                 </syntax>
558                 <description>
559                         <para>Say a given character string with phonetics, returning early if any of the
560                         given DTMF digits are received on the channel. Returns <literal>0</literal> if
561                         playback completes without a digit pressed, the ASCII numerical value of the digit
562                         if one was pressed, or <literal>-1</literal> on error/hangup.</para>
563                 </description>
564                 <see-also>
565                         <ref type="agi">say alpha</ref>
566                         <ref type="agi">say digits</ref>
567                         <ref type="agi">say number</ref>
568                         <ref type="agi">say date</ref>
569                         <ref type="agi">say time</ref>
570                         <ref type="agi">say datetime</ref>
571                         <ref type="application">AGI</ref>
572                 </see-also>
573         </agi>
574         <agi name="say date" language="en_US">
575                 <synopsis>
576                         Says a given date.
577                 </synopsis>
578                 <syntax>
579                         <parameter name="date" required="true">
580                                 <para>Is number of seconds elapsed since 00:00:00 on January 1, 1970.
581                                 Coordinated Universal Time (UTC).</para>
582                         </parameter>
583                         <parameter name="escape_digits" required="true" />
584                 </syntax>
585                 <description>
586                         <para>Say a given date, returning early if any of the given DTMF digits are
587                         received on the channel. Returns <literal>0</literal> if playback
588                         completes without a digit being pressed, or the ASCII numerical value of the
589                         digit if one was pressed or <literal>-1</literal> on error/hangup.</para>
590                 </description>
591                 <see-also>
592                         <ref type="agi">say alpha</ref>
593                         <ref type="agi">say digits</ref>
594                         <ref type="agi">say number</ref>
595                         <ref type="agi">say phonetic</ref>
596                         <ref type="agi">say time</ref>
597                         <ref type="agi">say datetime</ref>
598                         <ref type="application">AGI</ref>
599                 </see-also>
600         </agi>
601         <agi name="say time" language="en_US">
602                 <synopsis>
603                         Says a given time.
604                 </synopsis>
605                 <syntax>
606                         <parameter name="time" required="true">
607                                 <para>Is number of seconds elapsed since 00:00:00 on January 1, 1970.
608                                 Coordinated Universal Time (UTC).</para>
609                         </parameter>
610                         <parameter name="escape_digits" required="true" />
611                 </syntax>
612                 <description>
613                         <para>Say a given time, returning early if any of the given DTMF digits are
614                         received on the channel. Returns <literal>0</literal> if playback completes
615                         without a digit being pressed, or the ASCII numerical value of the digit if
616                         one was pressed or <literal>-1</literal> on error/hangup.</para>
617                 </description>
618                 <see-also>
619                         <ref type="agi">say alpha</ref>
620                         <ref type="agi">say digits</ref>
621                         <ref type="agi">say number</ref>
622                         <ref type="agi">say phonetic</ref>
623                         <ref type="agi">say date</ref>
624                         <ref type="agi">say datetime</ref>
625                         <ref type="application">AGI</ref>
626                 </see-also>
627         </agi>
628         <agi name="say datetime" language="en_US">
629                 <synopsis>
630                         Says a given time as specified by the format given.
631                 </synopsis>
632                 <syntax>
633                         <parameter name="time" required="true">
634                                 <para>Is number of seconds elapsed since 00:00:00
635                                 on January 1, 1970, Coordinated Universal Time (UTC)</para>
636                         </parameter>
637                         <parameter name="escape_digits" required="true" />
638                         <parameter name="format">
639                                 <para>Is the format the time should be said in. See
640                                 <filename>voicemail.conf</filename> (defaults to <literal>ABdY
641                                 'digits/at' IMp</literal>).</para>
642                         </parameter>
643                         <parameter name="timezone">
644                                 <para>Acceptable values can be found in <filename>/usr/share/zoneinfo</filename>
645                                 Defaults to machine default.</para>
646                         </parameter>
647                 </syntax>
648                 <description>
649                         <para>Say a given time, returning early if any of the given DTMF digits are
650                         received on the channel. Returns <literal>0</literal> if playback
651                         completes without a digit being pressed, or the ASCII numerical value of the
652                         digit if one was pressed or <literal>-1</literal> on error/hangup.</para>
653                 </description>
654                 <see-also>
655                         <ref type="agi">say alpha</ref>
656                         <ref type="agi">say digits</ref>
657                         <ref type="agi">say number</ref>
658                         <ref type="agi">say phonetic</ref>
659                         <ref type="agi">say date</ref>
660                         <ref type="agi">say time</ref>
661                         <ref type="application">AGI</ref>
662                 </see-also>
663         </agi>
664         <agi name="send image" language="en_US">
665                 <synopsis>
666                         Sends images to channels supporting it.
667                 </synopsis>
668                 <syntax>
669                         <parameter name="image" required="true" />
670                 </syntax>
671                 <description>
672                         <para>Sends the given image on a channel. Most channels do not support the
673                         transmission of images. Returns <literal>0</literal> if image is sent, or if
674                         the channel does not support image transmission.  Returns <literal>-1</literal>
675                         only on error/hangup. Image names should not include extensions.</para>
676                 </description>
677                 <see-also>
678                         <ref type="application">AGI</ref>
679                 </see-also>
680         </agi>
681         <agi name="send text" language="en_US">
682                 <synopsis>
683                         Sends text to channels supporting it.
684                 </synopsis>
685                 <syntax>
686                         <parameter name="text to send" required="true">
687                                 <para>Text consisting of greater than one word should be placed
688                                 in quotes since the command only accepts a single argument.</para>
689                         </parameter>
690                 </syntax>
691                 <description>
692                         <para>Sends the given text on a channel. Most channels do not support the
693                         transmission of text. Returns <literal>0</literal> if text is sent, or if the
694                         channel does not support text transmission. Returns <literal>-1</literal> only
695                         on error/hangup.</para>
696                 </description>
697                 <see-also>
698                         <ref type="agi">receive text</ref>
699                         <ref type="application">AGI</ref>
700                 </see-also>
701         </agi>
702         <agi name="set autohangup" language="en_US">
703                 <synopsis>
704                         Autohangup channel in some time.
705                 </synopsis>
706                 <syntax>
707                         <parameter name="time" required="true" />
708                 </syntax>
709                 <description>
710                         <para>Cause the channel to automatically hangup at <replaceable>time</replaceable>
711                         seconds in the future. Of course it can be hungup before then as well. Setting to
712                         <literal>0</literal> will cause the autohangup feature to be disabled on this channel.</para>
713                 </description>
714                 <see-also>
715                         <ref type="application">AGI</ref>
716                 </see-also>
717         </agi>
718         <agi name="set callerid" language="en_US">
719                 <synopsis>
720                         Sets callerid for the current channel.
721                 </synopsis>
722                 <syntax>
723                         <parameter name="number" required="true" />
724                 </syntax>
725                 <description>
726                         <para>Changes the callerid of the current channel.</para>
727                 </description>
728                 <see-also>
729                         <ref type="application">AGI</ref>
730                 </see-also>
731         </agi>
732         <agi name="set context" language="en_US">
733                 <synopsis>
734                         Sets channel context.
735                 </synopsis>
736                 <syntax>
737                         <parameter name="desired context" required="true" />
738                 </syntax>
739                 <description>
740                         <para>Sets the context for continuation upon exiting the application.</para>
741                 </description>
742                 <see-also>
743                         <ref type="agi">set extension</ref>
744                         <ref type="agi">set priority</ref>
745                         <ref type="application">AGI</ref>
746                 </see-also>
747         </agi>
748         <agi name="set extension" language="en_US">
749                 <synopsis>
750                         Changes channel extension.
751                 </synopsis>
752                 <syntax>
753                         <parameter name="new extension" required="true" />
754                 </syntax>
755                 <description>
756                         <para>Changes the extension for continuation upon exiting the application.</para>
757                 </description>
758                 <see-also>
759                         <ref type="agi">set context</ref>
760                         <ref type="agi">set priority</ref>
761                         <ref type="application">AGI</ref>
762                 </see-also>
763         </agi>
764         <agi name="set music" language="en_US">
765                 <synopsis>
766                         Enable/Disable Music on hold generator
767                 </synopsis>
768                 <syntax>
769                         <parameter required="true">
770                                 <enumlist>
771                                         <enum>
772                                                 <parameter name="on" literal="true" required="true" />
773                                         </enum>
774                                         <enum>
775                                                 <parameter name="off" literal="true" required="true" />
776                                         </enum>
777                                 </enumlist>
778                         </parameter>
779                         <parameter name="class" required="true" />
780                 </syntax>
781                 <description>
782                         <para>Enables/Disables the music on hold generator. If <replaceable>class</replaceable>
783                         is not specified, then the <literal>default</literal> music on hold class will be
784                         used. This generator will be stopped automatically when playing a file.</para>
785                         <para>Always returns <literal>0</literal>.</para>
786                 </description>
787                 <see-also>
788                         <ref type="application">AGI</ref>
789                 </see-also>
790         </agi>
791         <agi name="set priority" language="en_US">
792                 <synopsis>
793                         Set channel dialplan priority.
794                 </synopsis>
795                 <syntax>
796                         <parameter name="priority" required="true" />
797                 </syntax>
798                 <description>
799                         <para>Changes the priority for continuation upon exiting the application.
800                         The priority must be a valid priority or label.</para>
801                 </description>
802                 <see-also>
803                         <ref type="agi">set context</ref>
804                         <ref type="agi">set extension</ref>
805                         <ref type="application">AGI</ref>
806                 </see-also>
807         </agi>
808         <agi name="set variable" language="en_US">
809                 <synopsis>
810                         Sets a channel variable.
811                 </synopsis>
812                 <syntax>
813                         <parameter name="variablename" required="true" />
814                         <parameter name="value" required="true" />
815                 </syntax>
816                 <description>
817                         <para>Sets a variable to the current channel.</para>
818                 </description>
819                 <see-also>
820                         <ref type="agi">get variable</ref>
821                         <ref type="agi">get full variable</ref>
822                         <ref type="application">AGI</ref>
823                 </see-also>
824         </agi>
825         <agi name="stream file" language="en_US">
826                 <synopsis>
827                         Sends audio file on channel.
828                 </synopsis>
829                 <syntax>
830                         <parameter name="filename" required="true">
831                                 <para>File name to play. The file extension must not be
832                                 included in the <replaceable>filename</replaceable>.</para>
833                         </parameter>
834                         <parameter name="escape_digits" required="true">
835                                 <para>Use double quotes for the digits if you wish none to be
836                                 permitted.</para>
837                         </parameter>
838                         <parameter name="sample offset">
839                                 <para>If sample offset is provided then the audio will seek to sample
840                                 offset before play starts.</para>
841                         </parameter>
842                 </syntax>
843                 <description>
844                         <para>Send the given file, allowing playback to be interrupted by the given
845                         digits, if any. Returns <literal>0</literal> if playback completes without a digit
846                         being pressed, or the ASCII numerical value of the digit if one was pressed,
847                         or <literal>-1</literal> on error or if the channel was disconnected. If
848                         musiconhold is playing before calling stream file it will be automatically
849                         stopped and will not be restarted after completion.</para>
850                         <para>It sets the following channel variables upon completion:</para>
851                         <variablelist>
852                                 <variable name="PLAYBACKSTATUS">
853                                         <para>The status of the playback attempt as a text string.</para>
854                                         <value name="SUCCESS"/>
855                                         <value name="FAILED"/>
856                                 </variable>
857                         </variablelist>
858                 </description>
859                 <see-also>
860                         <ref type="agi">control stream file</ref>
861                         <ref type="agi">get option</ref>
862                         <ref type="application">AGI</ref>
863                 </see-also>
864         </agi>
865         <agi name="tdd mode" language="en_US">
866                 <synopsis>
867                         Toggles TDD mode (for the deaf).
868                 </synopsis>
869                 <syntax>
870                         <parameter name="boolean" required="true">
871                                 <enumlist>
872                                         <enum name="on" />
873                                         <enum name="off" />
874                                 </enumlist>
875                         </parameter>
876                 </syntax>
877                 <description>
878                         <para>Enable/Disable TDD transmission/reception on a channel. Returns <literal>1</literal> if
879                         successful, or <literal>0</literal> if channel is not TDD-capable.</para>
880                 </description>
881                 <see-also>
882                         <ref type="application">AGI</ref>
883                 </see-also>
884         </agi>
885         <agi name="verbose" language="en_US">
886                 <synopsis>
887                         Logs a message to the asterisk verbose log.
888                 </synopsis>
889                 <syntax>
890                         <parameter name="message" required="true" />
891                         <parameter name="level" required="true" />
892                 </syntax>
893                 <description>
894                         <para>Sends <replaceable>message</replaceable> to the console via verbose
895                         message system. <replaceable>level</replaceable> is the verbose level (1-4).
896                         Always returns <literal>1</literal></para>
897                 </description>
898                 <see-also>
899                         <ref type="application">AGI</ref>
900                 </see-also>
901         </agi>
902         <agi name="wait for digit" language="en_US">
903                 <synopsis>
904                         Waits for a digit to be pressed.
905                 </synopsis>
906                 <syntax>
907                         <parameter name="timeout" required="true" />
908                 </syntax>
909                 <description>
910                         <para>Waits up to <replaceable>timeout</replaceable> milliseconds for channel to
911                         receive a DTMF digit. Returns <literal>-1</literal> on channel failure, <literal>0</literal>
912                         if no digit is received in the timeout, or the numerical value of the ascii of the digit if
913                         one is received. Use <literal>-1</literal> for the <replaceable>timeout</replaceable> value if
914                         you desire the call to block indefinitely.</para>
915                 </description>
916                 <see-also>
917                         <ref type="application">AGI</ref>
918                 </see-also>
919         </agi>
920         <agi name="speech create" language="en_US">
921                 <synopsis>
922                         Creates a speech object.
923                 </synopsis>
924                 <syntax>
925                         <parameter name="engine" required="true" />
926                 </syntax>
927                 <description>
928                         <para>Create a speech object to be used by the other Speech AGI commands.</para>
929                 </description>
930                 <see-also>
931                         <ref type="agi">speech set</ref>
932                         <ref type="agi">speech destroy</ref>
933                         <ref type="agi">speech load grammar</ref>
934                         <ref type="agi">speech unload grammar</ref>
935                         <ref type="agi">speech activate grammar</ref>
936                         <ref type="agi">speech deactivate grammar</ref>
937                         <ref type="agi">speech recognize</ref>
938                         <ref type="application">AGI</ref>
939                 </see-also>
940         </agi>
941         <agi name="speech set" language="en_US">
942                 <synopsis>
943                         Sets a speech engine setting.
944                 </synopsis>
945                 <syntax>
946                         <parameter name="name" required="true" />
947                         <parameter name="value" required="true" />
948                 </syntax>
949                 <description>
950                         <para>Set an engine-specific setting.</para>
951                 </description>
952                 <see-also>
953                         <ref type="agi">speech create</ref>
954                         <ref type="agi">speech destroy</ref>
955                         <ref type="agi">speech load grammar</ref>
956                         <ref type="agi">speech unload grammar</ref>
957                         <ref type="agi">speech activate grammar</ref>
958                         <ref type="agi">speech deactivate grammar</ref>
959                         <ref type="agi">speech recognize</ref>
960                         <ref type="application">AGI</ref>
961                 </see-also>
962         </agi>
963         <agi name="speech destroy" language="en_US">
964                 <synopsis>
965                         Destroys a speech object.
966                 </synopsis>
967                 <syntax>
968                 </syntax>
969                 <description>
970                         <para>Destroy the speech object created by <literal>SPEECH CREATE</literal>.</para>
971                 </description>
972                 <see-also>
973                         <ref type="agi">speech create</ref>
974                         <ref type="agi">speech set</ref>
975                         <ref type="agi">speech load grammar</ref>
976                         <ref type="agi">speech unload grammar</ref>
977                         <ref type="agi">speech activate grammar</ref>
978                         <ref type="agi">speech deactivate grammar</ref>
979                         <ref type="agi">speech recognize</ref>
980                         <ref type="application">AGI</ref>
981                 </see-also>
982         </agi>
983         <agi name="speech load grammar" language="en_US">
984                 <synopsis>
985                         Loads a grammar.
986                 </synopsis>
987                 <syntax>
988                         <parameter name="grammar name" required="true" />
989                         <parameter name="path to grammar" required="true" />
990                 </syntax>
991                 <description>
992                         <para>Loads the specified grammar as the specified name.</para>
993                 </description>
994                 <see-also>
995                         <ref type="agi">speech create</ref>
996                         <ref type="agi">speech set</ref>
997                         <ref type="agi">speech destroy</ref>
998                         <ref type="agi">speech unload grammar</ref>
999                         <ref type="agi">speech activate grammar</ref>
1000                         <ref type="agi">speech deactivate grammar</ref>
1001                         <ref type="agi">speech recognize</ref>
1002                         <ref type="application">AGI</ref>
1003                 </see-also>
1004         </agi>
1005         <agi name="speech unload grammar" language="en_US">
1006                 <synopsis>
1007                         Unloads a grammar.
1008                 </synopsis>
1009                 <syntax>
1010                         <parameter name="grammar name" required="true" />
1011                 </syntax>
1012                 <description>
1013                         <para>Unloads the specified grammar.</para>
1014                 </description>
1015                 <see-also>
1016                         <ref type="agi">speech create</ref>
1017                         <ref type="agi">speech set</ref>
1018                         <ref type="agi">speech destroy</ref>
1019                         <ref type="agi">speech load grammar</ref>
1020                         <ref type="agi">speech activate grammar</ref>
1021                         <ref type="agi">speech deactivate grammar</ref>
1022                         <ref type="agi">speech recognize</ref>
1023                         <ref type="application">AGI</ref>
1024                 </see-also>
1025         </agi>
1026         <agi name="speech activate grammar" language="en_US">
1027                 <synopsis>
1028                         Activates a grammar.
1029                 </synopsis>
1030                 <syntax>
1031                         <parameter name="grammar name" required="true" />
1032                 </syntax>
1033                 <description>
1034                         <para>Activates the specified grammar on the speech object.</para>
1035                 </description>
1036                 <see-also>
1037                         <ref type="agi">speech create</ref>
1038                         <ref type="agi">speech set</ref>
1039                         <ref type="agi">speech destroy</ref>
1040                         <ref type="agi">speech load grammar</ref>
1041                         <ref type="agi">speech unload grammar</ref>
1042                         <ref type="agi">speech deactivate grammar</ref>
1043                         <ref type="agi">speech recognize</ref>
1044                         <ref type="application">AGI</ref>
1045                 </see-also>
1046         </agi>
1047         <agi name="speech deactivate grammar" language="en_US">
1048                 <synopsis>
1049                         Deactivates a grammar.
1050                 </synopsis>
1051                 <syntax>
1052                         <parameter name="grammar name" required="true" />
1053                 </syntax>
1054                 <description>
1055                         <para>Deactivates the specified grammar on the speech object.</para>
1056                 </description>
1057                 <see-also>
1058                         <ref type="agi">speech create</ref>
1059                         <ref type="agi">speech set</ref>
1060                         <ref type="agi">speech destroy</ref>
1061                         <ref type="agi">speech load grammar</ref>
1062                         <ref type="agi">speech unload grammar</ref>
1063                         <ref type="agi">speech activate grammar</ref>
1064                         <ref type="agi">speech recognize</ref>
1065                         <ref type="application">AGI</ref>
1066                 </see-also>
1067         </agi>
1068         <agi name="speech recognize" language="en_US">
1069                 <synopsis>
1070                         Recognizes speech.
1071                 </synopsis>
1072                 <syntax>
1073                         <parameter name="prompt" required="true" />
1074                         <parameter name="timeout" required="true" />
1075                         <parameter name="offset" />
1076                 </syntax>
1077                 <description>
1078                         <para>Plays back given <replaceable>prompt</replaceable> while listening for
1079                         speech and dtmf.</para>
1080                 </description>
1081                 <see-also>
1082                         <ref type="agi">speech create</ref>
1083                         <ref type="agi">speech set</ref>
1084                         <ref type="agi">speech destroy</ref>
1085                         <ref type="agi">speech load grammar</ref>
1086                         <ref type="agi">speech unload grammar</ref>
1087                         <ref type="agi">speech activate grammar</ref>
1088                         <ref type="agi">speech deactivate grammar</ref>
1089                         <ref type="application">AGI</ref>
1090                 </see-also>
1091         </agi>
1092         <application name="AGI" language="en_US">
1093                 <synopsis>
1094                         Executes an AGI compliant application.
1095                 </synopsis>
1096                 <syntax>
1097                         <parameter name="command" required="true">
1098                                 <para>How AGI should be invoked on the channel.</para>
1099                         </parameter>
1100                         <parameter name="args">
1101                                 <para>Arguments to pass to the AGI script or server.</para>
1102                                 <argument name="arg1" required="true" />
1103                                 <argument name="arg2" multiple="yes" />
1104                         </parameter>
1105                 </syntax>
1106                 <description>
1107                         <para>Executes an Asterisk Gateway Interface compliant
1108                         program on a channel. AGI allows Asterisk to launch external programs written
1109                         in any language to control a telephony channel, play audio, read DTMF digits,
1110                         etc. by communicating with the AGI protocol.</para>
1111                         <para>The following variants of AGI exist, and are chosen based on the value
1112                         passed to <replaceable>command</replaceable>:</para>
1113                         <enumlist>
1114                                 <enum name="AGI">
1115                                         <para>The classic variant of AGI, this will launch the script
1116                                         specified by <replaceable>command</replaceable> as a new process.
1117                                         Communication with the script occurs on <literal>stdin</literal> and
1118                                         <literal>stdout</literal>. If the full path to the script is not
1119                                         provided, the <directory>astagidir</directory> specified in
1120                                         <filename>asterisk.conf</filename> will be used.
1121                                         </para>
1122                                 </enum>
1123                                 <enum name="FastAGI">
1124                                         <para>Connect Asterisk to a FastAGI server using a TCP connection.
1125                                         The URI to the FastAGI server should be given in the form
1126                                         <literal>[scheme]://host.domain[:port][/script/name]</literal>,
1127                                         where <replaceable>scheme</replaceable> is either <literal>agi</literal>
1128                                         or <literal>hagi</literal>.</para>
1129                                         <para>In the case of <literal>hagi</literal>, an SRV lookup will be
1130                                         performed to try to connect to a list of FastAGI servers. The hostname in
1131                                         the URI must be prefixed with <literal>_agi._tcp</literal>. prior to the DNS resolution. For
1132                                         example, if you specify the URI <literal>hagi://agi.example.com/foo.agi</literal>
1133                                         the DNS query would be for <literal>_agi._tcp.agi.example.com</literal>. You
1134                                         will need to make sure this resolves correctly.</para>
1135                                 </enum>
1136                                 <enum name="AsyncAGI">
1137                                         <para>Use AMI to control the channel in AGI. AGI commands can be invoked
1138                                         using the <literal>AMI</literal> action, with a variety of AGI specific
1139                                         events passed back over the AMI connection. AsyncAGI should be invoked
1140                                         by passing <literal>agi:async</literal> to the <replaceable>command</replaceable>
1141                                         parameter.</para>
1142                                 </enum>
1143                         </enumlist>
1144                         <note>
1145                         <para>As of <literal>1.6.0</literal>, this channel will
1146                         not stop dialplan execution on hangup inside of this application. Dialplan
1147                         execution will continue normally, even upon hangup until the AGI application
1148                         signals a desire to stop (either by exiting or, in the case of a net script, by
1149                         closing the connection).</para>
1150                         <para>A locally executed AGI script will receive <literal>SIGHUP</literal> on
1151                         hangup from the channel except when using <literal>DeadAGI</literal>
1152                         (or when the channel is already hungup). A fast AGI server will
1153                         correspondingly receive a <literal>HANGUP</literal> inline with the command dialog.
1154                         Both of these signals may be disabled by setting the <variable>AGISIGHUP</variable>
1155                         channel variable to <literal>no</literal> before executing the AGI application.
1156                         Alternatively, if you would like the AGI application to exit immediately
1157                         after a channel hangup is detected, set the <variable>AGIEXITONHANGUP</variable>
1158                         variable to <literal>yes</literal>.</para>
1159                         </note>
1160                         <example title="AGI invocation examples">
1161                                 ; Start the AGI script /tmp/my-cool-script.sh, passing it the contents
1162                                 ; of the channel variable FOO
1163                                 same => n,AGI(/tmp/my-cool-script.sh,${FOO})
1164
1165                                 ; Start the AGI script my-cool-script.sh located in the astagidir
1166                                 ; directory, specified in asterisk.conf
1167                                 same => n,AGI(my-cool-script.sh)
1168
1169                                 ; Connect to the FastAGI server located at 127.0.0.1 and start the script
1170                                 ; awesome-script
1171                                 same => n,AGI(agi://127.0.0.1/awesome-script)
1172
1173                                 ; Start AsyncAGI
1174                                 same => n,AGI(agi:async)
1175                         </example>
1176                         <para>This application sets the following channel variable upon completion:</para>
1177                         <variablelist>
1178                                 <variable name="AGISTATUS">
1179                                         <para>The status of the attempt to the run the AGI script
1180                                         text string, one of:</para>
1181                                         <value name="SUCCESS" />
1182                                         <value name="FAILURE" />
1183                                         <value name="NOTFOUND" />
1184                                         <value name="HANGUP" />
1185                                 </variable>
1186                         </variablelist>
1187                 </description>
1188                 <see-also>
1189                         <ref type="manager">AGI</ref>
1190                         <ref type="managerEvent">AsyncAGIStart</ref>
1191                         <ref type="managerEvent">AsyncAGIEnd</ref>
1192                         <ref type="application">EAGI</ref>
1193                         <ref type="application">DeadAGI</ref>
1194                         <ref type="filename">asterisk.conf</ref>
1195                 </see-also>
1196         </application>
1197         <application name="EAGI" language="en_US">
1198                 <synopsis>
1199                         Executes an EAGI compliant application.
1200                 </synopsis>
1201                 <syntax>
1202                         <xi:include xpointer="xpointer(/docs/application[@name='AGI']/syntax/parameter[@name='command'])" />
1203                         <xi:include xpointer="xpointer(/docs/application[@name='AGI']/syntax/parameter[@name='args'])" />
1204                 </syntax>
1205                 <description>
1206                         <para>Using 'EAGI' provides enhanced AGI, with incoming audio available out of band
1207                         on file descriptor 3. In all other respects, it behaves in the same fashion as
1208                         AGI. See the documentation for the <literal>AGI</literal> dialplan application for
1209                         more information on invoking AGI on a channel.</para>
1210                         <para>This application sets the following channel variable upon completion:</para>
1211                         <xi:include xpointer="xpointer(/docs/application[@name='AGI']/description/variablelist)" />
1212                 </description>
1213                 <see-also>
1214                         <ref type="application">AGI</ref>
1215                         <ref type="application">DeadAGI</ref>
1216                 </see-also>
1217         </application>
1218         <application name="DeadAGI" language="en_US">
1219                 <synopsis>
1220                         Executes AGI on a hungup channel.
1221                 </synopsis>
1222                 <syntax>
1223                         <xi:include xpointer="xpointer(/docs/application[@name='AGI']/syntax/parameter[@name='command'])" />
1224                         <xi:include xpointer="xpointer(/docs/application[@name='AGI']/syntax/parameter[@name='args'])" />
1225                 </syntax>
1226                 <description>
1227                         <warning>
1228                                 <para>This application is deprecated and may be removed in a future version
1229                                 of Asterisk. Use the replacement application <literal>AGI</literal> instead
1230                                 of <literal>DeadAGI</literal>.
1231                                 </para>
1232                         </warning>
1233                         <para>Execute AGI on a 'dead' or hungup channel. See the documentation for the
1234                         <literal>AGI</literal> dialplan application for more information on invoking
1235                         AGI on a channel.</para>
1236                         <para>This application sets the following channel variable upon completion:</para>
1237                         <xi:include xpointer="xpointer(/docs/application[@name='AGI']/description/variablelist)" />
1238                 </description>
1239                 <see-also>
1240                         <ref type="application">AGI</ref>
1241                         <ref type="application">EAGI</ref>
1242                 </see-also>
1243         </application>
1244         <manager name="AGI" language="en_US">
1245                 <synopsis>
1246                         Add an AGI command to execute by Async AGI.
1247                 </synopsis>
1248                 <syntax>
1249                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1250                         <parameter name="Channel" required="true">
1251                                 <para>Channel that is currently in Async AGI.</para>
1252                         </parameter>
1253                         <parameter name="Command" required="true">
1254                                 <para>Application to execute.</para>
1255                         </parameter>
1256                         <parameter name="CommandID">
1257                                 <para>This will be sent back in CommandID header of AsyncAGI exec
1258                                 event notification.</para>
1259                         </parameter>
1260                 </syntax>
1261                 <description>
1262                         <para>Add an AGI command to the execute queue of the channel in Async AGI.</para>
1263                 </description>
1264                 <see-also>
1265                         <ref type="managerEvent">AsyncAGIStart</ref>
1266                         <ref type="managerEvent">AsyncAGIExec</ref>
1267                         <ref type="managerEvent">AsyncAGIEnd</ref>
1268                 </see-also>
1269         </manager>
1270         <managerEvent language="en_US" name="AsyncAGIStart">
1271                 <managerEventInstance class="EVENT_FLAG_AGI">
1272                         <synopsis>Raised when a channel starts AsyncAGI command processing.</synopsis>
1273                         <syntax>
1274                                 <channel_snapshot/>
1275                                 <parameter name="Env">
1276                                         <para>URL encoded string read from the AsyncAGI server.</para>
1277                                 </parameter>
1278                         </syntax>
1279                         <see-also>
1280                                 <ref type="managerEvent">AsyncAGIEnd</ref>
1281                                 <ref type="managerEvent">AsyncAGIExec</ref>
1282                                 <ref type="application">AGI</ref>
1283                                 <ref type="manager">AGI</ref>
1284                         </see-also>
1285                 </managerEventInstance>
1286         </managerEvent>
1287         <managerEvent language="en_US" name="AsyncAGIEnd">
1288                 <managerEventInstance class="EVENT_FLAG_AGI">
1289                         <synopsis>Raised when a channel stops AsyncAGI command processing.</synopsis>
1290                         <syntax>
1291                                 <channel_snapshot/>
1292                         </syntax>
1293                         <see-also>
1294                                 <ref type="managerEvent">AsyncAGIStart</ref>
1295                                 <ref type="managerEvent">AsyncAGIExec</ref>
1296                                 <ref type="application">AGI</ref>
1297                                 <ref type="manager">AGI</ref>
1298                         </see-also>
1299                 </managerEventInstance>
1300         </managerEvent>
1301         <managerEvent language="en_US" name="AsyncAGIExec">
1302                 <managerEventInstance class="EVENT_FLAG_AGI">
1303                         <synopsis>Raised when AsyncAGI completes an AGI command.</synopsis>
1304                         <syntax>
1305                                 <channel_snapshot/>
1306                                 <parameter name="CommandID" required="false">
1307                                         <para>Optional command ID sent by the AsyncAGI server to identify the command.</para>
1308                                 </parameter>
1309                                 <parameter name="Result">
1310                                         <para>URL encoded result string from the executed AGI command.</para>
1311                                 </parameter>
1312                         </syntax>
1313                         <see-also>
1314                                 <ref type="managerEvent">AsyncAGIStart</ref>
1315                                 <ref type="managerEvent">AsyncAGIEnd</ref>
1316                                 <ref type="application">AGI</ref>
1317                                 <ref type="manager">AGI</ref>
1318                         </see-also>
1319                 </managerEventInstance>
1320         </managerEvent>
1321         <managerEvent language="en_US" name="AGIExecStart">
1322                 <managerEventInstance class="EVENT_FLAG_AGI">
1323                         <synopsis>Raised when a received AGI command starts processing.</synopsis>
1324                         <syntax>
1325                                 <channel_snapshot/>
1326                                 <parameter name="Command">
1327                                         <para>The AGI command as received from the external source.</para>
1328                                 </parameter>
1329                                 <parameter name="CommandId">
1330                                         <para>Random identification number assigned to the execution of this command.</para>
1331                                 </parameter>
1332                         </syntax>
1333                         <see-also>
1334                                 <ref type="managerEvent">AGIExecEnd</ref>
1335                                 <ref type="application">AGI</ref>
1336                         </see-also>
1337                 </managerEventInstance>
1338         </managerEvent>
1339         <managerEvent language="en_US" name="AGIExecEnd">
1340                 <managerEventInstance class="EVENT_FLAG_AGI">
1341                         <synopsis>Raised when a received AGI command completes processing.</synopsis>
1342                         <syntax>
1343                                 <channel_snapshot/>
1344                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='AGIExecStart']/managerEventInstance/syntax/parameter)" />
1345                                 <parameter name="ResultCode">
1346                                         <para>The numeric result code from AGI</para>
1347                                 </parameter>
1348                                 <parameter name="Result">
1349                                         <para>The text result reason from AGI</para>
1350                                 </parameter>
1351                         </syntax>
1352                         <see-also>
1353                                 <ref type="managerEvent">AGIExecStart</ref>
1354                                 <ref type="application">AGI</ref>
1355                         </see-also>
1356                 </managerEventInstance>
1357         </managerEvent>
1358  ***/
1359
1360 #define MAX_ARGS 128
1361 #define MAX_CMD_LEN 80
1362 #define AGI_NANDFS_RETRY 3
1363 #define AGI_BUF_LEN 2048
1364 #define SRV_PREFIX "_agi._tcp."
1365
1366 static char *app = "AGI";
1367
1368 static char *eapp = "EAGI";
1369
1370 static char *deadapp = "DeadAGI";
1371
1372 static int agidebug = 0;
1373
1374 #define TONE_BLOCK_SIZE 200
1375
1376 /* Max time to connect to an AGI remote host */
1377 #define MAX_AGI_CONNECT 2000
1378
1379 #define AGI_PORT 4573
1380
1381 /*! Special return code for "asyncagi break" command. */
1382 #define ASYNC_AGI_BREAK 3
1383
1384 enum agi_result {
1385         AGI_RESULT_FAILURE = -1,
1386         AGI_RESULT_SUCCESS,
1387         AGI_RESULT_SUCCESS_FAST,
1388         AGI_RESULT_SUCCESS_ASYNC,
1389         AGI_RESULT_NOTFOUND,
1390         AGI_RESULT_HANGUP,
1391 };
1392
1393 static struct ast_manager_event_blob *agi_channel_to_ami(const char *type, struct stasis_message *message)
1394 {
1395         struct ast_channel_blob *obj = stasis_message_data(message);
1396         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
1397         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
1398
1399         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
1400         event_string = ast_manager_str_from_json_object(obj->blob, NULL);
1401         if (!channel_string || !event_string) {
1402                 return NULL;
1403         }
1404
1405         return ast_manager_event_blob_create(EVENT_FLAG_AGI, type,
1406                 "%s"
1407                 "%s",
1408                 ast_str_buffer(channel_string),
1409                 ast_str_buffer(event_string));
1410 }
1411
1412 static struct ast_manager_event_blob *agi_exec_start_to_ami(struct stasis_message *message)
1413 {
1414         return agi_channel_to_ami("AGIExecStart", message);
1415 }
1416
1417 static struct ast_manager_event_blob *agi_exec_end_to_ami(struct stasis_message *message)
1418 {
1419         return agi_channel_to_ami("AGIExecEnd", message);
1420 }
1421
1422 static struct ast_manager_event_blob *agi_async_start_to_ami(struct stasis_message *message)
1423 {
1424         return agi_channel_to_ami("AsyncAGIStart", message);
1425 }
1426
1427 static struct ast_manager_event_blob *agi_async_exec_to_ami(struct stasis_message *message)
1428 {
1429         return agi_channel_to_ami("AsyncAGIExec", message);
1430 }
1431
1432 static struct ast_manager_event_blob *agi_async_end_to_ami(struct stasis_message *message)
1433 {
1434         return agi_channel_to_ami("AsyncAGIEnd", message);
1435 }
1436
1437 STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_exec_start_type,
1438         .to_ami = agi_exec_start_to_ami,
1439         );
1440 STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_exec_end_type,
1441         .to_ami = agi_exec_end_to_ami,
1442         );
1443 STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_async_start_type,
1444         .to_ami = agi_async_start_to_ami,
1445         );
1446 STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_async_exec_type,
1447         .to_ami = agi_async_exec_to_ami,
1448         );
1449 STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_async_end_type,
1450         .to_ami = agi_async_end_to_ami,
1451         );
1452
1453 static agi_command *find_command(const char * const cmds[], int exact);
1454
1455 AST_THREADSTORAGE(agi_buf);
1456 #define AGI_BUF_INITSIZE 256
1457
1458 int AST_OPTIONAL_API_NAME(ast_agi_send)(int fd, struct ast_channel *chan, char *fmt, ...)
1459 {
1460         int res = 0;
1461         va_list ap;
1462         struct ast_str *buf;
1463
1464         if (!(buf = ast_str_thread_get(&agi_buf, AGI_BUF_INITSIZE)))
1465                 return -1;
1466
1467         va_start(ap, fmt);
1468         res = ast_str_set_va(&buf, 0, fmt, ap);
1469         va_end(ap);
1470
1471         if (res == -1) {
1472                 ast_log(LOG_ERROR, "Out of memory\n");
1473                 return -1;
1474         }
1475
1476         if (agidebug) {
1477                 if (chan) {
1478                         ast_verbose("<%s>AGI Tx >> %s", ast_channel_name(chan), ast_str_buffer(buf));
1479                 } else {
1480                         ast_verbose("AGI Tx >> %s", ast_str_buffer(buf));
1481                 }
1482         }
1483
1484         return ast_carefulwrite(fd, ast_str_buffer(buf), ast_str_strlen(buf), 100);
1485 }
1486
1487 /* linked list of AGI commands ready to be executed by Async AGI */
1488 struct agi_cmd {
1489         char *cmd_buffer;
1490         char *cmd_id;
1491         AST_LIST_ENTRY(agi_cmd) entry;
1492 };
1493
1494 static void free_agi_cmd(struct agi_cmd *cmd)
1495 {
1496         ast_free(cmd->cmd_buffer);
1497         ast_free(cmd->cmd_id);
1498         ast_free(cmd);
1499 }
1500
1501 /* AGI datastore destructor */
1502 static void agi_destroy_commands_cb(void *data)
1503 {
1504         struct agi_cmd *cmd;
1505         AST_LIST_HEAD(, agi_cmd) *chan_cmds = data;
1506         AST_LIST_LOCK(chan_cmds);
1507         while ( (cmd = AST_LIST_REMOVE_HEAD(chan_cmds, entry)) ) {
1508                 free_agi_cmd(cmd);
1509         }
1510         AST_LIST_UNLOCK(chan_cmds);
1511         AST_LIST_HEAD_DESTROY(chan_cmds);
1512         ast_free(chan_cmds);
1513 }
1514
1515 /* channel datastore to keep the queue of AGI commands in the channel */
1516 static const struct ast_datastore_info agi_commands_datastore_info = {
1517         .type = "AsyncAGI",
1518         .destroy = agi_destroy_commands_cb
1519 };
1520
1521 /*!
1522  * \brief Retrieve the list head to the requested channel's AGI datastore
1523  * \param chan Channel datastore is requested for
1524  * \param cmd Pointer to the struct pointer which will reference the head of the agi command list.
1525  *
1526  * \retval 0 if the datastore was valid and the list head was retrieved appropriately (even if it's
1527  *           NULL and the list is empty)
1528  * \retval -1 if the datastore could not be retrieved causing an error
1529 */
1530 static int get_agi_cmd(struct ast_channel *chan, struct agi_cmd **cmd)
1531 {
1532         struct ast_datastore *store;
1533         AST_LIST_HEAD(, agi_cmd) *agi_commands;
1534
1535         ast_channel_lock(chan);
1536         store = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
1537         ast_channel_unlock(chan);
1538         if (!store) {
1539                 ast_log(LOG_ERROR, "Huh? Async AGI datastore disappeared on Channel %s!\n",
1540                         ast_channel_name(chan));
1541                 *cmd = NULL;
1542                 return -1;
1543         }
1544         agi_commands = store->data;
1545         AST_LIST_LOCK(agi_commands);
1546         *cmd = AST_LIST_REMOVE_HEAD(agi_commands, entry);
1547         AST_LIST_UNLOCK(agi_commands);
1548         return 0;
1549 }
1550
1551 /* channel is locked when calling this one either from the CLI or manager thread */
1552 static int add_agi_cmd(struct ast_channel *chan, const char *cmd_buff, const char *cmd_id)
1553 {
1554         struct ast_datastore *store;
1555         struct agi_cmd *cmd;
1556         AST_LIST_HEAD(, agi_cmd) *agi_commands;
1557
1558         store = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
1559         if (!store) {
1560                 ast_log(LOG_WARNING, "Channel %s is not setup for Async AGI.\n", ast_channel_name(chan));
1561                 return -1;
1562         }
1563         agi_commands = store->data;
1564         cmd = ast_calloc(1, sizeof(*cmd));
1565         if (!cmd) {
1566                 return -1;
1567         }
1568         cmd->cmd_buffer = ast_strdup(cmd_buff);
1569         if (!cmd->cmd_buffer) {
1570                 ast_free(cmd);
1571                 return -1;
1572         }
1573         cmd->cmd_id = ast_strdup(cmd_id);
1574         if (!cmd->cmd_id) {
1575                 ast_free(cmd->cmd_buffer);
1576                 ast_free(cmd);
1577                 return -1;
1578         }
1579         AST_LIST_LOCK(agi_commands);
1580         AST_LIST_INSERT_TAIL(agi_commands, cmd, entry);
1581         AST_LIST_UNLOCK(agi_commands);
1582         return 0;
1583 }
1584
1585 static int add_to_agi(struct ast_channel *chan)
1586 {
1587         struct ast_datastore *datastore;
1588         AST_LIST_HEAD(, agi_cmd) *agi_cmds_list;
1589
1590         /* check if already on AGI */
1591         ast_channel_lock(chan);
1592         datastore = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
1593         ast_channel_unlock(chan);
1594         if (datastore) {
1595                 /* we already have an AGI datastore, let's just
1596                    return success */
1597                 return 0;
1598         }
1599
1600         /* the channel has never been on Async AGI,
1601            let's allocate it's datastore */
1602         datastore = ast_datastore_alloc(&agi_commands_datastore_info, "AGI");
1603         if (!datastore) {
1604                 return -1;
1605         }
1606         agi_cmds_list = ast_calloc(1, sizeof(*agi_cmds_list));
1607         if (!agi_cmds_list) {
1608                 ast_log(LOG_ERROR, "Unable to allocate Async AGI commands list.\n");
1609                 ast_datastore_free(datastore);
1610                 return -1;
1611         }
1612         datastore->data = agi_cmds_list;
1613         AST_LIST_HEAD_INIT(agi_cmds_list);
1614         ast_channel_lock(chan);
1615         ast_channel_datastore_add(chan, datastore);
1616         ast_channel_unlock(chan);
1617         return 0;
1618 }
1619
1620 /*!
1621  * \brief CLI command to add applications to execute in Async AGI
1622  * \param e
1623  * \param cmd
1624  * \param a
1625  *
1626  * \retval CLI_SUCCESS on success
1627  * \retval NULL when init or tab completion is used
1628 */
1629 static char *handle_cli_agi_add_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1630 {
1631         struct ast_channel *chan;
1632         switch (cmd) {
1633         case CLI_INIT:
1634                 e->command = "agi exec";
1635                 e->usage = "Usage: agi exec <channel name> <app and arguments> [id]\n"
1636                            "       Add AGI command to the execute queue of the specified channel in Async AGI\n";
1637                 return NULL;
1638         case CLI_GENERATE:
1639                 if (a->pos == 2)
1640                         return ast_complete_channels(a->line, a->word, a->pos, a->n, 2);
1641                 return NULL;
1642         }
1643
1644         if (a->argc < 4) {
1645                 return CLI_SHOWUSAGE;
1646         }
1647
1648         if (!(chan = ast_channel_get_by_name(a->argv[2]))) {
1649                 ast_cli(a->fd, "Channel %s does not exist.\n", a->argv[2]);
1650                 return CLI_FAILURE;
1651         }
1652
1653         ast_channel_lock(chan);
1654
1655         if (add_agi_cmd(chan, a->argv[3], (a->argc > 4 ? a->argv[4] : ""))) {
1656                 ast_cli(a->fd, "Failed to add AGI command to queue of channel %s\n", ast_channel_name(chan));
1657                 ast_channel_unlock(chan);
1658                 chan = ast_channel_unref(chan);
1659                 return CLI_FAILURE;
1660         }
1661
1662         ast_debug(1, "Added AGI command to channel %s queue\n", ast_channel_name(chan));
1663
1664         ast_channel_unlock(chan);
1665         chan = ast_channel_unref(chan);
1666
1667         return CLI_SUCCESS;
1668 }
1669
1670 /*!
1671  * \brief Add a new command to execute by the Async AGI application
1672  * \param s
1673  * \param m
1674  *
1675  * It will append the application to the specified channel's queue
1676  * if the channel is not inside Async AGI application it will return an error
1677  * \retval 0 on success or incorrect use
1678  * \retval 1 on failure to add the command ( most likely because the channel
1679  * is not in Async AGI loop )
1680 */
1681 static int action_add_agi_cmd(struct mansession *s, const struct message *m)
1682 {
1683         const char *channel = astman_get_header(m, "Channel");
1684         const char *cmdbuff = astman_get_header(m, "Command");
1685         const char *cmdid   = astman_get_header(m, "CommandID");
1686         struct ast_channel *chan;
1687         char buf[256];
1688
1689         if (ast_strlen_zero(channel) || ast_strlen_zero(cmdbuff)) {
1690                 astman_send_error(s, m, "Both, Channel and Command are *required*");
1691                 return 0;
1692         }
1693
1694         if (!(chan = ast_channel_get_by_name(channel))) {
1695                 snprintf(buf, sizeof(buf), "Channel %s does not exist.", channel);
1696                 astman_send_error(s, m, buf);
1697                 return 0;
1698         }
1699
1700         ast_channel_lock(chan);
1701
1702         if (add_agi_cmd(chan, cmdbuff, cmdid)) {
1703                 snprintf(buf, sizeof(buf), "Failed to add AGI command to channel %s queue", ast_channel_name(chan));
1704                 astman_send_error(s, m, buf);
1705                 ast_channel_unlock(chan);
1706                 chan = ast_channel_unref(chan);
1707                 return 0;
1708         }
1709
1710         ast_channel_unlock(chan);
1711         chan = ast_channel_unref(chan);
1712
1713         astman_send_ack(s, m, "Added AGI command to queue");
1714
1715         return 0;
1716 }
1717
1718 static enum agi_result agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int dead);
1719 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced, int argc, char *argv[]);
1720
1721 /*!
1722  * \internal
1723  * \brief Read and handle a channel frame for Async AGI.
1724  *
1725  * \param chan Channel to read a frame from.
1726  *
1727  * \retval AGI_RESULT_SUCCESS on success.
1728  * \retval AGI_RESULT_HANGUP on hangup.
1729  * \retval AGI_RESULT_FAILURE on error.
1730  */
1731 static enum agi_result async_agi_read_frame(struct ast_channel *chan)
1732 {
1733         struct ast_frame *f;
1734
1735         f = ast_read(chan);
1736         if (!f) {
1737                 ast_debug(3, "No frame read on channel %s, going out ...\n", ast_channel_name(chan));
1738                 return AGI_RESULT_HANGUP;
1739         }
1740         if (f->frametype == AST_FRAME_CONTROL) {
1741                 /*
1742                  * Is there any other frame we should care about besides
1743                  * AST_CONTROL_HANGUP?
1744                  */
1745                 switch (f->subclass.integer) {
1746                 case AST_CONTROL_HANGUP:
1747                         ast_debug(3, "Got HANGUP frame on channel %s, going out ...\n", ast_channel_name(chan));
1748                         ast_frfree(f);
1749                         return AGI_RESULT_HANGUP;
1750                 default:
1751                         break;
1752                 }
1753         }
1754         ast_frfree(f);
1755
1756         return AGI_RESULT_SUCCESS;
1757 }
1758
1759 static enum agi_result launch_asyncagi(struct ast_channel *chan, int argc, char *argv[], int *efd)
1760 {
1761 /* This buffer sizes might cause truncation if the AGI command writes more data
1762    than AGI_BUF_SIZE as result. But let's be serious, is there an AGI command
1763    that writes a response larger than 1024 bytes?, I don't think so, most of
1764    them are just result=blah stuff. However probably if GET VARIABLE is called
1765    and the variable has large amount of data, that could be a problem. We could
1766    make this buffers dynamic, but let's leave that as a second step.
1767
1768    AMI_BUF_SIZE is twice AGI_BUF_SIZE just for the sake of choosing a safe
1769    number. Some characters of AGI buf will be url encoded to be sent to manager
1770    clients.  An URL encoded character will take 3 bytes, but again, to cause
1771    truncation more than about 70% of the AGI buffer should be URL encoded for
1772    that to happen.  Not likely at all.
1773
1774    On the other hand. I wonder if read() could eventually return less data than
1775    the amount already available in the pipe? If so, how to deal with that?
1776    So far, my tests on Linux have not had any problems.
1777  */
1778 #define AGI_BUF_SIZE 1024
1779 #define AMI_BUF_SIZE 2048
1780         enum agi_result cmd_status;
1781         struct agi_cmd *cmd;
1782         int res;
1783         int fds[2];
1784         int hungup;
1785         int timeout = 100;
1786         char agi_buffer[AGI_BUF_SIZE + 1];
1787         char ami_buffer[AMI_BUF_SIZE];
1788         enum agi_result returnstatus = AGI_RESULT_SUCCESS;
1789         AGI async_agi;
1790         RAII_VAR(struct ast_json *, startblob, NULL, ast_json_unref);
1791
1792         if (efd) {
1793                 ast_log(LOG_WARNING, "Async AGI does not support Enhanced AGI yet\n");
1794                 return AGI_RESULT_FAILURE;
1795         }
1796
1797         /* add AsyncAGI datastore to the channel */
1798         if (add_to_agi(chan)) {
1799                 ast_log(LOG_ERROR, "Failed to start Async AGI on channel %s\n", ast_channel_name(chan));
1800                 return AGI_RESULT_FAILURE;
1801         }
1802
1803         /* this pipe allows us to create a "fake" AGI struct to use
1804            the AGI commands */
1805         res = pipe(fds);
1806         if (res) {
1807                 ast_log(LOG_ERROR, "Failed to create Async AGI pipe\n");
1808                 /*
1809                  * Intentionally do not remove the datastore added with
1810                  * add_to_agi() the from channel.  It will be removed when the
1811                  * channel is hung up anyway.
1812                  */
1813                 return AGI_RESULT_FAILURE;
1814         }
1815
1816         /* handlers will get the pipe write fd and we read the AGI responses
1817            from the pipe read fd */
1818         async_agi.fd = fds[1];
1819         async_agi.ctrl = fds[1];
1820         async_agi.audio = -1; /* no audio support */
1821         async_agi.fast = 0;
1822         async_agi.speech = NULL;
1823
1824         /* notify possible manager users of a new channel ready to
1825            receive commands */
1826         setup_env(chan, "async", fds[1], 0, argc, argv);
1827         /* read the environment */
1828         res = read(fds[0], agi_buffer, AGI_BUF_SIZE);
1829         if (res <= 0) {
1830                 ast_log(LOG_ERROR, "Failed to read from Async AGI pipe on channel %s: %s\n",
1831                                 ast_channel_name(chan), res < 0 ? strerror(errno) : "EOF");
1832                 returnstatus = AGI_RESULT_FAILURE;
1833                 goto async_agi_abort;
1834         }
1835         agi_buffer[res] = '\0';
1836         /* encode it and send it thru the manager so whoever is going to take
1837            care of AGI commands on this channel can decide which AGI commands
1838            to execute based on the setup info */
1839         ast_uri_encode(agi_buffer, ami_buffer, AMI_BUF_SIZE, ast_uri_http);
1840         startblob = ast_json_pack("{s: s}", "Env", ami_buffer);
1841
1842         ast_channel_publish_cached_blob(chan, agi_async_start_type(), startblob);
1843
1844         hungup = ast_check_hangup_locked(chan);
1845
1846         for (;;) {
1847                 /*
1848                  * Process as many commands as we can.  Commands are added via
1849                  * the manager or the cli threads.
1850                  */
1851                 while (!hungup) {
1852                         RAII_VAR(struct ast_json *, execblob, NULL, ast_json_unref);
1853                         res = get_agi_cmd(chan, &cmd);
1854
1855                         if (res) {
1856                                 returnstatus = AGI_RESULT_FAILURE;
1857                                 goto async_agi_done;
1858                         } else if (!cmd) {
1859                                 break;
1860                         }
1861
1862                         /* OK, we have a command, let's call the command handler. */
1863                         cmd_status = agi_handle_command(chan, &async_agi, cmd->cmd_buffer, 0);
1864
1865                         /*
1866                          * The command handler must have written to our fake AGI struct
1867                          * fd (the pipe), let's read the response.
1868                          */
1869                         res = read(fds[0], agi_buffer, AGI_BUF_SIZE);
1870                         if (res <= 0) {
1871                                 ast_log(LOG_ERROR, "Failed to read from Async AGI pipe on channel %s: %s\n",
1872                                         ast_channel_name(chan), res < 0 ? strerror(errno) : "EOF");
1873                                 free_agi_cmd(cmd);
1874                                 returnstatus = AGI_RESULT_FAILURE;
1875                                 goto async_agi_done;
1876                         }
1877                         /*
1878                          * We have a response, let's send the response thru the manager.
1879                          * Include the CommandID if it was specified when the command
1880                          * was added.
1881                          */
1882                         agi_buffer[res] = '\0';
1883                         ast_uri_encode(agi_buffer, ami_buffer, AMI_BUF_SIZE, ast_uri_http);
1884
1885                         execblob = ast_json_pack("{s: s}", "Result", ami_buffer);
1886                         if (execblob && !ast_strlen_zero(cmd->cmd_id)) {
1887                                 ast_json_object_set(execblob, "CommandId", ast_json_string_create(cmd->cmd_id));
1888                         }
1889                         ast_channel_publish_cached_blob(chan, agi_async_exec_type(), execblob);
1890
1891                         free_agi_cmd(cmd);
1892
1893                         /*
1894                          * Check the command status to determine if we should continue
1895                          * executing more commands.
1896                          */
1897                         hungup = ast_check_hangup(chan);
1898                         switch (cmd_status) {
1899                         case AGI_RESULT_FAILURE:
1900                                 if (!hungup) {
1901                                         /* The failure was not because of a hangup. */
1902                                         returnstatus = AGI_RESULT_FAILURE;
1903                                         goto async_agi_done;
1904                                 }
1905                                 break;
1906                         case AGI_RESULT_SUCCESS_ASYNC:
1907                                 /* Only the "asyncagi break" command does this. */
1908                                 returnstatus = AGI_RESULT_SUCCESS_ASYNC;
1909                                 goto async_agi_done;
1910                         default:
1911                                 break;
1912                         }
1913                 }
1914
1915                 if (!hungup) {
1916                         /* Wait a bit for a frame to read or to poll for a new command. */
1917                         res = ast_waitfor(chan, timeout);
1918                         if (res < 0) {
1919                                 ast_debug(1, "ast_waitfor returned <= 0 on chan %s\n", ast_channel_name(chan));
1920                                 returnstatus = AGI_RESULT_FAILURE;
1921                                 break;
1922                         }
1923                 } else {
1924                         /*
1925                          * Read the channel control queue until it is dry so we can
1926                          * quit.
1927                          */
1928                         res = 1;
1929                 }
1930                 if (0 < res) {
1931                         do {
1932                                 cmd_status = async_agi_read_frame(chan);
1933                                 if (cmd_status != AGI_RESULT_SUCCESS) {
1934                                         returnstatus = cmd_status;
1935                                         goto async_agi_done;
1936                                 }
1937                                 hungup = ast_check_hangup(chan);
1938                         } while (hungup);
1939                 } else {
1940                         hungup = ast_check_hangup(chan);
1941                 }
1942         }
1943 async_agi_done:
1944
1945         if (async_agi.speech) {
1946                 ast_speech_destroy(async_agi.speech);
1947         }
1948         /* notify manager users this channel cannot be controlled anymore by Async AGI */
1949         ast_channel_publish_cached_blob(chan, agi_async_end_type(), NULL);
1950
1951 async_agi_abort:
1952         /* close the pipe */
1953         close(fds[0]);
1954         close(fds[1]);
1955
1956         /*
1957          * Intentionally do not remove the datastore added with
1958          * add_to_agi() the from channel.  There might be commands still
1959          * in the queue or in-flight to us and AsyncAGI may get called
1960          * again.  The datastore destructor will be called on channel
1961          * destruction anyway.
1962          */
1963
1964         if (returnstatus == AGI_RESULT_SUCCESS) {
1965                 returnstatus = AGI_RESULT_SUCCESS_ASYNC;
1966         }
1967         return returnstatus;
1968
1969 #undef AGI_BUF_SIZE
1970 #undef AMI_BUF_SIZE
1971 }
1972
1973 /*!
1974  * \internal
1975  * \brief Handle the connection that was started by launch_netscript.
1976  *
1977  * \param agiurl Url that we are trying to connect to.
1978  * \param addr Address that host was resolved to.
1979  * \param netsockfd File descriptor of socket.
1980  *
1981  * \retval 0 when connection is succesful.
1982  * \retval 1 when there is an error.
1983  */
1984 static int handle_connection(const char *agiurl, const struct ast_sockaddr addr, const int netsockfd)
1985 {
1986         struct pollfd pfds[1];
1987         int res, conresult;
1988         socklen_t reslen;
1989
1990         reslen = sizeof(conresult);
1991
1992         pfds[0].fd = netsockfd;
1993         pfds[0].events = POLLOUT;
1994
1995         while ((res = ast_poll(pfds, 1, MAX_AGI_CONNECT)) != 1) {
1996                 if (errno != EINTR) {
1997                         if (!res) {
1998                                 ast_log(LOG_WARNING, "FastAGI connection to '%s' timed out after MAX_AGI_CONNECT (%d) milliseconds.\n",
1999                                         agiurl, MAX_AGI_CONNECT);
2000                         } else {
2001                                 ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
2002                         }
2003
2004                         return 1;
2005                 }
2006         }
2007
2008         if (getsockopt(pfds[0].fd, SOL_SOCKET, SO_ERROR, &conresult, &reslen) < 0) {
2009                 ast_log(LOG_WARNING, "Connection to %s failed with error: %s\n",
2010                         ast_sockaddr_stringify(&addr), strerror(errno));
2011                 return 1;
2012         }
2013
2014         if (conresult) {
2015                 ast_log(LOG_WARNING, "Connecting to '%s' failed for url '%s': %s\n",
2016                         ast_sockaddr_stringify(&addr), agiurl, strerror(conresult));
2017                 return 1;
2018         }
2019
2020         return 0;
2021 }
2022
2023 /* launch_netscript: The fastagi handler.
2024         FastAGI defaults to port 4573 */
2025 static enum agi_result launch_netscript(char *agiurl, char *argv[], int *fds)
2026 {
2027         int s = 0, flags;
2028         char *host, *script;
2029         int num_addrs = 0, i = 0;
2030         struct ast_sockaddr *addrs;
2031
2032         /* agiurl is "agi://host.domain[:port][/script/name]" */
2033         host = ast_strdupa(agiurl + 6); /* Remove agi:// */
2034
2035         /* Strip off any script name */
2036         if ((script = strchr(host, '/'))) {
2037                 *script++ = '\0';
2038         } else {
2039                 script = "";
2040         }
2041
2042         if (!(num_addrs = ast_sockaddr_resolve(&addrs, host, 0, AST_AF_UNSPEC))) {
2043                 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", host);
2044                 return AGI_RESULT_FAILURE;
2045         }
2046
2047         for (i = 0; i < num_addrs; i++) {
2048                 if (!ast_sockaddr_port(&addrs[i])) {
2049                         ast_sockaddr_set_port(&addrs[i], AGI_PORT);
2050                 }
2051
2052                 if ((s = socket(addrs[i].ss.ss_family, SOCK_STREAM, IPPROTO_TCP)) < 0) {
2053                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
2054                         continue;
2055                 }
2056
2057                 if ((flags = fcntl(s, F_GETFL)) < 0) {
2058                         ast_log(LOG_WARNING, "fcntl(F_GETFL) failed: %s\n", strerror(errno));
2059                         close(s);
2060                         continue;
2061                 }
2062
2063                 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0) {
2064                         ast_log(LOG_WARNING, "fnctl(F_SETFL) failed: %s\n", strerror(errno));
2065                         close(s);
2066                         continue;
2067                 }
2068
2069                 if (ast_connect(s, &addrs[i]) && errno == EINPROGRESS) {
2070
2071                         if (handle_connection(agiurl, addrs[i], s)) {
2072                                 close(s);
2073                                 continue;
2074                         }
2075
2076                 } else {
2077                         ast_log(LOG_WARNING, "Connection to %s failed with unexpected error: %s\n",
2078                         ast_sockaddr_stringify(&addrs[i]), strerror(errno));
2079                 }
2080
2081                 break;
2082         }
2083
2084         ast_free(addrs);
2085
2086         if (i == num_addrs) {
2087                 ast_log(LOG_WARNING, "Couldn't connect to any host.  FastAGI failed.\n");
2088                 return AGI_RESULT_FAILURE;
2089         }
2090
2091         if (ast_agi_send(s, NULL, "agi_network: yes\n") < 0) {
2092                 if (errno != EINTR) {
2093                         ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
2094                         close(s);
2095                         return AGI_RESULT_FAILURE;
2096                 }
2097         }
2098
2099         /* If we have a script parameter, relay it to the fastagi server */
2100         /* Script parameters take the form of: AGI(agi://my.example.com/?extension=${EXTEN}) */
2101         if (!ast_strlen_zero(script)) {
2102                 ast_agi_send(s, NULL, "agi_network_script: %s\n", script);
2103         }
2104
2105         ast_debug(4, "Wow, connected!\n");
2106         fds[0] = s;
2107         fds[1] = s;
2108         return AGI_RESULT_SUCCESS_FAST;
2109 }
2110
2111 /*!
2112  * \internal
2113  * \brief The HA fastagi handler.
2114  * \param agiurl The request URL as passed to Agi() in the dial plan
2115  * \param argv The parameters after the URL passed to Agi() in the dial plan
2116  * \param fds Input/output file descriptors
2117  *
2118  * Uses SRV lookups to try to connect to a list of FastAGI servers. The hostname in
2119  * the URI is prefixed with _agi._tcp. prior to the DNS resolution. For
2120  * example, if you specify the URI \a hagi://agi.example.com/foo.agi the DNS
2121  * query would be for \a _agi._tcp.agi.example.com and you'll need to make sure
2122  * this resolves.
2123  *
2124  * This function parses the URI, resolves the SRV service name, forms new URIs
2125  * with the results of the DNS lookup, and then calls launch_netscript on the
2126  * new URIs until one succeeds.
2127  *
2128  * \return the result of the AGI operation.
2129  */
2130 static enum agi_result launch_ha_netscript(char *agiurl, char *argv[], int *fds)
2131 {
2132         char *host, *script;
2133         enum agi_result result;
2134         struct srv_context *context = NULL;
2135         int srv_ret;
2136         char service[256];
2137         char resolved_uri[1024];
2138         const char *srvhost;
2139         unsigned short srvport;
2140
2141         /* format of agiurl is "hagi://host.domain[:port][/script/name]" */
2142         if (strlen(agiurl) < 7) { /* Remove hagi:// */
2143                 ast_log(LOG_WARNING, "An error occurred parsing the AGI URI: %s", agiurl);
2144                 return AGI_RESULT_FAILURE;
2145         }
2146         host = ast_strdupa(agiurl + 7);
2147
2148         /* Strip off any script name */
2149         if ((script = strchr(host, '/'))) {
2150                 *script++ = '\0';
2151         } else {
2152                 script = "";
2153         }
2154
2155         if (strchr(host, ':')) {
2156                 ast_log(LOG_WARNING, "Specifying a port number disables SRV lookups: %s\n", agiurl);
2157                 return launch_netscript(agiurl + 1, argv, fds); /* +1 to strip off leading h from hagi:// */
2158         }
2159
2160         snprintf(service, sizeof(service), "%s%s", SRV_PREFIX, host);
2161
2162         while (!(srv_ret = ast_srv_lookup(&context, service, &srvhost, &srvport))) {
2163                 snprintf(resolved_uri, sizeof(resolved_uri), "agi://%s:%d/%s", srvhost, srvport, script);
2164                 result = launch_netscript(resolved_uri, argv, fds);
2165                 if (result == AGI_RESULT_FAILURE || result == AGI_RESULT_NOTFOUND) {
2166                         ast_log(LOG_WARNING, "AGI request failed for host '%s' (%s:%d)\n", host, srvhost, srvport);
2167                 } else {
2168                         /* The script launched so we must cleanup the context. */
2169                         ast_srv_cleanup(&context);
2170                         return result;
2171                 }
2172         }
2173         /*
2174          * The DNS SRV lookup failed or we ran out of servers to check.
2175          * ast_srv_lookup() has already cleaned up the context for us.
2176          */
2177         if (srv_ret < 0) {
2178                 ast_log(LOG_WARNING, "SRV lookup failed for %s\n", agiurl);
2179         }
2180
2181         return AGI_RESULT_FAILURE;
2182 }
2183
2184 static enum agi_result launch_script(struct ast_channel *chan, char *script, int argc, char *argv[], int *fds, int *efd, int *opid)
2185 {
2186         char tmp[256];
2187         int pid, toast[2], fromast[2], audio[2], res;
2188         struct stat st;
2189
2190         if (!strncasecmp(script, "agi://", 6)) {
2191                 return (efd == NULL) ? launch_netscript(script, argv, fds) : AGI_RESULT_FAILURE;
2192         }
2193         if (!strncasecmp(script, "hagi://", 7)) {
2194                 return (efd == NULL) ? launch_ha_netscript(script, argv, fds) : AGI_RESULT_FAILURE;
2195         }
2196         if (!strncasecmp(script, "agi:async", sizeof("agi:async") - 1)) {
2197                 return launch_asyncagi(chan, argc, argv, efd);
2198         }
2199
2200         if (script[0] != '/') {
2201                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_AGI_DIR, script);
2202                 script = tmp;
2203         }
2204
2205         /* Before even trying let's see if the file actually exists */
2206         if (stat(script, &st)) {
2207                 ast_log(LOG_WARNING, "Failed to execute '%s': File does not exist.\n", script);
2208                 return AGI_RESULT_NOTFOUND;
2209         }
2210
2211         if (pipe(toast)) {
2212                 ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
2213                 return AGI_RESULT_FAILURE;
2214         }
2215         if (pipe(fromast)) {
2216                 ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
2217                 close(toast[0]);
2218                 close(toast[1]);
2219                 return AGI_RESULT_FAILURE;
2220         }
2221         if (efd) {
2222                 if (pipe(audio)) {
2223                         ast_log(LOG_WARNING, "unable to create audio pipe: %s\n", strerror(errno));
2224                         close(fromast[0]);
2225                         close(fromast[1]);
2226                         close(toast[0]);
2227                         close(toast[1]);
2228                         return AGI_RESULT_FAILURE;
2229                 }
2230                 res = fcntl(audio[1], F_GETFL);
2231                 if (res > -1)
2232                         res = fcntl(audio[1], F_SETFL, res | O_NONBLOCK);
2233                 if (res < 0) {
2234                         ast_log(LOG_WARNING, "unable to set audio pipe parameters: %s\n", strerror(errno));
2235                         close(fromast[0]);
2236                         close(fromast[1]);
2237                         close(toast[0]);
2238                         close(toast[1]);
2239                         close(audio[0]);
2240                         close(audio[1]);
2241                         return AGI_RESULT_FAILURE;
2242                 }
2243         }
2244
2245         if ((pid = ast_safe_fork(1)) < 0) {
2246                 ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
2247                 return AGI_RESULT_FAILURE;
2248         }
2249         if (!pid) {
2250                 /* Pass paths to AGI via environmental variables */
2251                 setenv("AST_CONFIG_DIR", ast_config_AST_CONFIG_DIR, 1);
2252                 setenv("AST_CONFIG_FILE", ast_config_AST_CONFIG_FILE, 1);
2253                 setenv("AST_MODULE_DIR", ast_config_AST_MODULE_DIR, 1);
2254                 setenv("AST_SPOOL_DIR", ast_config_AST_SPOOL_DIR, 1);
2255                 setenv("AST_MONITOR_DIR", ast_config_AST_MONITOR_DIR, 1);
2256                 setenv("AST_VAR_DIR", ast_config_AST_VAR_DIR, 1);
2257                 setenv("AST_DATA_DIR", ast_config_AST_DATA_DIR, 1);
2258                 setenv("AST_LOG_DIR", ast_config_AST_LOG_DIR, 1);
2259                 setenv("AST_AGI_DIR", ast_config_AST_AGI_DIR, 1);
2260                 setenv("AST_KEY_DIR", ast_config_AST_KEY_DIR, 1);
2261                 setenv("AST_RUN_DIR", ast_config_AST_RUN_DIR, 1);
2262
2263                 /* Don't run AGI scripts with realtime priority -- it causes audio stutter */
2264                 ast_set_priority(0);
2265
2266                 /* Redirect stdin and out, provide enhanced audio channel if desired */
2267                 dup2(fromast[0], STDIN_FILENO);
2268                 dup2(toast[1], STDOUT_FILENO);
2269                 if (efd)
2270                         dup2(audio[0], STDERR_FILENO + 1);
2271                 else
2272                         close(STDERR_FILENO + 1);
2273
2274                 /* Close everything but stdin/out/error */
2275                 ast_close_fds_above_n(STDERR_FILENO + 1);
2276
2277                 /* Execute script */
2278                 /* XXX argv should be deprecated in favor of passing agi_argX paramaters */
2279                 execv(script, argv);
2280                 /* Can't use ast_log since FD's are closed */
2281                 ast_child_verbose(1, "Failed to execute '%s': %s", script, strerror(errno));
2282                 /* Special case to set status of AGI to failure */
2283                 fprintf(stdout, "failure\n");
2284                 fflush(stdout);
2285                 _exit(1);
2286         }
2287         ast_verb(3, "Launched AGI Script %s\n", script);
2288         fds[0] = toast[0];
2289         fds[1] = fromast[1];
2290         if (efd)
2291                 *efd = audio[1];
2292         /* close what we're not using in the parent */
2293         close(toast[1]);
2294         close(fromast[0]);
2295
2296         if (efd)
2297                 close(audio[0]);
2298
2299         *opid = pid;
2300         return AGI_RESULT_SUCCESS;
2301 }
2302
2303 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced, int argc, char *argv[])
2304 {
2305         int count;
2306
2307         /* Print initial environment, with agi_request always being the first
2308            thing */
2309         ast_agi_send(fd, chan, "agi_request: %s\n", request);
2310         ast_agi_send(fd, chan, "agi_channel: %s\n", ast_channel_name(chan));
2311         ast_agi_send(fd, chan, "agi_language: %s\n", ast_channel_language(chan));
2312         ast_agi_send(fd, chan, "agi_type: %s\n", ast_channel_tech(chan)->type);
2313         ast_agi_send(fd, chan, "agi_uniqueid: %s\n", ast_channel_uniqueid(chan));
2314         ast_agi_send(fd, chan, "agi_version: %s\n", ast_get_version());
2315
2316         /* ANI/DNIS */
2317         ast_agi_send(fd, chan, "agi_callerid: %s\n",
2318                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "unknown"));
2319         ast_agi_send(fd, chan, "agi_calleridname: %s\n",
2320                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "unknown"));
2321         ast_agi_send(fd, chan, "agi_callingpres: %d\n",
2322                 ast_party_id_presentation(&ast_channel_caller(chan)->id));
2323         ast_agi_send(fd, chan, "agi_callingani2: %d\n", ast_channel_caller(chan)->ani2);
2324         ast_agi_send(fd, chan, "agi_callington: %d\n", ast_channel_caller(chan)->id.number.plan);
2325         ast_agi_send(fd, chan, "agi_callingtns: %d\n", ast_channel_dialed(chan)->transit_network_select);
2326         ast_agi_send(fd, chan, "agi_dnid: %s\n", S_OR(ast_channel_dialed(chan)->number.str, "unknown"));
2327         ast_agi_send(fd, chan, "agi_rdnis: %s\n",
2328                 S_COR(ast_channel_redirecting(chan)->from.number.valid, ast_channel_redirecting(chan)->from.number.str, "unknown"));
2329
2330         /* Context information */
2331         ast_agi_send(fd, chan, "agi_context: %s\n", ast_channel_context(chan));
2332         ast_agi_send(fd, chan, "agi_extension: %s\n", ast_channel_exten(chan));
2333         ast_agi_send(fd, chan, "agi_priority: %d\n", ast_channel_priority(chan));
2334         ast_agi_send(fd, chan, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
2335
2336         /* User information */
2337         ast_agi_send(fd, chan, "agi_accountcode: %s\n", ast_channel_accountcode(chan) ? ast_channel_accountcode(chan) : "");
2338         ast_agi_send(fd, chan, "agi_threadid: %ld\n", (long)pthread_self());
2339
2340         /* Send any parameters to the fastagi server that have been passed via the agi application */
2341         /* Agi application paramaters take the form of: AGI(/path/to/example/script|${EXTEN}) */
2342         for(count = 1; count < argc; count++)
2343                 ast_agi_send(fd, chan, "agi_arg_%d: %s\n", count, argv[count]);
2344
2345         /* End with empty return */
2346         ast_agi_send(fd, chan, "\n");
2347 }
2348
2349 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2350 {
2351         int res = 0;
2352
2353         /* Answer the channel */
2354         if (ast_channel_state(chan) != AST_STATE_UP)
2355                 res = ast_answer(chan);
2356
2357         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2358         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2359 }
2360
2361 static int handle_asyncagi_break(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2362 {
2363         ast_agi_send(agi->fd, chan, "200 result=0\n");
2364         return ASYNC_AGI_BREAK;
2365 }
2366
2367 static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2368 {
2369         int res, to;
2370
2371         if (argc != 4)
2372                 return RESULT_SHOWUSAGE;
2373         if (sscanf(argv[3], "%30d", &to) != 1)
2374                 return RESULT_SHOWUSAGE;
2375         res = ast_waitfordigit_full(chan, to, agi->audio, agi->ctrl);
2376         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2377         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2378 }
2379
2380 static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2381 {
2382         int res;
2383
2384         if (argc != 3)
2385                 return RESULT_SHOWUSAGE;
2386
2387         /* At the moment, the parser (perhaps broken) returns with
2388            the last argument PLUS the newline at the end of the input
2389            buffer. This probably needs to be fixed, but I wont do that
2390            because other stuff may break as a result. The right way
2391            would probably be to strip off the trailing newline before
2392            parsing, then here, add a newline at the end of the string
2393            before sending it to ast_sendtext --DUDE */
2394         res = ast_sendtext(chan, argv[2]);
2395         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2396         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2397 }
2398
2399 static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2400 {
2401         int res;
2402
2403         if (argc != 3)
2404                 return RESULT_SHOWUSAGE;
2405
2406         res = ast_recvchar(chan,atoi(argv[2]));
2407         if (res == 0) {
2408                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout)\n", res);
2409                 return RESULT_SUCCESS;
2410         }
2411         if (res > 0) {
2412                 ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2413                 return RESULT_SUCCESS;
2414         }
2415         ast_agi_send(agi->fd, chan, "200 result=%d (hangup)\n", res);
2416         return RESULT_FAILURE;
2417 }
2418
2419 static int handle_recvtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2420 {
2421         char *buf;
2422
2423         if (argc != 3)
2424                 return RESULT_SHOWUSAGE;
2425
2426         buf = ast_recvtext(chan, atoi(argv[2]));
2427         if (buf) {
2428                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", buf);
2429                 ast_free(buf);
2430         } else {
2431                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2432         }
2433         return RESULT_SUCCESS;
2434 }
2435
2436 static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2437 {
2438         int res, x;
2439
2440         if (argc != 3)
2441                 return RESULT_SHOWUSAGE;
2442
2443         if (!strncasecmp(argv[2],"on",2)) {
2444                 x = 1;
2445         } else  {
2446                 x = 0;
2447         }
2448         if (!strncasecmp(argv[2],"mate",4))  {
2449                 x = 2;
2450         }
2451         if (!strncasecmp(argv[2],"tdd",3)) {
2452                 x = 1;
2453         }
2454         res = ast_channel_setoption(chan, AST_OPTION_TDD, &x, sizeof(char), 0);
2455         if (res) {
2456                 /* Set channel option failed */
2457                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2458         } else {
2459                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2460         }
2461         return RESULT_SUCCESS;
2462 }
2463
2464 static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2465 {
2466         int res;
2467
2468         if (argc != 3) {
2469                 return RESULT_SHOWUSAGE;
2470         }
2471
2472         res = ast_send_image(chan, argv[2]);
2473         if (!ast_check_hangup(chan)) {
2474                 res = 0;
2475         }
2476         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2477         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2478 }
2479
2480 static int handle_controlstreamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2481 {
2482         int res = 0, skipms = 3000;
2483         const char *fwd = "#", *rev = "*", *suspend = NULL, *stop = NULL;       /* Default values */
2484         char stopkeybuf[2];
2485         long offsetms = 0;
2486         char offsetbuf[20];
2487
2488         if (argc < 5 || argc > 10) {
2489                 return RESULT_SHOWUSAGE;
2490         }
2491
2492         if (!ast_strlen_zero(argv[4])) {
2493                 stop = argv[4];
2494         }
2495
2496         if ((argc > 5) && (sscanf(argv[5], "%30d", &skipms) != 1)) {
2497                 return RESULT_SHOWUSAGE;
2498         }
2499
2500         if (argc > 6 && !ast_strlen_zero(argv[6])) {
2501                 fwd = argv[6];
2502         }
2503
2504         if (argc > 7 && !ast_strlen_zero(argv[7])) {
2505                 rev = argv[7];
2506         }
2507
2508         if (argc > 8 && !ast_strlen_zero(argv[8])) {
2509                 suspend = argv[8];
2510         }
2511
2512         if (argc > 9 && (sscanf(argv[9], "%30ld", &offsetms) != 1)) {
2513                 return RESULT_SHOWUSAGE;
2514         }
2515
2516         res = ast_control_streamfile(chan, argv[3], fwd, rev, stop, suspend, NULL, skipms, &offsetms);
2517
2518         /* If we stopped on one of our stop keys, return 0  */
2519         if (res > 0 && stop && strchr(stop, res)) {
2520                 pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "USERSTOPPED");
2521                 snprintf(stopkeybuf, sizeof(stopkeybuf), "%c", res);
2522                 pbx_builtin_setvar_helper(chan, "CPLAYBACKSTOPKEY", stopkeybuf);
2523         } else if (res > 0 && res == AST_CONTROL_STREAM_STOP) {
2524                 pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "REMOTESTOPPED");
2525                 res = 0;
2526         } else {
2527                 if (res < 0) {
2528                         pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "ERROR");
2529                 } else {
2530                         pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "SUCCESS");
2531                 }
2532         }
2533
2534         snprintf(offsetbuf, sizeof(offsetbuf), "%ld", offsetms);
2535         pbx_builtin_setvar_helper(chan, "CPLAYBACKOFFSET", offsetbuf);
2536
2537         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, offsetms);
2538
2539         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2540 }
2541
2542 static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2543 {
2544         int res;
2545         struct ast_filestream *fs, *vfs;
2546         long sample_offset = 0, max_length;
2547         const char *edigits = "";
2548
2549         if (argc < 4 || argc > 5) {
2550                 return RESULT_SHOWUSAGE;
2551         }
2552
2553         if (argv[3]) {
2554                 edigits = argv[3];
2555         }
2556
2557         if ((argc > 4) && (sscanf(argv[4], "%30ld", &sample_offset) != 1)) {
2558                 return RESULT_SHOWUSAGE;
2559         }
2560
2561         if (!(fs = ast_openstream(chan, argv[2], ast_channel_language(chan)))) {
2562                 ast_agi_send(agi->fd, chan, "200 result=-1 endpos=%ld\n", sample_offset);
2563                 return RESULT_FAILURE;
2564         }
2565
2566         if ((vfs = ast_openvstream(chan, argv[2], ast_channel_language(chan)))) {
2567                 ast_debug(1, "Ooh, found a video stream, too\n");
2568         }
2569         ast_verb(3, "<%s> Playing '%s.%s' (escape_digits=%s) (sample_offset %ld) (language '%s')\n",
2570                 ast_channel_name(chan), argv[2], ast_format_get_name(ast_channel_writeformat(chan)),
2571                 edigits, sample_offset, S_OR(ast_channel_language(chan), "default"));
2572
2573         ast_seekstream(fs, 0, SEEK_END);
2574         max_length = ast_tellstream(fs);
2575         ast_seekstream(fs, sample_offset, SEEK_SET);
2576         res = ast_applystream(chan, fs);
2577         if (vfs) {
2578                 ast_applystream(chan, vfs);
2579         }
2580         ast_playstream(fs);
2581         if (vfs) {
2582                 ast_playstream(vfs);
2583         }
2584
2585         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
2586         /* this is to check for if ast_waitstream closed the stream, we probably are at
2587          * the end of the stream, return that amount, else check for the amount */
2588         sample_offset = (ast_channel_stream(chan)) ? ast_tellstream(fs) : max_length;
2589         ast_stopstream(chan);
2590         if (res == 1) {
2591                 /* Stop this command, don't print a result line, as there is a new command */
2592                 return RESULT_SUCCESS;
2593         }
2594         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
2595         pbx_builtin_setvar_helper(chan, "PLAYBACKSTATUS", res ? "FAILED" : "SUCCESS");
2596
2597         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2598 }
2599
2600 /*! \brief get option - really similar to the handle_streamfile, but with a timeout */
2601 static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2602 {
2603         int res;
2604         struct ast_filestream *fs, *vfs;
2605         long sample_offset = 0, max_length;
2606         int timeout = 0;
2607         const char *edigits = "";
2608
2609         if ( argc < 4 || argc > 5 )
2610                 return RESULT_SHOWUSAGE;
2611
2612         if ( argv[3] )
2613                 edigits = argv[3];
2614
2615         if ( argc == 5 )
2616                 timeout = atoi(argv[4]);
2617         else if (ast_channel_pbx(chan)->dtimeoutms) {
2618                 /* by default dtimeout is set to 5sec */
2619                 timeout = ast_channel_pbx(chan)->dtimeoutms; /* in msec */
2620         }
2621
2622         if (!(fs = ast_openstream(chan, argv[2], ast_channel_language(chan)))) {
2623                 ast_agi_send(agi->fd, chan, "200 result=-1 endpos=%ld\n", sample_offset);
2624                 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
2625                 return RESULT_FAILURE;
2626         }
2627
2628         if ((vfs = ast_openvstream(chan, argv[2], ast_channel_language(chan))))
2629                 ast_debug(1, "Ooh, found a video stream, too\n");
2630
2631         ast_verb(3, "Playing '%s' (escape_digits=%s) (timeout %d)\n", argv[2], edigits, timeout);
2632
2633         ast_seekstream(fs, 0, SEEK_END);
2634         max_length = ast_tellstream(fs);
2635         ast_seekstream(fs, sample_offset, SEEK_SET);
2636         res = ast_applystream(chan, fs);
2637         if (vfs)
2638                 ast_applystream(chan, vfs);
2639         ast_playstream(fs);
2640         if (vfs)
2641                 ast_playstream(vfs);
2642
2643         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
2644         /* this is to check for if ast_waitstream closed the stream, we probably are at
2645          * the end of the stream, return that amount, else check for the amount */
2646         sample_offset = (ast_channel_stream(chan))?ast_tellstream(fs):max_length;
2647         ast_stopstream(chan);
2648         if (res == 1) {
2649                 /* Stop this command, don't print a result line, as there is a new command */
2650                 return RESULT_SUCCESS;
2651         }
2652
2653         /* If the user didnt press a key, wait for digitTimeout*/
2654         if (res == 0 ) {
2655                 res = ast_waitfordigit_full(chan, timeout, agi->audio, agi->ctrl);
2656                 /* Make sure the new result is in the escape digits of the GET OPTION */
2657                 if ( !strchr(edigits,res) )
2658                         res=0;
2659         }
2660
2661         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
2662         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2663 }
2664
2665
2666
2667
2668 /*! \brief Say number in various language syntaxes */
2669 /* While waiting, we're sending a NULL.  */
2670 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2671 {
2672         int res, num;
2673
2674         if (argc < 4 || argc > 5)
2675                 return RESULT_SHOWUSAGE;
2676         if (sscanf(argv[2], "%30d", &num) != 1)
2677                 return RESULT_SHOWUSAGE;
2678         res = ast_say_number_full(chan, num, argv[3], ast_channel_language(chan), argc > 4 ? argv[4] : NULL, agi->audio, agi->ctrl);
2679         if (res == 1)
2680                 return RESULT_SUCCESS;
2681         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2682         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2683 }
2684
2685 static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2686 {
2687         int res, num;
2688
2689         if (argc != 4)
2690                 return RESULT_SHOWUSAGE;
2691         if (sscanf(argv[2], "%30d", &num) != 1)
2692                 return RESULT_SHOWUSAGE;
2693
2694         res = ast_say_digit_str_full(chan, argv[2], argv[3], ast_channel_language(chan), agi->audio, agi->ctrl);
2695         if (res == 1) /* New command */
2696                 return RESULT_SUCCESS;
2697         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2698         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2699 }
2700
2701 static int handle_sayalpha(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2702 {
2703         int res;
2704         int sensitivity = AST_SAY_CASE_NONE;
2705
2706         if (argc < 4 || argc > 5) {
2707                 return RESULT_SHOWUSAGE;
2708         }
2709
2710         if (argc > 4) {
2711                 switch (argv[4][0]) {
2712                 case 'a':
2713                 case 'A':
2714                         sensitivity = AST_SAY_CASE_ALL;
2715                         break;
2716                 case 'l':
2717                 case 'L':
2718                         sensitivity = AST_SAY_CASE_LOWER;
2719                         break;
2720                 case 'n':
2721                 case 'N':
2722                         sensitivity = AST_SAY_CASE_NONE;
2723                         break;
2724                 case 'u':
2725                 case 'U':
2726                         sensitivity = AST_SAY_CASE_UPPER;
2727                         break;
2728                 case '\0':
2729                         break;
2730                 default:
2731                         return RESULT_SHOWUSAGE;
2732                 }
2733         }
2734         res = ast_say_character_str_full(chan, argv[2], argv[3], ast_channel_language(chan), sensitivity, agi->audio, agi->ctrl);
2735         if (res == 1) /* New command */
2736                 return RESULT_SUCCESS;
2737         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2738         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2739 }
2740
2741 static int handle_saydate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2742 {
2743         int res, num;
2744
2745         if (argc != 4)
2746                 return RESULT_SHOWUSAGE;
2747         if (sscanf(argv[2], "%30d", &num) != 1)
2748                 return RESULT_SHOWUSAGE;
2749         res = ast_say_date(chan, num, argv[3], ast_channel_language(chan));
2750         if (res == 1)
2751                 return RESULT_SUCCESS;
2752         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2753         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2754 }
2755
2756 static int handle_saytime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2757 {
2758         int res, num;
2759
2760         if (argc != 4)
2761                 return RESULT_SHOWUSAGE;
2762         if (sscanf(argv[2], "%30d", &num) != 1)
2763                 return RESULT_SHOWUSAGE;
2764         res = ast_say_time(chan, num, argv[3], ast_channel_language(chan));
2765         if (res == 1)
2766                 return RESULT_SUCCESS;
2767         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2768         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2769 }
2770
2771 static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2772 {
2773         int res = 0;
2774         time_t unixtime;
2775         const char *format, *zone = NULL;
2776
2777         if (argc < 4)
2778                 return RESULT_SHOWUSAGE;
2779
2780         if (argc > 4) {
2781                 format = argv[4];
2782         } else {
2783                 /* XXX this doesn't belong here, but in the 'say' module */
2784                 if (!strcasecmp(ast_channel_language(chan), "de")) {
2785                         format = "A dBY HMS";
2786                 } else {
2787                         format = "ABdY 'digits/at' IMp";
2788                 }
2789         }
2790
2791         if (argc > 5 && !ast_strlen_zero(argv[5]))
2792                 zone = argv[5];
2793
2794         if (ast_get_time_t(argv[2], &unixtime, 0, NULL))
2795                 return RESULT_SHOWUSAGE;
2796
2797         res = ast_say_date_with_format(chan, unixtime, argv[3], ast_channel_language(chan), format, zone);
2798         if (res == 1)
2799                 return RESULT_SUCCESS;
2800
2801         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2802         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2803 }
2804
2805 static int handle_sayphonetic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2806 {
2807         int res;
2808
2809         if (argc != 4)
2810                 return RESULT_SHOWUSAGE;
2811
2812         res = ast_say_phonetic_str_full(chan, argv[2], argv[3], ast_channel_language(chan), agi->audio, agi->ctrl);
2813         if (res == 1) /* New command */
2814                 return RESULT_SUCCESS;
2815         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2816         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2817 }
2818
2819 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2820 {
2821         int res, max, timeout;
2822         char data[1024];
2823
2824         if (argc < 3)
2825                 return RESULT_SHOWUSAGE;
2826         if (argc >= 4)
2827                 timeout = atoi(argv[3]);
2828         else
2829                 timeout = 0;
2830         if (argc >= 5)
2831                 max = atoi(argv[4]);
2832         else
2833                 max = 1024;
2834         res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
2835         if (res == 2)                   /* New command */
2836                 return RESULT_SUCCESS;
2837         else if (res == 1)
2838                 ast_agi_send(agi->fd, chan, "200 result=%s (timeout)\n", data);
2839         else if (res < 0 )
2840                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2841         else
2842                 ast_agi_send(agi->fd, chan, "200 result=%s\n", data);
2843         return RESULT_SUCCESS;
2844 }
2845
2846 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2847 {
2848
2849         if (argc != 3)
2850                 return RESULT_SHOWUSAGE;
2851         ast_channel_context_set(chan, argv[2]);
2852         ast_agi_send(agi->fd, chan, "200 result=0\n");
2853         return RESULT_SUCCESS;
2854 }
2855
2856 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2857 {
2858         if (argc != 3)
2859                 return RESULT_SHOWUSAGE;
2860         ast_channel_exten_set(chan, argv[2]);
2861         ast_agi_send(agi->fd, chan, "200 result=0\n");
2862         return RESULT_SUCCESS;
2863 }
2864
2865 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2866 {
2867         int pri;
2868
2869         if (argc != 3)
2870                 return RESULT_SHOWUSAGE;
2871
2872         if (sscanf(argv[2], "%30d", &pri) != 1) {
2873                 pri = ast_findlabel_extension(chan, ast_channel_context(chan), ast_channel_exten(chan), argv[2],
2874                         S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL));
2875                 if (pri < 1)
2876                         return RESULT_SHOWUSAGE;
2877         }
2878
2879         ast_explicit_goto(chan, NULL, NULL, pri);
2880         ast_agi_send(agi->fd, chan, "200 result=0\n");
2881         return RESULT_SUCCESS;
2882 }
2883
2884 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2885 {
2886         struct ast_filestream *fs;
2887         struct ast_frame *f;
2888         struct timeval start;
2889         long sample_offset = 0;
2890         int res = 0;
2891         int ms;
2892
2893         struct ast_dsp *sildet=NULL;         /* silence detector dsp */
2894         int totalsilence = 0;
2895         int dspsilence = 0;
2896         int silence = 0;                /* amount of silence to allow */
2897         int gotsilence = 0;             /* did we timeout for silence? */
2898         char *silencestr = NULL;
2899         RAII_VAR(struct ast_format *, rfmt, NULL, ao2_cleanup);
2900
2901         /* XXX EAGI FIXME XXX */
2902
2903         if (argc < 6)
2904                 return RESULT_SHOWUSAGE;
2905         if (sscanf(argv[5], "%30d", &ms) != 1)
2906                 return RESULT_SHOWUSAGE;
2907
2908         if (argc > 6)
2909                 silencestr = strchr(argv[6],'s');
2910         if ((argc > 7) && (!silencestr))
2911                 silencestr = strchr(argv[7],'s');
2912         if ((argc > 8) && (!silencestr))
2913                 silencestr = strchr(argv[8],'s');
2914
2915         if (silencestr) {
2916                 if (strlen(silencestr) > 2) {
2917                         if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
2918                                 silencestr++;
2919                                 silencestr++;
2920                                 if (silencestr)
2921                                         silence = atoi(silencestr);
2922                                 if (silence > 0)
2923                                         silence *= 1000;
2924                         }
2925                 }
2926         }
2927
2928         if (silence > 0) {
2929                 rfmt = ao2_bump(ast_channel_readformat(chan));
2930                 res = ast_set_read_format(chan, ast_format_slin);
2931                 if (res < 0) {
2932                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
2933                         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2934                         return RESULT_FAILURE;
2935                 }
2936                 sildet = ast_dsp_new();
2937                 if (!sildet) {
2938                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
2939                         ast_agi_send(agi->fd, chan, "200 result=-1\n");
2940                         return RESULT_FAILURE;
2941                 }
2942                 ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
2943         }
2944
2945         /* backward compatibility, if no offset given, arg[6] would have been
2946          * caught below and taken to be a beep, else if it is a digit then it is a
2947          * offset */
2948         if ((argc >6) && (sscanf(argv[6], "%30ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
2949                 res = ast_streamfile(chan, "beep", ast_channel_language(chan));
2950
2951         if ((argc > 7) && (!strchr(argv[7], '=')))
2952                 res = ast_streamfile(chan, "beep", ast_channel_language(chan));
2953
2954         if (!res)
2955                 res = ast_waitstream(chan, argv[4]);
2956         if (res) {
2957                 ast_agi_send(agi->fd, chan, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
2958         } else {
2959                 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, AST_FILE_MODE);
2960                 if (!fs) {
2961                         res = -1;
2962                         ast_agi_send(agi->fd, chan, "200 result=%d (writefile)\n", res);
2963                         if (sildet)
2964                                 ast_dsp_free(sildet);
2965                         return RESULT_FAILURE;
2966                 }
2967