de18ea6f27b376b5b447e1170a437bae93b79d39
[asterisk/asterisk.git] / channels / h323 / chan_h323.c
1 /*
2  * chan_h323.c
3  *
4  * OpenH323 Channel Driver for ASTERISK PBX.
5  *                      By Jeremy McNamara
6  *                      For The NuFone Network 
7  *
8  * This code has been derived from code created by
9  *              Michael Manousos and Mark Spencer
10  *
11  * This file is part of the chan_h323 driver for Asterisk
12  *
13  * chan_h323 is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version. 
17  *
18  * chan_h323 is distributed WITHOUT ANY WARRANTY; without even 
19  * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
20  * PURPOSE. See the GNU General Public License for more details. 
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 
25  *
26  */
27
28
29 #include <stdio.h>
30 #include <pthread.h>
31 #include <string.h>
32 #include <asterisk/lock.h>
33 #include <asterisk/logger.h>
34 #include <asterisk/channel.h>
35 #include <asterisk/channel_pvt.h>
36 #include <asterisk/config.h>
37 #include <asterisk/module.h>
38 #include <asterisk/pbx.h>
39 #include <asterisk/options.h>
40 #include <asterisk/lock.h>
41 #include <asterisk/sched.h>
42 #include <asterisk/io.h>
43 #include <asterisk/rtp.h>
44 #include <asterisk/acl.h>
45 #include <asterisk/callerid.h>
46 #include <asterisk/cli.h>
47 #include <asterisk/dsp.h>
48 #include <sys/socket.h>
49 #include <net/if.h>
50 #include <errno.h>
51 #include <unistd.h>
52 #include <stdlib.h>
53 #include <fcntl.h>
54 #include <netdb.h>
55 #include <sys/signal.h>
56 #include <netinet/ip.h>
57
58
59 #include "chan_h323.h"
60
61 /** String variables required by ASTERISK */
62 static char *type       = "H323";
63 static char *desc       = "The NuFone Network's Open H.323 Channel Driver";
64 static char *tdesc      = "The NuFone Network's Open H.323 Channel Driver";
65 static char *config = "h323.conf";
66
67 static char default_context[AST_MAX_EXTENSION];
68
69 /** H.323 configuration values */
70 static char gatekeeper[100];
71 static int      gatekeeper_disable = 1;
72 static int      gatekeeper_discover = 0;
73 static int  usingGk;
74 static int      port = 1720;
75 static int  gkroute = 0;
76
77 /* Just about everybody seems to support ulaw, so make it a nice default */
78 static int capability = AST_FORMAT_ULAW;
79
80 /* TOS flag */
81 static int tos = 0;
82
83 static int dtmfmode = H323_DTMF_RFC2833;
84
85 static char secret[50];
86
87 /** Private structure of a OpenH323 channel */
88 struct oh323_pvt {
89         pthread_mutex_t lock;                                   /* Channel private lock */
90         call_options_t calloptions;                             /* Options to be used during call setup */
91         int     alreadygone;                                            /* Whether or not we've already been destroyed by or peer */
92         int needdestroy;                                                /* if we need to be destroyed */
93         call_details_t cd;                                              /* Call details */
94         struct ast_channel *owner;                              /* Who owns us */
95         int capability;                                                 /* Special capability */
96         int nonCodecCapability;
97         int outgoing;                                                   /* Outgoing or incoming call? */
98         int nat;                                                                /* Are we talking to a NAT EP?*/
99         int bridge;                                                             /* Determine of we should native bridge or not*/
100         char exten[AST_MAX_EXTENSION];                  /* Requested extension */
101         char context[AST_MAX_EXTENSION];                /* Context where to start */
102         char username[81];                                              /* H.323 alias using this channel */
103         char accountcode[256];                                  /* Account code */
104         int amaflags;                                                   /* AMA Flags */
105         char callerid[80];                                              /* Caller*ID if available */
106         struct ast_rtp *rtp;                                    /* RTP Session */
107         int dtmfmode;
108         struct ast_dsp *vad;                                    /* Used for in-band DTMF detection */
109         struct oh323_pvt *next;                                 /* Next channel in list */
110 } *iflist = NULL;
111
112 static struct ast_user_list {
113         struct oh323_user *users;
114         pthread_mutex_t lock;
115 } userl = { NULL, AST_MUTEX_INITIALIZER };
116
117 static struct ast_peer_list {
118         struct oh323_peer *peers;
119         pthread_mutex_t lock;
120 } peerl = { NULL, AST_MUTEX_INITIALIZER };
121
122 static struct ast_alias_list {
123         struct oh323_alias *aliases;
124         pthread_mutex_t lock;
125 } aliasl = { NULL, AST_MUTEX_INITIALIZER };
126
127 /** Asterisk RTP stuff*/
128 static struct sched_context *sched;
129 static struct io_context *io;
130
131 /** Protect the interface list (of oh323_pvt's) */
132 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
133
134 /** Usage counter and associated lock */
135 static int usecnt =0;
136 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
137
138 /* Protect the monitoring thread, so only one process can kill or start it, and not
139    when it's doing something critical. */
140 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
141
142 /* This is the thread for the monitor which checks for input on the channels
143    which are not currently in use.  */
144 static pthread_t monitor_thread = 0;
145
146 static int restart_monitor(void);
147
148 static void __oh323_destroy(struct oh323_pvt *p)
149 {
150         struct oh323_pvt *cur, *prev = NULL;
151         
152         if (p->rtp) {
153                 ast_rtp_destroy(p->rtp);
154         }
155         
156         /* Unlink us from the owner if we have one */
157         if (p->owner) {
158                 ast_pthread_mutex_lock(&p->owner->lock);
159                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
160                 p->owner->pvt->pvt = NULL;
161                 ast_pthread_mutex_unlock(&p->owner->lock);
162         }
163         cur = iflist;
164         while(cur) {
165                 if (cur == p) {
166                         if (prev)
167                                 prev->next = cur->next;
168                         else
169                                 iflist = cur->next;
170                         break;
171                 }
172                 prev = cur;
173                 cur = cur->next;
174         }
175         if (!cur) {
176                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
177         } else
178                 free(p);
179 }
180
181 static void oh323_destroy(struct oh323_pvt *p)
182 {
183         ast_pthread_mutex_lock(&iflock);
184         __oh323_destroy(p);
185         ast_pthread_mutex_unlock(&iflock);
186 }
187
188 static struct oh323_alias *build_alias(char *name, struct ast_variable *v)
189 {
190         struct oh323_alias *alias;
191
192         alias = (struct oh323_alias *)malloc(sizeof(struct oh323_alias));
193
194         if (alias) {
195                 memset(alias, 0, sizeof(struct oh323_alias));
196                 strncpy(alias->name, name, sizeof(alias->name)-1);
197
198                 while (v) {
199                         if (!strcasecmp(v->name, "e164")) {
200                                 strncpy(alias->e164,  v->value, sizeof(alias->e164)-1);
201                         } else if (!strcasecmp(v->name, "prefix")) {
202                                 strncpy(alias->prefix,  v->value, sizeof(alias->prefix)-1);
203                         } else if (!strcasecmp(v->name, "context")) {
204                                 strncpy(alias->context,  v->value, sizeof(alias->context)-1);
205                         } else if (!strcasecmp(v->name, "secret")) {
206                                 strncpy(alias->secret,  v->value, sizeof(alias->secret)-1);
207                         }
208                         v = v->next;
209                 }
210         }
211         return alias;
212 }
213
214 static struct oh323_user *build_user(char *name, struct ast_variable *v)
215 {
216         struct oh323_user *user;
217         int format;
218         
219         user = (struct oh323_user *)malloc(sizeof(struct oh323_user));
220         if (user) {
221                 memset(user, 0, sizeof(struct oh323_user));
222                 strncpy(user->name, name, sizeof(user->name)-1);
223                 
224                 /* set the usage flag to a sane starting value*/
225                 user->inUse = 0;
226                 /* Assume we can native bridge */
227                 user->bridge = 1; 
228
229                 while(v) {
230                         if (!strcasecmp(v->name, "context")) {
231                                 strncpy(user->context, v->value, sizeof(user->context)-1);
232                         } else if (!strcasecmp(v->name, "bridge")) {
233                                 user->bridge = ast_true(v->value);
234                         } else if (!strcasecmp(v->name, "noFastStart")) {
235                                 user->noFastStart = ast_true(v->value);
236                         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
237                                 user->noH245Tunneling = ast_true(v->value);
238                         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
239                                 user->noSilenceSuppression = ast_true(v->value);
240                         } else if (!strcasecmp(v->name, "secret")) {
241                                 strncpy(user->secret, v->value, sizeof(user->secret)-1);
242                         } else if (!strcasecmp(v->name, "callerid")) {
243                                 strncpy(user->callerid, v->value, sizeof(user->callerid)-1);
244                         } else if (!strcasecmp(v->name, "accountcode")) {
245                                 strncpy(user->accountcode, v->value, sizeof(user->accountcode)-1);
246                         } else if (!strcasecmp(v->name, "incominglimit")) {
247                                 user->incominglimit = atoi(v->value);
248                                 if (user->incominglimit < 0)
249                                         user->incominglimit = 0;
250                         } else if (!strcasecmp(v->name, "host")) {
251                                 if (!strcasecmp(v->value, "dynamic")) {
252                                         ast_log(LOG_ERROR, "Dynamic host configuration not implemented, yet!\n");
253                                         free(user);
254                                         return NULL;
255                                 } else if (ast_get_ip(&user->addr, v->value)) {
256                                         free(user);
257                                         return NULL;
258                                 } 
259                                 /* Let us know we need to use ip authentication */
260                                 user->host = 1;
261                         } else if (!strcasecmp(v->name, "amaflags")) {
262                                 format = ast_cdr_amaflags2int(v->value);
263                                 if (format < 0) {
264                                         ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
265                                 } else {
266                                         user->amaflags = format;
267                                 }
268                         }
269                         v = v->next;
270                 }
271         }
272         return user;
273 }
274
275
276 static struct oh323_peer *build_peer(char *name, struct ast_variable *v)
277 {
278         struct oh323_peer *peer;
279         struct oh323_peer *prev;
280         int found=0;
281         
282         prev = NULL;
283         ast_pthread_mutex_lock(&peerl.lock);
284         peer = peerl.peers;
285
286         while(peer) {
287                 if (!strcasecmp(peer->name, name)) {    
288                         break;
289                 }
290                 prev = peer;
291                 peer = peer->next;
292         }
293
294         if (peer) {
295                 found++;
296                 /* Already in the list, remove it and it will be added back (or FREE'd) */
297                 if (prev) {
298                         prev->next = peer->next;
299                 } else {
300                         peerl.peers = peer->next;
301                 }
302                 ast_pthread_mutex_unlock(&peerl.lock);
303         } else {
304                 ast_pthread_mutex_unlock(&peerl.lock);
305                 peer = malloc(sizeof(struct oh323_peer));
306                 memset(peer, 0, sizeof(struct oh323_peer));
307         }
308         if (peer) {
309                 if (!found) {
310                         strncpy(peer->name, name, sizeof(peer->name)-1);
311                 }
312                 
313                 /* set the usage flag to a sane starting value*/
314                 peer->inUse = 0;
315
316                 while(v) {
317                         if (!strcasecmp(v->name, "context")) {
318                                 strncpy(peer->context, v->value, sizeof(peer->context)-1);
319                         }  else if (!strcasecmp(v->name, "bridge")) {
320                                 peer->bridge = ast_true(v->value);
321                         } else if (!strcasecmp(v->name, "noFastStart")) {
322                                 peer->noFastStart = ast_true(v->value);
323                         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
324                                 peer->noH245Tunneling = ast_true(v->value);
325                         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
326                                 peer->noSilenceSuppression = ast_true(v->value);
327                         } else if (!strcasecmp(v->name, "outgoinglimit")) {
328                                 peer->outgoinglimit = atoi(v->value);
329                                 if (peer->outgoinglimit > 0)
330                                         peer->outgoinglimit = 0;
331                         } else if (!strcasecmp(v->name, "host")) {
332                                 if (!strcasecmp(v->value, "dynamic")) {
333                                         ast_log(LOG_ERROR, "Dynamic host configuration not implemented, yet!\n");
334                                         free(peer);
335                                         return NULL;
336                                 }
337                                 if (ast_get_ip(&peer->addr, v->value)) {
338                                                 free(peer);
339                                                 return NULL;
340                                 }
341                         } 
342                         v=v->next;
343                 }
344         }
345         return peer;
346 }
347
348
349
350 /**
351  * Send (play) the specified digit to the channel.
352  * 
353  */
354 static int oh323_digit(struct ast_channel *c, char digit)
355 {
356         struct oh323_pvt *p = c->pvt->pvt;
357         if (p && p->rtp && (p->dtmfmode & H323_DTMF_RFC2833)) {
358                 ast_rtp_senddigit(p->rtp, digit);
359         }
360         /* If in-band DTMF is desired, send that */
361         if (p->dtmfmode & H323_DTMF_INBAND)
362                 h323_send_tone(p->cd.call_token, digit);
363         return 0;
364 }
365
366
367 /**
368  * Make a call over the specified channel to the specified 
369  * destination. This function will parse the destination string
370  * and determine the address-number to call.
371  * Return -1 on error, 0 on success.
372  */
373 static int oh323_call(struct ast_channel *c, char *dest, int timeout)
374 {
375         int res;
376         struct oh323_pvt *p = c->pvt->pvt;
377         char called_addr[256];
378         char *tmp;
379
380         strtok_r(dest, "/", &(tmp));
381
382         ast_log(LOG_DEBUG, "dest=%s, timeout=%d.\n", dest, timeout);
383
384         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
385                 ast_log(LOG_WARNING, "Line is already in use (%s)\n", c->name);
386                 return -1;
387         }
388         
389         /* outgoing call */
390         p->outgoing = 1;
391
392         /* Clear the call token */
393         if ((p->cd).call_token == NULL)
394                 (p->cd).call_token = (char *)malloc(128);
395
396         memset((char *)(p->cd).call_token, 0, 128);
397         
398         if (p->cd.call_token == NULL) {
399                 ast_log(LOG_ERROR, "Not enough memory.\n");
400                 return -1;
401         }
402
403         /* Build the address to call */
404         memset(called_addr, 0, sizeof(dest));
405         memcpy(called_addr, dest, sizeof(called_addr));
406
407         /* Copy callerid, if there is any */
408         if (strlen(c->callerid)) {
409                 p->calloptions.callerid = strdup(c->callerid);
410         }
411
412         res = h323_make_call(called_addr, &(p->cd), p->calloptions);
413
414         if (res) {
415                 ast_log(LOG_NOTICE, "h323_make_call failed(%s)\n", c->name);
416                 return -1;
417         }
418
419         ast_setstate(c, AST_STATE_RINGING);
420         return 0;
421 }
422
423
424 static int oh323_answer(struct ast_channel *c)
425 {
426         int res;
427
428         struct oh323_pvt *p = c->pvt->pvt;
429
430         res = h323_answering_call(p->cd.call_token, 0);
431         
432         if (c->_state != AST_STATE_UP)
433                 ast_setstate(c, AST_STATE_UP);
434
435         return res;
436 }
437
438 static int oh323_hangup(struct ast_channel *c)
439 {
440         struct oh323_pvt *p = c->pvt->pvt;
441         int needcancel = 0;
442         if (h323debug)
443                 ast_log(LOG_DEBUG, "oh323_hangup(%s)\n", c->name);
444         if (!c->pvt->pvt) {
445                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
446                 return 0;
447         }
448         ast_pthread_mutex_lock(&p->lock);
449         /* Determine how to disconnect */
450         if (p->owner != c) {
451                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
452                 ast_pthread_mutex_unlock(&p->lock);
453                 return 0;
454         }
455         if (!c || (c->_state != AST_STATE_UP))
456                 needcancel = 1;
457         /* Disconnect */
458         p = c->pvt->pvt;
459         
460         /* Free dsp used for in-band DTMF detection */
461         if (p->vad) {
462                 ast_dsp_free(p->vad);
463      }
464
465         p->owner = NULL;
466         c->pvt->pvt = NULL;
467
468         /* Start the process if it's not already started */
469         if (!p->alreadygone) {
470                 if (h323_clear_call((p->cd).call_token)) 
471                         ast_log(LOG_DEBUG, "ClearCall failed.\n");
472                 p->needdestroy = 1;
473         }
474
475         /* Update usage counter */
476         ast_pthread_mutex_lock(&usecnt_lock);
477         usecnt--;
478         if (usecnt < 0)
479                 ast_log(LOG_WARNING, "Usecnt < 0\n");
480         ast_pthread_mutex_unlock(&usecnt_lock);
481         ast_update_use_count();
482
483         ast_pthread_mutex_unlock(&p->lock);
484         return 0;
485 }
486
487 static struct ast_frame *oh323_rtp_read(struct oh323_pvt *p)
488 {
489         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
490         struct ast_frame *f;
491         static struct ast_frame null_frame = { AST_FRAME_NULL, };
492         f = ast_rtp_read(p->rtp);
493         /* Don't send RFC2833 if we're not supposed to */
494         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & H323_DTMF_RFC2833))
495                 return &null_frame;
496         if (p->owner) {
497                 /* We already hold the channel lock */
498                 if (f->frametype == AST_FRAME_VOICE) {
499                         if (f->subclass != p->owner->nativeformats) {
500                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
501                                 p->owner->nativeformats = f->subclass;
502                                 ast_set_read_format(p->owner, p->owner->readformat);
503                                 ast_set_write_format(p->owner, p->owner->writeformat);
504                         }
505                 
506                         /* Do in-band DTMF detection */
507                         if (p->dtmfmode & H323_DTMF_INBAND) {
508                    f = ast_dsp_process(p->owner,p->vad,f,0);
509                                    if (f->frametype == AST_FRAME_DTMF)
510                                         ast_log(LOG_DEBUG, "Got in-band digit %c.\n", f->subclass);
511             }
512                         
513                         
514                 }
515         }
516         return f;
517 }
518
519
520 static struct ast_frame  *oh323_read(struct ast_channel *c)
521 {
522         struct ast_frame *fr;
523         struct oh323_pvt *p = c->pvt->pvt;
524         ast_pthread_mutex_lock(&p->lock);
525         fr = oh323_rtp_read(p);
526         ast_pthread_mutex_unlock(&p->lock);
527         return fr;
528 }
529
530 static int oh323_write(struct ast_channel *c, struct ast_frame *frame)
531 {
532         struct oh323_pvt *p = c->pvt->pvt;
533         int res = 0;
534         if (frame->frametype != AST_FRAME_VOICE) {
535                 if (frame->frametype == AST_FRAME_IMAGE)
536                         return 0;
537                 else {
538                         ast_log(LOG_WARNING, "Can't send %d type frames with H323 write\n", frame->frametype);
539                         return 0;
540                 }
541         } else {
542                 if (!(frame->subclass & c->nativeformats)) {
543                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
544                                 frame->subclass, c->nativeformats, c->readformat, c->writeformat);
545                         return -1;
546                 }
547         }
548         if (p) {
549                 ast_pthread_mutex_lock(&p->lock);
550                 if (p->rtp) {
551                         res =  ast_rtp_write(p->rtp, frame);
552                 }
553                 ast_pthread_mutex_unlock(&p->lock);
554         }
555         return res;
556 }
557
558 /** FIXME: Can I acutally use this or does Open H.323 take care of everything? */
559 static int oh323_indicate(struct ast_channel *c, int condition)
560 {
561
562         struct oh323_pvt *p = c->pvt->pvt;
563         
564         switch(condition) {
565         case AST_CONTROL_RINGING:
566                 if (c->_state == AST_STATE_RING) {
567                 //      transmit_response(p, "180 Ringing", &p->initreq);
568                         break;
569                 }
570                 return -1;
571         case AST_CONTROL_BUSY:
572                 if (c->_state != AST_STATE_UP) {
573                 //      transmit_response(p, "600 Busy everywhere", &p->initreq);
574                         p->alreadygone = 1;
575                         ast_softhangup(c, AST_SOFTHANGUP_DEV);
576                         break;
577                 }
578                 return -1;
579         case AST_CONTROL_CONGESTION:
580                 if (c->_state != AST_STATE_UP) {
581                 //      transmit_response(p, "486 Busy here", &p->initreq);
582                         p->alreadygone = 1;
583                         ast_softhangup(c, AST_SOFTHANGUP_DEV);
584                         break;
585                 }
586                 return -1;
587         case -1:
588                 return -1;
589         default:
590                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
591                 return -1;
592         }
593         return 0;
594 }
595
596 // FIXME: WTF is this? Do I need this???
597 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
598 {
599         struct oh323_pvt *p = newchan->pvt->pvt;
600
601         ast_pthread_mutex_lock(&p->lock);
602         if (p->owner != oldchan) {
603                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
604                 return -1;
605         }
606         p->owner = newchan;
607         ast_pthread_mutex_unlock(&p->lock);
608         return 0;
609 }
610
611 static struct ast_channel *oh323_new(struct oh323_pvt *i, int state, const char *host)
612 {
613         struct ast_channel *tmp;
614         int fmt;
615         tmp = ast_channel_alloc(1);
616         
617         if (tmp) {
618                 
619                 snprintf(tmp->name, sizeof(tmp->name)-1, "H323/%s", host);
620                 tmp->nativeformats = i->capability;
621                 if (!tmp->nativeformats)
622                         tmp->nativeformats = capability;
623                 fmt = ast_best_codec(tmp->nativeformats);
624                 tmp->type = type;
625                 tmp->fds[0] = ast_rtp_fd(i->rtp);
626                 ast_setstate(tmp, state);
627                 
628                 if (state == AST_STATE_RING)
629                         tmp->rings = 1;
630                 
631                 tmp->writeformat = fmt;
632                 tmp->pvt->rawwriteformat = fmt;
633                 tmp->readformat = fmt;
634                 tmp->pvt->rawreadformat = fmt;
635                 
636                 /* Allocate dsp for in-band DTMF support */
637                 if (i->dtmfmode & H323_DTMF_INBAND) {
638                         i->vad = ast_dsp_new();
639                         ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
640         }
641
642                 /* Register the OpenH323 channel's functions. */
643                 tmp->pvt->pvt = i;
644                 tmp->pvt->send_digit = oh323_digit;
645                 tmp->pvt->call = oh323_call;
646                 tmp->pvt->hangup = oh323_hangup;
647                 tmp->pvt->answer = oh323_answer;
648                 tmp->pvt->read = oh323_read;
649                 tmp->pvt->write = oh323_write;
650                 tmp->pvt->indicate = oh323_indicate;
651                 tmp->pvt->fixup = oh323_fixup;
652 //              tmp->pvt->bridge = ast_rtp_bridge;
653
654                 /*  Set the owner of this channel */
655                 i->owner = tmp;
656                 
657                 ast_pthread_mutex_lock(&usecnt_lock);
658                 usecnt++;
659                 ast_pthread_mutex_unlock(&usecnt_lock);
660                 ast_update_use_count();
661                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
662                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);            
663                 tmp->priority = 1;
664                 if (strlen(i->callerid))
665                         tmp->callerid = strdup(i->callerid);
666                 if (strlen(i->accountcode))
667                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
668                 if (i->amaflags)
669                         tmp->amaflags = i->amaflags;
670                 if (state != AST_STATE_DOWN) {
671                         if (ast_pbx_start(tmp)) {
672                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
673                                 ast_hangup(tmp);
674                                 tmp = NULL;
675                         }
676                 }
677         } else
678                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
679         return tmp;
680 }
681
682 static struct oh323_pvt *oh323_alloc(int callid)
683 {
684         struct oh323_pvt *p;
685
686         p = malloc(sizeof(struct oh323_pvt));
687         if (!p) {
688                 ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
689                 return NULL;
690         }
691
692         /* Keep track of stuff */
693         memset(p, 0, sizeof(struct oh323_pvt));
694         p->rtp = ast_rtp_new(sched, io, 1, 0);
695
696         if (!p->rtp) {
697                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
698                 free(p);
699                 return NULL;
700         }
701         ast_rtp_settos(p->rtp, tos);
702         ast_pthread_mutex_init(&p->lock);
703         
704         p->cd.call_reference = callid;
705         p->bridge = 1;
706         
707         p->dtmfmode = dtmfmode;
708         if (p->dtmfmode & H323_DTMF_RFC2833)
709                 p->nonCodecCapability |= AST_RTP_DTMF;
710
711         /* Add to interface list */
712         ast_pthread_mutex_lock(&iflock);
713         p->next = iflist;
714         iflist = p;
715         ast_pthread_mutex_unlock(&iflock);
716         return p;
717 }
718
719 static struct oh323_pvt *find_call(int call_reference)
720 {  
721         struct oh323_pvt *p;
722
723                 ast_pthread_mutex_lock(&iflock);
724         p = iflist; 
725
726         while(p) {
727                 if (p->cd.call_reference == call_reference) {
728                         /* Found the call */                                            
729                                                 ast_pthread_mutex_unlock(&iflock);
730                                                 return p;
731                 }
732                 p = p->next; 
733         }
734         ast_pthread_mutex_unlock(&iflock);
735                 return NULL;
736         
737 }
738
739 static struct ast_channel *oh323_request(char *type, int format, void *data)
740 {
741
742         int oldformat;
743         struct oh323_pvt *p;
744         struct ast_channel *tmpc = NULL;
745         char *dest = data;
746         char *ext, *host;
747         char *h323id = NULL;
748         char tmp[256];
749
750         
751         ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
752
753         oldformat = format;
754         format &= capability;
755         if (!format) {
756                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
757                 return NULL;
758         }
759         
760         strncpy(tmp, dest, sizeof(tmp) - 1);
761                 
762         host = strchr(tmp, '@');
763         if (host) {
764                 *host = '\0';
765                 host++;
766                 ext = tmp;
767         } else {
768                 host = tmp;
769                 ext = NULL;
770         }
771
772         strtok_r(host, "/", &(h323id));
773                 
774         if (*h323id) {
775                 h323_set_id(h323id);
776         }
777                 
778         
779         p = oh323_alloc(0);
780
781         if (!p) {
782                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
783                 return NULL;
784         }
785
786         /* Assign a default capability */
787         p->capability = capability;
788
789         if (p->dtmfmode) {
790                 if (p->dtmfmode & H323_DTMF_RFC2833)
791                         p->nonCodecCapability |= AST_RTP_DTMF;
792                 else
793                         p->nonCodecCapability &= ~AST_RTP_DTMF;
794         }
795
796
797         ast_log(LOG_DEBUG, "Host: %s\tUsername: %s\n", host, p->username);
798
799         if (ext)
800                 strncpy(p->username, ext, sizeof(p->username) - 1);
801         tmpc = oh323_new(p, AST_STATE_DOWN, host);
802         if (!tmpc)
803                 oh323_destroy(p);
804         
805         restart_monitor();
806         
807         return tmpc;
808 }
809
810 struct oh323_alias *find_alias(const char *source_aliases)
811 {
812         struct oh323_alias *a;
813
814         a = aliasl.aliases;
815
816         while(a) {
817
818                 if (!strcasecmp(a->name, source_aliases)) {
819                         break;
820                 }
821                 a = a->next;
822         }
823         return a;
824 }
825
826 struct oh323_user *find_user(const char *source_aliases)
827 {
828         struct oh323_user *u;
829
830         u = userl.users;
831
832         while(u) {
833
834                 if (!strcasecmp(u->name, source_aliases)) {
835                         break;
836                 }
837                 u = u->next;
838         }
839         return u;
840
841 }
842
843 struct oh323_peer *find_peer(char *dest_peer)
844 {
845         struct oh323_peer *p;
846
847         p = peerl.peers;
848
849         while(p) {
850                 if (!strcasecmp(p->name, dest_peer)) {
851                         break;
852                 }
853                 p = p->next;
854         }
855         return p;
856
857 }
858
859 /**
860   * Callback for sending digits from H.323 up to asterisk
861   *
862   */
863 int send_digit(unsigned call_reference, char digit)
864 {
865         struct oh323_pvt *p;
866         struct ast_frame f;
867
868         ast_log(LOG_DEBUG, "Recieved Digit: %c\n", digit);
869         p = find_call(call_reference);
870         
871         if (!p) {
872                 ast_log(LOG_ERROR, "Private structure not found in send_digit.\n");
873                 return -1;
874         }
875         memset(&f, 0, sizeof(f));
876         f.frametype = AST_FRAME_DTMF;
877     f.subclass = digit;
878     f.datalen = 0;
879     f.samples = 300;
880         f.offset = 0;
881         f.data = NULL;
882     f.mallocd = 0;
883     f.src = "SEND_DIGIT";
884         
885         return ast_queue_frame(p->owner, &f, 1);        
886 }
887
888 /**
889   * Call-back function that gets called when any H.323 connection is made
890   *
891   * Returns the local RTP port
892   */
893 int create_connection(unsigned call_reference)
894 {       
895         struct oh323_pvt *p;
896         struct sockaddr_in us;
897
898         p = find_call(call_reference);
899
900         if (!p) {
901                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is very bad.\n");
902                 return -1;
903         }
904
905         /* figure out our local RTP port and tell the H.323 stack about it*/
906         ast_rtp_get_us(p->rtp, &us);
907         return ntohs(us.sin_port);
908 }
909
910 /**
911  *  Call-back function for incoming calls
912  *
913  *  Returns 1 on success
914  */
915
916 int setup_incoming_call(call_details_t cd)
917 {
918         
919         struct oh323_pvt *p = NULL;
920         struct ast_channel *c = NULL;
921         struct oh323_user *user = NULL;
922         struct oh323_alias *alias = NULL;
923
924         /* allocate the call*/
925         p = oh323_alloc(cd.call_reference);
926
927         if (!p) {
928                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
929                 return 0;
930         }
931
932         /* Populate the call details in the private structure */
933         p->cd.call_token = cd.call_token;
934         p->cd.call_source_aliases = cd.call_source_aliases;
935         p->cd.call_dest_alias = cd.call_dest_alias;
936         p->cd.call_source_e164 = cd.call_source_e164;
937         p->cd.call_dest_e164 = cd.call_dest_e164;
938
939         if (h323debug) {
940                 printf("        == Setting up Call\n");
941                 printf("           -- Calling party name:  %s\n", p->cd.call_source_aliases);
942                 printf("           -- Calling party number:  %s\n", p->cd.call_source_e164);
943                 printf("           -- Called  party name:  %s\n", p->cd.call_dest_alias);
944                 printf("           -- Called  party number:  %s\n", p->cd.call_dest_e164);
945         }
946
947         /* Decide if we are allowing Gatekeeper routed calls*/
948         if ((!strcasecmp(cd.sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk == 1)) {
949                 
950                 if (strlen(cd.call_dest_e164)) {
951                         strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
952                         strncpy(p->context, default_context, sizeof(p->context)-1); 
953                 } else {
954                         alias = find_alias(cd.call_dest_alias);
955                 
956                         if (!alias) {
957                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd.call_dest_alias);
958                                 return 0;
959                         }
960                         printf("Alias found: %s and %s\n", alias->name, alias->context);
961
962                         strncpy(p->exten, alias->name, sizeof(p->exten)-1);
963                         strncpy(p->context, alias->context, sizeof(p->context)-1);
964                 }
965
966                 sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164);
967
968         } else { 
969                 /* Either this call is not from the Gatekeeper 
970                    or we are not allowing gk routed calls */
971                 
972                 user  = find_user(cd.call_source_aliases);
973                 
974                 if (!user) {
975                         sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164); 
976                         if (strlen(p->cd.call_dest_e164)) {
977                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
978                         } else {
979                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
980                         }
981                         if (!strlen(default_context)) {
982                                 ast_log(LOG_ERROR, "Call from user '%s' rejected due to no default context\n", p->cd.call_source_aliases);
983                                 return 0;
984                         }
985                         strncpy(p->context, default_context, sizeof(p->context)-1);
986                         ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd.call_source_aliases, p->context);
987                 } else {
988                         if (user->host) {
989                                 if (strcasecmp(cd.sourceIp, inet_ntoa(user->addr.sin_addr))){
990                                         
991                                         if(!strlen(default_context)) {
992                                                 ast_log(LOG_ERROR, "Call from user '%s' rejected due to non-matching IP address of '%s'\n", user->name, cd.sourceIp);
993                                 return 0;
994                                         }
995                                         strncpy(p->context, default_context, sizeof(p->context)-1);
996                                         sprintf(p->exten,"i");
997                                         goto exit;                                      
998                                 }
999                         }
1000                         if (user->incominglimit > 0) {
1001                                 if (user->inUse >= user->incominglimit) {
1002                                         ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", user->name, user->incominglimit);
1003                                         return 0;
1004                                 }
1005                         }
1006                         strncpy(p->context, user->context, sizeof(p->context)-1);
1007                         p->bridge = user->bridge;
1008
1009                         if (strlen(user->callerid)) 
1010                                 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
1011                         else
1012                                 if (!strlen(p->cd.call_source_aliases)) 
1013                                         sprintf(p->callerid, "Unknown Name <%s>", p->cd.call_source_e164); 
1014                                 else
1015                                         sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164); 
1016
1017                         if (strlen(p->cd.call_dest_e164)) {
1018                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1019                         } else {
1020                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
1021                         }
1022
1023                         if (strlen(user->accountcode)) {
1024                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)-1);
1025                         } 
1026
1027                         /* Increment the usage counter */
1028                         user->inUse++;
1029                 } 
1030         }
1031
1032 /* I know this is horrid, don't kill me saddam */
1033 exit:
1034         /* allocate a channel and tell asterisk about it */
1035         c = oh323_new(p, AST_STATE_RINGING, cd.call_token);
1036
1037         if (!c) {
1038                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1039                 return 0;
1040         }
1041
1042         return 1;
1043 }
1044
1045 /**
1046  * Call-back function to establish an outgoing H.323 call
1047  * 
1048  * Returns 1 on success 
1049  */
1050 int setup_outgoing_call(call_details_t cd)
1051 {       
1052         return 1;
1053 }
1054
1055 #if 0
1056 if (p->inUse >= p->outgoinglimit) {
1057         ast_log(LOG_ERROR, "Call to %s rejected due to usage limit of %d outgoing channels\n", p->name, p->inUse);
1058         return 0;
1059 }
1060
1061 if (!p) {
1062         ast_log(LOG_ERROR, "Rejecting call: peer %s not found\n", dest_peer);
1063         return 0;
1064 }
1065 #endif
1066
1067 /**
1068   * Call-back function that gets called for each rtp channel opened 
1069   *
1070   * Returns nothing 
1071   */
1072 void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort)
1073 {
1074         struct oh323_pvt *p = NULL;
1075         struct sockaddr_in them;
1076
1077         /* Find the call or allocate a private structure if call not found */
1078         p = find_call(call_reference);
1079
1080         if (!p) {
1081                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1082                 return;
1083         }
1084
1085         them.sin_family = AF_INET;
1086         them.sin_addr.s_addr = inet_addr(remoteIp); // only works for IPv4
1087         them.sin_port = htons(remotePort);
1088         ast_rtp_set_peer(p->rtp, &them);
1089
1090         return;
1091 }
1092
1093 /**  
1094   *     Call-back function to signal asterisk that the channel has been answered 
1095   * Returns nothing
1096   */
1097 void connection_made(unsigned call_reference)
1098 {
1099         struct ast_channel *c = NULL;
1100         struct oh323_pvt *p = NULL;
1101         
1102         p = find_call(call_reference);
1103         
1104         if (!p)
1105                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1106
1107
1108         if (!p->owner) {
1109                 printf("Channel has no owner\n");
1110                 return;
1111         }
1112         c = p->owner;   
1113
1114         ast_setstate(c, AST_STATE_UP);
1115         return;
1116 }
1117
1118 /**
1119   * Call-back function to cleanup communication
1120   * Returns nothing,
1121   */
1122 void cleanup_connection(call_details_t cd)
1123 {       
1124         struct oh323_pvt *p = NULL;
1125 //      struct oh323_peer *peer = NULL;
1126         struct oh323_user *user = NULL;
1127         struct ast_rtp *rtp = NULL;
1128
1129         ast_log(LOG_DEBUG, "Cleaning up our mess\n");
1130         
1131         p = find_call(cd.call_reference);
1132
1133         if (!p) {
1134                 return;
1135         }
1136
1137         /* Decrement usage counter */
1138         if (!p->outgoing) {
1139                 user = find_user(cd.call_source_aliases);
1140                 
1141                 if(user)
1142                         user->inUse--;
1143         }
1144
1145 #if 0
1146                 if (p->outgoing) {
1147                 peer = find_peer(cd.call_dest_alias);
1148                 peer->inUse--;
1149         } else {
1150                 user = find_user(cd.call_source_aliases);
1151                 user->inUse--;
1152         }
1153 #endif
1154         
1155         if (p->rtp) {
1156                 rtp = p->rtp;
1157                 p->rtp = NULL;
1158                 /* Immediately stop RTP */
1159                 ast_rtp_destroy(rtp);
1160         }
1161         
1162         p->alreadygone = 1;
1163
1164         /* Send hangup */       
1165         if (p->owner)
1166                 ast_queue_hangup(p->owner, 1);
1167
1168         p = NULL;
1169         return; 
1170 }
1171
1172 static void *do_monitor(void *data)
1173 {
1174         int res;
1175         struct oh323_pvt *oh323 = NULL;
1176         
1177                 for(;;) {
1178                 /* Check for interfaces needing to be killed */
1179                 ast_pthread_mutex_lock(&iflock);
1180 restartsearch:          
1181                 oh323 = iflist;
1182                 while(oh323) {
1183                         if (oh323->needdestroy) {
1184                                 __oh323_destroy(oh323);
1185                                 goto restartsearch;
1186                         }
1187                         oh323 = oh323->next;
1188                 }
1189                 ast_pthread_mutex_unlock(&iflock);
1190
1191                 pthread_testcancel();
1192
1193                 /* Wait for sched or io */
1194                 res = ast_sched_wait(sched);
1195                 if ((res < 0) || (res > 1000))
1196                         res = 1000;
1197                 res = ast_io_wait(io, res);
1198                 ast_pthread_mutex_lock(&monlock);
1199                 if (res >= 0) 
1200                         ast_sched_runq(sched);
1201                 ast_pthread_mutex_unlock(&monlock);
1202         }
1203         /* Never reached */
1204         return NULL;
1205         
1206 }
1207
1208 static int restart_monitor(void)
1209 {
1210         /* If we're supposed to be stopped -- stay stopped */
1211         if (monitor_thread == -2)
1212                 return 0;
1213         if (ast_pthread_mutex_lock(&monlock)) {
1214                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1215                 return -1;
1216         }
1217         if (monitor_thread == pthread_self()) {
1218                 ast_pthread_mutex_unlock(&monlock);
1219                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1220                 return -1;
1221         }
1222         if (monitor_thread) {
1223                 /* Wake up the thread */
1224                 pthread_kill(monitor_thread, SIGURG);
1225         } else {
1226                 /* Start a new monitor */
1227                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1228                         ast_pthread_mutex_unlock(&monlock);
1229                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1230                         return -1;
1231                 }
1232         }
1233         ast_pthread_mutex_unlock(&monlock);
1234         return 0;
1235 }
1236
1237 static int h323_do_trace(int fd, int argc, char *argv[])
1238 {
1239         if (argc != 3)
1240                 return RESULT_SHOWUSAGE;
1241         
1242         h323_debug(1, atoi(argv[2]));
1243         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1244         return RESULT_SUCCESS;
1245 }
1246
1247 static int h323_no_trace(int fd, int argc, char *argv[])
1248 {
1249         if (argc != 3)
1250                 return RESULT_SHOWUSAGE;
1251
1252         h323_debug(0,0);
1253         ast_cli(fd, "H.323 trace disabled\n");
1254         return RESULT_SUCCESS;
1255 }
1256
1257 static int h323_do_debug(int fd, int argc, char *argv[])
1258 {
1259         if (argc != 2)
1260                 return RESULT_SHOWUSAGE;
1261         
1262         h323debug = 1;
1263         ast_cli(fd, "H323 debug enabled\n");
1264         return RESULT_SUCCESS;
1265 }
1266
1267 static int h323_no_debug(int fd, int argc, char *argv[])
1268 {
1269         if (argc != 3)
1270                 return RESULT_SHOWUSAGE;
1271
1272         h323debug = 0;
1273         ast_cli(fd, "H323 Debug disabled\n");
1274         return RESULT_SUCCESS;
1275 }
1276
1277 static int h323_gk_cycle(int fd, int argc, char *argv[])
1278 {
1279         if (argc != 3)
1280                 return RESULT_SHOWUSAGE;
1281                 
1282         h323_gk_urq();
1283         
1284         /* Possibly register with a GK */
1285         if (gatekeeper_disable == 0) {
1286                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1287                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1288                         h323_end_process();
1289                 }
1290         }
1291
1292         return RESULT_SUCCESS;
1293 }
1294
1295
1296 static char trace_usage[] = 
1297 "Usage: h.323 trace <level num>\n"
1298 "       Enables H.323 stack tracing for debugging purposes\n";
1299
1300 static char no_trace_usage[] = 
1301 "Usage: h.323 no trace\n"
1302 "       Disables H.323 stack tracing for debugging purposes\n";
1303
1304 static char debug_usage[] = 
1305 "Usage: h.323 debug\n"
1306 "       Enables chan_h323 debug output\n";
1307
1308 static char no_debug_usage[] = 
1309 "Usage: h.323 no debug\n"
1310 "       Disables chan_h323 debug output\n";
1311
1312 static char show_codec_usage[] = 
1313 "Usage: h.323 show codec\n"
1314 "       Shows all enabled codecs\n";
1315
1316 static char show_cycle_usage[] = 
1317 "Usage: h.323 gk cycle\n"
1318 "       Manually re-register with the Gatekeper\n";
1319
1320
1321 static struct ast_cli_entry  cli_trace =
1322         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1323 static struct ast_cli_entry  cli_no_trace =
1324         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1325 static struct ast_cli_entry  cli_debug =
1326         { { "h.323", "debug", NULL }, h323_do_debug, "Enable chan_h323 debug", debug_usage };
1327 static struct ast_cli_entry  cli_no_debug =
1328         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable chan_h323 debug", no_debug_usage };
1329 static struct ast_cli_entry  cli_show_codecs =
1330         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1331 static struct ast_cli_entry  cli_gk_cycle =
1332         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1333
1334
1335
1336 int reload_config()
1337 {
1338         
1339         int format;
1340         struct ast_config *cfg;
1341         struct ast_variable *v;
1342         struct oh323_peer *peer   = NULL;
1343         struct oh323_user *user   = NULL;
1344         struct oh323_alias *alias = NULL;
1345         struct hostent *hp;
1346         char *cat;
1347     char *utype;
1348         
1349         cfg = ast_load(config);
1350
1351         /* We *must* have a config file otherwise stop immediately */
1352         if (!cfg) {
1353                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
1354                 return 0;
1355         }
1356         
1357         h323debug=0;
1358         dtmfmode = H323_DTMF_RFC2833;
1359
1360         memset(&bindaddr, 0, sizeof(bindaddr));
1361
1362         v = ast_variable_browse(cfg, "general");
1363         while(v) {
1364                 /* Create the interface list */
1365                 if (!strcasecmp(v->name, "port")) {
1366                         port = (int)strtol(v->value, NULL, 10);
1367                 } else if (!strcasecmp(v->name, "bindaddr")) {
1368                         if (!(hp = gethostbyname(v->value))) {
1369                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1370                         } else {
1371                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1372                         }
1373                 } else if (!strcasecmp(v->name, "allow")) {
1374                         format = ast_getformatbyname(v->value);
1375                         if (format < 1) 
1376                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1377                         else
1378                                 capability |= format;
1379                 } else if (!strcasecmp(v->name, "disallow")) {
1380                         format = ast_getformatbyname(v->value);
1381                         if (format < 1) 
1382                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1383                         else
1384                                 capability &= ~format;
1385                 } else if (!strcasecmp(v->name, "tos")) {
1386                         if (sscanf(v->value, "%i", &format) == 1)
1387                                 tos = format & 0xff;
1388                         else if (!strcasecmp(v->value, "lowdelay"))
1389                                 tos = IPTOS_LOWDELAY;
1390                         else if (!strcasecmp(v->value, "throughput"))
1391                                 tos = IPTOS_THROUGHPUT;
1392                         else if (!strcasecmp(v->value, "reliability"))
1393                                 tos = IPTOS_RELIABILITY;
1394                         else if (!strcasecmp(v->value, "mincost"))
1395                                 tos = IPTOS_MINCOST;
1396                         else if (!strcasecmp(v->value, "none"))
1397                                 tos = 0;
1398                         else
1399                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
1400                 } else if (!strcasecmp(v->name, "gatekeeper")) {
1401                         if (!strcasecmp(v->value, "DISABLE")) {
1402                                 gatekeeper_disable = 1;
1403                                 usingGk = 0;
1404                         } else if (!strcasecmp(v->value, "DISCOVER")) {
1405                                 gatekeeper_disable = 0;
1406                                 gatekeeper_discover = 1;
1407                                 usingGk = 1;
1408                         } else {
1409                                 gatekeeper_disable = 0;
1410                                 usingGk = 1;
1411                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper)-1);
1412                         }
1413                 } else if (!strcasecmp(v->name, "secret")) {
1414                                 strncpy(secret, v->value, sizeof(secret)-1);
1415                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
1416                                 gkroute = ast_true(v->value);
1417                 } else if (!strcasecmp(v->name, "context")) {
1418                         strncpy(default_context, v->value, sizeof(default_context)-1);
1419                         printf("  == Setting default context to %s\n", default_context);        
1420                 } else if (!strcasecmp(v->name, "dtmfmode")) {
1421                         if (!strcasecmp(v->value, "inband"))
1422                                 dtmfmode=H323_DTMF_INBAND;
1423                         else if (!strcasecmp(v->value, "rfc2833"))
1424                                 dtmfmode = H323_DTMF_RFC2833;
1425                         else {
1426                                 ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1427                                 dtmfmode = H323_DTMF_RFC2833;
1428                         }
1429                 }
1430                 v = v->next;    
1431         }
1432         
1433         cat = ast_category_browse(cfg, NULL);
1434         while(cat) {
1435                 if (strcasecmp(cat, "general")) {
1436                         utype = ast_variable_retrieve(cfg, cat, "type");
1437                         if (utype) {
1438                                 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
1439                                         user = build_user(cat, ast_variable_browse(cfg, cat));
1440                                         if (user) {
1441                                                 ast_pthread_mutex_lock(&userl.lock);
1442                                                 user->next = userl.users;
1443                                                 userl.users = user;
1444                                                 ast_pthread_mutex_unlock(&userl.lock);
1445                                         }
1446                                 }  else if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
1447                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
1448                                         if (peer) {
1449                                                 ast_pthread_mutex_lock(&peerl.lock);
1450                                                 peer->next = peerl.peers;
1451                                                 peerl.peers = peer;
1452                                                 ast_pthread_mutex_unlock(&peerl.lock);
1453                                         }
1454                                 }  else if (!strcasecmp(utype, "h323")) {                       
1455                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
1456                                         if (alias) {
1457                                                 ast_pthread_mutex_lock(&aliasl.lock);
1458                                                 alias->next = aliasl.aliases;
1459                                                 aliasl.aliases = alias;
1460                                                 ast_pthread_mutex_unlock(&aliasl.lock);
1461                                         }
1462                                 } else {
1463                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
1464                                 }
1465                         } else
1466                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
1467                 }
1468                 cat = ast_category_browse(cfg, cat);
1469         }
1470
1471         /* Register our H.323 aliases if any*/
1472         while (alias) {         
1473                 if (h323_set_alias(alias)) {
1474                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
1475                         return -1;
1476                 }       
1477                 alias = alias->next;
1478         }
1479
1480         /* Add some capabilities */
1481         if(h323_set_capability(capability, dtmfmode)) {
1482                 ast_log(LOG_ERROR, "Capabilities failure, this is bad.\n");
1483                 return -1;
1484         }       
1485         ast_destroy(cfg);
1486
1487         return 0;
1488 }
1489
1490 void delete_users(void)
1491 {
1492         struct oh323_user *user, *userlast;
1493         struct oh323_peer *peer;
1494         
1495         /* Delete all users */
1496         ast_pthread_mutex_lock(&userl.lock);
1497         for (user=userl.users;user;) {
1498                 userlast = user;
1499                 user=user->next;
1500                 free(userlast);
1501         }
1502         userl.users=NULL;
1503         ast_pthread_mutex_unlock(&userl.lock);
1504         ast_pthread_mutex_lock(&peerl.lock);
1505         for (peer=peerl.peers;peer;) {
1506                 /* Assume all will be deleted, and we'll find out for sure later */
1507                 peer->delme = 1;
1508                 peer = peer->next;
1509         }
1510         ast_pthread_mutex_unlock(&peerl.lock);
1511 }
1512
1513 void delete_aliases(void)
1514 {
1515         struct oh323_alias *alias, *aliaslast;
1516                 
1517         /* Delete all users */
1518         ast_pthread_mutex_lock(&aliasl.lock);
1519         for (alias=aliasl.aliases;alias;) {
1520                 aliaslast = alias;
1521                 alias=alias->next;
1522                 free(aliaslast);
1523         }
1524         aliasl.aliases=NULL;
1525         ast_pthread_mutex_unlock(&aliasl.lock);
1526 }
1527
1528 void prune_peers(void)
1529 {
1530         /* Prune peers who still are supposed to be deleted */
1531         struct oh323_peer *peer, *peerlast, *peernext;
1532         ast_pthread_mutex_lock(&peerl.lock);
1533         peerlast = NULL;
1534         for (peer=peerl.peers;peer;) {
1535                 peernext = peer->next;
1536                 if (peer->delme) {
1537                         free(peer);
1538                         if (peerlast)
1539                                 peerlast->next = peernext;
1540                         else
1541                                 peerl.peers = peernext;
1542                 } else
1543                         peerlast = peer;
1544                 peer=peernext;
1545         }
1546         ast_pthread_mutex_unlock(&peerl.lock);
1547 }
1548
1549 int reload(void)
1550 {
1551         delete_users();
1552         delete_aliases();
1553         prune_peers();
1554
1555         if (strlen(gatekeeper)) {
1556                 h323_gk_urq();
1557         }
1558
1559         reload_config();
1560
1561         /* Possibly register with a GK */
1562         if (gatekeeper_disable == 0) {
1563                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1564                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1565                         h323_end_process();
1566                         return -1;
1567                 }
1568         }
1569         restart_monitor();
1570         return 0;
1571 }
1572
1573
1574 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
1575 {
1576         struct oh323_pvt *p;
1577         p = chan->pvt->pvt;
1578         if (p && p->rtp && p->bridge)
1579                 return p->rtp;
1580         return NULL;
1581 }
1582
1583 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
1584 {
1585         return NULL;
1586 }
1587
1588 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp)
1589 {
1590         /* XXX Deal with Video */
1591         
1592         struct oh323_pvt *p;
1593         struct sockaddr_in them;
1594         struct sockaddr_in us;
1595
1596         if (!rtp) 
1597                 return 0;
1598
1599         p = chan->pvt->pvt;
1600         if (!p) {
1601                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
1602                 return -1;
1603         }
1604
1605         ast_rtp_get_peer(rtp, &them);   
1606         printf("peer is now: %s\n", inet_ntoa(them.sin_addr));
1607                 
1608         ast_rtp_set_peer(p->rtp, &them);
1609         ast_rtp_get_us(p->rtp, &us);
1610
1611         h323_native_bridge(p->cd.call_token, inet_ntoa(them.sin_addr), inet_ntoa(us.sin_addr));
1612         
1613         return 0;
1614         
1615 }
1616
1617 static struct ast_rtp_protocol oh323_rtp = {
1618         get_rtp_info: oh323_get_rtp_peer,
1619         get_vrtp_info: oh323_get_vrtp_peer,
1620         set_rtp_peer: oh323_set_rtp_peer,
1621 };
1622
1623
1624 int load_module()
1625 {
1626         int res;
1627
1628         /* fire up the H.323 Endpoint */ 
1629         h323_end_point_create();
1630
1631         res = reload_config();
1632         if (!res) {
1633         /* Make sure we can register our channel type */
1634                 if (ast_channel_register(type, tdesc, capability, oh323_request)) {
1635                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1636                         h323_end_process();
1637                         return -1;
1638                 }
1639                 ast_cli_register(&cli_debug);
1640                 ast_cli_register(&cli_no_debug);
1641                 ast_cli_register(&cli_trace);
1642                 ast_cli_register(&cli_no_trace);
1643                 ast_cli_register(&cli_show_codecs);
1644                 ast_cli_register(&cli_gk_cycle);
1645
1646                 oh323_rtp.type = type;
1647                 ast_rtp_proto_register(&oh323_rtp);
1648
1649                 sched = sched_context_create();
1650                 if (!sched) {
1651                         ast_log(LOG_WARNING, "Unable to create schedule context\n");
1652                 }
1653                 io = io_context_create();
1654                 if (!io) {
1655                         ast_log(LOG_WARNING, "Unable to create I/O context\n");
1656                 }
1657                 
1658                 /* Register our callback functions */
1659                 h323_callback_register(setup_incoming_call, 
1660                                                            setup_outgoing_call, 
1661                                                            create_connection, 
1662                                                            setup_rtp_connection, 
1663                                                            cleanup_connection, 
1664                                                            connection_made, send_digit);        
1665         
1666                 /* start the h.323 listener */
1667                 if (h323_start_listener(port, bindaddr)) {
1668                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
1669 //                      h323_end_process();
1670                         return -1;
1671                 }
1672
1673                 /* Possibly register with a GK */
1674                 if (gatekeeper_disable == 0) {
1675                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1676                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1677 //                              h323_end_process();
1678                                 return -1;
1679                         }
1680                 }
1681                 /* And start the monitor for the first time */
1682                 restart_monitor();
1683         } else {
1684                 h323_end_process();
1685         }
1686         return res;
1687 }
1688 int unload_module() 
1689 {
1690         struct oh323_pvt *p, *pl;
1691                 
1692         if (!ast_pthread_mutex_lock(&iflock)) {
1693         /* hangup all interfaces if they have an owner */
1694         p = iflist;
1695         while(p) {
1696                 if (p->owner)
1697                         ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1698                 p = p->next;
1699         }
1700         iflist = NULL;
1701         ast_pthread_mutex_unlock(&iflock);
1702         } else {
1703                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1704                 return -1;
1705         }
1706                 
1707         if (!ast_pthread_mutex_lock(&iflock)) {
1708                 /* destroy all the interfaces and free their memory */
1709                 p = iflist;
1710                 while(p) {
1711                         pl = p;
1712                         p = p->next;
1713                         /* free associated memory */
1714                         free(pl);
1715                 }
1716                 iflist = NULL;
1717                 ast_pthread_mutex_unlock(&iflock);
1718         } else {
1719                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1720                 return -1;
1721         }
1722         h323_gk_urq();
1723         h323_end_process();
1724
1725         /* unregister rtp */
1726         ast_rtp_proto_unregister(&oh323_rtp);
1727         
1728         /* unregister commands */
1729         ast_cli_unregister(&cli_debug);
1730         ast_cli_unregister(&cli_no_debug);
1731         ast_cli_unregister(&cli_trace);
1732         ast_cli_unregister(&cli_no_trace);
1733         ast_cli_unregister(&cli_show_codecs);
1734         ast_cli_unregister(&cli_gk_cycle);
1735
1736         /* unregister channel type */
1737         ast_channel_unregister(type);
1738
1739         return 0;
1740
1741 }
1742
1743 int usecount()
1744 {
1745         int res;
1746         ast_pthread_mutex_lock(&usecnt_lock);
1747         res = usecnt;
1748         ast_pthread_mutex_unlock(&usecnt_lock);
1749         return res;
1750 }
1751
1752 char *description()
1753 {
1754         return desc;
1755 }
1756
1757 char *key()
1758 {
1759         return ASTERISK_GPL_KEY;
1760 }
1761
1762
1763
1764