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