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