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