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