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