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