remote lame ^M's
[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(NULL, NULL);
688         if (!p->rtp) {
689                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
690                 free(p);
691                 return NULL;
692         }
693         ast_rtp_settos(p->rtp, tos);
694         ast_pthread_mutex_init(&p->lock);
695         
696         p->cd.call_reference = callid;
697         p->bridge = 1;
698         
699         p->dtmfmode = dtmfmode;
700         if (p->dtmfmode & H323_DTMF_RFC2833)
701                 p->nonCodecCapability |= AST_RTP_DTMF;
702
703         /* Add to interface list */
704         ast_pthread_mutex_lock(&iflock);
705         p->next = iflist;
706         iflist = p;
707         ast_pthread_mutex_unlock(&iflock);
708         return p;
709 }
710
711 static struct oh323_pvt *find_call(int call_reference)
712 {  
713         struct oh323_pvt *p;
714
715                 ast_pthread_mutex_lock(&iflock);
716         p = iflist; 
717
718         while(p) {
719                 if (p->cd.call_reference == call_reference) {
720                         /* Found the call */                                            
721                                                 ast_pthread_mutex_unlock(&iflock);
722                                                 return p;
723                 }
724                 p = p->next; 
725         }
726         ast_pthread_mutex_unlock(&iflock);
727                 return NULL;
728         
729 }
730
731 static struct ast_channel *oh323_request(char *type, int format, void *data)
732 {
733
734         int oldformat;
735         struct oh323_pvt *p;
736         struct ast_channel *tmpc = NULL;
737         char *dest = data;
738         char *ext, *host;
739         char *h323id = NULL;
740         char tmp[256];
741
742         
743         ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
744
745         oldformat = format;
746         format &= capability;
747         if (!format) {
748                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
749                 return NULL;
750         }
751         
752         strncpy(tmp, dest, sizeof(tmp) - 1);
753                 
754         host = strchr(tmp, '@');
755         if (host) {
756                 *host = '\0';
757                 host++;
758                 ext = tmp;
759         } else {
760                 host = tmp;
761                 ext = NULL;
762         }
763
764         strtok_r(host, "/", &(h323id));
765                 
766         if (*h323id) {
767                 h323_set_id(h323id);
768         }
769                 
770         
771         p = oh323_alloc(0);
772
773         if (!p) {
774                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
775                 return NULL;
776         }
777
778         /* Assign a default capability */
779         p->capability = capability;
780
781         if (p->dtmfmode) {
782                 if (p->dtmfmode & H323_DTMF_RFC2833)
783                         p->nonCodecCapability |= AST_RTP_DTMF;
784                 else
785                         p->nonCodecCapability &= ~AST_RTP_DTMF;
786         }
787
788
789         ast_log(LOG_DEBUG, "Host: %s\tUsername: %s\n", host, p->username);
790
791         if (ext)
792                 strncpy(p->username, ext, sizeof(p->username) - 1);
793         tmpc = oh323_new(p, AST_STATE_DOWN, host);
794         if (!tmpc)
795                 oh323_destroy(p);
796         
797         restart_monitor();
798         
799         return tmpc;
800 }
801
802 struct oh323_alias *find_alias(const char *source_aliases)
803 {
804         struct oh323_alias *a;
805
806         a = aliasl.aliases;
807
808         while(a) {
809
810                 if (!strcasecmp(a->name, source_aliases)) {
811                         break;
812                 }
813                 a = a->next;
814         }
815         return a;
816 }
817
818 struct oh323_user *find_user(const char *source_aliases)
819 {
820         struct oh323_user *u;
821
822         u = userl.users;
823
824         while(u) {
825
826                 if (!strcasecmp(u->name, source_aliases)) {
827                         break;
828                 }
829                 u = u->next;
830         }
831         return u;
832
833 }
834
835 struct oh323_peer *find_peer(char *dest_peer)
836 {
837         struct oh323_peer *p;
838
839         p = peerl.peers;
840
841         while(p) {
842                 if (!strcasecmp(p->name, dest_peer)) {
843                         break;
844                 }
845                 p = p->next;
846         }
847         return p;
848
849 }
850
851 /**
852   * Callback for sending digits from H.323 up to asterisk
853   *
854   */
855 int send_digit(unsigned call_reference, char digit)
856 {
857         struct oh323_pvt *p;
858         struct ast_frame f;
859
860         ast_log(LOG_DEBUG, "Recieved Digit: %c\n", digit);
861         p = find_call(call_reference);
862         
863         if (!p) {
864                 ast_log(LOG_ERROR, "Private structure not found in send_digit.\n");
865                 return -1;
866         }
867         memset(&f, 0, sizeof(f));
868         f.frametype = AST_FRAME_DTMF;
869     f.subclass = digit;
870     f.datalen = 0;
871     f.samples = 300;
872         f.offset = 0;
873         f.data = NULL;
874     f.mallocd = 0;
875     f.src = "SEND_DIGIT";
876         
877         return ast_queue_frame(p->owner, &f, 1);        
878 }
879
880 /**
881   * Call-back function that gets called when any H.323 connection is made
882   *
883   * Returns the local RTP port
884   */
885 int create_connection(unsigned call_reference)
886 {       
887         struct oh323_pvt *p;
888         struct sockaddr_in us;
889
890         p = find_call(call_reference);
891
892         if (!p) {
893                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is very bad.\n");
894                 return -1;
895         }
896
897         /* figure out our local RTP port and tell the H.323 stack about it*/
898         ast_rtp_get_us(p->rtp, &us);
899         return ntohs(us.sin_port);
900 }
901
902 /**
903  *  Call-back function for incoming calls
904  *
905  *  Returns 1 on success
906  */
907
908 int setup_incoming_call(call_details_t cd)
909 {
910         
911         struct oh323_pvt *p = NULL;
912         struct ast_channel *c = NULL;
913         struct oh323_user *user = NULL;
914         struct oh323_alias *alias = NULL;
915
916         /* allocate the call*/
917         p = oh323_alloc(cd.call_reference);
918
919         if (!p) {
920                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
921                 return 0;
922         }
923
924         /* Populate the call details in the private structure */
925         p->cd.call_token = cd.call_token;
926         p->cd.call_source_aliases = cd.call_source_aliases;
927         p->cd.call_dest_alias = cd.call_dest_alias;
928         p->cd.call_source_e164 = cd.call_source_e164;
929         p->cd.call_dest_e164 = cd.call_dest_e164;
930
931         if (h323debug) {
932                 printf("        == Setting up Call\n");
933                 printf("           -- Calling party name:  %s\n", p->cd.call_source_aliases);
934                 printf("           -- Calling party number:  %s\n", p->cd.call_source_e164);
935                 printf("           -- Called  party name:  %s\n", p->cd.call_dest_alias);
936                 printf("           -- Called  party number:  %s\n", p->cd.call_dest_e164);
937         }
938
939         /* Decide if we are allowing Gatekeeper routed calls*/
940         if ((!strcasecmp(cd.sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk == 1)) {
941                 
942                 if (strlen(cd.call_dest_e164)) {
943                         strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
944                         strncpy(p->context, default_context, sizeof(p->context)-1); 
945                 } else {
946                         alias = find_alias(cd.call_dest_alias);
947                 
948                         if (!alias) {
949                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd.call_dest_alias);
950                                 return 0;
951                         }
952                         printf("Alias found: %s and %s\n", alias->name, alias->context);
953
954                         strncpy(p->exten, alias->name, sizeof(p->exten)-1);
955                         strncpy(p->context, alias->context, sizeof(p->context)-1);
956                 }
957
958                 sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164);
959
960         } else { 
961                 /* Either this call is not from the Gatekeeper 
962                    or we are not allowing gk routed calls */
963                 
964                 user  = find_user(cd.call_source_aliases);
965                 
966                 if (!user) {
967                         sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164); 
968                         if (strlen(p->cd.call_dest_e164)) {
969                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
970                         } else {
971                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
972                         }
973                         if (!strlen(default_context)) {
974                                 ast_log(LOG_ERROR, "Call from user '%s' rejected due to no default context\n", p->cd.call_source_aliases);
975                                 return 0;
976                         }
977                         strncpy(p->context, default_context, sizeof(p->context)-1);
978                         ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd.call_source_aliases, p->context);
979                 } else {
980                         if (user->host) {
981                                 if (strcasecmp(cd.sourceIp, inet_ntoa(user->addr.sin_addr))){
982                                         
983                                         if(!strlen(default_context)) {
984                                                 ast_log(LOG_ERROR, "Call from user '%s' rejected due to non-matching IP address of '%s'\n", user->name, cd.sourceIp);
985                                 return 0;
986                                         }
987                                         strncpy(p->context, default_context, sizeof(p->context)-1);
988                                         sprintf(p->exten,"i");
989                                         goto exit;                                      
990                                 }
991                         }
992                         if (user->incominglimit > 0) {
993                                 if (user->inUse >= user->incominglimit) {
994                                         ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", user->name, user->incominglimit);
995                                         return 0;
996                                 }
997                         }
998                         strncpy(p->context, user->context, sizeof(p->context)-1);
999                         p->bridge = user->bridge;
1000
1001                         if (strlen(user->callerid) && strlen(p->callerid)) 
1002                                 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
1003                         else
1004                                 sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164); 
1005         
1006                         if (strlen(p->cd.call_dest_e164)) {
1007                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1008                         } else {
1009                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
1010                         }
1011
1012                         if (strlen(user->accountcode)) {
1013                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)-1);
1014                         } 
1015
1016                         /* Increment the usage counter */
1017                         user->inUse++;
1018                 } 
1019         }
1020
1021 /* I know this is horrid, don't kill me saddam */
1022 exit:
1023         /* allocate a channel and tell asterisk about it */
1024         c = oh323_new(p, AST_STATE_RINGING, cd.call_token);
1025
1026         if (!c) {
1027                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1028                 return 0;
1029         }
1030
1031         return 1;
1032 }
1033
1034 /**
1035  * Call-back function to establish an outgoing H.323 call
1036  * 
1037  * Returns 1 on success 
1038  */
1039 int setup_outgoing_call(call_details_t cd)
1040 {       
1041         return 1;
1042 }
1043
1044 #if 0
1045 if (p->inUse >= p->outgoinglimit) {
1046         ast_log(LOG_ERROR, "Call to %s rejected due to usage limit of %d outgoing channels\n", p->name, p->inUse);
1047         return 0;
1048 }
1049
1050 if (!p) {
1051         ast_log(LOG_ERROR, "Rejecting call: peer %s not found\n", dest_peer);
1052         return 0;
1053 }
1054 #endif
1055
1056 /**
1057   * Call-back function that gets called for each rtp channel opened 
1058   *
1059   * Returns nothing 
1060   */
1061 void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort)
1062 {
1063         struct oh323_pvt *p = NULL;
1064         struct sockaddr_in them;
1065
1066         /* Find the call or allocate a private structure if call not found */
1067         p = find_call(call_reference);
1068
1069         if (!p) {
1070                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1071                 return;
1072         }
1073
1074         them.sin_family = AF_INET;
1075         them.sin_addr.s_addr = inet_addr(remoteIp); // only works for IPv4
1076         them.sin_port = htons(remotePort);
1077         ast_rtp_set_peer(p->rtp, &them);
1078
1079         return;
1080 }
1081
1082 /**  
1083   *     Call-back function to signal asterisk that the channel has been answered 
1084   * Returns nothing
1085   */
1086 void connection_made(unsigned call_reference)
1087 {
1088         struct ast_channel *c = NULL;
1089         struct oh323_pvt *p = NULL;
1090         
1091         p = find_call(call_reference);
1092         
1093         if (!p)
1094                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1095
1096
1097         if (!p->owner) {
1098                 printf("Channel has no owner\n");
1099                 return;
1100         }
1101         c = p->owner;   
1102
1103         ast_setstate(c, AST_STATE_UP);
1104         return;
1105 }
1106
1107 /**
1108   * Call-back function to cleanup communication
1109   * Returns nothing,
1110   */
1111 void cleanup_connection(call_details_t cd)
1112 {       
1113         struct oh323_pvt *p = NULL;
1114 //      struct oh323_peer *peer = NULL;
1115         struct oh323_user *user = NULL;
1116         struct ast_rtp *rtp = NULL;
1117
1118         ast_log(LOG_DEBUG, "Cleaning up our mess\n");
1119         
1120         p = find_call(cd.call_reference);
1121
1122         if (!p) {
1123                 return;
1124         }
1125
1126         /* Decrement usage counter */
1127         if (!p->outgoing) {
1128                 user = find_user(cd.call_source_aliases);
1129                 
1130                 if(user)
1131                         user->inUse--;
1132         }
1133
1134 #if 0
1135                 if (p->outgoing) {
1136                 peer = find_peer(cd.call_dest_alias);
1137                 peer->inUse--;
1138         } else {
1139                 user = find_user(cd.call_source_aliases);
1140                 user->inUse--;
1141         }
1142 #endif
1143         
1144         if (p->rtp) {
1145                 rtp = p->rtp;
1146                 p->rtp = NULL;
1147                 /* Immediately stop RTP */
1148                 ast_rtp_destroy(rtp);
1149         }
1150         
1151         p->alreadygone = 1;
1152
1153         /* Send hangup */       
1154         if (p->owner)
1155                 ast_queue_hangup(p->owner, 1);
1156
1157         p = NULL;
1158         return; 
1159 }
1160
1161 static void *do_monitor(void *data)
1162 {
1163         int res;
1164         struct oh323_pvt *oh323 = NULL;
1165         
1166                 for(;;) {
1167                 /* Check for interfaces needing to be killed */
1168                 ast_pthread_mutex_lock(&iflock);
1169 restartsearch:          
1170                 oh323 = iflist;
1171                 while(oh323) {
1172                         if (oh323->needdestroy) {
1173                                 __oh323_destroy(oh323);
1174                                 goto restartsearch;
1175                         }
1176                         oh323 = oh323->next;
1177                 }
1178                 ast_pthread_mutex_unlock(&iflock);
1179
1180                 pthread_testcancel();
1181
1182                 /* Wait for sched or io */
1183                 res = ast_sched_wait(sched);
1184                 if ((res < 0) || (res > 1000))
1185                         res = 1000;
1186                 res = ast_io_wait(io, res);
1187                 ast_pthread_mutex_lock(&monlock);
1188                 if (res >= 0) 
1189                         ast_sched_runq(sched);
1190                 ast_pthread_mutex_unlock(&monlock);
1191         }
1192         /* Never reached */
1193         return NULL;
1194         
1195 }
1196
1197 static int restart_monitor(void)
1198 {
1199         /* If we're supposed to be stopped -- stay stopped */
1200         if (monitor_thread == -2)
1201                 return 0;
1202         if (ast_pthread_mutex_lock(&monlock)) {
1203                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1204                 return -1;
1205         }
1206         if (monitor_thread == pthread_self()) {
1207                 ast_pthread_mutex_unlock(&monlock);
1208                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1209                 return -1;
1210         }
1211         if (monitor_thread) {
1212                 /* Wake up the thread */
1213                 pthread_kill(monitor_thread, SIGURG);
1214         } else {
1215                 /* Start a new monitor */
1216                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1217                         ast_pthread_mutex_unlock(&monlock);
1218                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1219                         return -1;
1220                 }
1221         }
1222         ast_pthread_mutex_unlock(&monlock);
1223         return 0;
1224 }
1225
1226 static int h323_do_trace(int fd, int argc, char *argv[])
1227 {
1228         if (argc != 3)
1229                 return RESULT_SHOWUSAGE;
1230         
1231         h323_debug(1, atoi(argv[2]));
1232         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1233         return RESULT_SUCCESS;
1234 }
1235
1236 static int h323_no_trace(int fd, int argc, char *argv[])
1237 {
1238         if (argc != 3)
1239                 return RESULT_SHOWUSAGE;
1240
1241         h323_debug(0,0);
1242         ast_cli(fd, "H.323 trace disabled\n");
1243         return RESULT_SUCCESS;
1244 }
1245
1246 static int h323_do_debug(int fd, int argc, char *argv[])
1247 {
1248         if (argc != 2)
1249                 return RESULT_SHOWUSAGE;
1250         
1251         h323debug = 1;
1252         ast_cli(fd, "H323 debug enabled\n");
1253         return RESULT_SUCCESS;
1254 }
1255
1256 static int h323_no_debug(int fd, int argc, char *argv[])
1257 {
1258         if (argc != 3)
1259                 return RESULT_SHOWUSAGE;
1260
1261         h323debug = 0;
1262         ast_cli(fd, "H323 Debug disabled\n");
1263         return RESULT_SUCCESS;
1264 }
1265
1266 static int h323_gk_cycle(int fd, int argc, char *argv[])
1267 {
1268         if (argc != 3)
1269                 return RESULT_SHOWUSAGE;
1270                 
1271         h323_gk_urq();
1272         
1273         /* Possibly register with a GK */
1274         if (gatekeeper_disable == 0) {
1275                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1276                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1277                         h323_end_process();
1278                 }
1279         }
1280
1281         return RESULT_SUCCESS;
1282 }
1283
1284
1285 static char trace_usage[] = 
1286 "Usage: h.323 trace <level num>\n"
1287 "       Enables H.323 stack tracing for debugging purposes\n";
1288
1289 static char no_trace_usage[] = 
1290 "Usage: h.323 no trace\n"
1291 "       Disables H.323 stack tracing for debugging purposes\n";
1292
1293 static char debug_usage[] = 
1294 "Usage: h.323 debug\n"
1295 "       Enables chan_h323 debug output\n";
1296
1297 static char no_debug_usage[] = 
1298 "Usage: h.323 no debug\n"
1299 "       Disables chan_h323 debug output\n";
1300
1301 static char show_codec_usage[] = 
1302 "Usage: h.323 show codec\n"
1303 "       Shows all enabled codecs\n";
1304
1305 static char show_cycle_usage[] = 
1306 "Usage: h.323 gk cycle\n"
1307 "       Manually re-register with the Gatekeper\n";
1308
1309
1310 static struct ast_cli_entry  cli_trace =
1311         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1312 static struct ast_cli_entry  cli_no_trace =
1313         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1314 static struct ast_cli_entry  cli_debug =
1315         { { "h.323", "debug", NULL }, h323_do_debug, "Enable chan_h323 debug", debug_usage };
1316 static struct ast_cli_entry  cli_no_debug =
1317         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable chan_h323 debug", no_debug_usage };
1318 static struct ast_cli_entry  cli_show_codecs =
1319         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1320 static struct ast_cli_entry  cli_gk_cycle =
1321         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1322
1323
1324
1325 int reload_config()
1326 {
1327         
1328         int format;
1329         struct ast_config *cfg;
1330         struct ast_variable *v;
1331         struct oh323_peer *peer   = NULL;
1332         struct oh323_user *user   = NULL;
1333         struct oh323_alias *alias = NULL;
1334         struct hostent *hp;
1335         char *cat;
1336     char *utype;
1337         
1338         cfg = ast_load(config);
1339
1340         /* We *must* have a config file otherwise stop immediately */
1341         if (!cfg) {
1342                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
1343                 return 0;
1344         }
1345         
1346         h323debug=0;
1347         dtmfmode = H323_DTMF_RFC2833;
1348
1349         memset(&bindaddr, 0, sizeof(bindaddr));
1350
1351         v = ast_variable_browse(cfg, "general");
1352         while(v) {
1353                 /* Create the interface list */
1354                 if (!strcasecmp(v->name, "port")) {
1355                         port = (int)strtol(v->value, NULL, 10);
1356                 } else if (!strcasecmp(v->name, "bindaddr")) {
1357                         if (!(hp = gethostbyname(v->value))) {
1358                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1359                         } else {
1360                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1361                         }
1362                 } else if (!strcasecmp(v->name, "allow")) {
1363                         format = ast_getformatbyname(v->value);
1364                         if (format < 1) 
1365                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1366                         else
1367                                 capability |= format;
1368                 } else if (!strcasecmp(v->name, "disallow")) {
1369                         format = ast_getformatbyname(v->value);
1370                         if (format < 1) 
1371                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1372                         else
1373                                 capability &= ~format;
1374                 } else if (!strcasecmp(v->name, "tos")) {
1375                         if (sscanf(v->value, "%i", &format) == 1)
1376                                 tos = format & 0xff;
1377                         else if (!strcasecmp(v->value, "lowdelay"))
1378                                 tos = IPTOS_LOWDELAY;
1379                         else if (!strcasecmp(v->value, "throughput"))
1380                                 tos = IPTOS_THROUGHPUT;
1381                         else if (!strcasecmp(v->value, "reliability"))
1382                                 tos = IPTOS_RELIABILITY;
1383                         else if (!strcasecmp(v->value, "mincost"))
1384                                 tos = IPTOS_MINCOST;
1385                         else if (!strcasecmp(v->value, "none"))
1386                                 tos = 0;
1387                         else
1388                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
1389                 } else if (!strcasecmp(v->name, "gatekeeper")) {
1390                         if (!strcasecmp(v->value, "DISABLE")) {
1391                                 gatekeeper_disable = 1;
1392                                 usingGk = 0;
1393                         } else if (!strcasecmp(v->value, "DISCOVER")) {
1394                                 gatekeeper_disable = 0;
1395                                 gatekeeper_discover = 1;
1396                                 usingGk = 1;
1397                         } else {
1398                                 gatekeeper_disable = 0;
1399                                 usingGk = 1;
1400                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper)-1);
1401                         }
1402                 } else if (!strcasecmp(v->name, "secret")) {
1403                                 strncpy(secret, v->value, sizeof(secret)-1);
1404                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
1405                                 gkroute = ast_true(v->value);
1406                 } else if (!strcasecmp(v->name, "context")) {
1407                         strncpy(default_context, v->value, sizeof(default_context)-1);
1408                         printf("  == Setting default context to %s\n", default_context);        
1409                 } else if (!strcasecmp(v->name, "dtmfmode")) {
1410                         if (!strcasecmp(v->value, "inband"))
1411                                 dtmfmode=H323_DTMF_INBAND;
1412                         else if (!strcasecmp(v->value, "rfc2833"))
1413                                 dtmfmode = H323_DTMF_RFC2833;
1414                         else {
1415                                 ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1416                                 dtmfmode = H323_DTMF_RFC2833;
1417                         }
1418                 }
1419                 v = v->next;    
1420         }
1421         
1422         cat = ast_category_browse(cfg, NULL);
1423         while(cat) {
1424                 if (strcasecmp(cat, "general")) {
1425                         utype = ast_variable_retrieve(cfg, cat, "type");
1426                         if (utype) {
1427                                 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
1428                                         user = build_user(cat, ast_variable_browse(cfg, cat));
1429                                         if (user) {
1430                                                 ast_pthread_mutex_lock(&userl.lock);
1431                                                 user->next = userl.users;
1432                                                 userl.users = user;
1433                                                 ast_pthread_mutex_unlock(&userl.lock);
1434                                         }
1435                                 }  else if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
1436                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
1437                                         if (peer) {
1438                                                 ast_pthread_mutex_lock(&peerl.lock);
1439                                                 peer->next = peerl.peers;
1440                                                 peerl.peers = peer;
1441                                                 ast_pthread_mutex_unlock(&peerl.lock);
1442                                         }
1443                                 }  else if (!strcasecmp(utype, "h323")) {                       
1444                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
1445                                         if (alias) {
1446                                                 ast_pthread_mutex_lock(&aliasl.lock);
1447                                                 alias->next = aliasl.aliases;
1448                                                 aliasl.aliases = alias;
1449                                                 ast_pthread_mutex_unlock(&aliasl.lock);
1450                                         }
1451                                 } else {
1452                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
1453                                 }
1454                         } else
1455                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
1456                 }
1457                 cat = ast_category_browse(cfg, cat);
1458         }
1459
1460         /* Register our H.323 aliases if any*/
1461         while (alias) {         
1462                 if (h323_set_alias(alias)) {
1463                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
1464                         return -1;
1465                 }       
1466                 alias = alias->next;
1467         }
1468
1469         /* Add some capabilities */
1470         if(h323_set_capability(capability, dtmfmode)) {
1471                 ast_log(LOG_ERROR, "Capabilities failure, this is bad.\n");
1472                 return -1;
1473         }       
1474         ast_destroy(cfg);
1475
1476         return 0;
1477 }
1478
1479 void delete_users(void)
1480 {
1481         struct oh323_user *user, *userlast;
1482         struct oh323_peer *peer;
1483         
1484         /* Delete all users */
1485         ast_pthread_mutex_lock(&userl.lock);
1486         for (user=userl.users;user;) {
1487                 userlast = user;
1488                 user=user->next;
1489                 free(userlast);
1490         }
1491         userl.users=NULL;
1492         ast_pthread_mutex_unlock(&userl.lock);
1493         ast_pthread_mutex_lock(&peerl.lock);
1494         for (peer=peerl.peers;peer;) {
1495                 /* Assume all will be deleted, and we'll find out for sure later */
1496                 peer->delme = 1;
1497                 peer = peer->next;
1498         }
1499         ast_pthread_mutex_unlock(&peerl.lock);
1500 }
1501
1502 void delete_aliases(void)
1503 {
1504         struct oh323_alias *alias, *aliaslast;
1505                 
1506         /* Delete all users */
1507         ast_pthread_mutex_lock(&aliasl.lock);
1508         for (alias=aliasl.aliases;alias;) {
1509                 aliaslast = alias;
1510                 alias=alias->next;
1511                 free(aliaslast);
1512         }
1513         aliasl.aliases=NULL;
1514         ast_pthread_mutex_unlock(&aliasl.lock);
1515 }
1516
1517 void prune_peers(void)
1518 {
1519         /* Prune peers who still are supposed to be deleted */
1520         struct oh323_peer *peer, *peerlast, *peernext;
1521         ast_pthread_mutex_lock(&peerl.lock);
1522         peerlast = NULL;
1523         for (peer=peerl.peers;peer;) {
1524                 peernext = peer->next;
1525                 if (peer->delme) {
1526                         free(peer);
1527                         if (peerlast)
1528                                 peerlast->next = peernext;
1529                         else
1530                                 peerl.peers = peernext;
1531                 } else
1532                         peerlast = peer;
1533                 peer=peernext;
1534         }
1535         ast_pthread_mutex_unlock(&peerl.lock);
1536 }
1537
1538 int reload(void)
1539 {
1540         delete_users();
1541         delete_aliases();
1542         prune_peers();
1543
1544         if (strlen(gatekeeper)) {
1545                 h323_gk_urq();
1546         }
1547
1548         reload_config();
1549
1550         /* Possibly register with a GK */
1551         if (gatekeeper_disable == 0) {
1552                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1553                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1554                         h323_end_process();
1555                         return -1;
1556                 }
1557         }
1558         restart_monitor();
1559         return 0;
1560 }
1561
1562
1563 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
1564 {
1565         struct oh323_pvt *p;
1566         p = chan->pvt->pvt;
1567         if (p && p->rtp && p->bridge)
1568                 return p->rtp;
1569         return NULL;
1570 }
1571
1572 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp)
1573 {
1574         struct oh323_pvt *p;
1575         struct sockaddr_in them;
1576         struct sockaddr_in us;
1577
1578         if (!rtp) 
1579                 return 0;
1580
1581         p = chan->pvt->pvt;
1582         if (!p) {
1583                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
1584                 return -1;
1585         }
1586
1587         ast_rtp_get_peer(rtp, &them);   
1588         printf("peer is now: %s\n", inet_ntoa(them.sin_addr));
1589                 
1590         ast_rtp_set_peer(p->rtp, &them);
1591         ast_rtp_get_us(p->rtp, &us);
1592
1593         h323_native_bridge(p->cd.call_token, inet_ntoa(them.sin_addr), inet_ntoa(us.sin_addr));
1594         
1595         return 0;
1596         
1597 }
1598
1599 static struct ast_rtp_protocol oh323_rtp = {
1600         get_rtp_info: oh323_get_rtp_peer,
1601         set_rtp_peer: oh323_set_rtp_peer,
1602 };
1603
1604 int load_module()
1605 {
1606         int res;
1607
1608         /* fire up the H.323 Endpoint */ 
1609         h323_end_point_create();
1610
1611         res = reload_config();
1612         if (!res) {
1613         /* Make sure we can register our channel type */
1614                 if (ast_channel_register(type, tdesc, capability, oh323_request)) {
1615                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1616                         h323_end_process();
1617                         return -1;
1618                 }
1619                 ast_cli_register(&cli_debug);
1620                 ast_cli_register(&cli_no_debug);
1621                 ast_cli_register(&cli_trace);
1622                 ast_cli_register(&cli_no_trace);
1623                 ast_cli_register(&cli_show_codecs);
1624                 ast_cli_register(&cli_gk_cycle);
1625
1626                 oh323_rtp.type = type;
1627                 ast_rtp_proto_register(&oh323_rtp);
1628
1629                 sched = sched_context_create();
1630                 if (!sched) {
1631                         ast_log(LOG_WARNING, "Unable to create schedule context\n");
1632                 }
1633                 io = io_context_create();
1634                 if (!io) {
1635                         ast_log(LOG_WARNING, "Unable to create I/O context\n");
1636                 }
1637                 
1638                 /* Register our callback functions */
1639                 h323_callback_register(setup_incoming_call, 
1640                                                            setup_outgoing_call, 
1641                                                            create_connection, 
1642                                                            setup_rtp_connection, 
1643                                                            cleanup_connection, 
1644                                                            connection_made, send_digit);        
1645         
1646                 /* start the h.323 listener */
1647                 if (h323_start_listener(port, bindaddr)) {
1648                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
1649 //                      h323_end_process();
1650                         return -1;
1651                 }
1652
1653                 /* Possibly register with a GK */
1654                 if (gatekeeper_disable == 0) {
1655                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1656                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1657 //                              h323_end_process();
1658                                 return -1;
1659                         }
1660                 }
1661                 /* And start the monitor for the first time */
1662                 restart_monitor();
1663         } else {
1664                 h323_end_process();
1665         }
1666         return res;
1667 }
1668 int unload_module() 
1669 {
1670         struct oh323_pvt *p, *pl;
1671                 
1672         if (!ast_pthread_mutex_lock(&iflock)) {
1673         /* hangup all interfaces if they have an owner */
1674         p = iflist;
1675         while(p) {
1676                 if (p->owner)
1677                         ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1678                 p = p->next;
1679         }
1680         iflist = NULL;
1681         ast_pthread_mutex_unlock(&iflock);
1682         } else {
1683                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1684                 return -1;
1685         }
1686                 
1687         if (!ast_pthread_mutex_lock(&iflock)) {
1688                 /* destroy all the interfaces and free their memory */
1689                 p = iflist;
1690                 while(p) {
1691                         pl = p;
1692                         p = p->next;
1693                         /* free associated memory */
1694                         free(pl);
1695                 }
1696                 iflist = NULL;
1697                 ast_pthread_mutex_unlock(&iflock);
1698         } else {
1699                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1700                 return -1;
1701         }
1702         h323_gk_urq();
1703         h323_end_process();
1704
1705         /* unregister rtp */
1706         ast_rtp_proto_unregister(&oh323_rtp);
1707         
1708         /* unregister commands */
1709         ast_cli_unregister(&cli_debug);
1710         ast_cli_unregister(&cli_no_debug);
1711         ast_cli_unregister(&cli_trace);
1712         ast_cli_unregister(&cli_no_trace);
1713         ast_cli_unregister(&cli_show_codecs);
1714         ast_cli_unregister(&cli_gk_cycle);
1715
1716         /* unregister channel type */
1717         ast_channel_unregister(type);
1718
1719         return 0;
1720
1721 }
1722
1723 int usecount()
1724 {
1725         int res;
1726         ast_pthread_mutex_lock(&usecnt_lock);
1727         res = usecnt;
1728         ast_pthread_mutex_unlock(&usecnt_lock);
1729         return res;
1730 }
1731
1732 char *description()
1733 {
1734         return desc;
1735 }
1736
1737 char *key()
1738 {
1739         return ASTERISK_GPL_KEY;
1740 }
1741
1742
1743
1744