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