74d665bd5018fdb9b1ae2cca5f2043a9d9223672
[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         int sensitivity = AST_SAY_CASE_NONE;
2317
2318         if (argc < 4 || argc > 5) {
2319                 return RESULT_SHOWUSAGE;
2320         }
2321
2322         if (argc > 4) {
2323                 switch (argv[4][0]) {
2324                 case 'a':
2325                 case 'A':
2326                         sensitivity = AST_SAY_CASE_ALL;
2327                         break;
2328                 case 'l':
2329                 case 'L':
2330                         sensitivity = AST_SAY_CASE_LOWER;
2331                         break;
2332                 case 'n':
2333                 case 'N':
2334                         sensitivity = AST_SAY_CASE_NONE;
2335                         break;
2336                 case 'u':
2337                 case 'U':
2338                         sensitivity = AST_SAY_CASE_UPPER;
2339                         break;
2340                 case '\0':
2341                         break;
2342                 default:
2343                         return RESULT_SHOWUSAGE;
2344                 }
2345         }
2346         res = ast_say_character_str_full(chan, argv[2], argv[3], ast_channel_language(chan), sensitivity, agi->audio, agi->ctrl);
2347         if (res == 1) /* New command */
2348                 return RESULT_SUCCESS;
2349         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2350         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2351 }
2352
2353 static int handle_saydate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2354 {
2355         int res, num;
2356
2357         if (argc != 4)
2358                 return RESULT_SHOWUSAGE;
2359         if (sscanf(argv[2], "%30d", &num) != 1)
2360                 return RESULT_SHOWUSAGE;
2361         res = ast_say_date(chan, num, argv[3], ast_channel_language(chan));
2362         if (res == 1)
2363                 return RESULT_SUCCESS;
2364         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2365         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2366 }
2367
2368 static int handle_saytime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2369 {
2370         int res, num;
2371
2372         if (argc != 4)
2373                 return RESULT_SHOWUSAGE;
2374         if (sscanf(argv[2], "%30d", &num) != 1)
2375                 return RESULT_SHOWUSAGE;
2376         res = ast_say_time(chan, num, argv[3], ast_channel_language(chan));
2377         if (res == 1)
2378                 return RESULT_SUCCESS;
2379         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2380         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2381 }
2382
2383 static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2384 {
2385         int res = 0;
2386         time_t unixtime;
2387         const char *format, *zone = NULL;
2388
2389         if (argc < 4)
2390                 return RESULT_SHOWUSAGE;
2391
2392         if (argc > 4) {
2393                 format = argv[4];
2394         } else {
2395                 /* XXX this doesn't belong here, but in the 'say' module */
2396                 if (!strcasecmp(ast_channel_language(chan), "de")) {
2397                         format = "A dBY HMS";
2398                 } else {
2399                         format = "ABdY 'digits/at' IMp";
2400                 }
2401         }
2402
2403         if (argc > 5 && !ast_strlen_zero(argv[5]))
2404                 zone = argv[5];
2405
2406         if (ast_get_time_t(argv[2], &unixtime, 0, NULL))
2407                 return RESULT_SHOWUSAGE;
2408
2409         res = ast_say_date_with_format(chan, unixtime, argv[3], ast_channel_language(chan), format, zone);
2410         if (res == 1)
2411                 return RESULT_SUCCESS;
2412
2413         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2414         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2415 }
2416
2417 static int handle_sayphonetic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2418 {
2419         int res;
2420
2421         if (argc != 4)
2422                 return RESULT_SHOWUSAGE;
2423
2424         res = ast_say_phonetic_str_full(chan, argv[2], argv[3], ast_channel_language(chan), agi->audio, agi->ctrl);
2425         if (res == 1) /* New command */
2426                 return RESULT_SUCCESS;
2427         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2428         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2429 }
2430
2431 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2432 {
2433         int res, max, timeout;
2434         char data[1024];
2435
2436         if (argc < 3)
2437                 return RESULT_SHOWUSAGE;
2438         if (argc >= 4)
2439                 timeout = atoi(argv[3]);
2440         else
2441                 timeout = 0;
2442         if (argc >= 5)
2443                 max = atoi(argv[4]);
2444         else
2445                 max = 1024;
2446         res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
2447         if (res == 2)                   /* New command */
2448                 return RESULT_SUCCESS;
2449         else if (res == 1)
2450                 ast_agi_send(agi->fd, chan, "200 result=%s (timeout)\n", data);
2451         else if (res < 0 )
2452                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2453         else
2454                 ast_agi_send(agi->fd, chan, "200 result=%s\n", data);
2455         return RESULT_SUCCESS;
2456 }
2457
2458 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2459 {
2460
2461         if (argc != 3)
2462                 return RESULT_SHOWUSAGE;
2463         ast_channel_context_set(chan, argv[2]);
2464         ast_agi_send(agi->fd, chan, "200 result=0\n");
2465         return RESULT_SUCCESS;
2466 }
2467
2468 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2469 {
2470         if (argc != 3)
2471                 return RESULT_SHOWUSAGE;
2472         ast_channel_exten_set(chan, argv[2]);
2473         ast_agi_send(agi->fd, chan, "200 result=0\n");
2474         return RESULT_SUCCESS;
2475 }
2476
2477 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2478 {
2479         int pri;
2480
2481         if (argc != 3)
2482                 return RESULT_SHOWUSAGE;
2483
2484         if (sscanf(argv[2], "%30d", &pri) != 1) {
2485                 pri = ast_findlabel_extension(chan, ast_channel_context(chan), ast_channel_exten(chan), argv[2],
2486                         S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL));
2487                 if (pri < 1)
2488                         return RESULT_SHOWUSAGE;
2489         }
2490
2491         ast_explicit_goto(chan, NULL, NULL, pri);
2492         ast_agi_send(agi->fd, chan, "200 result=0\n");
2493         return RESULT_SUCCESS;
2494 }
2495
2496 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2497 {
2498         struct ast_filestream *fs;
2499         struct ast_frame *f;
2500         struct timeval start;
2501         long sample_offset = 0;
2502         int res = 0;
2503         int ms;
2504
2505         struct ast_dsp *sildet=NULL;         /* silence detector dsp */
2506         int totalsilence = 0;
2507         int dspsilence = 0;
2508         int silence = 0;                /* amount of silence to allow */
2509         int gotsilence = 0;             /* did we timeout for silence? */
2510         char *silencestr = NULL;
2511         struct ast_format rfmt;
2512         ast_format_clear(&rfmt);
2513
2514         /* XXX EAGI FIXME XXX */
2515
2516         if (argc < 6)
2517                 return RESULT_SHOWUSAGE;
2518         if (sscanf(argv[5], "%30d", &ms) != 1)
2519                 return RESULT_SHOWUSAGE;
2520
2521         if (argc > 6)
2522                 silencestr = strchr(argv[6],'s');
2523         if ((argc > 7) && (!silencestr))
2524                 silencestr = strchr(argv[7],'s');
2525         if ((argc > 8) && (!silencestr))
2526                 silencestr = strchr(argv[8],'s');
2527
2528         if (silencestr) {
2529                 if (strlen(silencestr) > 2) {
2530                         if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
2531                                 silencestr++;
2532                                 silencestr++;
2533                                 if (silencestr)
2534                                         silence = atoi(silencestr);
2535                                 if (silence > 0)
2536                                         silence *= 1000;
2537                         }
2538                 }
2539         }
2540
2541         if (silence > 0) {
2542                 ast_format_copy(&rfmt, ast_channel_readformat(chan));
2543                 res = ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
2544                 if (res < 0) {
2545                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
2546                         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2547                         return RESULT_FAILURE;
2548                 }
2549                 sildet = ast_dsp_new();
2550                 if (!sildet) {
2551                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
2552                         ast_agi_send(agi->fd, chan, "200 result=-1\n");
2553                         return RESULT_FAILURE;
2554                 }
2555                 ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
2556         }
2557
2558         /* backward compatibility, if no offset given, arg[6] would have been
2559          * caught below and taken to be a beep, else if it is a digit then it is a
2560          * offset */
2561         if ((argc >6) && (sscanf(argv[6], "%30ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
2562                 res = ast_streamfile(chan, "beep", ast_channel_language(chan));
2563
2564         if ((argc > 7) && (!strchr(argv[7], '=')))
2565                 res = ast_streamfile(chan, "beep", ast_channel_language(chan));
2566
2567         if (!res)
2568                 res = ast_waitstream(chan, argv[4]);
2569         if (res) {
2570                 ast_agi_send(agi->fd, chan, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
2571         } else {
2572                 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, AST_FILE_MODE);
2573                 if (!fs) {
2574                         res = -1;
2575                         ast_agi_send(agi->fd, chan, "200 result=%d (writefile)\n", res);
2576                         if (sildet)
2577                                 ast_dsp_free(sildet);
2578                         return RESULT_FAILURE;
2579                 }
2580
2581                 /* Request a video update */
2582                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
2583
2584                 ast_channel_stream_set(chan, fs);
2585                 ast_applystream(chan,fs);
2586                 /* really should have checks */
2587                 ast_seekstream(fs, sample_offset, SEEK_SET);
2588                 ast_truncstream(fs);
2589
2590                 start = ast_tvnow();
2591                 while ((ms < 0) || ast_tvdiff_ms(ast_tvnow(), start) < ms) {
2592                         res = ast_waitfor(chan, ms - ast_tvdiff_ms(ast_tvnow(), start));
2593                         if (res < 0) {
2594                                 ast_closestream(fs);
2595                                 ast_agi_send(agi->fd, chan, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
2596                                 if (sildet)
2597                                         ast_dsp_free(sildet);
2598                                 return RESULT_FAILURE;
2599                         }
2600                         f = ast_read(chan);
2601                         if (!f) {
2602                                 ast_agi_send(agi->fd, chan, "200 result=%d (hangup) endpos=%ld\n", -1, sample_offset);
2603                                 ast_closestream(fs);
2604                                 if (sildet)
2605                                         ast_dsp_free(sildet);
2606                                 return RESULT_FAILURE;
2607                         }
2608                         switch(f->frametype) {
2609                         case AST_FRAME_DTMF:
2610                                 if (strchr(argv[4], f->subclass.integer)) {
2611                                         /* This is an interrupting chracter, so rewind to chop off any small
2612                                            amount of DTMF that may have been recorded
2613                                         */
2614                                         ast_stream_rewind(fs, 200);
2615                                         ast_truncstream(fs);
2616                                         sample_offset = ast_tellstream(fs);
2617                                         ast_agi_send(agi->fd, chan, "200 result=%d (dtmf) endpos=%ld\n", f->subclass.integer, sample_offset);
2618                                         ast_closestream(fs);
2619                                         ast_frfree(f);
2620                                         if (sildet)
2621                                                 ast_dsp_free(sildet);
2622                                         return RESULT_SUCCESS;
2623                                 }
2624                                 break;
2625                         case AST_FRAME_VOICE:
2626                                 ast_writestream(fs, f);
2627                                 /* this is a safe place to check progress since we know that fs
2628                                  * is valid after a write, and it will then have our current
2629                                  * location */
2630                                 sample_offset = ast_tellstream(fs);
2631                                 if (silence > 0) {
2632                                         dspsilence = 0;
2633                                         ast_dsp_silence(sildet, f, &dspsilence);
2634                                         if (dspsilence) {
2635                                                 totalsilence = dspsilence;
2636                                         } else {
2637                                                 totalsilence = 0;
2638                                         }
2639                                         if (totalsilence > silence) {
2640                                                 /* Ended happily with silence */
2641                                                 gotsilence = 1;
2642                                                 break;
2643                                         }
2644                                 }
2645                                 break;
2646                         case AST_FRAME_VIDEO:
2647                                 ast_writestream(fs, f);
2648                         default:
2649                                 /* Ignore all other frames */
2650                                 break;
2651                         }
2652                         ast_frfree(f);
2653                         if (gotsilence)
2654                                 break;
2655                 }
2656
2657                 if (gotsilence) {
2658                         ast_stream_rewind(fs, silence-1000);
2659                         ast_truncstream(fs);
2660                         sample_offset = ast_tellstream(fs);
2661                 }
2662                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
2663                 ast_closestream(fs);
2664         }
2665
2666         if (silence > 0) {
2667                 res = ast_set_read_format(chan, &rfmt);
2668                 if (res)
2669                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", ast_channel_name(chan));
2670                 ast_dsp_free(sildet);
2671         }
2672
2673         return RESULT_SUCCESS;
2674 }
2675
2676 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2677 {
2678         double timeout;
2679         struct timeval whentohangup = { 0, 0 };
2680
2681         if (argc != 3)
2682                 return RESULT_SHOWUSAGE;
2683         if (sscanf(argv[2], "%30lf", &timeout) != 1)
2684                 return RESULT_SHOWUSAGE;
2685         if (timeout < 0)
2686                 timeout = 0;
2687         if (timeout) {
2688                 whentohangup.tv_sec = timeout;
2689                 whentohangup.tv_usec = (timeout - whentohangup.tv_sec) * 1000000.0;
2690         }
2691         ast_channel_setwhentohangup_tv(chan, whentohangup);
2692         ast_agi_send(agi->fd, chan, "200 result=0\n");
2693         return RESULT_SUCCESS;
2694 }
2695
2696 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2697 {
2698         struct ast_channel *c;
2699
2700         if (argc == 1) {
2701                 /* no argument: hangup the current channel */
2702                 ast_set_hangupsource(chan, "dialplan/agi", 0);
2703                 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
2704                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2705                 return RESULT_SUCCESS;
2706         } else if (argc == 2) {
2707                 /* one argument: look for info on the specified channel */
2708                 if ((c = ast_channel_get_by_name(argv[1]))) {
2709                         /* we have a matching channel */
2710                         ast_set_hangupsource(c, "dialplan/agi", 0);
2711                         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
2712                         c = ast_channel_unref(c);
2713                         ast_agi_send(agi->fd, chan, "200 result=1\n");
2714                         return RESULT_SUCCESS;
2715                 }
2716                 /* if we get this far no channel name matched the argument given */
2717                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2718                 return RESULT_SUCCESS;
2719         } else {
2720                 return RESULT_SHOWUSAGE;
2721         }
2722 }
2723
2724 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2725 {
2726         int res, workaround;
2727         struct ast_app *app_to_exec;
2728
2729         if (argc < 2)
2730                 return RESULT_SHOWUSAGE;
2731
2732         ast_verb(3, "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argc >= 3 ? argv[2] : "");
2733
2734         if ((app_to_exec = pbx_findapp(argv[1]))) {
2735                 if (!(workaround = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS))) {
2736                         ast_set_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS);
2737                 }
2738                 if (ast_compat_res_agi && argc >= 3 && !ast_strlen_zero(argv[2])) {
2739                         char *compat = ast_alloca(strlen(argv[2]) * 2 + 1), *cptr;
2740                         const char *vptr;
2741                         for (cptr = compat, vptr = argv[2]; *vptr; vptr++) {
2742                                 if (*vptr == ',') {
2743                                         *cptr++ = '\\';
2744                                         *cptr++ = ',';
2745                                 } else if (*vptr == '|') {
2746                                         *cptr++ = ',';
2747                                 } else {
2748                                         *cptr++ = *vptr;
2749                                 }
2750                         }
2751                         *cptr = '\0';
2752                         res = pbx_exec(chan, app_to_exec, compat);
2753                 } else {
2754                         res = pbx_exec(chan, app_to_exec, argc == 2 ? "" : argv[2]);
2755                 }
2756                 if (!workaround) {
2757                         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS);
2758                 }
2759         } else {
2760                 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
2761                 res = -2;
2762         }
2763         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2764
2765         /* Even though this is wrong, users are depending upon this result. */
2766         return res;
2767 }
2768
2769 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2770 {
2771         char tmp[256]="";
2772         char *l = NULL, *n = NULL;
2773
2774         if (argv[2]) {
2775                 ast_copy_string(tmp, argv[2], sizeof(tmp));
2776                 ast_callerid_parse(tmp, &n, &l);
2777                 if (l)
2778                         ast_shrink_phone_number(l);
2779                 else
2780                         l = "";
2781                 if (!n)
2782                         n = "";
2783                 ast_set_callerid(chan, l, n, NULL);
2784         }
2785
2786         ast_agi_send(agi->fd, chan, "200 result=1\n");
2787         return RESULT_SUCCESS;
2788 }
2789
2790 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2791 {
2792         if (argc == 2) {
2793                 /* no argument: supply info on the current channel */
2794                 ast_agi_send(agi->fd, chan, "200 result=%d\n", ast_channel_state(chan));
2795                 return RESULT_SUCCESS;
2796         } else if (argc == 3) {
2797                 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
2798
2799                 /* one argument: look for info on the specified channel */
2800                 if ((msg = stasis_cache_get(ast_channel_cache_by_name(), ast_channel_snapshot_type(), argv[2]))) {
2801                         struct ast_channel_snapshot *snapshot = stasis_message_data(msg);
2802
2803                         ast_agi_send(agi->fd, chan, "200 result=%d\n", snapshot->state);
2804                         return RESULT_SUCCESS;
2805                 }
2806                 /* if we get this far no channel name matched the argument given */
2807                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2808                 return RESULT_SUCCESS;
2809         } else {
2810                 return RESULT_SHOWUSAGE;
2811         }
2812 }
2813
2814 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2815 {
2816         if (argv[3])
2817                 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
2818
2819         ast_agi_send(agi->fd, chan, "200 result=1\n");
2820         return RESULT_SUCCESS;
2821 }
2822
2823 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2824 {
2825         char *ret;
2826         char tempstr[1024] = "";
2827
2828         if (argc != 3)
2829                 return RESULT_SHOWUSAGE;
2830
2831         /* check if we want to execute an ast_custom_function */
2832         if (!ast_strlen_zero(argv[2]) && (argv[2][strlen(argv[2]) - 1] == ')')) {
2833                 ret = ast_func_read(chan, argv[2], tempstr, sizeof(tempstr)) ? NULL : tempstr;
2834         } else {
2835                 pbx_retrieve_variable(chan, argv[2], &ret, tempstr, sizeof(tempstr), NULL);
2836         }
2837
2838         if (ret)
2839                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ret);
2840         else
2841                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2842
2843         return RESULT_SUCCESS;
2844 }
2845
2846 static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2847 {
2848         struct ast_channel *chan2 = NULL;
2849
2850         if (argc != 4 && argc != 5) {
2851                 return RESULT_SHOWUSAGE;
2852         }
2853
2854         if (argc == 5) {
2855                 chan2 = ast_channel_get_by_name(argv[4]);
2856         } else {
2857                 chan2 = ast_channel_ref(chan);
2858         }
2859
2860         if (chan2) {
2861                 struct ast_str *str = ast_str_create(16);
2862                 if (!str) {
2863                         ast_agi_send(agi->fd, chan, "200 result=0\n");
2864                         return RESULT_SUCCESS;
2865                 }
2866                 ast_str_substitute_variables(&str, 0, chan2, argv[3]);
2867                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(str));
2868                 ast_free(str);
2869         } else {
2870                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2871         }
2872
2873         if (chan2) {
2874                 chan2 = ast_channel_unref(chan2);
2875         }
2876
2877         return RESULT_SUCCESS;
2878 }
2879
2880 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2881 {
2882         int level = 0;
2883
2884         if (argc < 2)
2885                 return RESULT_SHOWUSAGE;
2886
2887         if (argv[2])
2888                 sscanf(argv[2], "%30d", &level);
2889
2890         ast_verb(level, "%s: %s\n", ast_channel_data(chan), argv[1]);
2891
2892         ast_agi_send(agi->fd, chan, "200 result=1\n");
2893
2894         return RESULT_SUCCESS;
2895 }
2896
2897 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2898 {
2899         int res;
2900         struct ast_str *buf;
2901
2902         if (argc != 4)
2903                 return RESULT_SHOWUSAGE;
2904
2905         if (!(buf = ast_str_create(16))) {
2906                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2907                 return RESULT_SUCCESS;
2908         }
2909
2910         do {
2911                 res = ast_db_get(argv[2], argv[3], ast_str_buffer(buf), ast_str_size(buf));
2912                 ast_str_update(buf);
2913                 if (ast_str_strlen(buf) < ast_str_size(buf) - 1) {
2914                         break;
2915                 }
2916                 if (ast_str_make_space(&buf, ast_str_size(buf) * 2)) {
2917                         break;
2918                 }
2919         } while (1);
2920
2921         if (res)
2922                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2923         else
2924                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(buf));
2925
2926         ast_free(buf);
2927         return RESULT_SUCCESS;
2928 }
2929
2930 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2931 {
2932         int res;
2933
2934         if (argc != 5)
2935                 return RESULT_SHOWUSAGE;
2936         res = ast_db_put(argv[2], argv[3], argv[4]);
2937         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2938         return RESULT_SUCCESS;
2939 }
2940
2941 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2942 {
2943         int res;
2944
2945         if (argc != 4)
2946                 return RESULT_SHOWUSAGE;
2947         res = ast_db_del(argv[2], argv[3]);
2948         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2949         return RESULT_SUCCESS;
2950 }
2951
2952 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2953 {
2954         int num_deleted;
2955
2956         if ((argc < 3) || (argc > 4)) {
2957                 return RESULT_SHOWUSAGE;
2958         }
2959         if (argc == 4) {
2960                 num_deleted = ast_db_deltree(argv[2], argv[3]);
2961         } else {
2962                 num_deleted = ast_db_deltree(argv[2], NULL);
2963         }
2964
2965         ast_agi_send(agi->fd, chan, "200 result=%c\n", num_deleted > 0 ? '0' : '1');
2966         return RESULT_SUCCESS;
2967 }
2968
2969 static char *handle_cli_agi_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2970 {
2971         switch (cmd) {
2972         case CLI_INIT:
2973                 e->command = "agi set debug [on|off]";
2974                 e->usage =
2975                         "Usage: agi set debug [on|off]\n"
2976                         "       Enables/disables dumping of AGI transactions for\n"
2977                         "       debugging purposes.\n";
2978                 return NULL;
2979
2980         case CLI_GENERATE:
2981                 return NULL;
2982         }
2983
2984         if (a->argc != e->args)
2985                 return CLI_SHOWUSAGE;
2986
2987         if (strncasecmp(a->argv[3], "off", 3) == 0) {
2988                 agidebug = 0;
2989         } else if (strncasecmp(a->argv[3], "on", 2) == 0) {
2990                 agidebug = 1;
2991         } else {
2992                 return CLI_SHOWUSAGE;
2993         }
2994         ast_cli(a->fd, "AGI Debugging %sabled\n", agidebug ? "En" : "Dis");
2995         return CLI_SUCCESS;
2996 }
2997
2998 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, const char * const argv[])
2999 {
3000         ast_agi_send(agi->fd, chan, "200 result=0\n");
3001         return RESULT_SUCCESS;
3002 }
3003
3004 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3005 {
3006         if (argc < 3) {
3007                 return RESULT_SHOWUSAGE;
3008         }
3009         if (!strncasecmp(argv[2], "on", 2))
3010                 ast_moh_start(chan, argc > 3 ? argv[3] : NULL, NULL);
3011         else if (!strncasecmp(argv[2], "off", 3))
3012                 ast_moh_stop(chan);
3013         ast_agi_send(agi->fd, chan, "200 result=0\n");
3014         return RESULT_SUCCESS;
3015 }
3016
3017 static int handle_speechcreate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3018 {
3019         struct ast_format_cap *cap;
3020         struct ast_format tmpfmt;
3021
3022         /* If a structure already exists, return an error */
3023         if (agi->speech) {
3024                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3025                 return RESULT_SUCCESS;
3026         }
3027
3028         if (!(cap = ast_format_cap_alloc_nolock())) {
3029                 return RESULT_FAILURE;
3030         }
3031         ast_format_cap_add(cap, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0));
3032         if ((agi->speech = ast_speech_new(argv[2], cap))) {
3033                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3034         } else {
3035                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3036         }
3037         cap = ast_format_cap_destroy(cap);
3038
3039         return RESULT_SUCCESS;
3040 }
3041
3042 static int handle_speechset(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3043 {
3044         /* Check for minimum arguments */
3045         if (argc != 4)
3046                 return RESULT_SHOWUSAGE;
3047
3048         /* Check to make sure speech structure exists */
3049         if (!agi->speech) {
3050                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3051                 return RESULT_SUCCESS;
3052         }
3053
3054         ast_speech_change(agi->speech, argv[2], argv[3]);
3055         ast_agi_send(agi->fd, chan, "200 result=1\n");
3056
3057         return RESULT_SUCCESS;
3058 }
3059
3060 static int handle_speechdestroy(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3061 {
3062         if (agi->speech) {
3063                 ast_speech_destroy(agi->speech);
3064                 agi->speech = NULL;
3065                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3066         } else {
3067                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3068         }
3069
3070         return RESULT_SUCCESS;
3071 }
3072
3073 static int handle_speechloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3074 {
3075         if (argc != 5)
3076                 return RESULT_SHOWUSAGE;
3077
3078         if (!agi->speech) {
3079                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3080                 return RESULT_SUCCESS;
3081         }
3082
3083         if (ast_speech_grammar_load(agi->speech, argv[3], argv[4]))
3084                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3085         else
3086                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3087
3088         return RESULT_SUCCESS;
3089 }
3090
3091 static int handle_speechunloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3092 {
3093         if (argc != 4)
3094                 return RESULT_SHOWUSAGE;
3095
3096         if (!agi->speech) {
3097                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3098                 return RESULT_SUCCESS;
3099         }
3100
3101         if (ast_speech_grammar_unload(agi->speech, argv[3]))
3102                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3103         else
3104                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3105
3106         return RESULT_SUCCESS;
3107 }
3108
3109 static int handle_speechactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3110 {
3111         if (argc != 4)
3112                 return RESULT_SHOWUSAGE;
3113
3114         if (!agi->speech) {
3115                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3116                 return RESULT_SUCCESS;
3117         }
3118
3119         if (ast_speech_grammar_activate(agi->speech, argv[3]))
3120                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3121         else
3122                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3123
3124         return RESULT_SUCCESS;
3125 }
3126
3127 static int handle_speechdeactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3128 {
3129         if (argc != 4)
3130                 return RESULT_SHOWUSAGE;
3131
3132         if (!agi->speech) {
3133                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3134                 return RESULT_SUCCESS;
3135         }
3136
3137         if (ast_speech_grammar_deactivate(agi->speech, argv[3]))
3138                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3139         else
3140                 ast_agi_send(agi->fd, chan, "200 result=1\n");
3141
3142         return RESULT_SUCCESS;
3143 }
3144
3145 static int speech_streamfile(struct ast_channel *chan, const char *filename, const char *preflang, int offset)
3146 {
3147         struct ast_filestream *fs = NULL;
3148
3149         if (!(fs = ast_openstream(chan, filename, preflang)))
3150                 return -1;
3151
3152         if (offset)
3153                 ast_seekstream(fs, offset, SEEK_SET);
3154
3155         if (ast_applystream(chan, fs))
3156                 return -1;
3157
3158         if (ast_playstream(fs))
3159                 return -1;
3160
3161         return 0;
3162 }
3163
3164 static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
3165 {
3166         struct ast_speech *speech = agi->speech;
3167         const char *prompt;
3168         char dtmf = 0, tmp[4096] = "", *buf = tmp;
3169         int timeout = 0, offset = 0, res = 0, i = 0;
3170         struct ast_format old_read_format;
3171         long current_offset = 0;
3172         const char *reason = NULL;
3173         struct ast_frame *fr = NULL;
3174         struct ast_speech_result *result = NULL;
3175         size_t left = sizeof(tmp);
3176         time_t start = 0, current;
3177
3178         if (argc < 4)
3179                 return RESULT_SHOWUSAGE;
3180
3181         if (!speech) {
3182                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3183                 return RESULT_SUCCESS;
3184         }
3185
3186         prompt = argv[2];
3187         timeout = atoi(argv[3]);
3188
3189         /* If offset is specified then convert from text to integer */
3190         if (argc == 5)
3191                 offset = atoi(argv[4]);
3192
3193         /* We want frames coming in signed linear */
3194         ast_format_copy(&old_read_format, ast_channel_readformat(chan));
3195         if (ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR)) {
3196                 ast_agi_send(agi->fd, chan, "200 result=0\n");
3197                 return RESULT_SUCCESS;
3198         }
3199
3200         /* Setup speech structure */
3201         if (speech->state == AST_SPEECH_STATE_NOT_READY || speech->state == AST_SPEECH_STATE_DONE) {
3202                 ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
3203                 ast_speech_start(speech);
3204         }
3205
3206         /* Start playing prompt */
3207         speech_streamfile(chan, prompt, ast_channel_language(chan), offset);
3208
3209         /* Go into loop reading in frames, passing to speech thingy, checking for hangup, all that jazz */
3210         while (ast_strlen_zero(reason)) {
3211                 /* Run scheduled items */
3212                 ast_sched_runq(ast_channel_sched(chan));
3213
3214                 /* See maximum time of waiting */
3215                 if ((res = ast_sched_wait(ast_channel_sched(chan))) < 0)
3216                         res = 1000;
3217
3218                 /* Wait for frame */
3219                 if (ast_waitfor(chan, res) > 0) {
3220                         if (!(fr = ast_read(chan))) {
3221                                 reason = "hangup";
3222                                 break;
3223                         }
3224                 }
3225
3226                 /* Perform timeout check */
3227                 if ((timeout > 0) && (start > 0)) {
3228                         time(&current);
3229                         if ((current - start) >= timeout) {
3230                                 reason = "timeout";
3231                                 if (fr)
3232                                         ast_frfree(fr);
3233                                 break;
3234                         }
3235                 }
3236
3237                 /* Check the speech structure for any changes */
3238                 ast_mutex_lock(&speech->lock);
3239
3240                 /* See if we need to quiet the audio stream playback */
3241                 if (ast_test_flag(speech, AST_SPEECH_QUIET) && ast_channel_stream(chan)) {
3242                         current_offset = ast_tellstream(ast_channel_stream(chan));
3243                         ast_stopstream(chan);
3244                         ast_clear_flag(speech, AST_SPEECH_QUIET);
3245                 }
3246
3247                 /* Check each state */
3248                 switch (speech->state) {
3249                 case AST_SPEECH_STATE_READY:
3250                         /* If the stream is done, start timeout calculation */
3251                         if ((timeout > 0) && start == 0 && ((!ast_channel_stream(chan)) || (ast_channel_streamid(chan) == -1 && ast_channel_timingfunc(chan) == NULL))) {
3252                                 ast_stopstream(chan);
3253                                 time(&start);
3254                         }
3255                         /* Write audio frame data into speech engine if possible */
3256                         if (fr && fr->frametype == AST_FRAME_VOICE)
3257                                 ast_speech_write(speech, fr->data.ptr, fr->datalen);
3258                         break;
3259                 case AST_SPEECH_STATE_WAIT:
3260                         /* Cue waiting sound if not already playing */
3261                         if ((!ast_channel_stream(chan)) || (ast_channel_streamid(chan) == -1 && ast_channel_timingfunc(chan) == NULL)) {
3262                                 ast_stopstream(chan);
3263                                 /* If a processing sound exists, or is not none - play it */
3264                                 if (!ast_strlen_zero(speech->processing_sound) && strcasecmp(speech->processing_sound, "none"))
3265                                         speech_streamfile(chan, speech->processing_sound, ast_channel_language(chan), 0);
3266                         }
3267                         break;
3268                 case AST_SPEECH_STATE_DONE:
3269                         /* Get the results */
3270                         speech->results = ast_speech_results_get(speech);
3271                         /* Change state to not ready */
3272                         ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
3273                         reason = "speech";
3274                         break;
3275                 default:
3276                         break;
3277                 }
3278                 ast_mutex_unlock(&speech->lock);
3279
3280                 /* Check frame for DTMF or hangup */
3281                 if (fr) {
3282                         if (fr->frametype == AST_FRAME_DTMF) {
3283                                 reason = "dtmf";
3284                                 dtmf = fr->subclass.integer;
3285                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_HANGUP) {
3286                                 reason = "hangup";
3287                         }
3288                         ast_frfree(fr);
3289                 }
3290         }
3291
3292         if (!strcasecmp(reason, "speech")) {
3293                 /* Build string containing speech results */
3294                 for (result = speech->results; result; result = AST_LIST_NEXT(result, list)) {
3295                         /* Build result string */
3296                         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);
3297                         /* Increment result count */
3298                         i++;
3299                 }
3300                 /* Print out */
3301                 ast_agi_send(agi->fd, chan, "200 result=1 (speech) endpos=%ld results=%d %s\n", current_offset, i, tmp);
3302         } else if (!strcasecmp(reason, "dtmf")) {
3303                 ast_agi_send(agi->fd, chan, "200 result=1 (digit) digit=%c endpos=%ld\n", dtmf, current_offset);
3304         } else if (!strcasecmp(reason, "hangup") || !strcasecmp(reason, "timeout")) {
3305                 ast_agi_send(agi->fd, chan, "200 result=1 (%s) endpos=%ld\n", reason, current_offset);
3306         } else {
3307                 ast_agi_send(agi->fd, chan, "200 result=0 endpos=%ld\n", current_offset);
3308         }
3309
3310         return RESULT_SUCCESS;
3311 }
3312
3313 /*!
3314  * \brief AGI commands list
3315  */
3316 static struct agi_command commands[] = {
3317         { { "answer", NULL }, handle_answer, NULL, NULL, 0 },
3318         { { "asyncagi", "break", NULL }, handle_asyncagi_break, NULL, NULL, 1 },
3319         { { "channel", "status", NULL }, handle_channelstatus, NULL, NULL, 0 },
3320         { { "database", "del", NULL }, handle_dbdel, NULL, NULL, 1 },
3321         { { "database", "deltree", NULL }, handle_dbdeltree, NULL, NULL, 1 },
3322         { { "database", "get", NULL }, handle_dbget, NULL, NULL, 1 },
3323         { { "database", "put", NULL }, handle_dbput, NULL, NULL, 1 },
3324         { { "exec", NULL }, handle_exec, NULL, NULL, 1 },
3325         { { "get", "data", NULL }, handle_getdata, NULL, NULL, 0 },
3326         { { "get", "full", "variable", NULL }, handle_getvariablefull, NULL, NULL, 1 },
3327         { { "get", "option", NULL }, handle_getoption, NULL, NULL, 0 },
3328         { { "get", "variable", NULL }, handle_getvariable, NULL, NULL, 1 },
3329         { { "hangup", NULL }, handle_hangup, NULL, NULL, 0 },
3330         { { "noop", NULL }, handle_noop, NULL, NULL, 1 },
3331         { { "receive", "char", NULL }, handle_recvchar, NULL, NULL, 0 },
3332         { { "receive", "text", NULL }, handle_recvtext, NULL, NULL, 0 },
3333         { { "record", "file", NULL }, handle_recordfile, NULL, NULL, 0 },
3334         { { "say", "alpha", NULL }, handle_sayalpha, NULL, NULL, 0},
3335         { { "say", "digits", NULL }, handle_saydigits, NULL, NULL, 0 },
3336         { { "say", "number", NULL }, handle_saynumber, NULL, NULL, 0 },
3337         { { "say", "phonetic", NULL }, handle_sayphonetic, NULL, NULL, 0},
3338         { { "say", "date", NULL }, handle_saydate, NULL, NULL, 0},
3339         { { "say", "time", NULL }, handle_saytime, NULL, NULL, 0},
3340         { { "say", "datetime", NULL }, handle_saydatetime, NULL, NULL, 0},
3341         { { "send", "image", NULL }, handle_sendimage, NULL, NULL, 0},
3342         { { "send", "text", NULL }, handle_sendtext, NULL, NULL, 0},
3343         { { "set", "autohangup", NULL }, handle_autohangup, NULL, NULL, 0},
3344         { { "set", "callerid", NULL }, handle_setcallerid, NULL, NULL, 0},
3345         { { "set", "context", NULL }, handle_setcontext, NULL, NULL, 0},
3346         { { "set", "extension", NULL }, handle_setextension, NULL, NULL, 0},
3347         { { "set", "music", NULL }, handle_setmusic, NULL, NULL, 0 },
3348         { { "set", "priority", NULL }, handle_setpriority, NULL, NULL, 0 },
3349         { { "set", "variable", NULL }, handle_setvariable, NULL, NULL, 1 },
3350         { { "stream", "file", NULL }, handle_streamfile, NULL, NULL, 0 },
3351         { { "control", "stream", "file", NULL }, handle_controlstreamfile, NULL, NULL, 0 },
3352         { { "tdd", "mode", NULL }, handle_tddmode, NULL, NULL, 0 },
3353         { { "verbose", NULL }, handle_verbose, NULL, NULL, 1 },
3354         { { "wait", "for", "digit", NULL }, handle_waitfordigit, NULL, NULL, 0 },
3355         { { "speech", "create", NULL }, handle_speechcreate, NULL, NULL, 0 },
3356         { { "speech", "set", NULL }, handle_speechset, NULL, NULL, 0 },
3357         { { "speech", "destroy", NULL }, handle_speechdestroy, NULL, NULL, 1 },
3358         { { "speech", "load", "grammar", NULL }, handle_speechloadgrammar, NULL, NULL, 0 },
3359         { { "speech", "unload", "grammar", NULL }, handle_speechunloadgrammar, NULL, NULL, 1 },
3360         { { "speech", "activate", "grammar", NULL }, handle_speechactivategrammar, NULL, NULL, 0 },
3361         { { "speech", "deactivate", "grammar", NULL }, handle_speechdeactivategrammar, NULL, NULL, 0 },
3362         { { "speech", "recognize", NULL }, handle_speechrecognize, NULL, NULL, 0 },
3363 };
3364
3365 static AST_RWLIST_HEAD_STATIC(agi_commands, agi_command);
3366
3367 static char *help_workhorse(int fd, const char * const match[])
3368 {
3369         char fullcmd[MAX_CMD_LEN], matchstr[MAX_CMD_LEN];
3370         struct agi_command *e;
3371
3372         if (match)
3373                 ast_join(matchstr, sizeof(matchstr), match);
3374
3375         ast_cli(fd, "%5.5s %30.30s   %s\n","Dead","Command","Description");
3376         AST_RWLIST_RDLOCK(&agi_commands);
3377         AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
3378                 if (!e->cmda[0])
3379                         break;
3380                 /* Hide commands that start with '_' */
3381                 if ((e->cmda[0])[0] == '_')
3382                         continue;
3383                 ast_join(fullcmd, sizeof(fullcmd), e->cmda);
3384                 if (match && strncasecmp(matchstr, fullcmd, strlen(matchstr)))
3385                         continue;
3386                 ast_cli(fd, "%5.5s %30.30s   %s\n", e->dead ? "Yes" : "No" , fullcmd, S_OR(e->summary, "Not available"));
3387         }
3388         AST_RWLIST_UNLOCK(&agi_commands);
3389
3390         return CLI_SUCCESS;
3391 }
3392
3393 int AST_OPTIONAL_API_NAME(ast_agi_register)(struct ast_module *mod, agi_command *cmd)
3394 {
3395         char fullcmd[MAX_CMD_LEN];
3396
3397         ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
3398
3399         if (!find_command(cmd->cmda, 1)) {
3400                 *((enum ast_doc_src *) &cmd->docsrc) = AST_STATIC_DOC;
3401                 if (ast_strlen_zero(cmd->summary) && ast_strlen_zero(cmd->usage)) {
3402 #ifdef AST_XML_DOCS
3403                         *((char **) &cmd->summary) = ast_xmldoc_build_synopsis("agi", fullcmd, NULL);
3404                         *((char **) &cmd->usage) = ast_xmldoc_build_description("agi", fullcmd, NULL);
3405                         *((char **) &cmd->syntax) = ast_xmldoc_build_syntax("agi", fullcmd, NULL);
3406                         *((char **) &cmd->seealso) = ast_xmldoc_build_seealso("agi", fullcmd, NULL);
3407                         *((enum ast_doc_src *) &cmd->docsrc) = AST_XML_DOC;
3408 #endif
3409 #ifndef HAVE_NULLSAFE_PRINTF
3410                         if (!cmd->summary) {
3411                                 *((char **) &cmd->summary) = ast_strdup("");
3412                         }
3413                         if (!cmd->usage) {
3414                                 *((char **) &cmd->usage) = ast_strdup("");
3415                         }
3416                         if (!cmd->syntax) {
3417                                 *((char **) &cmd->syntax) = ast_strdup("");
3418                         }
3419                         if (!cmd->seealso) {
3420                                 *((char **) &cmd->seealso) = ast_strdup("");
3421                         }
3422 #endif
3423                 }
3424
3425                 cmd->mod = mod;
3426                 AST_RWLIST_WRLOCK(&agi_commands);
3427                 AST_LIST_INSERT_TAIL(&agi_commands, cmd, list);
3428                 AST_RWLIST_UNLOCK(&agi_commands);
3429                 if (mod != ast_module_info->self)
3430                         ast_module_ref(ast_module_info->self);
3431                 ast_verb(2, "AGI Command '%s' registered\n",fullcmd);
3432                 return 1;
3433         } else {
3434                 ast_log(LOG_WARNING, "Command already registered!\n");
3435                 return 0;
3436         }
3437 }
3438
3439 int AST_OPTIONAL_API_NAME(ast_agi_unregister)(struct ast_module *mod, agi_command *cmd)
3440 {
3441         struct agi_command *e;
3442         int unregistered = 0;
3443         char fullcmd[MAX_CMD_LEN];
3444
3445         ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
3446
3447         AST_RWLIST_WRLOCK(&agi_commands);
3448         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&agi_commands, e, list) {
3449                 if (cmd == e) {
3450                         AST_RWLIST_REMOVE_CURRENT(list);
3451                         if (mod != ast_module_info->self)
3452                                 ast_module_unref(ast_module_info->self);
3453 #ifdef AST_XML_DOCS
3454                         if (e->docsrc == AST_XML_DOC) {
3455                                 ast_free((char *) e->summary);
3456                                 ast_free((char *) e->usage);
3457                                 ast_free((char *) e->syntax);
3458                                 ast_free((char *) e->seealso);
3459                                 *((char **) &e->summary) = NULL;
3460                                 *((char **) &e->usage) = NULL;
3461                                 *((char **) &e->syntax) = NULL;
3462                                 *((char **) &e->seealso) = NULL;
3463                         }
3464 #endif
3465                         unregistered=1;
3466                         break;
3467                 }
3468         }
3469         AST_RWLIST_TRAVERSE_SAFE_END;
3470         AST_RWLIST_UNLOCK(&agi_commands);
3471         if (unregistered)
3472                 ast_verb(2, "AGI Command '%s' unregistered\n",fullcmd);
3473         else
3474                 ast_log(LOG_WARNING, "Unable to unregister command: '%s'!\n",fullcmd);
3475         return unregistered;
3476 }
3477
3478 int AST_OPTIONAL_API_NAME(ast_agi_register_multiple)(struct ast_module *mod, struct agi_command *cmd, unsigned int len)
3479 {
3480         unsigned int i, x = 0;
3481
3482         for (i = 0; i < len; i++) {
3483                 if (ast_agi_register(mod, cmd + i) == 1) {
3484                         x++;
3485                         continue;
3486                 }
3487
3488                 /* registration failed, unregister everything
3489                    that had been registered up to that point
3490                 */
3491                 for (; x > 0; x--) {
3492                         /* we are intentionally ignoring the
3493                            result of ast_agi_unregister() here,
3494                            but it should be safe to do so since
3495                            we just registered these commands and
3496                            the only possible way for unregistration
3497                            to fail is if the command is not
3498                            registered
3499                         */
3500                         (void) ast_agi_unregister(mod, cmd + x - 1);
3501                 }
3502                 return -1;
3503         }
3504
3505         return 0;
3506 }