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