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