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