Migrate a large number of AMI events over to Stasis-Core
[asterisk/asterisk.git] / apps / app_chanspy.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2005 Anthony Minessale II (anthmct@yahoo.com)
5  * Copyright (C) 2005 - 2008, Digium, Inc.
6  *
7  * A license has been granted to Digium (via disclaimer) for the use of
8  * this code.
9  *
10  * See http://www.asterisk.org for more information about
11  * the Asterisk project. Please do not directly contact
12  * any of the maintainers of this project for assistance;
13  * the project provides a web site, mailing lists and IRC
14  * channels for your use.
15  *
16  * This program is free software, distributed under the terms of
17  * the GNU General Public License Version 2. See the LICENSE file
18  * at the top of the source tree.
19  */
20
21 /*! \file
22  *
23  * \brief ChanSpy: Listen in on any channel.
24  *
25  * \author Anthony Minessale II <anthmct@yahoo.com>
26  * \author Joshua Colp <jcolp@digium.com>
27  * \author Russell Bryant <russell@digium.com>
28  *
29  * \ingroup applications
30  */
31
32 /*** MODULEINFO
33         <support_level>core</support_level>
34  ***/
35
36 #include "asterisk.h"
37
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39
40 #include <ctype.h>
41 #include <errno.h>
42
43 #include "asterisk/paths.h" /* use ast_config_AST_MONITOR_DIR */
44 #include "asterisk/file.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/audiohook.h"
47 #include "asterisk/features.h"
48 #include "asterisk/app.h"
49 #include "asterisk/utils.h"
50 #include "asterisk/say.h"
51 #include "asterisk/pbx.h"
52 #include "asterisk/translate.h"
53 #include "asterisk/manager.h"
54 #include "asterisk/module.h"
55 #include "asterisk/lock.h"
56 #include "asterisk/options.h"
57 #include "asterisk/autochan.h"
58 #include "asterisk/stasis_channels.h"
59 #include "asterisk/json.h"
60
61 #define AST_NAME_STRLEN 256
62 #define NUM_SPYGROUPS 128
63
64 /*** DOCUMENTATION
65         <application name="ChanSpy" language="en_US">
66                 <synopsis>
67                         Listen to a channel, and optionally whisper into it.
68                 </synopsis>
69                 <syntax>
70                         <parameter name="chanprefix" />
71                         <parameter name="options">
72                                 <optionlist>
73                                         <option name="b">
74                                                 <para>Only spy on channels involved in a bridged call.</para>
75                                         </option>
76                                         <option name="B">
77                                                 <para>Instead of whispering on a single channel barge in on both
78                                                 channels involved in the call.</para>
79                                         </option>
80                                         <option name="c">
81                                                 <argument name="digit" required="true">
82                                                         <para>Specify a DTMF digit that can be used to spy on the next available channel.</para>
83                                                 </argument>
84                                         </option>
85                                         <option name="d">
86                                                 <para>Override the typical numeric DTMF functionality and instead
87                                                 use DTMF to switch between spy modes.</para>
88                                                 <enumlist>
89                                                         <enum name="4">
90                                                                 <para>spy mode</para>
91                                                         </enum>
92                                                         <enum name="5">
93                                                                 <para>whisper mode</para>
94                                                         </enum>
95                                                         <enum name="6">
96                                                                 <para>barge mode</para>
97                                                         </enum>
98                                                 </enumlist>
99                                         </option>
100                                         <option name="e">
101                                                 <argument name="ext" required="true" />
102                                                 <para>Enable <emphasis>enforced</emphasis> mode, so the spying channel can
103                                                 only monitor extensions whose name is in the <replaceable>ext</replaceable> : delimited 
104                                                 list.</para>
105                                         </option>
106                                         <option name="E">
107                                                 <para>Exit when the spied-on channel hangs up.</para>
108                                         </option>
109                                         <option name="g">
110                                                 <argument name="grp" required="true">
111                                                         <para>Only spy on channels in which one or more of the groups
112                                                         listed in <replaceable>grp</replaceable> matches one or more groups from the
113                                                         <variable>SPYGROUP</variable> variable set on the channel to be spied upon.</para>
114                                                 </argument>
115                                                 <note><para>both <replaceable>grp</replaceable> and <variable>SPYGROUP</variable> can contain 
116                                                 either a single group or a colon-delimited list of groups, such
117                                                 as <literal>sales:support:accounting</literal>.</para></note>
118                                         </option>
119                                         <option name="n" argsep="@">
120                                                 <para>Say the name of the person being spied on if that person has recorded
121                                                 his/her name. If a context is specified, then that voicemail context will
122                                                 be searched when retrieving the name, otherwise the <literal>default</literal> context
123                                                 be used when searching for the name (i.e. if SIP/1000 is the channel being
124                                                 spied on and no mailbox is specified, then <literal>1000</literal> will be used when searching
125                                                 for the name).</para>
126                                                 <argument name="mailbox" />
127                                                 <argument name="context" />
128                                         </option>
129                                         <option name="o">
130                                                 <para>Only listen to audio coming from this channel.</para>
131                                         </option>
132                                         <option name="q">
133                                                 <para>Don't play a beep when beginning to spy on a channel, or speak the
134                                                 selected channel name.</para>
135                                         </option>
136                                         <option name="r">
137                                                 <para>Record the session to the monitor spool directory. An optional base for the filename 
138                                                 may be specified. The default is <literal>chanspy</literal>.</para>
139                                                 <argument name="basename" />
140                                         </option>
141                                         <option name="s">
142                                                 <para>Skip the playback of the channel type (i.e. SIP, IAX, etc) when
143                                                 speaking the selected channel name.</para>
144                                         </option>
145                                         <option name="S">
146                                                 <para>Stop when no more channels are left to spy on.</para>
147                                         </option>
148                                         <option name="v">
149                                                 <argument name="value" />
150                                                 <para>Adjust the initial volume in the range from <literal>-4</literal> 
151                                                 to <literal>4</literal>. A negative value refers to a quieter setting.</para>
152                                         </option>
153                                         <option name="w">
154                                                 <para>Enable <literal>whisper</literal> mode, so the spying channel can talk to
155                                                 the spied-on channel.</para>
156                                         </option>
157                                         <option name="W">
158                                                 <para>Enable <literal>private whisper</literal> mode, so the spying channel can
159                                                 talk to the spied-on channel but cannot listen to that channel.</para>
160                                         </option>
161                                         <option name="x">
162                                                 <argument name="digit" required="true">
163                                                         <para>Specify a DTMF digit that can be used to exit the application.</para>
164                                                 </argument>
165                                         </option>
166                                         <option name="X">
167                                                 <para>Allow the user to exit ChanSpy to a valid single digit
168                                                 numeric extension in the current context or the context
169                                                 specified by the <variable>SPY_EXIT_CONTEXT</variable> channel variable. The
170                                                 name of the last channel that was spied on will be stored
171                                                 in the <variable>SPY_CHANNEL</variable> variable.</para>
172                                         </option>
173                                 </optionlist>           
174                         </parameter>
175                 </syntax>
176                 <description>
177                         <para>This application is used to listen to the audio from an Asterisk channel. This includes the audio 
178                         coming in and out of the channel being spied on. If the <literal>chanprefix</literal> parameter is specified,
179                         only channels beginning with this string will be spied upon.</para>
180                         <para>While spying, the following actions may be performed:</para>
181                         <para> - Dialing <literal>#</literal> cycles the volume level.</para>
182                         <para> - Dialing <literal>*</literal> will stop spying and look for another channel to spy on.</para>
183                         <para> - Dialing a series of digits followed by <literal>#</literal> builds a channel name to append
184                         to 'chanprefix'. For example, executing ChanSpy(Agent) and then dialing the digits '1234#' 
185                         while spying will begin spying on the channel 'Agent/1234'. Note that this feature will be overridden if the 'd' option
186                         is used</para>
187                         <note><para>The <replaceable>X</replaceable> option supersedes the three features above in that if a valid
188                         single digit extension exists in the correct context ChanSpy will exit to it.
189                         This also disables choosing a channel based on <literal>chanprefix</literal> and a digit sequence.</para></note>
190                 </description>
191                 <see-also>
192                         <ref type="application">ExtenSpy</ref>
193                         <ref type="managerEvent">ChanSpyStart</ref>
194                         <ref type="managerEvent">ChanSpyStop</ref>
195                 </see-also>
196         </application>
197         <application name="ExtenSpy" language="en_US">
198                 <synopsis>
199                         Listen to a channel, and optionally whisper into it.
200                 </synopsis>
201                 <syntax>
202                         <parameter name="exten" required="true" argsep="@">
203                                 <argument name="exten" required="true">
204                                         <para>Specify extension.</para>
205                                 </argument>
206                                 <argument name="context">
207                                         <para>Optionally specify a context, defaults to <literal>default</literal>.</para>
208                                 </argument>
209                         </parameter>
210                         <parameter name="options">
211                                 <optionlist>
212                                         <option name="b">
213                                                 <para>Only spy on channels involved in a bridged call.</para>
214                                         </option>
215                                         <option name="B">
216                                                 <para>Instead of whispering on a single channel barge in on both
217                                                 channels involved in the call.</para>
218                                         </option>
219                                         <option name="c">
220                                                 <argument name="digit" required="true">
221                                                         <para>Specify a DTMF digit that can be used to spy on the next available channel.</para>
222                                                 </argument>
223                                         </option>
224                                         <option name="d">
225                                                 <para>Override the typical numeric DTMF functionality and instead
226                                                 use DTMF to switch between spy modes.</para>
227                                                 <enumlist>
228                                                         <enum name="4">
229                                                                 <para>spy mode</para>
230                                                         </enum>
231                                                         <enum name="5">
232                                                                 <para>whisper mode</para>
233                                                         </enum>
234                                                         <enum name="6">
235                                                                 <para>barge mode</para>
236                                                         </enum>
237                                                 </enumlist>
238                                         </option>
239                                         <option name="e">
240                                                 <argument name="ext" required="true" />
241                                                 <para>Enable <emphasis>enforced</emphasis> mode, so the spying channel can
242                                                 only monitor extensions whose name is in the <replaceable>ext</replaceable> : delimited 
243                                                 list.</para>
244                                         </option>
245                                         <option name="E">
246                                                 <para>Exit when the spied-on channel hangs up.</para>
247                                         </option>
248                                         <option name="g">
249                                                 <argument name="grp" required="true">
250                                                         <para>Only spy on channels in which one or more of the groups
251                                                         listed in <replaceable>grp</replaceable> matches one or more groups from the
252                                                         <variable>SPYGROUP</variable> variable set on the channel to be spied upon.</para>
253                                                 </argument>
254                                                 <note><para>both <replaceable>grp</replaceable> and <variable>SPYGROUP</variable> can contain 
255                                                 either a single group or a colon-delimited list of groups, such
256                                                 as <literal>sales:support:accounting</literal>.</para></note>
257                                         </option>
258                                         <option name="n" argsep="@">
259                                                 <para>Say the name of the person being spied on if that person has recorded
260                                                 his/her name. If a context is specified, then that voicemail context will
261                                                 be searched when retrieving the name, otherwise the <literal>default</literal> context
262                                                 be used when searching for the name (i.e. if SIP/1000 is the channel being
263                                                 spied on and no mailbox is specified, then <literal>1000</literal> will be used when searching
264                                                 for the name).</para>
265                                                 <argument name="mailbox" />
266                                                 <argument name="context" />
267                                         </option>
268                                         <option name="o">
269                                                 <para>Only listen to audio coming from this channel.</para>
270                                         </option>
271                                         <option name="q">
272                                                 <para>Don't play a beep when beginning to spy on a channel, or speak the
273                                                 selected channel name.</para>
274                                         </option>
275                                         <option name="r">
276                                                 <para>Record the session to the monitor spool directory. An optional base for the filename 
277                                                 may be specified. The default is <literal>chanspy</literal>.</para>
278                                                 <argument name="basename" />
279                                         </option>
280                                         <option name="s">
281                                                 <para>Skip the playback of the channel type (i.e. SIP, IAX, etc) when
282                                                 speaking the selected channel name.</para>
283                                         </option>
284                                         <option name="S">
285                                                 <para>Stop when there are no more extensions left to spy on.</para>
286                                         </option>
287                                         <option name="v">
288                                                 <argument name="value" />
289                                                 <para>Adjust the initial volume in the range from <literal>-4</literal> 
290                                                 to <literal>4</literal>. A negative value refers to a quieter setting.</para>
291                                         </option>
292                                         <option name="w">
293                                                 <para>Enable <literal>whisper</literal> mode, so the spying channel can talk to
294                                                 the spied-on channel.</para>
295                                         </option>
296                                         <option name="W">
297                                                 <para>Enable <literal>private whisper</literal> mode, so the spying channel can
298                                                 talk to the spied-on channel but cannot listen to that channel.</para>
299                                         </option>
300                                         <option name="x">
301                                                 <argument name="digit" required="true">
302                                                         <para>Specify a DTMF digit that can be used to exit the application.</para>
303                                                 </argument>
304                                         </option>
305                                         <option name="X">
306                                                 <para>Allow the user to exit ChanSpy to a valid single digit
307                                                 numeric extension in the current context or the context
308                                                 specified by the <variable>SPY_EXIT_CONTEXT</variable> channel variable. The
309                                                 name of the last channel that was spied on will be stored
310                                                 in the <variable>SPY_CHANNEL</variable> variable.</para>
311                                         </option>
312                                 </optionlist>   
313                         </parameter>
314                 </syntax>
315                 <description>
316                         <para>This application is used to listen to the audio from an Asterisk channel. This includes 
317                         the audio coming in and out of the channel being spied on. Only channels created by outgoing calls for the
318                         specified extension will be selected for spying. If the optional context is not supplied, 
319                         the current channel's context will be used.</para>
320                         <para>While spying, the following actions may be performed:</para>
321                         <para> - Dialing <literal>#</literal> cycles the volume level.</para>
322                         <para> - Dialing <literal>*</literal> will stop spying and look for another channel to spy on.</para>
323                         <note><para>The <replaceable>X</replaceable> option supersedes the three features above in that if a valid
324                         single digit extension exists in the correct context ChanSpy will exit to it.
325                         This also disables choosing a channel based on <literal>chanprefix</literal> and a digit sequence.</para></note>
326                 </description>
327                 <see-also>
328                         <ref type="application">ChanSpy</ref>
329                         <ref type="managerEvent">ChanSpyStart</ref>
330                         <ref type="managerEvent">ChanSpyStop</ref>
331                 </see-also>
332         </application>
333         <application name="DAHDIScan" language="en_US">
334                 <synopsis>
335                         Scan DAHDI channels to monitor calls.
336                 </synopsis>
337                 <syntax>
338                         <parameter name="group">
339                                 <para>Limit scanning to a channel <replaceable>group</replaceable> by setting this option.</para>
340                         </parameter>
341                 </syntax>
342                 <description>
343                         <para>Allows a call center manager to monitor DAHDI channels in a
344                         convenient way.  Use <literal>#</literal> to select the next channel and use <literal>*</literal> to exit.</para>
345                 </description>
346                 <see-also>
347                         <ref type="managerEvent">ChanSpyStart</ref>
348                         <ref type="managerEvent">ChanSpyStop</ref>
349                 </see-also>
350         </application>
351  ***/
352
353 static const char app_chan[] = "ChanSpy";
354
355 static const char app_ext[] = "ExtenSpy";
356
357 static const char app_dahdiscan[] = "DAHDIScan";
358
359 enum {
360         OPTION_QUIET             = (1 << 0),    /* Quiet, no announcement */
361         OPTION_BRIDGED           = (1 << 1),    /* Only look at bridged calls */
362         OPTION_VOLUME            = (1 << 2),    /* Specify initial volume */
363         OPTION_GROUP             = (1 << 3),    /* Only look at channels in group */
364         OPTION_RECORD            = (1 << 4),
365         OPTION_WHISPER           = (1 << 5),
366         OPTION_PRIVATE           = (1 << 6),    /* Private Whisper mode */
367         OPTION_READONLY          = (1 << 7),    /* Don't mix the two channels */
368         OPTION_EXIT              = (1 << 8),    /* Exit to a valid single digit extension */
369         OPTION_ENFORCED          = (1 << 9),    /* Enforced mode */
370         OPTION_NOTECH            = (1 << 10),   /* Skip technology name playback */
371         OPTION_BARGE             = (1 << 11),   /* Barge mode (whisper to both channels) */
372         OPTION_NAME              = (1 << 12),   /* Say the name of the person on whom we will spy */
373         OPTION_DTMF_SWITCH_MODES = (1 << 13),   /* Allow numeric DTMF to switch between chanspy modes */
374         OPTION_DTMF_EXIT         = (1 << 14),   /* Set DTMF to exit, added for DAHDIScan integration */
375         OPTION_DTMF_CYCLE        = (1 << 15),   /* Custom DTMF for cycling next avaliable channel, (default is '*') */
376         OPTION_DAHDI_SCAN        = (1 << 16),   /* Scan groups in DAHDIScan mode */
377         OPTION_STOP              = (1 << 17),
378         OPTION_EXITONHANGUP      = (1 << 18),   /* Hang up when the spied-on channel hangs up. */
379 };
380
381 enum {
382         OPT_ARG_VOLUME = 0,
383         OPT_ARG_GROUP,
384         OPT_ARG_RECORD,
385         OPT_ARG_ENFORCED,
386         OPT_ARG_NAME,
387         OPT_ARG_EXIT,
388         OPT_ARG_CYCLE,
389         OPT_ARG_ARRAY_SIZE,
390 };
391
392 AST_APP_OPTIONS(spy_opts, {
393         AST_APP_OPTION('b', OPTION_BRIDGED),
394         AST_APP_OPTION('B', OPTION_BARGE),
395         AST_APP_OPTION_ARG('c', OPTION_DTMF_CYCLE, OPT_ARG_CYCLE),
396         AST_APP_OPTION('d', OPTION_DTMF_SWITCH_MODES),
397         AST_APP_OPTION_ARG('e', OPTION_ENFORCED, OPT_ARG_ENFORCED),
398         AST_APP_OPTION('E', OPTION_EXITONHANGUP),
399         AST_APP_OPTION_ARG('g', OPTION_GROUP, OPT_ARG_GROUP),
400         AST_APP_OPTION_ARG('n', OPTION_NAME, OPT_ARG_NAME),
401         AST_APP_OPTION('o', OPTION_READONLY),
402         AST_APP_OPTION('q', OPTION_QUIET),
403         AST_APP_OPTION_ARG('r', OPTION_RECORD, OPT_ARG_RECORD),
404         AST_APP_OPTION('s', OPTION_NOTECH),
405         AST_APP_OPTION('S', OPTION_STOP),
406         AST_APP_OPTION_ARG('v', OPTION_VOLUME, OPT_ARG_VOLUME),
407         AST_APP_OPTION('w', OPTION_WHISPER),
408         AST_APP_OPTION('W', OPTION_PRIVATE),
409         AST_APP_OPTION_ARG('x', OPTION_DTMF_EXIT, OPT_ARG_EXIT),
410         AST_APP_OPTION('X', OPTION_EXIT),
411 });
412
413 struct chanspy_translation_helper {
414         /* spy data */
415         struct ast_audiohook spy_audiohook;
416         struct ast_audiohook whisper_audiohook;
417         struct ast_audiohook bridge_whisper_audiohook;
418         int fd;
419         int volfactor;
420         struct ast_flags flags;
421 };
422
423 struct spy_dtmf_options {
424         char exit;
425         char cycle;
426         char volume;
427 };
428
429 static void *spy_alloc(struct ast_channel *chan, void *data)
430 {
431         /* just store the data pointer in the channel structure */
432         return data;
433 }
434
435 static void spy_release(struct ast_channel *chan, void *data)
436 {
437         /* nothing to do */
438 }
439
440 static int spy_generate(struct ast_channel *chan, void *data, int len, int samples)
441 {
442         struct chanspy_translation_helper *csth = data;
443         struct ast_frame *f, *cur;
444         struct ast_format format_slin;
445
446         ast_format_set(&format_slin, AST_FORMAT_SLINEAR, 0);
447
448         ast_audiohook_lock(&csth->spy_audiohook);
449         if (csth->spy_audiohook.status != AST_AUDIOHOOK_STATUS_RUNNING) {
450                 /* Channel is already gone more than likely */
451                 ast_audiohook_unlock(&csth->spy_audiohook);
452                 return -1;
453         }
454
455         if (ast_test_flag(&csth->flags, OPTION_READONLY)) {
456                 /* Option 'o' was set, so don't mix channel audio */
457                 f = ast_audiohook_read_frame(&csth->spy_audiohook, samples, AST_AUDIOHOOK_DIRECTION_READ, &format_slin);
458         } else {
459                 f = ast_audiohook_read_frame(&csth->spy_audiohook, samples, AST_AUDIOHOOK_DIRECTION_BOTH, &format_slin);
460         }
461
462         ast_audiohook_unlock(&csth->spy_audiohook);
463
464         if (!f)
465                 return 0;
466
467         for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
468                 if (ast_write(chan, cur)) {
469                         ast_frfree(f);
470                         return -1;
471                 }
472
473                 if (csth->fd) {
474                         if (write(csth->fd, cur->data.ptr, cur->datalen) < 0) {
475                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
476                         }
477                 }
478         }
479
480         ast_frfree(f);
481
482         return 0;
483 }
484
485 static struct ast_generator spygen = {
486         .alloc = spy_alloc,
487         .release = spy_release,
488         .generate = spy_generate,
489 };
490
491 static int start_spying(struct ast_autochan *autochan, const char *spychan_name, struct ast_audiohook *audiohook)
492 {
493         int res = 0;
494
495         ast_log(LOG_NOTICE, "Attaching %s to %s\n", spychan_name, ast_channel_name(autochan->chan));
496
497         ast_set_flag(audiohook, AST_AUDIOHOOK_TRIGGER_SYNC | AST_AUDIOHOOK_SMALL_QUEUE);
498         res = ast_audiohook_attach(autochan->chan, audiohook);
499
500         if (!res) {
501                 ast_channel_lock(autochan->chan);
502                 if (ast_channel_is_bridged(autochan->chan)) {
503                         ast_softhangup_nolock(autochan->chan, AST_SOFTHANGUP_UNBRIDGE);
504                 }
505                 ast_channel_unlock(autochan->chan);
506         }
507         return res;
508 }
509
510 static void change_spy_mode(const char digit, struct ast_flags *flags)
511 {
512         if (digit == '4') {
513                 ast_clear_flag(flags, OPTION_WHISPER);
514                 ast_clear_flag(flags, OPTION_BARGE);
515         } else if (digit == '5') {
516                 ast_clear_flag(flags, OPTION_BARGE);
517                 ast_set_flag(flags, OPTION_WHISPER);
518         } else if (digit == '6') {
519                 ast_clear_flag(flags, OPTION_WHISPER);
520                 ast_set_flag(flags, OPTION_BARGE);
521         }
522 }
523
524 static int pack_channel_into_message(struct ast_channel *chan, const char *role,
525                                                                          struct ast_multi_channel_blob *payload)
526 {
527         RAII_VAR(struct ast_channel_snapshot *, snapshot,
528                         ast_channel_snapshot_get_latest(ast_channel_uniqueid(chan)),
529                         ao2_cleanup);
530
531         if (!snapshot) {
532                 return -1;
533         }
534         ast_multi_channel_blob_add_channel(payload, role, snapshot);
535         return 0;
536 }
537
538 /*! \internal
539  * \brief Publish the chanspy message over Stasis-Core
540  * \param spyer The channel doing the spying
541  * \param spyee Who is being spied upon
542  * \start start If non-zero, the spying is starting. Otherwise, the spyer is
543  * finishing
544  */
545 static void publish_chanspy_message(struct ast_channel *spyer,
546                                                                         struct ast_channel *spyee,
547                                                                         int start)
548 {
549         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
550         RAII_VAR(struct ast_multi_channel_blob *, payload, NULL, ao2_cleanup);
551         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
552
553         if (!spyer) {
554                 ast_log(AST_LOG_WARNING, "Attempt to publish ChanSpy message for NULL spyer channel\n");
555                 return;
556         }
557         blob = ast_json_null();
558         if (!blob) {
559                 return;
560         }
561
562         payload = ast_multi_channel_blob_create(blob);
563         if (!payload) {
564                 return;
565         }
566
567         if (pack_channel_into_message(spyer, "spyer_channel", payload)) {
568                 return;
569         }
570
571         if (spyee) {
572                 if (pack_channel_into_message(spyee, "spyee_channel", payload)) {
573                         return;
574                 }
575         }
576
577         message = stasis_message_create(
578                         start ? ast_channel_chanspy_start_type(): ast_channel_chanspy_stop_type(),
579                                         payload);
580         if (!message) {
581                 return;
582         }
583         stasis_publish(ast_channel_topic(spyer), message);
584 }
585
586 static int channel_spy(struct ast_channel *chan, struct ast_autochan *spyee_autochan,
587         int *volfactor, int fd, struct spy_dtmf_options *user_options, struct ast_flags *flags,
588         char *exitcontext)
589 {
590         struct chanspy_translation_helper csth;
591         int running = 0, res, x = 0;
592         char inp[24] = {0};
593         char *name;
594         struct ast_frame *f;
595         struct ast_silence_generator *silgen = NULL;
596         struct ast_autochan *spyee_bridge_autochan = NULL;
597         const char *spyer_name;
598
599         if (ast_check_hangup(chan) || ast_check_hangup(spyee_autochan->chan) ||
600                         ast_test_flag(ast_channel_flags(spyee_autochan->chan), AST_FLAG_ZOMBIE)) {
601                 return 0;
602         }
603
604         ast_channel_lock(chan);
605         spyer_name = ast_strdupa(ast_channel_name(chan));
606         ast_channel_unlock(chan);
607
608         ast_channel_lock(spyee_autochan->chan);
609         name = ast_strdupa(ast_channel_name(spyee_autochan->chan));
610         ast_channel_unlock(spyee_autochan->chan);
611
612         ast_verb(2, "Spying on channel %s\n", name);
613         publish_chanspy_message(chan, spyee_autochan->chan, 1);
614
615         memset(&csth, 0, sizeof(csth));
616         ast_copy_flags(&csth.flags, flags, AST_FLAGS_ALL);
617
618         /* This is the audiohook which gives us the audio off the channel we are
619            spying on.
620         */
621         ast_audiohook_init(&csth.spy_audiohook, AST_AUDIOHOOK_TYPE_SPY, "ChanSpy", 0);
622
623         if (start_spying(spyee_autochan, spyer_name, &csth.spy_audiohook)) {
624                 ast_audiohook_destroy(&csth.spy_audiohook);
625                 return 0;
626         }
627
628         if (ast_test_flag(flags, OPTION_WHISPER | OPTION_BARGE | OPTION_DTMF_SWITCH_MODES)) {
629                 /* This audiohook will let us inject audio from our channel into the
630                    channel we are currently spying on.
631                 */
632                 ast_audiohook_init(&csth.whisper_audiohook, AST_AUDIOHOOK_TYPE_WHISPER, "ChanSpy", 0);
633
634                 if (start_spying(spyee_autochan, spyer_name, &csth.whisper_audiohook)) {
635                         ast_log(LOG_WARNING, "Unable to attach whisper audiohook to spyee %s. Whisper mode disabled!\n", name);
636                 }
637         }
638
639         if (ast_test_flag(flags, OPTION_BARGE | OPTION_DTMF_SWITCH_MODES)) {
640                 /* And this hook lets us inject audio into the channel that the spied on
641                    channel is currently bridged with.
642                 */
643                 ast_audiohook_init(&csth.bridge_whisper_audiohook, AST_AUDIOHOOK_TYPE_WHISPER, "Chanspy", 0);
644
645                 if ((spyee_bridge_autochan = ast_autochan_setup(ast_bridged_channel(spyee_autochan->chan)))) {
646                         ast_channel_lock(spyee_bridge_autochan->chan);
647                         if (start_spying(spyee_bridge_autochan, spyer_name, &csth.bridge_whisper_audiohook)) {
648                                 ast_log(LOG_WARNING, "Unable to attach barge audiohook on spyee %s. Barge mode disabled!\n", name);
649                         }
650                         ast_channel_unlock(spyee_bridge_autochan->chan);
651                 }
652         }
653
654         ast_channel_lock(chan);
655         ast_set_flag(ast_channel_flags(chan), AST_FLAG_END_DTMF_ONLY);
656         ast_channel_unlock(chan);
657
658         csth.volfactor = *volfactor;
659
660         if (csth.volfactor) {
661                 csth.spy_audiohook.options.read_volume = csth.volfactor;
662                 csth.spy_audiohook.options.write_volume = csth.volfactor;
663         }
664
665         csth.fd = fd;
666
667         if (ast_test_flag(flags, OPTION_PRIVATE))
668                 silgen = ast_channel_start_silence_generator(chan);
669         else
670                 ast_activate_generator(chan, &spygen, &csth);
671
672         /* We can no longer rely on 'spyee' being an actual channel;
673            it can be hung up and freed out from under us. However, the
674            channel destructor will put NULL into our csth.spy.chan
675            field when that happens, so that is our signal that the spyee
676            channel has gone away.
677         */
678
679         /* Note: it is very important that the ast_waitfor() be the first
680            condition in this expression, so that if we wait for some period
681            of time before receiving a frame from our spying channel, we check
682            for hangup on the spied-on channel _after_ knowing that a frame
683            has arrived, since the spied-on channel could have gone away while
684            we were waiting
685         */
686         while (ast_waitfor(chan, -1) > -1 && csth.spy_audiohook.status == AST_AUDIOHOOK_STATUS_RUNNING) {
687                 if (!(f = ast_read(chan)) || ast_check_hangup(chan)) {
688                         running = -1;
689                         break;
690                 }
691
692                 if (ast_test_flag(flags, OPTION_BARGE) && f->frametype == AST_FRAME_VOICE) {
693                         ast_audiohook_lock(&csth.whisper_audiohook);
694                         ast_audiohook_lock(&csth.bridge_whisper_audiohook);
695                         ast_audiohook_write_frame(&csth.whisper_audiohook, AST_AUDIOHOOK_DIRECTION_WRITE, f);
696                         ast_audiohook_write_frame(&csth.bridge_whisper_audiohook, AST_AUDIOHOOK_DIRECTION_WRITE, f);
697                         ast_audiohook_unlock(&csth.whisper_audiohook);
698                         ast_audiohook_unlock(&csth.bridge_whisper_audiohook);
699                         ast_frfree(f);
700                         continue;
701                 } else if (ast_test_flag(flags, OPTION_WHISPER) && f->frametype == AST_FRAME_VOICE) {
702                         ast_audiohook_lock(&csth.whisper_audiohook);
703                         ast_audiohook_write_frame(&csth.whisper_audiohook, AST_AUDIOHOOK_DIRECTION_WRITE, f);
704                         ast_audiohook_unlock(&csth.whisper_audiohook);
705                         ast_frfree(f);
706                         continue;
707                 }
708                 
709                 res = (f->frametype == AST_FRAME_DTMF) ? f->subclass.integer : 0;
710                 ast_frfree(f);
711                 if (!res)
712                         continue;
713
714                 if (x == sizeof(inp))
715                         x = 0;
716
717                 if (res < 0) {
718                         running = -1;
719                         break;
720                 }
721
722                 if (ast_test_flag(flags, OPTION_EXIT)) {
723                         char tmp[2];
724                         tmp[0] = res;
725                         tmp[1] = '\0';
726                         if (!ast_goto_if_exists(chan, exitcontext, tmp, 1)) {
727                                 ast_debug(1, "Got DTMF %c, goto context %s\n", tmp[0], exitcontext);
728                                 pbx_builtin_setvar_helper(chan, "SPY_CHANNEL", name);
729                                 running = -2;
730                                 break;
731                         } else {
732                                 ast_debug(2, "Exit by single digit did not work in chanspy. Extension %s does not exist in context %s\n", tmp, exitcontext);
733                         }
734                 } else if (res >= '0' && res <= '9') {
735                         if (ast_test_flag(flags, OPTION_DTMF_SWITCH_MODES)) {
736                                 change_spy_mode(res, flags);
737                         } else {
738                                 inp[x++] = res;
739                         }
740                 }
741
742                 if (res == user_options->cycle) {
743                         running = 0;
744                         break;
745                 } else if (res == user_options->exit) {
746                         running = -2;
747                         break;
748                 } else if (res == user_options->volume) {
749                         if (!ast_strlen_zero(inp)) {
750                                 running = atoi(inp);
751                                 break;
752                         }
753
754                         (*volfactor)++;
755                         if (*volfactor > 4)
756                                 *volfactor = -4;
757                         ast_verb(3, "Setting spy volume on %s to %d\n", ast_channel_name(chan), *volfactor);
758
759                         csth.volfactor = *volfactor;
760                         csth.spy_audiohook.options.read_volume = csth.volfactor;
761                         csth.spy_audiohook.options.write_volume = csth.volfactor;
762                 }
763         }
764
765         if (ast_test_flag(flags, OPTION_PRIVATE))
766                 ast_channel_stop_silence_generator(chan, silgen);
767         else
768                 ast_deactivate_generator(chan);
769
770         ast_channel_lock(chan);
771         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_END_DTMF_ONLY);
772         ast_channel_unlock(chan);
773
774         if (ast_test_flag(flags, OPTION_WHISPER | OPTION_BARGE | OPTION_DTMF_SWITCH_MODES)) {
775                 ast_audiohook_lock(&csth.whisper_audiohook);
776                 ast_audiohook_detach(&csth.whisper_audiohook);
777                 ast_audiohook_unlock(&csth.whisper_audiohook);
778                 ast_audiohook_destroy(&csth.whisper_audiohook);
779         }
780
781         if (ast_test_flag(flags, OPTION_BARGE | OPTION_DTMF_SWITCH_MODES)) {
782                 ast_audiohook_lock(&csth.bridge_whisper_audiohook);
783                 ast_audiohook_detach(&csth.bridge_whisper_audiohook);
784                 ast_audiohook_unlock(&csth.bridge_whisper_audiohook);
785                 ast_audiohook_destroy(&csth.bridge_whisper_audiohook);
786         }
787
788         ast_audiohook_lock(&csth.spy_audiohook);
789         ast_audiohook_detach(&csth.spy_audiohook);
790         ast_audiohook_unlock(&csth.spy_audiohook);
791         ast_audiohook_destroy(&csth.spy_audiohook);
792
793         if (spyee_bridge_autochan) {
794                 ast_autochan_destroy(spyee_bridge_autochan);
795         }
796
797         ast_verb(2, "Done Spying on channel %s\n", name);
798         publish_chanspy_message(chan, NULL, 0);
799
800         return running;
801 }
802
803 static struct ast_autochan *next_channel(struct ast_channel_iterator *iter,
804                 struct ast_autochan *autochan, struct ast_channel *chan)
805 {
806         struct ast_channel *next;
807         struct ast_autochan *autochan_store;
808         const size_t pseudo_len = strlen("DAHDI/pseudo");
809
810         if (!iter) {
811                 return NULL;
812         }
813
814         for (; (next = ast_channel_iterator_next(iter)); ast_channel_unref(next)) {
815                 if (!strncmp(ast_channel_name(next), "DAHDI/pseudo", pseudo_len)
816                         || next == chan) {
817                         continue;
818                 }
819
820                 autochan_store = ast_autochan_setup(next);
821                 ast_channel_unref(next);
822
823                 return autochan_store;
824         }
825         return NULL;
826 }
827
828 static int common_exec(struct ast_channel *chan, struct ast_flags *flags,
829         int volfactor, const int fd, struct spy_dtmf_options *user_options,
830         const char *mygroup, const char *myenforced, const char *spec, const char *exten,
831         const char *context, const char *mailbox, const char *name_context)
832 {
833         char nameprefix[AST_NAME_STRLEN];
834         char exitcontext[AST_MAX_CONTEXT] = "";
835         signed char zero_volume = 0;
836         int waitms;
837         int res;
838         int num_spyed_upon = 1;
839         struct ast_channel_iterator *iter = NULL;
840
841         if (ast_test_flag(flags, OPTION_EXIT)) {
842                 const char *c;
843                 ast_channel_lock(chan);
844                 if ((c = pbx_builtin_getvar_helper(chan, "SPY_EXIT_CONTEXT"))) {
845                         ast_copy_string(exitcontext, c, sizeof(exitcontext));
846                 } else if (!ast_strlen_zero(ast_channel_macrocontext(chan))) {
847                         ast_copy_string(exitcontext, ast_channel_macrocontext(chan), sizeof(exitcontext));
848                 } else {
849                         ast_copy_string(exitcontext, ast_channel_context(chan), sizeof(exitcontext));
850                 }
851                 ast_channel_unlock(chan);
852         }
853
854         if (ast_channel_state(chan) != AST_STATE_UP)
855                 ast_answer(chan);
856
857         ast_set_flag(ast_channel_flags(chan), AST_FLAG_SPYING); /* so nobody can spy on us while we are spying */
858
859         waitms = 100;
860
861         for (;;) {
862                 struct ast_autochan *autochan = NULL, *next_autochan = NULL;
863                 struct ast_channel *prev = NULL;
864
865                 if (!ast_test_flag(flags, OPTION_QUIET) && num_spyed_upon) {
866                         res = ast_streamfile(chan, "beep", ast_channel_language(chan));
867                         if (!res)
868                                 res = ast_waitstream(chan, "");
869                         else if (res < 0) {
870                                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_SPYING);
871                                 break;
872                         }
873                         if (!ast_strlen_zero(exitcontext)) {
874                                 char tmp[2];
875                                 tmp[0] = res;
876                                 tmp[1] = '\0';
877                                 if (!ast_goto_if_exists(chan, exitcontext, tmp, 1))
878                                         goto exit;
879                                 else
880                                         ast_debug(2, "Exit by single digit did not work in chanspy. Extension %s does not exist in context %s\n", tmp, exitcontext);
881                         }
882                 }
883
884                 /* Set up the iterator we'll be using during this call */
885                 if (!ast_strlen_zero(spec)) {
886                         iter = ast_channel_iterator_by_name_new(spec, strlen(spec));
887                 } else if (!ast_strlen_zero(exten)) {
888                         iter = ast_channel_iterator_by_exten_new(exten, context);
889                 } else {
890                         iter = ast_channel_iterator_all_new();
891                 }
892
893                 if (!iter) {
894                         res = -1;
895                         goto exit;
896                 }
897
898                 res = ast_waitfordigit(chan, waitms);
899                 if (res < 0) {
900                         iter = ast_channel_iterator_destroy(iter);
901                         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_SPYING);
902                         break;
903                 }
904                 if (!ast_strlen_zero(exitcontext)) {
905                         char tmp[2];
906                         tmp[0] = res;
907                         tmp[1] = '\0';
908                         if (!ast_goto_if_exists(chan, exitcontext, tmp, 1)) {
909                                 iter = ast_channel_iterator_destroy(iter);
910                                 goto exit;
911                         } else {
912                                 ast_debug(2, "Exit by single digit did not work in chanspy. Extension %s does not exist in context %s\n", tmp, exitcontext);
913                         }
914                 }
915
916                 /* reset for the next loop around, unless overridden later */
917                 waitms = 100;
918                 num_spyed_upon = 0;
919
920                 for (autochan = next_channel(iter, autochan, chan);
921                      autochan;
922                          prev = autochan->chan, ast_autochan_destroy(autochan),
923                      autochan = next_autochan ? next_autochan : 
924                                 next_channel(iter, autochan, chan), next_autochan = NULL) {
925                         int igrp = !mygroup;
926                         int ienf = !myenforced;
927
928                         if (autochan->chan == prev) {
929                                 ast_autochan_destroy(autochan);
930                                 break;
931                         }
932
933                         if (ast_check_hangup(chan)) {
934                                 ast_autochan_destroy(autochan);
935                                 break;
936                         }
937
938                         if (ast_test_flag(flags, OPTION_BRIDGED) && !ast_bridged_channel(autochan->chan)) {
939                                 continue;
940                         }
941
942                         if (ast_check_hangup(autochan->chan) || ast_test_flag(ast_channel_flags(autochan->chan), AST_FLAG_SPYING)) {
943                                 continue;
944                         }
945
946                         if (mygroup) {
947                                 int num_groups = 0;
948                                 int num_mygroups = 0;
949                                 char dup_group[512];
950                                 char dup_mygroup[512];
951                                 char *groups[NUM_SPYGROUPS];
952                                 char *mygroups[NUM_SPYGROUPS];
953                                 const char *group = NULL;
954                                 int x;
955                                 int y;
956                                 ast_copy_string(dup_mygroup, mygroup, sizeof(dup_mygroup));
957                                 num_mygroups = ast_app_separate_args(dup_mygroup, ':', mygroups,
958                                         ARRAY_LEN(mygroups));
959
960                                 /* Before dahdi scan was part of chanspy, it would use the "GROUP" variable 
961                                  * rather than "SPYGROUP", this check is done to preserve expected behavior */
962                                 if (ast_test_flag(flags, OPTION_DAHDI_SCAN)) {
963                                         group = pbx_builtin_getvar_helper(autochan->chan, "GROUP");
964                                 } else {
965                                         group = pbx_builtin_getvar_helper(autochan->chan, "SPYGROUP");
966                                 }
967
968                                 if (!ast_strlen_zero(group)) {
969                                         ast_copy_string(dup_group, group, sizeof(dup_group));
970                                         num_groups = ast_app_separate_args(dup_group, ':', groups,
971                                                 ARRAY_LEN(groups));
972                                 }
973
974                                 for (y = 0; y < num_mygroups; y++) {
975                                         for (x = 0; x < num_groups; x++) {
976                                                 if (!strcmp(mygroups[y], groups[x])) {
977                                                         igrp = 1;
978                                                         break;
979                                                 }
980                                         }
981                                 }
982                         }
983
984                         if (!igrp) {
985                                 continue;
986                         }
987                         if (myenforced) {
988                                 char ext[AST_CHANNEL_NAME + 3];
989                                 char buffer[512];
990                                 char *end;
991
992                                 snprintf(buffer, sizeof(buffer) - 1, ":%s:", myenforced);
993
994                                 ast_copy_string(ext + 1, ast_channel_name(autochan->chan), sizeof(ext) - 1);
995                                 if ((end = strchr(ext, '-'))) {
996                                         *end++ = ':';
997                                         *end = '\0';
998                                 }
999
1000                                 ext[0] = ':';
1001
1002                                 if (strcasestr(buffer, ext)) {
1003                                         ienf = 1;
1004                                 }
1005                         }
1006
1007                         if (!ienf) {
1008                                 continue;
1009                         }
1010
1011                         if (!ast_test_flag(flags, OPTION_QUIET)) {
1012                                 char peer_name[AST_NAME_STRLEN + 5];
1013                                 char *ptr, *s;
1014
1015                                 strcpy(peer_name, "spy-");
1016                                 strncat(peer_name, ast_channel_name(autochan->chan), AST_NAME_STRLEN - 4 - 1);
1017                                 if ((ptr = strchr(peer_name, '/'))) {
1018                                         *ptr++ = '\0';
1019                                         for (s = peer_name; s < ptr; s++) {
1020                                                 *s = tolower(*s);
1021                                         }
1022                                         if ((s = strchr(ptr, '-'))) {
1023                                                 *s = '\0';
1024                                         }
1025                                 }
1026
1027                                 if (ast_test_flag(flags, OPTION_NAME)) {
1028                                         const char *local_context = S_OR(name_context, "default");
1029                                         const char *local_mailbox = S_OR(mailbox, ptr);
1030                                         if (local_mailbox) {
1031                                                 res = ast_app_sayname(chan, local_mailbox, local_context);
1032                                         } else {
1033                                                 res = -1;
1034                                         }
1035                                 }
1036                                 if (!ast_test_flag(flags, OPTION_NAME) || res < 0) {
1037                                         int num;
1038                                         if (!ast_test_flag(flags, OPTION_NOTECH)) {
1039                                                 if (ast_fileexists(peer_name, NULL, NULL) > 0) {
1040                                                         res = ast_streamfile(chan, peer_name, ast_channel_language(chan));
1041                                                         if (!res) {
1042                                                                 res = ast_waitstream(chan, "");
1043                                                         }
1044                                                         if (res) {
1045                                                                 ast_autochan_destroy(autochan);
1046                                                                 break;
1047                                                         }
1048                                                 } else {
1049                                                         res = ast_say_character_str(chan, peer_name, "", ast_channel_language(chan));
1050                                                 }
1051                                         }
1052                                         if (ptr && (num = atoi(ptr))) {
1053                                                 ast_say_digits(chan, num, "", ast_channel_language(chan));
1054                                         }
1055                                 }
1056                         }
1057
1058                         res = channel_spy(chan, autochan, &volfactor, fd, user_options, flags, exitcontext);
1059                         num_spyed_upon++;
1060
1061                         if (res == -1) {
1062                                 ast_autochan_destroy(autochan);
1063                                 iter = ast_channel_iterator_destroy(iter);
1064                                 goto exit;
1065                         } else if (res == -2) {
1066                                 res = 0;
1067                                 ast_autochan_destroy(autochan);
1068                                 iter = ast_channel_iterator_destroy(iter);
1069                                 goto exit;
1070                         } else if (res > 1 && spec) {
1071                                 struct ast_channel *next;
1072
1073                                 snprintf(nameprefix, AST_NAME_STRLEN, "%s/%d", spec, res);
1074
1075                                 if ((next = ast_channel_get_by_name_prefix(nameprefix, strlen(nameprefix)))) {
1076                                         next_autochan = ast_autochan_setup(next);
1077                                         next = ast_channel_unref(next);
1078                                 } else {
1079                                         /* stay on this channel, if it is still valid */
1080                                         if (!ast_check_hangup(autochan->chan)) {
1081                                                 next_autochan = ast_autochan_setup(autochan->chan);
1082                                         } else {
1083                                                 /* the channel is gone */
1084                                                 next_autochan = NULL;
1085                                         }
1086                                 }
1087                         } else if (res == 0 && ast_test_flag(flags, OPTION_EXITONHANGUP)) {
1088                                 ast_autochan_destroy(autochan);
1089                                 iter = ast_channel_iterator_destroy(iter);
1090                                 goto exit;
1091                         }
1092                 }
1093
1094                 iter = ast_channel_iterator_destroy(iter);
1095
1096                 if (res == -1 || ast_check_hangup(chan))
1097                         break;
1098                 if (ast_test_flag(flags, OPTION_STOP) && !next_autochan) {
1099                         break;
1100                 }
1101         }
1102 exit:
1103
1104         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_SPYING);
1105
1106         ast_channel_setoption(chan, AST_OPTION_TXGAIN, &zero_volume, sizeof(zero_volume), 0);
1107
1108         return res;
1109 }
1110
1111 static int chanspy_exec(struct ast_channel *chan, const char *data)
1112 {
1113         char *myenforced = NULL;
1114         char *mygroup = NULL;
1115         char *recbase = NULL;
1116         int fd = 0;
1117         struct ast_flags flags;
1118         struct spy_dtmf_options user_options = {
1119                 .cycle = '*',
1120                 .volume = '#',
1121                 .exit = '\0',
1122         };
1123         struct ast_format oldwf;
1124         int volfactor = 0;
1125         int res;
1126         char *mailbox = NULL;
1127         char *name_context = NULL;
1128         AST_DECLARE_APP_ARGS(args,
1129                 AST_APP_ARG(spec);
1130                 AST_APP_ARG(options);
1131         );
1132         char *opts[OPT_ARG_ARRAY_SIZE];
1133         char *parse = ast_strdupa(data);
1134
1135         AST_STANDARD_APP_ARGS(args, parse);
1136         ast_format_clear(&oldwf);
1137
1138         if (args.spec && !strcmp(args.spec, "all"))
1139                 args.spec = NULL;
1140
1141         if (args.options) {
1142                 char tmp;
1143                 ast_app_parse_options(spy_opts, &flags, opts, args.options);
1144                 if (ast_test_flag(&flags, OPTION_GROUP))
1145                         mygroup = opts[OPT_ARG_GROUP];
1146
1147                 if (ast_test_flag(&flags, OPTION_RECORD) &&
1148                         !(recbase = opts[OPT_ARG_RECORD]))
1149                         recbase = "chanspy";
1150
1151                 if (ast_test_flag(&flags, OPTION_DTMF_EXIT) && opts[OPT_ARG_EXIT]) {
1152                         tmp = opts[OPT_ARG_EXIT][0];
1153                         if (strchr("0123456789*#", tmp) && tmp != '\0') {
1154                                 user_options.exit = tmp;
1155                         } else {
1156                                 ast_log(LOG_NOTICE, "Argument for option 'x' must be a valid DTMF digit.\n");
1157                         }
1158                 }
1159
1160                 if (ast_test_flag(&flags, OPTION_DTMF_CYCLE) && opts[OPT_ARG_CYCLE]) {
1161                         tmp = opts[OPT_ARG_CYCLE][0];
1162                         if (strchr("0123456789*#", tmp) && tmp != '\0') {
1163                                 user_options.cycle = tmp;
1164                         } else {
1165                                 ast_log(LOG_NOTICE, "Argument for option 'c' must be a valid DTMF digit.\n");
1166                         }
1167                 }
1168
1169                 if (ast_test_flag(&flags, OPTION_VOLUME) && opts[OPT_ARG_VOLUME]) {
1170                         int vol;
1171
1172                         if ((sscanf(opts[OPT_ARG_VOLUME], "%30d", &vol) != 1) || (vol > 4) || (vol < -4))
1173                                 ast_log(LOG_NOTICE, "Volume factor must be a number between -4 and 4\n");
1174                         else
1175                                 volfactor = vol;
1176                 }
1177
1178                 if (ast_test_flag(&flags, OPTION_PRIVATE))
1179                         ast_set_flag(&flags, OPTION_WHISPER);
1180
1181                 if (ast_test_flag(&flags, OPTION_ENFORCED))
1182                         myenforced = opts[OPT_ARG_ENFORCED];
1183
1184                 if (ast_test_flag(&flags, OPTION_NAME)) {
1185                         if (!ast_strlen_zero(opts[OPT_ARG_NAME])) {
1186                                 char *delimiter;
1187                                 if ((delimiter = strchr(opts[OPT_ARG_NAME], '@'))) {
1188                                         mailbox = opts[OPT_ARG_NAME];
1189                                         *delimiter++ = '\0';
1190                                         name_context = delimiter;
1191                                 } else {
1192                                         mailbox = opts[OPT_ARG_NAME];
1193                                 }
1194                         }
1195                 }
1196         } else {
1197                 ast_clear_flag(&flags, AST_FLAGS_ALL);
1198         }
1199
1200         ast_format_copy(&oldwf, ast_channel_writeformat(chan));
1201         if (ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR) < 0) {
1202                 ast_log(LOG_ERROR, "Could Not Set Write Format.\n");
1203                 return -1;
1204         }
1205
1206         if (recbase) {
1207                 char filename[PATH_MAX];
1208
1209                 snprintf(filename, sizeof(filename), "%s/%s.%d.raw", ast_config_AST_MONITOR_DIR, recbase, (int) time(NULL));
1210                 if ((fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, AST_FILE_MODE)) <= 0) {
1211                         ast_log(LOG_WARNING, "Cannot open '%s' for recording\n", filename);
1212                         fd = 0;
1213                 }
1214         }
1215
1216         res = common_exec(chan, &flags, volfactor, fd, &user_options, mygroup, myenforced, args.spec, NULL, NULL, mailbox, name_context);
1217
1218         if (fd)
1219                 close(fd);
1220
1221         if (oldwf.id && ast_set_write_format(chan, &oldwf) < 0)
1222                 ast_log(LOG_ERROR, "Could Not Set Write Format.\n");
1223
1224         if (ast_test_flag(&flags, OPTION_EXITONHANGUP)) {
1225                 ast_verb(3, "Stopped spying due to the spied-on channel hanging up.\n");
1226         }
1227
1228         return res;
1229 }
1230
1231 static int extenspy_exec(struct ast_channel *chan, const char *data)
1232 {
1233         char *ptr, *exten = NULL;
1234         char *mygroup = NULL;
1235         char *recbase = NULL;
1236         int fd = 0;
1237         struct ast_flags flags;
1238         struct spy_dtmf_options user_options = {
1239                 .cycle = '*',
1240                 .volume = '#',
1241                 .exit = '\0',
1242         };
1243         struct ast_format oldwf;
1244         int volfactor = 0;
1245         int res;
1246         char *mailbox = NULL;
1247         char *name_context = NULL;
1248         AST_DECLARE_APP_ARGS(args,
1249                 AST_APP_ARG(context);
1250                 AST_APP_ARG(options);
1251         );
1252         char *parse = ast_strdupa(data);
1253
1254         AST_STANDARD_APP_ARGS(args, parse);
1255         ast_format_clear(&oldwf);
1256
1257         if (!ast_strlen_zero(args.context) && (ptr = strchr(args.context, '@'))) {
1258                 exten = args.context;
1259                 *ptr++ = '\0';
1260                 args.context = ptr;
1261         }
1262         if (ast_strlen_zero(args.context))
1263                 args.context = ast_strdupa(ast_channel_context(chan));
1264
1265         if (args.options) {
1266                 char *opts[OPT_ARG_ARRAY_SIZE];
1267                 char tmp;
1268
1269                 ast_app_parse_options(spy_opts, &flags, opts, args.options);
1270                 if (ast_test_flag(&flags, OPTION_GROUP))
1271                         mygroup = opts[OPT_ARG_GROUP];
1272
1273                 if (ast_test_flag(&flags, OPTION_RECORD) &&
1274                         !(recbase = opts[OPT_ARG_RECORD]))
1275                         recbase = "chanspy";
1276
1277                 if (ast_test_flag(&flags, OPTION_DTMF_EXIT) && opts[OPT_ARG_EXIT]) {
1278                         tmp = opts[OPT_ARG_EXIT][0];
1279                         if (strchr("0123456789*#", tmp) && tmp != '\0') {
1280                                 user_options.exit = tmp;
1281                         } else {
1282                                 ast_log(LOG_NOTICE, "Argument for option 'x' must be a valid DTMF digit.\n");
1283                         }
1284                 }
1285
1286                 if (ast_test_flag(&flags, OPTION_DTMF_CYCLE) && opts[OPT_ARG_CYCLE]) {
1287                         tmp = opts[OPT_ARG_CYCLE][0];
1288                         if (strchr("0123456789*#", tmp) && tmp != '\0') {
1289                                 user_options.cycle = tmp;
1290                         } else {
1291                                 ast_log(LOG_NOTICE, "Argument for option 'c' must be a valid DTMF digit.\n");
1292                         }
1293                 }
1294
1295                 if (ast_test_flag(&flags, OPTION_VOLUME) && opts[OPT_ARG_VOLUME]) {
1296                         int vol;
1297
1298                         if ((sscanf(opts[OPT_ARG_VOLUME], "%30d", &vol) != 1) || (vol > 4) || (vol < -4))
1299                                 ast_log(LOG_NOTICE, "Volume factor must be a number between -4 and 4\n");
1300                         else
1301                                 volfactor = vol;
1302                 }
1303
1304                 if (ast_test_flag(&flags, OPTION_PRIVATE))
1305                         ast_set_flag(&flags, OPTION_WHISPER);
1306
1307                 if (ast_test_flag(&flags, OPTION_NAME)) {
1308                         if (!ast_strlen_zero(opts[OPT_ARG_NAME])) {
1309                                 char *delimiter;
1310                                 if ((delimiter = strchr(opts[OPT_ARG_NAME], '@'))) {
1311                                         mailbox = opts[OPT_ARG_NAME];
1312                                         *delimiter++ = '\0';
1313                                         name_context = delimiter;
1314                                 } else {
1315                                         mailbox = opts[OPT_ARG_NAME];
1316                                 }
1317                         }
1318                 }
1319
1320         } else {
1321                 /* Coverity - This uninit_use should be ignored since this macro initializes the flags */
1322                 ast_clear_flag(&flags, AST_FLAGS_ALL);
1323         }
1324
1325         ast_format_copy(&oldwf, ast_channel_writeformat(chan));
1326         if (ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR) < 0) {
1327                 ast_log(LOG_ERROR, "Could Not Set Write Format.\n");
1328                 return -1;
1329         }
1330
1331         if (recbase) {
1332                 char filename[PATH_MAX];
1333
1334                 snprintf(filename, sizeof(filename), "%s/%s.%d.raw", ast_config_AST_MONITOR_DIR, recbase, (int) time(NULL));
1335                 if ((fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, AST_FILE_MODE)) <= 0) {
1336                         ast_log(LOG_WARNING, "Cannot open '%s' for recording\n", filename);
1337                         fd = 0;
1338                 }
1339         }
1340
1341
1342         res = common_exec(chan, &flags, volfactor, fd, &user_options, mygroup, NULL, NULL, exten, args.context, mailbox, name_context);
1343
1344         if (fd)
1345                 close(fd);
1346
1347         if (oldwf.id && ast_set_write_format(chan, &oldwf) < 0)
1348                 ast_log(LOG_ERROR, "Could Not Set Write Format.\n");
1349
1350         return res;
1351 }
1352
1353 static int dahdiscan_exec(struct ast_channel *chan, const char *data)
1354 {
1355         const char *spec = "DAHDI";
1356         struct ast_flags flags;
1357         struct spy_dtmf_options user_options = {
1358                 .cycle = '#',
1359                 .volume = '\0',
1360                 .exit = '*',
1361         };
1362         struct ast_format oldwf;
1363         int res;
1364         char *mygroup = NULL;
1365
1366         /* Coverity - This uninit_use should be ignored since this macro initializes the flags */
1367         ast_clear_flag(&flags, AST_FLAGS_ALL);
1368         ast_format_clear(&oldwf);
1369         if (!ast_strlen_zero(data)) {
1370                 mygroup = ast_strdupa(data);
1371         }
1372         ast_set_flag(&flags, OPTION_DTMF_EXIT);
1373         ast_set_flag(&flags, OPTION_DTMF_CYCLE);
1374         ast_set_flag(&flags, OPTION_DAHDI_SCAN);
1375
1376         ast_format_copy(&oldwf, ast_channel_writeformat(chan));
1377         if (ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR) < 0) {
1378                 ast_log(LOG_ERROR, "Could Not Set Write Format.\n");
1379                 return -1;
1380         }
1381
1382         res = common_exec(chan, &flags, 0, 0, &user_options, mygroup, NULL, spec, NULL, NULL, NULL, NULL);
1383
1384         if (oldwf.id && ast_set_write_format(chan, &oldwf) < 0)
1385                 ast_log(LOG_ERROR, "Could Not Set Write Format.\n");
1386
1387         return res;
1388 }
1389
1390 static int unload_module(void)
1391 {
1392         int res = 0;
1393
1394         res |= ast_unregister_application(app_chan);
1395         res |= ast_unregister_application(app_ext);
1396         res |= ast_unregister_application(app_dahdiscan);
1397
1398         return res;
1399 }
1400
1401 static int load_module(void)
1402 {
1403         int res = 0;
1404
1405         res |= ast_register_application_xml(app_chan, chanspy_exec);
1406         res |= ast_register_application_xml(app_ext, extenspy_exec);
1407         res |= ast_register_application_xml(app_dahdiscan, dahdiscan_exec);
1408
1409         return res;
1410 }
1411
1412 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Listen to the audio of an active channel");