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