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