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