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