remove header that no longer exists
[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
188         if (f0 && f1) {
189                 if (!csth->trans0) {
190                         if (f0->subclass != AST_FORMAT_SLINEAR && (csth->trans0 = ast_translator_build_path(AST_FORMAT_SLINEAR, f0->subclass)) == NULL) {
191                                 ast_log(LOG_WARNING, "Cannot build a path from %s to slin\n", ast_getformatname(f0->subclass));
192                                 return -1;
193                         }
194                         if (!csth->trans1) {
195                                 if (f1->subclass == f0->subclass) {
196                                         csth->trans1 = csth->trans0;
197                                 } else if (f1->subclass != AST_FORMAT_SLINEAR && (csth->trans1 = ast_translator_build_path(AST_FORMAT_SLINEAR, f1->subclass)) == NULL) {
198                                         ast_log(LOG_WARNING, "Cannot build a path from %s to slin\n", ast_getformatname(f1->subclass));
199                                         return -1;
200                                 }
201                                 
202                         }
203                 }
204
205                 memset(buf, 0, sizeof(buf));
206                 memset(buf0, 0, sizeof(buf0));
207                 memset(buf1, 0, sizeof(buf1));
208                 if (csth->trans0) {
209                         if ((f = ast_translate(csth->trans0, f0, 0))) {
210                                 framelen_a = f->datalen * sizeof(short);
211                                 memcpy(buf0, f->data, framelen_a);
212                                 ast_frfree(f);
213                         } else 
214                                 return 0;
215                 } else {
216                         framelen_a = f0->datalen * sizeof(short);
217                         memcpy(buf0, f0->data, framelen_a);
218                 }
219                 if (csth->trans1) {
220                         if ((f = ast_translate(csth->trans1, f1, 0))) {
221                                 framelen_b = f->datalen * sizeof(short);
222                                 memcpy(buf1, f->data, framelen_b);
223                                 ast_frfree(f);
224                         } else 
225                                 return 0;
226                 } else {
227                         framelen_b = f1->datalen * sizeof(short);
228                         memcpy(buf1, f1->data, framelen_b);
229                 }
230                 size = find_smallest_of_three(len, framelen_a, framelen_b);
231
232                 vf = get_volfactor(csth->volfactor);
233                 vf = minmax(vf, 16);
234                 for(x=0; x < size; x++) {
235                         if (vf < 0) {
236                                 buf0[x] /= abs(vf);
237                                 buf1[x] /= abs(vf);
238                         } else if (vf > 0) {
239                                 buf0[x] *= vf;
240                                 buf1[x] *= vf;
241                         }
242                         buf[x] = ast_fit_in_short(buf0[x] + buf1[x]);
243                 }
244                 memset(&write_frame, 0, sizeof(write_frame));
245                 write_frame.frametype = AST_FRAME_VOICE;
246                 write_frame.subclass = AST_FORMAT_SLINEAR;
247                 write_frame.datalen = size;
248                 write_frame.samples = size;
249                 write_frame.data = buf;
250                 write_frame.offset = 0;
251                 ast_write(chan, &write_frame);
252         } else {
253                 nc++;
254                 if(nc > 1) {
255                         return -1;
256                 }
257         }
258         
259         if (f0)
260                 ast_frfree(f0);
261         if (f1) 
262                 ast_frfree(f1);
263
264         return 0;
265
266 }
267
268 static struct ast_generator spygen = {
269     alloc: spy_alloc, 
270     release: spy_release, 
271     generate: spy_generate, 
272 };
273
274 static void start_spying(struct ast_channel *chan, struct ast_channel *spychan, struct ast_channel_spy *spy) 
275 {
276
277         struct ast_channel_spy *cptr=NULL;
278         struct ast_channel *peer;
279
280
281         ast_log(LOG_WARNING, "Attaching %s to %s\n", spychan->name, chan->name);
282
283
284         ast_mutex_lock(&chan->lock);
285         if (chan->spiers) {
286                 for(cptr=chan->spiers;cptr && cptr->next;cptr=cptr->next);
287                 cptr->next = spy;
288         } else {
289                 chan->spiers = spy;
290         }
291         ast_mutex_unlock(&chan->lock);
292         if ( ast_test_flag(chan, AST_FLAG_NBRIDGE) && (peer = ast_bridged_channel(chan))) {
293                 ast_softhangup(peer, AST_SOFTHANGUP_UNBRIDGE);  
294         }
295
296 }
297
298 static void stop_spying(struct ast_channel *chan, struct ast_channel_spy *spy) 
299 {
300         struct ast_channel_spy *cptr=NULL, *prev=NULL;
301         int count = 0;
302
303         while(ast_mutex_trylock(&chan->lock)) {
304                 /* if its locked already it's almost surely hanging up and we are too late 
305                    we can safely remove the head pointer if it points at us without needing a lock.
306                    since everybody spying will be in the same boat whomever is pointing at the head
307                    will surely erase it which is all we really need since it's a linked list of
308                    staticly declared structs that belong to each spy.
309                 */
310                 if (chan->spiers == spy) {
311                         chan->spiers = NULL;
312                         return;
313                 }
314                 count++;
315                 if(count > 10) {
316                         return;
317                 }
318                 sched_yield();
319         }
320
321         for(cptr=chan->spiers; cptr; cptr=cptr->next) {
322                 if (cptr == spy) {
323                         if (prev) {
324                                 prev->next = cptr->next;
325                                 cptr->next = NULL;
326                         } else
327                                 chan->spiers = NULL;
328                 }
329                 prev = cptr;
330         }
331         ast_mutex_unlock(&chan->lock);
332
333 }
334
335 static int channel_spy(struct ast_channel *chan, struct ast_channel *spyee, int *volfactor) 
336 {
337         struct chanspy_translation_helper csth;
338         int running = 1, res = 0, x = 0;
339         char inp[24];
340         char *name=NULL;
341         struct ast_channel_spy spy;
342
343         if (chan && !ast_check_hangup(chan) && spyee && !ast_check_hangup(spyee)) {
344                 memset(inp, 0, sizeof(inp));
345                 name = ast_strdupa(spyee->name);
346                 if (option_verbose >= 2)
347                         ast_verbose(VERBOSE_PREFIX_2 "Spying on channel %s\n", name);
348                 
349                 memset(&spy, 0, sizeof(struct ast_channel_spy));
350                 spy.status = CHANSPY_RUNNING;
351                 ast_mutex_init(&spy.lock);
352                 start_spying(spyee, chan, &spy);
353                 
354                 memset(&csth, 0, sizeof(csth));
355                 csth.volfactor = *volfactor;
356                 csth.spy = &spy;
357                 ast_activate_generator(chan, &spygen, &csth);
358
359                 while(spy.status == CHANSPY_RUNNING && chan && !ast_check_hangup(chan) && spyee && !ast_check_hangup(spyee) && running == 1) {
360                         res = ast_waitfordigit(chan, 100);
361
362                         if (x == sizeof(inp)) {
363                                 x = 0;
364                         }
365                         if (res < 0) {
366                                 running = -1;
367                         }
368                         if (res == 0) {
369                                 continue;
370                         } else if (res == '*') {
371                                 running = 0; 
372                         } else if (res == '#') {
373                                 if (!ast_strlen_zero(inp)) {
374                                         running = x ? atoi(inp) : -1;
375                                         break;
376                                 } else {
377                                         csth.volfactor++;
378                                         if (csth.volfactor > 4) {
379                                                 csth.volfactor = -4;
380                                         }
381                                         if (option_verbose > 2) {
382                                                 ast_verbose(VERBOSE_PREFIX_3"Setting spy volume on %s to %d\n", chan->name, csth.volfactor);
383                                         }
384                                         *volfactor = csth.volfactor;
385                                 }
386                         } else if (res >= 48 && res <= 57) {
387                                 inp[x++] = res;
388                         }
389                 }
390                 ast_deactivate_generator(chan);
391                 stop_spying(spyee, &spy);
392
393                 if (option_verbose >= 2)
394                         ast_verbose(VERBOSE_PREFIX_2 "Done Spying on channel %s\n", name);
395
396                 ast_flush_spy_queue(&spy);
397         } else {
398                 running = 0;
399         }
400         ast_mutex_destroy(&spy.lock);
401         return running;
402 }
403
404
405
406 static int chanspy_exec(struct ast_channel *chan, void *data)
407 {
408         int res=-1;
409         struct localuser *u;
410         struct ast_channel *peer=NULL, *prev=NULL;
411         char *ptr=NULL;
412         char name[AST_NAME_STRLEN], peer_name[AST_NAME_STRLEN];
413         int count=0, waitms=100, num=0;
414         char *args;
415         struct ast_flags flags;
416         char *options=NULL;
417         char *spec = NULL;
418         int volfactor=0;
419         int silent=0;
420         int argc = 0;
421         char *argv[5];
422         char *mygroup = NULL;
423         int bronly = 0;
424
425
426         if (!(args = ast_strdupa((char *)data))) {
427                 ast_log(LOG_ERROR, "Out of memory!\n");
428                 return -1;
429         }
430
431         if (ast_set_read_format(chan, AST_FORMAT_SLINEAR) < 0) {
432                 ast_log(LOG_ERROR, "Could Not Set Read Format.\n");
433                 return -1;
434         }
435         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
436                 ast_log(LOG_ERROR, "Could Not Set Write Format.\n");
437                 return -1;
438         }
439
440         LOCAL_USER_ADD(u);
441         ast_answer(chan);
442
443         ast_set_flag(chan, AST_FLAG_SPYING); /* so nobody can spy on us while we are spying */
444
445
446         if ((argc = ast_separate_app_args(args, '|', argv, sizeof(argv) / sizeof(argv[0])))) {
447                 spec = argv[0];
448                 if ( argc > 1) {
449                         options = argv[1];
450                 }
451                 if (ast_strlen_zero(spec) || !strcmp(spec, "all")) {
452                         spec = NULL;
453                 }
454         }
455         
456         if (options) {
457                 char *opts[2];
458                 ast_parseoptions(chanspy_opts, &flags, opts, options);
459                 if (ast_test_flag(&flags, OPTION_GROUP))
460                         mygroup = opts[0];
461                 silent = ast_test_flag(&flags, OPTION_QUIET);
462                 bronly = ast_test_flag(&flags, OPTION_BRIDGED);
463                 if (ast_test_flag(&flags, OPTION_VOLUME) && opts[1]) {
464                         if (sscanf(opts[1], "%d", &volfactor) != 1)
465                                 ast_log(LOG_NOTICE, "volfactor must be a number between -16 and 16\n");
466                         else if (volfactor > 16)
467                                 volfactor = 16;
468                         else if (volfactor < -16)
469                                 volfactor = -16;
470                 }
471         }
472
473
474         for(;;) {
475                 res = ast_streamfile(chan, "beep", chan->language);
476                 if (!res)
477                         res = ast_waitstream(chan, "");
478                 if (res < 0) {
479                         ast_clear_flag(chan, AST_FLAG_SPYING);
480                         ALL_DONE(u, -1);
481                 }                       
482
483                 count = 0;
484                 res = ast_waitfordigit(chan, waitms);
485                 if (res < 0) {
486                         ast_clear_flag(chan, AST_FLAG_SPYING);
487                         ALL_DONE(u, -1);
488                 }
489                                 
490                 peer = local_channel_walk(NULL);
491                 prev=NULL;
492                 while(peer) {
493                         if (peer != chan) {
494                                 char *group = NULL;
495
496                                 if (peer == prev) {
497                                         break;
498                                 }
499
500                                 group = pbx_builtin_getvar_helper(chan, "SPYGROUP");
501
502                                 if (mygroup && group && strcmp(group, mygroup)) { 
503                                         continue;
504                                 }
505                                 if (!spec || ((strlen(spec) < strlen(peer->name) && 
506                                                            !strncasecmp(peer->name, spec, strlen(spec))))) {
507                                                 
508                                         if (peer && (!bronly || ast_bridged_channel(peer)) &&
509                                                 !ast_check_hangup(peer) && !ast_test_flag(peer, AST_FLAG_SPYING)) {
510                                                 strncpy(peer_name, peer->name, AST_NAME_STRLEN);
511                                                 ptr = strchr(peer_name, '/');
512                                                 *ptr = '\0';
513                                                 ptr++;
514                                                 peer_name[0] = tolower(peer_name[0]);
515
516                                                 if (!silent) {
517                                                         if (ast_fileexists(peer_name, NULL, NULL) != -1) {
518                                                                 res = ast_streamfile(chan, peer_name, chan->language);
519                                                                 if (!res)
520                                                                         res = ast_waitstream(chan, "");
521                                                                 if (res)
522                                                                         break;
523                                                         } else
524                                                                 res = ast_say_character_str(chan, peer_name, "", chan->language);
525                                                         if ((num=atoi(ptr))) 
526                                                                 ast_say_digits(chan, atoi(ptr), "", chan->language);
527                                                 }
528                                                 count++;
529                                                 prev = peer;
530                                                 res = channel_spy(chan, peer, &volfactor);
531                                                 if (res == -1) {
532                                                         ast_clear_flag(chan, AST_FLAG_SPYING);
533                                                         ALL_DONE(u, -1);
534                                                 } else if (res > 1 && spec) {
535                                                         snprintf(name, AST_NAME_STRLEN, "%s/%d", spec, res);
536                                                         if (!silent)
537                                                                 ast_say_digits(chan, res, "", chan->language);
538                                                         peer=local_get_channel_by_name(name);
539                                                         continue;
540                                                 }
541                                         }
542                                 }
543                         }
544
545                         if ((peer = local_channel_walk(peer)) == NULL)
546                                 break;
547                 }
548                 waitms = count ? 100 : 5000;
549         }
550         
551
552         ast_clear_flag(chan, AST_FLAG_SPYING);
553         ALL_DONE(u, res);
554 }
555
556 int unload_module(void)
557 {
558         STANDARD_HANGUP_LOCALUSERS;
559         return ast_unregister_application(app);
560 }
561
562 int load_module(void)
563 {
564         return ast_register_application(app, chanspy_exec, synopsis, desc);
565 }
566
567 char *description(void)
568 {
569         return synopsis;
570 }
571
572 int usecount(void)
573 {
574         int res;
575         STANDARD_USECOUNT(res);
576         return res;
577 }
578
579 char *key()
580 {
581         return ASTERISK_GPL_KEY;
582 }