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