Merge "res_rtp_asterisk: Always return provided DTLS packet length."
[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 = ast_socket_nonblock(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_connect(s, &addrs[i]) && errno == EINPROGRESS) {
2080
2081                         if (handle_connection(agiurl, addrs[i], s)) {
2082                                 close(s);
2083                                 continue;
2084                         }
2085
2086                 } else {
2087                         ast_log(LOG_WARNING, "Connection to %s failed with unexpected error: %s\n",
2088                         ast_sockaddr_stringify(&addrs[i]), strerror(errno));
2089                 }
2090
2091                 break;
2092         }
2093
2094         ast_free(addrs);
2095
2096         if (i == num_addrs) {
2097                 ast_log(LOG_WARNING, "Couldn't connect to any host.  FastAGI failed.\n");
2098                 return AGI_RESULT_FAILURE;
2099         }
2100
2101         if (ast_agi_send(s, NULL, "agi_network: yes\n") < 0) {
2102                 if (errno != EINTR) {
2103                         ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
2104                         close(s);
2105                         return AGI_RESULT_FAILURE;
2106                 }
2107         }
2108
2109         /* If we have a script parameter, relay it to the fastagi server */
2110         /* Script parameters take the form of: AGI(agi://my.example.com/?extension=${EXTEN}) */
2111         if (!ast_strlen_zero(script)) {
2112                 ast_agi_send(s, NULL, "agi_network_script: %s\n", script);
2113         }
2114
2115         ast_debug(4, "Wow, connected!\n");
2116         fds[0] = s;
2117         fds[1] = s;
2118         return AGI_RESULT_SUCCESS_FAST;
2119 }
2120
2121 /*!
2122  * \internal
2123  * \brief The HA fastagi handler.
2124  * \param agiurl The request URL as passed to Agi() in the dial plan
2125  * \param argv The parameters after the URL passed to Agi() in the dial plan
2126  * \param fds Input/output file descriptors
2127  *
2128  * Uses SRV lookups to try to connect to a list of FastAGI servers. The hostname in
2129  * the URI is prefixed with _agi._tcp. prior to the DNS resolution. For
2130  * example, if you specify the URI \a hagi://agi.example.com/foo.agi the DNS
2131  * query would be for \a _agi._tcp.agi.example.com and you'll need to make sure
2132  * this resolves.
2133  *
2134  * This function parses the URI, resolves the SRV service name, forms new URIs
2135  * with the results of the DNS lookup, and then calls launch_netscript on the
2136  * new URIs until one succeeds.
2137  *
2138  * \return the result of the AGI operation.
2139  */
2140 static enum agi_result launch_ha_netscript(char *agiurl, char *argv[], int *fds)
2141 {
2142         char *host, *script;
2143         enum agi_result result;
2144         struct srv_context *context = NULL;
2145         int srv_ret;
2146         char service[256];
2147         char resolved_uri[1024];
2148         const char *srvhost;
2149         unsigned short srvport;
2150
2151         /* format of agiurl is "hagi://host.domain[:port][/script/name]" */
2152         if (strlen(agiurl) < 7) { /* Remove hagi:// */
2153                 ast_log(LOG_WARNING, "An error occurred parsing the AGI URI: %s", agiurl);
2154                 return AGI_RESULT_FAILURE;
2155         }
2156         host = ast_strdupa(agiurl + 7);
2157
2158         /* Strip off any script name */
2159         if ((script = strchr(host, '/'))) {
2160                 *script++ = '\0';
2161         } else {
2162                 script = "";
2163         }
2164
2165         if (strchr(host, ':')) {
2166                 ast_log(LOG_WARNING, "Specifying a port number disables SRV lookups: %s\n", agiurl);
2167                 return launch_netscript(agiurl + 1, argv, fds); /* +1 to strip off leading h from hagi:// */
2168         }
2169
2170         snprintf(service, sizeof(service), "%s%s", SRV_PREFIX, host);
2171
2172         while (!(srv_ret = ast_srv_lookup(&context, service, &srvhost, &srvport))) {
2173                 snprintf(resolved_uri, sizeof(resolved_uri), "agi://%s:%d/%s", srvhost, srvport, script);
2174                 result = launch_netscript(resolved_uri, argv, fds);
2175                 if (result == AGI_RESULT_FAILURE || result == AGI_RESULT_NOTFOUND) {
2176                         ast_log(LOG_WARNING, "AGI request failed for host '%s' (%s:%d)\n", host, srvhost, srvport);
2177                 } else {
2178                         /* The script launched so we must cleanup the context. */
2179                         ast_srv_cleanup(&context);
2180                         return result;
2181                 }
2182         }
2183         /*
2184          * The DNS SRV lookup failed or we ran out of servers to check.
2185          * ast_srv_lookup() has already cleaned up the context for us.
2186          */
2187         if (srv_ret < 0) {
2188                 ast_log(LOG_WARNING, "SRV lookup failed for %s\n", agiurl);
2189         }
2190
2191         return AGI_RESULT_FAILURE;
2192 }
2193
2194 static enum agi_result launch_script(struct ast_channel *chan, char *script, int argc, char *argv[], int *fds, int *efd, int *opid)
2195 {
2196         char tmp[256];
2197         int pid, toast[2], fromast[2], audio[2], res;
2198         struct stat st;
2199
2200         if (!strncasecmp(script, "agi://", 6)) {
2201                 return (efd == NULL) ? launch_netscript(script, argv, fds) : AGI_RESULT_FAILURE;
2202         }
2203         if (!strncasecmp(script, "hagi://", 7)) {
2204                 return (efd == NULL) ? launch_ha_netscript(script, argv, fds) : AGI_RESULT_FAILURE;
2205         }
2206         if (!strncasecmp(script, "agi:async", sizeof("agi:async") - 1)) {
2207                 return launch_asyncagi(chan, argc, argv, efd);
2208         }
2209
2210         if (script[0] != '/') {
2211                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_AGI_DIR, script);
2212                 script = tmp;
2213         }
2214
2215         /* Before even trying let's see if the file actually exists */
2216         if (stat(script, &st)) {
2217                 ast_log(LOG_WARNING, "Failed to execute '%s': File does not exist.\n", script);
2218                 return AGI_RESULT_NOTFOUND;
2219         }
2220
2221         if (pipe(toast)) {
2222                 ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
2223                 return AGI_RESULT_FAILURE;
2224         }
2225         if (pipe(fromast)) {
2226                 ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
2227                 close(toast[0]);
2228                 close(toast[1]);
2229                 return AGI_RESULT_FAILURE;
2230         }
2231         if (efd) {
2232                 if (pipe(audio)) {
2233                         ast_log(LOG_WARNING, "unable to create audio pipe: %s\n", strerror(errno));
2234                         close(fromast[0]);
2235                         close(fromast[1]);
2236                         close(toast[0]);
2237                         close(toast[1]);
2238                         return AGI_RESULT_FAILURE;
2239                 }
2240
2241                 res = ast_fd_set_flags(audio[1], O_NONBLOCK);
2242                 if (res < 0) {
2243                         ast_log(LOG_WARNING, "unable to set audio pipe parameters: %s\n", strerror(errno));
2244                         close(fromast[0]);
2245                         close(fromast[1]);
2246                         close(toast[0]);
2247                         close(toast[1]);
2248                         close(audio[0]);
2249                         close(audio[1]);
2250                         return AGI_RESULT_FAILURE;
2251                 }
2252         }
2253
2254         if ((pid = ast_safe_fork(1)) < 0) {
2255                 ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
2256                 return AGI_RESULT_FAILURE;
2257         }
2258         if (!pid) {
2259                 /* Pass paths to AGI via environmental variables */
2260                 setenv("AST_CONFIG_DIR", ast_config_AST_CONFIG_DIR, 1);
2261                 setenv("AST_CONFIG_FILE", ast_config_AST_CONFIG_FILE, 1);
2262                 setenv("AST_MODULE_DIR", ast_config_AST_MODULE_DIR, 1);
2263                 setenv("AST_SPOOL_DIR", ast_config_AST_SPOOL_DIR, 1);
2264                 setenv("AST_MONITOR_DIR", ast_config_AST_MONITOR_DIR, 1);
2265                 setenv("AST_VAR_DIR", ast_config_AST_VAR_DIR, 1);
2266                 setenv("AST_DATA_DIR", ast_config_AST_DATA_DIR, 1);
2267                 setenv("AST_LOG_DIR", ast_config_AST_LOG_DIR, 1);
2268                 setenv("AST_AGI_DIR", ast_config_AST_AGI_DIR, 1);
2269                 setenv("AST_KEY_DIR", ast_config_AST_KEY_DIR, 1);
2270                 setenv("AST_RUN_DIR", ast_config_AST_RUN_DIR, 1);
2271
2272                 /* Don't run AGI scripts with realtime priority -- it causes audio stutter */
2273                 ast_set_priority(0);
2274
2275                 /* Redirect stdin and out, provide enhanced audio channel if desired */
2276                 dup2(fromast[0], STDIN_FILENO);
2277                 dup2(toast[1], STDOUT_FILENO);
2278                 if (efd)
2279                         dup2(audio[0], STDERR_FILENO + 1);
2280                 else
2281                         close(STDERR_FILENO + 1);
2282
2283                 /* Close everything but stdin/out/error */
2284                 ast_close_fds_above_n(STDERR_FILENO + 1);
2285
2286                 /* Execute script */
2287                 /* XXX argv should be deprecated in favor of passing agi_argX paramaters */
2288                 execv(script, argv);
2289                 /* Can't use ast_log since FD's are closed */
2290                 ast_child_verbose(1, "Failed to execute '%s': %s", script, strerror(errno));
2291                 /* Special case to set status of AGI to failure */
2292                 fprintf(stdout, "failure\n");
2293                 fflush(stdout);
2294                 _exit(1);
2295         }
2296         ast_verb(3, "Launched AGI Script %s\n", script);
2297         fds[0] = toast[0];
2298         fds[1] = fromast[1];
2299         if (efd)
2300                 *efd = audio[1];
2301         /* close what we're not using in the parent */
2302         close(toast[1]);
2303         close(fromast[0]);
2304
2305         if (efd)
2306                 close(audio[0]);
2307
2308         *opid = pid;
2309         return AGI_RESULT_SUCCESS;
2310 }
2311
2312 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced, int argc, char *argv[])
2313 {
2314         int count;
2315
2316         /* Print initial environment, with agi_request always being the first
2317            thing */
2318         ast_agi_send(fd, chan, "agi_request: %s\n", request);
2319         ast_agi_send(fd, chan, "agi_channel: %s\n", ast_channel_name(chan));
2320         ast_agi_send(fd, chan, "agi_language: %s\n", ast_channel_language(chan));
2321         ast_agi_send(fd, chan, "agi_type: %s\n", ast_channel_tech(chan)->type);
2322         ast_agi_send(fd, chan, "agi_uniqueid: %s\n", ast_channel_uniqueid(chan));
2323         ast_agi_send(fd, chan, "agi_version: %s\n", ast_get_version());
2324
2325         /* ANI/DNIS */
2326         ast_agi_send(fd, chan, "agi_callerid: %s\n",
2327                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "unknown"));
2328         ast_agi_send(fd, chan, "agi_calleridname: %s\n",
2329                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "unknown"));
2330         ast_agi_send(fd, chan, "agi_callingpres: %d\n",
2331                 ast_party_id_presentation(&ast_channel_caller(chan)->id));
2332         ast_agi_send(fd, chan, "agi_callingani2: %d\n", ast_channel_caller(chan)->ani2);
2333         ast_agi_send(fd, chan, "agi_callington: %d\n", ast_channel_caller(chan)->id.number.plan);
2334         ast_agi_send(fd, chan, "agi_callingtns: %d\n", ast_channel_dialed(chan)->transit_network_select);
2335         ast_agi_send(fd, chan, "agi_dnid: %s\n", S_OR(ast_channel_dialed(chan)->number.str, "unknown"));
2336         ast_agi_send(fd, chan, "agi_rdnis: %s\n",
2337                 S_COR(ast_channel_redirecting(chan)->from.number.valid, ast_channel_redirecting(chan)->from.number.str, "unknown"));
2338
2339         /* Context information */
2340         ast_agi_send(fd, chan, "agi_context: %s\n", ast_channel_context(chan));
2341         ast_agi_send(fd, chan, "agi_extension: %s\n", ast_channel_exten(chan));
2342         ast_agi_send(fd, chan, "agi_priority: %d\n", ast_channel_priority(chan));
2343         ast_agi_send(fd, chan, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
2344
2345         /* User information */
2346         ast_agi_send(fd, chan, "agi_accountcode: %s\n", ast_channel_accountcode(chan) ? ast_channel_accountcode(chan) : "");
2347         ast_agi_send(fd, chan, "agi_threadid: %ld\n", (long)pthread_self());
2348
2349         /* Send any parameters to the fastagi server that have been passed via the agi application */
2350         /* Agi application paramaters take the form of: AGI(/path/to/example/script|${EXTEN}) */
2351         for(count = 1; count < argc; count++)
2352                 ast_agi_send(fd, chan, "agi_arg_%d: %s\n", count, argv[count]);
2353
2354         /* End with empty return */
2355         ast_agi_send(fd, chan, "\n");
2356 }
2357
2358 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2359 {
2360         int res = 0;
2361
2362         /* Answer the channel */
2363         if (ast_channel_state(chan) != AST_STATE_UP)
2364                 res = ast_answer(chan);
2365
2366         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2367         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2368 }
2369
2370 static int handle_asyncagi_break(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2371 {
2372         ast_agi_send(agi->fd, chan, "200 result=0\n");
2373         return ASYNC_AGI_BREAK;
2374 }
2375
2376 static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2377 {
2378         int res, to;
2379
2380         if (argc != 4)
2381                 return RESULT_SHOWUSAGE;
2382         if (sscanf(argv[3], "%30d", &to) != 1)
2383                 return RESULT_SHOWUSAGE;
2384         res = ast_waitfordigit_full(chan, to, NULL, agi->audio, agi->ctrl);
2385         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2386         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2387 }
2388
2389 static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2390 {
2391         int res;
2392
2393         if (argc != 3)
2394                 return RESULT_SHOWUSAGE;
2395
2396         /* At the moment, the parser (perhaps broken) returns with
2397            the last argument PLUS the newline at the end of the input
2398            buffer. This probably needs to be fixed, but I wont do that
2399            because other stuff may break as a result. The right way
2400            would probably be to strip off the trailing newline before
2401            parsing, then here, add a newline at the end of the string
2402            before sending it to ast_sendtext --DUDE */
2403         res = ast_sendtext(chan, argv[2]);
2404         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2405         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2406 }
2407
2408 static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2409 {
2410         int res;
2411
2412         if (argc != 3)
2413                 return RESULT_SHOWUSAGE;
2414
2415         res = ast_recvchar(chan,atoi(argv[2]));
2416         if (res == 0) {
2417                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout)\n", res);
2418                 return RESULT_SUCCESS;
2419         }
2420         if (res > 0) {
2421                 ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2422                 return RESULT_SUCCESS;
2423         }
2424         ast_agi_send(agi->fd, chan, "200 result=%d (hangup)\n", res);
2425         return RESULT_FAILURE;
2426 }
2427
2428 static int handle_recvtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2429 {
2430         char *buf;
2431
2432         if (argc != 3)
2433                 return RESULT_SHOWUSAGE;
2434
2435         buf = ast_recvtext(chan, atoi(argv[2]));
2436         if (buf) {
2437                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", buf);
2438                 ast_free(buf);
2439         } else {
2440                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2441         }
2442         return RESULT_SUCCESS;
2443 }
2444
2445 static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2446 {
2447         int res, x;
2448
2449         if (argc != 3)
2450                 return RESULT_SHOWUSAGE;
2451
2452         if (!strncasecmp(argv[2],"on",2)) {
2453                 x = 1;
2454         } else  {
2455                 x = 0;
2456         }
2457         if (!strncasecmp(argv[2],"mate",4))  {
2458                 x = 2;
2459         }
2460         if (!strncasecmp(argv[2],"tdd",3)) {
2461                 x = 1;
2462         }
2463         res = ast_channel_setoption(chan, AST_OPTION_TDD, &x, sizeof(char), 0);
2464         if (res) {
2465                 /* Set channel option failed */
2466                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2467         } else {
2468                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2469         }
2470         return RESULT_SUCCESS;
2471 }
2472
2473 static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2474 {
2475         int res;
2476
2477         if (argc != 3) {
2478                 return RESULT_SHOWUSAGE;
2479         }
2480
2481         res = ast_send_image(chan, argv[2]);
2482         if (!ast_check_hangup(chan)) {
2483                 res = 0;
2484         }
2485         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2486         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2487 }
2488
2489 static int handle_controlstreamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2490 {
2491         int res = 0, skipms = 3000;
2492         const char *fwd = "#", *rev = "*", *suspend = NULL, *stop = NULL;       /* Default values */
2493         char stopkeybuf[2];
2494         long offsetms = 0;
2495         char offsetbuf[20];
2496
2497         if (argc < 5 || argc > 10) {
2498                 return RESULT_SHOWUSAGE;
2499         }
2500
2501         if (!ast_strlen_zero(argv[4])) {
2502                 stop = argv[4];
2503         }
2504
2505         if ((argc > 5) && (sscanf(argv[5], "%30d", &skipms) != 1)) {
2506                 return RESULT_SHOWUSAGE;
2507         }
2508
2509         if (argc > 6 && !ast_strlen_zero(argv[6])) {
2510                 fwd = argv[6];
2511         }
2512
2513         if (argc > 7 && !ast_strlen_zero(argv[7])) {
2514                 rev = argv[7];
2515         }
2516
2517         if (argc > 8 && !ast_strlen_zero(argv[8])) {
2518                 suspend = argv[8];
2519         }
2520
2521         if (argc > 9 && (sscanf(argv[9], "%30ld", &offsetms) != 1)) {
2522                 return RESULT_SHOWUSAGE;
2523         }
2524
2525         res = ast_control_streamfile(chan, argv[3], fwd, rev, stop, suspend, NULL, skipms, &offsetms);
2526
2527         /* If we stopped on one of our stop keys, return 0  */
2528         if (res > 0 && stop && strchr(stop, res)) {
2529                 pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "USERSTOPPED");
2530                 snprintf(stopkeybuf, sizeof(stopkeybuf), "%c", res);
2531                 pbx_builtin_setvar_helper(chan, "CPLAYBACKSTOPKEY", stopkeybuf);
2532         } else if (res > 0 && res == AST_CONTROL_STREAM_STOP) {
2533                 pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "REMOTESTOPPED");
2534                 res = 0;
2535         } else {
2536                 if (res < 0) {
2537                         pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "ERROR");
2538                 } else {
2539                         pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "SUCCESS");
2540                 }
2541         }
2542
2543         snprintf(offsetbuf, sizeof(offsetbuf), "%ld", offsetms);
2544         pbx_builtin_setvar_helper(chan, "CPLAYBACKOFFSET", offsetbuf);
2545
2546         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, offsetms);
2547
2548         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2549 }
2550
2551 static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2552 {
2553         int res;
2554         struct ast_filestream *fs, *vfs;
2555         long sample_offset = 0, max_length;
2556         const char *edigits = "";
2557
2558         if (argc < 4 || argc > 5) {
2559                 return RESULT_SHOWUSAGE;
2560         }
2561
2562         if (argv[3]) {
2563                 edigits = argv[3];
2564         }
2565
2566         if ((argc > 4) && (sscanf(argv[4], "%30ld", &sample_offset) != 1)) {
2567                 return RESULT_SHOWUSAGE;
2568         }
2569
2570         if (!(fs = ast_openstream(chan, argv[2], ast_channel_language(chan)))) {
2571                 ast_agi_send(agi->fd, chan, "200 result=-1 endpos=%ld\n", sample_offset);
2572                 return RESULT_FAILURE;
2573         }
2574
2575         if ((vfs = ast_openvstream(chan, argv[2], ast_channel_language(chan)))) {
2576                 ast_debug(1, "Ooh, found a video stream, too\n");
2577         }
2578         ast_verb(3, "<%s> Playing '%s.%s' (escape_digits=%s) (sample_offset %ld) (language '%s')\n",
2579                 ast_channel_name(chan), argv[2], ast_format_get_name(ast_channel_writeformat(chan)),
2580                 edigits, sample_offset, S_OR(ast_channel_language(chan), "default"));
2581
2582         ast_seekstream(fs, 0, SEEK_END);
2583         max_length = ast_tellstream(fs);
2584         ast_seekstream(fs, sample_offset, SEEK_SET);
2585         res = ast_applystream(chan, fs);
2586         if (vfs) {
2587                 ast_applystream(chan, vfs);
2588         }
2589         ast_playstream(fs);
2590         if (vfs) {
2591                 ast_playstream(vfs);
2592         }
2593
2594         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
2595         /* this is to check for if ast_waitstream closed the stream, we probably are at
2596          * the end of the stream, return that amount, else check for the amount */
2597         sample_offset = (ast_channel_stream(chan)) ? ast_tellstream(fs) : max_length;
2598         ast_stopstream(chan);
2599         if (res == 1) {
2600                 /* Stop this command, don't print a result line, as there is a new command */
2601                 return RESULT_SUCCESS;
2602         }
2603         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
2604         pbx_builtin_setvar_helper(chan, "PLAYBACKSTATUS", res ? "FAILED" : "SUCCESS");
2605
2606         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2607 }
2608
2609 /*! \brief get option - really similar to the handle_streamfile, but with a timeout */
2610 static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2611 {
2612         int res;
2613         struct ast_filestream *fs, *vfs;
2614         long sample_offset = 0, max_length;
2615         int timeout = 0;
2616         const char *edigits = "";
2617
2618         if ( argc < 4 || argc > 5 )
2619                 return RESULT_SHOWUSAGE;
2620
2621         if ( argv[3] )
2622                 edigits = argv[3];
2623
2624         if ( argc == 5 )
2625                 timeout = atoi(argv[4]);
2626         else if (ast_channel_pbx(chan)->dtimeoutms) {
2627                 /* by default dtimeout is set to 5sec */
2628                 timeout = ast_channel_pbx(chan)->dtimeoutms; /* in msec */
2629         }
2630
2631         if (!(fs = ast_openstream(chan, argv[2], ast_channel_language(chan)))) {
2632                 ast_agi_send(agi->fd, chan, "200 result=-1 endpos=%ld\n", sample_offset);
2633                 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
2634                 return RESULT_FAILURE;
2635         }
2636
2637         if ((vfs = ast_openvstream(chan, argv[2], ast_channel_language(chan))))
2638                 ast_debug(1, "Ooh, found a video stream, too\n");
2639
2640         ast_verb(3, "Playing '%s' (escape_digits=%s) (timeout %d)\n", argv[2], edigits, timeout);
2641
2642         ast_seekstream(fs, 0, SEEK_END);
2643         max_length = ast_tellstream(fs);
2644         ast_seekstream(fs, sample_offset, SEEK_SET);
2645         res = ast_applystream(chan, fs);
2646         if (vfs)
2647                 ast_applystream(chan, vfs);
2648         ast_playstream(fs);
2649         if (vfs)
2650                 ast_playstream(vfs);
2651
2652         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
2653         /* this is to check for if ast_waitstream closed the stream, we probably are at
2654          * the end of the stream, return that amount, else check for the amount */
2655         sample_offset = (ast_channel_stream(chan))?ast_tellstream(fs):max_length;
2656         ast_stopstream(chan);
2657         if (res == 1) {
2658                 /* Stop this command, don't print a result line, as there is a new command */
2659                 return RESULT_SUCCESS;
2660         }
2661
2662         /* If the user didnt press a key, wait for digitTimeout*/
2663         if (res == 0 ) {
2664                 res = ast_waitfordigit_full(chan, timeout, NULL, agi->audio, agi->ctrl);
2665                 /* Make sure the new result is in the escape digits of the GET OPTION */
2666                 if ( !strchr(edigits,res) )
2667                         res=0;
2668         }
2669
2670         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
2671         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2672 }
2673
2674
2675
2676
2677 /*! \brief Say number in various language syntaxes */
2678 /* While waiting, we're sending a NULL.  */
2679 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2680 {
2681         int res, num;
2682
2683         if (argc < 4 || argc > 5)
2684                 return RESULT_SHOWUSAGE;
2685         if (sscanf(argv[2], "%30d", &num) != 1)
2686                 return RESULT_SHOWUSAGE;
2687         res = ast_say_number_full(chan, num, argv[3], ast_channel_language(chan), argc > 4 ? argv[4] : NULL, agi->audio, agi->ctrl);
2688         if (res == 1)
2689                 return RESULT_SUCCESS;
2690         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2691         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2692 }
2693
2694 static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2695 {
2696         int res, num;
2697
2698         if (argc != 4)
2699                 return RESULT_SHOWUSAGE;
2700         if (sscanf(argv[2], "%30d", &num) != 1)
2701                 return RESULT_SHOWUSAGE;
2702
2703         res = ast_say_digit_str_full(chan, argv[2], argv[3], ast_channel_language(chan), agi->audio, agi->ctrl);
2704         if (res == 1) /* New command */
2705                 return RESULT_SUCCESS;
2706         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2707         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2708 }
2709
2710 static int handle_sayalpha(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2711 {
2712         int res;
2713         int sensitivity = AST_SAY_CASE_NONE;
2714
2715         if (argc < 4 || argc > 5) {
2716                 return RESULT_SHOWUSAGE;
2717         }
2718
2719         if (argc > 4) {
2720                 switch (argv[4][0]) {
2721                 case 'a':
2722                 case 'A':
2723                         sensitivity = AST_SAY_CASE_ALL;
2724                         break;
2725                 case 'l':
2726                 case 'L':
2727                         sensitivity = AST_SAY_CASE_LOWER;
2728                         break;
2729                 case 'n':
2730                 case 'N':
2731                         sensitivity = AST_SAY_CASE_NONE;
2732                         break;
2733                 case 'u':
2734                 case 'U':
2735                         sensitivity = AST_SAY_CASE_UPPER;
2736                         break;
2737                 case '\0':
2738                         break;
2739                 default:
2740                         return RESULT_SHOWUSAGE;
2741                 }
2742         }
2743         res = ast_say_character_str_full(chan, argv[2], argv[3], ast_channel_language(chan), sensitivity, agi->audio, agi->ctrl);
2744         if (res == 1) /* New command */
2745                 return RESULT_SUCCESS;
2746         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2747         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2748 }
2749
2750 static int handle_saydate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2751 {
2752         int res, num;
2753
2754         if (argc != 4)
2755                 return RESULT_SHOWUSAGE;
2756         if (sscanf(argv[2], "%30d", &num) != 1)
2757                 return RESULT_SHOWUSAGE;
2758         res = ast_say_date(chan, num, argv[3], ast_channel_language(chan));
2759         if (res == 1)
2760                 return RESULT_SUCCESS;
2761         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2762         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2763 }
2764
2765 static int handle_saytime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2766 {
2767         int res, num;
2768
2769         if (argc != 4)
2770                 return RESULT_SHOWUSAGE;
2771         if (sscanf(argv[2], "%30d", &num) != 1)
2772                 return RESULT_SHOWUSAGE;
2773         res = ast_say_time(chan, num, argv[3], ast_channel_language(chan));
2774         if (res == 1)
2775                 return RESULT_SUCCESS;
2776         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2777         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2778 }
2779
2780 static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2781 {
2782         int res = 0;
2783         time_t unixtime;
2784         const char *format, *zone = NULL;
2785
2786         if (argc < 4)
2787                 return RESULT_SHOWUSAGE;
2788
2789         if (argc > 4) {
2790                 format = argv[4];
2791         } else {
2792                 /* XXX this doesn't belong here, but in the 'say' module */
2793                 if (!strcasecmp(ast_channel_language(chan), "de")) {
2794                         format = "A dBY HMS";
2795                 } else {
2796                         format = "ABdY 'digits/at' IMp";
2797                 }
2798         }
2799
2800         if (argc > 5 && !ast_strlen_zero(argv[5]))
2801                 zone = argv[5];
2802
2803         if (ast_get_time_t(argv[2], &unixtime, 0, NULL))
2804                 return RESULT_SHOWUSAGE;
2805
2806         res = ast_say_date_with_format(chan, unixtime, argv[3], ast_channel_language(chan), format, zone);
2807         if (res == 1)
2808                 return RESULT_SUCCESS;
2809
2810         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2811         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2812 }
2813
2814 static int handle_sayphonetic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2815 {
2816         int res;
2817
2818         if (argc != 4)
2819                 return RESULT_SHOWUSAGE;
2820
2821         res = ast_say_phonetic_str_full(chan, argv[2], argv[3], ast_channel_language(chan), agi->audio, agi->ctrl);
2822         if (res == 1) /* New command */
2823                 return RESULT_SUCCESS;
2824         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2825         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2826 }
2827
2828 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2829 {
2830         int res, max, timeout;
2831         char data[1024];
2832
2833         if (argc < 3)
2834                 return RESULT_SHOWUSAGE;
2835         if (argc >= 4)
2836                 timeout = atoi(argv[3]);
2837         else
2838                 timeout = 0;
2839         if (argc >= 5)
2840                 max = atoi(argv[4]);
2841         else
2842                 max = 1024;
2843         res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
2844         if (res == 2)                   /* New command */
2845                 return RESULT_SUCCESS;
2846         else if (res == 1)
2847                 ast_agi_send(agi->fd, chan, "200 result=%s (timeout)\n", data);
2848         else if (res < 0 )
2849                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2850         else
2851                 ast_agi_send(agi->fd, chan, "200 result=%s\n", data);
2852         return RESULT_SUCCESS;
2853 }
2854
2855 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2856 {
2857
2858         if (argc != 3)
2859                 return RESULT_SHOWUSAGE;
2860         ast_channel_context_set(chan, argv[2]);
2861         ast_agi_send(agi->fd, chan, "200 result=0\n");
2862         return RESULT_SUCCESS;
2863 }
2864
2865 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2866 {
2867         if (argc != 3)
2868                 return RESULT_SHOWUSAGE;
2869         ast_channel_exten_set(chan, argv[2]);
2870         ast_agi_send(agi->fd, chan, "200 result=0\n");
2871         return RESULT_SUCCESS;
2872 }
2873
2874 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2875 {
2876         int pri;
2877
2878         if (argc != 3)
2879                 return RESULT_SHOWUSAGE;
2880
2881         if (sscanf(argv[2], "%30d", &pri) != 1) {
2882                 pri = ast_findlabel_extension(chan, ast_channel_context(chan), ast_channel_exten(chan), argv[2],
2883                         S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL));
2884                 if (pri < 1)
2885                         return RESULT_SHOWUSAGE;
2886         }
2887
2888         ast_explicit_goto(chan, NULL, NULL, pri);
2889         ast_agi_send(agi->fd, chan, "200 result=0\n");
2890         return RESULT_SUCCESS;
2891 }
2892
2893 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2894 {
2895         struct ast_filestream *fs;
2896         struct ast_frame *f;
2897         struct timeval start;
2898         long sample_offset = 0;
2899         int res = 0;
2900         int ms;
2901
2902         struct ast_dsp *sildet=NULL;         /* silence detector dsp */
2903         int totalsilence = 0;
2904         int dspsilence = 0;
2905         int silence = 0;                /* amount of silence to allow */
2906         int gotsilence = 0;             /* did we timeout for silence? */
2907         char *silencestr = NULL;
2908         RAII_VAR(struct ast_format *, rfmt, NULL, ao2_cleanup);
2909
2910         /* XXX EAGI FIXME XXX */
2911
2912         if (argc < 6)
2913                 return RESULT_SHOWUSAGE;
2914         if (sscanf(argv[5], "%30d", &ms) != 1)
2915                 return RESULT_SHOWUSAGE;
2916
2917         if (argc > 6)
2918                 silencestr = strchr(argv[6],'s');
2919         if ((argc > 7) && (!silencestr))
2920                 silencestr = strchr(argv[7],'s');
2921         if ((argc > 8) && (!silencestr))
2922                 silencestr = strchr(argv[8],'s');
2923
2924         if (silencestr) {
2925                 if (strlen(silencestr) > 2) {
2926                         if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
2927                                 silencestr++;
2928                                 silencestr++;
2929                                 if (silencestr)
2930                                         silence = atoi(silencestr);
2931                                 if (silence > 0)
2932                                         silence *= 1000;
2933                         }
2934                 }
2935         }
2936
2937         if (silence > 0) {
2938                 rfmt = ao2_bump(ast_channel_readformat(chan));
2939                 res = ast_set_read_format(chan, ast_format_slin);
2940                 if (res < 0) {
2941                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
2942                         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2943                         return RESULT_FAILURE;
2944                 }
2945                 sildet = ast_dsp_new();
2946                 if (!sildet) {
2947                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
2948                         ast_agi_send(agi->fd, chan, "200 result=-1\n");
2949                         return RESULT_FAILURE;
2950                 }
2951                 ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
2952         }
2953
2954         /* backward compatibility, if no offset given, arg[6] would have been
2955          * caught below and taken to be a beep, else if it is a digit then it is a
2956          * offset */
2957         if ((argc >6) && (sscanf(argv[6], "%30ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
2958                 res = ast_streamfile(chan, "beep", ast_channel_language(chan));
2959
2960         if ((argc > 7) && (!strchr(argv[7], '=')))
2961                 res = ast_streamfile(chan, "beep", ast_channel_language(chan));
2962
2963         if (!res)
2964                 res = ast_waitstream(chan, argv[4]);
2965         if (res) {
2966                 ast_agi_send(agi->fd, chan, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
2967         } else {
2968                 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, AST_FILE_MODE);
2969                 if (!fs) {
2970                         res = -1;
2971                         ast_agi_send(agi->fd, chan, "200 result=%d (writefile)\n", res);
2972                         if (sildet)
2973                                 ast_dsp_free(sildet);
2974                         return RESULT_FAILURE;
2975                 }
2976
2977                 /* Request a video update */
2978                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
2979
2980                 ast_channel_stream_set(chan, fs);
2981                 ast_applystream(chan,fs);
2982                 /* really should have checks */
2983                 ast_seekstream(fs, sample_offset, SEEK_SET);
2984                 ast_truncstream(fs);
2985
2986                 start = ast_tvnow();
2987                 while ((ms < 0) || ast_tvdiff_ms(ast_tvnow(), start) < ms) {
2988                         res = ast_waitfor(chan, ms - ast_tvdiff_ms(ast_tvnow(), start));
2989                         if (res < 0) {
2990                                 ast_closestream(fs);
2991                                 ast_agi_send(agi->fd, chan, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
2992                                 if (sildet)
2993                                         ast_dsp_free(sildet);
2994                                 return RESULT_FAILURE;
2995                         }
2996                         f = ast_read(chan);
2997                         if (!f) {
2998                                 ast_closestream(fs);
2999                                 ast_agi_send(agi->fd, chan, "200 result=%d (hangup) endpos=%ld\n", -1, sample_offset);
3000                                 if (sildet)
3001                                         ast_dsp_free(sildet);
3002                                 return RESULT_FAILURE;
3003                         }
3004                         switch(f->frametype) {
3005                         case AST_FRAME_DTMF:
3006                                 if (strchr(argv[4], f->subclass.integer)) {
3007                                         /* This is an interrupting chracter, so rewind to chop off any small
3008                                            amount of DTMF that may have been recorded
3009                                         */
3010                                         ast_stream_rewind(fs, 200);
3011                                         ast_truncstream(fs);
3012                                         sample_offset = ast_tellstream(fs);
3013                                         ast_closestream(fs);
3014                                         ast_agi_send(agi->fd, chan, "200 result=%d (dtmf) endpos=%ld\n", f->subclass.integer, sample_offset);
3015                                         ast_frfree(f);
3016                                         if (sildet)
3017                                                 ast_dsp_free(sildet);
3018                                         return RESULT_SUCCESS;
3019                                 }
3020                                 break;
3021                         case AST_FRAME_VOICE:
3022                                 ast_writestream(fs, f);
3023                                 /* this is a safe place to check progress since we know that fs
3024                                  * is valid after a write, and it will then have our current
3025                                  * location */
3026                                 sample_offset = ast_tellstream(fs);
3027                                 if (silence > 0) {
3028                                         dspsilence = 0;
3029                                         ast_dsp_silence(sildet, f, &dspsilence);
3030                                         if (dspsilence) {
3031                                                 totalsilence = dspsilence;
3032                                         } else {
3033                                                 totalsilence = 0;
3034                                         }
3035                                         if (totalsilence > silence) {
3036                                                 /* Ended happily with silence */
3037                                                 gotsilence = 1;
3038                                                 break;
3039                                         }
3040                                 }
3041                                 break;
3042                         case AST_FRAME_VIDEO:
3043                                 ast_writestream(fs, f);
3044                         default:
3045                                 /* Ignore all other frames */
3046                                 break;
3047                         }
3048                         ast_frfree(f);
3049                         if (gotsilence)
3050                                 break;
3051                 }
3052
3053                 if (gotsilence) {
3054                         ast_stream_rewind(fs, silence-1000);
3055                         ast_truncstream(fs);
3056                         sample_offset = ast_tellstream(fs);
3057                 }
3058                 ast_closestream(fs);
3059                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
3060         }
3061
3062         if (silence > 0) {
3063                 res = ast_set_read_format(chan, rfmt);
3064                 if (res)
3065                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", ast_channel_name(chan));
3066                 ast_dsp_free(sildet);
3067         }
3068
3069         return RESULT_SUCCESS;
3070 }
3071
3072 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3073 {
3074         double timeout;
3075         struct timeval whentohangup = { 0, 0 };
3076
3077         if (argc != 3)
3078                 return RESULT_SHOWUSAGE;
3079         if (sscanf(argv[2], "%30lf", &timeout) != 1)
3080                 return RESULT_SHOWUSAGE;
3081         if (timeout < 0)
3082                 timeout = 0;
3083         if (timeout) {
3084                 whentohangup.tv_sec = timeout;
3085                 whentohangup.tv_usec = (timeout - whentohangup.tv_sec) * 1000000.0;
3086         }
3087         ast_channel_lock(chan);
3088         ast_channel_setwhentohangup_tv(chan, whentohangup);
3089         ast_channel_unlock(chan);
3090         ast_agi_send(agi->fd, chan, "200 result=0\n");
3091         return RESULT_SUCCESS;
3092 }
3093
3094 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3095 {
3096         struct ast_channel *c;
3097
3098         if (argc == 1) {
3099                 /* no argument: hangup the current channel */
3100                 ast_set_hangupsource(chan, "dialplan/agi", 0);
3101                 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
3102                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3103                 return RESULT_SUCCESS;
3104         } else if (argc == 2) {
3105                 /* one argument: look for info on the specified channel */
3106                 if ((c = ast_channel_get_by_name(argv[1]))) {
3107                         /* we have a matching channel */
3108                         ast_set_hangupsource(c, "dialplan/agi", 0);
3109                         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
3110                         c = ast_channel_unref(c);
3111                         ast_agi_send(agi->fd, chan, "200 result=1\n");
3112                         return RESULT_SUCCESS;
3113                 }
3114                 /* if we get this far no channel name matched the argument given */
3115                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
3116                 return RESULT_SUCCESS;
3117         } else {
3118                 return RESULT_SHOWUSAGE;
3119         }
3120 }
3121
3122 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3123 {
3124         int res, workaround;
3125         struct ast_app *app_to_exec;
3126
3127         if (argc < 2)
3128                 return RESULT_SHOWUSAGE;
3129
3130         ast_verb(3, "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argc >= 3 ? argv[2] : "");
3131
3132         if ((app_to_exec = pbx_findapp(argv[1]))) {
3133                 ast_channel_lock(chan);
3134                 if (!(workaround = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS))) {
3135                         ast_set_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS);
3136                 }
3137                 ast_channel_unlock(chan);
3138                 res = pbx_exec(chan, app_to_exec, argc == 2 ? "" : argv[2]);
3139                 if (!workaround) {
3140                         ast_channel_clear_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS);
3141                 }
3142         } else {
3143                 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
3144                 res = -2;
3145         }
3146         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
3147
3148         /* Even though this is wrong, users are depending upon this result. */
3149         return res;
3150 }
3151
3152 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3153 {
3154         char tmp[256]="";
3155         char *l = NULL, *n = NULL;
3156
3157         if (argv[2]) {
3158                 ast_copy_string(tmp, argv[2], sizeof(tmp));
3159                 ast_callerid_parse(tmp, &n, &l);
3160                 if (l)
3161                         ast_shrink_phone_number(l);
3162                 else
3163                         l = "";
3164                 if (!n)
3165                         n = "";
3166                 ast_set_callerid(chan, l, n, NULL);
3167         }
3168
3169         ast_agi_send(agi->fd, chan, "200 result=1\n");
3170         return RESULT_SUCCESS;
3171 }
3172
3173 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3174 {
3175         if (argc == 2) {
3176                 /* no argument: supply info on the current channel */
3177                 ast_agi_send(agi->fd, chan, "200 result=%u\n", ast_channel_state(chan));
3178                 return RESULT_SUCCESS;
3179         } else if (argc == 3) {
3180                 struct ast_channel_snapshot *snapshot;
3181
3182                 /* one argument: look for info on the specified channel */
3183                 snapshot = ast_channel_snapshot_get_latest_by_name(argv[2]);
3184                 if (snapshot) {
3185                         ast_agi_send(agi->fd, chan, "200 result=%u\n", snapshot->state);
3186                         ao2_ref(snapshot, -1);
3187                         return RESULT_SUCCESS;
3188                 }
3189                 /* if we get this far no channel name matched the argument given */
3190                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
3191                 return RESULT_SUCCESS;
3192         } else {
3193                 return RESULT_SHOWUSAGE;
3194         }
3195 }
3196
3197 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3198 {
3199         if (argc != 4) {
3200                 return RESULT_SHOWUSAGE;
3201         }
3202
3203         if (argv[3])
3204                 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
3205
3206         ast_agi_send(agi->fd, chan, "200 result=1\n");
3207         return RESULT_SUCCESS;
3208 }
3209
3210 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3211 {
3212         char *ret;
3213         char tempstr[1024] = "";
3214
3215         if (argc != 3)
3216                 return RESULT_SHOWUSAGE;
3217
3218         /* check if we want to execute an ast_custom_function */
3219         if (!ast_strlen_zero(argv[2]) && (argv[2][strlen(argv[2]) - 1] == ')')) {
3220                 ret = ast_func_read(chan, argv[2], tempstr, sizeof(tempstr)) ? NULL : tempstr;
3221         } else {
3222                 pbx_retrieve_variable(chan, argv[2], &ret, tempstr, sizeof(tempstr), NULL);
3223         }
3224
3225         if (ret)
3226                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ret);
3227         else
3228                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3229
3230         return RESULT_SUCCESS;
3231 }
3232
3233 static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3234 {
3235         struct ast_channel *chan2 = NULL;
3236
3237         if (argc != 4 && argc != 5) {
3238                 return RESULT_SHOWUSAGE;
3239         }
3240
3241         if (argc == 5) {
3242                 chan2 = ast_channel_get_by_name(argv[4]);
3243         } else {
3244                 chan2 = ast_channel_ref(chan);
3245         }
3246
3247         if (chan2) {
3248                 struct ast_str *str = ast_str_create(16);
3249                 if (!str) {
3250                         ast_agi_send(agi->fd, chan, "200 result=0\n");
3251                         return RESULT_SUCCESS;
3252                 }
3253                 ast_str_substitute_variables(&str, 0, chan2, argv[3]);
3254                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(str));
3255                 ast_free(str);
3256         } else {
3257                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3258         }
3259
3260         if (chan2) {
3261                 chan2 = ast_channel_unref(chan2);
3262         }
3263
3264         return RESULT_SUCCESS;
3265 }
3266
3267 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3268 {
3269         int level = 0;
3270
3271         if (argc < 2)
3272                 return RESULT_SHOWUSAGE;
3273
3274         if (argv[2])
3275                 sscanf(argv[2], "%30d", &level);
3276
3277         ast_verb(level, "%s: %s\n", ast_channel_data(chan), argv[1]);
3278
3279         ast_agi_send(agi->fd, chan, "200 result=1\n");
3280
3281         return RESULT_SUCCESS;
3282 }
3283
3284 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3285 {
3286         int res;
3287         struct ast_str *buf;
3288
3289         if (argc != 4)
3290                 return RESULT_SHOWUSAGE;
3291
3292         if (!(buf = ast_str_create(16))) {
3293                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
3294                 return RESULT_SUCCESS;
3295         }
3296
3297         do {
3298                 res = ast_db_get(argv[2], argv[3], ast_str_buffer(buf), ast_str_size(buf));
3299                 ast_str_update(buf);
3300                 if (ast_str_strlen(buf) < ast_str_size(buf) - 1) {
3301                         break;
3302                 }
3303                 if (ast_str_make_space(&buf, ast_str_size(buf) * 2)) {
3304                         break;
3305                 }
3306         } while (1);
3307
3308         if (res)
3309                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3310         else
3311                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(buf));
3312
3313         ast_free(buf);
3314         return RESULT_SUCCESS;
3315 }
3316
3317 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3318 {
3319         int res;
3320
3321         if (argc != 5)
3322                 return RESULT_SHOWUSAGE;
3323         res = ast_db_put(argv[2], argv[3], argv[4]);
3324         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
3325         return RESULT_SUCCESS;
3326 }
3327
3328 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3329 {
3330         int res;
3331
3332         if (argc != 4)
3333                 return RESULT_SHOWUSAGE;
3334         res = ast_db_del(argv[2], argv[3]);
3335         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
3336         return RESULT_SUCCESS;
3337 }
3338
3339 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3340 {
3341         int num_deleted;
3342
3343         if ((argc < 3) || (argc > 4)) {
3344                 return RESULT_SHOWUSAGE;
3345         }
3346         if (argc == 4) {
3347                 num_deleted = ast_db_deltree(argv[2], argv[3]);
3348         } else {
3349                 num_deleted = ast_db_deltree(argv[2], NULL);
3350         }
3351
3352         ast_agi_send(agi->fd, chan, "200 result=%c\n", num_deleted > 0 ? '0' : '1');
3353         return RESULT_SUCCESS;
3354 }
3355
3356 static char *handle_cli_agi_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3357 {
3358         switch (cmd) {
3359         case CLI_INIT:
3360                 e->command = "agi set debug [on|off]";
3361                 e->usage =
3362                         "Usage: agi set debug [on|off]\n"
3363                         "       Enables/disables dumping of AGI transactions for\n"
3364                         "       debugging purposes.\n";
3365                 return NULL;
3366
3367         case CLI_GENERATE:
3368                 return NULL;
3369         }
3370
3371         if (a->argc != e->args)
3372                 return CLI_SHOWUSAGE;
3373
3374         if (strncasecmp(a->argv[3], "off", 3) == 0) {
3375                 agidebug = 0;
3376         } else if (strncasecmp(a->argv[3], "on", 2) == 0) {
3377                 agidebug = 1;
3378         } else {
3379                 return CLI_SHOWUSAGE;
3380         }
3381         ast_cli(a->fd, "AGI Debugging %sabled\n", agidebug ? "En" : "Dis");
3382         return CLI_SUCCESS;
3383 }
3384
3385 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, const char * const argv[])
3386 {
3387         ast_agi_send(agi->fd, chan, "200 result=0\n");
3388         return RESULT_SUCCESS;
3389 }
3390
3391 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3392 {
3393         if (argc < 3) {
3394                 return RESULT_SHOWUSAGE;
3395         }
3396         if (!strncasecmp(argv[2], "on", 2))
3397                 ast_moh_start(chan, argc > 3 ? argv[3] : NULL, NULL);
3398         else if (!strncasecmp(argv[2], "off", 3))
3399                 ast_moh_stop(chan);
3400         ast_agi_send(agi->fd, chan, "200 result=0\n");
3401         return RESULT_SUCCESS;
3402 }
3403
3404 static int handle_speechcreate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3405 {
3406         struct ast_format_cap *cap;
3407
3408         /* If a structure already exists, return an error */
3409         if (agi->speech) {
3410                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3411                 return RESULT_SUCCESS;
3412         }
3413
3414         if (!(cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
3415                 return RESULT_FAILURE;
3416         }
3417         ast_format_cap_append(cap, ast_format_slin, 0);
3418         if ((agi->speech = ast_speech_new(argv[2], cap))) {
3419                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3420         } else {
3421                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3422         }
3423         ao2_ref(cap, -1);
3424
3425         return RESULT_SUCCESS;
3426 }
3427
3428 static int handle_speechset(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3429 {
3430         /* Check for minimum arguments */
3431         if (argc != 4)
3432                 return RESULT_SHOWUSAGE;
3433
3434         /* Check to make sure speech structure exists */
3435         if (!agi->speech) {
3436                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3437                 return RESULT_SUCCESS;
3438         }
3439
3440         ast_speech_change(agi->speech, argv[2], argv[3]);
3441         ast_agi_send(agi->fd, chan, "200 result=1\n");
3442
3443         return RESULT_SUCCESS;
3444 }
3445
3446 static int handle_speechdestroy(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3447 {
3448         if (agi->speech) {
3449                 ast_speech_destroy(agi->speech);
3450                 agi->speech = NULL;
3451                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3452         } else {
3453                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3454         }
3455
3456         return RESULT_SUCCESS;
3457 }
3458
3459 static int handle_speechloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3460 {
3461         if (argc != 5)
3462                 return RESULT_SHOWUSAGE;
3463
3464         if (!agi->speech) {
3465                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3466                 return RESULT_SUCCESS;
3467         }
3468
3469         if (ast_speech_grammar_load(agi->speech, argv[3], argv[4]))
3470                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3471         else
3472                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3473
3474         return RESULT_SUCCESS;
3475 }
3476
3477 static int handle_speechunloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3478 {
3479         if (argc != 4)
3480                 return RESULT_SHOWUSAGE;
3481
3482         if (!agi->speech) {
3483                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3484                 return RESULT_SUCCESS;
3485         }
3486
3487         if (ast_speech_grammar_unload(agi->speech, argv[3]))
3488                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3489         else
3490                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3491
3492         return RESULT_SUCCESS;
3493 }
3494
3495 static int handle_speechactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3496 {
3497         if (argc != 4)
3498                 return RESULT_SHOWUSAGE;
3499
3500         if (!agi->speech) {
3501                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3502                 return RESULT_SUCCESS;
3503         }
3504
3505         if (ast_speech_grammar_activate(agi->speech, argv[3]))
3506                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3507         else
3508                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3509
3510         return RESULT_SUCCESS;
3511 }
3512
3513 static int handle_speechdeactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3514 {
3515         if (argc != 4)
3516                 return RESULT_SHOWUSAGE;
3517
3518         if (!agi->speech) {
3519                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3520                 return RESULT_SUCCESS;
3521         }
3522
3523         if (ast_speech_grammar_deactivate(agi->speech, argv[3]))
3524                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3525         else
3526                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3527
3528         return RESULT_SUCCESS;
3529 }
3530
3531 static int speech_streamfile(struct ast_channel *chan, const char *filename, const char *preflang, int offset)
3532 {
3533         struct ast_filestream *fs = NULL;
3534
3535         if (!(fs = ast_openstream(chan, filename, preflang)))
3536                 return -1;
3537
3538         if (offset)
3539                 ast_seekstream(fs, offset, SEEK_SET);
3540
3541         if (ast_applystream(chan, fs))
3542                 return -1;
3543
3544         if (ast_playstream(fs))
3545                 return -1;
3546
3547         return 0;
3548 }
3549
3550 static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3551 {
3552         struct ast_speech *speech = agi->speech;
3553         const char *prompt;
3554         char dtmf = 0, tmp[4096] = "", *buf = tmp;
3555         int timeout = 0, offset = 0, res = 0, i = 0;
3556         long current_offset = 0;
3557         const char *reason = NULL;
3558         struct ast_frame *fr = NULL;
3559         struct ast_speech_result *result = NULL;
3560         size_t left = sizeof(tmp);
3561         time_t start = 0, current;
3562
3563         if (argc < 4)
3564                 return RESULT_SHOWUSAGE;
3565
3566         if (!speech) {
3567                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3568                 return RESULT_SUCCESS;
3569         }
3570
3571         prompt = argv[2];
3572         timeout = atoi(argv[3]);
3573
3574         /* If offset is specified then convert from text to integer */
3575         if (argc == 5)
3576                 offset = atoi(argv[4]);
3577
3578         /* We want frames coming in signed linear */
3579         if (ast_set_read_format(chan, ast_format_slin)) {
3580                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3581                 return RESULT_SUCCESS;
3582         }
3583
3584         /* Setup speech structure */
3585         if (speech->state == AST_SPEECH_STATE_NOT_READY || speech->state == AST_SPEECH_STATE_DONE) {
3586                 ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
3587                 ast_speech_start(speech);
3588         }
3589
3590         /* Start playing prompt */
3591         speech_streamfile(chan, prompt, ast_channel_language(chan), offset);
3592
3593         /* Go into loop reading in frames, passing to speech thingy, checking for hangup, all that jazz */
3594         while (ast_strlen_zero(reason)) {
3595                 /* Run scheduled items */
3596                 ast_sched_runq(ast_channel_sched(chan));
3597
3598                 /* See maximum time of waiting */
3599                 if ((res = ast_sched_wait(ast_channel_sched(chan))) < 0)
3600                         res = 1000;
3601
3602                 /* Wait for frame */
3603                 if (ast_waitfor(chan, res) > 0) {
3604                         if (!(fr = ast_read(chan))) {
3605                                 reason = "hangup";
3606                                 break;
3607                         }
3608                 }
3609
3610                 /* Perform timeout check */
3611                 if ((timeout > 0) && (start > 0)) {
3612                         time(&current);
3613                         if ((current - start) >= timeout) {
3614                                 reason = "timeout";
3615                                 if (fr)
3616                                         ast_frfree(fr);
3617                                 break;
3618                         }
3619                 }
3620
3621                 /* Check the speech structure for any changes */
3622                 ast_mutex_lock(&speech->lock);
3623
3624                 /* See if we need to quiet the audio stream playback */
3625                 if (ast_test_flag(speech, AST_SPEECH_QUIET) && ast_channel_stream(chan)) {
3626                         current_offset = ast_tellstream(ast_channel_stream(chan));
3627                         ast_stopstream(chan);
3628                         ast_clear_flag(speech, AST_SPEECH_QUIET);
3629                 }
3630
3631                 /* Check each state */
3632                 switch (speech->state) {
3633                 case AST_SPEECH_STATE_READY:
3634                         /* If the stream is done, start timeout calculation */
3635                         if ((timeout > 0) && start == 0 && ((!ast_channel_stream(chan)) || (ast_channel_streamid(chan) == -1 && ast_channel_timingfunc(chan) == NULL))) {
3636                                 ast_stopstream(chan);
3637                                 time(&start);
3638                         }
3639                         /* Write audio frame data into speech engine if possible */
3640                         if (fr && fr->frametype == AST_FRAME_VOICE)
3641                                 ast_speech_write(speech, fr->data.ptr, fr->datalen);
3642                         break;
3643                 case AST_SPEECH_STATE_WAIT:
3644                         /* Cue waiting sound if not already playing */
3645                         if ((!ast_channel_stream(chan)) || (ast_channel_streamid(chan) == -1 && ast_channel_timingfunc(chan) == NULL)) {
3646                                 ast_stopstream(chan);
3647                                 /* If a processing sound exists, or is not none - play it */
3648                                 if (!ast_strlen_zero(speech->processing_sound) && strcasecmp(speech->processing_sound, "none"))
3649                                         speech_streamfile(chan, speech->processing_sound, ast_channel_language(chan), 0);
3650                         }
3651                         break;
3652                 case AST_SPEECH_STATE_DONE:
3653                         /* Get the results */
3654                         speech->results = ast_speech_results_get(speech);
3655                         /* Change state to not ready */
3656                         ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
3657                         reason = "speech";
3658                         break;
3659                 default:
3660                         break;
3661                 }
3662                 ast_mutex_unlock(&speech->lock);
3663
3664                 /* Check frame for DTMF or hangup */
3665                 if (fr) {
3666                         if (fr->frametype == AST_FRAME_DTMF) {
3667                                 reason = "dtmf";
3668                                 dtmf = fr->subclass.integer;
3669                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_HANGUP) {
3670                                 reason = "hangup";
3671                         }
3672                         ast_frfree(fr);
3673                 }
3674         }
3675
3676         if (!strcasecmp(reason, "speech")) {
3677                 /* Build string containing speech results */
3678                 for (result = speech->results; result; result = AST_LIST_NEXT(result, list)) {
3679                         /* Build result string */
3680                         ast_build_string(&buf, &left, "%sscore%d=%d text%d=\"%s\" grammar%d=%s", (i > 0 ? " " : ""), i, result->score, i, result->text, i, result->grammar);
3681                         /* Increment result count */
3682                         i++;
3683                 }
3684                 /* Print out */
3685                 ast_agi_send(agi->fd, chan, "200 result=1 (speech) endpos=%ld results=%d %s\n", current_offset, i, tmp);
3686         } else if (!strcasecmp(reason, "dtmf")) {
3687                 ast_agi_send(agi->fd, chan, "200 result=1 (digit) digit=%c endpos=%ld\n", dtmf, current_offset);
3688         } else if (!strcasecmp(reason, "hangup") || !strcasecmp(reason, "timeout")) {
3689                 ast_agi_send(agi->fd, chan, "200 result=1 (%s) endpos=%ld\n", reason, current_offset);
3690         } else {
3691                 ast_agi_send(agi->fd, chan, "200 result=0 endpos=%ld\n", current_offset);
3692         }
3693
3694         return RESULT_SUCCESS;
3695 }
3696
3697 /*!
3698  * \brief AGI commands list
3699  */
3700 static struct agi_command commands[] = {
3701         { { "answer", NULL }, handle_answer, NULL, NULL, 0 },
3702         { { "asyncagi", "break", NULL }, handle_asyncagi_break, NULL, NULL, 1 },
3703         { { "channel", "status", NULL }, handle_channelstatus, NULL, NULL, 0 },
3704         { { "database", "del", NULL }, handle_dbdel, NULL, NULL, 1 },
3705         { { "database", "deltree", NULL }, handle_dbdeltree, NULL, NULL, 1 },
3706         { { "database", "get", NULL }, handle_dbget, NULL, NULL, 1 },
3707         { { "database", "put", NULL }, handle_dbput, NULL, NULL, 1 },
3708         { { "exec", NULL }, handle_exec, NULL, NULL, 1 },
3709         { { "get", "data", NULL }, handle_getdata, NULL, NULL, 0 },
3710         { { "get", "full", "variable", NULL }, handle_getvariablefull, NULL, NULL, 1 },
3711         { { "get", "option", NULL }, handle_getoption, NULL, NULL, 0 },
3712         { { "get", "variable", NULL }, handle_getvariable, NULL, NULL, 1 },
3713         { { "hangup", NULL }, handle_hangup, NULL, NULL, 0 },
3714         { { "noop", NULL }, handle_noop, NULL, NULL, 1 },
3715         { { "receive", "char", NULL }, handle_recvchar, NULL, NULL, 0 },
3716         { { "receive", "text", NULL }, handle_recvtext, NULL, NULL, 0 },
3717         { { "record", "file", NULL }, handle_recordfile, NULL, NULL, 0 },
3718         { { "say", "alpha", NULL }, handle_sayalpha, NULL, NULL, 0},
3719         { { "say", "digits", NULL }, handle_saydigits, NULL, NULL, 0 },
3720         { { "say", "number", NULL }, handle_saynumber, NULL, NULL, 0 },
3721         { { "say", "phonetic", NULL }, handle_sayphonetic, NULL, NULL, 0},
3722         { { "say", "date", NULL }, handle_saydate, NULL, NULL, 0},
3723         { { "say", "time", NULL }, handle_saytime, NULL, NULL, 0},
3724         { { "say", "datetime", NULL }, handle_saydatetime, NULL, NULL, 0},
3725         { { "send", "image", NULL }, handle_sendimage, NULL, NULL, 0},
3726         { { "send", "text", NULL }, handle_sendtext, NULL, NULL, 0},
3727         { { "set", "autohangup", NULL }, handle_autohangup, NULL, NULL, 0},
3728         { { "set", "callerid", NULL }, handle_setcallerid, NULL, NULL, 0},
3729         { { "set", "context", NULL }, handle_setcontext, NULL, NULL, 0},
3730         { { "set", "extension", NULL }, handle_setextension, NULL, NULL, 0},
3731         { { "set", "music", NULL }, handle_setmusic, NULL, NULL, 0 },
3732         { { "set", "priority", NULL }, handle_setpriority, NULL, NULL, 0 },
3733         { { "set", "variable", NULL }, handle_setvariable, NULL, NULL, 1 },
3734         { { "stream", "file", NULL }, handle_streamfile, NULL, NULL, 0 },
3735         { { "control", "stream", "file", NULL }, handle_controlstreamfile, NULL, NULL, 0 },
3736         { { "tdd", "mode", NULL }, handle_tddmode, NULL, NULL, 0 },
3737         { { "verbose", NULL }, handle_verbose, NULL, NULL, 1 },
3738         { { "wait", "for", "digit", NULL }, handle_waitfordigit, NULL, NULL, 0 },
3739         { { "speech", "create", NULL }, handle_speechcreate, NULL, NULL, 0 },
3740         { { "speech", "set", NULL }, handle_speechset, NULL, NULL, 0 },
3741         { { "speech", "destroy", NULL }, handle_speechdestroy, NULL, NULL, 1 },
3742         { { "speech", "load", "grammar", NULL }, handle_speechloadgrammar, NULL, NULL, 0 },
3743         { { "speech", "unload", "grammar", NULL }, handle_speechunloadgrammar, NULL, NULL, 1 },
3744         { { "speech", "activate", "grammar", NULL }, handle_speechactivategrammar, NULL, NULL, 0 },
3745         { { "speech", "deactivate", "grammar", NULL }, handle_speechdeactivategrammar, NULL, NULL, 0 },
3746         { { "speech", "recognize", NULL }, handle_speechrecognize, NULL, NULL, 0 },
3747 };
3748
3749 static AST_RWLIST_HEAD_STATIC(agi_commands, agi_command);
3750
3751 static char *help_workhorse(int fd, const char * const match[])
3752 {
3753         char fullcmd[MAX_CMD_LEN], matchstr[MAX_CMD_LEN];
3754         struct agi_command *e;
3755
3756         if (match)
3757                 ast_join(matchstr, sizeof(matchstr), match);
3758
3759         ast_cli(fd, "%5.5s %30.30s   %s\n","Dead","Command","Description");
3760         AST_RWLIST_RDLOCK(&agi_commands);
3761         AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
3762                 if (!e->cmda[0])
3763                         break;
3764                 /* Hide commands that start with '_' */
3765                 if ((e->cmda[0])[0] == '_')
3766                         continue;
3767                 ast_join(fullcmd, sizeof(fullcmd), e->cmda);
3768                 if (match && strncasecmp(matchstr, fullcmd, strlen(matchstr)))
3769                         continue;
3770                 ast_cli(fd, "%5.5s %30.30s   %s\n", e->dead ? "Yes" : "No" , fullcmd, S_OR(e->summary, "Not available"));
3771         }
3772         AST_RWLIST_UNLOCK(&agi_commands);
3773
3774         return CLI_SUCCESS;
3775 }
3776
3777 int AST_OPTIONAL_API_NAME(ast_agi_register)(struct ast_module *mod, agi_command *cmd)
3778 {
3779         char fullcmd[MAX_CMD_LEN];
3780
3781         ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
3782
3783         if (!find_command(cmd->cmda, 1)) {
3784                 *((enum ast_doc_src *) &cmd->docsrc) = AST_STATIC_DOC;
3785                 if (ast_strlen_zero(cmd->summary) && ast_strlen_zero(cmd->usage)) {
3786 #ifdef AST_XML_DOCS
3787                         *((char **) &cmd->summary) = ast_xmldoc_build_synopsis("agi", fullcmd, NULL);
3788                         *((char **) &cmd->usage) = ast_xmldoc_build_description("agi", fullcmd, NULL);
3789                         *((char **) &cmd->syntax) = ast_xmldoc_build_syntax("agi", fullcmd, NULL);
3790                         *((char **) &cmd->seealso) = ast_xmldoc_build_seealso("agi", fullcmd, NULL);
3791                         *((enum ast_doc_src *) &cmd->docsrc) = AST_XML_DOC;
3792 #endif
3793 #ifndef HAVE_NULLSAFE_PRINTF
3794                         if (!cmd->summary) {
3795                                 *((char **) &cmd->summary) = ast_strdup("");
3796                         }
3797                         if (!cmd->usage) {
3798                                 *((char **) &cmd->usage) = ast_strdup("");
3799                         }
3800                         if (!cmd->syntax) {
3801                                 *((char **) &cmd->syntax) = ast_strdup("");
3802                         }
3803                         if (!cmd->seealso) {
3804                                 *((char **) &cmd->seealso) = ast_strdup("");
3805                         }
3806 #endif
3807                 }
3808
3809                 cmd->mod = mod;
3810                 AST_RWLIST_WRLOCK(&agi_commands);
3811                 AST_LIST_INSERT_TAIL(&agi_commands, cmd, list);
3812                 AST_RWLIST_UNLOCK(&agi_commands);
3813                 ast_verb(2, "AGI Command '%s' registered\n",fullcmd);
3814                 return 1;
3815         } else {
3816                 ast_log(LOG_WARNING, "Command already registered!\n");
3817                 return 0;
3818         }
3819 }
3820
3821 int AST_OPTIONAL_API_NAME(ast_agi_unregister)(agi_command *cmd)
3822 {
3823         struct agi_command *e;
3824         int unregistered = 0;
3825         char fullcmd[MAX_CMD_LEN];
3826
3827         ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
3828
3829         AST_RWLIST_WRLOCK(&agi_commands);
3830         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&agi_commands, e, list) {
3831                 if (cmd == e) {
3832                         AST_RWLIST_REMOVE_CURRENT(list);
3833 #ifdef AST_XML_DOCS
3834                         if (e->docsrc == AST_XML_DOC) {
3835                                 ast_free((char *) e->summary);
3836                                 ast_free((char *) e->usage);
3837                                 ast_free((char *) e->syntax);
3838                                 ast_free((char *) e->seealso);
3839                                 *((char **) &e->summary) = NULL;
3840                                 *((char **) &e->usage) = NULL;
3841                                 *((char **) &e->syntax) = NULL;
3842                                 *((char **) &e->seealso) = NULL;
3843                         }
3844 #endif
3845                         unregistered=1;
3846                         break;
3847                 }
3848         }
3849         AST_RWLIST_TRAVERSE_SAFE_END;
3850         AST_RWLIST_UNLOCK(&agi_commands);
3851         if (unregistered) {
3852                 ast_verb(2, "AGI Command '%s' unregistered\n",fullcmd);
3853         }
3854         return unregistered;
3855 }
3856
3857 int AST_OPTIONAL_API_NAME(ast_agi_register_multiple)(struct ast_module *mod, struct agi_command *cmd, unsigned int len)
3858 {
3859         unsigned int i, x = 0;
3860
3861         for (i = 0; i < len; i++) {
3862                 if (ast_agi_register(mod, cmd + i) == 1) {
3863                         x++;
3864                         continue;
3865                 }
3866
3867                 /* registration failed, unregister everything
3868                    that had been registered up to that point
3869                 */
3870                 for (; x > 0; x--) {
3871                         /* we are intentionally ignoring the
3872                            result of ast_agi_unregister() here,
3873                            but it should be safe to do so since
3874                            we just registered these commands and
3875                            the only possible way for unregistration
3876