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