393a503511a2139ad592848eccc322c5b6cc3e3f
[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;
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 (ast_fd_set_flags(s, O_NONBLOCK)) {
2080                         close(s);
2081                         continue;
2082                 }
2083
2084                 if (ast_connect(s, &addrs[i]) && errno == EINPROGRESS) {
2085
2086                         if (handle_connection(agiurl, addrs[i], s)) {
2087                                 close(s);
2088                                 continue;
2089                         }
2090
2091                 } else {
2092                         ast_log(LOG_WARNING, "Connection to %s failed with unexpected error: %s\n",
2093                         ast_sockaddr_stringify(&addrs[i]), strerror(errno));
2094                 }
2095
2096                 break;
2097         }
2098
2099         ast_free(addrs);
2100
2101         if (i == num_addrs) {
2102                 ast_log(LOG_WARNING, "Couldn't connect to any host.  FastAGI failed.\n");
2103                 return AGI_RESULT_FAILURE;
2104         }
2105
2106         if (ast_agi_send(s, NULL, "agi_network: yes\n") < 0) {
2107                 if (errno != EINTR) {
2108                         ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
2109                         close(s);
2110                         return AGI_RESULT_FAILURE;
2111                 }
2112         }
2113
2114         /* If we have a script parameter, relay it to the fastagi server */
2115         /* Script parameters take the form of: AGI(agi://my.example.com/?extension=${EXTEN}) */
2116         if (!ast_strlen_zero(script)) {
2117                 ast_agi_send(s, NULL, "agi_network_script: %s\n", script);
2118         }
2119
2120         ast_debug(4, "Wow, connected!\n");
2121         fds[0] = s;
2122         fds[1] = s;
2123         return AGI_RESULT_SUCCESS_FAST;
2124 }
2125
2126 /*!
2127  * \internal
2128  * \brief The HA fastagi handler.
2129  * \param agiurl The request URL as passed to Agi() in the dial plan
2130  * \param argv The parameters after the URL passed to Agi() in the dial plan
2131  * \param fds Input/output file descriptors
2132  *
2133  * Uses SRV lookups to try to connect to a list of FastAGI servers. The hostname in
2134  * the URI is prefixed with _agi._tcp. prior to the DNS resolution. For
2135  * example, if you specify the URI \a hagi://agi.example.com/foo.agi the DNS
2136  * query would be for \a _agi._tcp.agi.example.com and you'll need to make sure
2137  * this resolves.
2138  *
2139  * This function parses the URI, resolves the SRV service name, forms new URIs
2140  * with the results of the DNS lookup, and then calls launch_netscript on the
2141  * new URIs until one succeeds.
2142  *
2143  * \return the result of the AGI operation.
2144  */
2145 static enum agi_result launch_ha_netscript(char *agiurl, char *argv[], int *fds)
2146 {
2147         char *host, *script;
2148         enum agi_result result;
2149         struct srv_context *context = NULL;
2150         int srv_ret;
2151         char service[256];
2152         char resolved_uri[1024];
2153         const char *srvhost;
2154         unsigned short srvport;
2155
2156         /* format of agiurl is "hagi://host.domain[:port][/script/name]" */
2157         if (strlen(agiurl) < 7) { /* Remove hagi:// */
2158                 ast_log(LOG_WARNING, "An error occurred parsing the AGI URI: %s", agiurl);
2159                 return AGI_RESULT_FAILURE;
2160         }
2161         host = ast_strdupa(agiurl + 7);
2162
2163         /* Strip off any script name */
2164         if ((script = strchr(host, '/'))) {
2165                 *script++ = '\0';
2166         } else {
2167                 script = "";
2168         }
2169
2170         if (strchr(host, ':')) {
2171                 ast_log(LOG_WARNING, "Specifying a port number disables SRV lookups: %s\n", agiurl);
2172                 return launch_netscript(agiurl + 1, argv, fds); /* +1 to strip off leading h from hagi:// */
2173         }
2174
2175         snprintf(service, sizeof(service), "%s%s", SRV_PREFIX, host);
2176
2177         while (!(srv_ret = ast_srv_lookup(&context, service, &srvhost, &srvport))) {
2178                 snprintf(resolved_uri, sizeof(resolved_uri), "agi://%s:%d/%s", srvhost, srvport, script);
2179                 result = launch_netscript(resolved_uri, argv, fds);
2180                 if (result == AGI_RESULT_FAILURE || result == AGI_RESULT_NOTFOUND) {
2181                         ast_log(LOG_WARNING, "AGI request failed for host '%s' (%s:%d)\n", host, srvhost, srvport);
2182                 } else {
2183                         /* The script launched so we must cleanup the context. */
2184                         ast_srv_cleanup(&context);
2185                         return result;
2186                 }
2187         }
2188         /*
2189          * The DNS SRV lookup failed or we ran out of servers to check.
2190          * ast_srv_lookup() has already cleaned up the context for us.
2191          */
2192         if (srv_ret < 0) {
2193                 ast_log(LOG_WARNING, "SRV lookup failed for %s\n", agiurl);
2194         }
2195
2196         return AGI_RESULT_FAILURE;
2197 }
2198
2199 static enum agi_result launch_script(struct ast_channel *chan, char *script, int argc, char *argv[], int *fds, int *efd, int *opid)
2200 {
2201         char tmp[256];
2202         int pid, toast[2], fromast[2], audio[2], res;
2203         struct stat st;
2204
2205         if (!strncasecmp(script, "agi://", 6)) {
2206                 return (efd == NULL) ? launch_netscript(script, argv, fds) : AGI_RESULT_FAILURE;
2207         }
2208         if (!strncasecmp(script, "hagi://", 7)) {
2209                 return (efd == NULL) ? launch_ha_netscript(script, argv, fds) : AGI_RESULT_FAILURE;
2210         }
2211         if (!strncasecmp(script, "agi:async", sizeof("agi:async") - 1)) {
2212                 return launch_asyncagi(chan, argc, argv, efd);
2213         }
2214
2215         if (script[0] != '/') {
2216                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_AGI_DIR, script);
2217                 script = tmp;
2218         }
2219
2220         /* Before even trying let's see if the file actually exists */
2221         if (stat(script, &st)) {
2222                 ast_log(LOG_WARNING, "Failed to execute '%s': File does not exist.\n", script);
2223                 return AGI_RESULT_NOTFOUND;
2224         }
2225
2226         if (pipe(toast)) {
2227                 ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
2228                 return AGI_RESULT_FAILURE;
2229         }
2230         if (pipe(fromast)) {
2231                 ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
2232                 close(toast[0]);
2233                 close(toast[1]);
2234                 return AGI_RESULT_FAILURE;
2235         }
2236         if (efd) {
2237                 if (pipe(audio)) {
2238                         ast_log(LOG_WARNING, "unable to create audio pipe: %s\n", strerror(errno));
2239                         close(fromast[0]);
2240                         close(fromast[1]);
2241                         close(toast[0]);
2242                         close(toast[1]);
2243                         return AGI_RESULT_FAILURE;
2244                 }
2245
2246                 res = ast_fd_set_flags(audio[1], O_NONBLOCK);
2247                 if (res < 0) {
2248                         ast_log(LOG_WARNING, "unable to set audio pipe parameters: %s\n", strerror(errno));
2249                         close(fromast[0]);
2250                         close(fromast[1]);
2251                         close(toast[0]);
2252                         close(toast[1]);
2253                         close(audio[0]);
2254                         close(audio[1]);
2255                         return AGI_RESULT_FAILURE;
2256                 }
2257         }
2258
2259         if ((pid = ast_safe_fork(1)) < 0) {
2260                 ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
2261                 return AGI_RESULT_FAILURE;
2262         }
2263         if (!pid) {
2264                 /* Pass paths to AGI via environmental variables */
2265                 setenv("AST_CONFIG_DIR", ast_config_AST_CONFIG_DIR, 1);
2266                 setenv("AST_CONFIG_FILE", ast_config_AST_CONFIG_FILE, 1);
2267                 setenv("AST_MODULE_DIR", ast_config_AST_MODULE_DIR, 1);
2268                 setenv("AST_SPOOL_DIR", ast_config_AST_SPOOL_DIR, 1);
2269                 setenv("AST_MONITOR_DIR", ast_config_AST_MONITOR_DIR, 1);
2270                 setenv("AST_VAR_DIR", ast_config_AST_VAR_DIR, 1);
2271                 setenv("AST_DATA_DIR", ast_config_AST_DATA_DIR, 1);
2272                 setenv("AST_LOG_DIR", ast_config_AST_LOG_DIR, 1);
2273                 setenv("AST_AGI_DIR", ast_config_AST_AGI_DIR, 1);
2274                 setenv("AST_KEY_DIR", ast_config_AST_KEY_DIR, 1);
2275                 setenv("AST_RUN_DIR", ast_config_AST_RUN_DIR, 1);
2276
2277                 /* Don't run AGI scripts with realtime priority -- it causes audio stutter */
2278                 ast_set_priority(0);
2279
2280                 /* Redirect stdin and out, provide enhanced audio channel if desired */
2281                 dup2(fromast[0], STDIN_FILENO);
2282                 dup2(toast[1], STDOUT_FILENO);
2283                 if (efd)
2284                         dup2(audio[0], STDERR_FILENO + 1);
2285                 else
2286                         close(STDERR_FILENO + 1);
2287
2288                 /* Close everything but stdin/out/error */
2289                 ast_close_fds_above_n(STDERR_FILENO + 1);
2290
2291                 /* Execute script */
2292                 /* XXX argv should be deprecated in favor of passing agi_argX paramaters */
2293                 execv(script, argv);
2294                 /* Can't use ast_log since FD's are closed */
2295                 ast_child_verbose(1, "Failed to execute '%s': %s", script, strerror(errno));
2296                 /* Special case to set status of AGI to failure */
2297                 fprintf(stdout, "failure\n");
2298                 fflush(stdout);
2299                 _exit(1);
2300         }
2301         ast_verb(3, "Launched AGI Script %s\n", script);
2302         fds[0] = toast[0];
2303         fds[1] = fromast[1];
2304         if (efd)
2305                 *efd = audio[1];
2306         /* close what we're not using in the parent */
2307         close(toast[1]);
2308         close(fromast[0]);
2309
2310         if (efd)
2311                 close(audio[0]);
2312
2313         *opid = pid;
2314         return AGI_RESULT_SUCCESS;
2315 }
2316
2317 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced, int argc, char *argv[])
2318 {
2319         int count;
2320
2321         /* Print initial environment, with agi_request always being the first
2322            thing */
2323         ast_agi_send(fd, chan, "agi_request: %s\n", request);
2324         ast_agi_send(fd, chan, "agi_channel: %s\n", ast_channel_name(chan));
2325         ast_agi_send(fd, chan, "agi_language: %s\n", ast_channel_language(chan));
2326         ast_agi_send(fd, chan, "agi_type: %s\n", ast_channel_tech(chan)->type);
2327         ast_agi_send(fd, chan, "agi_uniqueid: %s\n", ast_channel_uniqueid(chan));
2328         ast_agi_send(fd, chan, "agi_version: %s\n", ast_get_version());
2329
2330         /* ANI/DNIS */
2331         ast_agi_send(fd, chan, "agi_callerid: %s\n",
2332                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "unknown"));
2333         ast_agi_send(fd, chan, "agi_calleridname: %s\n",
2334                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "unknown"));
2335         ast_agi_send(fd, chan, "agi_callingpres: %d\n",
2336                 ast_party_id_presentation(&ast_channel_caller(chan)->id));
2337         ast_agi_send(fd, chan, "agi_callingani2: %d\n", ast_channel_caller(chan)->ani2);
2338         ast_agi_send(fd, chan, "agi_callington: %d\n", ast_channel_caller(chan)->id.number.plan);
2339         ast_agi_send(fd, chan, "agi_callingtns: %d\n", ast_channel_dialed(chan)->transit_network_select);
2340         ast_agi_send(fd, chan, "agi_dnid: %s\n", S_OR(ast_channel_dialed(chan)->number.str, "unknown"));
2341         ast_agi_send(fd, chan, "agi_rdnis: %s\n",
2342                 S_COR(ast_channel_redirecting(chan)->from.number.valid, ast_channel_redirecting(chan)->from.number.str, "unknown"));
2343
2344         /* Context information */
2345         ast_agi_send(fd, chan, "agi_context: %s\n", ast_channel_context(chan));
2346         ast_agi_send(fd, chan, "agi_extension: %s\n", ast_channel_exten(chan));
2347         ast_agi_send(fd, chan, "agi_priority: %d\n", ast_channel_priority(chan));
2348         ast_agi_send(fd, chan, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
2349
2350         /* User information */
2351         ast_agi_send(fd, chan, "agi_accountcode: %s\n", ast_channel_accountcode(chan) ? ast_channel_accountcode(chan) : "");
2352         ast_agi_send(fd, chan, "agi_threadid: %ld\n", (long)pthread_self());
2353
2354         /* Send any parameters to the fastagi server that have been passed via the agi application */
2355         /* Agi application paramaters take the form of: AGI(/path/to/example/script|${EXTEN}) */
2356         for(count = 1; count < argc; count++)
2357                 ast_agi_send(fd, chan, "agi_arg_%d: %s\n", count, argv[count]);
2358
2359         /* End with empty return */
2360         ast_agi_send(fd, chan, "\n");
2361 }
2362
2363 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2364 {
2365         int res = 0;
2366
2367         /* Answer the channel */
2368         if (ast_channel_state(chan) != AST_STATE_UP)
2369                 res = ast_answer(chan);
2370
2371         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2372         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2373 }
2374
2375 static int handle_asyncagi_break(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2376 {
2377         ast_agi_send(agi->fd, chan, "200 result=0\n");
2378         return ASYNC_AGI_BREAK;
2379 }
2380
2381 static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2382 {
2383         int res, to;
2384
2385         if (argc != 4)
2386                 return RESULT_SHOWUSAGE;
2387         if (sscanf(argv[3], "%30d", &to) != 1)
2388                 return RESULT_SHOWUSAGE;
2389         res = ast_waitfordigit_full(chan, to, NULL, agi->audio, agi->ctrl);
2390         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2391         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2392 }
2393
2394 static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2395 {
2396         int res;
2397
2398         if (argc != 3)
2399                 return RESULT_SHOWUSAGE;
2400
2401         /* At the moment, the parser (perhaps broken) returns with
2402            the last argument PLUS the newline at the end of the input
2403            buffer. This probably needs to be fixed, but I wont do that
2404            because other stuff may break as a result. The right way
2405            would probably be to strip off the trailing newline before
2406            parsing, then here, add a newline at the end of the string
2407            before sending it to ast_sendtext --DUDE */
2408         res = ast_sendtext(chan, argv[2]);
2409         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2410         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2411 }
2412
2413 static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2414 {
2415         int res;
2416
2417         if (argc != 3)
2418                 return RESULT_SHOWUSAGE;
2419
2420         res = ast_recvchar(chan,atoi(argv[2]));
2421         if (res == 0) {
2422                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout)\n", res);
2423                 return RESULT_SUCCESS;
2424         }
2425         if (res > 0) {
2426                 ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2427                 return RESULT_SUCCESS;
2428         }
2429         ast_agi_send(agi->fd, chan, "200 result=%d (hangup)\n", res);
2430         return RESULT_FAILURE;
2431 }
2432
2433 static int handle_recvtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2434 {
2435         char *buf;
2436
2437         if (argc != 3)
2438                 return RESULT_SHOWUSAGE;
2439
2440         buf = ast_recvtext(chan, atoi(argv[2]));
2441         if (buf) {
2442                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", buf);
2443                 ast_free(buf);
2444         } else {
2445                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2446         }
2447         return RESULT_SUCCESS;
2448 }
2449
2450 static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2451 {
2452         int res, x;
2453
2454         if (argc != 3)
2455                 return RESULT_SHOWUSAGE;
2456
2457         if (!strncasecmp(argv[2],"on",2)) {
2458                 x = 1;
2459         } else  {
2460                 x = 0;
2461         }
2462         if (!strncasecmp(argv[2],"mate",4))  {
2463                 x = 2;
2464         }
2465         if (!strncasecmp(argv[2],"tdd",3)) {
2466                 x = 1;
2467         }
2468         res = ast_channel_setoption(chan, AST_OPTION_TDD, &x, sizeof(char), 0);
2469         if (res) {
2470                 /* Set channel option failed */
2471                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2472         } else {
2473                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2474         }
2475         return RESULT_SUCCESS;
2476 }
2477
2478 static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2479 {
2480         int res;
2481
2482         if (argc != 3) {
2483                 return RESULT_SHOWUSAGE;
2484         }
2485
2486         res = ast_send_image(chan, argv[2]);
2487         if (!ast_check_hangup(chan)) {
2488                 res = 0;
2489         }
2490         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2491         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2492 }
2493
2494 static int handle_controlstreamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2495 {
2496         int res = 0, skipms = 3000;
2497         const char *fwd = "#", *rev = "*", *suspend = NULL, *stop = NULL;       /* Default values */
2498         char stopkeybuf[2];
2499         long offsetms = 0;
2500         char offsetbuf[20];
2501
2502         if (argc < 5 || argc > 10) {
2503                 return RESULT_SHOWUSAGE;
2504         }
2505
2506         if (!ast_strlen_zero(argv[4])) {
2507                 stop = argv[4];
2508         }
2509
2510         if ((argc > 5) && (sscanf(argv[5], "%30d", &skipms) != 1)) {
2511                 return RESULT_SHOWUSAGE;
2512         }
2513
2514         if (argc > 6 && !ast_strlen_zero(argv[6])) {
2515                 fwd = argv[6];
2516         }
2517
2518         if (argc > 7 && !ast_strlen_zero(argv[7])) {
2519                 rev = argv[7];
2520         }
2521
2522         if (argc > 8 && !ast_strlen_zero(argv[8])) {
2523                 suspend = argv[8];
2524         }
2525
2526         if (argc > 9 && (sscanf(argv[9], "%30ld", &offsetms) != 1)) {
2527                 return RESULT_SHOWUSAGE;
2528         }
2529
2530         res = ast_control_streamfile(chan, argv[3], fwd, rev, stop, suspend, NULL, skipms, &offsetms);
2531
2532         /* If we stopped on one of our stop keys, return 0  */
2533         if (res > 0 && stop && strchr(stop, res)) {
2534                 pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "USERSTOPPED");
2535                 snprintf(stopkeybuf, sizeof(stopkeybuf), "%c", res);
2536                 pbx_builtin_setvar_helper(chan, "CPLAYBACKSTOPKEY", stopkeybuf);
2537         } else if (res > 0 && res == AST_CONTROL_STREAM_STOP) {
2538                 pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "REMOTESTOPPED");
2539                 res = 0;
2540         } else {
2541                 if (res < 0) {
2542                         pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "ERROR");
2543                 } else {
2544                         pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "SUCCESS");
2545                 }
2546         }
2547
2548         snprintf(offsetbuf, sizeof(offsetbuf), "%ld", offsetms);
2549         pbx_builtin_setvar_helper(chan, "CPLAYBACKOFFSET", offsetbuf);
2550
2551         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, offsetms);
2552
2553         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2554 }
2555
2556 static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2557 {
2558         int res;
2559         struct ast_filestream *fs, *vfs;
2560         long sample_offset = 0, max_length;
2561         const char *edigits = "";
2562
2563         if (argc < 4 || argc > 5) {
2564                 return RESULT_SHOWUSAGE;
2565         }
2566
2567         if (argv[3]) {
2568                 edigits = argv[3];
2569         }
2570
2571         if ((argc > 4) && (sscanf(argv[4], "%30ld", &sample_offset) != 1)) {
2572                 return RESULT_SHOWUSAGE;
2573         }
2574
2575         if (!(fs = ast_openstream(chan, argv[2], ast_channel_language(chan)))) {
2576                 ast_agi_send(agi->fd, chan, "200 result=-1 endpos=%ld\n", sample_offset);
2577                 return RESULT_FAILURE;
2578         }
2579
2580         if ((vfs = ast_openvstream(chan, argv[2], ast_channel_language(chan)))) {
2581                 ast_debug(1, "Ooh, found a video stream, too\n");
2582         }
2583         ast_verb(3, "<%s> Playing '%s.%s' (escape_digits=%s) (sample_offset %ld) (language '%s')\n",
2584                 ast_channel_name(chan), argv[2], ast_format_get_name(ast_channel_writeformat(chan)),
2585                 edigits, sample_offset, S_OR(ast_channel_language(chan), "default"));
2586
2587         ast_seekstream(fs, 0, SEEK_END);
2588         max_length = ast_tellstream(fs);
2589         ast_seekstream(fs, sample_offset, SEEK_SET);
2590         res = ast_applystream(chan, fs);
2591         if (vfs) {
2592                 ast_applystream(chan, vfs);
2593         }
2594         ast_playstream(fs);
2595         if (vfs) {
2596                 ast_playstream(vfs);
2597         }
2598
2599         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
2600         /* this is to check for if ast_waitstream closed the stream, we probably are at
2601          * the end of the stream, return that amount, else check for the amount */
2602         sample_offset = (ast_channel_stream(chan)) ? ast_tellstream(fs) : max_length;
2603         ast_stopstream(chan);
2604         if (res == 1) {
2605                 /* Stop this command, don't print a result line, as there is a new command */
2606                 return RESULT_SUCCESS;
2607         }
2608         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
2609         pbx_builtin_setvar_helper(chan, "PLAYBACKSTATUS", res ? "FAILED" : "SUCCESS");
2610
2611         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2612 }
2613
2614 /*! \brief get option - really similar to the handle_streamfile, but with a timeout */
2615 static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2616 {
2617         int res;
2618         struct ast_filestream *fs, *vfs;
2619         long sample_offset = 0, max_length;
2620         int timeout = 0;
2621         const char *edigits = "";
2622
2623         if ( argc < 4 || argc > 5 )
2624                 return RESULT_SHOWUSAGE;
2625
2626         if ( argv[3] )
2627                 edigits = argv[3];
2628
2629         if ( argc == 5 )
2630                 timeout = atoi(argv[4]);
2631         else if (ast_channel_pbx(chan)->dtimeoutms) {
2632                 /* by default dtimeout is set to 5sec */
2633                 timeout = ast_channel_pbx(chan)->dtimeoutms; /* in msec */
2634         }
2635
2636         if (!(fs = ast_openstream(chan, argv[2], ast_channel_language(chan)))) {
2637                 ast_agi_send(agi->fd, chan, "200 result=-1 endpos=%ld\n", sample_offset);
2638                 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
2639                 return RESULT_FAILURE;
2640         }
2641
2642         if ((vfs = ast_openvstream(chan, argv[2], ast_channel_language(chan))))
2643                 ast_debug(1, "Ooh, found a video stream, too\n");
2644
2645         ast_verb(3, "Playing '%s' (escape_digits=%s) (timeout %d)\n", argv[2], edigits, timeout);
2646
2647         ast_seekstream(fs, 0, SEEK_END);
2648         max_length = ast_tellstream(fs);
2649         ast_seekstream(fs, sample_offset, SEEK_SET);
2650         res = ast_applystream(chan, fs);
2651         if (vfs)
2652                 ast_applystream(chan, vfs);
2653         ast_playstream(fs);
2654         if (vfs)
2655                 ast_playstream(vfs);
2656
2657         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
2658         /* this is to check for if ast_waitstream closed the stream, we probably are at
2659          * the end of the stream, return that amount, else check for the amount */
2660         sample_offset = (ast_channel_stream(chan))?ast_tellstream(fs):max_length;
2661         ast_stopstream(chan);
2662         if (res == 1) {
2663                 /* Stop this command, don't print a result line, as there is a new command */
2664                 return RESULT_SUCCESS;
2665         }
2666
2667         /* If the user didnt press a key, wait for digitTimeout*/
2668         if (res == 0 ) {
2669                 res = ast_waitfordigit_full(chan, timeout, NULL, agi->audio, agi->ctrl);
2670                 /* Make sure the new result is in the escape digits of the GET OPTION */
2671                 if ( !strchr(edigits,res) )
2672                         res=0;
2673         }
2674
2675         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
2676         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2677 }
2678
2679
2680
2681
2682 /*! \brief Say number in various language syntaxes */
2683 /* While waiting, we're sending a NULL.  */
2684 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2685 {
2686         int res, num;
2687
2688         if (argc < 4 || argc > 5)
2689                 return RESULT_SHOWUSAGE;
2690         if (sscanf(argv[2], "%30d", &num) != 1)
2691                 return RESULT_SHOWUSAGE;
2692         res = ast_say_number_full(chan, num, argv[3], ast_channel_language(chan), argc > 4 ? argv[4] : NULL, agi->audio, agi->ctrl);
2693         if (res == 1)
2694                 return RESULT_SUCCESS;
2695         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2696         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2697 }
2698
2699 static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2700 {
2701         int res, num;
2702
2703         if (argc != 4)
2704                 return RESULT_SHOWUSAGE;
2705         if (sscanf(argv[2], "%30d", &num) != 1)
2706                 return RESULT_SHOWUSAGE;
2707
2708         res = ast_say_digit_str_full(chan, argv[2], argv[3], ast_channel_language(chan), agi->audio, agi->ctrl);
2709         if (res == 1) /* New command */
2710                 return RESULT_SUCCESS;
2711         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2712         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2713 }
2714
2715 static int handle_sayalpha(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2716 {
2717         int res;
2718         int sensitivity = AST_SAY_CASE_NONE;
2719
2720         if (argc < 4 || argc > 5) {
2721                 return RESULT_SHOWUSAGE;
2722         }
2723
2724         if (argc > 4) {
2725                 switch (argv[4][0]) {
2726                 case 'a':
2727                 case 'A':
2728                         sensitivity = AST_SAY_CASE_ALL;
2729                         break;
2730                 case 'l':
2731                 case 'L':
2732                         sensitivity = AST_SAY_CASE_LOWER;
2733                         break;
2734                 case 'n':
2735                 case 'N':
2736                         sensitivity = AST_SAY_CASE_NONE;
2737                         break;
2738                 case 'u':
2739                 case 'U':
2740                         sensitivity = AST_SAY_CASE_UPPER;
2741                         break;
2742                 case '\0':
2743                         break;
2744                 default:
2745                         return RESULT_SHOWUSAGE;
2746                 }
2747         }
2748         res = ast_say_character_str_full(chan, argv[2], argv[3], ast_channel_language(chan), sensitivity, agi->audio, agi->ctrl);
2749         if (res == 1) /* New command */
2750                 return RESULT_SUCCESS;
2751         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2752         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2753 }
2754
2755 static int handle_saydate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2756 {
2757         int res, num;
2758
2759         if (argc != 4)
2760                 return RESULT_SHOWUSAGE;
2761         if (sscanf(argv[2], "%30d", &num) != 1)
2762                 return RESULT_SHOWUSAGE;
2763         res = ast_say_date(chan, num, argv[3], ast_channel_language(chan));
2764         if (res == 1)
2765                 return RESULT_SUCCESS;
2766         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2767         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2768 }
2769
2770 static int handle_saytime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2771 {
2772         int res, num;
2773
2774         if (argc != 4)
2775                 return RESULT_SHOWUSAGE;
2776         if (sscanf(argv[2], "%30d", &num) != 1)
2777                 return RESULT_SHOWUSAGE;
2778         res = ast_say_time(chan, num, argv[3], ast_channel_language(chan));
2779         if (res == 1)
2780                 return RESULT_SUCCESS;
2781         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2782         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2783 }
2784
2785 static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2786 {
2787         int res = 0;
2788         time_t unixtime;
2789         const char *format, *zone = NULL;
2790
2791         if (argc < 4)
2792                 return RESULT_SHOWUSAGE;
2793
2794         if (argc > 4) {
2795                 format = argv[4];
2796         } else {
2797                 /* XXX this doesn't belong here, but in the 'say' module */
2798                 if (!strcasecmp(ast_channel_language(chan), "de")) {
2799                         format = "A dBY HMS";
2800                 } else {
2801                         format = "ABdY 'digits/at' IMp";
2802                 }
2803         }
2804
2805         if (argc > 5 && !ast_strlen_zero(argv[5]))
2806                 zone = argv[5];
2807
2808         if (ast_get_time_t(argv[2], &unixtime, 0, NULL))
2809                 return RESULT_SHOWUSAGE;
2810
2811         res = ast_say_date_with_format(chan, unixtime, argv[3], ast_channel_language(chan), format, zone);
2812         if (res == 1)
2813                 return RESULT_SUCCESS;
2814
2815         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2816         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2817 }
2818
2819 static int handle_sayphonetic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2820 {
2821         int res;
2822
2823         if (argc != 4)
2824                 return RESULT_SHOWUSAGE;
2825
2826         res = ast_say_phonetic_str_full(chan, argv[2], argv[3], ast_channel_language(chan), agi->audio, agi->ctrl);
2827         if (res == 1) /* New command */
2828                 return RESULT_SUCCESS;
2829         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2830         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2831 }
2832
2833 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2834 {
2835         int res, max, timeout;
2836         char data[1024];
2837
2838         if (argc < 3)
2839                 return RESULT_SHOWUSAGE;
2840         if (argc >= 4)
2841                 timeout = atoi(argv[3]);
2842         else
2843                 timeout = 0;
2844         if (argc >= 5)
2845                 max = atoi(argv[4]);
2846         else
2847                 max = 1024;
2848         res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
2849         if (res == 2)                   /* New command */
2850                 return RESULT_SUCCESS;
2851         else if (res == 1)
2852                 ast_agi_send(agi->fd, chan, "200 result=%s (timeout)\n", data);
2853         else if (res < 0 )
2854                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2855         else
2856                 ast_agi_send(agi->fd, chan, "200 result=%s\n", data);
2857         return RESULT_SUCCESS;
2858 }
2859
2860 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2861 {
2862
2863         if (argc != 3)
2864                 return RESULT_SHOWUSAGE;
2865         ast_channel_context_set(chan, argv[2]);
2866         ast_agi_send(agi->fd, chan, "200 result=0\n");
2867         return RESULT_SUCCESS;
2868 }
2869
2870 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2871 {
2872         if (argc != 3)
2873                 return RESULT_SHOWUSAGE;
2874         ast_channel_exten_set(chan, argv[2]);
2875         ast_agi_send(agi->fd, chan, "200 result=0\n");
2876         return RESULT_SUCCESS;
2877 }
2878
2879 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2880 {
2881         int pri;
2882
2883         if (argc != 3)
2884                 return RESULT_SHOWUSAGE;
2885
2886         if (sscanf(argv[2], "%30d", &pri) != 1) {
2887                 pri = ast_findlabel_extension(chan, ast_channel_context(chan), ast_channel_exten(chan), argv[2],
2888                         S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL));
2889                 if (pri < 1)
2890                         return RESULT_SHOWUSAGE;
2891         }
2892
2893         ast_explicit_goto(chan, NULL, NULL, pri);
2894         ast_agi_send(agi->fd, chan, "200 result=0\n");
2895         return RESULT_SUCCESS;
2896 }
2897
2898 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2899 {
2900         struct ast_filestream *fs;
2901         struct ast_frame *f;
2902         struct timeval start;
2903         long sample_offset = 0;
2904         int res = 0;
2905         int ms;
2906
2907         struct ast_dsp *sildet=NULL;         /* silence detector dsp */
2908         int totalsilence = 0;
2909         int dspsilence = 0;
2910         int silence = 0;                /* amount of silence to allow */
2911         int gotsilence = 0;             /* did we timeout for silence? */
2912         char *silencestr = NULL;
2913         RAII_VAR(struct ast_format *, rfmt, NULL, ao2_cleanup);
2914
2915         /* XXX EAGI FIXME XXX */
2916
2917         if (argc < 6)
2918                 return RESULT_SHOWUSAGE;
2919         if (sscanf(argv[5], "%30d", &ms) != 1)
2920                 return RESULT_SHOWUSAGE;
2921
2922         if (argc > 6)
2923                 silencestr = strchr(argv[6],'s');
2924         if ((argc > 7) && (!silencestr))
2925                 silencestr = strchr(argv[7],'s');
2926         if ((argc > 8) && (!silencestr))
2927                 silencestr = strchr(argv[8],'s');
2928
2929         if (silencestr) {
2930                 if (strlen(silencestr) > 2) {
2931                         if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
2932                                 silencestr++;
2933                                 silencestr++;
2934                                 if (silencestr)
2935                                         silence = atoi(silencestr);
2936                                 if (silence > 0)
2937                                         silence *= 1000;
2938                         }
2939                 }
2940         }
2941
2942         if (silence > 0) {
2943                 rfmt = ao2_bump(ast_channel_readformat(chan));
2944                 res = ast_set_read_format(chan, ast_format_slin);
2945                 if (res < 0) {
2946                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
2947                         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2948                         return RESULT_FAILURE;
2949                 }
2950                 sildet = ast_dsp_new();
2951                 if (!sildet) {
2952                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
2953                         ast_agi_send(agi->fd, chan, "200 result=-1\n");
2954                         return RESULT_FAILURE;
2955                 }
2956                 ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
2957         }
2958
2959         /* backward compatibility, if no offset given, arg[6] would have been
2960          * caught below and taken to be a beep, else if it is a digit then it is a
2961          * offset */
2962         if ((argc >6) && (sscanf(argv[6], "%30ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
2963                 res = ast_streamfile(chan, "beep", ast_channel_language(chan));
2964
2965         if ((argc > 7) && (!strchr(argv[7], '=')))
2966                 res = ast_streamfile(chan, "beep", ast_channel_language(chan));
2967
2968         if (!res)
2969                 res = ast_waitstream(chan, argv[4]);
2970         if (res) {
2971                 ast_agi_send(agi->fd, chan, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
2972         } else {
2973                 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, AST_FILE_MODE);
2974                 if (!fs) {
2975                         res = -1;
2976                         ast_agi_send(agi->fd, chan, "200 result=%d (writefile)\n", res);
2977                         if (sildet)
2978                                 ast_dsp_free(sildet);
2979                         return RESULT_FAILURE;
2980                 }
2981
2982                 /* Request a video update */
2983                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
2984
2985                 ast_channel_stream_set(chan, fs);
2986                 ast_applystream(chan,fs);
2987                 /* really should have checks */
2988                 ast_seekstream(fs, sample_offset, SEEK_SET);
2989                 ast_truncstream(fs);
2990
2991                 start = ast_tvnow();
2992                 while ((ms < 0) || ast_tvdiff_ms(ast_tvnow(), start) < ms) {
2993                         res = ast_waitfor(chan, ms - ast_tvdiff_ms(ast_tvnow(), start));
2994                         if (res < 0) {
2995                                 ast_closestream(fs);
2996                                 ast_agi_send(agi->fd, chan, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
2997                                 if (sildet)
2998                                         ast_dsp_free(sildet);
2999                                 return RESULT_FAILURE;
3000                         }
3001                         f = ast_read(chan);
3002                         if (!f) {
3003                                 ast_closestream(fs);
3004                                 ast_agi_send(agi->fd, chan, "200 result=%d (hangup) endpos=%ld\n", -1, sample_offset);
3005                                 if (sildet)
3006                                         ast_dsp_free(sildet);
3007                                 return RESULT_FAILURE;
3008                         }
3009                         switch(f->frametype) {
3010                         case AST_FRAME_DTMF:
3011                                 if (strchr(argv[4], f->subclass.integer)) {
3012                                         /* This is an interrupting chracter, so rewind to chop off any small
3013                                            amount of DTMF that may have been recorded
3014                                         */
3015                                         ast_stream_rewind(fs, 200);
3016                                         ast_truncstream(fs);
3017                                         sample_offset = ast_tellstream(fs);
3018                                         ast_closestream(fs);
3019                                         ast_agi_send(agi->fd, chan, "200 result=%d (dtmf) endpos=%ld\n", f->subclass.integer, sample_offset);
3020                                         ast_frfree(f);
3021                                         if (sildet)
3022                                                 ast_dsp_free(sildet);
3023                                         return RESULT_SUCCESS;
3024                                 }
3025                                 break;
3026                         case AST_FRAME_VOICE:
3027                                 ast_writestream(fs, f);
3028                                 /* this is a safe place to check progress since we know that fs
3029                                  * is valid after a write, and it will then have our current
3030                                  * location */
3031                                 sample_offset = ast_tellstream(fs);
3032                                 if (silence > 0) {
3033                                         dspsilence = 0;
3034                                         ast_dsp_silence(sildet, f, &dspsilence);
3035                                         if (dspsilence) {
3036                                                 totalsilence = dspsilence;
3037                                         } else {
3038                                                 totalsilence = 0;
3039                                         }
3040                                         if (totalsilence > silence) {
3041                                                 /* Ended happily with silence */
3042                                                 gotsilence = 1;
3043                                                 break;
3044                                         }
3045                                 }
3046                                 break;
3047                         case AST_FRAME_VIDEO:
3048                                 ast_writestream(fs, f);
3049                         default:
3050                                 /* Ignore all other frames */
3051                                 break;
3052                         }
3053                         ast_frfree(f);
3054                         if (gotsilence)
3055                                 break;
3056                 }
3057
3058                 if (gotsilence) {
3059                         ast_stream_rewind(fs, silence-1000);
3060                         ast_truncstream(fs);
3061                         sample_offset = ast_tellstream(fs);
3062                 }
3063                 ast_closestream(fs);
3064                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
3065         }
3066
3067         if (silence > 0) {
3068                 res = ast_set_read_format(chan, rfmt);
3069                 if (res)
3070                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", ast_channel_name(chan));
3071                 ast_dsp_free(sildet);
3072         }
3073
3074         return RESULT_SUCCESS;
3075 }
3076
3077 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3078 {
3079         double timeout;
3080         struct timeval whentohangup = { 0, 0 };
3081
3082         if (argc != 3)
3083                 return RESULT_SHOWUSAGE;
3084         if (sscanf(argv[2], "%30lf", &timeout) != 1)
3085                 return RESULT_SHOWUSAGE;
3086         if (timeout < 0)
3087                 timeout = 0;
3088         if (timeout) {
3089                 whentohangup.tv_sec = timeout;
3090                 whentohangup.tv_usec = (timeout - whentohangup.tv_sec) * 1000000.0;
3091         }
3092         ast_channel_lock(chan);
3093         ast_channel_setwhentohangup_tv(chan, whentohangup);
3094         ast_channel_unlock(chan);
3095         ast_agi_send(agi->fd, chan, "200 result=0\n");
3096         return RESULT_SUCCESS;
3097 }
3098
3099 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3100 {
3101         struct ast_channel *c;
3102
3103         if (argc == 1) {
3104                 /* no argument: hangup the current channel */
3105                 ast_set_hangupsource(chan, "dialplan/agi", 0);
3106                 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
3107                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3108                 return RESULT_SUCCESS;
3109         } else if (argc == 2) {
3110                 /* one argument: look for info on the specified channel */
3111                 if ((c = ast_channel_get_by_name(argv[1]))) {
3112                         /* we have a matching channel */
3113                         ast_set_hangupsource(c, "dialplan/agi", 0);
3114                         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
3115                         c = ast_channel_unref(c);
3116                         ast_agi_send(agi->fd, chan, "200 result=1\n");
3117                         return RESULT_SUCCESS;
3118                 }
3119                 /* if we get this far no channel name matched the argument given */
3120                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
3121                 return RESULT_SUCCESS;
3122         } else {
3123                 return RESULT_SHOWUSAGE;
3124         }
3125 }
3126
3127 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3128 {
3129         int res, workaround;
3130         struct ast_app *app_to_exec;
3131
3132         if (argc < 2)
3133                 return RESULT_SHOWUSAGE;
3134
3135         ast_verb(3, "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argc >= 3 ? argv[2] : "");
3136
3137         if ((app_to_exec = pbx_findapp(argv[1]))) {
3138                 ast_channel_lock(chan);
3139                 if (!(workaround = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS))) {
3140                         ast_set_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS);
3141                 }
3142                 ast_channel_unlock(chan);
3143                 res = pbx_exec(chan, app_to_exec, argc == 2 ? "" : argv[2]);
3144                 if (!workaround) {
3145                         ast_channel_clear_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS);
3146                 }
3147         } else {
3148                 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
3149                 res = -2;
3150         }
3151         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
3152
3153         /* Even though this is wrong, users are depending upon this result. */
3154         return res;
3155 }
3156
3157 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3158 {
3159         char tmp[256]="";
3160         char *l = NULL, *n = NULL;
3161
3162         if (argv[2]) {
3163                 ast_copy_string(tmp, argv[2], sizeof(tmp));
3164                 ast_callerid_parse(tmp, &n, &l);
3165                 if (l)
3166                         ast_shrink_phone_number(l);
3167                 else
3168                         l = "";
3169                 if (!n)
3170                         n = "";
3171                 ast_set_callerid(chan, l, n, NULL);
3172         }
3173
3174         ast_agi_send(agi->fd, chan, "200 result=1\n");
3175         return RESULT_SUCCESS;
3176 }
3177
3178 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3179 {
3180         if (argc == 2) {
3181                 /* no argument: supply info on the current channel */
3182                 ast_agi_send(agi->fd, chan, "200 result=%u\n", ast_channel_state(chan));
3183                 return RESULT_SUCCESS;
3184         } else if (argc == 3) {
3185                 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
3186
3187                 /* one argument: look for info on the specified channel */
3188                 if ((msg = stasis_cache_get(ast_channel_cache_by_name(), ast_channel_snapshot_type(), argv[2]))) {
3189                         struct ast_channel_snapshot *snapshot = stasis_message_data(msg);
3190
3191                         ast_agi_send(agi->fd, chan, "200 result=%u\n", snapshot->state);
3192                         return RESULT_SUCCESS;
3193                 }
3194                 /* if we get this far no channel name matched the argument given */
3195                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
3196                 return RESULT_SUCCESS;
3197         } else {
3198                 return RESULT_SHOWUSAGE;
3199         }
3200 }
3201
3202 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3203 {
3204         if (argc != 4) {
3205                 return RESULT_SHOWUSAGE;
3206         }
3207
3208         if (argv[3])
3209                 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
3210
3211         ast_agi_send(agi->fd, chan, "200 result=1\n");
3212         return RESULT_SUCCESS;
3213 }
3214
3215 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3216 {
3217         char *ret;
3218         char tempstr[1024] = "";
3219
3220         if (argc != 3)
3221                 return RESULT_SHOWUSAGE;
3222
3223         /* check if we want to execute an ast_custom_function */
3224         if (!ast_strlen_zero(argv[2]) && (argv[2][strlen(argv[2]) - 1] == ')')) {
3225                 ret = ast_func_read(chan, argv[2], tempstr, sizeof(tempstr)) ? NULL : tempstr;
3226         } else {
3227                 pbx_retrieve_variable(chan, argv[2], &ret, tempstr, sizeof(tempstr), NULL);
3228         }
3229
3230         if (ret)
3231                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ret);
3232         else
3233                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3234
3235         return RESULT_SUCCESS;
3236 }
3237
3238 static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3239 {
3240         struct ast_channel *chan2 = NULL;
3241
3242         if (argc != 4 && argc != 5) {
3243                 return RESULT_SHOWUSAGE;
3244         }
3245
3246         if (argc == 5) {
3247                 chan2 = ast_channel_get_by_name(argv[4]);
3248         } else {
3249                 chan2 = ast_channel_ref(chan);
3250         }
3251
3252         if (chan2) {
3253                 struct ast_str *str = ast_str_create(16);
3254                 if (!str) {
3255                         ast_agi_send(agi->fd, chan, "200 result=0\n");
3256                         return RESULT_SUCCESS;
3257                 }
3258                 ast_str_substitute_variables(&str, 0, chan2, argv[3]);
3259                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(str));
3260                 ast_free(str);
3261         } else {
3262                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3263         }
3264
3265         if (chan2) {
3266                 chan2 = ast_channel_unref(chan2);
3267         }
3268
3269         return RESULT_SUCCESS;
3270 }
3271
3272 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3273 {
3274         int level = 0;
3275
3276         if (argc < 2)
3277                 return RESULT_SHOWUSAGE;
3278
3279         if (argv[2])
3280                 sscanf(argv[2], "%30d", &level);
3281
3282         ast_verb(level, "%s: %s\n", ast_channel_data(chan), argv[1]);
3283
3284         ast_agi_send(agi->fd, chan, "200 result=1\n");
3285
3286         return RESULT_SUCCESS;
3287 }
3288
3289 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3290 {
3291         int res;
3292         struct ast_str *buf;
3293
3294         if (argc != 4)
3295                 return RESULT_SHOWUSAGE;
3296
3297         if (!(buf = ast_str_create(16))) {
3298                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
3299                 return RESULT_SUCCESS;
3300         }
3301
3302         do {
3303                 res = ast_db_get(argv[2], argv[3], ast_str_buffer(buf), ast_str_size(buf));
3304                 ast_str_update(buf);
3305                 if (ast_str_strlen(buf) < ast_str_size(buf) - 1) {
3306                         break;
3307                 }
3308                 if (ast_str_make_space(&buf, ast_str_size(buf) * 2)) {
3309                         break;
3310                 }
3311         } while (1);
3312
3313         if (res)
3314                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3315         else
3316                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(buf));
3317
3318         ast_free(buf);
3319         return RESULT_SUCCESS;
3320 }
3321
3322 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3323 {
3324         int res;
3325
3326         if (argc != 5)
3327                 return RESULT_SHOWUSAGE;
3328         res = ast_db_put(argv[2], argv[3], argv[4]);
3329         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
3330         return RESULT_SUCCESS;
3331 }
3332
3333 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3334 {
3335         int res;
3336
3337         if (argc != 4)
3338                 return RESULT_SHOWUSAGE;
3339         res = ast_db_del(argv[2], argv[3]);
3340         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
3341         return RESULT_SUCCESS;
3342 }
3343
3344 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3345 {
3346         int num_deleted;
3347
3348         if ((argc < 3) || (argc > 4)) {
3349                 return RESULT_SHOWUSAGE;
3350         }
3351         if (argc == 4) {
3352                 num_deleted = ast_db_deltree(argv[2], argv[3]);
3353         } else {
3354                 num_deleted = ast_db_deltree(argv[2], NULL);
3355         }
3356
3357         ast_agi_send(agi->fd, chan, "200 result=%c\n", num_deleted > 0 ? '0' : '1');
3358         return RESULT_SUCCESS;
3359 }
3360
3361 static char *handle_cli_agi_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3362 {
3363         switch (cmd) {
3364         case CLI_INIT:
3365                 e->command = "agi set debug [on|off]";
3366                 e->usage =
3367                         "Usage: agi set debug [on|off]\n"
3368                         "       Enables/disables dumping of AGI transactions for\n"
3369                         "       debugging purposes.\n";
3370                 return NULL;
3371
3372         case CLI_GENERATE:
3373                 return NULL;
3374         }
3375
3376         if (a->argc != e->args)
3377                 return CLI_SHOWUSAGE;
3378
3379         if (strncasecmp(a->argv[3], "off", 3) == 0) {
3380                 agidebug = 0;
3381         } else if (strncasecmp(a->argv[3], "on", 2) == 0) {
3382                 agidebug = 1;
3383         } else {
3384                 return CLI_SHOWUSAGE;
3385         }
3386         ast_cli(a->fd, "AGI Debugging %sabled\n", agidebug ? "En" : "Dis");
3387         return CLI_SUCCESS;
3388 }
3389
3390 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, const char * const argv[])
3391 {
3392         ast_agi_send(agi->fd, chan, "200 result=0\n");
3393         return RESULT_SUCCESS;
3394 }
3395
3396 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3397 {
3398         if (argc < 3) {
3399                 return RESULT_SHOWUSAGE;
3400         }
3401         if (!strncasecmp(argv[2], "on", 2))
3402                 ast_moh_start(chan, argc > 3 ? argv[3] : NULL, NULL);
3403         else if (!strncasecmp(argv[2], "off", 3))
3404                 ast_moh_stop(chan);
3405         ast_agi_send(agi->fd, chan, "200 result=0\n");
3406         return RESULT_SUCCESS;
3407 }
3408
3409 static int handle_speechcreate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3410 {
3411         struct ast_format_cap *cap;
3412
3413         /* If a structure already exists, return an error */
3414         if (agi->speech) {
3415                 ast_agi_send(agi->fd, chan, "200 result=0\n");