612e28c8b2d1c81395335eb624254e5d8b567c7c
[asterisk/asterisk.git] / channels / chan_local.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \author Mark Spencer <markster@digium.com>
22  *
23  * \brief Local Proxy Channel
24  * 
25  * \ingroup channel_drivers
26  */
27
28 #include <stdio.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/socket.h>
32 #include <errno.h>
33 #include <stdlib.h>
34 #include <fcntl.h>
35 #include <netdb.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38 #include <sys/signal.h>
39
40 #include "asterisk.h"
41
42 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43
44 #include "asterisk/lock.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/config.h"
47 #include "asterisk/logger.h"
48 #include "asterisk/module.h"
49 #include "asterisk/pbx.h"
50 #include "asterisk/options.h"
51 #include "asterisk/lock.h"
52 #include "asterisk/sched.h"
53 #include "asterisk/io.h"
54 #include "asterisk/rtp.h"
55 #include "asterisk/acl.h"
56 #include "asterisk/callerid.h"
57 #include "asterisk/file.h"
58 #include "asterisk/cli.h"
59 #include "asterisk/app.h"
60 #include "asterisk/musiconhold.h"
61 #include "asterisk/manager.h"
62
63 static const char desc[] = "Local Proxy Channel";
64 static const char type[] = "Local";
65 static const char tdesc[] = "Local Proxy Channel Driver";
66
67 static int usecnt =0;
68 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
69
70 #define IS_OUTBOUND(a,b) (a == b->chan ? 1 : 0)
71
72 /* Protect the interface list (of sip_pvt's) */
73 AST_MUTEX_DEFINE_STATIC(locallock);
74
75 static struct ast_channel *local_request(const char *type, int format, void *data, int *cause);
76 static int local_digit(struct ast_channel *ast, char digit);
77 static int local_call(struct ast_channel *ast, char *dest, int timeout);
78 static int local_hangup(struct ast_channel *ast);
79 static int local_answer(struct ast_channel *ast);
80 static struct ast_frame *local_read(struct ast_channel *ast);
81 static int local_write(struct ast_channel *ast, struct ast_frame *f);
82 static int local_indicate(struct ast_channel *ast, int condition);
83 static int local_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
84 static int local_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
85
86 /* PBX interface structure for channel registration */
87 static const struct ast_channel_tech local_tech = {
88         .type = type,
89         .description = tdesc,
90         .capabilities = -1,
91         .requester = local_request,
92         .send_digit = local_digit,
93         .call = local_call,
94         .hangup = local_hangup,
95         .answer = local_answer,
96         .read = local_read,
97         .write = local_write,
98         .exception = local_read,
99         .indicate = local_indicate,
100         .fixup = local_fixup,
101         .send_html = local_sendhtml,
102 };
103
104 static struct local_pvt {
105         ast_mutex_t lock;                       /* Channel private lock */
106         char context[AST_MAX_CONTEXT];          /* Context to call */
107         char exten[AST_MAX_EXTENSION];          /* Extension to call */
108         int reqformat;                          /* Requested format */
109         int glaredetect;                        /* Detect glare on hangup */
110         int cancelqueue;                        /* Cancel queue */
111         int alreadymasqed;                      /* Already masqueraded */
112         int launchedpbx;                        /* Did we launch the PBX */
113         int nooptimization;                     /* Don't leave masq state */
114         struct ast_channel *owner;              /* Master Channel */
115         struct ast_channel *chan;               /* Outbound channel */
116         struct local_pvt *next;                 /* Next entity */
117 } *locals = NULL;
118
119 static int local_queue_frame(struct local_pvt *p, int isoutbound, struct ast_frame *f, struct ast_channel *us)
120 {
121         struct ast_channel *other;
122 retrylock:              
123         /* Recalculate outbound channel */
124         if (isoutbound) {
125                 other = p->owner;
126         } else {
127                 other = p->chan;
128         }
129         /* Set glare detection */
130         p->glaredetect = 1;
131         if (p->cancelqueue) {
132                 /* We had a glare on the hangup.  Forget all this business,
133                 return and destroy p.  */
134                 ast_mutex_unlock(&p->lock);
135                 ast_mutex_destroy(&p->lock);
136                 free(p);
137                 return -1;
138         }
139         if (!other) {
140                 p->glaredetect = 0;
141                 return 0;
142         }
143         if (ast_mutex_trylock(&other->lock)) {
144                 /* Failed to lock.  Release main lock and try again */
145                 ast_mutex_unlock(&p->lock);
146                 if (us) {
147                         if (ast_mutex_unlock(&us->lock)) {
148                                 ast_log(LOG_WARNING, "%s wasn't locked while sending %d/%d\n",
149                                         us->name, f->frametype, f->subclass);
150                                 us = NULL;
151                         }
152                 }
153                 /* Wait just a bit */
154                 usleep(1);
155                 /* Only we can destroy ourselves, so we can't disappear here */
156                 if (us)
157                         ast_mutex_lock(&us->lock);
158                 ast_mutex_lock(&p->lock);
159                 goto retrylock;
160         }
161         ast_queue_frame(other, f);
162         ast_mutex_unlock(&other->lock);
163         p->glaredetect = 0;
164         return 0;
165 }
166
167 static int local_answer(struct ast_channel *ast)
168 {
169         struct local_pvt *p = ast->tech_pvt;
170         int isoutbound;
171         int res = -1;
172
173         ast_mutex_lock(&p->lock);
174         isoutbound = IS_OUTBOUND(ast, p);
175         if (isoutbound) {
176                 /* Pass along answer since somebody answered us */
177                 struct ast_frame answer = { AST_FRAME_CONTROL, AST_CONTROL_ANSWER };
178                 res = local_queue_frame(p, isoutbound, &answer, ast);
179         } else
180                 ast_log(LOG_WARNING, "Huh?  Local is being asked to answer?\n");
181         ast_mutex_unlock(&p->lock);
182         return res;
183 }
184
185 static void check_bridge(struct local_pvt *p, int isoutbound)
186 {
187         if (p->alreadymasqed || p->nooptimization)
188                 return;
189         if (!p->chan || !p->owner)
190                 return;
191         if (isoutbound&& p->chan->_bridge /* Not ast_bridged_channel!  Only go one step! */ && !p->owner->readq) {
192                 /* Masquerade bridged channel into owner */
193                 /* Lock everything we need, one by one, and give up if
194                    we can't get everything.  Remember, we'll get another
195                    chance in just a little bit */
196                 if (!ast_mutex_trylock(&(p->chan->_bridge)->lock)) {
197                         if (!p->chan->_bridge->_softhangup) {
198                                 if (!ast_mutex_trylock(&p->owner->lock)) {
199                                         if (!p->owner->_softhangup) {
200                                                 ast_channel_masquerade(p->owner, p->chan->_bridge);
201                                                 p->alreadymasqed = 1;
202                                         }
203                                         ast_mutex_unlock(&p->owner->lock);
204                                 }
205                                 ast_mutex_unlock(&(p->chan->_bridge)->lock);
206                         }
207                 }
208         } else if (!isoutbound && p->owner && p->owner->_bridge && p->chan && !p->chan->readq) {
209                 /* Masquerade bridged channel into chan */
210                 if (!ast_mutex_trylock(&(p->owner->_bridge)->lock)) {
211                         if (!p->owner->_bridge->_softhangup) {
212                                 if (!ast_mutex_trylock(&p->chan->lock)) {
213                                         if (!p->chan->_softhangup) {
214                                                 ast_channel_masquerade(p->chan, p->owner->_bridge);
215                                                 p->alreadymasqed = 1;
216                                         }
217                                         ast_mutex_unlock(&p->chan->lock);
218                                 }
219                         }
220                         ast_mutex_unlock(&(p->owner->_bridge)->lock);
221                 }
222         }
223 }
224
225 static struct ast_frame  *local_read(struct ast_channel *ast)
226 {
227         static struct ast_frame null = { AST_FRAME_NULL, };
228
229         return &null;
230 }
231
232 static int local_write(struct ast_channel *ast, struct ast_frame *f)
233 {
234         struct local_pvt *p = ast->tech_pvt;
235         int res = -1;
236         int isoutbound;
237
238         /* Just queue for delivery to the other side */
239         ast_mutex_lock(&p->lock);
240         isoutbound = IS_OUTBOUND(ast, p);
241         if (f && (f->frametype == AST_FRAME_VOICE)) 
242                 check_bridge(p, isoutbound);
243         if (!p->alreadymasqed)
244                 res = local_queue_frame(p, isoutbound, f, ast);
245         else {
246                 ast_log(LOG_DEBUG, "Not posting to queue since already masked on '%s'\n", ast->name);
247                 res = 0;
248         }
249         ast_mutex_unlock(&p->lock);
250         return res;
251 }
252
253 static int local_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
254 {
255         struct local_pvt *p = newchan->tech_pvt;
256         ast_mutex_lock(&p->lock);
257
258         if ((p->owner != oldchan) && (p->chan != oldchan)) {
259                 ast_log(LOG_WARNING, "Old channel wasn't %p but was %p/%p\n", oldchan, p->owner, p->chan);
260                 ast_mutex_unlock(&p->lock);
261                 return -1;
262         }
263         if (p->owner == oldchan)
264                 p->owner = newchan;
265         else
266                 p->chan = newchan;
267         ast_mutex_unlock(&p->lock);
268         return 0;
269 }
270
271 static int local_indicate(struct ast_channel *ast, int condition)
272 {
273         struct local_pvt *p = ast->tech_pvt;
274         int res = -1;
275         struct ast_frame f = { AST_FRAME_CONTROL, };
276         int isoutbound;
277
278         /* Queue up a frame representing the indication as a control frame */
279         ast_mutex_lock(&p->lock);
280         isoutbound = IS_OUTBOUND(ast, p);
281         f.subclass = condition;
282         res = local_queue_frame(p, isoutbound, &f, ast);
283         ast_mutex_unlock(&p->lock);
284         return res;
285 }
286
287 static int local_digit(struct ast_channel *ast, char digit)
288 {
289         struct local_pvt *p = ast->tech_pvt;
290         int res = -1;
291         struct ast_frame f = { AST_FRAME_DTMF, };
292         int isoutbound;
293
294         ast_mutex_lock(&p->lock);
295         isoutbound = IS_OUTBOUND(ast, p);
296         f.subclass = digit;
297         res = local_queue_frame(p, isoutbound, &f, ast);
298         ast_mutex_unlock(&p->lock);
299         return res;
300 }
301
302 static int local_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
303 {
304         struct local_pvt *p = ast->tech_pvt;
305         int res = -1;
306         struct ast_frame f = { AST_FRAME_HTML, };
307         int isoutbound;
308
309         ast_mutex_lock(&p->lock);
310         isoutbound = IS_OUTBOUND(ast, p);
311         f.subclass = subclass;
312         f.data = (char *)data;
313         f.datalen = datalen;
314         res = local_queue_frame(p, isoutbound, &f, ast);
315         ast_mutex_unlock(&p->lock);
316         return res;
317 }
318
319 /*--- local_call: Initiate new call, part of PBX interface */
320 /*      dest is the dial string */
321 static int local_call(struct ast_channel *ast, char *dest, int timeout)
322 {
323         struct local_pvt *p = ast->tech_pvt;
324         int res;
325         struct ast_var_t *varptr = NULL, *new;
326         size_t len, namelen;
327         
328         ast_mutex_lock(&p->lock);
329
330         p->chan->cid.cid_num = ast_strdup(p->owner->cid.cid_num);
331         p->chan->cid.cid_name = ast_strdup(p->owner->cid.cid_name);
332         p->chan->cid.cid_rdnis = ast_strdup(p->owner->cid.cid_rdnis);
333         p->chan->cid.cid_ani = ast_strdup(p->owner->cid.cid_ani);
334
335         strncpy(p->chan->language, p->owner->language, sizeof(p->chan->language) - 1);
336         strncpy(p->chan->accountcode, p->owner->accountcode, sizeof(p->chan->accountcode) - 1);
337         p->chan->cdrflags = p->owner->cdrflags;
338
339         /* copy the channel variables from the incoming channel to the outgoing channel */
340         /* Note that due to certain assumptions, they MUST be in the same order */
341         AST_LIST_TRAVERSE(&p->owner->varshead, varptr, entries) {
342                 namelen = strlen(varptr->name);
343                 len = sizeof(struct ast_var_t) + namelen + strlen(varptr->value) + 2;
344                 if ((new = ast_calloc(1, len))) {
345                         memcpy(new, varptr, len);
346                         new->value = &(new->name[0]) + namelen + 1;
347                         AST_LIST_INSERT_TAIL(&p->chan->varshead, new, entries);
348                 }
349         }
350
351         p->launchedpbx = 1;
352
353         /* Start switch on sub channel */
354         res = ast_pbx_start(p->chan);
355         ast_mutex_unlock(&p->lock);
356         return res;
357 }
358
359 #if 0
360 static void local_destroy(struct local_pvt *p)
361 {
362         struct local_pvt *cur, *prev = NULL;
363         ast_mutex_lock(&locallock);
364         cur = locals;
365         while(cur) {
366                 if (cur == p) {
367                         if (prev)
368                                 prev->next = cur->next;
369                         else
370                                 locals = cur->next;
371                         ast_mutex_destroy(cur);
372                         free(cur);
373                         break;
374                 }
375                 prev = cur;
376                 cur = cur->next;
377         }
378         ast_mutex_unlock(&locallock);
379         if (!cur)
380                 ast_log(LOG_WARNING, "Unable ot find local '%s@%s' in local list\n", p->exten, p->context);
381 }
382 #endif
383
384 /*--- local_hangup: Hangup a call through the local proxy channel */
385 static int local_hangup(struct ast_channel *ast)
386 {
387         struct local_pvt *p = ast->tech_pvt;
388         int isoutbound;
389         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
390         struct local_pvt *cur, *prev=NULL;
391         struct ast_channel *ochan = NULL;
392         int glaredetect;
393         char *status;
394
395         ast_mutex_lock(&p->lock);
396         isoutbound = IS_OUTBOUND(ast, p);
397         if (isoutbound) {
398                 status = pbx_builtin_getvar_helper(p->chan, "DIALSTATUS");
399                 if(status)
400                         pbx_builtin_setvar_helper(p->owner, "CHANLOCALSTATUS", status);
401                 p->chan = NULL;
402                 p->launchedpbx = 0;
403         } else
404                 p->owner = NULL;
405         ast->tech_pvt = NULL;
406         
407         ast_mutex_lock(&usecnt_lock);
408         usecnt--;
409         ast_mutex_unlock(&usecnt_lock);
410         
411         if (!p->owner && !p->chan) {
412                 /* Okay, done with the private part now, too. */
413                 glaredetect = p->glaredetect;
414                 /* If we have a queue holding, don't actually destroy p yet, but
415                    let local_queue do it. */
416                 if (p->glaredetect)
417                         p->cancelqueue = 1;
418                 ast_mutex_unlock(&p->lock);
419                 /* Remove from list */
420                 ast_mutex_lock(&locallock);
421                 cur = locals;
422                 while(cur) {
423                         if (cur == p) {
424                                 if (prev)
425                                         prev->next = cur->next;
426                                 else
427                                         locals = cur->next;
428                                 break;
429                         }
430                         prev = cur;
431                         cur = cur->next;
432                 }
433                 ast_mutex_unlock(&locallock);
434                 /* Grab / release lock just in case */
435                 ast_mutex_lock(&p->lock);
436                 ast_mutex_unlock(&p->lock);
437                 /* And destroy */
438                 if (!glaredetect) {
439                         ast_mutex_destroy(&p->lock);
440                         free(p);
441                 }
442                 return 0;
443         }
444         if (p->chan && !p->launchedpbx)
445                 /* Need to actually hangup since there is no PBX */
446                 ochan = p->chan;
447         else
448                 local_queue_frame(p, isoutbound, &f, NULL);
449         ast_mutex_unlock(&p->lock);
450         if (ochan)
451                 ast_hangup(ochan);
452         return 0;
453 }
454
455 /*--- local_alloc: Create a call structure */
456 static struct local_pvt *local_alloc(char *data, int format)
457 {
458         struct local_pvt *tmp;
459         char *c;
460         char *opts;
461
462         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
463                 return NULL;
464         
465         ast_mutex_init(&tmp->lock);
466         strncpy(tmp->exten, data, sizeof(tmp->exten) - 1);
467         opts = strchr(tmp->exten, '/');
468         if (opts) {
469                 *opts='\0';
470                 opts++;
471                 if (strchr(opts, 'n'))
472                         tmp->nooptimization = 1;
473         }
474         c = strchr(tmp->exten, '@');
475         if (c) {
476                 *c = '\0';
477                 c++;
478                 strncpy(tmp->context, c, sizeof(tmp->context) - 1);
479         } else
480                 strncpy(tmp->context, "default", sizeof(tmp->context) - 1);
481         tmp->reqformat = format;
482         if (!ast_exists_extension(NULL, tmp->context, tmp->exten, 1, NULL)) {
483                 ast_log(LOG_NOTICE, "No such extension/context %s@%s creating local channel\n", tmp->exten, tmp->context);
484                 ast_mutex_destroy(&tmp->lock);
485                 free(tmp);
486                 tmp = NULL;
487         } else {
488                 /* Add to list */
489                 ast_mutex_lock(&locallock);
490                 tmp->next = locals;
491                 locals = tmp;
492                 ast_mutex_unlock(&locallock);
493         }
494         
495         return tmp;
496 }
497
498 /*--- local_new: Start new local channel */
499 static struct ast_channel *local_new(struct local_pvt *p, int state)
500 {
501         struct ast_channel *tmp, *tmp2;
502         int randnum = rand() & 0xffff;
503
504         tmp = ast_channel_alloc(1);
505         tmp2 = ast_channel_alloc(1);
506         if (!tmp || !tmp2) {
507                 if (tmp)
508                         ast_channel_free(tmp);
509                 if (tmp2)
510                         ast_channel_free(tmp2);
511                 ast_log(LOG_WARNING, "Unable to allocate channel structure(s)\n");
512                 return NULL;
513         } 
514
515         tmp2->tech = tmp->tech = &local_tech;
516         tmp->nativeformats = p->reqformat;
517         tmp2->nativeformats = p->reqformat;
518         snprintf(tmp->name, sizeof(tmp->name), "Local/%s@%s-%04x,1", p->exten, p->context, randnum);
519         snprintf(tmp2->name, sizeof(tmp2->name), "Local/%s@%s-%04x,2", p->exten, p->context, randnum);
520         tmp->type = type;
521         tmp2->type = type;
522         ast_setstate(tmp, state);
523         ast_setstate(tmp2, AST_STATE_RING);
524         tmp->writeformat = p->reqformat;
525         tmp2->writeformat = p->reqformat;
526         tmp->rawwriteformat = p->reqformat;
527         tmp2->rawwriteformat = p->reqformat;
528         tmp->readformat = p->reqformat;
529         tmp2->readformat = p->reqformat;
530         tmp->rawreadformat = p->reqformat;
531         tmp2->rawreadformat = p->reqformat;
532         tmp->tech_pvt = p;
533         tmp2->tech_pvt = p;
534         p->owner = tmp;
535         p->chan = tmp2;
536         ast_mutex_lock(&usecnt_lock);
537         usecnt++;
538         usecnt++;
539         ast_mutex_unlock(&usecnt_lock);
540         ast_update_use_count();
541         ast_copy_string(tmp->context, p->context, sizeof(tmp->context));
542         ast_copy_string(tmp2->context, p->context, sizeof(tmp2->context));
543         ast_copy_string(tmp2->exten, p->exten, sizeof(tmp->exten));
544         tmp->priority = 1;
545         tmp2->priority = 1;
546
547         return tmp;
548 }
549
550
551 /*--- local_request: Part of PBX interface */
552 static struct ast_channel *local_request(const char *type, int format, void *data, int *cause)
553 {
554         struct local_pvt *p;
555         struct ast_channel *chan = NULL;
556
557         p = local_alloc(data, format);
558         if (p)
559                 chan = local_new(p, AST_STATE_DOWN);
560         return chan;
561 }
562
563 /*--- locals_show: CLI command "local show channels" */
564 static int locals_show(int fd, int argc, char **argv)
565 {
566         struct local_pvt *p;
567
568         if (argc != 3)
569                 return RESULT_SHOWUSAGE;
570         ast_mutex_lock(&locallock);
571         p = locals;
572         while(p) {
573                 ast_mutex_lock(&p->lock);
574                 ast_cli(fd, "%s -- %s@%s\n", p->owner ? p->owner->name : "<unowned>", p->exten, p->context);
575                 ast_mutex_unlock(&p->lock);
576                 p = p->next;
577         }
578         if (!locals)
579                 ast_cli(fd, "No local channels in use\n");
580         ast_mutex_unlock(&locallock);
581         return RESULT_SUCCESS;
582 }
583
584 static char show_locals_usage[] = 
585 "Usage: local show channels\n"
586 "       Provides summary information on active local proxy channels.\n";
587
588 static struct ast_cli_entry cli_show_locals = {
589         { "local", "show", "channels", NULL }, locals_show, 
590         "Show status of local channels", show_locals_usage, NULL };
591
592 /*--- load_module: Load module into PBX, register channel */
593 int load_module()
594 {
595         /* Make sure we can register our channel type */
596         if (ast_channel_register(&local_tech)) {
597                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
598                 return -1;
599         }
600         ast_cli_register(&cli_show_locals);
601         return 0;
602 }
603
604 /*--- reload: Reload module */
605 int reload()
606 {
607         return 0;
608 }
609
610 /*--- unload_module: Unload the local proxy channel from Asterisk */
611 int unload_module()
612 {
613         struct local_pvt *p;
614
615         /* First, take us out of the channel loop */
616         ast_cli_unregister(&cli_show_locals);
617         ast_channel_unregister(&local_tech);
618         if (!ast_mutex_lock(&locallock)) {
619                 /* Hangup all interfaces if they have an owner */
620                 p = locals;
621                 while(p) {
622                         if (p->owner)
623                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
624                         p = p->next;
625                 }
626                 locals = NULL;
627                 ast_mutex_unlock(&locallock);
628         } else {
629                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
630                 return -1;
631         }               
632         return 0;
633 }
634
635 int usecount()
636 {
637         return usecnt;
638 }
639
640 char *key()
641 {
642         return ASTERISK_GPL_KEY;
643 }
644
645 char *description()
646 {
647         return (char *) desc;
648 }
649