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