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