remove some more local declarations of null frames
[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         return &ast_null_frame;
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 /*! \brief 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
328         p->chan->cid.cid_num = ast_strdup(p->owner->cid.cid_num);
329         p->chan->cid.cid_name = ast_strdup(p->owner->cid.cid_name);
330         p->chan->cid.cid_rdnis = ast_strdup(p->owner->cid.cid_rdnis);
331         p->chan->cid.cid_ani = ast_strdup(p->owner->cid.cid_ani);
332
333         strncpy(p->chan->language, p->owner->language, sizeof(p->chan->language) - 1);
334         strncpy(p->chan->accountcode, p->owner->accountcode, sizeof(p->chan->accountcode) - 1);
335         p->chan->cdrflags = p->owner->cdrflags;
336
337         /* copy the channel variables from the incoming channel to the outgoing channel */
338         /* Note that due to certain assumptions, they MUST be in the same order */
339         AST_LIST_TRAVERSE(&p->owner->varshead, varptr, entries) {
340                 namelen = strlen(varptr->name);
341                 len = sizeof(struct ast_var_t) + namelen + strlen(varptr->value) + 2;
342                 if ((new = ast_calloc(1, len))) {
343                         memcpy(new, varptr, len);
344                         new->value = &(new->name[0]) + namelen + 1;
345                         AST_LIST_INSERT_TAIL(&p->chan->varshead, new, entries);
346                 }
347         }
348
349         p->launchedpbx = 1;
350
351         /* Start switch on sub channel */
352         res = ast_pbx_start(p->chan);
353         ast_mutex_unlock(&p->lock);
354         return res;
355 }
356
357 #if 0
358 static void local_destroy(struct local_pvt *p)
359 {
360         struct local_pvt *cur, *prev = NULL;
361         ast_mutex_lock(&locallock);
362         cur = locals;
363         while(cur) {
364                 if (cur == p) {
365                         if (prev)
366                                 prev->next = cur->next;
367                         else
368                                 locals = cur->next;
369                         ast_mutex_destroy(cur);
370                         free(cur);
371                         break;
372                 }
373                 prev = cur;
374                 cur = cur->next;
375         }
376         ast_mutex_unlock(&locallock);
377         if (!cur)
378                 ast_log(LOG_WARNING, "Unable ot find local '%s@%s' in local list\n", p->exten, p->context);
379 }
380 #endif
381
382 /*! \brief Hangup a call through the local proxy channel */
383 static int local_hangup(struct ast_channel *ast)
384 {
385         struct local_pvt *p = ast->tech_pvt;
386         int isoutbound;
387         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
388         struct local_pvt *cur, *prev=NULL;
389         struct ast_channel *ochan = NULL;
390         int glaredetect;
391         const char *status;
392
393         ast_mutex_lock(&p->lock);
394         isoutbound = IS_OUTBOUND(ast, p);
395         if (isoutbound) {
396                 status = pbx_builtin_getvar_helper(p->chan, "DIALSTATUS");
397                 if(status)
398                         pbx_builtin_setvar_helper(p->owner, "CHANLOCALSTATUS", status);
399                 p->chan = NULL;
400                 p->launchedpbx = 0;
401         } else
402                 p->owner = NULL;
403         ast->tech_pvt = NULL;
404         
405         ast_mutex_lock(&usecnt_lock);
406         usecnt--;
407         ast_mutex_unlock(&usecnt_lock);
408         
409         if (!p->owner && !p->chan) {
410                 /* Okay, done with the private part now, too. */
411                 glaredetect = p->glaredetect;
412                 /* If we have a queue holding, don't actually destroy p yet, but
413                    let local_queue do it. */
414                 if (p->glaredetect)
415                         p->cancelqueue = 1;
416                 ast_mutex_unlock(&p->lock);
417                 /* Remove from list */
418                 ast_mutex_lock(&locallock);
419                 cur = locals;
420                 while(cur) {
421                         if (cur == p) {
422                                 if (prev)
423                                         prev->next = cur->next;
424                                 else
425                                         locals = cur->next;
426                                 break;
427                         }
428                         prev = cur;
429                         cur = cur->next;
430                 }
431                 ast_mutex_unlock(&locallock);
432                 /* Grab / release lock just in case */
433                 ast_mutex_lock(&p->lock);
434                 ast_mutex_unlock(&p->lock);
435                 /* And destroy */
436                 if (!glaredetect) {
437                         ast_mutex_destroy(&p->lock);
438                         free(p);
439                 }
440                 return 0;
441         }
442         if (p->chan && !p->launchedpbx)
443                 /* Need to actually hangup since there is no PBX */
444                 ochan = p->chan;
445         else
446                 local_queue_frame(p, isoutbound, &f, NULL);
447         ast_mutex_unlock(&p->lock);
448         if (ochan)
449                 ast_hangup(ochan);
450         return 0;
451 }
452
453 /*! \brief Create a call structure */
454 static struct local_pvt *local_alloc(char *data, int format)
455 {
456         struct local_pvt *tmp;
457         char *c;
458         char *opts;
459
460         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
461                 return NULL;
462         
463         ast_mutex_init(&tmp->lock);
464         strncpy(tmp->exten, data, sizeof(tmp->exten) - 1);
465         opts = strchr(tmp->exten, '/');
466         if (opts) {
467                 *opts='\0';
468                 opts++;
469                 if (strchr(opts, 'n'))
470                         tmp->nooptimization = 1;
471         }
472         c = strchr(tmp->exten, '@');
473         if (c) {
474                 *c = '\0';
475                 c++;
476                 strncpy(tmp->context, c, sizeof(tmp->context) - 1);
477         } else
478                 strncpy(tmp->context, "default", sizeof(tmp->context) - 1);
479         tmp->reqformat = format;
480         if (!ast_exists_extension(NULL, tmp->context, tmp->exten, 1, NULL)) {
481                 ast_log(LOG_NOTICE, "No such extension/context %s@%s creating local channel\n", tmp->exten, tmp->context);
482                 ast_mutex_destroy(&tmp->lock);
483                 free(tmp);
484                 tmp = NULL;
485         } else {
486                 /* Add to list */
487                 ast_mutex_lock(&locallock);
488                 tmp->next = locals;
489                 locals = tmp;
490                 ast_mutex_unlock(&locallock);
491         }
492         
493         return tmp;
494 }
495
496 /*! \brief Start new local channel */
497 static struct ast_channel *local_new(struct local_pvt *p, int state)
498 {
499         struct ast_channel *tmp, *tmp2;
500         int randnum = rand() & 0xffff;
501
502         tmp = ast_channel_alloc(1);
503         tmp2 = ast_channel_alloc(1);
504         if (!tmp || !tmp2) {
505                 if (tmp)
506                         ast_channel_free(tmp);
507                 if (tmp2)
508                         ast_channel_free(tmp2);
509                 ast_log(LOG_WARNING, "Unable to allocate channel structure(s)\n");
510                 return NULL;
511         } 
512
513         tmp2->tech = tmp->tech = &local_tech;
514         tmp->nativeformats = p->reqformat;
515         tmp2->nativeformats = p->reqformat;
516         snprintf(tmp->name, sizeof(tmp->name), "Local/%s@%s-%04x,1", p->exten, p->context, randnum);
517         snprintf(tmp2->name, sizeof(tmp2->name), "Local/%s@%s-%04x,2", p->exten, p->context, randnum);
518         tmp->type = type;
519         tmp2->type = type;
520         ast_setstate(tmp, state);
521         ast_setstate(tmp2, AST_STATE_RING);
522         tmp->writeformat = p->reqformat;
523         tmp2->writeformat = p->reqformat;
524         tmp->rawwriteformat = p->reqformat;
525         tmp2->rawwriteformat = p->reqformat;
526         tmp->readformat = p->reqformat;
527         tmp2->readformat = p->reqformat;
528         tmp->rawreadformat = p->reqformat;
529         tmp2->rawreadformat = p->reqformat;
530         tmp->tech_pvt = p;
531         tmp2->tech_pvt = p;
532         p->owner = tmp;
533         p->chan = tmp2;
534         ast_mutex_lock(&usecnt_lock);
535         usecnt++;
536         usecnt++;
537         ast_mutex_unlock(&usecnt_lock);
538         ast_update_use_count();
539         ast_copy_string(tmp->context, p->context, sizeof(tmp->context));
540         ast_copy_string(tmp2->context, p->context, sizeof(tmp2->context));
541         ast_copy_string(tmp2->exten, p->exten, sizeof(tmp->exten));
542         tmp->priority = 1;
543         tmp2->priority = 1;
544
545         return tmp;
546 }
547
548
549 /*! \brief Part of PBX interface */
550 static struct ast_channel *local_request(const char *type, int format, void *data, int *cause)
551 {
552         struct local_pvt *p;
553         struct ast_channel *chan = NULL;
554
555         p = local_alloc(data, format);
556         if (p)
557                 chan = local_new(p, AST_STATE_DOWN);
558         return chan;
559 }
560
561 /*! \brief CLI command "local show channels" */
562 static int locals_show(int fd, int argc, char **argv)
563 {
564         struct local_pvt *p;
565
566         if (argc != 3)
567                 return RESULT_SHOWUSAGE;
568         ast_mutex_lock(&locallock);
569         p = locals;
570         while(p) {
571                 ast_mutex_lock(&p->lock);
572                 ast_cli(fd, "%s -- %s@%s\n", p->owner ? p->owner->name : "<unowned>", p->exten, p->context);
573                 ast_mutex_unlock(&p->lock);
574                 p = p->next;
575         }
576         if (!locals)
577                 ast_cli(fd, "No local channels in use\n");
578         ast_mutex_unlock(&locallock);
579         return RESULT_SUCCESS;
580 }
581
582 static char show_locals_usage[] = 
583 "Usage: local show channels\n"
584 "       Provides summary information on active local proxy channels.\n";
585
586 static struct ast_cli_entry cli_show_locals = {
587         { "local", "show", "channels", NULL }, locals_show, 
588         "Show status of local channels", show_locals_usage, NULL };
589
590 /*! \brief Load module into PBX, register channel */
591 int load_module()
592 {
593         /* Make sure we can register our channel type */
594         if (ast_channel_register(&local_tech)) {
595                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
596                 return -1;
597         }
598         ast_cli_register(&cli_show_locals);
599         return 0;
600 }
601
602 /*! \brief Reload module */
603 int reload()
604 {
605         return 0;
606 }
607
608 /*! \brief Unload the local proxy channel from Asterisk */
609 int unload_module()
610 {
611         struct local_pvt *p;
612
613         /* First, take us out of the channel loop */
614         ast_cli_unregister(&cli_show_locals);
615         ast_channel_unregister(&local_tech);
616         if (!ast_mutex_lock(&locallock)) {
617                 /* Hangup all interfaces if they have an owner */
618                 p = locals;
619                 while(p) {
620                         if (p->owner)
621                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
622                         p = p->next;
623                 }
624                 locals = NULL;
625                 ast_mutex_unlock(&locallock);
626         } else {
627                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
628                 return -1;
629         }               
630         return 0;
631 }
632
633 int usecount()
634 {
635         return usecnt;
636 }
637
638 char *key()
639 {
640         return ASTERISK_GPL_KEY;
641 }
642
643 char *description()
644 {
645         return (char *) desc;
646 }
647