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