Add chanspy (bug #3836)
[asterisk/asterisk.git] / apps / app_chanspy.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * ChanSpy Listen in on any channel.
5  * 
6  * Copyright (C) 2005 Anthony Minessale II (anthmct@yahoo.com)
7  *
8  * Disclaimed to Digium
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <asterisk/file.h>
15 #include <asterisk/logger.h>
16 #include <asterisk/channel.h>
17 #include <asterisk/features.h>
18 #include <asterisk/options.h>
19 #include <asterisk/app.h>
20 #include <asterisk/utils.h>
21 #include <asterisk/say.h>
22 #include <asterisk/channel_pvt.h>
23 #include <asterisk/pbx.h>
24 #include <asterisk/translate.h>
25 #include <asterisk/module.h>
26 #include <asterisk/lock.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <string.h>
30 #include <ctype.h>
31
32 AST_MUTEX_DEFINE_STATIC(modlock);
33
34 #define ast_fit_in_short(in) (in < -32768 ? -32768 : in > 32767 ? 32767 : in)
35 #define find_smallest_of_three(a, b, c) ((a < b && a < c) ? a : (b < a && b < c) ? b : c)
36 #define AST_NAME_STRLEN 256
37 #define ALL_DONE(u, ret) LOCAL_USER_REMOVE(u); return ret;
38 #define get_volfactor(x) x ? ((x > 0) ? (1 << x) : ((1 << abs(x)) * -1)) : 0
39 #define minmax(x,y) x ? (x > y) ? y : ((x < (y * -1)) ? (y * -1) : x) : 0
40
41
42
43 static char *synopsis = "Tap into any type of asterisk channel and listen to audio";
44 static char *app = "ChanSpy";
45 static char *desc = "   Chanspy([<scanspec>][|<options>])\n\n"
46 "Valid Options:\n"
47 " - q: quiet, don't announce channels beep, etc.\n"
48 " - b: bridged, only spy on channels involved in a bridged call.\n"
49 " - v([-4..4]): adjust the initial volume. (negative is quieter)\n"
50 " - g(grp): enforce group.  Match only calls where their ${SPYGROUP} is 'grp'.\n\n"
51 "If <scanspec> is specified, only channel names *beginning* with that string will be scanned.\n"
52 "('all' or an empty string are also both valid <scanspec>)\n\n"
53 "While Spying:\n\n"
54 "Dialing # cycles the volume level.\n"
55 "Dialing * will stop spying and look for another channel to spy on.\n"
56 "Dialing a series of digits followed by # builds a channel name to append to <scanspec>\n"
57 "(e.g. run Chanspy(Agent) and dial 1234# while spying to jump to channel Agent/1234)\n\n"
58 "";
59
60 #define OPTION_QUIET     (1 << 0)       /* Quiet, no announcement */
61 #define OPTION_BRIDGED   (1 << 1)       /* Only look at bridged calls */
62 #define OPTION_VOLUME    (1 << 2)       /* Specify initial volume */
63 #define OPTION_GROUP     (1 << 3)   /* Only look at channels in group */
64
65 AST_DECLARE_OPTIONS(chanspy_opts,{
66         ['q'] = { OPTION_QUIET },
67         ['b'] = { OPTION_BRIDGED },
68         ['v'] = { OPTION_VOLUME, 1 },
69         ['g'] = { OPTION_GROUP, 2 },
70 });
71
72 STANDARD_LOCAL_USER;
73
74 LOCAL_USER_DECL;
75
76 struct chanspy_translation_helper {
77         struct ast_trans_pvt *trans0;
78         struct ast_trans_pvt *trans1;
79         int volfactor;
80         struct ast_channel_spy *spy;
81 };
82
83 /* Prototypes */
84 static struct ast_channel *local_get_channel_by_name(char *name);
85 static struct ast_channel *local_channel_walk(struct ast_channel *chan);
86 static void spy_release(struct ast_channel *chan, void *data);
87 static void *spy_alloc(struct ast_channel *chan, void *params);
88 static struct ast_frame *spy_queue_shift(struct ast_channel_spy *spy, int qnum);
89 static void ast_flush_spy_queue(struct ast_channel_spy *spy);
90 static int spy_generate(struct ast_channel *chan, void *data, int len, int samples);
91 static void start_spying(struct ast_channel *chan, struct ast_channel *spychan, struct ast_channel_spy *spy);
92 static void stop_spying(struct ast_channel *chan, struct ast_channel_spy *spy);
93 static int channel_spy(struct ast_channel *chan, struct ast_channel *spyee, int *volfactor);
94 static int chanspy_exec(struct ast_channel *chan, void *data);
95
96
97 static struct ast_channel *local_get_channel_by_name(char *name) 
98 {
99         struct ast_channel *ret;
100         ast_mutex_lock(&modlock);
101         if ((ret = ast_get_channel_by_name_locked(name))) {
102                 ast_mutex_unlock(&ret->lock);
103         }
104         ast_mutex_unlock(&modlock);
105
106         return ret;
107 }
108
109 static struct ast_channel *local_channel_walk(struct ast_channel *chan) 
110 {
111         struct ast_channel *ret;
112         ast_mutex_lock(&modlock);       
113         if ((ret = ast_channel_walk_locked(chan))) {
114                 ast_mutex_unlock(&ret->lock);
115         }
116         ast_mutex_unlock(&modlock);                     
117         return ret;
118 }
119
120 static void spy_release(struct ast_channel *chan, void *data) 
121 {
122         struct chanspy_translation_helper *csth = data;
123         int same=0;
124
125         same = (csth->trans0 == csth->trans1) ? 1 : 0;
126
127         if (csth->trans0) {
128                 ast_translator_free_path(csth->trans0);
129                 csth->trans0 = NULL;
130         }
131         if (same)
132                 return;
133         if (csth->trans1) {
134                 ast_translator_free_path(csth->trans1);
135                 csth->trans1 = NULL;
136         }
137         return;
138 }
139
140 static void *spy_alloc(struct ast_channel *chan, void *params) 
141 {
142         return params;
143 }
144
145 static struct ast_frame *spy_queue_shift(struct ast_channel_spy *spy, int qnum) 
146 {
147         struct ast_frame *f;
148         
149         if (qnum < 0 || qnum > 1)
150                 return NULL;
151
152         f = spy->queue[qnum];
153         if (f) {
154                 spy->queue[qnum] = f->next;
155                 return f;
156         }
157         return NULL;
158 }
159
160
161 static void ast_flush_spy_queue(struct ast_channel_spy *spy) 
162 {
163         struct ast_frame *f=NULL;
164         int x = 0;
165         ast_mutex_lock(&spy->lock);
166         for(x=0;x<2;x++) {
167                 f = NULL;
168                 while((f = spy_queue_shift(spy, x))) 
169                         ast_frfree(f);
170         }
171         ast_mutex_unlock(&spy->lock);
172 }
173
174
175 static int spy_generate(struct ast_channel *chan, void *data, int len, int samples) 
176 {
177         struct ast_frame *f0, *f1, write_frame, *f;
178         int x=0, framelen_a = 0, framelen_b = 0, size = 0;
179         short buf[320], buf0[320], buf1[320];
180         struct chanspy_translation_helper *csth = data;
181         int nc = 0, vf;
182         
183         ast_mutex_lock(&csth->spy->lock);
184         f0 = spy_queue_shift(csth->spy, 0);
185         f1 = spy_queue_shift(csth->spy, 1);
186         ast_mutex_unlock(&csth->spy->lock);
187
188
189         if (f0 && f1) {
190                 if (!csth->trans0) {
191                         if (f0->subclass != AST_FORMAT_SLINEAR && (csth->trans0 = ast_translator_build_path(AST_FORMAT_SLINEAR, f0->subclass)) == NULL) {
192                                 ast_log(LOG_WARNING, "Cannot build a path from %s to slin\n", ast_getformatname(f0->subclass));
193                                 return -1;
194                         }
195                         if (!csth->trans1) {
196                                 if (f1->subclass == f0->subclass) {
197                                         csth->trans1 = csth->trans0;
198                                 } else if (f1->subclass != AST_FORMAT_SLINEAR && (csth->trans1 = ast_translator_build_path(AST_FORMAT_SLINEAR, f1->subclass)) == NULL) {
199                                         ast_log(LOG_WARNING, "Cannot build a path from %s to slin\n", ast_getformatname(f1->subclass));
200                                         return -1;
201                                 }
202                                 
203                         }
204                 }
205
206                 memset(buf, 0, sizeof(buf));
207                 memset(buf0, 0, sizeof(buf0));
208                 memset(buf1, 0, sizeof(buf1));
209                 if (csth->trans0) {
210                         if ((f = ast_translate(csth->trans0, f0, 0))) {
211                                 framelen_a = f->datalen * sizeof(short);
212                                 memcpy(buf0, f->data, framelen_a);
213                                 ast_frfree(f);
214                         } else 
215                                 return 0;
216                 } else {
217                         framelen_a = f0->datalen * sizeof(short);
218                         memcpy(buf0, f0->data, framelen_a);
219                 }
220                 if (csth->trans1) {
221                         if ((f = ast_translate(csth->trans1, f1, 0))) {
222                                 framelen_b = f->datalen * sizeof(short);
223                                 memcpy(buf1, f->data, framelen_b);
224                                 ast_frfree(f);
225                         } else 
226                                 return 0;
227                 } else {
228                         framelen_b = f1->datalen * sizeof(short);
229                         memcpy(buf1, f1->data, framelen_b);
230                 }
231                 size = find_smallest_of_three(len, framelen_a, framelen_b);
232
233                 vf = get_volfactor(csth->volfactor);
234                 vf = minmax(vf, 16);
235                 for(x=0; x < size; x++) {
236                         if (vf < 0) {
237                                 buf0[x] /= abs(vf);
238                                 buf1[x] /= abs(vf);
239                         } else if (vf > 0) {
240                                 buf0[x] *= vf;
241                                 buf1[x] *= vf;
242                         }
243                         buf[x] = ast_fit_in_short(buf0[x] + buf1[x]);
244                 }
245                 memset(&write_frame, 0, sizeof(write_frame));
246                 write_frame.frametype = AST_FRAME_VOICE;
247                 write_frame.subclass = AST_FORMAT_SLINEAR;
248                 write_frame.datalen = size;
249                 write_frame.samples = size;
250                 write_frame.data = buf;
251                 write_frame.offset = 0;
252                 ast_write(chan, &write_frame);
253         } else {
254                 nc++;
255                 if(nc > 1) {
256                         return -1;
257                 }
258         }
259         
260         if (f0)
261                 ast_frfree(f0);
262         if (f1) 
263                 ast_frfree(f1);
264
265         return 0;
266
267 }
268
269 static struct ast_generator spygen = {
270     alloc: spy_alloc, 
271     release: spy_release, 
272     generate: spy_generate, 
273 };
274
275 static void start_spying(struct ast_channel *chan, struct ast_channel *spychan, struct ast_channel_spy *spy) 
276 {
277
278         struct ast_channel_spy *cptr=NULL;
279         struct ast_channel *peer;
280
281
282         ast_log(LOG_WARNING, "Attaching %s to %s\n", spychan->name, chan->name);
283
284
285         ast_mutex_lock(&chan->lock);
286         if (chan->spiers) {
287                 for(cptr=chan->spiers;cptr && cptr->next;cptr=cptr->next);
288                 cptr->next = spy;
289         } else {
290                 chan->spiers = spy;
291         }
292         ast_mutex_unlock(&chan->lock);
293         if ( ast_test_flag(chan, AST_FLAG_NBRIDGE) && (peer = ast_bridged_channel(chan))) {
294                 ast_softhangup(peer, AST_SOFTHANGUP_UNBRIDGE);  
295         }
296
297 }
298
299 static void stop_spying(struct ast_channel *chan, struct ast_channel_spy *spy) 
300 {
301         struct ast_channel_spy *cptr=NULL, *prev=NULL;
302         int count = 0;
303
304         while(ast_mutex_trylock(&chan->lock)) {
305                 /* if its locked already it's almost surely hanging up and we are too late 
306                    we can safely remove the head pointer if it points at us without needing a lock.
307                    since everybody spying will be in the same boat whomever is pointing at the head
308                    will surely erase it which is all we really need since it's a linked list of
309                    staticly declared structs that belong to each spy.
310                 */
311                 if (chan->spiers == spy) {
312                         chan->spiers = NULL;
313                         return;
314                 }
315                 count++;
316                 if(count > 10) {
317                         return;
318                 }
319                 sched_yield();
320         }
321
322         for(cptr=chan->spiers; cptr; cptr=cptr->next) {
323                 if (cptr == spy) {
324                         if (prev) {
325                                 prev->next = cptr->next;
326                                 cptr->next = NULL;
327                         } else
328                                 chan->spiers = NULL;
329                 }
330                 prev = cptr;
331         }
332         ast_mutex_unlock(&chan->lock);
333
334 }
335
336 static int channel_spy(struct ast_channel *chan, struct ast_channel *spyee, int *volfactor) 
337 {
338         struct chanspy_translation_helper csth;
339         int running = 1, res = 0, x = 0;
340         char inp[24];
341         char *name=NULL;
342         struct ast_channel_spy spy;
343
344         if (chan && !ast_check_hangup(chan) && spyee && !ast_check_hangup(spyee)) {
345                 memset(inp, 0, sizeof(inp));
346                 name = ast_strdupa(spyee->name);
347                 if (option_verbose >= 2)
348                         ast_verbose(VERBOSE_PREFIX_2 "Spying on channel %s\n", name);
349                 
350                 memset(&spy, 0, sizeof(struct ast_channel_spy));
351                 spy.status = CHANSPY_RUNNING;
352                 ast_mutex_init(&spy.lock);
353                 start_spying(spyee, chan, &spy);
354                 
355                 memset(&csth, 0, sizeof(csth));
356                 csth.volfactor = *volfactor;
357                 csth.spy = &spy;
358                 ast_activate_generator(chan, &spygen, &csth);
359
360                 while(spy.status == CHANSPY_RUNNING && chan && !ast_check_hangup(chan) && spyee && !ast_check_hangup(spyee) && running == 1) {
361                         res = ast_waitfordigit(chan, 100);
362
363                         if (x == sizeof(inp)) {
364                                 x = 0;
365                         }
366                         if (res < 0) {
367                                 running = -1;
368                         }
369                         if (res == 0) {
370                                 continue;
371                         } else if (res == '*') {
372                                 running = 0; 
373                         } else if (res == '#') {
374                                 if (!ast_strlen_zero(inp)) {
375                                         running = x ? atoi(inp) : -1;
376                                         break;
377                                 } else {
378                                         csth.volfactor++;
379                                         if (csth.volfactor > 4) {
380                                                 csth.volfactor = -4;
381                                         }
382                                         if (option_verbose > 2) {
383                                                 ast_verbose(VERBOSE_PREFIX_3"Setting spy volume on %s to %d\n", chan->name, csth.volfactor);
384                                         }
385                                         *volfactor = csth.volfactor;
386                                 }
387                         } else if (res >= 48 && res <= 57) {
388                                 inp[x++] = res;
389                         }
390                 }
391                 ast_deactivate_generator(chan);
392                 stop_spying(spyee, &spy);
393
394                 if (option_verbose >= 2)
395                         ast_verbose(VERBOSE_PREFIX_2 "Done Spying on channel %s\n", name);
396
397                 ast_flush_spy_queue(&spy);
398         } else {
399                 running = 0;
400         }
401         ast_mutex_destroy(&spy.lock);
402         return running;
403 }
404
405
406
407 static int chanspy_exec(struct ast_channel *chan, void *data)
408 {
409         int res=-1;
410         struct localuser *u;
411         struct ast_channel *peer=NULL, *prev=NULL;
412         char *ptr=NULL;
413         char name[AST_NAME_STRLEN], peer_name[AST_NAME_STRLEN];
414         int count=0, waitms=100, num=0;
415         char *args;
416         struct ast_flags flags;
417         char *options=NULL;
418         char *spec = NULL;
419         int volfactor=0;
420         int silent=0;
421         int argc = 0;
422         char *argv[5];
423         char *mygroup = NULL;
424         int bronly = 0;
425
426
427         if (!(args = ast_strdupa((char *)data))) {
428                 ast_log(LOG_ERROR, "Out of memory!\n");
429                 return -1;
430         }
431
432         if (ast_set_read_format(chan, AST_FORMAT_SLINEAR) < 0) {
433                 ast_log(LOG_ERROR, "Could Not Set Read Format.\n");
434                 return -1;
435         }
436         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
437                 ast_log(LOG_ERROR, "Could Not Set Write Format.\n");
438                 return -1;
439         }
440
441         LOCAL_USER_ADD(u);
442         ast_answer(chan);
443
444         ast_set_flag(chan, AST_FLAG_SPYING); /* so nobody can spy on us while we are spying */
445
446
447         if ((argc = ast_separate_app_args(args, '|', argv, sizeof(argv) / sizeof(argv[0])))) {
448                 spec = argv[0];
449                 if ( argc > 1) {
450                         options = argv[1];
451                 }
452                 if (ast_strlen_zero(spec) || !strcmp(spec, "all")) {
453                         spec = NULL;
454                 }
455         }
456         
457         if (options) {
458                 char *opts[2];
459                 ast_parseoptions(chanspy_opts, &flags, opts, options);
460                 if (ast_test_flag(&flags, OPTION_GROUP))
461                         mygroup = opts[0];
462                 silent = ast_test_flag(&flags, OPTION_QUIET);
463                 bronly = ast_test_flag(&flags, OPTION_BRIDGED);
464                 if (ast_test_flag(&flags, OPTION_VOLUME) && opts[1]) {
465                         if (sscanf(opts[1], "%d", &volfactor) != 1)
466                                 ast_log(LOG_NOTICE, "volfactor must be a number between -16 and 16\n");
467                         else if (volfactor > 16)
468                                 volfactor = 16;
469                         else if (volfactor < -16)
470                                 volfactor = -16;
471                 }
472         }
473
474
475         for(;;) {
476                 res = ast_streamfile(chan, "beep", chan->language);
477                 if (!res)
478                         res = ast_waitstream(chan, "");
479                 if (res < 0) {
480                         ast_clear_flag(chan, AST_FLAG_SPYING);
481                         ALL_DONE(u, -1);
482                 }                       
483
484                 count = 0;
485                 res = ast_waitfordigit(chan, waitms);
486                 if (res < 0) {
487                         ast_clear_flag(chan, AST_FLAG_SPYING);
488                         ALL_DONE(u, -1);
489                 }
490                                 
491                 peer = local_channel_walk(NULL);
492                 prev=NULL;
493                 while(peer) {
494                         if (peer != chan) {
495                                 char *group = NULL;
496
497                                 if (peer == prev) {
498                                         break;
499                                 }
500
501                                 group = pbx_builtin_getvar_helper(chan, "SPYGROUP");
502
503                                 if (mygroup && group && strcmp(group, mygroup)) { 
504                                         continue;
505                                 }
506                                 if (!spec || ((strlen(spec) < strlen(peer->name) && 
507                                                            !strncasecmp(peer->name, spec, strlen(spec))))) {
508                                                 
509                                         if (peer && (!bronly || ast_bridged_channel(peer)) &&
510                                                 !ast_check_hangup(peer) && !ast_test_flag(peer, AST_FLAG_SPYING)) {
511                                                 strncpy(peer_name, peer->name, AST_NAME_STRLEN);
512                                                 ptr = strchr(peer_name, '/');
513                                                 *ptr = '\0';
514                                                 ptr++;
515                                                 peer_name[0] = tolower(peer_name[0]);
516
517                                                 if (!silent) {
518                                                         if (ast_fileexists(peer_name, NULL, NULL) != -1) {
519                                                                 res = ast_streamfile(chan, peer_name, chan->language);
520                                                                 if (!res)
521                                                                         res = ast_waitstream(chan, "");
522                                                                 if (res)
523                                                                         break;
524                                                         } else
525                                                                 res = ast_say_character_str(chan, peer_name, "", chan->language);
526                                                         if ((num=atoi(ptr))) 
527                                                                 ast_say_digits(chan, atoi(ptr), "", chan->language);
528                                                 }
529                                                 count++;
530                                                 prev = peer;
531                                                 res = channel_spy(chan, peer, &volfactor);
532                                                 if (res == -1) {
533                                                         ast_clear_flag(chan, AST_FLAG_SPYING);
534                                                         ALL_DONE(u, -1);
535                                                 } else if (res > 1 && spec) {
536                                                         snprintf(name, AST_NAME_STRLEN, "%s/%d", spec, res);
537                                                         if (!silent)
538                                                                 ast_say_digits(chan, res, "", chan->language);
539                                                         peer=local_get_channel_by_name(name);
540                                                         continue;
541                                                 }
542                                         }
543                                 }
544                         }
545
546                         if ((peer = local_channel_walk(peer)) == NULL)
547                                 break;
548                 }
549                 waitms = count ? 100 : 5000;
550         }
551         
552
553         ast_clear_flag(chan, AST_FLAG_SPYING);
554         ALL_DONE(u, res);
555 }
556
557 int unload_module(void)
558 {
559         STANDARD_HANGUP_LOCALUSERS;
560         return ast_unregister_application(app);
561 }
562
563 int load_module(void)
564 {
565         return ast_register_application(app, chanspy_exec, synopsis, desc);
566 }
567
568 char *description(void)
569 {
570         return synopsis;
571 }
572
573 int usecount(void)
574 {
575         int res;
576         STANDARD_USECOUNT(res);
577         return res;
578 }
579
580 char *key()
581 {
582         return ASTERISK_GPL_KEY;
583 }