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