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