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