Fix documentation replication issues
[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 STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_exec_start_type);
1037 STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_exec_end_type);
1038 STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_async_start_type);
1039 STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_async_exec_type);
1040 STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_async_end_type);
1041
1042 static void agi_channel_manager_event(void *data,
1043         struct stasis_subscription *sub, struct stasis_topic *topic,
1044         struct stasis_message *message)
1045 {
1046         const char *type = data;
1047         struct ast_channel_blob *obj = stasis_message_data(message);
1048         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
1049         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
1050
1051         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
1052         if (!channel_event_string) {
1053                 return;
1054         }
1055
1056         event_string = ast_manager_str_from_json_object(obj->blob, NULL);
1057         if (!event_string) {
1058                 return;
1059         }
1060
1061         manager_event(EVENT_FLAG_AGI, type,
1062                 "%s"
1063                 "%s",
1064                 ast_str_buffer(channel_event_string),
1065                 ast_str_buffer(event_string));
1066 }
1067
1068 static agi_command *find_command(const char * const cmds[], int exact);
1069
1070 AST_THREADSTORAGE(agi_buf);
1071 #define AGI_BUF_INITSIZE 256
1072
1073 int AST_OPTIONAL_API_NAME(ast_agi_send)(int fd, struct ast_channel *chan, char *fmt, ...)
1074 {
1075         int res = 0;
1076         va_list ap;
1077         struct ast_str *buf;
1078
1079         if (!(buf = ast_str_thread_get(&agi_buf, AGI_BUF_INITSIZE)))
1080                 return -1;
1081
1082         va_start(ap, fmt);
1083         res = ast_str_set_va(&buf, 0, fmt, ap);
1084         va_end(ap);
1085
1086         if (res == -1) {
1087                 ast_log(LOG_ERROR, "Out of memory\n");
1088                 return -1;
1089         }
1090
1091         if (agidebug) {
1092                 if (chan) {
1093                         ast_verbose("<%s>AGI Tx >> %s", ast_channel_name(chan), ast_str_buffer(buf));
1094                 } else {
1095                         ast_verbose("AGI Tx >> %s", ast_str_buffer(buf));
1096                 }
1097         }
1098
1099         return ast_carefulwrite(fd, ast_str_buffer(buf), ast_str_strlen(buf), 100);
1100 }
1101
1102 /* linked list of AGI commands ready to be executed by Async AGI */
1103 struct agi_cmd {
1104         char *cmd_buffer;
1105         char *cmd_id;
1106         AST_LIST_ENTRY(agi_cmd) entry;
1107 };
1108
1109 static void free_agi_cmd(struct agi_cmd *cmd)
1110 {
1111         ast_free(cmd->cmd_buffer);
1112         ast_free(cmd->cmd_id);
1113         ast_free(cmd);
1114 }
1115
1116 /* AGI datastore destructor */
1117 static void agi_destroy_commands_cb(void *data)
1118 {
1119         struct agi_cmd *cmd;
1120         AST_LIST_HEAD(, agi_cmd) *chan_cmds = data;
1121         AST_LIST_LOCK(chan_cmds);
1122         while ( (cmd = AST_LIST_REMOVE_HEAD(chan_cmds, entry)) ) {
1123                 free_agi_cmd(cmd);
1124         }
1125         AST_LIST_UNLOCK(chan_cmds);
1126         AST_LIST_HEAD_DESTROY(chan_cmds);
1127         ast_free(chan_cmds);
1128 }
1129
1130 /* channel datastore to keep the queue of AGI commands in the channel */
1131 static const struct ast_datastore_info agi_commands_datastore_info = {
1132         .type = "AsyncAGI",
1133         .destroy = agi_destroy_commands_cb
1134 };
1135
1136 /*!
1137  * \brief Retrieve the list head to the requested channel's AGI datastore
1138  * \param chan Channel datastore is requested for
1139  * \param cmd Pointer to the struct pointer which will reference the head of the agi command list.
1140  *
1141  * \retval 0 if the datastore was valid and the list head was retrieved appropriately (even if it's
1142  *           NULL and the list is empty)
1143  * \retval -1 if the datastore could not be retrieved causing an error
1144 */
1145 static int get_agi_cmd(struct ast_channel *chan, struct agi_cmd **cmd)
1146 {
1147         struct ast_datastore *store;
1148         AST_LIST_HEAD(, agi_cmd) *agi_commands;
1149
1150         ast_channel_lock(chan);
1151         store = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
1152         ast_channel_unlock(chan);
1153         if (!store) {
1154                 ast_log(LOG_ERROR, "Huh? Async AGI datastore disappeared on Channel %s!\n",
1155                         ast_channel_name(chan));
1156                 *cmd = NULL;
1157                 return -1;
1158         }
1159         agi_commands = store->data;
1160         AST_LIST_LOCK(agi_commands);
1161         *cmd = AST_LIST_REMOVE_HEAD(agi_commands, entry);
1162         AST_LIST_UNLOCK(agi_commands);
1163         return 0;
1164 }
1165
1166 /* channel is locked when calling this one either from the CLI or manager thread */
1167 static int add_agi_cmd(struct ast_channel *chan, const char *cmd_buff, const char *cmd_id)
1168 {
1169         struct ast_datastore *store;
1170         struct agi_cmd *cmd;
1171         AST_LIST_HEAD(, agi_cmd) *agi_commands;
1172
1173         store = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
1174         if (!store) {
1175                 ast_log(LOG_WARNING, "Channel %s is not setup for Async AGI.\n", ast_channel_name(chan));
1176                 return -1;
1177         }
1178         agi_commands = store->data;
1179         cmd = ast_calloc(1, sizeof(*cmd));
1180         if (!cmd) {
1181                 return -1;
1182         }
1183         cmd->cmd_buffer = ast_strdup(cmd_buff);
1184         if (!cmd->cmd_buffer) {
1185                 ast_free(cmd);
1186                 return -1;
1187         }
1188         cmd->cmd_id = ast_strdup(cmd_id);
1189         if (!cmd->cmd_id) {
1190                 ast_free(cmd->cmd_buffer);
1191                 ast_free(cmd);
1192                 return -1;
1193         }
1194         AST_LIST_LOCK(agi_commands);
1195         AST_LIST_INSERT_TAIL(agi_commands, cmd, entry);
1196         AST_LIST_UNLOCK(agi_commands);
1197         return 0;
1198 }
1199
1200 static int add_to_agi(struct ast_channel *chan)
1201 {
1202         struct ast_datastore *datastore;
1203         AST_LIST_HEAD(, agi_cmd) *agi_cmds_list;
1204
1205         /* check if already on AGI */
1206         ast_channel_lock(chan);
1207         datastore = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
1208         ast_channel_unlock(chan);
1209         if (datastore) {
1210                 /* we already have an AGI datastore, let's just
1211                    return success */
1212                 return 0;
1213         }
1214
1215         /* the channel has never been on Async AGI,
1216            let's allocate it's datastore */
1217         datastore = ast_datastore_alloc(&agi_commands_datastore_info, "AGI");
1218         if (!datastore) {
1219                 return -1;
1220         }
1221         agi_cmds_list = ast_calloc(1, sizeof(*agi_cmds_list));
1222         if (!agi_cmds_list) {
1223                 ast_log(LOG_ERROR, "Unable to allocate Async AGI commands list.\n");
1224                 ast_datastore_free(datastore);
1225                 return -1;
1226         }
1227         datastore->data = agi_cmds_list;
1228         AST_LIST_HEAD_INIT(agi_cmds_list);
1229         ast_channel_lock(chan);
1230         ast_channel_datastore_add(chan, datastore);
1231         ast_channel_unlock(chan);
1232         return 0;
1233 }
1234
1235 /*!
1236  * \brief CLI command to add applications to execute in Async AGI
1237  * \param e
1238  * \param cmd
1239  * \param a
1240  *
1241  * \retval CLI_SUCCESS on success
1242  * \retval NULL when init or tab completion is used
1243 */
1244 static char *handle_cli_agi_add_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1245 {
1246         struct ast_channel *chan;
1247         switch (cmd) {
1248         case CLI_INIT:
1249                 e->command = "agi exec";
1250                 e->usage = "Usage: agi exec <channel name> <app and arguments> [id]\n"
1251                            "       Add AGI command to the execute queue of the specified channel in Async AGI\n";
1252                 return NULL;
1253         case CLI_GENERATE:
1254                 if (a->pos == 2)
1255                         return ast_complete_channels(a->line, a->word, a->pos, a->n, 2);
1256                 return NULL;
1257         }
1258
1259         if (a->argc < 4) {
1260                 return CLI_SHOWUSAGE;
1261         }
1262
1263         if (!(chan = ast_channel_get_by_name(a->argv[2]))) {
1264                 ast_cli(a->fd, "Channel %s does not exist.\n", a->argv[2]);
1265                 return CLI_FAILURE;
1266         }
1267
1268         ast_channel_lock(chan);
1269
1270         if (add_agi_cmd(chan, a->argv[3], (a->argc > 4 ? a->argv[4] : ""))) {
1271                 ast_cli(a->fd, "Failed to add AGI command to queue of channel %s\n", ast_channel_name(chan));
1272                 ast_channel_unlock(chan);
1273                 chan = ast_channel_unref(chan);
1274                 return CLI_FAILURE;
1275         }
1276
1277         ast_debug(1, "Added AGI command to channel %s queue\n", ast_channel_name(chan));
1278
1279         ast_channel_unlock(chan);
1280         chan = ast_channel_unref(chan);
1281
1282         return CLI_SUCCESS;
1283 }
1284
1285 /*!
1286  * \brief Add a new command to execute by the Async AGI application
1287  * \param s
1288  * \param m
1289  *
1290  * It will append the application to the specified channel's queue
1291  * if the channel is not inside Async AGI application it will return an error
1292  * \retval 0 on success or incorrect use
1293  * \retval 1 on failure to add the command ( most likely because the channel
1294  * is not in Async AGI loop )
1295 */
1296 static int action_add_agi_cmd(struct mansession *s, const struct message *m)
1297 {
1298         const char *channel = astman_get_header(m, "Channel");
1299         const char *cmdbuff = astman_get_header(m, "Command");
1300         const char *cmdid   = astman_get_header(m, "CommandID");
1301         struct ast_channel *chan;
1302         char buf[256];
1303
1304         if (ast_strlen_zero(channel) || ast_strlen_zero(cmdbuff)) {
1305                 astman_send_error(s, m, "Both, Channel and Command are *required*");
1306                 return 0;
1307         }
1308
1309         if (!(chan = ast_channel_get_by_name(channel))) {
1310                 snprintf(buf, sizeof(buf), "Channel %s does not exist.", channel);
1311                 astman_send_error(s, m, buf);
1312                 return 0;
1313         }
1314
1315         ast_channel_lock(chan);
1316
1317         if (add_agi_cmd(chan, cmdbuff, cmdid)) {
1318                 snprintf(buf, sizeof(buf), "Failed to add AGI command to channel %s queue", ast_channel_name(chan));
1319                 astman_send_error(s, m, buf);
1320                 ast_channel_unlock(chan);
1321                 chan = ast_channel_unref(chan);
1322                 return 0;
1323         }
1324
1325         ast_channel_unlock(chan);
1326         chan = ast_channel_unref(chan);
1327
1328         astman_send_ack(s, m, "Added AGI command to queue");
1329
1330         return 0;
1331 }
1332
1333 static enum agi_result agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int dead);
1334 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced, int argc, char *argv[]);
1335
1336 /*!
1337  * \internal
1338  * \brief Read and handle a channel frame for Async AGI.
1339  *
1340  * \param chan Channel to read a frame from.
1341  *
1342  * \retval AGI_RESULT_SUCCESS on success.
1343  * \retval AGI_RESULT_HANGUP on hangup.
1344  * \retval AGI_RESULT_FAILURE on error.
1345  */
1346 static enum agi_result async_agi_read_frame(struct ast_channel *chan)
1347 {
1348         struct ast_frame *f;
1349
1350         f = ast_read(chan);
1351         if (!f) {
1352                 ast_debug(3, "No frame read on channel %s, going out ...\n", ast_channel_name(chan));
1353                 return AGI_RESULT_HANGUP;
1354         }
1355         if (f->frametype == AST_FRAME_CONTROL) {
1356                 /*
1357                  * Is there any other frame we should care about besides
1358                  * AST_CONTROL_HANGUP?
1359                  */
1360                 switch (f->subclass.integer) {
1361                 case AST_CONTROL_HANGUP:
1362                         ast_debug(3, "Got HANGUP frame on channel %s, going out ...\n", ast_channel_name(chan));
1363                         ast_frfree(f);
1364                         return AGI_RESULT_HANGUP;
1365                 default:
1366                         break;
1367                 }
1368         }
1369         ast_frfree(f);
1370
1371         return AGI_RESULT_SUCCESS;
1372 }
1373
1374 static enum agi_result launch_asyncagi(struct ast_channel *chan, int argc, char *argv[], int *efd)
1375 {
1376 /* This buffer sizes might cause truncation if the AGI command writes more data
1377    than AGI_BUF_SIZE as result. But let's be serious, is there an AGI command
1378    that writes a response larger than 1024 bytes?, I don't think so, most of
1379    them are just result=blah stuff. However probably if GET VARIABLE is called
1380    and the variable has large amount of data, that could be a problem. We could
1381    make this buffers dynamic, but let's leave that as a second step.
1382
1383    AMI_BUF_SIZE is twice AGI_BUF_SIZE just for the sake of choosing a safe
1384    number. Some characters of AGI buf will be url encoded to be sent to manager
1385    clients.  An URL encoded character will take 3 bytes, but again, to cause
1386    truncation more than about 70% of the AGI buffer should be URL encoded for
1387    that to happen.  Not likely at all.
1388
1389    On the other hand. I wonder if read() could eventually return less data than
1390    the amount already available in the pipe? If so, how to deal with that?
1391    So far, my tests on Linux have not had any problems.
1392  */
1393 #define AGI_BUF_SIZE 1024
1394 #define AMI_BUF_SIZE 2048
1395         enum agi_result cmd_status;
1396         struct agi_cmd *cmd;
1397         int res;
1398         int fds[2];
1399         int hungup;
1400         int timeout = 100;
1401         char agi_buffer[AGI_BUF_SIZE + 1];
1402         char ami_buffer[AMI_BUF_SIZE];
1403         enum agi_result returnstatus = AGI_RESULT_SUCCESS;
1404         AGI async_agi;
1405         RAII_VAR(struct ast_json *, startblob, NULL, ast_json_unref);
1406
1407         if (efd) {
1408                 ast_log(LOG_WARNING, "Async AGI does not support Enhanced AGI yet\n");
1409                 return AGI_RESULT_FAILURE;
1410         }
1411
1412         /* add AsyncAGI datastore to the channel */
1413         if (add_to_agi(chan)) {
1414                 ast_log(LOG_ERROR, "Failed to start Async AGI on channel %s\n", ast_channel_name(chan));
1415                 return AGI_RESULT_FAILURE;
1416         }
1417
1418         /* this pipe allows us to create a "fake" AGI struct to use
1419            the AGI commands */
1420         res = pipe(fds);
1421         if (res) {
1422                 ast_log(LOG_ERROR, "Failed to create Async AGI pipe\n");
1423                 /*
1424                  * Intentionally do not remove the datastore added with
1425                  * add_to_agi() the from channel.  It will be removed when the
1426                  * channel is hung up anyway.
1427                  */
1428                 return AGI_RESULT_FAILURE;
1429         }
1430
1431         /* handlers will get the pipe write fd and we read the AGI responses
1432            from the pipe read fd */
1433         async_agi.fd = fds[1];
1434         async_agi.ctrl = fds[1];
1435         async_agi.audio = -1; /* no audio support */
1436         async_agi.fast = 0;
1437         async_agi.speech = NULL;
1438
1439         /* notify possible manager users of a new channel ready to
1440            receive commands */
1441         setup_env(chan, "async", fds[1], 0, argc, argv);
1442         /* read the environment */
1443         res = read(fds[0], agi_buffer, AGI_BUF_SIZE);
1444         if (res <= 0) {
1445                 ast_log(LOG_ERROR, "Failed to read from Async AGI pipe on channel %s: %s\n",
1446                                 ast_channel_name(chan), res < 0 ? strerror(errno) : "EOF");
1447                 returnstatus = AGI_RESULT_FAILURE;
1448                 goto async_agi_abort;
1449         }
1450         agi_buffer[res] = '\0';
1451         /* encode it and send it thru the manager so whoever is going to take
1452            care of AGI commands on this channel can decide which AGI commands
1453            to execute based on the setup info */
1454         ast_uri_encode(agi_buffer, ami_buffer, AMI_BUF_SIZE, ast_uri_http);
1455         startblob = ast_json_pack("{s: s}", "Env", ami_buffer);
1456         ast_channel_publish_blob(chan, agi_async_start_type(), startblob);
1457
1458         hungup = ast_check_hangup(chan);
1459         for (;;) {
1460                 /*
1461                  * Process as many commands as we can.  Commands are added via
1462                  * the manager or the cli threads.
1463                  */
1464                 while (!hungup) {
1465                         RAII_VAR(struct ast_json *, execblob, NULL, ast_json_unref);
1466                         res = get_agi_cmd(chan, &cmd);
1467
1468                         if (res) {
1469                                 returnstatus = AGI_RESULT_FAILURE;
1470                                 goto async_agi_done;
1471                         } else if (!cmd) {
1472                                 break;
1473                         }
1474
1475                         /* OK, we have a command, let's call the command handler. */
1476                         cmd_status = agi_handle_command(chan, &async_agi, cmd->cmd_buffer, 0);
1477
1478                         /*
1479                          * The command handler must have written to our fake AGI struct
1480                          * fd (the pipe), let's read the response.
1481                          */
1482                         res = read(fds[0], agi_buffer, AGI_BUF_SIZE);
1483                         if (res <= 0) {
1484                                 ast_log(LOG_ERROR, "Failed to read from Async AGI pipe on channel %s: %s\n",
1485                                         ast_channel_name(chan), res < 0 ? strerror(errno) : "EOF");
1486                                 free_agi_cmd(cmd);
1487                                 returnstatus = AGI_RESULT_FAILURE;
1488                                 goto async_agi_done;
1489                         }
1490                         /*
1491                          * We have a response, let's send the response thru the manager.
1492                          * Include the CommandID if it was specified when the command
1493                          * was added.
1494                          */
1495                         agi_buffer[res] = '\0';
1496                         ast_uri_encode(agi_buffer, ami_buffer, AMI_BUF_SIZE, ast_uri_http);
1497
1498                         execblob = ast_json_pack("{s: s}", "Result", ami_buffer);
1499                         if (execblob && !ast_strlen_zero(cmd->cmd_id)) {
1500                                 ast_json_object_set(execblob, "CommandId", ast_json_string_create(cmd->cmd_id));
1501                         }
1502                         ast_channel_publish_blob(chan, agi_async_exec_type(), execblob);
1503
1504                         free_agi_cmd(cmd);
1505
1506                         /*
1507                          * Check the command status to determine if we should continue
1508                          * executing more commands.
1509                          */
1510                         hungup = ast_check_hangup(chan);
1511                         switch (cmd_status) {
1512                         case AGI_RESULT_FAILURE:
1513                                 if (!hungup) {
1514                                         /* The failure was not because of a hangup. */
1515                                         returnstatus = AGI_RESULT_FAILURE;
1516                                         goto async_agi_done;
1517                                 }
1518                                 break;
1519                         case AGI_RESULT_SUCCESS_ASYNC:
1520                                 /* Only the "asyncagi break" command does this. */
1521                                 returnstatus = AGI_RESULT_SUCCESS_ASYNC;
1522                                 goto async_agi_done;
1523                         default:
1524                                 break;
1525                         }
1526                 }
1527
1528                 if (!hungup) {
1529                         /* Wait a bit for a frame to read or to poll for a new command. */
1530                         res = ast_waitfor(chan, timeout);
1531                         if (res < 0) {
1532                                 ast_debug(1, "ast_waitfor returned <= 0 on chan %s\n", ast_channel_name(chan));
1533                                 returnstatus = AGI_RESULT_FAILURE;
1534                                 break;
1535                         }
1536                 } else {
1537                         /*
1538                          * Read the channel control queue until it is dry so we can
1539                          * quit.
1540                          */
1541                         res = 1;
1542                 }
1543                 if (0 < res) {
1544                         do {
1545                                 cmd_status = async_agi_read_frame(chan);
1546                                 if (cmd_status != AGI_RESULT_SUCCESS) {
1547                                         returnstatus = cmd_status;
1548                                         goto async_agi_done;
1549                                 }
1550                                 hungup = ast_check_hangup(chan);
1551                         } while (hungup);
1552                 } else {
1553                         hungup = ast_check_hangup(chan);
1554                 }
1555         }
1556 async_agi_done:
1557
1558         if (async_agi.speech) {
1559                 ast_speech_destroy(async_agi.speech);
1560         }
1561         /* notify manager users this channel cannot be controlled anymore by Async AGI */
1562         ast_channel_publish_blob(chan, agi_async_end_type(), NULL);
1563
1564 async_agi_abort:
1565         /* close the pipe */
1566         close(fds[0]);
1567         close(fds[1]);
1568
1569         /*
1570          * Intentionally do not remove the datastore added with
1571          * add_to_agi() the from channel.  There might be commands still
1572          * in the queue or in-flight to us and AsyncAGI may get called
1573          * again.  The datastore destructor will be called on channel
1574          * destruction anyway.
1575          */
1576
1577         if (returnstatus == AGI_RESULT_SUCCESS) {
1578                 returnstatus = AGI_RESULT_SUCCESS_ASYNC;
1579         }
1580         return returnstatus;
1581
1582 #undef AGI_BUF_SIZE
1583 #undef AMI_BUF_SIZE
1584 }
1585
1586 /*!
1587  * \internal
1588  * \brief Handle the connection that was started by launch_netscript.
1589  *
1590  * \param agiurl Url that we are trying to connect to.
1591  * \param addr Address that host was resolved to.
1592  * \param netsockfd File descriptor of socket.
1593  *
1594  * \retval 0 when connection is succesful.
1595  * \retval 1 when there is an error.
1596  */
1597 static int handle_connection(const char *agiurl, const struct ast_sockaddr addr, const int netsockfd)
1598 {
1599         struct pollfd pfds[1];
1600         int res, conresult;
1601         socklen_t reslen;
1602
1603         reslen = sizeof(conresult);
1604
1605         pfds[0].fd = netsockfd;
1606         pfds[0].events = POLLOUT;
1607
1608         while ((res = ast_poll(pfds, 1, MAX_AGI_CONNECT)) != 1) {
1609                 if (errno != EINTR) {
1610                         if (!res) {
1611                                 ast_log(LOG_WARNING, "FastAGI connection to '%s' timed out after MAX_AGI_CONNECT (%d) milliseconds.\n",
1612                                         agiurl, MAX_AGI_CONNECT);
1613                         } else {
1614                                 ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
1615                         }
1616
1617                         return 1;
1618                 }
1619         }
1620
1621         if (getsockopt(pfds[0].fd, SOL_SOCKET, SO_ERROR, &conresult, &reslen) < 0) {
1622                 ast_log(LOG_WARNING, "Connection to %s failed with error: %s\n",
1623                         ast_sockaddr_stringify(&addr), strerror(errno));
1624                 return 1;
1625         }
1626
1627         if (conresult) {
1628                 ast_log(LOG_WARNING, "Connecting to '%s' failed for url '%s': %s\n",
1629                         ast_sockaddr_stringify(&addr), agiurl, strerror(conresult));
1630                 return 1;
1631         }
1632
1633         return 0;
1634 }
1635
1636 /* launch_netscript: The fastagi handler.
1637         FastAGI defaults to port 4573 */
1638 static enum agi_result launch_netscript(char *agiurl, char *argv[], int *fds)
1639 {
1640         int s = 0, flags;
1641         char *host, *script;
1642         int num_addrs = 0, i = 0;
1643         struct ast_sockaddr *addrs;
1644
1645         /* agiurl is "agi://host.domain[:port][/script/name]" */
1646         host = ast_strdupa(agiurl + 6); /* Remove agi:// */
1647
1648         /* Strip off any script name */
1649         if ((script = strchr(host, '/'))) {
1650                 *script++ = '\0';
1651         } else {
1652                 script = "";
1653         }
1654
1655         if (!(num_addrs = ast_sockaddr_resolve(&addrs, host, 0, AST_AF_UNSPEC))) {
1656                 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", host);
1657                 return AGI_RESULT_FAILURE;
1658         }
1659
1660         for (i = 0; i < num_addrs; i++) {
1661                 if (!ast_sockaddr_port(&addrs[i])) {
1662                         ast_sockaddr_set_port(&addrs[i], AGI_PORT);
1663                 }
1664
1665                 if ((s = socket(addrs[i].ss.ss_family, SOCK_STREAM, IPPROTO_TCP)) < 0) {
1666                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1667                         continue;
1668                 }
1669
1670                 if ((flags = fcntl(s, F_GETFL)) < 0) {
1671                         ast_log(LOG_WARNING, "fcntl(F_GETFL) failed: %s\n", strerror(errno));
1672                         close(s);
1673                         continue;
1674                 }
1675
1676                 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0) {
1677                         ast_log(LOG_WARNING, "fnctl(F_SETFL) failed: %s\n", strerror(errno));
1678                         close(s);
1679                         continue;
1680                 }
1681
1682                 if (ast_connect(s, &addrs[i]) && errno == EINPROGRESS) {
1683
1684                         if (handle_connection(agiurl, addrs[i], s)) {
1685                                 close(s);
1686                                 continue;
1687                         }
1688
1689                 } else {
1690                         ast_log(LOG_WARNING, "Connection to %s failed with unexpected error: %s\n",
1691                         ast_sockaddr_stringify(&addrs[i]), strerror(errno));
1692                 }
1693
1694                 break;
1695         }
1696
1697         ast_free(addrs);
1698
1699         if (i == num_addrs) {
1700                 ast_log(LOG_WARNING, "Couldn't connect to any host.  FastAGI failed.\n");
1701                 return AGI_RESULT_FAILURE;
1702         }
1703
1704         if (ast_agi_send(s, NULL, "agi_network: yes\n") < 0) {
1705                 if (errno != EINTR) {
1706                         ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
1707                         close(s);
1708                         return AGI_RESULT_FAILURE;
1709                 }
1710         }
1711
1712         /* If we have a script parameter, relay it to the fastagi server */
1713         /* Script parameters take the form of: AGI(agi://my.example.com/?extension=${EXTEN}) */
1714         if (!ast_strlen_zero(script)) {
1715                 ast_agi_send(s, NULL, "agi_network_script: %s\n", script);
1716         }
1717
1718         ast_debug(4, "Wow, connected!\n");
1719         fds[0] = s;
1720         fds[1] = s;
1721         return AGI_RESULT_SUCCESS_FAST;
1722 }
1723
1724 /*!
1725  * \internal
1726  * \brief The HA fastagi handler.
1727  * \param agiurl The request URL as passed to Agi() in the dial plan
1728  * \param argv The parameters after the URL passed to Agi() in the dial plan
1729  * \param fds Input/output file descriptors
1730  *
1731  * Uses SRV lookups to try to connect to a list of FastAGI servers. The hostname in
1732  * the URI is prefixed with _agi._tcp. prior to the DNS resolution. For
1733  * example, if you specify the URI \a hagi://agi.example.com/foo.agi the DNS
1734  * query would be for \a _agi._tcp.agi.example.com and you'll need to make sure
1735  * this resolves.
1736  *
1737  * This function parses the URI, resolves the SRV service name, forms new URIs
1738  * with the results of the DNS lookup, and then calls launch_netscript on the
1739  * new URIs until one succeeds.
1740  *
1741  * \return the result of the AGI operation.
1742  */
1743 static enum agi_result launch_ha_netscript(char *agiurl, char *argv[], int *fds)
1744 {
1745         char *host, *script;
1746         enum agi_result result;
1747         struct srv_context *context = NULL;
1748         int srv_ret;
1749         char service[256];
1750         char resolved_uri[1024];
1751         const char *srvhost;
1752         unsigned short srvport;
1753
1754         /* format of agiurl is "hagi://host.domain[:port][/script/name]" */
1755         if (strlen(agiurl) < 7) { /* Remove hagi:// */
1756                 ast_log(LOG_WARNING, "An error occurred parsing the AGI URI: %s", agiurl);
1757                 return AGI_RESULT_FAILURE;
1758         }
1759         host = ast_strdupa(agiurl + 7);
1760
1761         /* Strip off any script name */
1762         if ((script = strchr(host, '/'))) {
1763                 *script++ = '\0';
1764         } else {
1765                 script = "";
1766         }
1767
1768         if (strchr(host, ':')) {
1769                 ast_log(LOG_WARNING, "Specifying a port number disables SRV lookups: %s\n", agiurl);
1770                 return launch_netscript(agiurl + 1, argv, fds); /* +1 to strip off leading h from hagi:// */
1771         }
1772
1773         snprintf(service, sizeof(service), "%s%s", SRV_PREFIX, host);
1774
1775         while (!(srv_ret = ast_srv_lookup(&context, service, &srvhost, &srvport))) {
1776                 snprintf(resolved_uri, sizeof(resolved_uri), "agi://%s:%d/%s", srvhost, srvport, script);
1777                 result = launch_netscript(resolved_uri, argv, fds);
1778                 if (result == AGI_RESULT_FAILURE || result == AGI_RESULT_NOTFOUND) {
1779                         ast_log(LOG_WARNING, "AGI request failed for host '%s' (%s:%d)\n", host, srvhost, srvport);
1780                 } else {
1781                         /* The script launched so we must cleanup the context. */
1782                         ast_srv_cleanup(&context);
1783                         return result;
1784                 }
1785         }
1786         /*
1787          * The DNS SRV lookup failed or we ran out of servers to check.
1788          * ast_srv_lookup() has already cleaned up the context for us.
1789          */
1790         if (srv_ret < 0) {
1791                 ast_log(LOG_WARNING, "SRV lookup failed for %s\n", agiurl);
1792         }
1793
1794         return AGI_RESULT_FAILURE;
1795 }
1796
1797 static enum agi_result launch_script(struct ast_channel *chan, char *script, int argc, char *argv[], int *fds, int *efd, int *opid)
1798 {
1799         char tmp[256];
1800         int pid, toast[2], fromast[2], audio[2], res;
1801         struct stat st;
1802
1803         if (!strncasecmp(script, "agi://", 6)) {
1804                 return (efd == NULL) ? launch_netscript(script, argv, fds) : AGI_RESULT_FAILURE;
1805         }
1806         if (!strncasecmp(script, "hagi://", 7)) {
1807                 return (efd == NULL) ? launch_ha_netscript(script, argv, fds) : AGI_RESULT_FAILURE;
1808         }
1809         if (!strncasecmp(script, "agi:async", sizeof("agi:async") - 1)) {
1810                 return launch_asyncagi(chan, argc, argv, efd);
1811         }
1812
1813         if (script[0] != '/') {
1814                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_AGI_DIR, script);
1815                 script = tmp;
1816         }
1817
1818         /* Before even trying let's see if the file actually exists */
1819         if (stat(script, &st)) {
1820                 ast_log(LOG_WARNING, "Failed to execute '%s': File does not exist.\n", script);
1821                 return AGI_RESULT_NOTFOUND;
1822         }
1823
1824         if (pipe(toast)) {
1825                 ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
1826                 return AGI_RESULT_FAILURE;
1827         }
1828         if (pipe(fromast)) {
1829                 ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
1830                 close(toast[0]);
1831                 close(toast[1]);
1832                 return AGI_RESULT_FAILURE;
1833         }
1834         if (efd) {
1835                 if (pipe(audio)) {
1836                         ast_log(LOG_WARNING, "unable to create audio pipe: %s\n", strerror(errno));
1837                         close(fromast[0]);
1838                         close(fromast[1]);
1839                         close(toast[0]);
1840                         close(toast[1]);
1841                         return AGI_RESULT_FAILURE;
1842                 }
1843                 res = fcntl(audio[1], F_GETFL);
1844                 if (res > -1)
1845                         res = fcntl(audio[1], F_SETFL, res | O_NONBLOCK);
1846                 if (res < 0) {
1847                         ast_log(LOG_WARNING, "unable to set audio pipe parameters: %s\n", strerror(errno));
1848                         close(fromast[0]);
1849                         close(fromast[1]);
1850                         close(toast[0]);
1851                         close(toast[1]);
1852                         close(audio[0]);
1853                         close(audio[1]);
1854                         return AGI_RESULT_FAILURE;
1855                 }
1856         }
1857
1858         if ((pid = ast_safe_fork(1)) < 0) {
1859                 ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
1860                 return AGI_RESULT_FAILURE;
1861         }
1862         if (!pid) {
1863                 /* Pass paths to AGI via environmental variables */
1864                 setenv("AST_CONFIG_DIR", ast_config_AST_CONFIG_DIR, 1);
1865                 setenv("AST_CONFIG_FILE", ast_config_AST_CONFIG_FILE, 1);
1866                 setenv("AST_MODULE_DIR", ast_config_AST_MODULE_DIR, 1);
1867                 setenv("AST_SPOOL_DIR", ast_config_AST_SPOOL_DIR, 1);
1868                 setenv("AST_MONITOR_DIR", ast_config_AST_MONITOR_DIR, 1);
1869                 setenv("AST_VAR_DIR", ast_config_AST_VAR_DIR, 1);
1870                 setenv("AST_DATA_DIR", ast_config_AST_DATA_DIR, 1);
1871                 setenv("AST_LOG_DIR", ast_config_AST_LOG_DIR, 1);
1872                 setenv("AST_AGI_DIR", ast_config_AST_AGI_DIR, 1);
1873                 setenv("AST_KEY_DIR", ast_config_AST_KEY_DIR, 1);
1874                 setenv("AST_RUN_DIR", ast_config_AST_RUN_DIR, 1);
1875
1876                 /* Don't run AGI scripts with realtime priority -- it causes audio stutter */
1877                 ast_set_priority(0);
1878
1879                 /* Redirect stdin and out, provide enhanced audio channel if desired */
1880                 dup2(fromast[0], STDIN_FILENO);
1881                 dup2(toast[1], STDOUT_FILENO);
1882                 if (efd)
1883                         dup2(audio[0], STDERR_FILENO + 1);
1884                 else
1885                         close(STDERR_FILENO + 1);
1886
1887                 /* Close everything but stdin/out/error */
1888                 ast_close_fds_above_n(STDERR_FILENO + 1);
1889
1890                 /* Execute script */
1891                 /* XXX argv should be deprecated in favor of passing agi_argX paramaters */
1892                 execv(script, argv);
1893                 /* Can't use ast_log since FD's are closed */
1894                 ast_child_verbose(1, "Failed to execute '%s': %s", script, strerror(errno));
1895                 /* Special case to set status of AGI to failure */
1896                 fprintf(stdout, "failure\n");
1897                 fflush(stdout);
1898                 _exit(1);
1899         }
1900         ast_verb(3, "Launched AGI Script %s\n", script);
1901         fds[0] = toast[0];
1902         fds[1] = fromast[1];
1903         if (efd)
1904                 *efd = audio[1];
1905         /* close what we're not using in the parent */
1906         close(toast[1]);
1907         close(fromast[0]);
1908
1909         if (efd)
1910                 close(audio[0]);
1911
1912         *opid = pid;
1913         return AGI_RESULT_SUCCESS;
1914 }
1915
1916 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced, int argc, char *argv[])
1917 {
1918         int count;
1919
1920         /* Print initial environment, with agi_request always being the first
1921            thing */
1922         ast_agi_send(fd, chan, "agi_request: %s\n", request);
1923         ast_agi_send(fd, chan, "agi_channel: %s\n", ast_channel_name(chan));
1924         ast_agi_send(fd, chan, "agi_language: %s\n", ast_channel_language(chan));
1925         ast_agi_send(fd, chan, "agi_type: %s\n", ast_channel_tech(chan)->type);
1926         ast_agi_send(fd, chan, "agi_uniqueid: %s\n", ast_channel_uniqueid(chan));
1927         ast_agi_send(fd, chan, "agi_version: %s\n", ast_get_version());
1928
1929         /* ANI/DNIS */
1930         ast_agi_send(fd, chan, "agi_callerid: %s\n",
1931                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "unknown"));
1932         ast_agi_send(fd, chan, "agi_calleridname: %s\n",
1933                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "unknown"));
1934         ast_agi_send(fd, chan, "agi_callingpres: %d\n",
1935                 ast_party_id_presentation(&ast_channel_caller(chan)->id));
1936         ast_agi_send(fd, chan, "agi_callingani2: %d\n", ast_channel_caller(chan)->ani2);
1937         ast_agi_send(fd, chan, "agi_callington: %d\n", ast_channel_caller(chan)->id.number.plan);
1938         ast_agi_send(fd, chan, "agi_callingtns: %d\n", ast_channel_dialed(chan)->transit_network_select);
1939         ast_agi_send(fd, chan, "agi_dnid: %s\n", S_OR(ast_channel_dialed(chan)->number.str, "unknown"));
1940         ast_agi_send(fd, chan, "agi_rdnis: %s\n",
1941                 S_COR(ast_channel_redirecting(chan)->from.number.valid, ast_channel_redirecting(chan)->from.number.str, "unknown"));
1942
1943         /* Context information */
1944         ast_agi_send(fd, chan, "agi_context: %s\n", ast_channel_context(chan));
1945         ast_agi_send(fd, chan, "agi_extension: %s\n", ast_channel_exten(chan));
1946         ast_agi_send(fd, chan, "agi_priority: %d\n", ast_channel_priority(chan));
1947         ast_agi_send(fd, chan, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
1948
1949         /* User information */
1950         ast_agi_send(fd, chan, "agi_accountcode: %s\n", ast_channel_accountcode(chan) ? ast_channel_accountcode(chan) : "");
1951         ast_agi_send(fd, chan, "agi_threadid: %ld\n", (long)pthread_self());
1952
1953         /* Send any parameters to the fastagi server that have been passed via the agi application */
1954         /* Agi application paramaters take the form of: AGI(/path/to/example/script|${EXTEN}) */
1955         for(count = 1; count < argc; count++)
1956                 ast_agi_send(fd, chan, "agi_arg_%d: %s\n", count, argv[count]);
1957
1958         /* End with empty return */
1959         ast_agi_send(fd, chan, "\n");
1960 }
1961
1962 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1963 {
1964         int res = 0;
1965
1966         /* Answer the channel */
1967         if (ast_channel_state(chan) != AST_STATE_UP)
1968                 res = ast_answer(chan);
1969
1970         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1971         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1972 }
1973
1974 static int handle_asyncagi_break(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1975 {
1976         ast_agi_send(agi->fd, chan, "200 result=0\n");
1977         return ASYNC_AGI_BREAK;
1978 }
1979
1980 static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1981 {
1982         int res, to;
1983
1984         if (argc != 4)
1985                 return RESULT_SHOWUSAGE;
1986         if (sscanf(argv[3], "%30d", &to) != 1)
1987                 return RESULT_SHOWUSAGE;
1988         res = ast_waitfordigit_full(chan, to, agi->audio, agi->ctrl);
1989         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1990         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1991 }
1992
1993 static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1994 {
1995         int res;
1996
1997         if (argc != 3)
1998                 return RESULT_SHOWUSAGE;
1999
2000         /* At the moment, the parser (perhaps broken) returns with
2001            the last argument PLUS the newline at the end of the input
2002            buffer. This probably needs to be fixed, but I wont do that
2003            because other stuff may break as a result. The right way
2004            would probably be to strip off the trailing newline before
2005            parsing, then here, add a newline at the end of the string
2006            before sending it to ast_sendtext --DUDE */
2007         res = ast_sendtext(chan, argv[2]);
2008         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2009         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2010 }
2011
2012 static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2013 {
2014         int res;
2015
2016         if (argc != 3)
2017                 return RESULT_SHOWUSAGE;
2018
2019         res = ast_recvchar(chan,atoi(argv[2]));
2020         if (res == 0) {
2021                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout)\n", res);
2022                 return RESULT_SUCCESS;
2023         }
2024         if (res > 0) {
2025                 ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2026                 return RESULT_SUCCESS;
2027         }
2028         ast_agi_send(agi->fd, chan, "200 result=%d (hangup)\n", res);
2029         return RESULT_FAILURE;
2030 }
2031
2032 static int handle_recvtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2033 {
2034         char *buf;
2035
2036         if (argc != 3)
2037                 return RESULT_SHOWUSAGE;
2038
2039         buf = ast_recvtext(chan, atoi(argv[2]));
2040         if (buf) {
2041                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", buf);
2042                 ast_free(buf);
2043         } else {
2044                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2045         }
2046         return RESULT_SUCCESS;
2047 }
2048
2049 static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2050 {
2051         int res, x;
2052
2053         if (argc != 3)
2054                 return RESULT_SHOWUSAGE;
2055
2056         if (!strncasecmp(argv[2],"on",2)) {
2057                 x = 1;
2058         } else  {
2059                 x = 0;
2060         }
2061         if (!strncasecmp(argv[2],"mate",4))  {
2062                 x = 2;
2063         }
2064         if (!strncasecmp(argv[2],"tdd",3)) {
2065                 x = 1;
2066         }
2067         res = ast_channel_setoption(chan, AST_OPTION_TDD, &x, sizeof(char), 0);
2068         if (res) {
2069                 /* Set channel option failed */
2070                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2071         } else {
2072                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2073         }
2074         return RESULT_SUCCESS;
2075 }
2076
2077 static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2078 {
2079         int res;
2080
2081         if (argc != 3) {
2082                 return RESULT_SHOWUSAGE;
2083         }
2084
2085         res = ast_send_image(chan, argv[2]);
2086         if (!ast_check_hangup(chan)) {
2087                 res = 0;
2088         }
2089         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2090         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2091 }
2092
2093 static int handle_controlstreamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2094 {
2095         int res = 0, skipms = 3000;
2096         const char *fwd = "#", *rev = "*", *suspend = NULL, *stop = NULL;       /* Default values */
2097         char stopkeybuf[2];
2098         long offsetms = 0;
2099         char offsetbuf[20];
2100
2101         if (argc < 5 || argc > 10) {
2102                 return RESULT_SHOWUSAGE;
2103         }
2104
2105         if (!ast_strlen_zero(argv[4])) {
2106                 stop = argv[4];
2107         }
2108
2109         if ((argc > 5) && (sscanf(argv[5], "%30d", &skipms) != 1)) {
2110                 return RESULT_SHOWUSAGE;
2111         }
2112
2113         if (argc > 6 && !ast_strlen_zero(argv[6])) {
2114                 fwd = argv[6];
2115         }
2116
2117         if (argc > 7 && !ast_strlen_zero(argv[7])) {
2118                 rev = argv[7];
2119         }
2120
2121         if (argc > 8 && !ast_strlen_zero(argv[8])) {
2122                 suspend = argv[8];
2123         }
2124
2125         if (argc > 9 && (sscanf(argv[9], "%30ld", &offsetms) != 1)) {
2126                 return RESULT_SHOWUSAGE;
2127         }
2128
2129         res = ast_control_streamfile(chan, argv[3], fwd, rev, stop, suspend, NULL, skipms, &offsetms);
2130
2131         /* If we stopped on one of our stop keys, return 0  */
2132         if (res > 0 && stop && strchr(stop, res)) {
2133                 pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "USERSTOPPED");
2134                 snprintf(stopkeybuf, sizeof(stopkeybuf), "%c", res);
2135                 pbx_builtin_setvar_helper(chan, "CPLAYBACKSTOPKEY", stopkeybuf);
2136         } else if (res > 0 && res == AST_CONTROL_STREAM_STOP) {
2137                 pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "REMOTESTOPPED");
2138                 res = 0;
2139         } else {
2140                 if (res < 0) {
2141                         pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "ERROR");
2142                 } else {
2143                         pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "SUCCESS");
2144                 }
2145         }
2146
2147         snprintf(offsetbuf, sizeof(offsetbuf), "%ld", offsetms);
2148         pbx_builtin_setvar_helper(chan, "CPLAYBACKOFFSET", offsetbuf);
2149
2150         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, offsetms);
2151
2152         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2153 }
2154
2155 static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2156 {
2157         int res;
2158         struct ast_filestream *fs, *vfs;
2159         long sample_offset = 0, max_length;
2160         const char *edigits = "";
2161
2162         if (argc < 4 || argc > 5) {
2163                 return RESULT_SHOWUSAGE;
2164         }
2165
2166         if (argv[3]) {
2167                 edigits = argv[3];
2168         }
2169
2170         if ((argc > 4) && (sscanf(argv[4], "%30ld", &sample_offset) != 1)) {
2171                 return RESULT_SHOWUSAGE;
2172         }
2173
2174         if (!(fs = ast_openstream(chan, argv[2], ast_channel_language(chan)))) {
2175                 ast_agi_send(agi->fd, chan, "200 result=-1 endpos=%ld\n", sample_offset);
2176                 return RESULT_FAILURE;
2177         }
2178
2179         if ((vfs = ast_openvstream(chan, argv[2], ast_channel_language(chan)))) {
2180                 ast_debug(1, "Ooh, found a video stream, too\n");
2181         }
2182
2183         ast_verb(3, "Playing '%s' (escape_digits=%s) (sample_offset %ld)\n", argv[2], edigits, sample_offset);
2184
2185         ast_seekstream(fs, 0, SEEK_END);
2186         max_length = ast_tellstream(fs);
2187         ast_seekstream(fs, sample_offset, SEEK_SET);
2188         res = ast_applystream(chan, fs);
2189         if (vfs) {
2190                 ast_applystream(chan, vfs);
2191         }
2192         ast_playstream(fs);
2193         if (vfs) {
2194                 ast_playstream(vfs);
2195         }
2196
2197         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
2198         /* this is to check for if ast_waitstream closed the stream, we probably are at
2199          * the end of the stream, return that amount, else check for the amount */
2200         sample_offset = (ast_channel_stream(chan)) ? ast_tellstream(fs) : max_length;
2201         ast_stopstream(chan);
2202         if (res == 1) {
2203                 /* Stop this command, don't print a result line, as there is a new command */
2204                 return RESULT_SUCCESS;
2205         }
2206         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
2207         pbx_builtin_setvar_helper(chan, "PLAYBACKSTATUS", res ? "FAILED" : "SUCCESS");
2208
2209         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2210 }
2211
2212 /*! \brief get option - really similar to the handle_streamfile, but with a timeout */
2213 static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2214 {
2215         int res;
2216         struct ast_filestream *fs, *vfs;
2217         long sample_offset = 0, max_length;
2218         int timeout = 0;
2219         const char *edigits = "";
2220
2221         if ( argc < 4 || argc > 5 )
2222                 return RESULT_SHOWUSAGE;
2223
2224         if ( argv[3] )
2225                 edigits = argv[3];
2226
2227         if ( argc == 5 )
2228                 timeout = atoi(argv[4]);
2229         else if (ast_channel_pbx(chan)->dtimeoutms) {
2230                 /* by default dtimeout is set to 5sec */
2231                 timeout = ast_channel_pbx(chan)->dtimeoutms; /* in msec */
2232         }
2233
2234         if (!(fs = ast_openstream(chan, argv[2], ast_channel_language(chan)))) {
2235                 ast_agi_send(agi->fd, chan, "200 result=-1 endpos=%ld\n", sample_offset);
2236                 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
2237                 return RESULT_FAILURE;
2238         }
2239
2240         if ((vfs = ast_openvstream(chan, argv[2], ast_channel_language(chan))))
2241                 ast_debug(1, "Ooh, found a video stream, too\n");
2242
2243         ast_verb(3, "Playing '%s' (escape_digits=%s) (timeout %d)\n", argv[2], edigits, timeout);
2244
2245         ast_seekstream(fs, 0, SEEK_END);
2246         max_length = ast_tellstream(fs);
2247         ast_seekstream(fs, sample_offset, SEEK_SET);
2248         res = ast_applystream(chan, fs);
2249         if (vfs)
2250                 ast_applystream(chan, vfs);
2251         ast_playstream(fs);
2252         if (vfs)
2253                 ast_playstream(vfs);
2254
2255         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
2256         /* this is to check for if ast_waitstream closed the stream, we probably are at
2257          * the end of the stream, return that amount, else check for the amount */
2258         sample_offset = (ast_channel_stream(chan))?ast_tellstream(fs):max_length;
2259         ast_stopstream(chan);
2260         if (res == 1) {
2261                 /* Stop this command, don't print a result line, as there is a new command */
2262                 return RESULT_SUCCESS;
2263         }
2264
2265         /* If the user didnt press a key, wait for digitTimeout*/
2266         if (res == 0 ) {
2267                 res = ast_waitfordigit_full(chan, timeout, agi->audio, agi->ctrl);
2268                 /* Make sure the new result is in the escape digits of the GET OPTION */
2269                 if ( !strchr(edigits,res) )
2270                         res=0;
2271         }
2272
2273         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
2274         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2275 }
2276
2277
2278
2279
2280 /*! \brief Say number in various language syntaxes */
2281 /* While waiting, we're sending a NULL.  */
2282 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2283 {
2284         int res, num;
2285
2286         if (argc < 4 || argc > 5)
2287                 return RESULT_SHOWUSAGE;
2288         if (sscanf(argv[2], "%30d", &num) != 1)
2289                 return RESULT_SHOWUSAGE;
2290         res = ast_say_number_full(chan, num, argv[3], ast_channel_language(chan), argc > 4 ? argv[4] : NULL, agi->audio, agi->ctrl);
2291         if (res == 1)
2292                 return RESULT_SUCCESS;
2293         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2294         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2295 }
2296
2297 static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2298 {
2299         int res, num;
2300
2301         if (argc != 4)
2302                 return RESULT_SHOWUSAGE;
2303         if (sscanf(argv[2], "%30d", &num) != 1)
2304                 return RESULT_SHOWUSAGE;
2305
2306         res = ast_say_digit_str_full(chan, argv[2], argv[3], ast_channel_language(chan), agi->audio, agi->ctrl);
2307         if (res == 1) /* New command */
2308                 return RESULT_SUCCESS;
2309         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2310         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2311 }
2312
2313 static int handle_sayalpha(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2314 {
2315         int res;
2316
2317         if (argc != 4)
2318                 return RESULT_SHOWUSAGE;
2319
2320         res = ast_say_character_str_full(chan, argv[2], argv[3], ast_channel_language(chan), agi->audio, agi->ctrl);
2321         if (res == 1) /* New command */
2322                 return RESULT_SUCCESS;
2323         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2324         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2325 }
2326
2327 static int handle_saydate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2328 {
2329         int res, num;
2330
2331         if (argc != 4)
2332                 return RESULT_SHOWUSAGE;
2333         if (sscanf(argv[2], "%30d", &num) != 1)
2334                 return RESULT_SHOWUSAGE;
2335         res = ast_say_date(chan, num, argv[3], ast_channel_language(chan));
2336         if (res == 1)
2337                 return RESULT_SUCCESS;
2338         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2339         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2340 }
2341
2342 static int handle_saytime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2343 {
2344         int res, num;
2345
2346         if (argc != 4)
2347                 return RESULT_SHOWUSAGE;
2348         if (sscanf(argv[2], "%30d", &num) != 1)
2349                 return RESULT_SHOWUSAGE;
2350         res = ast_say_time(chan, num, argv[3], ast_channel_language(chan));
2351         if (res == 1)
2352                 return RESULT_SUCCESS;
2353         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2354         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2355 }
2356
2357 static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2358 {
2359         int res = 0;
2360         time_t unixtime;
2361         const char *format, *zone = NULL;
2362
2363         if (argc < 4)
2364                 return RESULT_SHOWUSAGE;
2365
2366         if (argc > 4) {
2367                 format = argv[4];
2368         } else {
2369                 /* XXX this doesn't belong here, but in the 'say' module */
2370                 if (!strcasecmp(ast_channel_language(chan), "de")) {
2371                         format = "A dBY HMS";
2372                 } else {
2373                         format = "ABdY 'digits/at' IMp";
2374                 }
2375         }
2376
2377         if (argc > 5 && !ast_strlen_zero(argv[5]))
2378                 zone = argv[5];
2379
2380         if (ast_get_time_t(argv[2], &unixtime, 0, NULL))
2381                 return RESULT_SHOWUSAGE;
2382
2383         res = ast_say_date_with_format(chan, unixtime, argv[3], ast_channel_language(chan), format, zone);
2384         if (res == 1)
2385                 return RESULT_SUCCESS;
2386
2387         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2388         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2389 }
2390
2391 static int handle_sayphonetic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2392 {
2393         int res;
2394
2395         if (argc != 4)
2396                 return RESULT_SHOWUSAGE;
2397
2398         res = ast_say_phonetic_str_full(chan, argv[2], argv[3], ast_channel_language(chan), agi->audio, agi->ctrl);
2399         if (res == 1) /* New command */
2400                 return RESULT_SUCCESS;
2401         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2402         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2403 }
2404
2405 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2406 {
2407         int res, max, timeout;
2408         char data[1024];
2409
2410         if (argc < 3)
2411                 return RESULT_SHOWUSAGE;
2412         if (argc >= 4)
2413                 timeout = atoi(argv[3]);
2414         else
2415                 timeout = 0;
2416         if (argc >= 5)
2417                 max = atoi(argv[4]);
2418         else
2419                 max = 1024;
2420         res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
2421         if (res == 2)                   /* New command */
2422                 return RESULT_SUCCESS;
2423         else if (res == 1)
2424                 ast_agi_send(agi->fd, chan, "200 result=%s (timeout)\n", data);
2425         else if (res < 0 )
2426                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2427         else
2428                 ast_agi_send(agi->fd, chan, "200 result=%s\n", data);
2429         return RESULT_SUCCESS;
2430 }
2431
2432 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2433 {
2434
2435         if (argc != 3)
2436                 return RESULT_SHOWUSAGE;
2437         ast_channel_context_set(chan, argv[2]);
2438         ast_agi_send(agi->fd, chan, "200 result=0\n");
2439         return RESULT_SUCCESS;
2440 }
2441
2442 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2443 {
2444         if (argc != 3)
2445                 return RESULT_SHOWUSAGE;
2446         ast_channel_exten_set(chan, argv[2]);
2447         ast_agi_send(agi->fd, chan, "200 result=0\n");
2448         return RESULT_SUCCESS;
2449 }
2450
2451 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2452 {
2453         int pri;
2454
2455         if (argc != 3)
2456                 return RESULT_SHOWUSAGE;
2457
2458         if (sscanf(argv[2], "%30d", &pri) != 1) {
2459                 pri = ast_findlabel_extension(chan, ast_channel_context(chan), ast_channel_exten(chan), argv[2],
2460                         S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL));
2461                 if (pri < 1)
2462                         return RESULT_SHOWUSAGE;
2463         }
2464
2465         ast_explicit_goto(chan, NULL, NULL, pri);
2466         ast_agi_send(agi->fd, chan, "200 result=0\n");
2467         return RESULT_SUCCESS;
2468 }
2469
2470 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2471 {
2472         struct ast_filestream *fs;
2473         struct ast_frame *f;
2474         struct timeval start;
2475         long sample_offset = 0;
2476         int res = 0;
2477         int ms;
2478
2479         struct ast_dsp *sildet=NULL;         /* silence detector dsp */
2480         int totalsilence = 0;
2481         int dspsilence = 0;
2482         int silence = 0;                /* amount of silence to allow */
2483         int gotsilence = 0;             /* did we timeout for silence? */
2484         char *silencestr = NULL;
2485         struct ast_format rfmt;
2486         ast_format_clear(&rfmt);
2487
2488         /* XXX EAGI FIXME XXX */
2489
2490         if (argc < 6)
2491                 return RESULT_SHOWUSAGE;
2492         if (sscanf(argv[5], "%30d", &ms) != 1)
2493                 return RESULT_SHOWUSAGE;
2494
2495         if (argc > 6)
2496                 silencestr = strchr(argv[6],'s');
2497         if ((argc > 7) && (!silencestr))
2498                 silencestr = strchr(argv[7],'s');
2499         if ((argc > 8) && (!silencestr))
2500                 silencestr = strchr(argv[8],'s');
2501
2502         if (silencestr) {
2503                 if (strlen(silencestr) > 2) {
2504                         if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
2505                                 silencestr++;
2506                                 silencestr++;
2507                                 if (silencestr)
2508                                         silence = atoi(silencestr);
2509                                 if (silence > 0)
2510                                         silence *= 1000;
2511                         }
2512                 }
2513         }
2514
2515         if (silence > 0) {
2516                 ast_format_copy(&rfmt, ast_channel_readformat(chan));
2517                 res = ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
2518                 if (res < 0) {
2519                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
2520                         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2521                         return RESULT_FAILURE;
2522                 }
2523                 sildet = ast_dsp_new();
2524                 if (!sildet) {
2525                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
2526                         ast_agi_send(agi->fd, chan, "200 result=-1\n");
2527                         return RESULT_FAILURE;
2528                 }
2529                 ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
2530         }
2531
2532         /* backward compatibility, if no offset given, arg[6] would have been
2533          * caught below and taken to be a beep, else if it is a digit then it is a
2534          * offset */
2535         if ((argc >6) && (sscanf(argv[6], "%30ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
2536                 res = ast_streamfile(chan, "beep", ast_channel_language(chan));
2537
2538         if ((argc > 7) && (!strchr(argv[7], '=')))
2539                 res = ast_streamfile(chan, "beep", ast_channel_language(chan));
2540
2541         if (!res)
2542                 res = ast_waitstream(chan, argv[4]);
2543         if (res) {
2544                 ast_agi_send(agi->fd, chan, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
2545         } else {
2546                 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, AST_FILE_MODE);
2547                 if (!fs) {
2548                         res = -1;
2549                         ast_agi_send(agi->fd, chan, "200 result=%d (writefile)\n", res);
2550                         if (sildet)
2551                                 ast_dsp_free(sildet);
2552                         return RESULT_FAILURE;
2553                 }
2554
2555                 /* Request a video update */
2556                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
2557
2558                 ast_channel_stream_set(chan, fs);
2559                 ast_applystream(chan,fs);
2560                 /* really should have checks */
2561                 ast_seekstream(fs, sample_offset, SEEK_SET);
2562                 ast_truncstream(fs);
2563
2564                 start = ast_tvnow();
2565                 while ((ms < 0) || ast_tvdiff_ms(ast_tvnow(), start) < ms) {
2566                         res = ast_waitfor(chan, ms - ast_tvdiff_ms(ast_tvnow(), start));
2567                         if (res < 0) {
2568                                 ast_closestream(fs);
2569                                 ast_agi_send(agi->fd, chan, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
2570                                 if (sildet)
2571                                         ast_dsp_free(sildet);
2572                                 return RESULT_FAILURE;
2573                         }
2574                         f = ast_read(chan);
2575                         if (!f) {
2576                                 ast_agi_send(agi->fd, chan, "200 result=%d (hangup) endpos=%ld\n", -1, sample_offset);
2577                                 ast_closestream(fs);
2578                                 if (sildet)
2579                                         ast_dsp_free(sildet);
2580                                 return RESULT_FAILURE;
2581                         }
2582                         switch(f->frametype) {
2583                         case AST_FRAME_DTMF:
2584                                 if (strchr(argv[4], f->subclass.integer)) {
2585                                         /* This is an interrupting chracter, so rewind to chop off any small
2586                                            amount of DTMF that may have been recorded
2587                                         */
2588                                         ast_stream_rewind(fs, 200);
2589                                         ast_truncstream(fs);
2590                                         sample_offset = ast_tellstream(fs);
2591                                         ast_agi_send(agi->fd, chan, "200 result=%d (dtmf) endpos=%ld\n", f->subclass.integer, sample_offset);
2592                                         ast_closestream(fs);
2593                                         ast_frfree(f);
2594                                         if (sildet)
2595                                                 ast_dsp_free(sildet);
2596                                         return RESULT_SUCCESS;
2597                                 }
2598                                 break;
2599                         case AST_FRAME_VOICE:
2600                                 ast_writestream(fs, f);
2601                                 /* this is a safe place to check progress since we know that fs
2602                                  * is valid after a write, and it will then have our current
2603                                  * location */
2604                                 sample_offset = ast_tellstream(fs);
2605                                 if (silence > 0) {
2606                                         dspsilence = 0;
2607                                         ast_dsp_silence(sildet, f, &dspsilence);
2608                                         if (dspsilence) {
2609                                                 totalsilence = dspsilence;
2610                                         } else {
2611                                                 totalsilence = 0;
2612                                         }
2613                                         if (totalsilence > silence) {
2614                                                 /* Ended happily with silence */
2615                                                 gotsilence = 1;
2616                                                 break;
2617                                         }
2618                                 }
2619                                 break;
2620                         case AST_FRAME_VIDEO:
2621                                 ast_writestream(fs, f);
2622                         default:
2623                                 /* Ignore all other frames */
2624                                 break;
2625                         }
2626                         ast_frfree(f);
2627                         if (gotsilence)
2628                                 break;
2629                 }
2630
2631                 if (gotsilence) {
2632                         ast_stream_rewind(fs, silence-1000);
2633                         ast_truncstream(fs);
2634                         sample_offset = ast_tellstream(fs);
2635                 }
2636                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
2637                 ast_closestream(fs);
2638         }
2639
2640         if (silence > 0) {
2641                 res = ast_set_read_format(chan, &rfmt);
2642                 if (res)
2643                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", ast_channel_name(chan));
2644                 ast_dsp_free(sildet);
2645         }
2646
2647         return RESULT_SUCCESS;
2648 }
2649
2650 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2651 {
2652         double timeout;
2653         struct timeval whentohangup = { 0, 0 };
2654
2655         if (argc != 3)
2656                 return RESULT_SHOWUSAGE;
2657         if (sscanf(argv[2], "%30lf", &timeout) != 1)
2658                 return RESULT_SHOWUSAGE;
2659         if (timeout < 0)
2660                 timeout = 0;
2661         if (timeout) {
2662                 whentohangup.tv_sec = timeout;
2663                 whentohangup.tv_usec = (timeout - whentohangup.tv_sec) * 1000000.0;
2664         }
2665         ast_channel_setwhentohangup_tv(chan, whentohangup);
2666         ast_agi_send(agi->fd, chan, "200 result=0\n");
2667         return RESULT_SUCCESS;
2668 }
2669
2670 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2671 {
2672         struct ast_channel *c;
2673
2674         if (argc == 1) {
2675                 /* no argument: hangup the current channel */
2676                 ast_set_hangupsource(chan, "dialplan/agi", 0);
2677                 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
2678                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2679                 return RESULT_SUCCESS;
2680         } else if (argc == 2) {
2681                 /* one argument: look for info on the specified channel */
2682                 if ((c = ast_channel_get_by_name(argv[1]))) {
2683                         /* we have a matching channel */
2684                         ast_set_hangupsource(c, "dialplan/agi", 0);
2685                         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
2686                         c = ast_channel_unref(c);
2687                         ast_agi_send(agi->fd, chan, "200 result=1\n");
2688                         return RESULT_SUCCESS;
2689                 }
2690                 /* if we get this far no channel name matched the argument given */
2691                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2692                 return RESULT_SUCCESS;
2693         } else {
2694                 return RESULT_SHOWUSAGE;
2695         }
2696 }
2697
2698 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2699 {
2700         int res, workaround;
2701         struct ast_app *app_to_exec;
2702
2703         if (argc < 2)
2704                 return RESULT_SHOWUSAGE;
2705
2706         ast_verb(3, "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argc >= 3 ? argv[2] : "");
2707
2708         if ((app_to_exec = pbx_findapp(argv[1]))) {
2709                 if (!(workaround = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS))) {
2710                         ast_set_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS);
2711                 }
2712                 if (ast_compat_res_agi && argc >= 3 && !ast_strlen_zero(argv[2])) {
2713                         char *compat = ast_alloca(strlen(argv[2]) * 2 + 1), *cptr;
2714                         const char *vptr;
2715                         for (cptr = compat, vptr = argv[2]; *vptr; vptr++) {
2716                                 if (*vptr == ',') {
2717                                         *cptr++ = '\\';
2718                                         *cptr++ = ',';
2719                                 } else if (*vptr == '|') {
2720                                         *cptr++ = ',';
2721                                 } else {
2722                                         *cptr++ = *vptr;
2723                                 }
2724                         }
2725                         *cptr = '\0';
2726                         res = pbx_exec(chan, app_to_exec, compat);
2727                 } else {
2728                         res = pbx_exec(chan, app_to_exec, argc == 2 ? "" : argv[2]);
2729                 }
2730                 if (!workaround) {
2731                         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS);
2732                 }
2733         } else {
2734                 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
2735                 res = -2;
2736         }
2737         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2738
2739         /* Even though this is wrong, users are depending upon this result. */
2740         return res;
2741 }
2742
2743 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2744 {
2745         char tmp[256]="";
2746         char *l = NULL, *n = NULL;
2747
2748         if (argv[2]) {
2749                 ast_copy_string(tmp, argv[2], sizeof(tmp));
2750                 ast_callerid_parse(tmp, &n, &l);
2751                 if (l)
2752                         ast_shrink_phone_number(l);
2753                 else
2754                         l = "";
2755                 if (!n)
2756                         n = "";
2757                 ast_set_callerid(chan, l, n, NULL);
2758         }
2759
2760         ast_agi_send(agi->fd, chan, "200 result=1\n");
2761         return RESULT_SUCCESS;
2762 }
2763
2764 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2765 {
2766         if (argc == 2) {
2767                 /* no argument: supply info on the current channel */
2768                 ast_agi_send(agi->fd, chan, "200 result=%d\n", ast_channel_state(chan));
2769                 return RESULT_SUCCESS;
2770         } else if (argc == 3) {
2771                 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
2772
2773                 /* one argument: look for info on the specified channel */
2774                 if ((msg = stasis_cache_get(ast_channel_cache_by_name(), ast_channel_snapshot_type(), argv[2]))) {
2775                         struct ast_channel_snapshot *snapshot = stasis_message_data(msg);
2776
2777                         ast_agi_send(agi->fd, chan, "200 result=%d\n", snapshot->state);
2778                         return RESULT_SUCCESS;
2779                 }
2780                 /* if we get this far no channel name matched the argument given */
2781                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2782                 return RESULT_SUCCESS;
2783         } else {
2784                 return RESULT_SHOWUSAGE;
2785         }
2786 }
2787
2788 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2789 {
2790         if (argv[3])
2791                 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
2792
2793         ast_agi_send(agi->fd, chan, "200 result=1\n");
2794         return RESULT_SUCCESS;
2795 }
2796
2797 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2798 {
2799         char *ret;
2800         char tempstr[1024] = "";
2801
2802         if (argc != 3)
2803                 return RESULT_SHOWUSAGE;
2804
2805         /* check if we want to execute an ast_custom_function */
2806         if (!ast_strlen_zero(argv[2]) && (argv[2][strlen(argv[2]) - 1] == ')')) {
2807                 ret = ast_func_read(chan, argv[2], tempstr, sizeof(tempstr)) ? NULL : tempstr;
2808         } else {
2809                 pbx_retrieve_variable(chan, argv[2], &ret, tempstr, sizeof(tempstr), NULL);
2810         }
2811
2812         if (ret)
2813                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ret);
2814         else
2815                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2816
2817         return RESULT_SUCCESS;
2818 }
2819
2820 static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2821 {
2822         struct ast_channel *chan2 = NULL;
2823
2824         if (argc != 4 && argc != 5) {
2825                 return RESULT_SHOWUSAGE;
2826         }
2827
2828         if (argc == 5) {
2829                 chan2 = ast_channel_get_by_name(argv[4]);
2830         } else {
2831                 chan2 = ast_channel_ref(chan);
2832         }
2833
2834         if (chan2) {
2835                 struct ast_str *str = ast_str_create(16);
2836                 if (!str) {
2837                         ast_agi_send(agi->fd, chan, "200 result=0\n");
2838                         return RESULT_SUCCESS;
2839                 }
2840                 ast_str_substitute_variables(&str, 0, chan2, argv[3]);
2841                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(str));
2842                 ast_free(str);
2843         } else {
2844                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2845         }
2846
2847         if (chan2) {
2848                 chan2 = ast_channel_unref(chan2);
2849         }
2850
2851         return RESULT_SUCCESS;
2852 }
2853
2854 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2855 {
2856         int level = 0;
2857
2858         if (argc < 2)
2859                 return RESULT_SHOWUSAGE;
2860
2861         if (argv[2])
2862                 sscanf(argv[2], "%30d", &level);
2863
2864         ast_verb(level, "%s: %s\n", ast_channel_data(chan), argv[1]);
2865
2866         ast_agi_send(agi->fd, chan, "200 result=1\n");
2867
2868         return RESULT_SUCCESS;
2869 }
2870
2871 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2872 {
2873         int res;
2874         struct ast_str *buf;
2875
2876         if (argc != 4)
2877                 return RESULT_SHOWUSAGE;
2878
2879         if (!(buf = ast_str_create(16))) {
2880                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2881                 return RESULT_SUCCESS;
2882         }
2883
2884         do {
2885                 res = ast_db_get(argv[2], argv[3], ast_str_buffer(buf), ast_str_size(buf));
2886                 ast_str_update(buf);
2887                 if (ast_str_strlen(buf) < ast_str_size(buf) - 1) {
2888                         break;
2889                 }
2890                 if (ast_str_make_space(&buf, ast_str_size(buf) * 2)) {
2891                         break;
2892                 }
2893         } while (1);
2894
2895         if (res)
2896                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2897         else
2898                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(buf));
2899
2900         ast_free(buf);
2901         return RESULT_SUCCESS;
2902 }
2903
2904 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2905 {
2906         int res;
2907
2908         if (argc != 5)
2909                 return RESULT_SHOWUSAGE;
2910         res = ast_db_put(argv[2], argv[3], argv[4]);
2911         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2912         return RESULT_SUCCESS;
2913 }
2914
2915 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2916 {
2917         int res;
2918
2919         if (argc != 4)
2920                 return RESULT_SHOWUSAGE;
2921         res = ast_db_del(argv[2], argv[3]);
2922         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2923         return RESULT_SUCCESS;
2924 }
2925
2926 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2927 {
2928         int num_deleted;
2929
2930         if ((argc < 3) || (argc > 4)) {
2931                 return RESULT_SHOWUSAGE;
2932         }
2933         if (argc == 4) {
2934                 num_deleted = ast_db_deltree(argv[2], argv[3]);
2935         } else {
2936                 num_deleted = ast_db_deltree(argv[2], NULL);
2937         }
2938
2939         ast_agi_send(agi->fd, chan, "200 result=%c\n", num_deleted > 0 ? '0' : '1');
2940         return RESULT_SUCCESS;
2941 }
2942
2943 static char *handle_cli_agi_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2944 {
2945         switch (cmd) {
2946         case CLI_INIT:
2947                 e->command = "agi set debug [on|off]";
2948                 e->usage =
2949                         "Usage: agi set debug [on|off]\n"
2950                         "       Enables/disables dumping of AGI transactions for\n"
2951                         "       debugging purposes.\n";
2952                 return NULL;
2953
2954         case CLI_GENERATE:
2955                 return NULL;
2956         }
2957
2958         if (a->argc != e->args)
2959                 return CLI_SHOWUSAGE;
2960
2961         if (strncasecmp(a->argv[3], "off", 3) == 0) {
2962                 agidebug = 0;
2963         } else if (strncasecmp(a->argv[3], "on", 2) == 0) {
2964                 agidebug = 1;
2965         } else {
2966                 return CLI_SHOWUSAGE;
2967         }
2968         ast_cli(a->fd, "AGI Debugging %sabled\n", agidebug ? "En" : "Dis");
2969         return CLI_SUCCESS;
2970 }
2971
2972 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, const char * const argv[])
2973 {
2974         ast_agi_send(agi->fd, chan, "200 result=0\n");
2975         return RESULT_SUCCESS;
2976 }
2977
2978 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2979 {
2980         if (argc < 3) {
2981                 return RESULT_SHOWUSAGE;
2982         }
2983         if (!strncasecmp(argv[2], "on", 2))
2984                 ast_moh_start(chan, argc > 3 ? argv[3] : NULL, NULL);
2985         else if (!strncasecmp(argv[2], "off", 3))
2986                 ast_moh_stop(chan);
2987         ast_agi_send(agi->fd, chan, "200 result=0\n");
2988         return RESULT_SUCCESS;
2989 }
2990
2991 static int handle_speechcreate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2992 {
2993         struct ast_format_cap *cap;
2994         struct ast_format tmpfmt;
2995
2996         /* If a structure already exists, return an error */
2997         if (agi->speech) {
2998                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2999                 return RESULT_SUCCESS;
3000         }
3001
3002         if (!(cap = ast_format_cap_alloc_nolock())) {
3003                 return RESULT_FAILURE;
3004         }
3005         ast_format_cap_add(cap, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0));
3006         if ((agi->speech = ast_speech_new(argv[2], cap))) {
3007                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3008         } else {
3009                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3010         }
3011         cap = ast_format_cap_destroy(cap);
3012
3013         return RESULT_SUCCESS;
3014 }
3015
3016 static int handle_speechset(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3017 {
3018         /* Check for minimum arguments */
3019         if (argc != 4)
3020                 return RESULT_SHOWUSAGE;
3021
3022         /* Check to make sure speech structure exists */
3023         if (!agi->speech) {
3024                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3025                 return RESULT_SUCCESS;
3026         }
3027
3028         ast_speech_change(agi->speech, argv[2], argv[3]);
3029         ast_agi_send(agi->fd, chan, "200 result=1\n");
3030
3031         return RESULT_SUCCESS;
3032 }
3033
3034 static int handle_speechdestroy(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3035 {
3036         if (agi->speech) {
3037                 ast_speech_destroy(agi->speech);
3038                 agi->speech = NULL;
3039                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3040         } else {
3041                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3042         }
3043
3044         return RESULT_SUCCESS;
3045 }
3046
3047 static int handle_speechloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3048 {
3049         if (argc != 5)
3050                 return RESULT_SHOWUSAGE;
3051
3052         if (!agi->speech) {
3053                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3054                 return RESULT_SUCCESS;
3055         }
3056
3057         if (ast_speech_grammar_load(agi->speech, argv[3], argv[4]))
3058                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3059         else
3060                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3061
3062         return RESULT_SUCCESS;
3063 }
3064
3065 static int handle_speechunloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3066 {
3067         if (argc != 4)
3068                 return RESULT_SHOWUSAGE;
3069
3070         if (!agi->speech) {
3071                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3072                 return RESULT_SUCCESS;
3073         }
3074
3075         if (ast_speech_grammar_unload(agi->speech, argv[3]))
3076                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3077         else
3078                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3079
3080         return RESULT_SUCCESS;
3081 }
3082
3083 static int handle_speechactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3084 {
3085         if (argc != 4)
3086                 return RESULT_SHOWUSAGE;
3087
3088         if (!agi->speech) {
3089                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3090                 return RESULT_SUCCESS;
3091         }
3092
3093         if (ast_speech_grammar_activate(agi->speech, argv[3]))
3094                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3095         else
3096                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3097
3098         return RESULT_SUCCESS;
3099 }
3100
3101 static int handle_speechdeactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3102 {
3103         if (argc != 4)
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_deactivate(agi->speech, argv[3]))
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 speech_streamfile(struct ast_channel *chan, const char *filename, const char *preflang, int offset)
3120 {
3121         struct ast_filestream *fs = NULL;
3122
3123         if (!(fs = ast_openstream(chan, filename, preflang)))
3124                 return -1;
3125
3126         if (offset)
3127                 ast_seekstream(fs, offset, SEEK_SET);
3128
3129         if (ast_applystream(chan, fs))
3130                 return -1;
3131
3132         if (ast_playstream(fs))
3133                 return -1;
3134
3135         return 0;
3136 }
3137
3138 static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3139 {
3140         struct ast_speech *speech = agi->speech;
3141         const char *prompt;
3142         char dtmf = 0, tmp[4096] = "", *buf = tmp;
3143         int timeout = 0, offset = 0, res = 0, i = 0;
3144         struct ast_format old_read_format;
3145         long current_offset = 0;
3146         const char *reason = NULL;
3147         struct ast_frame *fr = NULL;
3148         struct ast_speech_result *result = NULL;
3149         size_t left = sizeof(tmp);
3150         time_t start = 0, current;
3151
3152         if (argc < 4)
3153                 return RESULT_SHOWUSAGE;
3154
3155         if (!speech) {
3156                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3157                 return RESULT_SUCCESS;
3158         }
3159
3160         prompt = argv[2];
3161         timeout = atoi(argv[3]);
3162
3163         /* If offset is specified then convert from text to integer */
3164         if (argc == 5)
3165                 offset = atoi(argv[4]);
3166
3167         /* We want frames coming in signed linear */
3168         ast_format_copy(&old_read_format, ast_channel_readformat(chan));
3169         if (ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR)) {
3170                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3171                 return RESULT_SUCCESS;
3172         }
3173
3174         /* Setup speech structure */
3175         if (speech->state == AST_SPEECH_STATE_NOT_READY || speech->state == AST_SPEECH_STATE_DONE) {
3176                 ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
3177                 ast_speech_start(speech);
3178         }
3179
3180         /* Start playing prompt */
3181         speech_streamfile(chan, prompt, ast_channel_language(chan), offset);
3182
3183         /* Go into loop reading in frames, passing to speech thingy, checking for hangup, all that jazz */
3184         while (ast_strlen_zero(reason)) {
3185                 /* Run scheduled items */
3186                 ast_sched_runq(ast_channel_sched(chan));
3187
3188                 /* See maximum time of waiting */
3189                 if ((res = ast_sched_wait(ast_channel_sched(chan))) < 0)
3190                         res = 1000;
3191
3192                 /* Wait for frame */
3193                 if (ast_waitfor(chan, res) > 0) {
3194                         if (!(fr = ast_read(chan))) {
3195                                 reason = "hangup";
3196                                 break;
3197                         }
3198                 }
3199
3200                 /* Perform timeout check */
3201                 if ((timeout > 0) && (start > 0)) {
3202                         time(&current);
3203                         if ((current - start) >= timeout) {
3204                                 reason = "timeout";
3205                                 if (fr)
3206                                         ast_frfree(fr);
3207                                 break;
3208                         }
3209                 }
3210
3211                 /* Check the speech structure for any changes */
3212                 ast_mutex_lock(&speech->lock);
3213
3214                 /* See if we need to quiet the audio stream playback */
3215                 if (ast_test_flag(speech, AST_SPEECH_QUIET) && ast_channel_stream(chan)) {
3216                         current_offset = ast_tellstream(ast_channel_stream(chan));
3217                         ast_stopstream(chan);
3218                         ast_clear_flag(speech, AST_SPEECH_QUIET);
3219                 }
3220
3221                 /* Check each state */
3222                 switch (speech->state) {
3223                 case AST_SPEECH_STATE_READY:
3224                         /* If the stream is done, start timeout calculation */
3225                         if ((timeout > 0) && start == 0 && ((!ast_channel_stream(chan)) || (ast_channel_streamid(chan) == -1 && ast_channel_timingfunc(chan) == NULL))) {
3226                                 ast_stopstream(chan);
3227                                 time(&start);
3228                         }
3229                         /* Write audio frame data into speech engine if possible */
3230                         if (fr && fr->frametype == AST_FRAME_VOICE)
3231                                 ast_speech_write(speech, fr->data.ptr, fr->datalen);
3232                         break;
3233                 case AST_SPEECH_STATE_WAIT:
3234                         /* Cue waiting sound if not already playing */
3235                         if ((!ast_channel_stream(chan)) || (ast_channel_streamid(chan) == -1 && ast_channel_timingfunc(chan) == NULL)) {
3236                                 ast_stopstream(chan);
3237                                 /* If a processing sound exists, or is not none - play it */
3238                                 if (!ast_strlen_zero(speech->processing_sound) && strcasecmp(speech->processing_sound, "none"))
3239                                         speech_streamfile(chan, speech->processing_sound, ast_channel_language(chan), 0);
3240                         }
3241                         break;
3242                 case AST_SPEECH_STATE_DONE:
3243                         /* Get the results */
3244                         speech->results = ast_speech_results_get(speech);
3245                         /* Change state to not ready */
3246                         ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
3247                         reason = "speech";
3248                         break;
3249                 default:
3250                         break;
3251                 }
3252                 ast_mutex_unlock(&speech->lock);
3253
3254                 /* Check frame for DTMF or hangup */
3255                 if (fr) {
3256                         if (fr->frametype == AST_FRAME_DTMF) {
3257                                 reason = "dtmf";
3258                                 dtmf = fr->subclass.integer;
3259                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_HANGUP) {
3260                                 reason = "hangup";
3261                         }
3262                         ast_frfree(fr);
3263                 }
3264         }
3265
3266         if (!strcasecmp(reason, "speech")) {
3267                 /* Build string containing speech results */
3268                 for (result = speech->results; result; result = AST_LIST_NEXT(result, list)) {
3269                         /* Build result string */
3270                         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);
3271                         /* Increment result count */
3272                         i++;
3273                 }
3274                 /* Print out */
3275                 ast_agi_send(agi->fd, chan, "200 result=1 (speech) endpos=%ld results=%d %s\n", current_offset, i, tmp);
3276         } else if (!strcasecmp(reason, "dtmf")) {
3277                 ast_agi_send(agi->fd, chan, "200 result=1 (digit) digit=%c endpos=%ld\n", dtmf, current_offset);
3278         } else if (!strcasecmp(reason, "hangup") || !strcasecmp(reason, "timeout")) {
3279                 ast_agi_send(agi->fd, chan, "200 result=1 (%s) endpos=%ld\n", reason, current_offset);
3280         } else {
3281                 ast_agi_send(agi->fd, chan, "200 result=0 endpos=%ld\n", current_offset);
3282         }
3283
3284         return RESULT_SUCCESS;
3285 }
3286
3287 /*!
3288  * \brief AGI commands list
3289  */
3290 static struct agi_command commands[] = {
3291         { { "answer", NULL }, handle_answer, NULL, NULL, 0 },
3292         { { "asyncagi", "break", NULL }, handle_asyncagi_break, NULL, NULL, 1 },
3293         { { "channel", "status", NULL }, handle_channelstatus, NULL, NULL, 0 },
3294         { { "database", "del", NULL }, handle_dbdel, NULL, NULL, 1 },
3295         { { "database", "deltree", NULL }, handle_dbdeltree, NULL, NULL, 1 },
3296         { { "database", "get", NULL }, handle_dbget, NULL, NULL, 1 },
3297         { { "database", "put", NULL }, handle_dbput, NULL, NULL, 1 },
3298         { { "exec", NULL }, handle_exec, NULL, NULL, 1 },
3299         { { "get", "data", NULL }, handle_getdata, NULL, NULL, 0 },
3300         { { "get", "full", "variable", NULL }, handle_getvariablefull, NULL, NULL, 1 },
3301         { { "get", "option", NULL }, handle_getoption, NULL, NULL, 0 },
3302         { { "get", "variable", NULL }, handle_getvariable, NULL, NULL, 1 },
3303         { { "hangup", NULL }, handle_hangup, NULL, NULL, 0 },
3304         { { "noop", NULL }, handle_noop, NULL, NULL, 1 },
3305         { { "receive", "char", NULL }, handle_recvchar, NULL, NULL, 0 },
3306         { { "receive", "text", NULL }, handle_recvtext, NULL, NULL, 0 },
3307         { { "record", "file", NULL }, handle_recordfile, NULL, NULL, 0 },
3308         { { "say", "alpha", NULL }, handle_sayalpha, NULL, NULL, 0},
3309         { { "say", "digits", NULL }, handle_saydigits, NULL, NULL, 0 },
3310         { { "say", "number", NULL }, handle_saynumber, NULL, NULL, 0 },
3311         { { "say", "phonetic", NULL }, handle_sayphonetic, NULL, NULL, 0},
3312         { { "say", "date", NULL }, handle_saydate, NULL, NULL, 0},
3313         { { "say", "time", NULL }, handle_saytime, NULL, NULL, 0},
3314         { { "say", "datetime", NULL }, handle_saydatetime, NULL, NULL, 0},
3315         { { "send", "image", NULL }, handle_sendimage, NULL, NULL, 0},
3316         { { "send", "text", NULL }, handle_sendtext, NULL, NULL, 0},
3317         { { "set", "autohangup", NULL }, handle_autohangup, NULL, NULL, 0},
3318         { { "set", "callerid", NULL }, handle_setcallerid, NULL, NULL, 0},
3319         { { "set", "context", NULL }, handle_setcontext, NULL, NULL, 0},
3320         { { "set", "extension", NULL }, handle_setextension, NULL, NULL, 0},
3321         { { "set", "music", NULL }, handle_setmusic, NULL, NULL, 0 },
3322         { { "set", "priority", NULL }, handle_setpriority, NULL, NULL, 0 },
3323         { { "set", "variable", NULL }, handle_setvariable, NULL, NULL, 1 },
3324         { { "stream", "file", NULL }, handle_streamfile, NULL, NULL, 0 },
3325         { { "control", "stream", "file", NULL }, handle_controlstreamfile, NULL, NULL, 0 },
3326         { { "tdd", "mode", NULL }, handle_tddmode, NULL, NULL, 0 },
3327         { { "verbose", NULL }, handle_verbose, NULL, NULL, 1 },
3328         { { "wait", "for", "digit", NULL }, handle_waitfordigit, NULL, NULL, 0 },
3329         { { "speech", "create", NULL }, handle_speechcreate, NULL, NULL, 0 },
3330         { { "speech", "set", NULL }, handle_speechset, NULL, NULL, 0 },
3331         { { "speech", "destroy", NULL }, handle_speechdestroy, NULL, NULL, 1 },
3332         { { "speech", "load", "grammar", NULL }, handle_speechloadgrammar, NULL, NULL, 0 },
3333         { { "speech", "unload", "grammar", NULL }, handle_speechunloadgrammar, NULL, NULL, 1 },
3334         { { "speech", "activate", "grammar", NULL }, handle_speechactivategrammar, NULL, NULL, 0 },
3335         { { "speech", "deactivate", "grammar", NULL }, handle_speechdeactivategrammar, NULL, NULL, 0 },
3336         { { "speech", "recognize", NULL }, handle_speechrecognize, NULL, NULL, 0 },
3337 };
3338
3339 static AST_RWLIST_HEAD_STATIC(agi_commands, agi_command);
3340
3341 static char *help_workhorse(int fd, const char * const match[])
3342 {
3343         char fullcmd[MAX_CMD_LEN], matchstr[MAX_CMD_LEN];
3344         struct agi_command *e;
3345
3346         if (match)
3347                 ast_join(matchstr, sizeof(matchstr), match);
3348
3349         ast_cli(fd, "%5.5s %30.30s   %s\n","Dead","Command","Description");
3350         AST_RWLIST_RDLOCK(&agi_commands);
3351         AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
3352                 if (!e->cmda[0])
3353                         break;
3354                 /* Hide commands that start with '_' */
3355                 if ((e->cmda[0])[0] == '_')
3356                         continue;
3357                 ast_join(fullcmd, sizeof(fullcmd), e->cmda);
3358                 if (match && strncasecmp(matchstr, fullcmd, strlen(matchstr)))
3359                         continue;
3360                 ast_cli(fd, "%5.5s %30.30s   %s\n", e->dead ? "Yes" : "No" , fullcmd, S_OR(e->summary, "Not available"));
3361         }
3362         AST_RWLIST_UNLOCK(&agi_commands);
3363
3364         return CLI_SUCCESS;
3365 }
3366
3367 int AST_OPTIONAL_API_NAME(ast_agi_register)(struct ast_module *mod, agi_command *cmd)
3368 {
3369         char fullcmd[MAX_CMD_LEN];
3370
3371         ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
3372
3373         if (!find_command(cmd->cmda, 1)) {
3374                 *((enum ast_doc_src *) &cmd->docsrc) = AST_STATIC_DOC;
3375                 if (ast_strlen_zero(cmd->summary) && ast_strlen_zero(cmd->usage)) {
3376 #ifdef AST_XML_DOCS
3377                         *((char **) &cmd->summary) = ast_xmldoc_build_synopsis("agi", fullcmd, NULL);
3378                         *((char **) &cmd->usage) = ast_xmldoc_build_description("agi", fullcmd, NULL);
3379                         *((char **) &cmd->syntax) = ast_xmldoc_build_syntax("agi", fullcmd, NULL);
3380                         *((char **) &cmd->seealso) = ast_xmldoc_build_seealso("agi", fullcmd, NULL);
3381                         *((enum ast_doc_src *) &cmd->docsrc) = AST_XML_DOC;
3382 #endif
3383 #ifndef HAVE_NULLSAFE_PRINTF
3384                         if (!cmd->summary) {
3385                                 *((char **) &cmd->summary) = ast_strdup("");
3386                         }
3387                         if (!cmd->usage) {
3388                                 *((char **) &cmd->usage) = ast_strdup("");
3389                         }
3390                         if (!cmd->syntax) {
3391                                 *((char **) &cmd->syntax) = ast_strdup("");
3392                         }
3393                         if (!cmd->seealso) {
3394                                 *((char **) &cmd->seealso) = ast_strdup("");
3395                         }
3396 #endif
3397                 }
3398
3399                 cmd->mod = mod;
3400                 AST_RWLIST_WRLOCK(&agi_commands);
3401                 AST_LIST_INSERT_TAIL(&agi_commands, cmd, list);
3402                 AST_RWLIST_UNLOCK(&agi_commands);
3403                 if (mod != ast_module_info->self)
3404                         ast_module_ref(ast_module_info->self);
3405                 ast_verb(2, "AGI Command '%s' registered\n",fullcmd);
3406                 return 1;
3407         } else {
3408                 ast_log(LOG_WARNING, "Command already registered!\n");
3409                 return 0;
3410         }
3411 }
3412
3413 int AST_OPTIONAL_API_NAME(ast_agi_unregister)(struct ast_module *mod, agi_command *cmd)
3414 {
3415         struct agi_command *e;
3416         int unregistered = 0;
3417         char fullcmd[MAX_CMD_LEN];
3418
3419         ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
3420
3421         AST_RWLIST_WRLOCK(&agi_commands);
3422         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&agi_commands, e, list) {
3423                 if (cmd == e) {
3424                         AST_RWLIST_REMOVE_CURRENT(list);
3425                         if (mod != ast_module_info->self)
3426                                 ast_module_unref(ast_module_info->self);
3427 #ifdef AST_XML_DOCS
3428                         if (e->docsrc == AST_XML_DOC) {
3429                                 ast_free((char *) e->summary);
3430                                 ast_free((char *) e->usage);
3431                                 ast_free((char *) e->syntax);
3432                                 ast_free((char *) e->seealso);
3433                                 *((char **) &e->summary) = NULL;
3434                                 *((char **) &e->usage) = NULL;
3435                                 *((char **) &e->syntax) = NULL;
3436                                 *((char **) &e->seealso) = NULL;
3437                         }
3438 #endif
3439                         unregistered=1;
3440                         break;
3441                 }
3442         }
3443         AST_RWLIST_TRAVERSE_SAFE_END;
3444         AST_RWLIST_UNLOCK(&agi_commands);
3445         if (unregistered)
3446                 ast_verb(2, "AGI Command '%s' unregistered\n",fullcmd);
3447         else
3448                 ast_log(LOG_WARNING, "Unable to unregister command: '%s'!\n",fullcmd);
3449         return unregistered;
3450 }
3451
3452 int AST_OPTIONAL_API_NAME(ast_agi_register_multiple)(struct ast_module *mod, struct agi_command *cmd, unsigned int len)
3453 {
3454         unsigned int i, x = 0;
3455
3456         for (i = 0; i < len; i++) {
3457                 if (ast_agi_register(mod, cmd + i) == 1) {
3458                         x++;
3459                         continue;
3460                 }
3461
3462                 /* registration failed, unregister everything
3463                    that had been registered up to that point
3464                 */
3465                 for (; x > 0; x--) {
3466                         /* we are intentionally ignoring the
3467                            result of ast_agi_unregister() here,
3468                            but it should be safe to do so since
3469                            we just registered these commands and
3470                            the only possible way for unregistration
3471                            to fail is if the command is not
3472                            registered
3473                         */
3474                         (void) ast_agi_unregister(mod, cmd + x - 1);
3475                 }
3476                 return -1;
3477         }
3478
3479         return 0;
3480 }
3481
3482 int AST_OPTIONAL_API_NAME(ast_agi_unregister_multiple)(struct ast_module *mod, struct agi_command *cmd, unsigned int len)
3483 {
3484         unsigned int i;
3485         int res = 0;
3486
3487         for (i = 0; i < len; i++) {
3488                 /* remember whether any of the unregistration
3489                    attempts failed... there is no recourse if
3490                    any of them do
3491                 */
3492                 res |= ast_agi_unregister(mod, cmd + i);