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