Consolidate ast_channel.cid.cid_rdnis into ast_channel.redirecting.from.number.
[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 listner 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 controled 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 recieve 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 preceeded 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 specfied 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 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 in OOB data. Both of these signals may be disabled
818                         by setting the <variable>AGISIGHUP</variable> channel variable to <literal>no</literal>
819                         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", S_OR(chan->cid.cid_num, "unknown"));
1630         ast_agi_send(fd, chan, "agi_calleridname: %s\n", S_OR(chan->cid.cid_name, "unknown"));
1631         ast_agi_send(fd, chan, "agi_callingpres: %d\n", chan->cid.cid_pres);
1632         ast_agi_send(fd, chan, "agi_callingani2: %d\n", chan->cid.cid_ani2);
1633         ast_agi_send(fd, chan, "agi_callington: %d\n", chan->cid.cid_ton);
1634         ast_agi_send(fd, chan, "agi_callingtns: %d\n", chan->cid.cid_tns);
1635         ast_agi_send(fd, chan, "agi_dnid: %s\n", S_OR(chan->cid.cid_dnid, "unknown"));
1636         ast_agi_send(fd, chan, "agi_rdnis: %s\n", S_OR(chan->redirecting.from.number, "unknown"));
1637
1638         /* Context information */
1639         ast_agi_send(fd, chan, "agi_context: %s\n", chan->context);
1640         ast_agi_send(fd, chan, "agi_extension: %s\n", chan->exten);
1641         ast_agi_send(fd, chan, "agi_priority: %d\n", chan->priority);
1642         ast_agi_send(fd, chan, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
1643
1644         /* User information */
1645         ast_agi_send(fd, chan, "agi_accountcode: %s\n", chan->accountcode ? chan->accountcode : "");
1646         ast_agi_send(fd, chan, "agi_threadid: %ld\n", (long)pthread_self());
1647
1648         /* Send any parameters to the fastagi server that have been passed via the agi application */
1649         /* Agi application paramaters take the form of: AGI(/path/to/example/script|${EXTEN}) */
1650         for(count = 1; count < argc; count++)
1651                 ast_agi_send(fd, chan, "agi_arg_%d: %s\n", count, argv[count]);
1652
1653         /* End with empty return */
1654         ast_agi_send(fd, chan, "\n");
1655 }
1656
1657 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1658 {
1659         int res = 0;
1660
1661         /* Answer the channel */
1662         if (chan->_state != AST_STATE_UP)
1663                 res = ast_answer(chan);
1664
1665         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1666         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1667 }
1668
1669 static int handle_asyncagi_break(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1670 {
1671         ast_agi_send(agi->fd, chan, "200 result=0\n");
1672         return RESULT_FAILURE;
1673 }
1674
1675 static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1676 {
1677         int res, to;
1678
1679         if (argc != 4)
1680                 return RESULT_SHOWUSAGE;
1681         if (sscanf(argv[3], "%30d", &to) != 1)
1682                 return RESULT_SHOWUSAGE;
1683         res = ast_waitfordigit_full(chan, to, agi->audio, agi->ctrl);
1684         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1685         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1686 }
1687
1688 static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1689 {
1690         int res;
1691
1692         if (argc != 3)
1693                 return RESULT_SHOWUSAGE;
1694
1695         /* At the moment, the parser (perhaps broken) returns with
1696            the last argument PLUS the newline at the end of the input
1697            buffer. This probably needs to be fixed, but I wont do that
1698            because other stuff may break as a result. The right way
1699            would probably be to strip off the trailing newline before
1700            parsing, then here, add a newline at the end of the string
1701            before sending it to ast_sendtext --DUDE */
1702         res = ast_sendtext(chan, argv[2]);
1703         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1704         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1705 }
1706
1707 static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1708 {
1709         int res;
1710
1711         if (argc != 3)
1712                 return RESULT_SHOWUSAGE;
1713
1714         res = ast_recvchar(chan,atoi(argv[2]));
1715         if (res == 0) {
1716                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout)\n", res);
1717                 return RESULT_SUCCESS;
1718         }
1719         if (res > 0) {
1720                 ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1721                 return RESULT_SUCCESS;
1722         }
1723         ast_agi_send(agi->fd, chan, "200 result=%d (hangup)\n", res);
1724         return RESULT_FAILURE;
1725 }
1726
1727 static int handle_recvtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1728 {
1729         char *buf;
1730
1731         if (argc != 3)
1732                 return RESULT_SHOWUSAGE;
1733
1734         buf = ast_recvtext(chan, atoi(argv[2]));
1735         if (buf) {
1736                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", buf);
1737                 ast_free(buf);
1738         } else {
1739                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
1740         }
1741         return RESULT_SUCCESS;
1742 }
1743
1744 static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1745 {
1746         int res, x;
1747
1748         if (argc != 3)
1749                 return RESULT_SHOWUSAGE;
1750
1751         if (!strncasecmp(argv[2],"on",2)) {
1752                 x = 1;
1753         } else  {
1754                 x = 0;
1755         }
1756         if (!strncasecmp(argv[2],"mate",4))  {
1757                 x = 2;
1758         }
1759         if (!strncasecmp(argv[2],"tdd",3)) {
1760                 x = 1;
1761         }
1762         res = ast_channel_setoption(chan, AST_OPTION_TDD, &x, sizeof(char), 0);
1763         if (res != RESULT_SUCCESS) {
1764                 ast_agi_send(agi->fd, chan, "200 result=0\n");
1765         } else {
1766                 ast_agi_send(agi->fd, chan, "200 result=1\n");
1767         }
1768         return RESULT_SUCCESS;
1769 }
1770
1771 static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1772 {
1773         int res;
1774
1775         if (argc != 3) {
1776                 return RESULT_SHOWUSAGE;
1777         }
1778
1779         res = ast_send_image(chan, argv[2]);
1780         if (!ast_check_hangup(chan)) {
1781                 res = 0;
1782         }
1783         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1784         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1785 }
1786
1787 static int handle_controlstreamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1788 {
1789         int res = 0, skipms = 3000;
1790         const char *fwd = "#", *rev = "*", *suspend = NULL, *stop = NULL;       /* Default values */
1791
1792         if (argc < 5 || argc > 9) {
1793                 return RESULT_SHOWUSAGE;
1794         }
1795
1796         if (!ast_strlen_zero(argv[4])) {
1797                 stop = argv[4];
1798         }
1799
1800         if ((argc > 5) && (sscanf(argv[5], "%30d", &skipms) != 1)) {
1801                 return RESULT_SHOWUSAGE;
1802         }
1803
1804         if (argc > 6 && !ast_strlen_zero(argv[6])) {
1805                 fwd = argv[6];
1806         }
1807
1808         if (argc > 7 && !ast_strlen_zero(argv[7])) {
1809                 rev = argv[7];
1810         }
1811
1812         if (argc > 8 && !ast_strlen_zero(argv[8])) {
1813                 suspend = argv[8];
1814         }
1815
1816         res = ast_control_streamfile(chan, argv[3], fwd, rev, stop, suspend, NULL, skipms, NULL);
1817
1818         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1819
1820         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1821 }
1822
1823 static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1824 {
1825         int res, vres;
1826         struct ast_filestream *fs, *vfs;
1827         long sample_offset = 0, max_length;
1828         const char *edigits = "";
1829
1830         if (argc < 4 || argc > 5)
1831                 return RESULT_SHOWUSAGE;
1832
1833         if (argv[3])
1834                 edigits = argv[3];
1835
1836         if ((argc > 4) && (sscanf(argv[4], "%30ld", &sample_offset) != 1))
1837                 return RESULT_SHOWUSAGE;
1838
1839         if (!(fs = ast_openstream(chan, argv[2], chan->language))) {
1840                 ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", 0, sample_offset);
1841                 return RESULT_SUCCESS;
1842         }
1843
1844         if ((vfs = ast_openvstream(chan, argv[2], chan->language)))
1845                 ast_debug(1, "Ooh, found a video stream, too\n");
1846
1847         ast_verb(3, "Playing '%s' (escape_digits=%s) (sample_offset %ld)\n", argv[2], edigits, sample_offset);
1848
1849         ast_seekstream(fs, 0, SEEK_END);
1850         max_length = ast_tellstream(fs);
1851         ast_seekstream(fs, sample_offset, SEEK_SET);
1852         res = ast_applystream(chan, fs);
1853         if (vfs)
1854                 vres = ast_applystream(chan, vfs);
1855         ast_playstream(fs);
1856         if (vfs)
1857                 ast_playstream(vfs);
1858
1859         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
1860         /* this is to check for if ast_waitstream closed the stream, we probably are at
1861          * the end of the stream, return that amount, else check for the amount */
1862         sample_offset = (chan->stream) ? ast_tellstream(fs) : max_length;
1863         ast_stopstream(chan);
1864         if (res == 1) {
1865                 /* Stop this command, don't print a result line, as there is a new command */
1866                 return RESULT_SUCCESS;
1867         }
1868         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
1869         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1870 }
1871
1872 /*! \brief get option - really similar to the handle_streamfile, but with a timeout */
1873 static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1874 {
1875         int res, vres;
1876         struct ast_filestream *fs, *vfs;
1877         long sample_offset = 0, max_length;
1878         int timeout = 0;
1879         const char *edigits = "";
1880
1881         if ( argc < 4 || argc > 5 )
1882                 return RESULT_SHOWUSAGE;
1883
1884         if ( argv[3] )
1885                 edigits = argv[3];
1886
1887         if ( argc == 5 )
1888                 timeout = atoi(argv[4]);
1889         else if (chan->pbx->dtimeoutms) {
1890                 /* by default dtimeout is set to 5sec */
1891                 timeout = chan->pbx->dtimeoutms; /* in msec */
1892         }
1893
1894         if (!(fs = ast_openstream(chan, argv[2], chan->language))) {
1895                 ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", 0, sample_offset);
1896                 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
1897                 return RESULT_SUCCESS;
1898         }
1899
1900         if ((vfs = ast_openvstream(chan, argv[2], chan->language)))
1901                 ast_debug(1, "Ooh, found a video stream, too\n");
1902
1903         ast_verb(3, "Playing '%s' (escape_digits=%s) (timeout %d)\n", argv[2], edigits, timeout);
1904
1905         ast_seekstream(fs, 0, SEEK_END);
1906         max_length = ast_tellstream(fs);
1907         ast_seekstream(fs, sample_offset, SEEK_SET);
1908         res = ast_applystream(chan, fs);
1909         if (vfs)
1910                 vres = ast_applystream(chan, vfs);
1911         ast_playstream(fs);
1912         if (vfs)
1913                 ast_playstream(vfs);
1914
1915         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
1916         /* this is to check for if ast_waitstream closed the stream, we probably are at
1917          * the end of the stream, return that amount, else check for the amount */
1918         sample_offset = (chan->stream)?ast_tellstream(fs):max_length;
1919         ast_stopstream(chan);
1920         if (res == 1) {
1921                 /* Stop this command, don't print a result line, as there is a new command */
1922                 return RESULT_SUCCESS;
1923         }
1924
1925         /* If the user didnt press a key, wait for digitTimeout*/
1926         if (res == 0 ) {
1927                 res = ast_waitfordigit_full(chan, timeout, agi->audio, agi->ctrl);
1928                 /* Make sure the new result is in the escape digits of the GET OPTION */
1929                 if ( !strchr(edigits,res) )
1930                         res=0;
1931         }
1932
1933         ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
1934         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1935 }
1936
1937
1938
1939
1940 /*! \brief Say number in various language syntaxes */
1941 /* While waiting, we're sending a NULL.  */
1942 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1943 {
1944         int res, num;
1945
1946         if (argc < 4 || argc > 5)
1947                 return RESULT_SHOWUSAGE;
1948         if (sscanf(argv[2], "%30d", &num) != 1)
1949                 return RESULT_SHOWUSAGE;
1950         res = ast_say_number_full(chan, num, argv[3], chan->language, argc > 4 ? argv[4] : NULL, agi->audio, agi->ctrl);
1951         if (res == 1)
1952                 return RESULT_SUCCESS;
1953         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1954         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1955 }
1956
1957 static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1958 {
1959         int res, num;
1960
1961         if (argc != 4)
1962                 return RESULT_SHOWUSAGE;
1963         if (sscanf(argv[2], "%30d", &num) != 1)
1964                 return RESULT_SHOWUSAGE;
1965
1966         res = ast_say_digit_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
1967         if (res == 1) /* New command */
1968                 return RESULT_SUCCESS;
1969         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1970         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1971 }
1972
1973 static int handle_sayalpha(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1974 {
1975         int res;
1976
1977         if (argc != 4)
1978                 return RESULT_SHOWUSAGE;
1979
1980         res = ast_say_character_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
1981         if (res == 1) /* New command */
1982                 return RESULT_SUCCESS;
1983         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1984         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
1985 }
1986
1987 static int handle_saydate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
1988 {
1989         int res, num;
1990
1991         if (argc != 4)
1992                 return RESULT_SHOWUSAGE;
1993         if (sscanf(argv[2], "%30d", &num) != 1)
1994                 return RESULT_SHOWUSAGE;
1995         res = ast_say_date(chan, num, argv[3], chan->language);
1996         if (res == 1)
1997                 return RESULT_SUCCESS;
1998         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
1999         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2000 }
2001
2002 static int handle_saytime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2003 {
2004         int res, num;
2005
2006         if (argc != 4)
2007                 return RESULT_SHOWUSAGE;
2008         if (sscanf(argv[2], "%30d", &num) != 1)
2009                 return RESULT_SHOWUSAGE;
2010         res = ast_say_time(chan, num, argv[3], chan->language);
2011         if (res == 1)
2012                 return RESULT_SUCCESS;
2013         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2014         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2015 }
2016
2017 static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2018 {
2019         int res = 0;
2020         time_t unixtime;
2021         const char *format, *zone = NULL;
2022
2023         if (argc < 4)
2024                 return RESULT_SHOWUSAGE;
2025
2026         if (argc > 4) {
2027                 format = argv[4];
2028         } else {
2029                 /* XXX this doesn't belong here, but in the 'say' module */
2030                 if (!strcasecmp(chan->language, "de")) {
2031                         format = "A dBY HMS";
2032                 } else {
2033                         format = "ABdY 'digits/at' IMp";
2034                 }
2035         }
2036
2037         if (argc > 5 && !ast_strlen_zero(argv[5]))
2038                 zone = argv[5];
2039
2040         if (ast_get_time_t(argv[2], &unixtime, 0, NULL))
2041                 return RESULT_SHOWUSAGE;
2042
2043         res = ast_say_date_with_format(chan, unixtime, argv[3], chan->language, format, zone);
2044         if (res == 1)
2045                 return RESULT_SUCCESS;
2046
2047         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2048         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2049 }
2050
2051 static int handle_sayphonetic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2052 {
2053         int res;
2054
2055         if (argc != 4)
2056                 return RESULT_SHOWUSAGE;
2057
2058         res = ast_say_phonetic_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
2059         if (res == 1) /* New command */
2060                 return RESULT_SUCCESS;
2061         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2062         return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
2063 }
2064
2065 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2066 {
2067         int res, max, timeout;
2068         char data[1024];
2069
2070         if (argc < 3)
2071                 return RESULT_SHOWUSAGE;
2072         if (argc >= 4)
2073                 timeout = atoi(argv[3]);
2074         else
2075                 timeout = 0;
2076         if (argc >= 5)
2077                 max = atoi(argv[4]);
2078         else
2079                 max = 1024;
2080         res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
2081         if (res == 2)                   /* New command */
2082                 return RESULT_SUCCESS;
2083         else if (res == 1)
2084                 ast_agi_send(agi->fd, chan, "200 result=%s (timeout)\n", data);
2085         else if (res < 0 )
2086                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2087         else
2088                 ast_agi_send(agi->fd, chan, "200 result=%s\n", data);
2089         return RESULT_SUCCESS;
2090 }
2091
2092 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2093 {
2094
2095         if (argc != 3)
2096                 return RESULT_SHOWUSAGE;
2097         ast_copy_string(chan->context, argv[2], sizeof(chan->context));
2098         ast_agi_send(agi->fd, chan, "200 result=0\n");
2099         return RESULT_SUCCESS;
2100 }
2101
2102 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2103 {
2104         if (argc != 3)
2105                 return RESULT_SHOWUSAGE;
2106         ast_copy_string(chan->exten, argv[2], sizeof(chan->exten));
2107         ast_agi_send(agi->fd, chan, "200 result=0\n");
2108         return RESULT_SUCCESS;
2109 }
2110
2111 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2112 {
2113         int pri;
2114
2115         if (argc != 3)
2116                 return RESULT_SHOWUSAGE;
2117
2118         if (sscanf(argv[2], "%30d", &pri) != 1) {
2119                 if ((pri = ast_findlabel_extension(chan, chan->context, chan->exten, argv[2], chan->cid.cid_num)) < 1)
2120                         return RESULT_SHOWUSAGE;
2121         }
2122
2123         ast_explicit_goto(chan, NULL, NULL, pri);
2124         ast_agi_send(agi->fd, chan, "200 result=0\n");
2125         return RESULT_SUCCESS;
2126 }
2127
2128 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2129 {
2130         struct ast_filestream *fs;
2131         struct ast_frame *f;
2132         struct timeval start;
2133         long sample_offset = 0;
2134         int res = 0;
2135         int ms;
2136
2137         struct ast_dsp *sildet=NULL;         /* silence detector dsp */
2138         int totalsilence = 0;
2139         int dspsilence = 0;
2140         int silence = 0;                /* amount of silence to allow */
2141         int gotsilence = 0;             /* did we timeout for silence? */
2142         char *silencestr = NULL;
2143         int rfmt = 0;
2144
2145         /* XXX EAGI FIXME XXX */
2146
2147         if (argc < 6)
2148                 return RESULT_SHOWUSAGE;
2149         if (sscanf(argv[5], "%30d", &ms) != 1)
2150                 return RESULT_SHOWUSAGE;
2151
2152         if (argc > 6)
2153                 silencestr = strchr(argv[6],'s');
2154         if ((argc > 7) && (!silencestr))
2155                 silencestr = strchr(argv[7],'s');
2156         if ((argc > 8) && (!silencestr))
2157                 silencestr = strchr(argv[8],'s');
2158
2159         if (silencestr) {
2160                 if (strlen(silencestr) > 2) {
2161                         if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
2162                                 silencestr++;
2163                                 silencestr++;
2164                                 if (silencestr)
2165                                         silence = atoi(silencestr);
2166                                 if (silence > 0)
2167                                         silence *= 1000;
2168                         }
2169                 }
2170         }
2171
2172         if (silence > 0) {
2173                 rfmt = chan->readformat;
2174                 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
2175                 if (res < 0) {
2176                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
2177                         return -1;
2178                 }
2179                 sildet = ast_dsp_new();
2180                 if (!sildet) {
2181                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
2182                         return -1;
2183                 }
2184                 ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
2185         }
2186         
2187         /* backward compatibility, if no offset given, arg[6] would have been
2188          * caught below and taken to be a beep, else if it is a digit then it is a
2189          * offset */
2190         if ((argc >6) && (sscanf(argv[6], "%30ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
2191                 res = ast_streamfile(chan, "beep", chan->language);
2192
2193         if ((argc > 7) && (!strchr(argv[7], '=')))
2194                 res = ast_streamfile(chan, "beep", chan->language);
2195
2196         if (!res)
2197                 res = ast_waitstream(chan, argv[4]);
2198         if (res) {
2199                 ast_agi_send(agi->fd, chan, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
2200         } else {
2201                 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, AST_FILE_MODE);
2202                 if (!fs) {
2203                         res = -1;
2204                         ast_agi_send(agi->fd, chan, "200 result=%d (writefile)\n", res);
2205                         if (sildet)
2206                                 ast_dsp_free(sildet);
2207                         return RESULT_FAILURE;
2208                 }
2209
2210                 /* Request a video update */
2211                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
2212
2213                 chan->stream = fs;
2214                 ast_applystream(chan,fs);
2215                 /* really should have checks */
2216                 ast_seekstream(fs, sample_offset, SEEK_SET);
2217                 ast_truncstream(fs);
2218
2219                 start = ast_tvnow();
2220                 while ((ms < 0) || ast_tvdiff_ms(ast_tvnow(), start) < ms) {
2221                         res = ast_waitfor(chan, ms - ast_tvdiff_ms(ast_tvnow(), start));
2222                         if (res < 0) {
2223                                 ast_closestream(fs);
2224                                 ast_agi_send(agi->fd, chan, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
2225                                 if (sildet)
2226                                         ast_dsp_free(sildet);
2227                                 return RESULT_FAILURE;
2228                         }
2229                         f = ast_read(chan);
2230                         if (!f) {
2231                                 ast_agi_send(agi->fd, chan, "200 result=%d (hangup) endpos=%ld\n", -1, sample_offset);
2232                                 ast_closestream(fs);
2233                                 if (sildet)
2234                                         ast_dsp_free(sildet);
2235                                 return RESULT_FAILURE;
2236                         }
2237                         switch(f->frametype) {
2238                         case AST_FRAME_DTMF:
2239                                 if (strchr(argv[4], f->subclass.integer)) {
2240                                         /* This is an interrupting chracter, so rewind to chop off any small
2241                                            amount of DTMF that may have been recorded
2242                                         */
2243                                         ast_stream_rewind(fs, 200);
2244                                         ast_truncstream(fs);
2245                                         sample_offset = ast_tellstream(fs);
2246                                         ast_agi_send(agi->fd, chan, "200 result=%d (dtmf) endpos=%ld\n", f->subclass.integer, sample_offset);
2247                                         ast_closestream(fs);
2248                                         ast_frfree(f);
2249                                         if (sildet)
2250                                                 ast_dsp_free(sildet);
2251                                         return RESULT_SUCCESS;
2252                                 }
2253                                 break;
2254                         case AST_FRAME_VOICE:
2255                                 ast_writestream(fs, f);
2256                                 /* this is a safe place to check progress since we know that fs
2257                                  * is valid after a write, and it will then have our current
2258                                  * location */
2259                                 sample_offset = ast_tellstream(fs);
2260                                 if (silence > 0) {
2261                                         dspsilence = 0;
2262                                         ast_dsp_silence(sildet, f, &dspsilence);
2263                                         if (dspsilence) {
2264                                                 totalsilence = dspsilence;
2265                                         } else {
2266                                                 totalsilence = 0;
2267                                         }
2268                                         if (totalsilence > silence) {
2269                                                 /* Ended happily with silence */
2270                                                 gotsilence = 1;
2271                                                 break;
2272                                         }
2273                                 }
2274                                 break;
2275                         case AST_FRAME_VIDEO:
2276                                 ast_writestream(fs, f);
2277                         default:
2278                                 /* Ignore all other frames */
2279                                 break;
2280                         }
2281                         ast_frfree(f);
2282                         if (gotsilence)
2283                                 break;
2284                 }
2285
2286                 if (gotsilence) {
2287                         ast_stream_rewind(fs, silence-1000);
2288                         ast_truncstream(fs);
2289                         sample_offset = ast_tellstream(fs);
2290                 }
2291                 ast_agi_send(agi->fd, chan, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
2292                 ast_closestream(fs);
2293         }
2294
2295         if (silence > 0) {
2296                 res = ast_set_read_format(chan, rfmt);
2297                 if (res)
2298                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", chan->name);
2299                 ast_dsp_free(sildet);
2300         }
2301
2302         return RESULT_SUCCESS;
2303 }
2304
2305 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2306 {
2307         double timeout;
2308         struct timeval whentohangup = { 0, 0 };
2309
2310         if (argc != 3)
2311                 return RESULT_SHOWUSAGE;
2312         if (sscanf(argv[2], "%30lf", &timeout) != 1)
2313                 return RESULT_SHOWUSAGE;
2314         if (timeout < 0)
2315                 timeout = 0;
2316         if (timeout) {
2317                 whentohangup.tv_sec = timeout;
2318                 whentohangup.tv_usec = (timeout - whentohangup.tv_sec) * 1000000.0;
2319         }
2320         ast_channel_setwhentohangup_tv(chan, whentohangup);
2321         ast_agi_send(agi->fd, chan, "200 result=0\n");
2322         return RESULT_SUCCESS;
2323 }
2324
2325 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2326 {
2327         struct ast_channel *c;
2328
2329         if (argc == 1) {
2330                 /* no argument: hangup the current channel */
2331                 ast_set_hangupsource(chan, "dialplan/agi", 0);
2332                 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
2333                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2334                 return RESULT_SUCCESS;
2335         } else if (argc == 2) {
2336                 /* one argument: look for info on the specified channel */
2337                 if ((c = ast_channel_get_by_name(argv[1]))) {
2338                         /* we have a matching channel */
2339                         ast_set_hangupsource(c, "dialplan/agi", 0);
2340                         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
2341                         c = ast_channel_unref(c);
2342                         ast_agi_send(agi->fd, chan, "200 result=1\n");
2343                         return RESULT_SUCCESS;
2344                 }
2345                 /* if we get this far no channel name matched the argument given */
2346                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2347                 return RESULT_SUCCESS;
2348         } else {
2349                 return RESULT_SHOWUSAGE;
2350         }
2351 }
2352
2353 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2354 {
2355         int res, workaround;
2356         struct ast_app *app_to_exec;
2357
2358         if (argc < 2)
2359                 return RESULT_SHOWUSAGE;
2360
2361         ast_verb(3, "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argc >= 3 ? argv[2] : "");
2362
2363         if ((app_to_exec = pbx_findapp(argv[1]))) {
2364                 if(!strcasecmp(argv[1], PARK_APP_NAME)) {
2365                         ast_masq_park_call(chan, NULL, 0, NULL);
2366                 }
2367                 if (!(workaround = ast_test_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS))) {
2368                         ast_set_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS);
2369                 }
2370                 if (ast_compat_res_agi && argc >= 3 && !ast_strlen_zero(argv[2])) {
2371                         char *compat = alloca(strlen(argv[2]) * 2 + 1), *cptr;
2372                         const char *vptr;
2373                         for (cptr = compat, vptr = argv[2]; *vptr; vptr++) {
2374                                 if (*vptr == ',') {
2375                                         *cptr++ = '\\';
2376                                         *cptr++ = ',';
2377                                 } else if (*vptr == '|') {
2378                                         *cptr++ = ',';
2379                                 } else {
2380                                         *cptr++ = *vptr;
2381                                 }
2382                         }
2383                         *cptr = '\0';
2384                         res = pbx_exec(chan, app_to_exec, compat);
2385                 } else {
2386                         res = pbx_exec(chan, app_to_exec, argc == 2 ? "" : argv[2]);
2387                 }
2388                 if (!workaround) {
2389                         ast_clear_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS);
2390                 }
2391         } else {
2392                 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
2393                 res = -2;
2394         }
2395         ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
2396
2397         /* Even though this is wrong, users are depending upon this result. */
2398         return res;
2399 }
2400
2401 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2402 {
2403         char tmp[256]="";
2404         char *l = NULL, *n = NULL;
2405
2406         if (argv[2]) {
2407                 ast_copy_string(tmp, argv[2], sizeof(tmp));
2408                 ast_callerid_parse(tmp, &n, &l);
2409                 if (l)
2410                         ast_shrink_phone_number(l);
2411                 else
2412                         l = "";
2413                 if (!n)
2414                         n = "";
2415                 ast_set_callerid(chan, l, n, NULL);
2416         }
2417
2418         ast_agi_send(agi->fd, chan, "200 result=1\n");
2419         return RESULT_SUCCESS;
2420 }
2421
2422 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2423 {
2424         struct ast_channel *c;
2425         if (argc == 2) {
2426                 /* no argument: supply info on the current channel */
2427                 ast_agi_send(agi->fd, chan, "200 result=%d\n", chan->_state);
2428                 return RESULT_SUCCESS;
2429         } else if (argc == 3) {
2430                 /* one argument: look for info on the specified channel */
2431                 if ((c = ast_channel_get_by_name(argv[2]))) {
2432                         ast_agi_send(agi->fd, chan, "200 result=%d\n", c->_state);
2433                         c = ast_channel_unref(c);
2434                         return RESULT_SUCCESS;
2435                 }
2436                 /* if we get this far no channel name matched the argument given */
2437                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2438                 return RESULT_SUCCESS;
2439         } else {
2440                 return RESULT_SHOWUSAGE;
2441         }
2442 }
2443
2444 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2445 {
2446         if (argv[3])
2447                 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
2448
2449         ast_agi_send(agi->fd, chan, "200 result=1\n");
2450         return RESULT_SUCCESS;
2451 }
2452
2453 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2454 {
2455         char *ret;
2456         char tempstr[1024];
2457
2458         if (argc != 3)
2459                 return RESULT_SHOWUSAGE;
2460
2461         /* check if we want to execute an ast_custom_function */
2462         if (!ast_strlen_zero(argv[2]) && (argv[2][strlen(argv[2]) - 1] == ')')) {
2463                 ret = ast_func_read(chan, argv[2], tempstr, sizeof(tempstr)) ? NULL : tempstr;
2464         } else {
2465                 pbx_retrieve_variable(chan, argv[2], &ret, tempstr, sizeof(tempstr), NULL);
2466         }
2467
2468         if (ret)
2469                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ret);
2470         else
2471                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2472
2473         return RESULT_SUCCESS;
2474 }
2475
2476 static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2477 {
2478         struct ast_channel *chan2 = NULL;
2479
2480         if (argc != 4 && argc != 5) {
2481                 return RESULT_SHOWUSAGE;
2482         }
2483
2484         if (argc == 5) {
2485                 chan2 = ast_channel_get_by_name(argv[4]);
2486         } else {
2487                 chan2 = ast_channel_ref(chan);
2488         }
2489
2490         if (chan2) {
2491                 struct ast_str *str = ast_str_create(16);
2492                 if (!str) {
2493                         ast_agi_send(agi->fd, chan, "200 result=0\n");
2494                         return RESULT_SUCCESS;
2495                 }
2496                 ast_str_substitute_variables(&str, 0, chan2, argv[3]);
2497                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(str));
2498                 ast_free(str);
2499         } else {
2500                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2501         }
2502
2503         if (chan2) {
2504                 chan2 = ast_channel_unref(chan2);
2505         }
2506
2507         return RESULT_SUCCESS;
2508 }
2509
2510 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2511 {
2512         int level = 0;
2513
2514         if (argc < 2)
2515                 return RESULT_SHOWUSAGE;
2516
2517         if (argv[2])
2518                 sscanf(argv[2], "%30d", &level);
2519
2520         ast_verb(level, "%s: %s\n", chan->data, argv[1]);
2521
2522         ast_agi_send(agi->fd, chan, "200 result=1\n");
2523
2524         return RESULT_SUCCESS;
2525 }
2526
2527 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2528 {
2529         int res;
2530         struct ast_str *buf;
2531
2532         if (argc != 4)
2533                 return RESULT_SHOWUSAGE;
2534
2535         if (!(buf = ast_str_create(16))) {
2536                 ast_agi_send(agi->fd, chan, "200 result=-1\n");
2537                 return RESULT_SUCCESS;
2538         }
2539
2540         do {
2541                 res = ast_db_get(argv[2], argv[3], ast_str_buffer(buf), ast_str_size(buf));
2542                 ast_str_update(buf);
2543                 if (ast_str_strlen(buf) < ast_str_size(buf) - 1) {
2544                         break;
2545                 }
2546                 if (ast_str_make_space(&buf, ast_str_size(buf) * 2)) {
2547                         break;
2548                 }
2549         } while (1);
2550         
2551         if (res)
2552                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2553         else
2554                 ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(buf));
2555
2556         ast_free(buf);
2557         return RESULT_SUCCESS;
2558 }
2559
2560 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2561 {
2562         int res;
2563
2564         if (argc != 5)
2565                 return RESULT_SHOWUSAGE;
2566         res = ast_db_put(argv[2], argv[3], argv[4]);
2567         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2568         return RESULT_SUCCESS;
2569 }
2570
2571 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2572 {
2573         int res;
2574
2575         if (argc != 4)
2576                 return RESULT_SHOWUSAGE;
2577         res = ast_db_del(argv[2], argv[3]);
2578         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2579         return RESULT_SUCCESS;
2580 }
2581
2582 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2583 {
2584         int res;
2585
2586         if ((argc < 3) || (argc > 4))
2587                 return RESULT_SHOWUSAGE;
2588         if (argc == 4)
2589                 res = ast_db_deltree(argv[2], argv[3]);
2590         else
2591                 res = ast_db_deltree(argv[2], NULL);
2592
2593         ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
2594         return RESULT_SUCCESS;
2595 }
2596
2597 static char *handle_cli_agi_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2598 {
2599         switch (cmd) {
2600         case CLI_INIT:
2601                 e->command = "agi set debug [on|off]";
2602                 e->usage =
2603                         "Usage: agi set debug [on|off]\n"
2604                         "       Enables/disables dumping of AGI transactions for\n"
2605                         "       debugging purposes.\n";
2606                 return NULL;
2607
2608         case CLI_GENERATE:
2609                 return NULL;
2610         }
2611
2612         if (a->argc != e->args)
2613                 return CLI_SHOWUSAGE;
2614
2615         if (strncasecmp(a->argv[3], "off", 3) == 0) {
2616                 agidebug = 0;
2617         } else if (strncasecmp(a->argv[3], "on", 2) == 0) {
2618                 agidebug = 1;
2619         } else {
2620                 return CLI_SHOWUSAGE;
2621         }
2622         ast_cli(a->fd, "AGI Debugging %sabled\n", agidebug ? "En" : "Dis");
2623         return CLI_SUCCESS;
2624 }
2625
2626 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, const char * const argv[])
2627 {
2628         ast_agi_send(agi->fd, chan, "200 result=0\n");
2629         return RESULT_SUCCESS;
2630 }
2631
2632 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2633 {
2634         if (argc < 3) {
2635                 return RESULT_SHOWUSAGE;
2636         }
2637         if (!strncasecmp(argv[2], "on", 2))
2638                 ast_moh_start(chan, argc > 3 ? argv[3] : NULL, NULL);
2639         else if (!strncasecmp(argv[2], "off", 3))
2640                 ast_moh_stop(chan);
2641         ast_agi_send(agi->fd, chan, "200 result=0\n");
2642         return RESULT_SUCCESS;
2643 }
2644
2645 static int handle_speechcreate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2646 {
2647         /* If a structure already exists, return an error */
2648         if (agi->speech) {
2649                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2650                 return RESULT_SUCCESS;
2651         }
2652
2653         if ((agi->speech = ast_speech_new(argv[2], AST_FORMAT_SLINEAR)))
2654                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2655         else
2656                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2657
2658         return RESULT_SUCCESS;
2659 }
2660
2661 static int handle_speechset(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2662 {
2663         /* Check for minimum arguments */
2664         if (argc != 4)
2665                 return RESULT_SHOWUSAGE;
2666
2667         /* Check to make sure speech structure exists */
2668         if (!agi->speech) {
2669                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2670                 return RESULT_SUCCESS;
2671         }
2672
2673         ast_speech_change(agi->speech, argv[2], argv[3]);
2674         ast_agi_send(agi->fd, chan, "200 result=1\n");
2675
2676         return RESULT_SUCCESS;
2677 }
2678
2679 static int handle_speechdestroy(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2680 {
2681         if (agi->speech) {
2682                 ast_speech_destroy(agi->speech);
2683                 agi->speech = NULL;
2684                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2685         } else {
2686                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2687         }
2688
2689         return RESULT_SUCCESS;
2690 }
2691
2692 static int handle_speechloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2693 {
2694         if (argc != 5)
2695                 return RESULT_SHOWUSAGE;
2696
2697         if (!agi->speech) {
2698                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2699                 return RESULT_SUCCESS;
2700         }
2701
2702         if (ast_speech_grammar_load(agi->speech, argv[3], argv[4]))
2703                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2704         else
2705                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2706
2707         return RESULT_SUCCESS;
2708 }
2709
2710 static int handle_speechunloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2711 {
2712         if (argc != 4)
2713                 return RESULT_SHOWUSAGE;
2714
2715         if (!agi->speech) {
2716                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2717                 return RESULT_SUCCESS;
2718         }
2719
2720         if (ast_speech_grammar_unload(agi->speech, argv[3]))
2721                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2722         else
2723                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2724
2725         return RESULT_SUCCESS;
2726 }
2727
2728 static int handle_speechactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2729 {
2730         if (argc != 4)
2731                 return RESULT_SHOWUSAGE;
2732
2733         if (!agi->speech) {
2734                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2735                 return RESULT_SUCCESS;
2736         }
2737
2738         if (ast_speech_grammar_activate(agi->speech, argv[3]))
2739                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2740         else
2741                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2742
2743         return RESULT_SUCCESS;
2744 }
2745
2746 static int handle_speechdeactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2747 {
2748         if (argc != 4)
2749                 return RESULT_SHOWUSAGE;
2750
2751         if (!agi->speech) {
2752                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2753                 return RESULT_SUCCESS;
2754         }
2755
2756         if (ast_speech_grammar_deactivate(agi->speech, argv[3]))
2757                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2758         else
2759                 ast_agi_send(agi->fd, chan, "200 result=1\n");
2760
2761         return RESULT_SUCCESS;
2762 }
2763
2764 static int speech_streamfile(struct ast_channel *chan, const char *filename, const char *preflang, int offset)
2765 {
2766         struct ast_filestream *fs = NULL;
2767
2768         if (!(fs = ast_openstream(chan, filename, preflang)))
2769                 return -1;
2770
2771         if (offset)
2772                 ast_seekstream(fs, offset, SEEK_SET);
2773
2774         if (ast_applystream(chan, fs))
2775                 return -1;
2776
2777         if (ast_playstream(fs))
2778                 return -1;
2779
2780         return 0;
2781 }
2782
2783 static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
2784 {
2785         struct ast_speech *speech = agi->speech;
2786         const char *prompt;
2787         char dtmf = 0, tmp[4096] = "", *buf = tmp;
2788         int timeout = 0, offset = 0, old_read_format = 0, res = 0, i = 0;
2789         long current_offset = 0;
2790         const char *reason = NULL;
2791         struct ast_frame *fr = NULL;
2792         struct ast_speech_result *result = NULL;
2793         size_t left = sizeof(tmp);
2794         time_t start = 0, current;
2795
2796         if (argc < 4)
2797                 return RESULT_SHOWUSAGE;
2798
2799         if (!speech) {
2800                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2801                 return RESULT_SUCCESS;
2802         }
2803
2804         prompt = argv[2];
2805         timeout = atoi(argv[3]);
2806
2807         /* If offset is specified then convert from text to integer */
2808         if (argc == 5)
2809                 offset = atoi(argv[4]);
2810
2811         /* We want frames coming in signed linear */
2812         old_read_format = chan->readformat;
2813         if (ast_set_read_format(chan, AST_FORMAT_SLINEAR)) {
2814                 ast_agi_send(agi->fd, chan, "200 result=0\n");
2815                 return RESULT_SUCCESS;
2816         }
2817
2818         /* Setup speech structure */
2819         if (speech->state == AST_SPEECH_STATE_NOT_READY || speech->state == AST_SPEECH_STATE_DONE) {
2820                 ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
2821                 ast_speech_start(speech);
2822         }
2823
2824         /* Start playing prompt */
2825         speech_streamfile(chan, prompt, chan->language, offset);
2826
2827         /* Go into loop reading in frames, passing to speech thingy, checking for hangup, all that jazz */
2828         while (ast_strlen_zero(reason)) {
2829                 /* Run scheduled items */
2830                 ast_sched_runq(chan->sched);
2831
2832                 /* See maximum time of waiting */
2833                 if ((res = ast_sched_wait(chan->sched)) < 0)
2834                         res = 1000;
2835
2836                 /* Wait for frame */
2837                 if (ast_waitfor(chan, res) > 0) {
2838                         if (!(fr = ast_read(chan))) {
2839                                 reason = "hangup";
2840                                 break;
2841                         }
2842                 }
2843
2844                 /* Perform timeout check */
2845                 if ((timeout > 0) && (start > 0)) {
2846                         time(&current);
2847                         if ((current - start) >= timeout) {
2848                                 reason = "timeout";
2849                                 if (fr)
2850                                         ast_frfree(fr);
2851                                 break;
2852                         }
2853                 }
2854
2855                 /* Check the speech structure for any changes */
2856                 ast_mutex_lock(&speech->lock);
2857
2858                 /* See if we need to quiet the audio stream playback */
2859                 if (ast_test_flag(speech, AST_SPEECH_QUIET) && chan->stream) {
2860                         current_offset = ast_tellstream(chan->stream);
2861                         ast_stopstream(chan);
2862                         ast_clear_flag(speech, AST_SPEECH_QUIET);
2863                 }
2864
2865                 /* Check each state */
2866                 switch (speech->state) {
2867                 case AST_SPEECH_STATE_READY:
2868                         /* If the stream is done, start timeout calculation */
2869                         if ((timeout > 0) && start == 0 && ((!chan->stream) || (chan->streamid == -1 && chan->timingfunc == NULL))) {
2870                                 ast_stopstream(chan);
2871                                 time(&start);
2872                         }
2873                         /* Write audio frame data into speech engine if possible */
2874                         if (fr && fr->frametype == AST_FRAME_VOICE)
2875                                 ast_speech_write(speech, fr->data.ptr, fr->datalen);
2876                         break;
2877                 case AST_SPEECH_STATE_WAIT:
2878                         /* Cue waiting sound if not already playing */
2879                         if ((!chan->stream) || (chan->streamid == -1 && chan->timingfunc == NULL)) {
2880                                 ast_stopstream(chan);
2881                                 /* If a processing sound exists, or is not none - play it */
2882                                 if (!ast_strlen_zero(speech->processing_sound) && strcasecmp(speech->processing_sound, "none"))
2883                                         speech_streamfile(chan, speech->processing_sound, chan->language, 0);
2884                         }
2885                         break;
2886                 case AST_SPEECH_STATE_DONE:
2887                         /* Get the results */
2888                         speech->results = ast_speech_results_get(speech);
2889                         /* Change state to not ready */
2890                         ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
2891                         reason = "speech";
2892                         break;
2893                 default:
2894                         break;
2895                 }
2896                 ast_mutex_unlock(&speech->lock);
2897
2898                 /* Check frame for DTMF or hangup */
2899                 if (fr) {
2900                         if (fr->frametype == AST_FRAME_DTMF) {
2901                                 reason = "dtmf";
2902                                 dtmf = fr->subclass.integer;
2903                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_HANGUP) {
2904                                 reason = "hangup";
2905                         }
2906                         ast_frfree(fr);
2907                 }
2908         }
2909
2910         if (!strcasecmp(reason, "speech")) {
2911                 /* Build string containing speech results */
2912                 for (result = speech->results; result; result = AST_LIST_NEXT(result, list)) {
2913                         /* Build result string */
2914                         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);
2915                         /* Increment result count */
2916                         i++;
2917                 }
2918                 /* Print out */
2919                 ast_agi_send(agi->fd, chan, "200 result=1 (speech) endpos=%ld results=%d %s\n", current_offset, i, tmp);
2920         } else if (!strcasecmp(reason, "dtmf")) {
2921                 ast_agi_send(agi->fd, chan, "200 result=1 (digit) digit=%c endpos=%ld\n", dtmf, current_offset);
2922         } else if (!strcasecmp(reason, "hangup") || !strcasecmp(reason, "timeout")) {
2923                 ast_agi_send(agi->fd, chan, "200 result=1 (%s) endpos=%ld\n", reason, current_offset);
2924         } else {
2925                 ast_agi_send(agi->fd, chan, "200 result=0 endpos=%ld\n", current_offset);
2926         }
2927
2928         return RESULT_SUCCESS;
2929 }
2930
2931 /*!
2932  * \brief AGI commands list
2933  */
2934 static struct agi_command commands[] = {
2935         { { "answer", NULL }, handle_answer, NULL, NULL, 0 },
2936         { { "asyncagi", "break", NULL }, handle_asyncagi_break, NULL, NULL, 1 },
2937         { { "channel", "status", NULL }, handle_channelstatus, NULL, NULL, 0 },
2938         { { "database", "del", NULL }, handle_dbdel, NULL, NULL, 1 },
2939         { { "database", "deltree", NULL }, handle_dbdeltree, NULL, NULL, 1 },
2940         { { "database", "get", NULL }, handle_dbget, NULL, NULL, 1 },
2941         { { "database", "put", NULL }, handle_dbput, NULL, NULL, 1 },
2942         { { "exec", NULL }, handle_exec, NULL, NULL, 1 },
2943         { { "get", "data", NULL }, handle_getdata, NULL, NULL, 0 },
2944         { { "get", "full", "variable", NULL }, handle_getvariablefull, NULL, NULL, 1 },
2945         { { "get", "option", NULL }, handle_getoption, NULL, NULL, 0 },
2946         { { "get", "variable", NULL }, handle_getvariable, NULL, NULL, 1 },
2947         { { "hangup", NULL }, handle_hangup, NULL, NULL, 0 },
2948         { { "noop", NULL }, handle_noop, NULL, NULL, 1 },
2949         { { "receive", "char", NULL }, handle_recvchar, NULL, NULL, 0 },
2950         { { "receive", "text", NULL }, handle_recvtext, NULL, NULL, 0 },
2951         { { "record", "file", NULL }, handle_recordfile, NULL, NULL, 0 }, 
2952         { { "say", "alpha", NULL }, handle_sayalpha, NULL, NULL, 0},
2953         { { "say", "digits", NULL }, handle_saydigits, NULL, NULL, 0 },
2954         { { "say", "number", NULL }, handle_saynumber, NULL, NULL, 0 },
2955         { { "say", "phonetic", NULL }, handle_sayphonetic, NULL, NULL, 0}, 
2956         { { "say", "date", NULL }, handle_saydate, NULL, NULL, 0}, 
2957         { { "say", "time", NULL }, handle_saytime, NULL, NULL, 0}, 
2958         { { "say", "datetime", NULL }, handle_saydatetime, NULL, NULL, 0},
2959         { { "send", "image", NULL }, handle_sendimage, NULL, NULL, 0}, 
2960         { { "send", "text", NULL }, handle_sendtext, NULL, NULL, 0},
2961         { { "set", "autohangup", NULL }, handle_autohangup, NULL, NULL, 0},
2962         { { "set", "callerid", NULL }, handle_setcallerid, NULL, NULL, 0},
2963         { { "set", "context", NULL }, handle_setcontext, NULL, NULL, 0},
2964         { { "set", "extension", NULL }, handle_setextension, NULL, NULL, 0},
2965         { { "set", "music", NULL }, handle_setmusic, NULL, NULL, 0 },
2966         { { "set", "priority", NULL }, handle_setpriority, NULL, NULL, 0 },
2967         { { "set", "variable", NULL }, handle_setvariable, NULL, NULL, 1 },
2968         { { "stream", "file", NULL }, handle_streamfile, NULL, NULL, 0 },
2969         { { "control", "stream", "file", NULL }, handle_controlstreamfile, NULL, NULL, 0 },
2970         { { "tdd", "mode", NULL }, handle_tddmode, NULL, NULL, 0 },
2971         { { "verbose", NULL }, handle_verbose, NULL, NULL, 1 },
2972         { { "wait", "for", "digit", NULL }, handle_waitfordigit, NULL, NULL, 0 },
2973         { { "speech", "create", NULL }, handle_speechcreate, NULL, NULL, 0 },
2974         { { "speech", "set", NULL }, handle_speechset, NULL, NULL, 0 },
2975         { { "speech", "destroy", NULL }, handle_speechdestroy, NULL, NULL, 1 },
2976         { { "speech", "load", "grammar", NULL }, handle_speechloadgrammar, NULL, NULL, 0 },
2977         { { "speech", "unload", "grammar", NULL }, handle_speechunloadgrammar, NULL, NULL, 1 },
2978         { { "speech", "activate", "grammar", NULL }, handle_speechactivategrammar, NULL, NULL, 0 },
2979         { { "speech", "deactivate", "grammar", NULL }, handle_speechdeactivategrammar, NULL, NULL, 0 },
2980         { { "speech", "recognize", NULL }, handle_speechrecognize, NULL, NULL, 0 },
2981 };
2982
2983 static AST_RWLIST_HEAD_STATIC(agi_commands, agi_command);
2984
2985 static char *help_workhorse(int fd, const char * const match[])
2986 {
2987         char fullcmd[MAX_CMD_LEN], matchstr[MAX_CMD_LEN];
2988         struct agi_command *e;
2989
2990         if (match)
2991                 ast_join(matchstr, sizeof(matchstr), match);
2992
2993         ast_cli(fd, "%5.5s %30.30s   %s\n","Dead","Command","Description");
2994         AST_RWLIST_RDLOCK(&agi_commands);
2995         AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
2996                 if (!e->cmda[0])
2997                         break;
2998                 /* Hide commands that start with '_' */
2999                 if ((e->cmda[0])[0] == '_')
3000                         continue;
3001                 ast_join(fullcmd, sizeof(fullcmd), e->cmda);
3002                 if (match && strncasecmp(matchstr, fullcmd, strlen(matchstr)))
3003                         continue;
3004                 ast_cli(fd, "%5.5s %30.30s   %s\n", e->dead ? "Yes" : "No" , fullcmd, S_OR(e->summary, "Not available"));
3005         }
3006         AST_RWLIST_UNLOCK(&agi_commands);
3007
3008         return CLI_SUCCESS;
3009 }
3010
3011 int AST_OPTIONAL_API_NAME(ast_agi_register)(struct ast_module *mod, agi_command *cmd)
3012 {
3013         char fullcmd[MAX_CMD_LEN];
3014
3015         ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
3016
3017         if (!find_command(cmd->cmda, 1)) {
3018                 *((enum ast_doc_src *) &cmd->docsrc) = AST_STATIC_DOC;
3019                 if (ast_strlen_zero(cmd->summary) && ast_strlen_zero(cmd->usage)) {
3020 #ifdef AST_XML_DOCS
3021                         *((char **) &cmd->summary) = ast_xmldoc_build_synopsis("agi", fullcmd);
3022                         *((char **) &cmd->usage) = ast_xmldoc_build_description("agi", fullcmd);
3023                         *((char **) &cmd->syntax) = ast_xmldoc_build_syntax("agi", fullcmd);
3024                         *((char **) &cmd->seealso) = ast_xmldoc_build_seealso("agi", fullcmd);
3025                         *((enum ast_doc_src *) &cmd->docsrc) = AST_XML_DOC;
3026 #elif (!defined(HAVE_NULLSAFE_PRINTF))
3027                         *((char **) &cmd->summary) = ast_strdup("");
3028                         *((char **) &cmd->usage) = ast_strdup("");
3029                         *((char **) &cmd->syntax) = ast_strdup("");
3030                         *((char **) &cmd->seealso) = ast_strdup("");
3031 #endif
3032                 }
3033
3034                 cmd->mod = mod;
3035                 AST_RWLIST_WRLOCK(&agi_commands);
3036                 AST_LIST_INSERT_TAIL(&agi_commands, cmd, list);
3037                 AST_RWLIST_UNLOCK(&agi_commands);
3038                 if (mod != ast_module_info->self)
3039                         ast_module_ref(ast_module_info->self);
3040                 ast_verb(2, "AGI Command '%s' registered\n",fullcmd);
3041                 return 1;
3042         } else {
3043                 ast_log(LOG_WARNING, "Command already registered!\n");
3044                 return 0;
3045         }
3046 }
3047
3048 int AST_OPTIONAL_API_NAME(ast_agi_unregister)(struct ast_module *mod, agi_command *cmd)
3049 {
3050         struct agi_command *e;
3051         int unregistered = 0;
3052         char fullcmd[MAX_CMD_LEN];
3053
3054         ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
3055
3056         AST_RWLIST_WRLOCK(&agi_commands);
3057         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&agi_commands, e, list) {
3058                 if (cmd == e) {
3059                         AST_RWLIST_REMOVE_CURRENT(list);
3060                         if (mod != ast_module_info->self)
3061                                 ast_module_unref(ast_module_info->self);
3062 #ifdef AST_XML_DOCS
3063                         if (e->docsrc == AST_XML_DOC) {
3064                                 ast_free((char *) e->summary);
3065                                 ast_free((char *) e->usage);
3066                                 ast_free((char *) e->syntax);
3067                                 ast_free((char *) e->seealso);
3068                                 *((char **) &e->summary) = NULL;
3069                                 *((char **) &e->usage) = NULL;
3070                                 *((char **) &e->syntax) = NULL;
3071                                 *((char **) &e->seealso) = NULL;
3072                         }
3073 #endif
3074                         unregistered=1;
3075                         break;
3076                 }
3077         }
3078         AST_RWLIST_TRAVERSE_SAFE_END;
3079         AST_RWLIST_UNLOCK(&agi_commands);
3080         if (unregistered)
3081                 ast_verb(2, "AGI Command '%s' unregistered\n",fullcmd);
3082         else
3083                 ast_log(LOG_WARNING, "Unable to unregister command: '%s'!\n",fullcmd);
3084         return unregistered;
3085 }
3086
3087 int AST_OPTIONAL_API_NAME(ast_agi_register_multiple)(struct ast_module *mod, struct agi_command *cmd, unsigned int len)
3088 {
3089         unsigned int i, x = 0;
3090
3091         for (i = 0; i < len; i++) {
3092                 if (ast_agi_register(mod, cmd + i) == 1) {
3093                         x++;
3094                         continue;
3095                 }
3096
3097                 /* registration failed, unregister everything
3098                    that had been registered up to that point
3099                 */
3100                 for (; x > 0; x--) {
3101                         /* we are intentionally ignoring the
3102                            result of ast_agi_unregister() here,
3103                            but it should be safe to do so since
3104                            we just registered these commands and
3105                            the only possible way for unregistration
3106                            to fail is if the command is not
3107                            registered
3108                         */
3109                         (void) ast_agi_unregister(mod, cmd + x - 1);
3110                 }
3111                 return -1;
3112         }
3113
3114         return 0;
3115 }
3116
3117 int AST_OPTIONAL_API_NAME(ast_agi_unregister_multiple)(struct ast_module *mod, struct agi_command *cmd, unsigned int len)
3118 {
3119         unsigned int i;
3120         int res = 0;
3121
3122         for (i = 0; i < len; i++) {
3123                 /* remember whether any of the unregistration
3124                    attempts failed... there is no recourse if
3125                    any of them do
3126                 */
3127                 res |= ast_agi_unregister(mod, cmd + i);
3128         }
3129
3130         return res;
3131 }
3132
3133 static agi_command *find_command(const char * const cmds[], int exact)
3134 {
3135         int y, match;
3136         struct agi_command *e;
3137
3138         AST_RWLIST_RDLOCK(&agi_commands);
3139         AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
3140                 if (!e->cmda[0])
3141                         break;
3142                 /* start optimistic */
3143                 match = 1;
3144                 for (y = 0; match && cmds[y]; y++) {
3145                         /* If there are no more words in the command (and we're looking for
3146                            an exact match) or there is a difference between the two words,
3147                            then this is not a match */
3148                         if (!e->cmda[y] && !exact)
3149                                 break;
3150                         /* don't segfault if the next part of a command doesn't exist */
3151                         if (!e->cmda[y]) {
3152                                 AST_RWLIST_UNLOCK(&agi_commands);
3153                                 return NULL;
3154                         }
3155                         if (strcasecmp(e->cmda[y], cmds[y]))
3156                                 match = 0;
3157                 }
3158                 /* If more words are needed to complete the command then this is not
3159                    a candidate (unless we're looking for a really inexact answer  */
3160                 if ((exact > -1) && e->cmda[y])
3161                         match = 0;
3162                 if (match) {
3163                         AST_RWLIST_UNLOCK(&agi_commands);
3164                         return e;
3165                 }
3166         }
3167         AST_RWLIST_UNLOCK(&agi_commands);
3168         return NULL;
3169 }
3170
3171 static int parse_args(char *s, int *max, const char *argv[])
3172 {
3173         int x = 0, quoted = 0, escaped = 0, whitespace = 1;
3174         char *cur;
3175
3176         cur = s;
3177         while(*s) {
3178                 switch(*s) {
3179                 case '"':
3180                         /* If it's escaped, put a literal quote */
3181                         if (escaped)
3182                                 goto normal;
3183                         else
3184                                 quoted = !quoted;
3185                         if (quoted && whitespace) {
3186                                 /* If we're starting a quote, coming off white space start a new word, too */
3187                                 argv[x++] = cur;
3188                                 whitespace=0;
3189                         }
3190                         escaped = 0;
3191                 break;
3192                 case ' ':
3193                 case '\t':
3194                         if (!quoted && !escaped) {
3195                                 /* If we're not quoted, mark this as whitespace, and
3196                                    end the previous argument */
3197                                 whitespace = 1;
3198                                 *(cur++) = '\0';
3199                         } else
3200                                 /* Otherwise, just treat it as anything else */
3201                                 goto normal;
3202                         break;
3203                 case '\\':
3204                         /* If we're escaped, print a literal, otherwise enable escaping */
3205                         if (escaped) {
3206                                 goto normal;
3207                         } else {
3208                                 escaped=1;
3209                         }
3210                         break;
3211                 default:
3212 normal:
3213                         if (whitespace) {
3214                                 if (x >= MAX_ARGS -1) {
3215                                         ast_log(LOG_WARNING, "Too many arguments, truncating\n");
3216                                         break;
3217                                 }
3218                                 /* Coming off of whitespace, start the next argument */
3219                                 argv[x++] = cur;
3220                                 whitespace=0;
3221                         }
3222                         *(cur++) = *s;
3223                         escaped=0;
3224                 }
3225                 s++;
3226         }
3227         /* Null terminate */
3228         *(cur++) = '\0';
3229         argv[x] = NULL;
3230         *max = x;
3231         return 0;
3232 }
3233
3234 static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int dead)
3235 {
3236         const char *argv[MAX_ARGS];
3237         int argc = MAX_ARGS, res;
3238         agi_command *c;
3239         const char *ami_res = "Unknown Result";
3240         char *ami_cmd = ast_strdupa(buf);
3241         int command_id = ast_random(), resultcode = 200;
3242
3243         manager_event(EVENT_FLAG_AGI, "AGIExec",
3244                         "SubEvent: Start\r\n"
3245                         "Channel: %s\r\n"
3246                         "CommandId: %d\r\n"
3247                         "Command: %s\r\n", chan->name, command_id, ami_cmd);
3248         parse_args(buf, &argc, argv);
3249         if ((c = find_command(argv, 0)) && (!dead || (dead && c->dead))) {
3250                 /* if this command wasnt registered by res_agi, be sure to usecount
3251                 the module we are using */
3252                 if (c->mod != ast_module_info->self)
3253                         ast_module_ref(c->mod);
3254                 /* If the AGI command being executed is an actual application (using agi exec)
3255                 the app field will be updated in pbx_exec via handle_exec */
3256                 if (chan->cdr && !ast_check_hangup(chan) && strcasecmp(argv[0], "EXEC"))
3257                         ast_cdr_setapp(chan->cdr, "AGI", buf);
3258
3259                 res = c->handler(chan, agi, argc, argv);
3260                 if (c->mod != ast_module_info->self)
3261                         ast_module_unref(c->mod);
3262                 switch (res) {
3263                 case RESULT_SHOWUSAGE: ami_res = "Usage"; resultcode = 520; break;
3264                 case RESULT_FAILURE: ami_res = "Failure"; resultcode = -1; break;
3265                 case RESULT_SUCCESS: ami_res = "Success"; resultcode = 200; break;
3266                 }
3267                 manager_event(EVENT_FLAG_AGI, "AGIExec",
3268                                 "SubEvent: End\r\n"
3269                                 "Channel: %s\r\n"
3270                                 "CommandId: %d\r\n"
3271                                 "Command: %s\r\n"
3272                                 "ResultCode: %d\r\n"
3273                                 "Result: %s\r\n", chan->name, command_id, ami_cmd, resultcode, ami_res);
3274                 switch(res) {
3275                 case RESULT_SHOWUSAGE:
3276                         if (ast_strlen_zero(c->usage)) {
3277                                 ast_agi_send(agi->fd, chan, "520 Invalid command syntax.  Proper usage not available.\n");
3278                         } else {
3279                                 ast_agi_send(agi->fd, chan, "520-Invalid command syntax.  Proper usage follows:\n");
3280                                 ast_agi_send(agi->fd, chan, "%s", c->usage);
3281                                 ast_agi_send(agi->fd, chan, "520 End of proper usage.\n");
3282                         }
3283                         break;
3284                 case RESULT_FAILURE:
3285                         /* They've already given the failure.  We've been hung up on so handle this
3286                            appropriately */
3287                         return -1;
3288                 }
3289         } else if ((c = find_command(argv, 0))) {
3290                 ast_agi_send(agi->fd, chan, "511 Command Not Permitted on a dead channel\n");
3291                 manager_event(EVENT_FLAG_AGI, "AGIExec",
3292                                 "SubEvent: End\r\n"
3293                                 "Channel: %s\r\n"
3294                                 "CommandId: %d\r\n"
3295                                 "Command: %s\r\n"
3296                                 "ResultCode: 511\r\n"
3297                                 "Result: Command not permitted on a dead channel\r\n", chan->name, command_id, ami_cmd);
3298         } else {
3299                 ast_agi_send(agi->fd, chan, "510 Invalid or unknown command\n");
3300                 manager_event(EVENT_FLAG_AGI, "AGIExec",
3301                                 "SubEvent: End\r\n"
3302                                 "Channel: %s\r\n"
3303                                 "CommandId: %d\r\n"
3304                                 "Command: %s\r\n"
3305                                 "ResultCode: 510\r\n"
3306                                 "Result: Invalid or unknown command\r\n", chan->name, command_id, ami_cmd);
3307         }
3308         return 0;
3309 }
3310 static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid, int *status, int dead, int argc, char *argv[])
3311 {
3312         struct ast_channel *c;
3313         int outfd, ms, needhup = 0;
3314         enum agi_result returnstatus = AGI_RESULT_SUCCESS;
3315         struct ast_frame *f;
3316         char buf[AGI_BUF_LEN];
3317         char *res = NULL;
3318         FILE *readf;
3319         /* how many times we'll retry if ast_waitfor_nandfs will return without either
3320           channel or file descriptor in case select is interrupted by a system call (EINTR) */
3321         int retry = AGI_NANDFS_RETRY;
3322         int send_sighup;
3323         const char *sighup_str;
3324         
3325         ast_channel_lock(chan);
3326         sighup_str = pbx_builtin_getvar_helper(chan, "AGISIGHUP");
3327         send_sighup = ast_strlen_zero(sighup_str) || !ast_false(sighup_str);
3328         ast_channel_unlock(chan);
3329
3330         if (!(readf = fdopen(agi->ctrl, "r"))) {
3331                 ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
3332                 if (send_sighup && pid > -1)
3333                         kill(pid, SIGHUP);
3334                 close(agi->ctrl);
3335                 return AGI_RESULT_FAILURE;
3336         }
3337         
3338         setlinebuf(readf);
3339         setup_env(chan, request, agi->fd, (agi->audio > -1), argc, argv);
3340         for (;;) {
3341                 if (needhup) {
3342                         needhup = 0;
3343                         dead = 1;
3344                         if (send_sighup) {
3345                                 if (pid > -1) {
3346                                         kill(pid, SIGHUP);
3347                                 } else if (agi->fast) {
3348                                         send(agi->ctrl, "HANGUP\n", 7, MSG_OOB);
3349                                 }
3350                         }
3351                 }
3352                 ms = -1;
3353                 c = ast_waitfor_nandfds(&chan, dead ? 0 : 1, &agi->ctrl, 1, NULL, &outfd, &ms);
3354                 if (c) {
3355                         retry = AGI_NANDFS_RETRY;
3356                         /* Idle the channel until we get a command */
3357                         f = ast_read(c);
3358                         if (!f) {
3359                                 ast_debug(1, "%s hungup\n", chan->name);
3360                                 returnstatus = AGI_RESULT_HANGUP;
3361                                 needhup = 1;
3362                                 continue;
3363                         } else {
3364                                 /* If it's voice, write it to the audio pipe */
3365                                 if ((agi->audio > -1) && (f->frametype == AST_FRAME_VOICE)) {
3366                                         /* Write, ignoring errors */
3367                                         if (write(agi->audio, f->data.ptr, f->datalen) < 0) {
3368                                         }
3369                                 }
3370                                 ast_frfree(f);
3371                         }
3372                 } else if (outfd > -1) {
3373                         size_t len = sizeof(buf);
3374                         size_t buflen = 0;
3375
3376                         retry = AGI_NANDFS_RETRY;
3377                         buf[0] = '\0';
3378
3379                         while (buflen < (len - 1)) {
3380                                 res = fgets(buf + buflen, len, readf);
3381                                 if (feof(readf))
3382                                         break;
3383                                 if (ferror(readf) && ((errno != EINTR) && (errno != EAGAIN)))
3384                                         break;
3385                                 if (res != NULL && !agi->fast)
3386                                         break;
3387                                 buflen = strlen(buf);
3388                                 if (buflen && buf[buflen - 1] == '\n')
3389                                         break;
3390                                 len -= buflen;
3391                                 if (agidebug)
3392                                         ast_verbose( "AGI Rx << temp buffer %s - errno %s\n", buf, strerror(errno));
3393                         }
3394
3395                         if (!buf[0]) {
3396                                 /* Program terminated */
3397                                 if (returnstatus) {
3398                                         returnstatus = -1;
3399                                 }
3400                                 ast_verb(3, "<%s>AGI Script %s completed, returning %d\n", chan->name, request, returnstatus);
3401                                 if (pid > 0)
3402                                         waitpid(pid, status, 0);
3403                                 /* No need to kill the pid anymore, since they closed us */
3404                                 pid = -1;
3405                                 break;
3406                         }
3407
3408                         /* Special case for inability to execute child process */
3409                         if (*buf && strncasecmp(buf, "failure", 7) == 0) {
3410                                 returnstatus = AGI_RESULT_FAILURE;
3411                                 break;
3412                         }
3413
3414                         /* get rid of trailing newline, if any */
3415                         if (*buf && buf[strlen(buf) - 1] == '\n')
3416                                 buf[strlen(buf) - 1] = 0;
3417                         if (agidebug)
3418                                 ast_verbose("<%s>AGI Rx << %s\n", chan->name, buf);
3419                         returnstatus |= agi_handle_command(chan, agi, buf, dead);
3420                         /* If the handle_command returns -1, we need to stop */
3421                         if (returnstatus < 0) {
3422                                 needhup = 1;
3423                                 continue;
3424                         }
3425                 } else {
3426                         if (--retry <= 0) {
3427                                 ast_log(LOG_WARNING, "No channel, no fd?\n");
3428                                 returnstatus = AGI_RESULT_FAILURE;
3429                                 break;
3430                         }
3431                 }
3432         }
3433         if (agi->speech) {
3434                 ast_speech_destroy(agi->speech);
3435         }
3436         /* Notify process */
3437         if (send_sighup) {
3438                 if (pid > -1) {
3439                         if (kill(pid, SIGHUP)) {
3440                                 ast_log(LOG_WARNING, "unable to send SIGHUP to AGI process %d: %s\n", pid, strerror(errno));
3441                         } else { /* Give the process a chance to die */
3442                                 usleep(1);
3443                         }
3444                         waitpid(pid, status, WNOHANG);
3445                 } else if (agi->fast) {
3446                         send(agi->ctrl, "HANGUP\n", 7, MSG_OOB);
3447                 }
3448         }
3449         fclose(readf);
3450         return returnstatus;
3451 }
3452
3453 static char *handle_cli_agi_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3454 {
3455         struct agi_command *command;
3456         char fullcmd[MAX_CMD_LEN];
3457         int error = 0;
3458
3459         switch (cmd) {
3460         case CLI_INIT:
3461                 e->command = "agi show commands [topic]";
3462                 e->usage =
3463                         "Usage: agi show commands [topic] <topic>\n"
3464                         "       When called with a topic as an argument, displays usage\n"