Merged revisions 288927 via svnmerge from
[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_log(LOG_DEBUG, "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, 1);
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_log(LOG_DEBUG, "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, 1);
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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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         int rfmt = 0;
2150
2151         /* XXX EAGI FIXME XXX */
2152
2153         if (argc < 6)
2154                 return RESULT_SHOWUSAGE;
2155         if (sscanf(argv[5], "%30d", &ms) != 1)
2156                 return RESULT_SHOWUSAGE;
2157
2158         if (argc > 6)
2159                 silencestr = strchr(argv[6],'s');
2160         if ((argc > 7) && (!silencestr))
2161                 silencestr = strchr(argv[7],'s');
2162         if ((argc > 8) && (!silencestr))
2163                 silencestr = strchr(argv[8],'s');
2164
2165         if (silencestr) {
2166                 if (strlen(silencestr) > 2) {
2167                         if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
2168                                 silencestr++;
2169                                 silencestr++;
2170                                 if (silencestr)
2171                                         silence = atoi(silencestr);
2172                                 if (silence > 0)
2173                                         silence *= 1000;
2174                         }
2175                 }
2176         }
2177
2178         if (silence > 0) {
2179                 rfmt = chan->readformat;
2180                 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
2181                 if (res < 0) {
2182                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
2183                         return -1;
2184                 }
2185                 sildet = ast_dsp_new();
2186                 if (!sildet) {
2187                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
2188                         return -1;
2189                 }
2190                 ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
2191         }
2192         
2193         /* backward compatibility, if no offset given, arg[6] would have been
2194          * caught below and taken to be a beep, else if it is a digit then it is a
2195          * offset */
2196         if ((argc >6) && (sscanf(argv[6], "%30ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
2197                 res = ast_streamfile(chan, "beep", chan->language);
2198
2199         if ((argc > 7) && (!strchr(argv[7], '=')))
2200                 res = ast_streamfile(chan, "beep", chan->language);
2201
2202         if (!res)
2203                 res = ast_waitstream(chan, argv[4]);
2204         if (res) {
2205                 ast_agi_send(agi->fd, chan, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
2206         } else {
2207                 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, AST_FILE_MODE);
2208                 if (!fs) {
2209                         res = -1;
2210                         ast_agi_send(agi->fd, chan, "200 result=%d (writefile)\n", res);
2211                         if (sildet)
2212                                 ast_dsp_free(sildet);
2213                         return RESULT_FAILURE;
2214                 }
2215
2216                 /* Request a video update */
2217                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
2218
2219                 chan->stream = fs;
2220                 ast_applystream(chan,fs);
2221                 /* really should have checks */
2222                 ast_seekstream(fs, sample_offset, SEEK_SET);
2223                 ast_truncstream(fs);
2224
2225                 start = ast_tvnow();
2226                 while ((ms < 0) || ast_tvdiff_ms(ast_tvnow(), start) < ms) {
2227                         res = ast_waitfor(chan, ms - ast_tvdiff_ms(ast_tvnow(), start));
2228                         if (res < 0) {
2229                                 ast_closestream(fs);
2230                                 ast_agi_send(agi->fd, chan, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
2231                                 if (sildet)
2232                                         ast_dsp_free(sildet);
2233                                 return RESULT_FAILURE;
2234                         }
2235                         f = ast_read(chan);
2236                         if (!f) {
2237                                 ast_agi_send(agi->fd, chan, "200 result=%d (hangup) endpos=%ld\n", -1, sample_offset);
2238                                 ast_closestream(fs);
2239                                 if (sildet)
2240                                         ast_dsp_free(sildet);
2241                                 return RESULT_FAILURE;
2242                         }
2243                         switch(f->frametype) {
2244                         case AST_FRAME_DTMF:
2245                                 if (strchr(argv[4], f->subclass.integer)) {
2246                                         /* This is an interrupting chracter, so rewind to chop off any small
2247                                            amount of DTMF that may have been recorded
2248                                         */
2249                                         ast_stream_rewind(fs, 200);
2250                                         ast_truncstream(fs);
2251                                         sample_offset = ast_tellstream(fs);
2252                                         ast_agi_send(agi->fd, chan, "200 result=%d (dtmf) endpos=%ld\n", f->subclass.integer, sample_offset);
2253                                         ast_closestream(fs);
2254                                         ast_frfree(f);
2255                                         if (sildet)
2256                                                 ast_dsp_free(sildet);
2257                                         return RESULT_SUCCESS;
2258                                 }
2259                                 break;
2260                         case AST_FRAME_VOICE:
2261                                 ast_writestream(fs, f);
2262                                 /* this is a safe place to check progress since we know that fs
2263                                  * is valid after a write, and it will then have our current
2264                                  * location */
2265                                 sample_offset = ast_tellstream(fs);
2266                                 if (silence > 0) {
2267                                         dspsilence = 0;
2268                                         ast_dsp_silence(sildet, f, &dspsilence);
2269                                         if (dspsilence) {
2270                                                 totalsilence = dspsilence;
2271                                         } else {
2272                                                 totalsilence = 0;
2273                                         }
2274                                         if (totalsilence > silence) {
2275                                                 /* Ended happily with silence */
2276                                                 gotsilence = 1;
2277                                                 break;
2278                                         }
2279                                 }
2280                                 break;
2281                         case AST_FRAME_VIDEO:
2282                                 ast_writestream(fs, f);
2283                         default:
2284                                 /* Ignore all other frames */
2285                                 break;
2286                         }
2287                         ast_frfree(f);
2288                         if (gotsilence)
2289                                 break;
2290                 }
2291
2292                 if (gotsilence) {
2293                         ast_stream_rewind(fs, silence-1000);
2294                         ast_truncstream(fs);
2295                         sample_offset = ast_tellstream(fs);
2296                 }
2297                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
2298                 ast_closestream(fs);
2299         }
2300
2301         if (silence > 0) {
2302                 res = ast_set_read_format(chan, rfmt);
2303                 if (res)
2304                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", chan->name);
2305                 ast_dsp_free(sildet);
2306         }
2307
2308         return RESULT_SUCCESS;
2309 }
2310
2311 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2312 {
2313         double timeout;
2314         struct timeval whentohangup = { 0, 0 };
2315
2316         if (argc != 3)
2317                 return RESULT_SHOWUSAGE;
2318         if (sscanf(argv[2], "%30lf", &timeout) != 1)
2319                 return RESULT_SHOWUSAGE;
2320         if (timeout < 0)
2321                 timeout = 0;
2322         if (timeout) {
2323                 whentohangup.tv_sec = timeout;
2324                 whentohangup.tv_usec = (timeout - whentohangup.tv_sec) * 1000000.0;
2325         }
2326         ast_channel_setwhentohangup_tv(chan, whentohangup);
2327         ast_agi_send(agi->fd, chan, "200 result=0\n");
2328         return RESULT_SUCCESS;
2329 }
2330
2331 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2332 {
2333         struct ast_channel *c;
2334
2335         if (argc == 1) {
2336                 /* no argument: hangup the current channel */
2337                 ast_set_hangupsource(chan, "dialplan/agi", 0);
2338                 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
2339                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2340                 return RESULT_SUCCESS;
2341         } else if (argc == 2) {
2342                 /* one argument: look for info on the specified channel */
2343                 if ((c = ast_channel_get_by_name(argv[1]))) {
2344                         /* we have a matching channel */
2345                         ast_set_hangupsource(c, "dialplan/agi", 0);
2346                         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
2347                         c = ast_channel_unref(c);
2348                         ast_agi_send(agi->fd, chan, "200 result=1\n");
2349                         return RESULT_SUCCESS;
2350                 }
2351                 /* if we get this far no channel name matched the argument given */
2352                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2353                 return RESULT_SUCCESS;
2354         } else {
2355                 return RESULT_SHOWUSAGE;
2356         }
2357 }
2358
2359 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2360 {
2361         int res, workaround;
2362         struct ast_app *app_to_exec;
2363
2364         if (argc < 2)
2365                 return RESULT_SHOWUSAGE;
2366
2367         ast_verb(3, "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argc >= 3 ? argv[2] : "");
2368
2369         if ((app_to_exec = pbx_findapp(argv[1]))) {
2370                 if(!strcasecmp(argv[1], PARK_APP_NAME)) {
2371                         ast_masq_park_call(chan, NULL, 0, NULL);
2372                 }
2373                 if (!(workaround = ast_test_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS))) {
2374                         ast_set_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS);
2375                 }
2376                 if (ast_compat_res_agi && argc >= 3 && !ast_strlen_zero(argv[2])) {
2377                         char *compat = alloca(strlen(argv[2]) * 2 + 1), *cptr;
2378                         const char *vptr;
2379                         for (cptr = compat, vptr = argv[2]; *vptr; vptr++) {
2380                                 if (*vptr == ',') {
2381                                         *cptr++ = '\\';
2382                                         *cptr++ = ',';
2383                                 } else if (*vptr == '|') {
2384                                         *cptr++ = ',';
2385                                 } else {
2386                                         *cptr++ = *vptr;
2387                                 }
2388                         }
2389                         *cptr = '\0';
2390                         res = pbx_exec(chan, app_to_exec, compat);
2391                 } else {
2392                         res = pbx_exec(chan, app_to_exec, argc == 2 ? "" : argv[2]);
2393                 }
2394                 if (!workaround) {
2395                         ast_clear_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS);
2396                 }
2397         } else {
2398                 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
2399                 res = -2;
2400         }
2401         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2402
2403         /* Even though this is wrong, users are depending upon this result. */
2404         return res;
2405 }
2406
2407 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2408 {
2409         char tmp[256]="";
2410         char *l = NULL, *n = NULL;
2411
2412         if (argv[2]) {
2413                 ast_copy_string(tmp, argv[2], sizeof(tmp));
2414                 ast_callerid_parse(tmp, &n, &l);
2415                 if (l)
2416                         ast_shrink_phone_number(l);
2417                 else
2418                         l = "";
2419                 if (!n)
2420                         n = "";
2421                 ast_set_callerid(chan, l, n, NULL);
2422         }
2423
2424         ast_agi_send(agi->fd, chan, "200 result=1\n");
2425         return RESULT_SUCCESS;
2426 }
2427
2428 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2429 {
2430         struct ast_channel *c;
2431         if (argc == 2) {
2432                 /* no argument: supply info on the current channel */
2433                 ast_agi_send(agi->fd, chan, "200 result=%d\n", chan->_state);
2434                 return RESULT_SUCCESS;
2435         } else if (argc == 3) {
2436                 /* one argument: look for info on the specified channel */
2437                 if ((c = ast_channel_get_by_name(argv[2]))) {
2438                         ast_agi_send(agi->fd, chan, "200 result=%d\n", c->_state);
2439                         c = ast_channel_unref(c);
2440                         return RESULT_SUCCESS;
2441                 }
2442                 /* if we get this far no channel name matched the argument given */
2443                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2444                 return RESULT_SUCCESS;
2445         } else {
2446                 return RESULT_SHOWUSAGE;
2447         }
2448 }
2449
2450 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2451 {
2452         if (argv[3])
2453                 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
2454
2455         ast_agi_send(agi->fd, chan, "200 result=1\n");
2456         return RESULT_SUCCESS;
2457 }
2458
2459 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2460 {
2461         char *ret;
2462         char tempstr[1024];
2463
2464         if (argc != 3)
2465                 return RESULT_SHOWUSAGE;
2466
2467         /* check if we want to execute an ast_custom_function */
2468         if (!ast_strlen_zero(argv[2]) && (argv[2][strlen(argv[2]) - 1] == ')')) {
2469                 ret = ast_func_read(chan, argv[2], tempstr, sizeof(tempstr)) ? NULL : tempstr;
2470         } else {
2471                 pbx_retrieve_variable(chan, argv[2], &ret, tempstr, sizeof(tempstr), NULL);
2472         }
2473
2474         if (ret)
2475                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ret);
2476         else
2477                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2478
2479         return RESULT_SUCCESS;
2480 }
2481
2482 static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2483 {
2484         struct ast_channel *chan2 = NULL;
2485
2486         if (argc != 4 && argc != 5) {
2487                 return RESULT_SHOWUSAGE;
2488         }
2489
2490         if (argc == 5) {
2491                 chan2 = ast_channel_get_by_name(argv[4]);
2492         } else {
2493                 chan2 = ast_channel_ref(chan);
2494         }
2495
2496         if (chan2) {
2497                 struct ast_str *str = ast_str_create(16);
2498                 if (!str) {
2499                         ast_agi_send(agi->fd, chan, "200 result=0\n");
2500                         return RESULT_SUCCESS;
2501                 }
2502                 ast_str_substitute_variables(&str, 0, chan2, argv[3]);
2503                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(str));
2504                 ast_free(str);
2505         } else {
2506                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2507         }
2508
2509         if (chan2) {
2510                 chan2 = ast_channel_unref(chan2);
2511         }
2512
2513         return RESULT_SUCCESS;
2514 }
2515
2516 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2517 {
2518         int level = 0;
2519
2520         if (argc < 2)
2521                 return RESULT_SHOWUSAGE;
2522
2523         if (argv[2])
2524                 sscanf(argv[2], "%30d", &level);
2525
2526         ast_verb(level, "%s: %s\n", chan->data, argv[1]);
2527
2528         ast_agi_send(agi->fd, chan, "200 result=1\n");
2529
2530         return RESULT_SUCCESS;
2531 }
2532
2533 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2534 {
2535         int res;
2536         struct ast_str *buf;
2537
2538         if (argc != 4)
2539                 return RESULT_SHOWUSAGE;
2540
2541         if (!(buf = ast_str_create(16))) {
2542                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2543                 return RESULT_SUCCESS;
2544         }
2545
2546         do {
2547                 res = ast_db_get(argv[2], argv[3], ast_str_buffer(buf), ast_str_size(buf));
2548                 ast_str_update(buf);
2549                 if (ast_str_strlen(buf) < ast_str_size(buf) - 1) {
2550                         break;
2551                 }
2552                 if (ast_str_make_space(&buf, ast_str_size(buf) * 2)) {
2553                         break;
2554                 }
2555         } while (1);
2556         
2557         if (res)
2558                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2559         else
2560                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(buf));
2561
2562         ast_free(buf);
2563         return RESULT_SUCCESS;
2564 }
2565
2566 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2567 {
2568         int res;
2569
2570         if (argc != 5)
2571                 return RESULT_SHOWUSAGE;
2572         res = ast_db_put(argv[2], argv[3], argv[4]);
2573         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2574         return RESULT_SUCCESS;
2575 }
2576
2577 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2578 {
2579         int res;
2580
2581         if (argc != 4)
2582                 return RESULT_SHOWUSAGE;
2583         res = ast_db_del(argv[2], argv[3]);
2584         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2585         return RESULT_SUCCESS;
2586 }
2587
2588 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2589 {
2590         int res;
2591
2592         if ((argc < 3) || (argc > 4))
2593                 return RESULT_SHOWUSAGE;
2594         if (argc == 4)
2595                 res = ast_db_deltree(argv[2], argv[3]);
2596         else
2597                 res = ast_db_deltree(argv[2], NULL);
2598
2599         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2600         return RESULT_SUCCESS;
2601 }
2602
2603 static char *handle_cli_agi_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2604 {
2605         switch (cmd) {
2606         case CLI_INIT:
2607                 e->command = "agi set debug [on|off]";
2608                 e->usage =
2609                         "Usage: agi set debug [on|off]\n"
2610                         "       Enables/disables dumping of AGI transactions for\n"
2611                         "       debugging purposes.\n";
2612                 return NULL;
2613
2614         case CLI_GENERATE:
2615                 return NULL;
2616         }
2617
2618         if (a->argc != e->args)
2619                 return CLI_SHOWUSAGE;
2620
2621         if (strncasecmp(a->argv[3], "off", 3) == 0) {
2622                 agidebug = 0;
2623         } else if (strncasecmp(a->argv[3], "on", 2) == 0) {
2624                 agidebug = 1;
2625         } else {
2626                 return CLI_SHOWUSAGE;
2627         }
2628         ast_cli(a->fd, "AGI Debugging %sabled\n", agidebug ? "En" : "Dis");
2629         return CLI_SUCCESS;
2630 }
2631
2632 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, const char * const argv[])
2633 {
2634         ast_agi_send(agi->fd, chan, "200 result=0\n");
2635         return RESULT_SUCCESS;
2636 }
2637
2638 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2639 {
2640         if (argc < 3) {
2641                 return RESULT_SHOWUSAGE;
2642         }
2643         if (!strncasecmp(argv[2], "on", 2))
2644                 ast_moh_start(chan, argc > 3 ? argv[3] : NULL, NULL);
2645         else if (!strncasecmp(argv[2], "off", 3))
2646                 ast_moh_stop(chan);
2647         ast_agi_send(agi->fd, chan, "200 result=0\n");
2648         return RESULT_SUCCESS;
2649 }
2650
2651 static int handle_speechcreate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2652 {
2653         /* If a structure already exists, return an error */
2654         if (agi->speech) {
2655                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2656                 return RESULT_SUCCESS;
2657         }
2658
2659         if ((agi->speech = ast_speech_new(argv[2], AST_FORMAT_SLINEAR)))
2660                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2661         else
2662                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2663
2664         return RESULT_SUCCESS;
2665 }
2666
2667 static int handle_speechset(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2668 {
2669         /* Check for minimum arguments */
2670         if (argc != 4)
2671                 return RESULT_SHOWUSAGE;
2672
2673         /* Check to make sure speech structure exists */
2674         if (!agi->speech) {
2675                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2676                 return RESULT_SUCCESS;
2677         }
2678
2679         ast_speech_change(agi->speech, argv[2], argv[3]);
2680         ast_agi_send(agi->fd, chan, "200 result=1\n");
2681
2682         return RESULT_SUCCESS;
2683 }
2684
2685 static int handle_speechdestroy(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2686 {
2687         if (agi->speech) {
2688                 ast_speech_destroy(agi->speech);
2689                 agi->speech = NULL;
2690                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2691         } else {
2692                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2693         }
2694
2695         return RESULT_SUCCESS;
2696 }
2697
2698 static int handle_speechloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2699 {
2700         if (argc != 5)
2701                 return RESULT_SHOWUSAGE;
2702
2703         if (!agi->speech) {
2704                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2705                 return RESULT_SUCCESS;
2706         }
2707
2708         if (ast_speech_grammar_load(agi->speech, argv[3], argv[4]))
2709                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2710         else
2711                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2712
2713         return RESULT_SUCCESS;
2714 }
2715
2716 static int handle_speechunloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2717 {
2718         if (argc != 4)
2719                 return RESULT_SHOWUSAGE;
2720
2721         if (!agi->speech) {
2722                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2723                 return RESULT_SUCCESS;
2724         }
2725
2726         if (ast_speech_grammar_unload(agi->speech, argv[3]))
2727                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2728         else
2729                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2730
2731         return RESULT_SUCCESS;
2732 }
2733
2734 static int handle_speechactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2735 {
2736         if (argc != 4)
2737                 return RESULT_SHOWUSAGE;
2738
2739         if (!agi->speech) {
2740                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2741                 return RESULT_SUCCESS;
2742         }
2743
2744         if (ast_speech_grammar_activate(agi->speech, argv[3]))
2745                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2746         else
2747                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2748
2749         return RESULT_SUCCESS;
2750 }
2751
2752 static int handle_speechdeactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2753 {
2754         if (argc != 4)
2755                 return RESULT_SHOWUSAGE;
2756
2757         if (!agi->speech) {
2758                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2759                 return RESULT_SUCCESS;
2760         }
2761
2762         if (ast_speech_grammar_deactivate(agi->speech, argv[3]))
2763                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2764         else
2765                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2766
2767         return RESULT_SUCCESS;
2768 }
2769
2770 static int speech_streamfile(struct ast_channel *chan, const char *filename, const char *preflang, int offset)
2771 {
2772         struct ast_filestream *fs = NULL;
2773
2774         if (!(fs = ast_openstream(chan, filename, preflang)))
2775                 return -1;
2776
2777         if (offset)
2778                 ast_seekstream(fs, offset, SEEK_SET);
2779
2780         if (ast_applystream(chan, fs))
2781                 return -1;
2782
2783         if (ast_playstream(fs))
2784                 return -1;
2785
2786         return 0;
2787 }
2788
2789 static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2790 {
2791         struct ast_speech *speech = agi->speech;
2792         const char *prompt;
2793         char dtmf = 0, tmp[4096] = "", *buf = tmp;
2794         int timeout = 0, offset = 0, old_read_format = 0, res = 0, i = 0;
2795         long current_offset = 0;
2796         const char *reason = NULL;
2797         struct ast_frame *fr = NULL;
2798         struct ast_speech_result *result = NULL;
2799         size_t left = sizeof(tmp);
2800         time_t start = 0, current;
2801
2802         if (argc < 4)
2803                 return RESULT_SHOWUSAGE;
2804
2805         if (!speech) {
2806                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2807                 return RESULT_SUCCESS;
2808         }
2809
2810         prompt = argv[2];
2811         timeout = atoi(argv[3]);
2812
2813         /* If offset is specified then convert from text to integer */
2814         if (argc == 5)
2815                 offset = atoi(argv[4]);
2816
2817         /* We want frames coming in signed linear */
2818         old_read_format = chan->readformat;
2819         if (ast_set_read_format(chan, AST_FORMAT_SLINEAR)) {
2820                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2821                 return RESULT_SUCCESS;
2822         }
2823
2824         /* Setup speech structure */
2825         if (speech->state == AST_SPEECH_STATE_NOT_READY || speech->state == AST_SPEECH_STATE_DONE) {
2826                 ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
2827                 ast_speech_start(speech);
2828         }
2829
2830         /* Start playing prompt */
2831         speech_streamfile(chan, prompt, chan->language, offset);
2832
2833         /* Go into loop reading in frames, passing to speech thingy, checking for hangup, all that jazz */
2834         while (ast_strlen_zero(reason)) {
2835                 /* Run scheduled items */
2836                 ast_sched_runq(chan->sched);
2837
2838                 /* See maximum time of waiting */
2839                 if ((res = ast_sched_wait(chan->sched)) < 0)
2840                         res = 1000;
2841
2842                 /* Wait for frame */
2843                 if (ast_waitfor(chan, res) > 0) {
2844                         if (!(fr = ast_read(chan))) {
2845                                 reason = "hangup";
2846                                 break;
2847                         }
2848                 }
2849
2850                 /* Perform timeout check */
2851                 if ((timeout > 0) && (start > 0)) {
2852                         time(&current);
2853                         if ((current - start) >= timeout) {
2854                                 reason = "timeout";
2855                                 if (fr)
2856                                         ast_frfree(fr);
2857                                 break;
2858                         }
2859                 }
2860
2861                 /* Check the speech structure for any changes */
2862                 ast_mutex_lock(&speech->lock);
2863
2864                 /* See if we need to quiet the audio stream playback */
2865                 if (ast_test_flag(speech, AST_SPEECH_QUIET) && chan->stream) {
2866                         current_offset = ast_tellstream(chan->stream);
2867                         ast_stopstream(chan);
2868                         ast_clear_flag(speech, AST_SPEECH_QUIET);
2869                 }
2870
2871                 /* Check each state */
2872                 switch (speech->state) {
2873                 case AST_SPEECH_STATE_READY:
2874                         /* If the stream is done, start timeout calculation */
2875                         if ((timeout > 0) && start == 0 && ((!chan->stream) || (chan->streamid == -1 && chan->timingfunc == NULL))) {
2876                                 ast_stopstream(chan);
2877                                 time(&start);
2878                         }
2879                         /* Write audio frame data into speech engine if possible */
2880                         if (fr && fr->frametype == AST_FRAME_VOICE)
2881                                 ast_speech_write(speech, fr->data.ptr, fr->datalen);
2882                         break;
2883                 case AST_SPEECH_STATE_WAIT:
2884                         /* Cue waiting sound if not already playing */
2885                         if ((!chan->stream) || (chan->streamid == -1 && chan->timingfunc == NULL)) {
2886                                 ast_stopstream(chan);
2887                                 /* If a processing sound exists, or is not none - play it */
2888                                 if (!ast_strlen_zero(speech->processing_sound) && strcasecmp(speech->processing_sound, "none"))
2889                                         speech_streamfile(chan, speech->processing_sound, chan->language, 0);
2890                         }
2891                         break;
2892                 case AST_SPEECH_STATE_DONE:
2893                         /* Get the results */
2894                         speech->results = ast_speech_results_get(speech);
2895                         /* Change state to not ready */
2896                         ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
2897                         reason = "speech";
2898                         break;
2899                 default:
2900                         break;
2901                 }
2902                 ast_mutex_unlock(&speech->lock);
2903
2904                 /* Check frame for DTMF or hangup */
2905                 if (fr) {
2906                         if (fr->frametype == AST_FRAME_DTMF) {
2907                                 reason = "dtmf";
2908                                 dtmf = fr->subclass.integer;
2909                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_HANGUP) {
2910                                 reason = "hangup";
2911                         }
2912                         ast_frfree(fr);
2913                 }
2914         }
2915
2916         if (!strcasecmp(reason, "speech")) {
2917                 /* Build string containing speech results */
2918                 for (result = speech->results; result; result = AST_LIST_NEXT(result, list)) {
2919                         /* Build result string */
2920                         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);
2921                         /* Increment result count */
2922                         i++;
2923                 }
2924                 /* Print out */
2925                 ast_agi_send(agi->fd, chan, "200 result=1 (speech) endpos=%ld results=%d %s\n", current_offset, i, tmp);
2926         } else if (!strcasecmp(reason, "dtmf")) {
2927                 ast_agi_send(agi->fd, chan, "200 result=1 (digit) digit=%c endpos=%ld\n", dtmf, current_offset);
2928         } else if (!strcasecmp(reason, "hangup") || !strcasecmp(reason, "timeout")) {
2929                 ast_agi_send(agi->fd, chan, "200 result=1 (%s) endpos=%ld\n", reason, current_offset);
2930         } else {
2931                 ast_agi_send(agi->fd, chan, "200 result=0 endpos=%ld\n", current_offset);
2932         }
2933
2934         return RESULT_SUCCESS;
2935 }
2936
2937 /*!
2938  * \brief AGI commands list
2939  */
2940 static struct agi_command commands[] = {
2941         { { "answer", NULL }, handle_answer, NULL, NULL, 0 },
2942         { { "asyncagi", "break", NULL }, handle_asyncagi_break, NULL, NULL, 1 },
2943         { { "channel", "status", NULL }, handle_channelstatus, NULL, NULL, 0 },
2944         { { "database", "del", NULL }, handle_dbdel, NULL, NULL, 1 },
2945         { { "database", "deltree", NULL }, handle_dbdeltree, NULL, NULL, 1 },
2946         { { "database", "get", NULL }, handle_dbget, NULL, NULL, 1 },
2947         { { "database", "put", NULL }, handle_dbput, NULL, NULL, 1 },
2948         { { "exec", NULL }, handle_exec, NULL, NULL, 1 },
2949         { { "get", "data", NULL }, handle_getdata, NULL, NULL, 0 },
2950         { { "get", "full", "variable", NULL }, handle_getvariablefull, NULL, NULL, 1 },
2951         { { "get", "option", NULL }, handle_getoption, NULL, NULL, 0 },
2952         { { "get", "variable", NULL }, handle_getvariable, NULL, NULL, 1 },
2953         { { "hangup", NULL }, handle_hangup, NULL, NULL, 0 },
2954         { { "noop", NULL }, handle_noop, NULL, NULL, 1 },
2955         { { "receive", "char", NULL }, handle_recvchar, NULL, NULL, 0 },
2956         { { "receive", "text", NULL }, handle_recvtext, NULL, NULL, 0 },
2957         { { "record", "file", NULL }, handle_recordfile, NULL, NULL, 0 }, 
2958         { { "say", "alpha", NULL }, handle_sayalpha, NULL, NULL, 0},
2959         { { "say", "digits", NULL }, handle_saydigits, NULL, NULL, 0 },
2960         { { "say", "number", NULL }, handle_saynumber, NULL, NULL, 0 },
2961         { { "say", "phonetic", NULL }, handle_sayphonetic, NULL, NULL, 0}, 
2962         { { "say", "date", NULL }, handle_saydate, NULL, NULL, 0}, 
2963         { { "say", "time", NULL }, handle_saytime, NULL, NULL, 0}, 
2964         { { "say", "datetime", NULL }, handle_saydatetime, NULL, NULL, 0},
2965         { { "send", "image", NULL }, handle_sendimage, NULL, NULL, 0}, 
2966         { { "send", "text", NULL }, handle_sendtext, NULL, NULL, 0},
2967         { { "set", "autohangup", NULL }, handle_autohangup, NULL, NULL, 0},
2968         { { "set", "callerid", NULL }, handle_setcallerid, NULL, NULL, 0},
2969         { { "set", "context", NULL }, handle_setcontext, NULL, NULL, 0},
2970         { { "set", "extension", NULL }, handle_setextension, NULL, NULL, 0},
2971         { { "set", "music", NULL }, handle_setmusic, NULL, NULL, 0 },
2972         { { "set", "priority", NULL }, handle_setpriority, NULL, NULL, 0 },
2973         { { "set", "variable", NULL }, handle_setvariable, NULL, NULL, 1 },
2974         { { "stream", "file", NULL }, handle_streamfile, NULL, NULL, 0 },
2975         { { "control", "stream", "file", NULL }, handle_controlstreamfile, NULL, NULL, 0 },
2976         { { "tdd", "mode", NULL }, handle_tddmode, NULL, NULL, 0 },
2977         { { "verbose", NULL }, handle_verbose, NULL, NULL, 1 },
2978         { { "wait", "for", "digit", NULL }, handle_waitfordigit, NULL, NULL, 0 },
2979         { { "speech", "create", NULL }, handle_speechcreate, NULL, NULL, 0 },
2980         { { "speech", "set", NULL }, handle_speechset, NULL, NULL, 0 },
2981         { { "speech", "destroy", NULL }, handle_speechdestroy, NULL, NULL, 1 },
2982         { { "speech", "load", "grammar", NULL }, handle_speechloadgrammar, NULL, NULL, 0 },
2983         { { "speech", "unload", "grammar", NULL }, handle_speechunloadgrammar, NULL, NULL, 1 },
2984         { { "speech", "activate", "grammar", NULL }, handle_speechactivategrammar, NULL, NULL, 0 },
2985         { { "speech", "deactivate", "grammar", NULL }, handle_speechdeactivategrammar, NULL, NULL, 0 },
2986         { { "speech", "recognize", NULL }, handle_speechrecognize, NULL, NULL, 0 },
2987 };
2988
2989 static AST_RWLIST_HEAD_STATIC(agi_commands, agi_command);
2990
2991 static char *help_workhorse(int fd, const char * const match[])
2992 {
2993         char fullcmd[MAX_CMD_LEN], matchstr[MAX_CMD_LEN];
2994         struct agi_command *e;
2995
2996         if (match)
2997                 ast_join(matchstr, sizeof(matchstr), match);
2998
2999         ast_cli(fd, "%5.5s %30.30s   %s\n","Dead","Command","Description");
3000         AST_RWLIST_RDLOCK(&agi_commands);
3001         AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
3002                 if (!e->cmda[0])
3003                         break;
3004                 /* Hide commands that start with '_' */
3005                 if ((e->cmda[0])[0] == '_')
3006                         continue;
3007                 ast_join(fullcmd, sizeof(fullcmd), e->cmda);
3008                 if (match && strncasecmp(matchstr, fullcmd, strlen(matchstr)))
3009                         continue;
3010                 ast_cli(fd, "%5.5s %30.30s   %s\n", e->dead ? "Yes" : "No" , fullcmd, S_OR(e->summary, "Not available"));
3011         }
3012         AST_RWLIST_UNLOCK(&agi_commands);
3013
3014         return CLI_SUCCESS;
3015 }
3016
3017 int AST_OPTIONAL_API_NAME(ast_agi_register)(struct ast_module *mod, agi_command *cmd)
3018 {
3019         char fullcmd[MAX_CMD_LEN];
3020
3021         ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
3022
3023         if (!find_command(cmd->cmda, 1)) {
3024                 *((enum ast_doc_src *) &cmd->docsrc) = AST_STATIC_DOC;
3025                 if (ast_strlen_zero(cmd->summary) && ast_strlen_zero(cmd->usage)) {
3026 #ifdef AST_XML_DOCS
3027                         *((char **) &cmd->summary) = ast_xmldoc_build_synopsis("agi", fullcmd);
3028                         *((char **) &cmd->usage) = ast_xmldoc_build_description("agi", fullcmd);
3029                         *((char **) &cmd->syntax) = ast_xmldoc_build_syntax("agi", fullcmd);
3030                         *((char **) &cmd->seealso) = ast_xmldoc_build_seealso("agi", fullcmd);
3031                         *((enum ast_doc_src *) &cmd->docsrc) = AST_XML_DOC;
3032 #elif (!defined(HAVE_NULLSAFE_PRINTF))
3033                         *((char **) &cmd->summary) = ast_strdup("");
3034                         *((char **) &cmd->usage) = ast_strdup("");
3035                         *((char **) &cmd->syntax) = ast_strdup("");
3036                         *((char **) &cmd->seealso) = ast_strdup("");
3037 #endif
3038                 }
3039
3040                 cmd->mod = mod;
3041                 AST_RWLIST_WRLOCK(&agi_commands);
3042                 AST_LIST_INSERT_TAIL(&agi_commands, cmd, list);
3043                 AST_RWLIST_UNLOCK(&agi_commands);
3044                 if (mod != ast_module_info->self)
3045                         ast_module_ref(ast_module_info->self);
3046                 ast_verb(2, "AGI Command '%s' registered\n",fullcmd);
3047                 return 1;
3048         } else {
3049                 ast_log(LOG_WARNING, "Command already registered!\n");
3050                 return 0;
3051         }
3052 }
3053
3054 int AST_OPTIONAL_API_NAME(ast_agi_unregister)(struct ast_module *mod, agi_command *cmd)
3055 {
3056         struct agi_command *e;
3057         int unregistered = 0;
3058         char fullcmd[MAX_CMD_LEN];
3059
3060         ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
3061
3062         AST_RWLIST_WRLOCK(&agi_commands);
3063         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&agi_commands, e, list) {
3064                 if (cmd == e) {
3065                         AST_RWLIST_REMOVE_CURRENT(list);
3066                         if (mod != ast_module_info->self)
3067                                 ast_module_unref(ast_module_info->self);
3068 #ifdef AST_XML_DOCS
3069                         if (e->docsrc == AST_XML_DOC) {
3070                                 ast_free((char *) e->summary);
3071                                 ast_free((char *) e->usage);
3072                                 ast_free((char *) e->syntax);
3073                                 ast_free((char *) e->seealso);
3074                                 *((char **) &e->summary) = NULL;
3075                                 *((char **) &e->usage) = NULL;
3076                                 *((char **) &e->syntax) = NULL;
3077                                 *((char **) &e->seealso) = NULL;
3078                         }
3079 #endif
3080                         unregistered=1;
3081                         break;
3082                 }
3083         }
3084         AST_RWLIST_TRAVERSE_SAFE_END;
3085         AST_RWLIST_UNLOCK(&agi_commands);
3086         if (unregistered)
3087                 ast_verb(2, "AGI Command '%s' unregistered\n",fullcmd);
3088         else
3089                 ast_log(LOG_WARNING, "Unable to unregister command: '%s'!\n",fullcmd);
3090         return unregistered;
3091 }
3092
3093 int AST_OPTIONAL_API_NAME(ast_agi_register_multiple)(struct ast_module *mod, struct agi_command *cmd, unsigned int len)
3094 {
3095         unsigned int i, x = 0;
3096
3097         for (i = 0; i < len; i++) {
3098                 if (ast_agi_register(mod, cmd + i) == 1) {
3099                         x++;
3100                         continue;
3101                 }
3102
3103                 /* registration failed, unregister everything
3104                    that had been registered up to that point
3105                 */
3106                 for (; x > 0; x--) {
3107                         /* we are intentionally ignoring the
3108                            result of ast_agi_unregister() here,
3109                            but it should be safe to do so since
3110                            we just registered these commands and
3111                            the only possible way for unregistration
3112                            to fail is if the command is not
3113                            registered
3114                         */
3115                         (void) ast_agi_unregister(mod, cmd + x - 1);
3116                 }
3117                 return -1;
3118         }
3119
3120         return 0;
3121 }
3122
3123 int AST_OPTIONAL_API_NAME(ast_agi_unregister_multiple)(struct ast_module *mod, struct agi_command *cmd, unsigned int len)
3124 {
3125         unsigned int i;
3126         int res = 0;
3127
3128         for (i = 0; i < len; i++) {
3129                 /* remember whether any of the unregistration
3130                    attempts failed... there is no recourse if
3131                    any of them do
3132                 */
3133                 res |= ast_agi_unregister(mod, cmd + i);
3134         }
3135
3136         return res;
3137 }
3138
3139 static agi_command *find_command(const char * const cmds[], int exact)
3140 {
3141         int y, match;
3142         struct agi_command *e;
3143
3144         AST_RWLIST_RDLOCK(&agi_commands);
3145         AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
3146                 if (!e->cmda[0])
3147                         break;
3148                 /* start optimistic */
3149                 match = 1;
3150                 for (y = 0; match && cmds[y]; y++) {
3151                         /* If there are no more words in the command (and we're looking for
3152                            an exact match) or there is a difference between the two words,
3153                            then this is not a match */
3154                         if (!e->cmda[y] && !exact)
3155                                 break;
3156                         /* don't segfault if the next part of a command doesn't exist */
3157                         if (!e->cmda[y]) {
3158                                 AST_RWLIST_UNLOCK(&agi_commands);
3159                                 return NULL;
3160                         }
3161                         if (strcasecmp(e->cmda[y], cmds[y]))
3162                                 match = 0;
3163                 }
3164                 /* If more words are needed to complete the command then this is not
3165                    a candidate (unless we're looking for a really inexact answer  */
3166                 if ((exact > -1) && e->cmda[y])
3167                         match = 0;
3168                 if (match) {
3169                         AST_RWLIST_UNLOCK(&agi_commands);
3170                         return e;
3171                 }
3172         }
3173         AST_RWLIST_UNLOCK(&agi_commands);
3174         return NULL;
3175 }
3176
3177 static int parse_args(char *s, int *max, const char *argv[])
3178 {
3179         int x = 0, quoted = 0, escaped = 0, whitespace = 1;
3180         char *cur;
3181
3182         cur = s;
3183         while(*s) {
3184                 switch(*s) {
3185                 case '"':
3186                         /* If it's escaped, put a literal quote */
3187                         if (escaped)
3188                                 goto normal;
3189                         else
3190                                 quoted = !quoted;
3191                         if (quoted && whitespace) {
3192                                 /* If we're starting a quote, coming off white space start a new word, too */
3193                                 argv[x++] = cur;
3194                                 whitespace=0;
3195                         }
3196                         escaped = 0;
3197                 break;
3198                 case ' ':
3199                 case '\t':
3200                         if (!quoted && !escaped) {
3201                                 /* If we're not quoted, mark this as whitespace, and
3202                                    end the previous argument */
3203                                 whitespace = 1;
3204                                 *(cur++) = '\0';
3205                         } else
3206                                 /* Otherwise, just treat it as anything else */
3207                                 goto normal;
3208                         break;
3209                 case '\\':
3210                         /* If we're escaped, print a literal, otherwise enable escaping */
3211                         if (escaped) {
3212                                 goto normal;
3213                         } else {
3214                                 escaped=1;
3215                         }
3216                         break;
3217                 default:
3218 normal:
3219                         if (whitespace) {
3220                                 if (x >= MAX_ARGS -1) {
3221                                         ast_log(LOG_WARNING, "Too many arguments, truncating\n");
3222                                         break;
3223                                 }
3224                                 /* Coming off of whitespace, start the next argument */
3225                                 argv[x++] = cur;
3226                                 whitespace=0;
3227                         }
3228                         *(cur++) = *s;
3229                         escaped=0;
3230                 }
3231                 s++;
3232         }
3233         /* Null terminate */
3234         *(cur++) = '\0';
3235         argv[x] = NULL;
3236         *max = x;
3237         return 0;
3238 }
3239
3240 static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int dead)
3241 {
3242         const char *argv[MAX_ARGS];
3243         int argc = MAX_ARGS, res;
3244         agi_command *c;
3245         const char *ami_res = "Unknown Result";
3246         char *ami_cmd = ast_strdupa(buf);
3247         int command_id = ast_random(), resultcode = 200;
3248
3249         manager_event(EVENT_FLAG_AGI, "AGIExec",
3250                         "SubEvent: Start\r\n"
3251                         "Channel: %s\r\n"
3252                         "CommandId: %d\r\n"
3253                         "Command: %s\r\n", chan->name, command_id, ami_cmd);
3254         parse_args(buf, &argc, argv);
3255         if ((c = find_command(argv, 0)) && (!dead || (dead && c->dead))) {
3256                 /* if this command wasnt registered by res_agi, be sure to usecount
3257                 the module we are using */
3258                 if (c->mod != ast_module_info->self)
3259                         ast_module_ref(c->mod);
3260                 /* If the AGI command being executed is an actual application (using agi exec)
3261                 the app field will be updated in pbx_exec via handle_exec */
3262                 if (chan->cdr && !ast_check_hangup(chan) && strcasecmp(argv[0], "EXEC"))
3263                         ast_cdr_setapp(chan->cdr, "AGI", buf);
3264
3265                 res = c->handler(chan, agi, argc, argv);
3266                 if (c->mod != ast_module_info->self)
3267                         ast_module_unref(c->mod);
3268                 switch (res) {
3269                 case RESULT_SHOWUSAGE: ami_res = "Usage"; resultcode = 520; break;
3270                 case RESULT_FAILURE: ami_res = "Failure"; resultcode = -1; break;
3271                 case RESULT_SUCCESS: ami_res = "Success"; resultcode = 200; break;
3272                 }
3273                 manager_event(EVENT_FLAG_AGI, "AGIExec",
3274                                 "SubEvent: End\r\n"
3275                                 "Channel: %s\r\n"
3276                                 "CommandId: %d\r\n"
3277                                 "Command: %s\r\n"
3278                                 "ResultCode: %d\r\n"
3279                                 "Result: %s\r\n", chan->name, command_id, ami_cmd, resultcode, ami_res);
3280                 switch(res) {
3281                 case RESULT_SHOWUSAGE:
3282                         if (ast_strlen_zero(c->usage)) {
3283                                 ast_agi_send(agi->fd, chan, "520 Invalid command syntax.  Proper usage not available.\n");
3284                         } else {
3285                                 ast_agi_send(agi->fd, chan, "520-Invalid command syntax.  Proper usage follows:\n");
3286                                 ast_agi_send(agi->fd, chan, "%s", c->usage);
3287                                 ast_agi_send(agi->fd, chan, "520 End of proper usage.\n");
3288                         }
3289                         break;
3290                 case RESULT_FAILURE:
3291                         /* They've already given the failure.  We've been hung up on so handle this
3292                            appropriately */
3293                         return -1;
3294                 }
3295         } else if ((c = find_command(argv, 0))) {
3296                 ast_agi_send(agi->fd, chan, "511 Command Not Permitted on a dead channel\n");
3297                 manager_event(EVENT_FLAG_AGI, "AGIExec",
3298                                 "SubEvent: End\r\n"
3299                                 "Channel: %s\r\n"
3300                                 "CommandId: %d\r\n"
3301                                 "Command: %s\r\n"
3302                                 "ResultCode: 511\r\n"
3303                                 "Result: Command not permitted on a dead channel\r\n", chan->name, command_id, ami_cmd);
3304         } else {
3305                 ast_agi_send(agi->fd, chan, "510 Invalid or unknown command\n");
3306                 manager_event(EVENT_FLAG_AGI, "AGIExec",
3307                                 "SubEvent: End\r\n"
3308                                 "Channel: %s\r\n"
3309                                 "CommandId: %d\r\n"
3310                                 "Command: %s\r\n"
3311                                 "ResultCode: 510\r\n"
3312                                 "Result: Invalid or unknown command\r\n", chan->name, command_id, ami_cmd);
3313         }
3314         return 0;
3315 }
3316 static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid, int *status, int dead, int argc, char *argv[])
3317 {
3318         struct ast_channel *c;
3319         int outfd, ms, needhup = 0;
3320         enum agi_result returnstatus = AGI_RESULT_SUCCESS;
3321         struct ast_frame *f;
3322         char buf[AGI_BUF_LEN];
3323         char *res = NULL;
3324         FILE *readf;
3325         /* how many times we'll retry if ast_waitfor_nandfs will return without either
3326           channel or file descriptor in case select is interrupted by a system call (EINTR) */
3327         int retry = AGI_NANDFS_RETRY;
3328         int send_sighup;
3329         const char *sighup_str;
3330         
3331         ast_channel_lock(chan);
3332         sighup_str = pbx_builtin_getvar_helper(chan, "AGISIGHUP");
3333         send_sighup = ast_strlen_zero(sighup_str) || !ast_false(sighup_str);
3334         ast_channel_unlock(chan);
3335
3336         if (!(readf = fdopen(agi->ctrl, "r"))) {
3337                 ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
3338                 if (send_sighup && pid > -1)
3339                         kill(pid, SIGHUP);
3340                 close(agi->ctrl);
3341                 return AGI_RESULT_FAILURE;
3342         }
3343         
3344         setlinebuf(readf);
3345         setup_env(chan, request, agi->fd, (agi->audio > -1), argc, argv);
3346         for (;;) {
3347                 if (needhup) {
3348                         needhup = 0;
3349                         dead = 1;
3350                         if (send_sighup) {
3351                                 if (pid > -1) {
3352                                         kill(pid, SIGHUP);
3353                                 } else if (agi->fast) {
3354                                         send(agi->ctrl, "HANGUP\n", 7, 0);
3355                                 }
3356                         }
3357                 }
3358                 ms = -1;
3359                 c = ast_waitfor_nandfds(&chan, dead ? 0 : 1, &agi->ctrl, 1, NULL, &outfd, &ms);
3360                 if (c) {
3361                         retry = AGI_NANDFS_RETRY;
3362                         /* Idle the channel until we get a command */
3363                         f = ast_read(c);
3364                         if (!f) {
3365                                 ast_debug(1, "%s hungup\n", chan->name);
3366                                 returnstatus = AGI_RESULT_HANGUP;
3367                                 needhup = 1;
3368                                 continue;
3369                         } else {
3370                                 /* If it's voice, write it to the audio pipe */
3371                                 if ((agi->audio > -1) && (f->frametype == AST_FRAME_VOICE)) {
3372                                         /* Write, ignoring errors */
3373                                         if (write(agi->audio, f->data.ptr, f->datalen) < 0) {
3374                                         }
3375                                 }
3376                                 ast_frfree(f);
3377                         }
3378                 } else if (outfd > -1) {
3379                         size_t len = sizeof(buf);
3380                         size_t buflen = 0;
3381
3382                         retry = AGI_NANDFS_RETRY;
3383                         buf[0] = '\0';
3384
3385                         while (buflen < (len - 1)) {
3386                                 res = fgets(buf + buflen, len, readf);
3387                                 if (feof(readf))
3388                                         break;
3389                                 if (ferror(readf) && ((errno != EINTR) && (errno != EAGAIN)))
3390                                         break;
3391                                 if (res != NULL && !agi->fast)
3392                                         break;
3393                                 buflen = strlen(buf);
3394                                 if (buflen && buf[buflen - 1] == '\n')
3395                                         break;
3396                                 len -= buflen;
3397                                 if (agidebug)
3398                                         ast_verbose( "AGI Rx << temp buffer %s - errno %s\n", buf, strerror(errno));
3399                         }
3400
3401                         if (!buf[0]) {
3402                                 /* Program terminated */
3403                                 if (returnstatus) {
3404                                         returnstatus = -1;
3405                                 }
3406                                 ast_verb(3, "<%s>AGI Script %s completed, returning %d\n", chan->name, request, returnstatus);
3407                                 if (pid > 0)
3408                                         waitpid(pid, status, 0);
3409                                 /* No need to kill the pid anymore, since they closed us */
3410                                 pid = -1;
3411                                 break;
3412                         }
3413
3414                         /* Special case for inability to execute child process */
3415                         if (*buf && strncasecmp(buf, "failure", 7) == 0) {
3416                                 returnstatus = AGI_RESULT_FAILURE;
3417                                 break;
3418                         }
3419
3420                         /* get rid of trailing newline, if any */
3421                         if (*buf && buf[strlen(buf) - 1] == '\n')
3422                                 buf[strlen(buf) - 1] = 0;
3423                         if (agidebug)
3424                                 ast_verbose("<%s>AGI Rx << %s\n", chan->name, buf);
3425                         returnstatus |= agi_handle_command(chan, agi, buf, dead);
3426                         /* If the handle_command returns -1, we need to stop */
3427                         if (returnstatus < 0) {
3428                                 needhup = 1;
3429                                 continue;
3430                         }
3431                 } else {
3432                         if (--retry <= 0) {
3433                                 ast_log(LOG_WARNING, "No channel, no fd?\n");
3434                                 returnstatus = AGI_RESULT_FAILURE;
3435                                 break;
3436                         }
3437                 }
3438         }
3439         if (agi->speech) {
3440                 ast_speech_destroy(agi->speech);
3441         }
3442         /* Notify process */
3443         if (send_sighup) {
3444                 if (pid > -1) {
3445                         if (kill(pid, SIGHUP)) {
3446                                 ast_log(LOG_WARNING, "unable to send SIGHUP to AGI process %d: %s\n", pid, strerror(errno));
3447                         } else { /* Give the process a chance to die */
3448                                 usleep(1);
3449                         }
3450                         waitpid(pid, status, WNOHANG);
3451                 } else if (agi->fast) {
3452                         send(agi->ctrl, "HANGUP\n", 7, 0);
3453                 }
3454         }
3455         fclose(readf);
3456         return returnstatus;
3457 }
3458
3459 static char *handle_cli_agi_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3460 {
3461         struct agi_command *command;
3462         char fullcmd[MAX_CMD_LEN];
3463         int error = 0;
3464
3465         switch (cmd) {</