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