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