1fc0daaacc5e938cf15de65128a635cd9e45c9b7
[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, "Hu? datastore disappeared at Async AGI on Channel %s!\n", chan->name);
1007                 return NULL;
1008         }
1009         agi_commands = store->data;
1010         AST_LIST_LOCK(agi_commands);
1011         cmd = AST_LIST_REMOVE_HEAD(agi_commands, entry);
1012         AST_LIST_UNLOCK(agi_commands);
1013         return cmd;
1014 }
1015
1016 /* channel is locked when calling this one either from the CLI or manager thread */
1017 static int add_agi_cmd(struct ast_channel *chan, const char *cmd_buff, const char *cmd_id)
1018 {
1019         struct ast_datastore *store;
1020         struct agi_cmd *cmd;
1021         AST_LIST_HEAD(, agi_cmd) *agi_commands;
1022
1023         store = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
1024         if (!store) {
1025                 ast_log(LOG_WARNING, "Channel %s is not at Async AGI.\n", chan->name);
1026                 return -1;
1027         }
1028         agi_commands = store->data;
1029         cmd = ast_calloc(1, sizeof(*cmd));
1030         if (!cmd) {
1031                 return -1;
1032         }
1033         cmd->cmd_buffer = ast_strdup(cmd_buff);
1034         if (!cmd->cmd_buffer) {
1035                 ast_free(cmd);
1036                 return -1;
1037         }
1038         cmd->cmd_id = ast_strdup(cmd_id);
1039         if (!cmd->cmd_id) {
1040                 ast_free(cmd->cmd_buffer);
1041                 ast_free(cmd);
1042                 return -1;
1043         }
1044         AST_LIST_LOCK(agi_commands);
1045         AST_LIST_INSERT_TAIL(agi_commands, cmd, entry);
1046         AST_LIST_UNLOCK(agi_commands);
1047         return 0;
1048 }
1049
1050 static int add_to_agi(struct ast_channel *chan)
1051 {
1052         struct ast_datastore *datastore;
1053         AST_LIST_HEAD(, agi_cmd) *agi_cmds_list;
1054
1055         /* check if already on AGI */
1056         ast_channel_lock(chan);
1057         datastore = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
1058         ast_channel_unlock(chan);
1059         if (datastore) {
1060                 /* we already have an AGI datastore, let's just
1061                    return success */
1062                 return 0;
1063         }
1064
1065         /* the channel has never been on Async AGI,
1066            let's allocate it's datastore */
1067         datastore = ast_datastore_alloc(&agi_commands_datastore_info, "AGI");
1068         if (!datastore) {
1069                 return -1;
1070         }
1071         agi_cmds_list = ast_calloc(1, sizeof(*agi_cmds_list));
1072         if (!agi_cmds_list) {
1073                 ast_log(LOG_ERROR, "Unable to allocate Async AGI commands list.\n");
1074                 ast_datastore_free(datastore);
1075                 return -1;
1076         }
1077         datastore->data = agi_cmds_list;
1078         AST_LIST_HEAD_INIT(agi_cmds_list);
1079         ast_channel_lock(chan);
1080         ast_channel_datastore_add(chan, datastore);
1081         ast_channel_unlock(chan);
1082         return 0;
1083 }
1084
1085 /*!
1086  * \brief CLI command to add applications to execute in Async AGI
1087  * \param e
1088  * \param cmd
1089  * \param a
1090  *
1091  * \retval CLI_SUCCESS on success
1092  * \retval NULL when init or tab completion is used
1093 */
1094 static char *handle_cli_agi_add_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1095 {
1096         struct ast_channel *chan;
1097         switch (cmd) {
1098         case CLI_INIT:
1099                 e->command = "agi exec";
1100                 e->usage = "Usage: agi exec <channel name> <app and arguments> [id]\n"
1101                            "       Add AGI command to the execute queue of the specified channel in Async AGI\n";
1102                 return NULL;
1103         case CLI_GENERATE:
1104                 if (a->pos == 2)
1105                         return ast_complete_channels(a->line, a->word, a->pos, a->n, 2);
1106                 return NULL;
1107         }
1108
1109         if (a->argc < 4) {
1110                 return CLI_SHOWUSAGE;
1111         }
1112
1113         if (!(chan = ast_channel_get_by_name(a->argv[2]))) {
1114                 ast_log(LOG_WARNING, "Channel %s does not exists or cannot lock it\n", a->argv[2]);
1115                 return CLI_FAILURE;
1116         }
1117
1118         ast_channel_lock(chan);
1119
1120         if (add_agi_cmd(chan, a->argv[3], (a->argc > 4 ? a->argv[4] : ""))) {
1121                 ast_log(LOG_WARNING, "failed to add AGI command to queue of channel %s\n", chan->name);
1122                 ast_channel_unlock(chan);
1123                 chan = ast_channel_unref(chan);
1124                 return CLI_FAILURE;
1125         }
1126
1127         ast_debug(1, "Added AGI command to channel %s queue\n", chan->name);
1128
1129         ast_channel_unlock(chan);
1130         chan = ast_channel_unref(chan);
1131
1132         return CLI_SUCCESS;
1133 }
1134
1135 /*!
1136  * \brief Add a new command to execute by the Async AGI application
1137  * \param s
1138  * \param m
1139  *
1140  * It will append the application to the specified channel's queue
1141  * if the channel is not inside Async AGI application it will return an error
1142  * \retval 0 on success or incorrect use
1143  * \retval 1 on failure to add the command ( most likely because the channel
1144  * is not in Async AGI loop )
1145 */
1146 static int action_add_agi_cmd(struct mansession *s, const struct message *m)
1147 {
1148         const char *channel = astman_get_header(m, "Channel");
1149         const char *cmdbuff = astman_get_header(m, "Command");
1150         const char *cmdid   = astman_get_header(m, "CommandID");
1151         struct ast_channel *chan;
1152         char buf[256];
1153
1154         if (ast_strlen_zero(channel) || ast_strlen_zero(cmdbuff)) {
1155                 astman_send_error(s, m, "Both, Channel and Command are *required*");
1156                 return 0;
1157         }
1158
1159         if (!(chan = ast_channel_get_by_name(channel))) {
1160                 snprintf(buf, sizeof(buf), "Channel %s does not exists or cannot get its lock", channel);
1161                 astman_send_error(s, m, buf);
1162                 return 0;
1163         }
1164
1165         ast_channel_lock(chan);
1166
1167         if (add_agi_cmd(chan, cmdbuff, cmdid)) {
1168                 snprintf(buf, sizeof(buf), "Failed to add AGI command to channel %s queue", chan->name);
1169                 astman_send_error(s, m, buf);
1170                 ast_channel_unlock(chan);
1171                 chan = ast_channel_unref(chan);
1172                 return 0;
1173         }
1174
1175         ast_channel_unlock(chan);
1176         chan = ast_channel_unref(chan);
1177
1178         astman_send_ack(s, m, "Added AGI command to queue");
1179
1180         return 0;
1181 }
1182
1183 static enum agi_result agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int dead);
1184 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced, int argc, char *argv[]);
1185 static enum agi_result launch_asyncagi(struct ast_channel *chan, char *argv[], int *efd)
1186 {
1187 /* This buffer sizes might cause truncation if the AGI command writes more data
1188    than AGI_BUF_SIZE as result. But let's be serious, is there an AGI command
1189    that writes a response larger than 1024 bytes?, I don't think so, most of
1190    them are just result=blah stuff. However probably if GET VARIABLE is called
1191    and the variable has large amount of data, that could be a problem. We could
1192    make this buffers dynamic, but let's leave that as a second step.
1193
1194    AMI_BUF_SIZE is twice AGI_BUF_SIZE just for the sake of choosing a safe
1195    number. Some characters of AGI buf will be url encoded to be sent to manager
1196    clients.  An URL encoded character will take 3 bytes, but again, to cause
1197    truncation more than about 70% of the AGI buffer should be URL encoded for
1198    that to happen.  Not likely at all.
1199
1200    On the other hand. I wonder if read() could eventually return less data than
1201    the amount already available in the pipe? If so, how to deal with that?
1202    So far, my tests on Linux have not had any problems.
1203  */
1204 #define AGI_BUF_SIZE 1024
1205 #define AMI_BUF_SIZE 2048
1206         struct ast_frame *f;
1207         struct agi_cmd *cmd;
1208         int res, fds[2];
1209         int timeout = 100;
1210         char agi_buffer[AGI_BUF_SIZE + 1];
1211         char ami_buffer[AMI_BUF_SIZE];
1212         enum agi_result returnstatus = AGI_RESULT_SUCCESS_ASYNC;
1213         AGI async_agi;
1214
1215         if (efd) {
1216                 ast_log(LOG_WARNING, "Async AGI does not support Enhanced AGI yet\n");
1217                 return AGI_RESULT_FAILURE;
1218         }
1219
1220         /* add AsyncAGI datastore to the channel */
1221         if (add_to_agi(chan)) {
1222                 ast_log(LOG_ERROR, "failed to start Async AGI on channel %s\n", chan->name);
1223                 return AGI_RESULT_FAILURE;
1224         }
1225
1226         /* Flush any stale commands. */
1227         while ((cmd = get_agi_cmd(chan))) {
1228                 free_agi_cmd(cmd);
1229         }
1230
1231         /* this pipe allows us to create a "fake" AGI struct to use
1232            the AGI commands */
1233         res = pipe(fds);
1234         if (res) {
1235                 ast_log(LOG_ERROR, "failed to create Async AGI pipe\n");
1236                 /* intentionally do not remove datastore, added with
1237                    add_to_agi(), from channel. It will be removed when
1238                    the channel is hung up anyways */
1239                 return AGI_RESULT_FAILURE;
1240         }
1241
1242         /* handlers will get the pipe write fd and we read the AGI responses
1243            from the pipe read fd */
1244         async_agi.fd = fds[1];
1245         async_agi.ctrl = fds[1];
1246         async_agi.audio = -1; /* no audio support */
1247         async_agi.fast = 0;
1248         async_agi.speech = NULL;
1249
1250         /* notify possible manager users of a new channel ready to
1251            receive commands */
1252         setup_env(chan, "async", fds[1], 0, 0, NULL);
1253         /* read the environment */
1254         res = read(fds[0], agi_buffer, AGI_BUF_SIZE);
1255         if (!res) {
1256                 ast_log(LOG_ERROR, "failed to read from Async AGI pipe on channel %s\n", chan->name);
1257                 returnstatus = AGI_RESULT_FAILURE;
1258                 goto quit;
1259         }
1260         agi_buffer[res] = '\0';
1261         /* encode it and send it thru the manager so whoever is going to take
1262            care of AGI commands on this channel can decide which AGI commands
1263            to execute based on the setup info */
1264         ast_uri_encode(agi_buffer, ami_buffer, AMI_BUF_SIZE, ast_uri_http);
1265         manager_event(EVENT_FLAG_AGI, "AsyncAGI", "SubEvent: Start\r\nChannel: %s\r\nEnv: %s\r\n", chan->name, ami_buffer);
1266         while (1) {
1267                 /* bail out if we need to hangup */
1268                 if (ast_check_hangup(chan)) {
1269                         ast_debug(1, "ast_check_hangup returned true on chan %s\n", chan->name);
1270                         break;
1271                 }
1272                 /* retrieve a command
1273                    (commands are added via the manager or the cli threads) */
1274                 cmd = get_agi_cmd(chan);
1275                 if (cmd) {
1276                         /* OK, we have a command, let's call the
1277                            command handler. */
1278                         res = agi_handle_command(chan, &async_agi, cmd->cmd_buffer, 0);
1279                         if (res < 0) {
1280                                 free_agi_cmd(cmd);
1281                                 break;
1282                         }
1283                         /* the command handler must have written to our fake
1284                            AGI struct fd (the pipe), let's read the response */
1285                         res = read(fds[0], agi_buffer, AGI_BUF_SIZE);
1286                         if (!res) {
1287                                 returnstatus = AGI_RESULT_FAILURE;
1288                                 ast_log(LOG_ERROR, "failed to read from AsyncAGI pipe on channel %s\n", chan->name);
1289                                 free_agi_cmd(cmd);
1290                                 break;
1291                         }
1292                         /* we have a response, let's send the response thru the
1293                            manager. Include the CommandID if it was specified
1294                            when the command was added */
1295                         agi_buffer[res] = '\0';
1296                         ast_uri_encode(agi_buffer, ami_buffer, AMI_BUF_SIZE, ast_uri_http);
1297                         if (ast_strlen_zero(cmd->cmd_id))
1298                                 manager_event(EVENT_FLAG_AGI, "AsyncAGI", "SubEvent: Exec\r\nChannel: %s\r\nResult: %s\r\n", chan->name, ami_buffer);
1299                         else
1300                                 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);
1301                         free_agi_cmd(cmd);
1302                 } else {
1303                         /* no command so far, wait a bit for a frame to read */
1304                         res = ast_waitfor(chan, timeout);
1305                         if (res < 0) {
1306                                 ast_debug(1, "ast_waitfor returned <= 0 on chan %s\n", chan->name);
1307                                 break;
1308                         }
1309                         if (res == 0)
1310                                 continue;
1311                         f = ast_read(chan);
1312                         if (!f) {
1313                                 ast_debug(1, "No frame read on channel %s, going out ...\n", chan->name);
1314                                 returnstatus = AGI_RESULT_HANGUP;
1315                                 break;
1316                         }
1317                         /* is there any other frame we should care about
1318                            besides AST_CONTROL_HANGUP? */
1319                         if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
1320                                 ast_debug(1, "Got HANGUP frame on channel %s, going out ...\n", chan->name);
1321                                 ast_frfree(f);
1322                                 break;
1323                         }
1324                         ast_frfree(f);
1325                 }
1326         }
1327
1328         if (async_agi.speech) {
1329                 ast_speech_destroy(async_agi.speech);
1330         }
1331 quit:
1332         /* notify manager users this channel cannot be
1333            controlled anymore by Async AGI */
1334         manager_event(EVENT_FLAG_AGI, "AsyncAGI", "SubEvent: End\r\nChannel: %s\r\n", chan->name);
1335
1336         /* close the pipe */
1337         close(fds[0]);
1338         close(fds[1]);
1339
1340         /* intentionally don't get rid of the datastore. So commands can be
1341            still in the queue in case AsyncAGI gets called again.
1342            Datastore destructor will be called on channel destroy anyway  */
1343
1344         return returnstatus;
1345
1346 #undef AGI_BUF_SIZE
1347 #undef AMI_BUF_SIZE
1348 }
1349
1350 /* launch_netscript: The fastagi handler.
1351         FastAGI defaults to port 4573 */
1352 static enum agi_result launch_netscript(char *agiurl, char *argv[], int *fds)
1353 {
1354         int s, flags, res, port = AGI_PORT;
1355         struct pollfd pfds[1];
1356         char *host, *c, *script;
1357         struct sockaddr_in addr_in;
1358         struct hostent *hp;
1359         struct ast_hostent ahp;
1360
1361         /* agiurl is "agi://host.domain[:port][/script/name]" */
1362         host = ast_strdupa(agiurl + 6); /* Remove agi:// */
1363         /* Strip off any script name */
1364         if ((script = strchr(host, '/'))) {
1365                 *script++ = '\0';
1366         } else {
1367                 script = "";
1368         }
1369
1370         if ((c = strchr(host, ':'))) {
1371                 *c++ = '\0';
1372                 port = atoi(c);
1373         }
1374         if (!(hp = ast_gethostbyname(host, &ahp))) {
1375                 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", host);
1376                 return -1;
1377         }
1378         if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1379                 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1380                 return -1;
1381         }
1382         if ((flags = fcntl(s, F_GETFL)) < 0) {
1383                 ast_log(LOG_WARNING, "Fcntl(F_GETFL) failed: %s\n", strerror(errno));
1384                 close(s);
1385                 return -1;
1386         }
1387         if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0) {
1388                 ast_log(LOG_WARNING, "Fnctl(F_SETFL) failed: %s\n", strerror(errno));
1389                 close(s);
1390                 return -1;
1391         }
1392         memset(&addr_in, 0, sizeof(addr_in));
1393         addr_in.sin_family = AF_INET;
1394         addr_in.sin_port = htons(port);
1395         memcpy(&addr_in.sin_addr, hp->h_addr, sizeof(addr_in.sin_addr));
1396         if (connect(s, (struct sockaddr *)&addr_in, sizeof(addr_in)) && (errno != EINPROGRESS)) {
1397                 ast_log(LOG_WARNING, "Connect failed with unexpected error: %s\n", strerror(errno));
1398                 close(s);
1399                 return AGI_RESULT_FAILURE;
1400         }
1401
1402         pfds[0].fd = s;
1403         pfds[0].events = POLLOUT;
1404         while ((res = ast_poll(pfds, 1, MAX_AGI_CONNECT)) != 1) {
1405                 if (errno != EINTR) {
1406                         if (!res) {
1407                                 ast_log(LOG_WARNING, "FastAGI connection to '%s' timed out after MAX_AGI_CONNECT (%d) milliseconds.\n",
1408                                         agiurl, MAX_AGI_CONNECT);
1409                         } else
1410                                 ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
1411                         close(s);
1412                         return AGI_RESULT_FAILURE;
1413                 }
1414         }
1415
1416         if (ast_agi_send(s, NULL, "agi_network: yes\n") < 0) {
1417                 if (errno != EINTR) {
1418                         ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
1419                         close(s);
1420                         return AGI_RESULT_FAILURE;
1421                 }
1422         }
1423
1424         /* If we have a script parameter, relay it to the fastagi server */
1425         /* Script parameters take the form of: AGI(agi://my.example.com/?extension=${EXTEN}) */
1426         if (!ast_strlen_zero(script))
1427                 ast_agi_send(s, NULL, "agi_network_script: %s\n", script);
1428
1429         ast_debug(4, "Wow, connected!\n");
1430         fds[0] = s;
1431         fds[1] = s;
1432         return AGI_RESULT_SUCCESS_FAST;
1433 }
1434
1435 /*!
1436  * \internal
1437  * \brief The HA fastagi handler.
1438  * \param agiurl The request URL as passed to Agi() in the dial plan
1439  * \param argv The parameters after the URL passed to Agi() in the dial plan
1440  * \param fds Input/output file descriptors
1441  *
1442  * Uses SRV lookups to try to connect to a list of FastAGI servers. The hostname in
1443  * the URI is prefixed with _agi._tcp. prior to the DNS resolution. For
1444  * example, if you specify the URI \a hagi://agi.example.com/foo.agi the DNS
1445  * query would be for \a _agi._tcp.agi.example.com and you'll need to make sure
1446  * this resolves.
1447  *
1448  * This function parses the URI, resolves the SRV service name, forms new URIs
1449  * with the results of the DNS lookup, and then calls launch_netscript on the
1450  * new URIs until one succeeds.
1451  *
1452  * \return the result of the AGI operation.
1453  */
1454 static enum agi_result launch_ha_netscript(char *agiurl, char *argv[], int *fds)
1455 {
1456         char *host, *script;
1457         enum agi_result result = AGI_RESULT_FAILURE;
1458         struct srv_context *context = NULL;
1459         int srv_ret;
1460         char service[256];
1461         char resolved_uri[1024];
1462         const char *srvhost;
1463         unsigned short srvport;
1464
1465         /* format of agiurl is "hagi://host.domain[:port][/script/name]" */
1466         if (!(host = ast_strdupa(agiurl + 7))) { /* Remove hagi:// */
1467                 ast_log(LOG_WARNING, "An error occurred parsing the AGI URI: %s", agiurl);
1468                 return AGI_RESULT_FAILURE;
1469         }
1470
1471         /* Strip off any script name */
1472         if ((script = strchr(host, '/'))) {
1473                 *script++ = '\0';
1474         } else {
1475                 script = "";
1476         }
1477
1478         if (strchr(host, ':')) {
1479                 ast_log(LOG_WARNING, "Specifying a port number disables SRV lookups: %s\n", agiurl);
1480                 return launch_netscript(agiurl + 1, argv, fds); /* +1 to strip off leading h from hagi:// */
1481         }
1482
1483         snprintf(service, sizeof(service), "%s%s", SRV_PREFIX, host);
1484
1485         while (!(srv_ret = ast_srv_lookup(&context, service, &srvhost, &srvport))) {
1486                 snprintf(resolved_uri, sizeof(resolved_uri), "agi://%s:%d/%s", srvhost, srvport, script);
1487                 result = launch_netscript(resolved_uri, argv, fds);
1488                 if (result == AGI_RESULT_FAILURE || result == AGI_RESULT_NOTFOUND) {
1489                         ast_log(LOG_WARNING, "AGI request failed for host '%s' (%s:%d)\n", host, srvhost, srvport);
1490                 } else {
1491                         break;
1492                 }
1493         }
1494         if (srv_ret < 0) {
1495                 ast_log(LOG_WARNING, "SRV lookup failed for %s\n", agiurl);
1496         } else {
1497         ast_srv_cleanup(&context);
1498     }
1499
1500         return result;
1501 }
1502
1503 static enum agi_result launch_script(struct ast_channel *chan, char *script, char *argv[], int *fds, int *efd, int *opid)
1504 {
1505         char tmp[256];
1506         int pid, toast[2], fromast[2], audio[2], res;
1507         struct stat st;
1508
1509         if (!strncasecmp(script, "agi://", 6)) {
1510                 return (efd == NULL) ? launch_netscript(script, argv, fds) : AGI_RESULT_FAILURE;
1511         }
1512         if (!strncasecmp(script, "hagi://", 7)) {
1513                 return (efd == NULL) ? launch_ha_netscript(script, argv, fds) : AGI_RESULT_FAILURE;
1514         }
1515         if (!strncasecmp(script, "agi:async", sizeof("agi:async") - 1)) {
1516                 return launch_asyncagi(chan, argv, efd);
1517         }
1518
1519         if (script[0] != '/') {
1520                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_AGI_DIR, script);
1521                 script = tmp;
1522         }
1523
1524         /* Before even trying let's see if the file actually exists */
1525         if (stat(script, &st)) {
1526                 ast_log(LOG_WARNING, "Failed to execute '%s': File does not exist.\n", script);
1527                 return AGI_RESULT_NOTFOUND;
1528         }
1529
1530         if (pipe(toast)) {
1531                 ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
1532                 return AGI_RESULT_FAILURE;
1533         }
1534         if (pipe(fromast)) {
1535                 ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
1536                 close(toast[0]);
1537                 close(toast[1]);
1538                 return AGI_RESULT_FAILURE;
1539         }
1540         if (efd) {
1541                 if (pipe(audio)) {
1542                         ast_log(LOG_WARNING, "unable to create audio pipe: %s\n", strerror(errno));
1543                         close(fromast[0]);
1544                         close(fromast[1]);
1545                         close(toast[0]);
1546                         close(toast[1]);
1547                         return AGI_RESULT_FAILURE;
1548                 }
1549                 res = fcntl(audio[1], F_GETFL);
1550                 if (res > -1)
1551                         res = fcntl(audio[1], F_SETFL, res | O_NONBLOCK);
1552                 if (res < 0) {
1553                         ast_log(LOG_WARNING, "unable to set audio pipe parameters: %s\n", strerror(errno));
1554                         close(fromast[0]);
1555                         close(fromast[1]);
1556                         close(toast[0]);
1557                         close(toast[1]);
1558                         close(audio[0]);
1559                         close(audio[1]);
1560                         return AGI_RESULT_FAILURE;
1561                 }
1562         }
1563
1564         if ((pid = ast_safe_fork(1)) < 0) {
1565                 ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
1566                 return AGI_RESULT_FAILURE;
1567         }
1568         if (!pid) {
1569                 /* Pass paths to AGI via environmental variables */
1570                 setenv("AST_CONFIG_DIR", ast_config_AST_CONFIG_DIR, 1);
1571                 setenv("AST_CONFIG_FILE", ast_config_AST_CONFIG_FILE, 1);
1572                 setenv("AST_MODULE_DIR", ast_config_AST_MODULE_DIR, 1);
1573                 setenv("AST_SPOOL_DIR", ast_config_AST_SPOOL_DIR, 1);
1574                 setenv("AST_MONITOR_DIR", ast_config_AST_MONITOR_DIR, 1);
1575                 setenv("AST_VAR_DIR", ast_config_AST_VAR_DIR, 1);
1576                 setenv("AST_DATA_DIR", ast_config_AST_DATA_DIR, 1);
1577                 setenv("AST_LOG_DIR", ast_config_AST_LOG_DIR, 1);
1578                 setenv("AST_AGI_DIR", ast_config_AST_AGI_DIR, 1);
1579                 setenv("AST_KEY_DIR", ast_config_AST_KEY_DIR, 1);
1580                 setenv("AST_RUN_DIR", ast_config_AST_RUN_DIR, 1);
1581
1582                 /* Don't run AGI scripts with realtime priority -- it causes audio stutter */
1583                 ast_set_priority(0);
1584
1585                 /* Redirect stdin and out, provide enhanced audio channel if desired */
1586                 dup2(fromast[0], STDIN_FILENO);
1587                 dup2(toast[1], STDOUT_FILENO);
1588                 if (efd)
1589                         dup2(audio[0], STDERR_FILENO + 1);
1590                 else
1591                         close(STDERR_FILENO + 1);
1592
1593                 /* Close everything but stdin/out/error */
1594                 ast_close_fds_above_n(STDERR_FILENO + 1);
1595
1596                 /* Execute script */
1597                 /* XXX argv should be deprecated in favor of passing agi_argX paramaters */
1598                 execv(script, argv);
1599                 /* Can't use ast_log since FD's are closed */
1600                 ast_child_verbose(1, "Failed to execute '%s': %s", script, strerror(errno));
1601                 /* Special case to set status of AGI to failure */
1602                 fprintf(stdout, "failure\n");
1603                 fflush(stdout);
1604                 _exit(1);
1605         }
1606         ast_verb(3, "Launched AGI Script %s\n", script);
1607         fds[0] = toast[0];
1608         fds[1] = fromast[1];
1609         if (efd)
1610                 *efd = audio[1];
1611         /* close what we're not using in the parent */
1612         close(toast[1]);
1613         close(fromast[0]);
1614
1615         if (efd)
1616                 close(audio[0]);
1617
1618         *opid = pid;
1619         return AGI_RESULT_SUCCESS;
1620 }
1621
1622 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced, int argc, char *argv[])
1623 {
1624         int count;
1625
1626         /* Print initial environment, with agi_request always being the first
1627            thing */
1628         ast_agi_send(fd, chan, "agi_request: %s\n", request);
1629         ast_agi_send(fd, chan, "agi_channel: %s\n", chan->name);
1630         ast_agi_send(fd, chan, "agi_language: %s\n", chan->language);
1631         ast_agi_send(fd, chan, "agi_type: %s\n", chan->tech->type);
1632         ast_agi_send(fd, chan, "agi_uniqueid: %s\n", chan->uniqueid);
1633         ast_agi_send(fd, chan, "agi_version: %s\n", ast_get_version());
1634
1635         /* ANI/DNIS */
1636         ast_agi_send(fd, chan, "agi_callerid: %s\n",
1637                 S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "unknown"));
1638         ast_agi_send(fd, chan, "agi_calleridname: %s\n",
1639                 S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, "unknown"));
1640         ast_agi_send(fd, chan, "agi_callingpres: %d\n",
1641                 ast_party_id_presentation(&chan->caller.id));
1642         ast_agi_send(fd, chan, "agi_callingani2: %d\n", chan->caller.ani2);
1643         ast_agi_send(fd, chan, "agi_callington: %d\n", chan->caller.id.number.plan);
1644         ast_agi_send(fd, chan, "agi_callingtns: %d\n", chan->dialed.transit_network_select);
1645         ast_agi_send(fd, chan, "agi_dnid: %s\n", S_OR(chan->dialed.number.str, "unknown"));
1646         ast_agi_send(fd, chan, "agi_rdnis: %s\n",
1647                 S_COR(chan->redirecting.from.number.valid, chan->redirecting.from.number.str, "unknown"));
1648
1649         /* Context information */
1650         ast_agi_send(fd, chan, "agi_context: %s\n", chan->context);
1651         ast_agi_send(fd, chan, "agi_extension: %s\n", chan->exten);
1652         ast_agi_send(fd, chan, "agi_priority: %d\n", chan->priority);
1653         ast_agi_send(fd, chan, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
1654
1655         /* User information */
1656         ast_agi_send(fd, chan, "agi_accountcode: %s\n", chan->accountcode ? chan->accountcode : "");
1657         ast_agi_send(fd, chan, "agi_threadid: %ld\n", (long)pthread_self());
1658
1659         /* Send any parameters to the fastagi server that have been passed via the agi application */
1660         /* Agi application paramaters take the form of: AGI(/path/to/example/script|${EXTEN}) */
1661         for(count = 1; count < argc; count++)
1662                 ast_agi_send(fd, chan, "agi_arg_%d: %s\n", count, argv[count]);
1663
1664         /* End with empty return */
1665         ast_agi_send(fd, chan, "\n");
1666 }
1667
1668 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1669 {
1670         int res = 0;
1671
1672         /* Answer the channel */
1673         if (chan->_state != AST_STATE_UP)
1674                 res = ast_answer(chan);
1675
1676         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1677         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1678 }
1679
1680 static int handle_asyncagi_break(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1681 {
1682         ast_agi_send(agi->fd, chan, "200 result=0\n");
1683         return RESULT_FAILURE;
1684 }
1685
1686 static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1687 {
1688         int res, to;
1689
1690         if (argc != 4)
1691                 return RESULT_SHOWUSAGE;
1692         if (sscanf(argv[3], "%30d", &to) != 1)
1693                 return RESULT_SHOWUSAGE;
1694         res = ast_waitfordigit_full(chan, to, agi->audio, agi->ctrl);
1695         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1696         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1697 }
1698
1699 static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1700 {
1701         int res;
1702
1703         if (argc != 3)
1704                 return RESULT_SHOWUSAGE;
1705
1706         /* At the moment, the parser (perhaps broken) returns with
1707            the last argument PLUS the newline at the end of the input
1708            buffer. This probably needs to be fixed, but I wont do that
1709            because other stuff may break as a result. The right way
1710            would probably be to strip off the trailing newline before
1711            parsing, then here, add a newline at the end of the string
1712            before sending it to ast_sendtext --DUDE */
1713         res = ast_sendtext(chan, argv[2]);
1714         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1715         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1716 }
1717
1718 static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1719 {
1720         int res;
1721
1722         if (argc != 3)
1723                 return RESULT_SHOWUSAGE;
1724
1725         res = ast_recvchar(chan,atoi(argv[2]));
1726         if (res == 0) {
1727                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout)\n", res);
1728                 return RESULT_SUCCESS;
1729         }
1730         if (res > 0) {
1731                 ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1732                 return RESULT_SUCCESS;
1733         }
1734         ast_agi_send(agi->fd, chan, "200 result=%d (hangup)\n", res);
1735         return RESULT_FAILURE;
1736 }
1737
1738 static int handle_recvtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1739 {
1740         char *buf;
1741
1742         if (argc != 3)
1743                 return RESULT_SHOWUSAGE;
1744
1745         buf = ast_recvtext(chan, atoi(argv[2]));
1746         if (buf) {
1747                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", buf);
1748                 ast_free(buf);
1749         } else {
1750                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
1751         }
1752         return RESULT_SUCCESS;
1753 }
1754
1755 static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1756 {
1757         int res, x;
1758
1759         if (argc != 3)
1760                 return RESULT_SHOWUSAGE;
1761
1762         if (!strncasecmp(argv[2],"on",2)) {
1763                 x = 1;
1764         } else  {
1765                 x = 0;
1766         }
1767         if (!strncasecmp(argv[2],"mate",4))  {
1768                 x = 2;
1769         }
1770         if (!strncasecmp(argv[2],"tdd",3)) {
1771                 x = 1;
1772         }
1773         res = ast_channel_setoption(chan, AST_OPTION_TDD, &x, sizeof(char), 0);
1774         if (res != RESULT_SUCCESS) {
1775                 ast_agi_send(agi->fd, chan, "200 result=0\n");
1776         } else {
1777                 ast_agi_send(agi->fd, chan, "200 result=1\n");
1778         }
1779         return RESULT_SUCCESS;
1780 }
1781
1782 static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1783 {
1784         int res;
1785
1786         if (argc != 3) {
1787                 return RESULT_SHOWUSAGE;
1788         }
1789
1790         res = ast_send_image(chan, argv[2]);
1791         if (!ast_check_hangup(chan)) {
1792                 res = 0;
1793         }
1794         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1795         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1796 }
1797
1798 static int handle_controlstreamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1799 {
1800         int res = 0, skipms = 3000;
1801         const char *fwd = "#", *rev = "*", *suspend = NULL, *stop = NULL;       /* Default values */
1802
1803         if (argc < 5 || argc > 9) {
1804                 return RESULT_SHOWUSAGE;
1805         }
1806
1807         if (!ast_strlen_zero(argv[4])) {
1808                 stop = argv[4];
1809         }
1810
1811         if ((argc > 5) && (sscanf(argv[5], "%30d", &skipms) != 1)) {
1812                 return RESULT_SHOWUSAGE;
1813         }
1814
1815         if (argc > 6 && !ast_strlen_zero(argv[6])) {
1816                 fwd = argv[6];
1817         }
1818
1819         if (argc > 7 && !ast_strlen_zero(argv[7])) {
1820                 rev = argv[7];
1821         }
1822
1823         if (argc > 8 && !ast_strlen_zero(argv[8])) {
1824                 suspend = argv[8];
1825         }
1826
1827         res = ast_control_streamfile(chan, argv[3], fwd, rev, stop, suspend, NULL, skipms, NULL);
1828
1829         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1830
1831         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1832 }
1833
1834 static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1835 {
1836         int res, vres;
1837         struct ast_filestream *fs, *vfs;
1838         long sample_offset = 0, max_length;
1839         const char *edigits = "";
1840
1841         if (argc < 4 || argc > 5)
1842                 return RESULT_SHOWUSAGE;
1843
1844         if (argv[3])
1845                 edigits = argv[3];
1846
1847         if ((argc > 4) && (sscanf(argv[4], "%30ld", &sample_offset) != 1))
1848                 return RESULT_SHOWUSAGE;
1849
1850         if (!(fs = ast_openstream(chan, argv[2], chan->language))) {
1851                 ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", 0, sample_offset);
1852                 return RESULT_SUCCESS;
1853         }
1854
1855         if ((vfs = ast_openvstream(chan, argv[2], chan->language)))
1856                 ast_debug(1, "Ooh, found a video stream, too\n");
1857
1858         ast_verb(3, "Playing '%s' (escape_digits=%s) (sample_offset %ld)\n", argv[2], edigits, sample_offset);
1859
1860         ast_seekstream(fs, 0, SEEK_END);
1861         max_length = ast_tellstream(fs);
1862         ast_seekstream(fs, sample_offset, SEEK_SET);
1863         res = ast_applystream(chan, fs);
1864         if (vfs)
1865                 vres = ast_applystream(chan, vfs);
1866         ast_playstream(fs);
1867         if (vfs)
1868                 ast_playstream(vfs);
1869
1870         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
1871         /* this is to check for if ast_waitstream closed the stream, we probably are at
1872          * the end of the stream, return that amount, else check for the amount */
1873         sample_offset = (chan->stream) ? ast_tellstream(fs) : max_length;
1874         ast_stopstream(chan);
1875         if (res == 1) {
1876                 /* Stop this command, don't print a result line, as there is a new command */
1877                 return RESULT_SUCCESS;
1878         }
1879         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
1880         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1881 }
1882
1883 /*! \brief get option - really similar to the handle_streamfile, but with a timeout */
1884 static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1885 {
1886         int res, vres;
1887         struct ast_filestream *fs, *vfs;
1888         long sample_offset = 0, max_length;
1889         int timeout = 0;
1890         const char *edigits = "";
1891
1892         if ( argc < 4 || argc > 5 )
1893                 return RESULT_SHOWUSAGE;
1894
1895         if ( argv[3] )
1896                 edigits = argv[3];
1897
1898         if ( argc == 5 )
1899                 timeout = atoi(argv[4]);
1900         else if (chan->pbx->dtimeoutms) {
1901                 /* by default dtimeout is set to 5sec */
1902                 timeout = chan->pbx->dtimeoutms; /* in msec */
1903         }
1904
1905         if (!(fs = ast_openstream(chan, argv[2], chan->language))) {
1906                 ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", 0, sample_offset);
1907                 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
1908                 return RESULT_SUCCESS;
1909         }
1910
1911         if ((vfs = ast_openvstream(chan, argv[2], chan->language)))
1912                 ast_debug(1, "Ooh, found a video stream, too\n");
1913
1914         ast_verb(3, "Playing '%s' (escape_digits=%s) (timeout %d)\n", argv[2], edigits, timeout);
1915
1916         ast_seekstream(fs, 0, SEEK_END);
1917         max_length = ast_tellstream(fs);
1918         ast_seekstream(fs, sample_offset, SEEK_SET);
1919         res = ast_applystream(chan, fs);
1920         if (vfs)
1921                 vres = ast_applystream(chan, vfs);
1922         ast_playstream(fs);
1923         if (vfs)
1924                 ast_playstream(vfs);
1925
1926         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
1927         /* this is to check for if ast_waitstream closed the stream, we probably are at
1928          * the end of the stream, return that amount, else check for the amount */
1929         sample_offset = (chan->stream)?ast_tellstream(fs):max_length;
1930         ast_stopstream(chan);
1931         if (res == 1) {
1932                 /* Stop this command, don't print a result line, as there is a new command */
1933                 return RESULT_SUCCESS;
1934         }
1935
1936         /* If the user didnt press a key, wait for digitTimeout*/
1937         if (res == 0 ) {
1938                 res = ast_waitfordigit_full(chan, timeout, agi->audio, agi->ctrl);
1939                 /* Make sure the new result is in the escape digits of the GET OPTION */
1940                 if ( !strchr(edigits,res) )
1941                         res=0;
1942         }
1943
1944         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
1945         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1946 }
1947
1948
1949
1950
1951 /*! \brief Say number in various language syntaxes */
1952 /* While waiting, we're sending a NULL.  */
1953 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1954 {
1955         int res, num;
1956
1957         if (argc < 4 || argc > 5)
1958                 return RESULT_SHOWUSAGE;
1959         if (sscanf(argv[2], "%30d", &num) != 1)
1960                 return RESULT_SHOWUSAGE;
1961         res = ast_say_number_full(chan, num, argv[3], chan->language, argc > 4 ? argv[4] : NULL, agi->audio, agi->ctrl);
1962         if (res == 1)
1963                 return RESULT_SUCCESS;
1964         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1965         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1966 }
1967
1968 static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1969 {
1970         int res, num;
1971
1972         if (argc != 4)
1973                 return RESULT_SHOWUSAGE;
1974         if (sscanf(argv[2], "%30d", &num) != 1)
1975                 return RESULT_SHOWUSAGE;
1976
1977         res = ast_say_digit_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
1978         if (res == 1) /* New command */
1979                 return RESULT_SUCCESS;
1980         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1981         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1982 }
1983
1984 static int handle_sayalpha(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1985 {
1986         int res;
1987
1988         if (argc != 4)
1989                 return RESULT_SHOWUSAGE;
1990
1991         res = ast_say_character_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
1992         if (res == 1) /* New command */
1993                 return RESULT_SUCCESS;
1994         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1995         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1996 }
1997
1998 static int handle_saydate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1999 {
2000         int res, num;
2001
2002         if (argc != 4)
2003                 return RESULT_SHOWUSAGE;
2004         if (sscanf(argv[2], "%30d", &num) != 1)
2005                 return RESULT_SHOWUSAGE;
2006         res = ast_say_date(chan, num, argv[3], chan->language);
2007         if (res == 1)
2008                 return RESULT_SUCCESS;
2009         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2010         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2011 }
2012
2013 static int handle_saytime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2014 {
2015         int res, num;
2016
2017         if (argc != 4)
2018                 return RESULT_SHOWUSAGE;
2019         if (sscanf(argv[2], "%30d", &num) != 1)
2020                 return RESULT_SHOWUSAGE;
2021         res = ast_say_time(chan, num, argv[3], chan->language);
2022         if (res == 1)
2023                 return RESULT_SUCCESS;
2024         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2025         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2026 }
2027
2028 static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2029 {
2030         int res = 0;
2031         time_t unixtime;
2032         const char *format, *zone = NULL;
2033
2034         if (argc < 4)
2035                 return RESULT_SHOWUSAGE;
2036
2037         if (argc > 4) {
2038                 format = argv[4];
2039         } else {
2040                 /* XXX this doesn't belong here, but in the 'say' module */
2041                 if (!strcasecmp(chan->language, "de")) {
2042                         format = "A dBY HMS";
2043                 } else {
2044                         format = "ABdY 'digits/at' IMp";
2045                 }
2046         }
2047
2048         if (argc > 5 && !ast_strlen_zero(argv[5]))
2049                 zone = argv[5];
2050
2051         if (ast_get_time_t(argv[2], &unixtime, 0, NULL))
2052                 return RESULT_SHOWUSAGE;
2053
2054         res = ast_say_date_with_format(chan, unixtime, argv[3], chan->language, format, zone);
2055         if (res == 1)
2056                 return RESULT_SUCCESS;
2057
2058         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2059         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2060 }
2061
2062 static int handle_sayphonetic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2063 {
2064         int res;
2065
2066         if (argc != 4)
2067                 return RESULT_SHOWUSAGE;
2068
2069         res = ast_say_phonetic_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
2070         if (res == 1) /* New command */
2071                 return RESULT_SUCCESS;
2072         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2073         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2074 }
2075
2076 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2077 {
2078         int res, max, timeout;
2079         char data[1024];
2080
2081         if (argc < 3)
2082                 return RESULT_SHOWUSAGE;
2083         if (argc >= 4)
2084                 timeout = atoi(argv[3]);
2085         else
2086                 timeout = 0;
2087         if (argc >= 5)
2088                 max = atoi(argv[4]);
2089         else
2090                 max = 1024;
2091         res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
2092         if (res == 2)                   /* New command */
2093                 return RESULT_SUCCESS;
2094         else if (res == 1)
2095                 ast_agi_send(agi->fd, chan, "200 result=%s (timeout)\n", data);
2096         else if (res < 0 )
2097                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2098         else
2099                 ast_agi_send(agi->fd, chan, "200 result=%s\n", data);
2100         return RESULT_SUCCESS;
2101 }
2102
2103 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2104 {
2105
2106         if (argc != 3)
2107                 return RESULT_SHOWUSAGE;
2108         ast_copy_string(chan->context, argv[2], sizeof(chan->context));
2109         ast_agi_send(agi->fd, chan, "200 result=0\n");
2110         return RESULT_SUCCESS;
2111 }
2112
2113 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2114 {
2115         if (argc != 3)
2116                 return RESULT_SHOWUSAGE;
2117         ast_copy_string(chan->exten, argv[2], sizeof(chan->exten));
2118         ast_agi_send(agi->fd, chan, "200 result=0\n");
2119         return RESULT_SUCCESS;
2120 }
2121
2122 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2123 {
2124         int pri;
2125
2126         if (argc != 3)
2127                 return RESULT_SHOWUSAGE;
2128
2129         if (sscanf(argv[2], "%30d", &pri) != 1) {
2130                 pri = ast_findlabel_extension(chan, chan->context, chan->exten, argv[2],
2131                         S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL));
2132                 if (pri < 1)
2133                         return RESULT_SHOWUSAGE;
2134         }
2135
2136         ast_explicit_goto(chan, NULL, NULL, pri);
2137         ast_agi_send(agi->fd, chan, "200 result=0\n");
2138         return RESULT_SUCCESS;
2139 }
2140
2141 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2142 {
2143         struct ast_filestream *fs;
2144         struct ast_frame *f;
2145         struct timeval start;
2146         long sample_offset = 0;
2147         int res = 0;
2148         int ms;
2149
2150         struct ast_dsp *sildet=NULL;         /* silence detector dsp */
2151         int totalsilence = 0;
2152         int dspsilence = 0;
2153         int silence = 0;                /* amount of silence to allow */
2154         int gotsilence = 0;             /* did we timeout for silence? */
2155         char *silencestr = NULL;
2156         struct ast_format rfmt;
2157         ast_format_clear(&rfmt);
2158
2159         /* XXX EAGI FIXME XXX */
2160
2161         if (argc < 6)
2162                 return RESULT_SHOWUSAGE;
2163         if (sscanf(argv[5], "%30d", &ms) != 1)
2164                 return RESULT_SHOWUSAGE;
2165
2166         if (argc > 6)
2167                 silencestr = strchr(argv[6],'s');
2168         if ((argc > 7) && (!silencestr))
2169                 silencestr = strchr(argv[7],'s');
2170         if ((argc > 8) && (!silencestr))
2171                 silencestr = strchr(argv[8],'s');
2172
2173         if (silencestr) {
2174                 if (strlen(silencestr) > 2) {
2175                         if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
2176                                 silencestr++;
2177                                 silencestr++;
2178                                 if (silencestr)
2179                                         silence = atoi(silencestr);
2180                                 if (silence > 0)
2181                                         silence *= 1000;
2182                         }
2183                 }
2184         }
2185
2186         if (silence > 0) {
2187                 ast_format_copy(&rfmt, &chan->readformat);
2188                 res = ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
2189                 if (res < 0) {
2190                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
2191                         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2192                         return RESULT_FAILURE;
2193                 }
2194                 sildet = ast_dsp_new();
2195                 if (!sildet) {
2196                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
2197                         ast_agi_send(agi->fd, chan, "200 result=-1\n");
2198                         return RESULT_FAILURE;
2199                 }
2200                 ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
2201         }
2202         
2203         /* backward compatibility, if no offset given, arg[6] would have been
2204          * caught below and taken to be a beep, else if it is a digit then it is a
2205          * offset */
2206         if ((argc >6) && (sscanf(argv[6], "%30ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
2207                 res = ast_streamfile(chan, "beep", chan->language);
2208
2209         if ((argc > 7) && (!strchr(argv[7], '=')))
2210                 res = ast_streamfile(chan, "beep", chan->language);
2211
2212         if (!res)
2213                 res = ast_waitstream(chan, argv[4]);
2214         if (res) {
2215                 ast_agi_send(agi->fd, chan, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
2216         } else {
2217                 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, AST_FILE_MODE);
2218                 if (!fs) {
2219                         res = -1;
2220                         ast_agi_send(agi->fd, chan, "200 result=%d (writefile)\n", res);
2221                         if (sildet)
2222                                 ast_dsp_free(sildet);
2223                         return RESULT_FAILURE;
2224                 }
2225
2226                 /* Request a video update */
2227                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
2228
2229                 chan->stream = fs;
2230                 ast_applystream(chan,fs);
2231                 /* really should have checks */
2232                 ast_seekstream(fs, sample_offset, SEEK_SET);
2233                 ast_truncstream(fs);
2234
2235                 start = ast_tvnow();
2236                 while ((ms < 0) || ast_tvdiff_ms(ast_tvnow(), start) < ms) {
2237                         res = ast_waitfor(chan, ms - ast_tvdiff_ms(ast_tvnow(), start));
2238                         if (res < 0) {
2239                                 ast_closestream(fs);
2240                                 ast_agi_send(agi->fd, chan, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
2241                                 if (sildet)
2242                                         ast_dsp_free(sildet);
2243                                 return RESULT_FAILURE;
2244                         }
2245                         f = ast_read(chan);
2246                         if (!f) {
2247                                 ast_agi_send(agi->fd, chan, "200 result=%d (hangup) endpos=%ld\n", -1, sample_offset);
2248                                 ast_closestream(fs);
2249                                 if (sildet)
2250                                         ast_dsp_free(sildet);
2251                                 return RESULT_FAILURE;
2252                         }
2253                         switch(f->frametype) {
2254                         case AST_FRAME_DTMF:
2255                                 if (strchr(argv[4], f->subclass.integer)) {
2256                                         /* This is an interrupting chracter, so rewind to chop off any small
2257                                            amount of DTMF that may have been recorded
2258                                         */
2259                                         ast_stream_rewind(fs, 200);
2260                                         ast_truncstream(fs);
2261                                         sample_offset = ast_tellstream(fs);
2262                                         ast_agi_send(agi->fd, chan, "200 result=%d (dtmf) endpos=%ld\n", f->subclass.integer, sample_offset);
2263                                         ast_closestream(fs);
2264                                         ast_frfree(f);
2265                                         if (sildet)
2266                                                 ast_dsp_free(sildet);
2267                                         return RESULT_SUCCESS;
2268                                 }
2269                                 break;
2270                         case AST_FRAME_VOICE:
2271                                 ast_writestream(fs, f);
2272                                 /* this is a safe place to check progress since we know that fs
2273                                  * is valid after a write, and it will then have our current
2274                                  * location */
2275                                 sample_offset = ast_tellstream(fs);
2276                                 if (silence > 0) {
2277                                         dspsilence = 0;
2278                                         ast_dsp_silence(sildet, f, &dspsilence);
2279                                         if (dspsilence) {
2280                                                 totalsilence = dspsilence;
2281                                         } else {
2282                                                 totalsilence = 0;
2283                                         }
2284                                         if (totalsilence > silence) {
2285                                                 /* Ended happily with silence */
2286                                                 gotsilence = 1;
2287                                                 break;
2288                                         }
2289                                 }
2290                                 break;
2291                         case AST_FRAME_VIDEO:
2292                                 ast_writestream(fs, f);
2293                         default:
2294                                 /* Ignore all other frames */
2295                                 break;
2296                         }
2297                         ast_frfree(f);
2298                         if (gotsilence)
2299                                 break;
2300                 }
2301
2302                 if (gotsilence) {
2303                         ast_stream_rewind(fs, silence-1000);
2304                         ast_truncstream(fs);
2305                         sample_offset = ast_tellstream(fs);
2306                 }
2307                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
2308                 ast_closestream(fs);
2309         }
2310
2311         if (silence > 0) {
2312                 res = ast_set_read_format(chan, &rfmt);
2313                 if (res)
2314                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", chan->name);
2315                 ast_dsp_free(sildet);
2316         }
2317
2318         return RESULT_SUCCESS;
2319 }
2320
2321 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2322 {
2323         double timeout;
2324         struct timeval whentohangup = { 0, 0 };
2325
2326         if (argc != 3)
2327                 return RESULT_SHOWUSAGE;
2328         if (sscanf(argv[2], "%30lf", &timeout) != 1)
2329                 return RESULT_SHOWUSAGE;
2330         if (timeout < 0)
2331                 timeout = 0;
2332         if (timeout) {
2333                 whentohangup.tv_sec = timeout;
2334                 whentohangup.tv_usec = (timeout - whentohangup.tv_sec) * 1000000.0;
2335         }
2336         ast_channel_setwhentohangup_tv(chan, whentohangup);
2337         ast_agi_send(agi->fd, chan, "200 result=0\n");
2338         return RESULT_SUCCESS;
2339 }
2340
2341 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2342 {
2343         struct ast_channel *c;
2344
2345         if (argc == 1) {
2346                 /* no argument: hangup the current channel */
2347                 ast_set_hangupsource(chan, "dialplan/agi", 0);
2348                 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
2349                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2350                 return RESULT_SUCCESS;
2351         } else if (argc == 2) {
2352                 /* one argument: look for info on the specified channel */
2353                 if ((c = ast_channel_get_by_name(argv[1]))) {
2354                         /* we have a matching channel */
2355                         ast_set_hangupsource(c, "dialplan/agi", 0);
2356                         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
2357                         c = ast_channel_unref(c);
2358                         ast_agi_send(agi->fd, chan, "200 result=1\n");
2359                         return RESULT_SUCCESS;
2360                 }
2361                 /* if we get this far no channel name matched the argument given */
2362                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2363                 return RESULT_SUCCESS;
2364         } else {
2365                 return RESULT_SHOWUSAGE;
2366         }
2367 }
2368
2369 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2370 {
2371         int res, workaround;
2372         struct ast_app *app_to_exec;
2373
2374         if (argc < 2)
2375                 return RESULT_SHOWUSAGE;
2376
2377         ast_verb(3, "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argc >= 3 ? argv[2] : "");
2378
2379         if ((app_to_exec = pbx_findapp(argv[1]))) {
2380                 if(!strcasecmp(argv[1], PARK_APP_NAME)) {
2381                         ast_masq_park_call(chan, NULL, 0, NULL);
2382                 }
2383                 if (!(workaround = ast_test_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS))) {
2384                         ast_set_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS);
2385                 }
2386                 if (ast_compat_res_agi && argc >= 3 && !ast_strlen_zero(argv[2])) {
2387                         char *compat = alloca(strlen(argv[2]) * 2 + 1), *cptr;
2388                         const char *vptr;
2389                         for (cptr = compat, vptr = argv[2]; *vptr; vptr++) {
2390                                 if (*vptr == ',') {
2391                                         *cptr++ = '\\';
2392                                         *cptr++ = ',';
2393                                 } else if (*vptr == '|') {
2394                                         *cptr++ = ',';
2395                                 } else {
2396                                         *cptr++ = *vptr;
2397                                 }
2398                         }
2399                         *cptr = '\0';
2400                         res = pbx_exec(chan, app_to_exec, compat);
2401                 } else {
2402                         res = pbx_exec(chan, app_to_exec, argc == 2 ? "" : argv[2]);
2403                 }
2404                 if (!workaround) {
2405                         ast_clear_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS);
2406                 }
2407         } else {
2408                 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
2409                 res = -2;
2410         }
2411         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2412
2413         /* Even though this is wrong, users are depending upon this result. */
2414         return res;
2415 }
2416
2417 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2418 {
2419         char tmp[256]="";
2420         char *l = NULL, *n = NULL;
2421
2422         if (argv[2]) {
2423                 ast_copy_string(tmp, argv[2], sizeof(tmp));
2424                 ast_callerid_parse(tmp, &n, &l);
2425                 if (l)
2426                         ast_shrink_phone_number(l);
2427                 else
2428                         l = "";
2429                 if (!n)
2430                         n = "";
2431                 ast_set_callerid(chan, l, n, NULL);
2432         }
2433
2434         ast_agi_send(agi->fd, chan, "200 result=1\n");
2435         return RESULT_SUCCESS;
2436 }
2437
2438 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2439 {
2440         struct ast_channel *c;
2441         if (argc == 2) {
2442                 /* no argument: supply info on the current channel */
2443                 ast_agi_send(agi->fd, chan, "200 result=%d\n", chan->_state);
2444                 return RESULT_SUCCESS;
2445         } else if (argc == 3) {
2446                 /* one argument: look for info on the specified channel */
2447                 if ((c = ast_channel_get_by_name(argv[2]))) {
2448                         ast_agi_send(agi->fd, chan, "200 result=%d\n", c->_state);
2449                         c = ast_channel_unref(c);
2450                         return RESULT_SUCCESS;
2451                 }
2452                 /* if we get this far no channel name matched the argument given */
2453                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2454                 return RESULT_SUCCESS;
2455         } else {
2456                 return RESULT_SHOWUSAGE;
2457         }
2458 }
2459
2460 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2461 {
2462         if (argv[3])
2463                 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
2464
2465         ast_agi_send(agi->fd, chan, "200 result=1\n");
2466         return RESULT_SUCCESS;
2467 }
2468
2469 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2470 {
2471         char *ret;
2472         char tempstr[1024];
2473
2474         if (argc != 3)
2475                 return RESULT_SHOWUSAGE;
2476
2477         /* check if we want to execute an ast_custom_function */
2478         if (!ast_strlen_zero(argv[2]) && (argv[2][strlen(argv[2]) - 1] == ')')) {
2479                 ret = ast_func_read(chan, argv[2], tempstr, sizeof(tempstr)) ? NULL : tempstr;
2480         } else {
2481                 pbx_retrieve_variable(chan, argv[2], &ret, tempstr, sizeof(tempstr), NULL);
2482         }
2483
2484         if (ret)
2485                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ret);
2486         else
2487                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2488
2489         return RESULT_SUCCESS;
2490 }
2491
2492 static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2493 {
2494         struct ast_channel *chan2 = NULL;
2495
2496         if (argc != 4 && argc != 5) {
2497                 return RESULT_SHOWUSAGE;
2498         }
2499
2500         if (argc == 5) {
2501                 chan2 = ast_channel_get_by_name(argv[4]);
2502         } else {
2503                 chan2 = ast_channel_ref(chan);
2504         }
2505
2506         if (chan2) {
2507                 struct ast_str *str = ast_str_create(16);
2508                 if (!str) {
2509                         ast_agi_send(agi->fd, chan, "200 result=0\n");
2510                         return RESULT_SUCCESS;
2511                 }
2512                 ast_str_substitute_variables(&str, 0, chan2, argv[3]);
2513                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(str));
2514                 ast_free(str);
2515         } else {
2516                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2517         }
2518
2519         if (chan2) {
2520                 chan2 = ast_channel_unref(chan2);
2521         }
2522
2523         return RESULT_SUCCESS;
2524 }
2525
2526 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2527 {
2528         int level = 0;
2529
2530         if (argc < 2)
2531                 return RESULT_SHOWUSAGE;
2532
2533         if (argv[2])
2534                 sscanf(argv[2], "%30d", &level);
2535
2536         ast_verb(level, "%s: %s\n", chan->data, argv[1]);
2537
2538         ast_agi_send(agi->fd, chan, "200 result=1\n");
2539
2540         return RESULT_SUCCESS;
2541 }
2542
2543 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2544 {
2545         int res;
2546         struct ast_str *buf;
2547
2548         if (argc != 4)
2549                 return RESULT_SHOWUSAGE;
2550
2551         if (!(buf = ast_str_create(16))) {
2552                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2553                 return RESULT_SUCCESS;
2554         }
2555
2556         do {
2557                 res = ast_db_get(argv[2], argv[3], ast_str_buffer(buf), ast_str_size(buf));
2558                 ast_str_update(buf);
2559                 if (ast_str_strlen(buf) < ast_str_size(buf) - 1) {
2560                         break;
2561                 }
2562                 if (ast_str_make_space(&buf, ast_str_size(buf) * 2)) {
2563                         break;
2564                 }
2565         } while (1);
2566         
2567         if (res)
2568                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2569         else
2570                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(buf));
2571
2572         ast_free(buf);
2573         return RESULT_SUCCESS;
2574 }
2575
2576 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2577 {
2578         int res;
2579
2580         if (argc != 5)
2581                 return RESULT_SHOWUSAGE;
2582         res = ast_db_put(argv[2], argv[3], argv[4]);
2583         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2584         return RESULT_SUCCESS;
2585 }
2586
2587 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2588 {
2589         int res;
2590
2591         if (argc != 4)
2592                 return RESULT_SHOWUSAGE;
2593         res = ast_db_del(argv[2], argv[3]);
2594         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2595         return RESULT_SUCCESS;
2596 }
2597
2598 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2599 {
2600         int res;
2601
2602         if ((argc < 3) || (argc > 4))
2603                 return RESULT_SHOWUSAGE;
2604         if (argc == 4)
2605                 res = ast_db_deltree(argv[2], argv[3]);
2606         else
2607                 res = ast_db_deltree(argv[2], NULL);
2608
2609         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2610         return RESULT_SUCCESS;
2611 }
2612
2613 static char *handle_cli_agi_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2614 {
2615         switch (cmd) {
2616         case CLI_INIT:
2617                 e->command = "agi set debug [on|off]";
2618                 e->usage =
2619                         "Usage: agi set debug [on|off]\n"
2620                         "       Enables/disables dumping of AGI transactions for\n"
2621                         "       debugging purposes.\n";
2622                 return NULL;
2623
2624         case CLI_GENERATE:
2625                 return NULL;
2626         }
2627
2628         if (a->argc != e->args)
2629                 return CLI_SHOWUSAGE;
2630
2631         if (strncasecmp(a->argv[3], "off", 3) == 0) {
2632                 agidebug = 0;
2633         } else if (strncasecmp(a->argv[3], "on", 2) == 0) {
2634                 agidebug = 1;
2635         } else {
2636                 return CLI_SHOWUSAGE;
2637         }
2638         ast_cli(a->fd, "AGI Debugging %sabled\n", agidebug ? "En" : "Dis");
2639         return CLI_SUCCESS;
2640 }
2641
2642 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, const char * const argv[])
2643 {
2644         ast_agi_send(agi->fd, chan, "200 result=0\n");
2645         return RESULT_SUCCESS;
2646 }
2647
2648 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2649 {
2650         if (argc < 3) {
2651                 return RESULT_SHOWUSAGE;
2652         }
2653         if (!strncasecmp(argv[2], "on", 2))
2654                 ast_moh_start(chan, argc > 3 ? argv[3] : NULL, NULL);
2655         else if (!strncasecmp(argv[2], "off", 3))
2656                 ast_moh_stop(chan);
2657         ast_agi_send(agi->fd, chan, "200 result=0\n");
2658         return RESULT_SUCCESS;
2659 }
2660
2661 static int handle_speechcreate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2662 {
2663         struct ast_format_cap *cap;
2664         struct ast_format tmpfmt;
2665
2666         /* If a structure already exists, return an error */
2667         if (agi->speech) {
2668                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2669                 return RESULT_SUCCESS;
2670         }
2671
2672         if (!(cap = ast_format_cap_alloc_nolock())) {
2673                 return RESULT_FAILURE;
2674         }
2675         ast_format_cap_add(cap, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0));
2676         if ((agi->speech = ast_speech_new(argv[2], cap))) {
2677                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2678         } else {
2679                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2680         }
2681         cap = ast_format_cap_destroy(cap);
2682
2683         return RESULT_SUCCESS;
2684 }
2685
2686 static int handle_speechset(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2687 {
2688         /* Check for minimum arguments */
2689         if (argc != 4)
2690                 return RESULT_SHOWUSAGE;
2691
2692         /* Check to make sure speech structure exists */
2693         if (!agi->speech) {
2694                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2695                 return RESULT_SUCCESS;
2696         }
2697
2698         ast_speech_change(agi->speech, argv[2], argv[3]);
2699         ast_agi_send(agi->fd, chan, "200 result=1\n");
2700
2701         return RESULT_SUCCESS;
2702 }
2703
2704 static int handle_speechdestroy(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2705 {
2706         if (agi->speech) {
2707                 ast_speech_destroy(agi->speech);
2708                 agi->speech = NULL;
2709                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2710         } else {
2711                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2712         }
2713
2714         return RESULT_SUCCESS;
2715 }
2716
2717 static int handle_speechloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2718 {
2719         if (argc != 5)
2720                 return RESULT_SHOWUSAGE;
2721
2722         if (!agi->speech) {
2723                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2724                 return RESULT_SUCCESS;
2725         }
2726
2727         if (ast_speech_grammar_load(agi->speech, argv[3], argv[4]))
2728                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2729         else
2730                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2731
2732         return RESULT_SUCCESS;
2733 }
2734
2735 static int handle_speechunloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2736 {
2737         if (argc != 4)
2738                 return RESULT_SHOWUSAGE;
2739
2740         if (!agi->speech) {
2741                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2742                 return RESULT_SUCCESS;
2743         }
2744
2745         if (ast_speech_grammar_unload(agi->speech, argv[3]))
2746                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2747         else
2748                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2749
2750         return RESULT_SUCCESS;
2751 }
2752
2753 static int handle_speechactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2754 {
2755         if (argc != 4)
2756                 return RESULT_SHOWUSAGE;
2757
2758         if (!agi->speech) {
2759                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2760                 return RESULT_SUCCESS;
2761         }
2762
2763         if (ast_speech_grammar_activate(agi->speech, argv[3]))
2764                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2765         else
2766                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2767
2768         return RESULT_SUCCESS;
2769 }
2770
2771 static int handle_speechdeactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2772 {
2773         if (argc != 4)
2774                 return RESULT_SHOWUSAGE;
2775
2776         if (!agi->speech) {
2777                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2778                 return RESULT_SUCCESS;
2779         }
2780
2781         if (ast_speech_grammar_deactivate(agi->speech, argv[3]))
2782                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2783         else
2784                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2785
2786         return RESULT_SUCCESS;
2787 }
2788
2789 static int speech_streamfile(struct ast_channel *chan, const char *filename, const char *preflang, int offset)
2790 {
2791         struct ast_filestream *fs = NULL;
2792
2793         if (!(fs = ast_openstream(chan, filename, preflang)))
2794                 return -1;
2795
2796         if (offset)
2797                 ast_seekstream(fs, offset, SEEK_SET);
2798
2799         if (ast_applystream(chan, fs))
2800                 return -1;
2801
2802         if (ast_playstream(fs))
2803                 return -1;
2804
2805         return 0;
2806 }
2807
2808 static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2809 {
2810         struct ast_speech *speech = agi->speech;
2811         const char *prompt;
2812         char dtmf = 0, tmp[4096] = "", *buf = tmp;
2813         int timeout = 0, offset = 0, res = 0, i = 0;
2814         struct ast_format old_read_format;
2815         long current_offset = 0;
2816         const char *reason = NULL;
2817         struct ast_frame *fr = NULL;
2818         struct ast_speech_result *result = NULL;
2819         size_t left = sizeof(tmp);
2820         time_t start = 0, current;
2821
2822         if (argc < 4)
2823                 return RESULT_SHOWUSAGE;
2824
2825         if (!speech) {
2826                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2827                 return RESULT_SUCCESS;
2828         }
2829
2830         prompt = argv[2];
2831         timeout = atoi(argv[3]);
2832
2833         /* If offset is specified then convert from text to integer */
2834         if (argc == 5)
2835                 offset = atoi(argv[4]);
2836
2837         /* We want frames coming in signed linear */
2838         ast_format_copy(&old_read_format, &chan->readformat);
2839         if (ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR)) {
2840                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2841                 return RESULT_SUCCESS;
2842         }
2843
2844         /* Setup speech structure */
2845         if (speech->state == AST_SPEECH_STATE_NOT_READY || speech->state == AST_SPEECH_STATE_DONE) {
2846                 ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
2847                 ast_speech_start(speech);
2848         }
2849
2850         /* Start playing prompt */
2851         speech_streamfile(chan, prompt, chan->language, offset);
2852
2853         /* Go into loop reading in frames, passing to speech thingy, checking for hangup, all that jazz */
2854         while (ast_strlen_zero(reason)) {
2855                 /* Run scheduled items */
2856                 ast_sched_runq(chan->sched);
2857
2858                 /* See maximum time of waiting */
2859                 if ((res = ast_sched_wait(chan->sched)) < 0)
2860                         res = 1000;
2861
2862                 /* Wait for frame */
2863                 if (ast_waitfor(chan, res) > 0) {
2864                         if (!(fr = ast_read(chan))) {
2865                                 reason = "hangup";
2866                                 break;
2867                         }
2868                 }
2869
2870                 /* Perform timeout check */
2871                 if ((timeout > 0) && (start > 0)) {
2872                         time(&current);
2873                         if ((current - start) >= timeout) {
2874                                 reason = "timeout";
2875                                 if (fr)
2876                                         ast_frfree(fr);
2877                                 break;
2878                         }
2879                 }
2880
2881                 /* Check the speech structure for any changes */
2882                 ast_mutex_lock(&speech->lock);
2883
2884                 /* See if we need to quiet the audio stream playback */
2885                 if (ast_test_flag(speech, AST_SPEECH_QUIET) && chan->stream) {
2886                         current_offset = ast_tellstream(chan->stream);
2887                         ast_stopstream(chan);
2888                         ast_clear_flag(speech, AST_SPEECH_QUIET);
2889                 }
2890
2891                 /* Check each state */
2892                 switch (speech->state) {
2893                 case AST_SPEECH_STATE_READY:
2894                         /* If the stream is done, start timeout calculation */
2895                         if ((timeout > 0) && start == 0 && ((!chan->stream) || (chan->streamid == -1 && chan->timingfunc == NULL))) {
2896                                 ast_stopstream(chan);
2897                                 time(&start);
2898                         }
2899                         /* Write audio frame data into speech engine if possible */
2900                         if (fr && fr->frametype == AST_FRAME_VOICE)
2901                                 ast_speech_write(speech, fr->data.ptr, fr->datalen);
2902                         break;
2903                 case AST_SPEECH_STATE_WAIT:
2904                         /* Cue waiting sound if not already playing */
2905                         if ((!chan->stream) || (chan->streamid == -1 && chan->timingfunc == NULL)) {
2906                                 ast_stopstream(chan);
2907                                 /* If a processing sound exists, or is not none - play it */
2908                                 if (!ast_strlen_zero(speech->processing_sound) && strcasecmp(speech->processing_sound, "none"))
2909                                         speech_streamfile(chan, speech->processing_sound, chan->language, 0);
2910                         }
2911                         break;
2912                 case AST_SPEECH_STATE_DONE:
2913                         /* Get the results */
2914                         speech->results = ast_speech_results_get(speech);
2915                         /* Change state to not ready */
2916                         ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
2917                         reason = "speech";
2918                         break;
2919                 default:
2920                         break;
2921                 }
2922                 ast_mutex_unlock(&speech->lock);
2923
2924                 /* Check frame for DTMF or hangup */
2925                 if (fr) {
2926                         if (fr->frametype == AST_FRAME_DTMF) {
2927                                 reason = "dtmf";
2928                                 dtmf = fr->subclass.integer;
2929                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_HANGUP) {
2930                                 reason = "hangup";
2931                         }
2932                         ast_frfree(fr);
2933                 }
2934         }
2935
2936         if (!strcasecmp(reason, "speech")) {
2937                 /* Build string containing speech results */
2938                 for (result = speech->results; result; result = AST_LIST_NEXT(result, list)) {
2939                         /* Build result string */
2940                         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);
2941                         /* Increment result count */
2942                         i++;
2943                 }
2944                 /* Print out */
2945                 ast_agi_send(agi->fd, chan, "200 result=1 (speech) endpos=%ld results=%d %s\n", current_offset, i, tmp);
2946         } else if (!strcasecmp(reason, "dtmf")) {
2947                 ast_agi_send(agi->fd, chan, "200 result=1 (digit) digit=%c endpos=%ld\n", dtmf, current_offset);
2948         } else if (!strcasecmp(reason, "hangup") || !strcasecmp(reason, "timeout")) {
2949                 ast_agi_send(agi->fd, chan, "200 result=1 (%s) endpos=%ld\n", reason, current_offset);
2950         } else {
2951                 ast_agi_send(agi->fd, chan, "200 result=0 endpos=%ld\n", current_offset);
2952         }
2953
2954         return RESULT_SUCCESS;
2955 }
2956
2957 /*!
2958  * \brief AGI commands list
2959  */
2960 static struct agi_command commands[] = {
2961         { { "answer", NULL }, handle_answer, NULL, NULL, 0 },
2962         { { "asyncagi", "break", NULL }, handle_asyncagi_break, NULL, NULL, 1 },
2963         { { "channel", "status", NULL }, handle_channelstatus, NULL, NULL, 0 },
2964         { { "database", "del", NULL }, handle_dbdel, NULL, NULL, 1 },
2965         { { "database", "deltree", NULL }, handle_dbdeltree, NULL, NULL, 1 },
2966         { { "database", "get", NULL }, handle_dbget, NULL, NULL, 1 },
2967         { { "database", "put", NULL }, handle_dbput, NULL, NULL, 1 },
2968         { { "exec", NULL }, handle_exec, NULL, NULL, 1 },
2969         { { "get", "data", NULL }, handle_getdata, NULL, NULL, 0 },
2970         { { "get", "full", "variable", NULL }, handle_getvariablefull, NULL, NULL, 1 },
2971         { { "get", "option", NULL }, handle_getoption, NULL, NULL, 0 },
2972         { { "get", "variable", NULL }, handle_getvariable, NULL, NULL, 1 },
2973         { { "hangup", NULL }, handle_hangup, NULL, NULL, 0 },
2974         { { "noop", NULL }, handle_noop, NULL, NULL, 1 },
2975         { { "receive", "char", NULL }, handle_recvchar, NULL, NULL, 0 },
2976         { { "receive", "text", NULL }, handle_recvtext, NULL, NULL, 0 },
2977         { { "record", "file", NULL }, handle_recordfile, NULL, NULL, 0 }, 
2978         { { "say", "alpha", NULL }, handle_sayalpha, NULL, NULL, 0},
2979         { { "say", "digits", NULL }, handle_saydigits, NULL, NULL, 0 },
2980         { { "say", "number", NULL }, handle_saynumber, NULL, NULL, 0 },
2981         { { "say", "phonetic", NULL }, handle_sayphonetic, NULL, NULL, 0}, 
2982         { { "say", "date", NULL }, handle_saydate, NULL, NULL, 0}, 
2983         { { "say", "time", NULL }, handle_saytime, NULL, NULL, 0}, 
2984         { { "say", "datetime", NULL }, handle_saydatetime, NULL, NULL, 0},
2985         { { "send", "image", NULL }, handle_sendimage, NULL, NULL, 0}, 
2986         { { "send", "text", NULL }, handle_sendtext, NULL, NULL, 0},
2987         { { "set", "autohangup", NULL }, handle_autohangup, NULL, NULL, 0},
2988         { { "set", "callerid", NULL }, handle_setcallerid, NULL, NULL, 0},
2989         { { "set", "context", NULL }, handle_setcontext, NULL, NULL, 0},
2990         { { "set", "extension", NULL }, handle_setextension, NULL, NULL, 0},
2991         { { "set", "music", NULL }, handle_setmusic, NULL, NULL, 0 },
2992         { { "set", "priority", NULL }, handle_setpriority, NULL, NULL, 0 },
2993         { { "set", "variable", NULL }, handle_setvariable, NULL, NULL, 1 },
2994         { { "stream", "file", NULL }, handle_streamfile, NULL, NULL, 0 },
2995         { { "control", "stream", "file", NULL }, handle_controlstreamfile, NULL, NULL, 0 },
2996         { { "tdd", "mode", NULL }, handle_tddmode, NULL, NULL, 0 },
2997         { { "verbose", NULL }, handle_verbose, NULL, NULL, 1 },
2998         { { "wait", "for", "digit", NULL }, handle_waitfordigit, NULL, NULL, 0 },
2999         { { "speech", "create", NULL }, handle_speechcreate, NULL, NULL, 0 },
3000         { { "speech", "set", NULL }, handle_speechset, NULL, NULL, 0 },
3001         { { "speech", "destroy", NULL }, handle_speechdestroy, NULL, NULL, 1 },
3002         { { "speech", "load", "grammar", NULL }, handle_speechloadgrammar, NULL, NULL, 0 },
3003         { { "speech", "unload", "grammar", NULL }, handle_speechunloadgrammar, NULL, NULL, 1 },
3004         { { "speech", "activate", "grammar", NULL }, handle_speechactivategrammar, NULL, NULL, 0 },
3005         { { "speech", "deactivate", "grammar", NULL }, handle_speechdeactivategrammar, NULL, NULL, 0 },
3006         { { "speech", "recognize", NULL }, handle_speechrecognize, NULL, NULL, 0 },
3007 };
3008
3009 static AST_RWLIST_HEAD_STATIC(agi_commands, agi_command);
3010
3011 static char *help_workhorse(int fd, const char * const match[])
3012 {
3013         char fullcmd[MAX_CMD_LEN], matchstr[MAX_CMD_LEN];
3014         struct agi_command *e;
3015
3016         if (match)
3017                 ast_join(matchstr, sizeof(matchstr), match);
3018
3019         ast_cli(fd, "%5.5s %30.30s   %s\n","Dead","Command","Description");
3020         AST_RWLIST_RDLOCK(&agi_commands);
3021         AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
3022                 if (!e->cmda[0])
3023                         break;
3024                 /* Hide commands that start with '_' */
3025                 if ((e->cmda[0])[0] == '_')
3026                         continue;
3027                 ast_join(fullcmd, sizeof(fullcmd), e->cmda);
3028                 if (match && strncasecmp(matchstr, fullcmd, strlen(matchstr)))
3029                         continue;
3030                 ast_cli(fd, "%5.5s %30.30s   %s\n", e->dead ? "Yes" : "No" , fullcmd, S_OR(e->summary, "Not available"));
3031         }
3032         AST_RWLIST_UNLOCK(&agi_commands);
3033
3034         return CLI_SUCCESS;
3035 }
3036
3037 int AST_OPTIONAL_API_NAME(ast_agi_register)(struct ast_module *mod, agi_command *cmd)
3038 {
3039         char fullcmd[MAX_CMD_LEN];
3040
3041         ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
3042
3043         if (!find_command(cmd->cmda, 1)) {
3044                 *((enum ast_doc_src *) &cmd->docsrc) = AST_STATIC_DOC;
3045                 if (ast_strlen_zero(cmd->summary) && ast_strlen_zero(cmd->usage)) {
3046 #ifdef AST_XML_DOCS
3047                         *((char **) &cmd->summary) = ast_xmldoc_build_synopsis("agi", fullcmd);
3048                         *((char **) &cmd->usage) = ast_xmldoc_build_description("agi", fullcmd);
3049                         *((char **) &cmd->syntax) = ast_xmldoc_build_syntax("agi", fullcmd);
3050                         *((char **) &cmd->seealso) = ast_xmldoc_build_seealso("agi", fullcmd);
3051                         *((enum ast_doc_src *) &cmd->docsrc) = AST_XML_DOC;
3052 #endif
3053 #ifndef HAVE_NULLSAFE_PRINTF
3054                         if (!cmd->summary) {
3055                                 *((char **) &cmd->summary) = ast_strdup("");
3056                         }
3057                         if (!cmd->usage) {
3058                                 *((char **) &cmd->usage) = ast_strdup("");
3059                         }
3060                         if (!cmd->syntax) {
3061                                 *((char **) &cmd->syntax) = ast_strdup("");
3062                         }
3063                         if (!cmd->seealso) {
3064                                 *((char **) &cmd->seealso) = ast_strdup("");
3065                         }
3066 #endif
3067                 }
3068
3069                 cmd->mod = mod;
3070                 AST_RWLIST_WRLOCK(&agi_commands);
3071                 AST_LIST_INSERT_TAIL(&agi_commands, cmd, list);
3072                 AST_RWLIST_UNLOCK(&agi_commands);
3073                 if (mod != ast_module_info->self)
3074                         ast_module_ref(ast_module_info->self);
3075                 ast_verb(2, "AGI Command '%s' registered\n",fullcmd);
3076                 return 1;
3077         } else {
3078                 ast_log(LOG_WARNING, "Command already registered!\n");
3079                 return 0;
3080         }
3081 }
3082
3083 int AST_OPTIONAL_API_NAME(ast_agi_unregister)(struct ast_module *mod, agi_command *cmd)
3084 {
3085         struct agi_command *e;
3086         int unregistered = 0;
3087         char fullcmd[MAX_CMD_LEN];
3088
3089         ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
3090
3091         AST_RWLIST_WRLOCK(&agi_commands);
3092         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&agi_commands, e, list) {
3093                 if (cmd == e) {
3094                         AST_RWLIST_REMOVE_CURRENT(list);
3095                         if (mod != ast_module_info->self)
3096                                 ast_module_unref(ast_module_info->self);
3097 #ifdef AST_XML_DOCS
3098                         if (e->docsrc == AST_XML_DOC) {
3099                                 ast_free((char *) e->summary);
3100                                 ast_free((char *) e->usage);
3101                                 ast_free((char *) e->syntax);
3102                                 ast_free((char *) e->seealso);
3103                                 *((char **) &e->summary) = NULL;
3104                                 *((char **) &e->usage) = NULL;
3105                                 *((char **) &e->syntax) = NULL;
3106                                 *((char **) &e->seealso) = NULL;
3107                         }
3108 #endif
3109                         unregistered=1;
3110                         break;
3111                 }
3112         }
3113         AST_RWLIST_TRAVERSE_SAFE_END;
3114         AST_RWLIST_UNLOCK(&agi_commands);
3115         if (unregistered)
3116                 ast_verb(2, "AGI Command '%s' unregistered\n",fullcmd);
3117         else
3118                 ast_log(LOG_WARNING, "Unable to unregister command: '%s'!\n",fullcmd);
3119         return unregistered;
3120 }
3121
3122 int AST_OPTIONAL_API_NAME(ast_agi_register_multiple)(struct ast_module *mod, struct agi_command *cmd, unsigned int len)
3123 {
3124         unsigned int i, x = 0;
3125
3126         for (i = 0; i < len; i++) {
3127                 if (ast_agi_register(mod, cmd + i) == 1) {
3128                         x++;
3129                         continue;
3130                 }
3131
3132                 /* registration failed, unregister everything
3133                    that had been registered up to that point
3134                 */
3135                 for (; x > 0; x--) {
3136                         /* we are intentionally ignoring the
3137                            result of ast_agi_unregister() here,
3138                            but it should be safe to do so since
3139                            we just registered these commands and
3140                            the only possible way for unregistration
3141                            to fail is if the command is not
3142                            registered
3143                         */
3144                         (void) ast_agi_unregister(mod, cmd + x - 1);
3145                 }
3146                 return -1;
3147         }
3148
3149         return 0;
3150 }
3151
3152 int AST_OPTIONAL_API_NAME(ast_agi_unregister_multiple)(struct ast_module *mod, struct agi_command *cmd, unsigned int len)
3153 {
3154         unsigned int i;
3155         int res = 0;
3156
3157         for (i = 0; i < len; i++) {
3158                 /* remember whether any of the unregistration
3159                    attempts failed... there is no recourse if
3160                    any of them do
3161                 */
3162                 res |= ast_agi_unregister(mod, cmd + i);
3163         }
3164
3165         return res;
3166 }
3167
3168 static agi_command *find_command(const char * const cmds[], int exact)
3169 {
3170         int y, match;
3171         struct agi_command *e;
3172
3173         AST_RWLIST_RDLOCK(&agi_commands);
3174         AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
3175                 if (!e->cmda[0])
3176                         break;
3177                 /* start optimistic */
3178                 match = 1;
3179                 for (y = 0; match && cmds[y]; y++) {
3180                         /* If there are no more words in the command (and we're looking for
3181                            an exact match) or there is a difference between the two words,
3182                            then this is not a match */
3183                         if (!e->cmda[y] && !exact)
3184                                 break;
3185                         /* don't segfault if the next part of a command doesn't exist */
3186                         if (!e->cmda[y]) {
3187                                 AST_RWLIST_UNLOCK(&agi_commands);
3188                                 return NULL;
3189                         }
3190                         if (strcasecmp(e->cmda[y], cmds[y]))
3191                                 match = 0;
3192                 }
3193                 /* If more words are needed to complete the command then this is not
3194                    a candidate (unless we're looking for a really inexact answer  */
3195                 if ((exact > -1) && e->cmda[y])
3196                         match = 0;
3197                 if (match) {
3198                         AST_RWLIST_UNLOCK(&agi_commands);
3199                         return e;
3200                 }
3201         }
3202         AST_RWLIST_UNLOCK(&agi_commands);
3203         return NULL;
3204 }
3205
3206 static int parse_args(char *s, int *max, const char *argv[])
3207 {
3208         int x = 0, quoted = 0, escaped = 0, whitespace = 1;
3209         char *cur;
3210
3211         cur = s;
3212         while(*s) {
3213                 switch(*s) {
3214                 case '"':
3215                         /* If it's escaped, put a literal quote */
3216                         if (escaped)
3217                                 goto normal;
3218                         else
3219                                 quoted = !quoted;
3220                         if (quoted && whitespace) {
3221                                 /* If we're starting a quote, coming off white space start a new word, too */
3222                                 argv[x++] = cur;
3223                                 whitespace=0;
3224                         }
3225                         escaped = 0;
3226                 break;
3227                 case ' ':
3228                 case '\t':
3229                         if (!quoted && !escaped) {
3230                                 /* If we're not quoted, mark this as whitespace, and
3231                                    end the previous argument */
3232                                 whitespace = 1;
3233                                 *(cur++) = '\0';
3234                         } else
3235                                 /* Otherwise, just treat it as anything else */
3236                                 goto normal;
3237                         break;
3238                 case '\\':
3239                         /* If we're escaped, print a literal, otherwise enable escaping */
3240                         if (escaped) {
3241                                 goto normal;
3242                         } else {
3243                                 escaped=1;
3244                         }
3245                         break;
3246                 default:
3247 normal:
3248                         if (whitespace) {
3249                                 if (x >= MAX_ARGS -1) {
3250                                         ast_log(LOG_WARNING, "Too many arguments, truncating\n");
3251                                         break;
3252                                 }
3253                                 /* Coming off of whitespace, start the next argument */
3254                                 argv[x++] = cur;
3255                                 whitespace=0;
3256                         }
3257                         *(cur++) = *s;
3258                         escaped=0;
3259                 }
3260                 s++;
3261         }
3262         /* Null terminate */
3263         *(cur++) = '\0';
3264         argv[x] = NULL;
3265         *max = x;
3266         return 0;
3267 }
3268
3269 static enum agi_result agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int dead)
3270 {
3271         const char *argv[MAX_ARGS];
3272         int argc = MAX_ARGS, res;
3273         agi_command *c;
3274         const char *ami_res = "Unknown Result";
3275         char *ami_cmd = ast_strdupa(buf);
3276         int command_id = ast_random(), resultcode = 200;
3277
3278         manager_event(EVENT_FLAG_AGI, "AGIExec",
3279                         "SubEvent: Start\r\n"
3280                         "Channel: %s\r\n"
3281                         "CommandId: %d\r\n"
3282                         "Command: %s\r\n", chan->name, command_id, ami_cmd);
3283         parse_args(buf, &argc, argv);
3284         if ((c = find_command(argv, 0)) && (!dead || (dead && c->dead))) {
3285                 /* if this command wasnt registered by res_agi, be sure to usecount
3286                 the module we are using */
3287                 if (c->mod != ast_module_info->self)
3288                         ast_module_ref(c->mod);
3289                 /* If the AGI command being executed is an actual application (using agi exec)
3290                 the app field will be updated in pbx_exec via handle_exec */
3291                 if (chan->cdr && !ast_check_hangup(chan) && strcasecmp(argv[0], "EXEC"))
3292                         ast_cdr_setapp(chan->cdr, "AGI", buf);
3293
3294                 res = c->handler(chan, agi, argc, argv);
3295                 if (c->mod != ast_module_info->self)
3296                         ast_module_unref(c->mod);
3297                 switch (res) {
3298                 case RESULT_SHOWUSAGE: ami_res = "Usage"; resultcode = 520; break;
3299                 case RESULT_FAILURE: ami_res = "Failure"; resultcode = -1; break;
3300                 case RESULT_SUCCESS: ami_res = "Success"; resultcode = 200; break;
3301                 }
3302                 manager_event(EVENT_FLAG_AGI, "AGIExec",
3303                                 "SubEvent: End\r\n"
3304                                 "Channel: %s\r\n"
3305                                 "CommandId: %d\r\n"
3306                                 "Command: %s\r\n"
3307                                 "ResultCode: %d\r\n"
3308                                 "Result: %s\r\n", chan->name, command_id, ami_cmd, resultcode, ami_res);
3309                 switch(res) {
3310                 case RESULT_SHOWUSAGE:
3311                         if (ast_strlen_zero(c->usage)) {
3312                                 ast_agi_send(agi->fd, chan, "520 Invalid command syntax.  Proper usage not available.\n");
3313                         } else {
3314                                 ast_agi_send(agi->fd, chan, "520-Invalid command syntax.  Proper usage follows:\n");
3315                                 ast_agi_send(agi->fd, chan, "%s", c->usage);
3316                                 ast_agi_send(agi->fd, chan, "520 End of proper usage.\n");
3317                         }
3318                         break;
3319                 case RESULT_FAILURE:
3320                         /* The RESULT_FAILURE code is usually because the channel hungup. */
3321                         return AGI_RESULT_FAILURE;
3322                 default:
3323                         break;
3324                 }
3325         } else if ((c = find_command(argv, 0))) {
3326                 ast_agi_send(agi->fd, chan, "511 Command Not Permitted on a dead channel\n");
3327                 manager_event(EVENT_FLAG_AGI, "AGIExec",
3328                                 "SubEvent: End\r\n"
3329                                 "Channel: %s\r\n"
3330                                 "CommandId: %d\r\n"
3331                                 "Command: %s\r\n"
3332                                 "ResultCode: 511\r\n"
3333                                 "Result: Command not permitted on a dead channel\r\n", chan->name, command_id, ami_cmd);
3334         } else {
3335                 ast_agi_send(agi->fd, chan, "510 Invalid or unknown command\n");
3336                 manager_event(EVENT_FLAG_AGI, "AGIExec",
3337                                 "SubEvent: End\r\n"
3338                                 "Channel: %s\r\n"
3339                                 "CommandId: %d\r\n"
3340                                 "Command: %s\r\n"
3341                                 "ResultCode: 510\r\n"
3342                                 "Result: Invalid or unknown command\r\n", chan->name, command_id, ami_cmd);
3343         }
3344         return AGI_RESULT_SUCCESS;
3345 }
3346 static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid, int *status, int dead, int argc, char *argv[])
3347 {
3348         struct ast_channel *c;
3349         int outfd, ms, needhup = 0;
3350         enum agi_result returnstatus = AGI_RESULT_SUCCESS;
3351         struct ast_frame *f;
3352         char buf[AGI_BUF_LEN];
3353         char *res = NULL;
3354         FILE *readf;
3355         /* how many times we'll retry if ast_waitfor_nandfs will return without either
3356           channel or file descriptor in case select is interrupted by a system call (EINTR) */
3357         int retry = AGI_NANDFS_RETRY;
3358         int send_sighup;
3359         const char *sighup_str;
3360         
3361         ast_channel_lock(chan);
3362         sighup_str = pbx_builtin_getvar_helper(chan, "AGISIGHUP");
3363         send_sighup = ast_strlen_zero(sighup_str) || !ast_false(sighup_str);
3364         ast_channel_unlock(chan);
3365
3366         if (!(readf = fdopen(agi->ctrl, "r"))) {
3367                 ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
3368                 if (send_sighup && pid > -1)
3369                         kill(pid, SIGHUP);
3370                 close(agi->ctrl);
3371                 return AGI_RESULT_FAILURE;
3372         }
3373         
3374         setlinebuf(readf);
3375         setup_env(chan, request, agi->fd, (agi->audio > -1), argc, argv);
3376         for (;;) {
3377                 if (needhup) {
3378                         needhup = 0;
3379                         dead = 1;
3380                         if (send_sighup) {
3381                                 if (pid > -1) {
3382                                         kill(pid, SIGHUP);
3383                                 } else if (agi->fast) {
3384                                         send(agi->ctrl, "HANGUP\n", 7, 0);
3385                                 }
3386                         }
3387                 }
3388                 ms = -1;
3389                 if (dead) {
3390                         c = ast_waitfor_nandfds(&chan, 0, &agi->ctrl, 1, NULL, &outfd, &ms);
3391                 } else if (!ast_check_hangup(chan)) {
3392                         c = ast_waitfor_nandfds(&chan, 1, &agi->ctrl, 1, NULL, &outfd, &ms);
3393                 } else {
3394                         /*
3395                          * Read the channel control queue until it is dry so we can
3396                          * switch to dead mode.
3397                          */
3398                         c = chan;
3399                 }
3400                 if (c) {
3401                         retry = AGI_NANDFS_RETRY;
3402                         /* Idle the channel until we get a command */
3403                         f = ast_read(c);
3404                         if (!f) {
3405                                 ast_debug(1, "%s hungup\n", chan->name);
3406                                 needhup = 1;
3407                                 if (!returnstatus) {
3408                                         returnstatus = AGI_RESULT_HANGUP;
3409                                 }
3410                         } else {
3411                                 /* If it's voice, write it to the audio pipe */
3412                                 if ((agi->audio > -1) && (f->frametype == AST_FRAME_VOICE)) {
3413                                         /* Write, ignoring errors */
3414                                         if (write(agi->audio, f->data.ptr, f->datalen) < 0) {
3415                                         }
3416                                 }
3417                                 ast_frfree(f);
3418                         }
3419                 } else if (outfd > -1) {
3420                         size_t len = sizeof(buf);
3421                         size_t buflen = 0;
3422                         enum agi_result cmd_status;
3423
3424                         retry = AGI_NANDFS_RETRY;
3425                         buf[0] = '\0';
3426
3427                         while (len > 1) {
3428                                 res = fgets(buf + buflen, len, readf);
3429                                 if (feof(readf))
3430                                         break;
3431                                 if (ferror(readf) && ((errno != EINTR) && (errno != EAGAIN)))
3432                                         break;
3433                                 if (res != NULL && !agi->fast)
3434                                         break;
3435                                 buflen = strlen(buf);
3436                                 if (buflen && buf[buflen - 1] == '\n')
3437                                         break;
3438                                 len = sizeof(buf) - buflen;
3439                                 if (agidebug)
3440                                         ast_verbose( "AGI Rx << temp buffer %s - errno %s\n", buf, strerror(errno));
3441                         }
3442
3443                         if (!buf[0]) {
3444                                 /* Program terminated */
3445                                 ast_verb(3, "<%s>AGI Script %s completed, returning %d\n", chan->name, request, returnstatus);
3446                                 if (pid > 0)
3447                                         waitpid(pid, status, 0);
3448                                 /* No need to kill the pid anymore, since they closed us */
3449                                 pid = -1;
3450                                 break;
3451                         }
3452
3453                         /* Special case for inability to execute child process */
3454                         if (*buf && strncasecmp(buf, "failure", 7) == 0) {
3455                                 returnstatus = AGI_RESULT_FAILURE;
3456                                 break;
3457                         }
3458
3459                         /* get rid of trailing newline, if any */
3460                         if (*buf && buf[strlen(buf) - 1] == '\n')
3461                                 buf[strlen(buf) - 1] = 0;
3462                         if (agidebug)
3463                                 ast_verbose("<%s>AGI Rx << %s\n", chan->name, buf);
3464                         cmd_status = agi_handle_command(chan, agi, buf, dead);
3465                         switch (cmd_status) {
3466                         case AGI_RESULT_FAILURE:
3467                                 if (dead || !ast_check_hangup(chan)) {
3468                                         /* The failure was not because of a hangup. */
3469                                         returnstatus = AGI_RESULT_FAILURE;
3470                                 }
3471                                 break;
3472                         default:
3473                                 break;
3474                         }
3475                 } else {
3476                         if (--retry <= 0) {
3477                                 ast_log(LOG_WARNING, "No channel, no fd?\n");
3478