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