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