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