Merge FreeBSD locking fixes (bug #1411)
[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 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
53
54 #define IS_OUTBOUND(a,b) (a == b->chan ? 1 : 0)
55
56 /* Protect the interface list (of sip_pvt's) */
57 AST_MUTEX_DEFINE_STATIC(locallock);
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);
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->rdnis)
243                 p->chan->rdnis = strdup(p->owner->rdnis);
244         else
245                 p->chan->rdnis = NULL;
246         if (p->owner->ani)
247                 p->chan->ani = strdup(p->owner->ani);
248         else
249                 p->chan->ani = NULL;
250         strncpy(p->chan->language, p->owner->language, sizeof(p->chan->language) - 1);
251         p->launchedpbx = 1;
252         /* Start switch on sub channel */
253         res = ast_pbx_start(p->chan);
254         ast_mutex_unlock(&p->lock);
255         return res;
256 }
257
258 /*
259 static void local_destroy(struct local_pvt *p)
260 {
261         struct local_pvt *cur, *prev = NULL;
262         ast_mutex_lock(&locallock);
263         cur = locals;
264         while(cur) {
265                 if (cur == p) {
266                         if (prev)
267                                 prev->next = cur->next;
268                         else
269                                 locals = cur->next;
270                         free(cur);
271                         break;
272                 }
273                 prev = cur;
274                 cur = cur->next;
275         }
276         ast_mutex_unlock(&locallock);
277         if (!cur)
278                 ast_log(LOG_WARNING, "Unable ot find local '%s@%s' in local list\n", p->exten, p->context);
279 }
280 */
281
282 static int local_hangup(struct ast_channel *ast)
283 {
284         struct local_pvt *p = ast->pvt->pvt;
285         int isoutbound = IS_OUTBOUND(ast, p);
286         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
287         struct local_pvt *cur, *prev=NULL;
288         struct ast_channel *ochan = NULL;
289         int glaredetect;
290         ast_mutex_lock(&p->lock);
291         if (isoutbound) {
292                 p->chan = NULL;
293                 p->launchedpbx = 0;
294         } else
295                 p->owner = NULL;
296         ast->pvt->pvt = NULL;
297         
298         if (!p->owner && !p->chan) {
299                 /* Okay, done with the private part now, too. */
300                 glaredetect = p->glaredetect;
301                 /* If we have a queue holding, don't actually destroy p yet, but
302                    let local_queue do it. */
303                 if (p->glaredetect)
304                         p->cancelqueue = 1;
305                 ast_mutex_unlock(&p->lock);
306                 /* Remove from list */
307                 ast_mutex_lock(&locallock);
308                 cur = locals;
309                 while(cur) {
310                         if (cur == p) {
311                                 if (prev)
312                                         prev->next = cur->next;
313                                 else
314                                         locals = cur->next;
315                                 break;
316                         }
317                         prev = cur;
318                         cur = cur->next;
319                 }
320                 ast_mutex_unlock(&locallock);
321                 /* And destroy */
322                 if (!glaredetect)
323                         free(p);
324                 return 0;
325         }
326         if (p->chan && !p->launchedpbx)
327                 /* Need to actually hangup since there is no PBX */
328                 ochan = p->chan;
329         else
330                 local_queue_frame(p, isoutbound, &f, NULL);
331         ast_mutex_unlock(&p->lock);
332         if (ochan)
333                 ast_hangup(ochan);
334         return 0;
335 }
336
337 static struct local_pvt *local_alloc(char *data, int format)
338 {
339         struct local_pvt *tmp;
340         char *c;
341         char *opts;
342         tmp = malloc(sizeof(struct local_pvt));
343         if (tmp) {
344                 memset(tmp, 0, sizeof(struct local_pvt));
345                 ast_mutex_init(&tmp->lock);
346                 strncpy(tmp->exten, data, sizeof(tmp->exten) - 1);
347                 opts = strchr(tmp->exten, '/');
348                 if (opts) {
349                         *opts='\0';
350                         opts++;
351                         if (strchr(opts, 'n'))
352                                 tmp->nooptimization = 1;
353                 }
354                 c = strchr(tmp->exten, '@');
355                 if (c) {
356                         *c = '\0';
357                         c++;
358                         strncpy(tmp->context, c, sizeof(tmp->context) - 1);
359                 } else
360                         strncpy(tmp->context, "default", sizeof(tmp->context) - 1);
361                 tmp->reqformat = format;
362                 if (!ast_exists_extension(NULL, tmp->context, tmp->exten, 1, NULL)) {
363                         ast_log(LOG_NOTICE, "No such extension/context %s@%s creating local channel\n", tmp->context, tmp->exten);
364                         free(tmp);
365                         tmp = NULL;
366                 } else {
367                         /* Add to list */
368                         ast_mutex_lock(&locallock);
369                         tmp->next = locals;
370                         locals = tmp;
371                         ast_mutex_unlock(&locallock);
372                 }
373                 
374         }
375         return tmp;
376 }
377
378 static struct ast_channel *local_new(struct local_pvt *p, int state)
379 {
380         struct ast_channel *tmp, *tmp2;
381         int randnum = rand() & 0xffff;
382         tmp = ast_channel_alloc(1);
383         tmp2 = ast_channel_alloc(1);
384         if (!tmp || !tmp2) {
385                 if (tmp)
386                         ast_channel_free(tmp);
387                 if (tmp2)
388                         ast_channel_free(tmp2);
389                 tmp = NULL;
390         }
391         if (tmp) {
392                 tmp->nativeformats = p->reqformat;
393                 tmp2->nativeformats = p->reqformat;
394                 snprintf(tmp->name, sizeof(tmp->name), "Local/%s@%s-%04x,1", p->exten, p->context, randnum);
395                 snprintf(tmp2->name, sizeof(tmp2->name), "Local/%s@%s-%04x,2", p->exten, p->context, randnum);
396                 tmp->type = type;
397                 tmp2->type = type;
398                 ast_setstate(tmp, state);
399                 ast_setstate(tmp2, AST_STATE_RING);
400                 tmp->writeformat = p->reqformat;;
401                 tmp2->writeformat = p->reqformat;
402                 tmp->pvt->rawwriteformat = p->reqformat;
403                 tmp2->pvt->rawwriteformat = p->reqformat;
404                 tmp->readformat = p->reqformat;
405                 tmp2->readformat = p->reqformat;
406                 tmp->pvt->rawreadformat = p->reqformat;
407                 tmp2->pvt->rawreadformat = p->reqformat;
408                 tmp->pvt->pvt = p;
409                 tmp2->pvt->pvt = p;
410                 tmp->pvt->send_digit = local_digit;
411                 tmp2->pvt->send_digit = local_digit;
412                 tmp->pvt->call = local_call;
413                 tmp2->pvt->call = local_call;
414                 tmp->pvt->hangup = local_hangup;
415                 tmp2->pvt->hangup = local_hangup;
416                 tmp->pvt->answer = local_answer;
417                 tmp2->pvt->answer = local_answer;
418                 tmp->pvt->read = local_read;
419                 tmp2->pvt->read = local_read;
420                 tmp->pvt->write = local_write;
421                 tmp2->pvt->write = local_write;
422                 tmp->pvt->exception = local_read;
423                 tmp2->pvt->exception = local_read;
424                 tmp->pvt->indicate = local_indicate;
425                 tmp2->pvt->indicate = local_indicate;
426                 tmp->pvt->fixup = local_fixup;
427                 tmp2->pvt->fixup = local_fixup;
428                 p->owner = tmp;
429                 p->chan = tmp2;
430                 ast_mutex_lock(&usecnt_lock);
431                 usecnt++;
432                 ast_mutex_unlock(&usecnt_lock);
433                 ast_update_use_count();
434                 strncpy(tmp->context, p->context, sizeof(tmp->context)-1);
435                 strncpy(tmp2->context, p->context, sizeof(tmp2->context)-1);
436                 strncpy(tmp2->exten, p->exten, sizeof(tmp->exten)-1);
437                 tmp->priority = 1;
438                 tmp2->priority = 1;
439         } else
440                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
441         return tmp;
442 }
443
444
445 static struct ast_channel *local_request(char *type, int format, void *data)
446 {
447         struct local_pvt *p;
448         struct ast_channel *chan = NULL;
449         p = local_alloc(data, format);
450         if (p)
451                 chan = local_new(p, AST_STATE_DOWN);
452         return chan;
453 }
454
455 static int locals_show(int fd, int argc, char **argv)
456 {
457         struct local_pvt *p;
458
459         if (argc != 3)
460                 return RESULT_SHOWUSAGE;
461         ast_mutex_lock(&locallock);
462         p = locals;
463         while(p) {
464                 ast_mutex_lock(&p->lock);
465                 ast_cli(fd, "%s -- %s@%s\n", p->owner ? p->owner->name : "<unowned>", p->exten, p->context);
466                 ast_mutex_unlock(&p->lock);
467                 p = p->next;
468         }
469         if (!locals)
470                 ast_cli(fd, "No local channels in use\n");
471         ast_mutex_unlock(&locallock);
472         return RESULT_SUCCESS;
473 }
474
475 static char show_locals_usage[] = 
476 "Usage: local show channels\n"
477 "       Provides summary information on local channels.\n";
478
479 static struct ast_cli_entry cli_show_locals = {
480         { "local", "show", "channels", NULL }, locals_show, 
481         "Show status of local channels", show_locals_usage, NULL };
482
483 int load_module()
484 {
485         /* Make sure we can register our sip channel type */
486         if (ast_channel_register(type, tdesc, capability, local_request)) {
487                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
488                 return -1;
489         }
490         ast_cli_register(&cli_show_locals);
491         return 0;
492 }
493
494 int reload()
495 {
496         return 0;
497 }
498
499 int unload_module()
500 {
501         struct local_pvt *p;
502         /* First, take us out of the channel loop */
503         ast_cli_unregister(&cli_show_locals);
504         ast_channel_unregister(type);
505         if (!ast_mutex_lock(&locallock)) {
506                 /* Hangup all interfaces if they have an owner */
507                 p = locals;
508                 while(p) {
509                         if (p->owner)
510                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
511                         p = p->next;
512                 }
513                 locals = NULL;
514                 ast_mutex_unlock(&locallock);
515         } else {
516                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
517                 return -1;
518         }               
519         return 0;
520 }
521
522 int usecount()
523 {
524         int res;
525         ast_mutex_lock(&usecnt_lock);
526         res = usecnt;
527         ast_mutex_unlock(&usecnt_lock);
528         return res;
529 }
530
531 char *key()
532 {
533         return ASTERISK_GPL_KEY;
534 }
535
536 char *description()
537 {
538         return desc;
539 }
540