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