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