Really fix chan local races (I hope)
[asterisk/asterisk.git] / channels / chan_local.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Local Proxy Channel
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <pthread.h>
16 #include <string.h>
17 #include <asterisk/lock.h>
18 #include <asterisk/channel.h>
19 #include <asterisk/channel_pvt.h>
20 #include <asterisk/config.h>
21 #include <asterisk/logger.h>
22 #include <asterisk/module.h>
23 #include <asterisk/pbx.h>
24 #include <asterisk/options.h>
25 #include <asterisk/lock.h>
26 #include <asterisk/sched.h>
27 #include <asterisk/io.h>
28 #include <asterisk/rtp.h>
29 #include <asterisk/acl.h>
30 #include <asterisk/callerid.h>
31 #include <asterisk/file.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/app.h>
34 #include <asterisk/musiconhold.h>
35 #include <asterisk/manager.h>
36 #include <sys/socket.h>
37 #include <errno.h>
38 #include <unistd.h>
39 #include <stdlib.h>
40 #include <fcntl.h>
41 #include <netdb.h>
42 #include <arpa/inet.h>
43 #include <sys/signal.h>
44
45 static char *desc = "Local Proxy Channel";
46 static char *type = "Local";
47 static char *tdesc = "Local Proxy Channel Driver";
48
49 static int capability = -1;
50
51 static int usecnt =0;
52 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
53
54 #define IS_OUTBOUND(a,b) (a == b->chan ? 1 : 0)
55
56 /* Protect the interface list (of sip_pvt's) */
57 static ast_mutex_t locallock = AST_MUTEX_INITIALIZER;
58
59 static struct local_pvt {
60         ast_mutex_t lock;                               /* Channel private lock */
61         char context[AST_MAX_EXTENSION];        /* Context to call */
62         char exten[AST_MAX_EXTENSION];          /* Extension to call */
63         int reqformat;                                          /* Requested format */
64         int glaredetect;                                        /* Detect glare on hangup */
65         int cancelqueue;                                        /* Cancel queue */
66         int alreadymasqed;                                      /* Already masqueraded */
67         int launchedpbx;                                        /* Did we launch the PBX */
68         int nooptimization;
69         struct ast_channel *owner;                      /* Master Channel */
70         struct ast_channel *chan;                       /* Outbound channel */
71         struct local_pvt *next;                         /* Next entity */
72 } *locals = NULL;
73
74 static int local_queue_frame(struct local_pvt *p, int isoutbound, struct ast_frame *f, struct ast_channel *us)
75 {
76         struct ast_channel *other;
77 retrylock:              
78         /* Recalculate outbound channel */
79         if (isoutbound) {
80                 other = p->owner;
81         } else {
82                 other = p->chan;
83         }
84         /* Set glare detection */
85         p->glaredetect = 1;
86         if (p->cancelqueue) {
87                 /* We had a glare on the hangup.  Forget all this business,
88                 return and destroy p.  */
89                 ast_mutex_unlock(&p->lock);
90                 free(p);
91                 return -1;
92         }
93         if (!other) {
94                 p->glaredetect = 0;
95                 return 0;
96         }
97         if (ast_mutex_trylock(&other->lock)) {
98                 /* Failed to lock.  Release main lock and try again */
99                 ast_mutex_unlock(&p->lock);
100                 if (us) {
101                         if (ast_mutex_unlock(&us->lock)) {
102                                 ast_log(LOG_WARNING, "%s wasn't locked while sending %d/%d\n",
103                                         us->name, f->frametype, f->subclass);
104                                 us = NULL;
105                         }
106                 }
107                 /* Wait just a bit */
108                 usleep(1);
109                 /* Only we can destroy ourselves, so we can't disappear here */
110                 if (us)
111                         ast_mutex_lock(&us->lock);
112                 ast_mutex_lock(&p->lock);
113                 goto retrylock;
114         }
115         ast_queue_frame(other, f, 0);
116         ast_mutex_unlock(&other->lock);
117         p->glaredetect = 0;
118         return 0;
119 }
120
121 static int local_answer(struct ast_channel *ast)
122 {
123         struct local_pvt *p = ast->pvt->pvt;
124         int isoutbound = IS_OUTBOUND(ast, p);
125         int res = -1;
126         ast_mutex_lock(&p->lock);
127         if (isoutbound) {
128                 /* Pass along answer since somebody answered us */
129                 struct ast_frame answer = { AST_FRAME_CONTROL, AST_CONTROL_ANSWER };
130                 res = local_queue_frame(p, isoutbound, &answer, ast);
131         } else
132                 ast_log(LOG_WARNING, "Huh?  Local is being asked to answer?\n");
133         ast_mutex_unlock(&p->lock);
134         return res;
135 }
136
137 static void check_bridge(struct local_pvt *p, int isoutbound)
138 {
139         if (p->alreadymasqed || p->nooptimization)
140                 return;
141         if (isoutbound && p->chan && p->chan->bridge && p->owner) {
142                 /* Masquerade bridged channel into owner */
143                 /* Lock everything we need, one by one, and give up if
144                    we can't get everything.  Remember, we'll get another
145                    chance in just a little bit */
146                 if (!ast_mutex_trylock(&p->chan->bridge->lock)) {
147                         if (!ast_mutex_trylock(&p->owner->lock)) {
148                                 ast_channel_masquerade(p->owner, p->chan->bridge);
149                                 p->alreadymasqed = 1;
150                                 ast_mutex_unlock(&p->owner->lock);
151                         }
152                         ast_mutex_unlock(&p->chan->bridge->lock);
153                 }
154         } else if (!isoutbound && p->owner && p->owner->bridge && p->chan) {
155                 /* Masquerade bridged channel into chan */
156                 if (!ast_mutex_trylock(&p->owner->bridge->lock)) {
157                         if (!ast_mutex_trylock(&p->chan->lock)) {
158                                 ast_channel_masquerade(p->chan, p->owner->bridge);
159                                 p->alreadymasqed = 1;
160                                 ast_mutex_unlock(&p->chan->lock);
161                         }
162                         ast_mutex_unlock(&p->owner->bridge->lock);
163                 }
164         }
165 }
166
167 static struct ast_frame  *local_read(struct ast_channel *ast)
168 {
169         static struct ast_frame null = { AST_FRAME_NULL, };
170         return &null;
171 }
172
173 static int local_write(struct ast_channel *ast, struct ast_frame *f)
174 {
175         struct local_pvt *p = ast->pvt->pvt;
176         int res = -1;
177         int isoutbound = IS_OUTBOUND(ast, p);
178
179
180         /* Just queue for delivery to the other side */
181         ast_mutex_lock(&p->lock);
182         res = local_queue_frame(p, isoutbound, f, ast);
183         check_bridge(p, isoutbound);
184         ast_mutex_unlock(&p->lock);
185         return res;
186 }
187
188 static int local_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
189 {
190         struct local_pvt *p = newchan->pvt->pvt;
191         ast_mutex_lock(&p->lock);
192         if ((p->owner != oldchan) && (p->chan != oldchan)) {
193                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p/%p\n", oldchan, p->owner, p->chan);
194                 ast_mutex_unlock(&p->lock);
195                 return -1;
196         }
197         if (p->owner == oldchan)
198                 p->owner = newchan;
199         else
200                 p->chan = newchan;      
201         ast_mutex_unlock(&p->lock);
202         return 0;
203 }
204
205 static int local_indicate(struct ast_channel *ast, int condition)
206 {
207         struct local_pvt *p = ast->pvt->pvt;
208         int res = -1;
209         struct ast_frame f = { AST_FRAME_CONTROL, };
210         int isoutbound = IS_OUTBOUND(ast, p);
211         /* Queue up a frame representing the indication as a control frame */
212         ast_mutex_lock(&p->lock);
213         f.subclass = condition;
214         res = local_queue_frame(p, isoutbound, &f, ast);
215         ast_mutex_unlock(&p->lock);
216         return res;
217 }
218
219 static int local_digit(struct ast_channel *ast, char digit)
220 {
221         struct local_pvt *p = ast->pvt->pvt;
222         int res = -1;
223         struct ast_frame f = { AST_FRAME_DTMF, };
224         int isoutbound = IS_OUTBOUND(ast, p);
225         ast_mutex_lock(&p->lock);
226         f.subclass = digit;
227         res = local_queue_frame(p, isoutbound, &f, ast);
228         ast_mutex_unlock(&p->lock);
229         return res;
230 }
231
232 static int local_call(struct ast_channel *ast, char *dest, int timeout)
233 {
234         struct local_pvt *p = ast->pvt->pvt;
235         int res;
236         
237         ast_mutex_lock(&p->lock);
238         if (p->owner->callerid)
239                 p->chan->callerid = strdup(p->owner->callerid);
240         else
241                 p->chan->callerid = NULL;
242         if (p->owner->ani)
243                 p->chan->ani = strdup(p->owner->ani);
244         else
245                 p->chan->ani = NULL;
246         p->launchedpbx = 1;
247         /* Start switch on sub channel */
248         res = ast_pbx_start(p->chan);
249         ast_mutex_unlock(&p->lock);
250         return res;
251 }
252
253 static void local_destroy(struct local_pvt *p)
254 {
255         struct local_pvt *cur, *prev = NULL;
256         ast_mutex_lock(&locallock);
257         cur = locals;
258         while(cur) {
259                 if (cur == p) {
260                         if (prev)
261                                 prev->next = cur->next;
262                         else
263                                 locals = cur->next;
264                         free(cur);
265                         break;
266                 }
267                 prev = cur;
268                 cur = cur->next;
269         }
270         ast_mutex_unlock(&locallock);
271         if (!cur)
272                 ast_log(LOG_WARNING, "Unable ot find local '%s@%s' in local list\n", p->exten, p->context);
273 }
274
275 static int local_hangup(struct ast_channel *ast)
276 {
277         struct local_pvt *p = ast->pvt->pvt;
278         int isoutbound = IS_OUTBOUND(ast, p);
279         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
280         struct local_pvt *cur, *prev=NULL;
281         struct ast_channel *ochan = NULL;
282         int glaredetect;
283         ast_mutex_lock(&p->lock);
284         if (isoutbound) {
285                 p->chan = NULL;
286                 p->launchedpbx = 0;
287         } else
288                 p->owner = NULL;
289         ast->pvt->pvt = NULL;
290         
291         if (!p->owner && !p->chan) {
292                 /* Okay, done with the private part now, too. */
293                 glaredetect = p->glaredetect;
294                 /* If we have a queue holding, don't actually destroy p yet, but
295                    let local_queue do it. */
296                 if (p->glaredetect)
297                         p->cancelqueue = 1;
298                 ast_mutex_unlock(&p->lock);
299                 /* Remove from list */
300                 ast_mutex_lock(&locallock);
301                 cur = locals;
302                 while(cur) {
303                         if (cur == p) {
304                                 if (prev)
305                                         prev->next = cur->next;
306                                 else
307                                         locals = cur->next;
308                                 break;
309                         }
310                         prev = cur;
311                         cur = cur->next;
312                 }
313                 ast_mutex_unlock(&locallock);
314                 /* And destroy */
315                 if (!glaredetect)
316                         free(p);
317                 return 0;
318         }
319         if (p->chan && !p->launchedpbx)
320                 /* Need to actually hangup since there is no PBX */
321                 ochan = p->chan;
322         else
323                 local_queue_frame(p, isoutbound, &f, NULL);
324         ast_mutex_unlock(&p->lock);
325         if (ochan)
326                 ast_hangup(ochan);
327         return 0;
328 }
329
330 static struct local_pvt *local_alloc(char *data, int format)
331 {
332         struct local_pvt *tmp;
333         char *c;
334         char *opts;
335         tmp = malloc(sizeof(struct local_pvt));
336         if (tmp) {
337                 memset(tmp, 0, sizeof(struct local_pvt));
338                 ast_mutex_init(&tmp->lock);
339                 strncpy(tmp->exten, data, sizeof(tmp->exten) - 1);
340                 opts = strchr(tmp->exten, '/');
341                 if (opts) {
342                         *opts='\0';
343                         opts++;
344                         if (strchr(opts, 'n'))
345                                 tmp->nooptimization = 1;
346                 }
347                 c = strchr(tmp->exten, '@');
348                 if (c) {
349                         *c = '\0';
350                         c++;
351                         strncpy(tmp->context, c, sizeof(tmp->context) - 1);
352                 } else
353                         strncpy(tmp->context, "default", sizeof(tmp->context) - 1);
354                 tmp->reqformat = format;
355                 if (!ast_exists_extension(NULL, tmp->context, tmp->exten, 1, NULL)) {
356                         ast_log(LOG_NOTICE, "No such extension/context %s@%s creating local channel\n", tmp->context, tmp->exten);
357                         free(tmp);
358                         tmp = NULL;
359                 } else {
360                         /* Add to list */
361                         ast_mutex_lock(&locallock);
362                         tmp->next = locals;
363                         locals = tmp;
364                         ast_mutex_unlock(&locallock);
365                 }
366                 
367         }
368         return tmp;
369 }
370
371 static struct ast_channel *local_new(struct local_pvt *p, int state)
372 {
373         struct ast_channel *tmp, *tmp2;
374         int randnum = rand() & 0xffff;
375         tmp = ast_channel_alloc(1);
376         tmp2 = ast_channel_alloc(1);
377         if (!tmp || !tmp2) {
378                 if (tmp)
379                         ast_channel_free(tmp);
380                 if (tmp2)
381                         ast_channel_free(tmp2);
382                 tmp = NULL;
383         }
384         if (tmp) {
385                 tmp->nativeformats = p->reqformat;
386                 tmp2->nativeformats = p->reqformat;
387                 snprintf(tmp->name, sizeof(tmp->name), "Local/%s@%s-%04x,1", p->exten, p->context, randnum);
388                 snprintf(tmp2->name, sizeof(tmp2->name), "Local/%s@%s-%04x,2", p->exten, p->context, randnum);
389                 tmp->type = type;
390                 tmp2->type = type;
391                 ast_setstate(tmp, state);
392                 ast_setstate(tmp2, AST_STATE_RING);
393                 tmp->writeformat = p->reqformat;;
394                 tmp2->writeformat = p->reqformat;
395                 tmp->pvt->rawwriteformat = p->reqformat;
396                 tmp2->pvt->rawwriteformat = p->reqformat;
397                 tmp->readformat = p->reqformat;
398                 tmp2->readformat = p->reqformat;
399                 tmp->pvt->rawreadformat = p->reqformat;
400                 tmp2->pvt->rawreadformat = p->reqformat;
401                 tmp->pvt->pvt = p;
402                 tmp2->pvt->pvt = p;
403                 tmp->pvt->send_digit = local_digit;
404                 tmp2->pvt->send_digit = local_digit;
405                 tmp->pvt->call = local_call;
406                 tmp2->pvt->call = local_call;
407                 tmp->pvt->hangup = local_hangup;
408                 tmp2->pvt->hangup = local_hangup;
409                 tmp->pvt->answer = local_answer;
410                 tmp2->pvt->answer = local_answer;
411                 tmp->pvt->read = local_read;
412                 tmp2->pvt->read = local_read;
413                 tmp->pvt->write = local_write;
414                 tmp2->pvt->write = local_write;
415                 tmp->pvt->exception = local_read;
416                 tmp2->pvt->exception = local_read;
417                 tmp->pvt->indicate = local_indicate;
418                 tmp2->pvt->indicate = local_indicate;
419                 tmp->pvt->fixup = local_fixup;
420                 tmp2->pvt->fixup = local_fixup;
421                 p->owner = tmp;
422                 p->chan = tmp2;
423                 ast_mutex_lock(&usecnt_lock);
424                 usecnt++;
425                 ast_mutex_unlock(&usecnt_lock);
426                 ast_update_use_count();
427                 strncpy(tmp->context, p->context, sizeof(tmp->context)-1);
428                 strncpy(tmp2->context, p->context, sizeof(tmp2->context)-1);
429                 strncpy(tmp2->exten, p->exten, sizeof(tmp->exten)-1);
430                 tmp->priority = 1;
431                 tmp2->priority = 1;
432         } else
433                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
434         return tmp;
435 }
436
437
438 static struct ast_channel *local_request(char *type, int format, void *data)
439 {
440         struct local_pvt *p;
441         struct ast_channel *chan = NULL;
442         p = local_alloc(data, format);
443         if (p)
444                 chan = local_new(p, AST_STATE_DOWN);
445         return chan;
446 }
447
448 static int locals_show(int fd, int argc, char **argv)
449 {
450         struct local_pvt *p;
451
452         if (argc != 2)
453                 return RESULT_SHOWUSAGE;
454         ast_mutex_lock(&locallock);
455         p = locals;
456         while(p) {
457                 ast_mutex_lock(&p->lock);
458                 ast_cli(fd, "%s -- %s@%s\n", p->owner ? p->owner->name : "<unowned>", p->exten, p->context);
459                 ast_mutex_unlock(&p->lock);
460                 p = p->next;
461         }
462         if (!locals)
463                 ast_cli(fd, "No local channels in use\n");
464         ast_mutex_unlock(&locallock);
465         return RESULT_SUCCESS;
466 }
467
468 static char show_locals_usage[] = 
469 "Usage: show locals\n"
470 "       Provides summary information on locals.\n";
471
472 static struct ast_cli_entry cli_show_locals = {
473         { "show", "locals", NULL }, locals_show, 
474         "Show status of local channels", show_locals_usage, NULL };
475
476 int load_module()
477 {
478         /* Make sure we can register our sip channel type */
479         if (ast_channel_register(type, tdesc, capability, local_request)) {
480                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
481                 return -1;
482         }
483         ast_cli_register(&cli_show_locals);
484         return 0;
485 }
486
487 int reload()
488 {
489         return 0;
490 }
491
492 int unload_module()
493 {
494         struct local_pvt *p;
495         /* First, take us out of the channel loop */
496         ast_cli_unregister(&cli_show_locals);
497         ast_channel_unregister(type);
498         if (!ast_mutex_lock(&locallock)) {
499                 /* Hangup all interfaces if they have an owner */
500                 p = locals;
501                 while(p) {
502                         if (p->owner)
503                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
504                         p = p->next;
505                 }
506                 locals = NULL;
507                 ast_mutex_unlock(&locallock);
508         } else {
509                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
510                 return -1;
511         }               
512         return 0;
513 }
514
515 int usecount()
516 {
517         int res;
518         ast_mutex_lock(&usecnt_lock);
519         res = usecnt;
520         ast_mutex_unlock(&usecnt_lock);
521         return res;
522 }
523
524 char *key()
525 {
526         return ASTERISK_GPL_KEY;
527 }
528
529 char *description()
530 {
531         return desc;
532 }
533