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