don't deal with gatekeeper on reload, known issue..someone fix
[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 -1;
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 -1;
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 -1;
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         printf("  us: %s:%d\n", inet_ntoa(us.sin_addr), ntohs(us.sin_port));
932         printf("them: %s:%d\n", inet_ntoa(them.sin_addr), ntohs(them.sin_port));
933
934         info->addr = inet_ntoa(us.sin_addr);
935         info->port = ntohs(us.sin_port);
936         
937         printf("info: %s:%d\n", info->addr, info->port);        
938         return info;
939 }
940
941 /**
942  *  Call-back function for incoming calls
943  *
944  *  Returns 1 on success
945  */
946
947 int setup_incoming_call(call_details_t cd)
948 {
949         
950         struct oh323_pvt *p = NULL;
951         struct ast_channel *c = NULL;
952         struct oh323_user *user = NULL;
953         struct oh323_alias *alias = NULL;
954
955         /* allocate the call*/
956         p = oh323_alloc(cd.call_reference);
957
958         if (!p) {
959                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
960                 return 0;
961         }
962
963         /* Populate the call details in the private structure */
964         p->cd.call_token = cd.call_token;
965         p->cd.call_source_aliases = cd.call_source_aliases;
966         p->cd.call_dest_alias = cd.call_dest_alias;
967         p->cd.call_source_e164 = cd.call_source_e164;
968         p->cd.call_dest_e164 = cd.call_dest_e164;
969
970         if (h323debug) {
971                 printf("        == Setting up Call\n");
972                 printf("           -- Calling party name:  [%s]\n", p->cd.call_source_aliases);
973                 printf("           -- Calling party number:  [%s]\n", p->cd.call_source_e164);
974                 printf("           -- Called  party name:  [%s]\n", p->cd.call_dest_alias);
975                 printf("           -- Called  party number:  [%s]\n", p->cd.call_dest_e164);
976         }
977
978         /* Decide if we are allowing Gatekeeper routed calls*/
979         if ((!strcasecmp(cd.sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk == 1)) {
980                 
981                 if (strlen(cd.call_dest_e164)) {
982                         strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
983                         strncpy(p->context, default_context, sizeof(p->context)-1); 
984                 } else {
985                         alias = find_alias(cd.call_dest_alias);
986                 
987                         if (!alias) {
988                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd.call_dest_alias);
989                                 return 0;
990                         }
991                         printf("Alias found: %s and %s\n", alias->name, alias->context);
992
993                         strncpy(p->exten, alias->name, sizeof(p->exten)-1);
994                         strncpy(p->context, alias->context, sizeof(p->context)-1);
995                 }
996
997
998                 sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164);
999
1000         } else { 
1001                 /* Either this call is not from the Gatekeeper 
1002                    or we are not allowing gk routed calls */
1003                 
1004
1005                 user  = find_user(cd.call_source_aliases);
1006
1007
1008                 if (!user) {
1009                         sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164); 
1010                         if (strlen(p->cd.call_dest_e164)) {
1011                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1012                         } else {
1013                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
1014                         }
1015                         if (!strlen(default_context)) {
1016                                 ast_log(LOG_ERROR, "Call from user '%s' rejected due to no default context\n", p->cd.call_source_aliases);
1017                                 return 0;
1018                         }
1019                         strncpy(p->context, default_context, sizeof(p->context)-1);
1020                         ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd.call_source_aliases, p->context);
1021                 } else {                                        
1022                         if (user->host) {
1023                                 if (strcasecmp(cd.sourceIp, inet_ntoa(user->addr.sin_addr))){
1024                                         
1025                                         if(!strlen(default_context)) {
1026                                                 ast_log(LOG_ERROR, "Call from user '%s' rejected due to non-matching IP address of '%s'\n", user->name, cd.sourceIp);
1027                                                 return 0;
1028                                         }
1029                                         
1030                                         strncpy(p->context, default_context, sizeof(p->context)-1);
1031                                         sprintf(p->exten,"i");
1032
1033                                         goto exit;                                      
1034                                 }
1035                         }
1036                         if (user->incominglimit > 0) {
1037                                 if (user->inUse >= user->incominglimit) {
1038                                         ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", user->name, user->incominglimit);
1039                                         return 0;
1040                                 }
1041                         }
1042                         strncpy(p->context, user->context, sizeof(p->context)-1);
1043                         p->bridge = user->bridge;
1044                       p->nat = user->nat;
1045
1046                         if (strlen(user->callerid)) 
1047                                 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
1048                         else
1049                                 sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164); 
1050
1051                         if (strlen(p->cd.call_dest_e164)) {
1052                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1053                                 printf("e164: [%s]\n", p->exten);
1054                         } else {
1055                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
1056                                 printf("dest alias: %s\n", p->exten);
1057                         }
1058                         if (strlen(user->accountcode)) {
1059                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)-1);
1060                         } 
1061
1062                         /* Increment the usage counter */
1063                         user->inUse++;
1064                 } 
1065         }
1066
1067 /* I know this is horrid, don't kill me saddam */
1068 exit:
1069         /* allocate a channel and tell asterisk about it */
1070         c = oh323_new(p, AST_STATE_RINGING, cd.call_token);
1071         if (!c) {
1072                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1073                 return 0;
1074         }
1075
1076         return 1;
1077 }
1078
1079 /**
1080  * Call-back function to establish an outgoing H.323 call
1081  * 
1082  * Returns 1 on success 
1083  */
1084 int setup_outgoing_call(call_details_t cd)
1085 {       
1086         return 1;
1087 }
1088
1089 #if 0
1090 if (p->inUse >= p->outgoinglimit) {
1091         ast_log(LOG_ERROR, "Call to %s rejected due to usage limit of %d outgoing channels\n", p->name, p->inUse);
1092         return 0;
1093 }
1094
1095 if (!p) {
1096         ast_log(LOG_ERROR, "Rejecting call: peer %s not found\n", dest_peer);
1097         return 0;
1098 }
1099 #endif
1100
1101 /**
1102   * Call-back function that gets called for each rtp channel opened 
1103   *
1104   * Returns nothing 
1105   */
1106 void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort)
1107 {
1108         struct oh323_pvt *p = NULL;
1109         struct sockaddr_in them;
1110
1111         /* Find the call or allocate a private structure if call not found */
1112         p = find_call(call_reference);
1113
1114         if (!p) {
1115                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1116                 return;
1117         }
1118
1119         them.sin_family = AF_INET;
1120         them.sin_addr.s_addr = inet_addr(remoteIp); // only works for IPv4
1121         them.sin_port = htons(remotePort);
1122         ast_rtp_set_peer(p->rtp, &them);
1123
1124         return;
1125 }
1126
1127 /**  
1128   *     Call-back function to signal asterisk that the channel has been answered 
1129   * Returns nothing
1130   */
1131 void connection_made(unsigned call_reference)
1132 {
1133         struct ast_channel *c = NULL;
1134         struct oh323_pvt *p = NULL;
1135         
1136         p = find_call(call_reference);
1137         
1138         if (!p)
1139                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1140
1141
1142         if (!p->owner) {
1143                 printf("Channel has no owner\n");
1144                 return;
1145         }
1146         c = p->owner;   
1147
1148         ast_setstate(c, AST_STATE_UP);
1149         return;
1150 }
1151
1152 /**
1153   * Call-back function to cleanup communication
1154   * Returns nothing,
1155   */
1156 void cleanup_connection(call_details_t cd)
1157 {       
1158         struct oh323_pvt *p = NULL;
1159 //      struct oh323_peer *peer = NULL;
1160         struct oh323_user *user = NULL;
1161         struct ast_rtp *rtp = NULL;
1162
1163         ast_log(LOG_DEBUG, "Cleaning up our mess\n");
1164         
1165         p = find_call(cd.call_reference);
1166
1167         if (!p) {
1168                 return;
1169         }
1170
1171         /* Decrement usage counter */
1172         if (!p->outgoing) {
1173                 user = find_user(cd.call_source_aliases);
1174                 
1175                 if(user)
1176                         user->inUse--;
1177         }
1178
1179 #if 0
1180                 if (p->outgoing) {
1181                 peer = find_peer(cd.call_dest_alias);
1182                 peer->inUse--;
1183         } else {
1184                 user = find_user(cd.call_source_aliases);
1185                 user->inUse--;
1186         }
1187 #endif
1188         
1189         if (p->rtp) {
1190                 rtp = p->rtp;
1191                 p->rtp = NULL;
1192                 /* Immediately stop RTP */
1193                 ast_rtp_destroy(rtp);
1194         }
1195         
1196         p->alreadygone = 1;
1197
1198         /* Send hangup */       
1199         if (p->owner)
1200                 ast_queue_hangup(p->owner, 1);
1201
1202         p = NULL;
1203         return; 
1204 }
1205
1206 static void *do_monitor(void *data)
1207 {
1208         int res;
1209         struct oh323_pvt *oh323 = NULL;
1210         
1211                 for(;;) {
1212                 /* Check for interfaces needing to be killed */
1213                 ast_mutex_lock(&iflock);
1214 restartsearch:          
1215                 oh323 = iflist;
1216                 while(oh323) {
1217                         if (oh323->needdestroy) {
1218                                 __oh323_destroy(oh323);
1219                                 goto restartsearch;
1220                         }
1221                         oh323 = oh323->next;
1222                 }
1223                 ast_mutex_unlock(&iflock);
1224
1225                 pthread_testcancel();
1226
1227                 /* Wait for sched or io */
1228                 res = ast_sched_wait(sched);
1229                 if ((res < 0) || (res > 1000))
1230                         res = 1000;
1231                 res = ast_io_wait(io, res);
1232                 ast_mutex_lock(&monlock);
1233                 if (res >= 0) 
1234                         ast_sched_runq(sched);
1235                 ast_mutex_unlock(&monlock);
1236         }
1237         /* Never reached */
1238         return NULL;
1239         
1240 }
1241
1242 static int restart_monitor(void)
1243 {
1244         /* If we're supposed to be stopped -- stay stopped */
1245         if (monitor_thread == -2)
1246                 return 0;
1247         if (ast_mutex_lock(&monlock)) {
1248                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1249                 return -1;
1250         }
1251         if (monitor_thread == pthread_self()) {
1252                 ast_mutex_unlock(&monlock);
1253                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1254                 return -1;
1255         }
1256         if (monitor_thread) {
1257                 /* Wake up the thread */
1258                 pthread_kill(monitor_thread, SIGURG);
1259         } else {
1260                 /* Start a new monitor */
1261                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1262                         ast_mutex_unlock(&monlock);
1263                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1264                         return -1;
1265                 }
1266         }
1267         ast_mutex_unlock(&monlock);
1268         return 0;
1269 }
1270
1271 static int h323_do_trace(int fd, int argc, char *argv[])
1272 {
1273         if (argc != 3)
1274                 return RESULT_SHOWUSAGE;
1275         
1276         h323_debug(1, atoi(argv[2]));
1277         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1278         return RESULT_SUCCESS;
1279 }
1280
1281 static int h323_no_trace(int fd, int argc, char *argv[])
1282 {
1283         if (argc != 3)
1284                 return RESULT_SHOWUSAGE;
1285
1286         h323_debug(0,0);
1287         ast_cli(fd, "H.323 trace disabled\n");
1288         return RESULT_SUCCESS;
1289 }
1290
1291 static int h323_do_debug(int fd, int argc, char *argv[])
1292 {
1293         if (argc != 2)
1294                 return RESULT_SHOWUSAGE;
1295         
1296         h323debug = 1;
1297         ast_cli(fd, "H323 debug enabled\n");
1298         return RESULT_SUCCESS;
1299 }
1300
1301 static int h323_no_debug(int fd, int argc, char *argv[])
1302 {
1303         if (argc != 3)
1304                 return RESULT_SHOWUSAGE;
1305
1306         h323debug = 0;
1307         ast_cli(fd, "H323 Debug disabled\n");
1308         return RESULT_SUCCESS;
1309 }
1310
1311 static int h323_gk_cycle(int fd, int argc, char *argv[])
1312 {
1313         if (argc != 3)
1314                 return RESULT_SHOWUSAGE;
1315                 
1316         h323_gk_urq();
1317         
1318         /* Possibly register with a GK */
1319         if (gatekeeper_disable == 0) {
1320                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1321                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1322                         h323_end_process();
1323                 }
1324         }
1325
1326         return RESULT_SUCCESS;
1327 }
1328
1329
1330 static char trace_usage[] = 
1331 "Usage: h.323 trace <level num>\n"
1332 "       Enables H.323 stack tracing for debugging purposes\n";
1333
1334 static char no_trace_usage[] = 
1335 "Usage: h.323 no trace\n"
1336 "       Disables H.323 stack tracing for debugging purposes\n";
1337
1338 static char debug_usage[] = 
1339 "Usage: h.323 debug\n"
1340 "       Enables chan_h323 debug output\n";
1341
1342 static char no_debug_usage[] = 
1343 "Usage: h.323 no debug\n"
1344 "       Disables chan_h323 debug output\n";
1345
1346 static char show_codec_usage[] = 
1347 "Usage: h.323 show codec\n"
1348 "       Shows all enabled codecs\n";
1349
1350 static char show_cycle_usage[] = 
1351 "Usage: h.323 gk cycle\n"
1352 "       Manually re-register with the Gatekeper\n";
1353
1354
1355 static struct ast_cli_entry  cli_trace =
1356         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1357 static struct ast_cli_entry  cli_no_trace =
1358         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1359 static struct ast_cli_entry  cli_debug =
1360         { { "h.323", "debug", NULL }, h323_do_debug, "Enable chan_h323 debug", debug_usage };
1361 static struct ast_cli_entry  cli_no_debug =
1362         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable chan_h323 debug", no_debug_usage };
1363 static struct ast_cli_entry  cli_show_codecs =
1364         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1365 static struct ast_cli_entry  cli_gk_cycle =
1366         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1367
1368
1369
1370 int reload_config()
1371 {
1372         
1373         int format;
1374         struct ast_config *cfg;
1375         struct ast_variable *v;
1376         struct oh323_peer *peer   = NULL;
1377         struct oh323_user *user   = NULL;
1378         struct oh323_alias *alias = NULL;
1379         struct hostent *hp;
1380         char *cat;
1381     char *utype;
1382         
1383         cfg = ast_load(config);
1384
1385         /* We *must* have a config file otherwise stop immediately */
1386         if (!cfg) {
1387                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
1388                 return 0;
1389         }
1390         
1391         h323debug=0;
1392         dtmfmode = H323_DTMF_RFC2833;
1393
1394         memset(&bindaddr, 0, sizeof(bindaddr));
1395
1396         v = ast_variable_browse(cfg, "general");
1397         while(v) {
1398                 /* Create the interface list */
1399                 if (!strcasecmp(v->name, "port")) {
1400                         port = (int)strtol(v->value, NULL, 10);
1401                 } else if (!strcasecmp(v->name, "bindaddr")) {
1402                         if (!(hp = gethostbyname(v->value))) {
1403                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1404                         } else {
1405                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1406                         }
1407                 } else if (!strcasecmp(v->name, "allow")) {
1408                         format = ast_getformatbyname(v->value);
1409                         if (format < 1) 
1410                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1411                         else
1412                                 capability |= format;
1413                 } else if (!strcasecmp(v->name, "disallow")) {
1414                         format = ast_getformatbyname(v->value);
1415                         if (format < 1) 
1416                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1417                         else
1418                                 capability &= ~format;
1419                 } else if (!strcasecmp(v->name, "tos")) {
1420                         if (sscanf(v->value, "%i", &format) == 1)
1421                                 tos = format & 0xff;
1422                         else if (!strcasecmp(v->value, "lowdelay"))
1423                                 tos = IPTOS_LOWDELAY;
1424                         else if (!strcasecmp(v->value, "throughput"))
1425                                 tos = IPTOS_THROUGHPUT;
1426                         else if (!strcasecmp(v->value, "reliability"))
1427                                 tos = IPTOS_RELIABILITY;
1428                         else if (!strcasecmp(v->value, "mincost"))
1429                                 tos = IPTOS_MINCOST;
1430                         else if (!strcasecmp(v->value, "none"))
1431                                 tos = 0;
1432                         else
1433                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
1434                 } else if (!strcasecmp(v->name, "gatekeeper")) {
1435                         if (!strcasecmp(v->value, "DISABLE")) {
1436                                 gatekeeper_disable = 1;
1437                                 usingGk = 0;
1438                         } else if (!strcasecmp(v->value, "DISCOVER")) {
1439                                 gatekeeper_disable = 0;
1440                                 gatekeeper_discover = 1;
1441                                 usingGk = 1;
1442                         } else {
1443                                 gatekeeper_disable = 0;
1444                                 usingGk = 1;
1445                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper)-1);
1446                         }
1447                 } else if (!strcasecmp(v->name, "secret")) {
1448                                 strncpy(secret, v->value, sizeof(secret)-1);
1449                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
1450                                 gkroute = ast_true(v->value);
1451                 } else if (!strcasecmp(v->name, "context")) {
1452                         strncpy(default_context, v->value, sizeof(default_context)-1);
1453                         printf("  == Setting default context to %s\n", default_context);        
1454                 } else if (!strcasecmp(v->name, "dtmfmode")) {
1455                         if (!strcasecmp(v->value, "inband"))
1456                                 dtmfmode=H323_DTMF_INBAND;
1457                         else if (!strcasecmp(v->value, "rfc2833"))
1458                                 dtmfmode = H323_DTMF_RFC2833;
1459                         else {
1460                                 ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1461                                 dtmfmode = H323_DTMF_RFC2833;
1462                         }
1463                 }
1464                 v = v->next;    
1465         }
1466         
1467         cat = ast_category_browse(cfg, NULL);
1468         while(cat) {
1469                 if (strcasecmp(cat, "general")) {
1470                         utype = ast_variable_retrieve(cfg, cat, "type");
1471                         if (utype) {
1472                                 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
1473                                         user = build_user(cat, ast_variable_browse(cfg, cat));
1474                                         if (user) {
1475                                                 ast_mutex_lock(&userl.lock);
1476                                                 user->next = userl.users;
1477                                                 userl.users = user;
1478                                                 ast_mutex_unlock(&userl.lock);
1479                                         }
1480                                 }  else if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
1481                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
1482                                         if (peer) {
1483                                                 ast_mutex_lock(&peerl.lock);
1484                                                 peer->next = peerl.peers;
1485                                                 peerl.peers = peer;
1486                                                 ast_mutex_unlock(&peerl.lock);
1487                                         }
1488                                 }  else if (!strcasecmp(utype, "h323")) {                       
1489                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
1490                                         if (alias) {
1491                                                 ast_mutex_lock(&aliasl.lock);
1492                                                 alias->next = aliasl.aliases;
1493                                                 aliasl.aliases = alias;
1494                                                 ast_mutex_unlock(&aliasl.lock);
1495                                         }
1496                                 } else {
1497                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
1498                                 }
1499                         } else
1500                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
1501                 }
1502                 cat = ast_category_browse(cfg, cat);
1503         }
1504
1505         /* Register our H.323 aliases if any*/
1506         while (alias) {         
1507                 if (h323_set_alias(alias)) {
1508                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
1509                         return -1;
1510                 }       
1511                 alias = alias->next;
1512         }
1513
1514         /* Add some capabilities */
1515         if(h323_set_capability(capability, dtmfmode)) {
1516                 ast_log(LOG_ERROR, "Capabilities failure, this is bad.\n");
1517                 return -1;
1518         }       
1519         ast_destroy(cfg);
1520
1521         return 0;
1522 }
1523
1524 void delete_users(void)
1525 {
1526         struct oh323_user *user, *userlast;
1527         struct oh323_peer *peer;
1528         
1529         /* Delete all users */
1530         ast_mutex_lock(&userl.lock);
1531         for (user=userl.users;user;) {
1532                 userlast = user;
1533                 user=user->next;
1534                 free(userlast);
1535         }
1536         userl.users=NULL;
1537         ast_mutex_unlock(&userl.lock);
1538         ast_mutex_lock(&peerl.lock);
1539         for (peer=peerl.peers;peer;) {
1540                 /* Assume all will be deleted, and we'll find out for sure later */
1541                 peer->delme = 1;
1542                 peer = peer->next;
1543         }
1544         ast_mutex_unlock(&peerl.lock);
1545 }
1546
1547 void delete_aliases(void)
1548 {
1549         struct oh323_alias *alias, *aliaslast;
1550                 
1551         /* Delete all users */
1552         ast_mutex_lock(&aliasl.lock);
1553         for (alias=aliasl.aliases;alias;) {
1554                 aliaslast = alias;
1555                 alias=alias->next;
1556                 free(aliaslast);
1557         }
1558         aliasl.aliases=NULL;
1559         ast_mutex_unlock(&aliasl.lock);
1560 }
1561
1562 void prune_peers(void)
1563 {
1564         /* Prune peers who still are supposed to be deleted */
1565         struct oh323_peer *peer, *peerlast, *peernext;
1566         ast_mutex_lock(&peerl.lock);
1567         peerlast = NULL;
1568         for (peer=peerl.peers;peer;) {
1569                 peernext = peer->next;
1570                 if (peer->delme) {
1571                         free(peer);
1572                         if (peerlast)
1573                                 peerlast->next = peernext;
1574                         else
1575                                 peerl.peers = peernext;
1576                 } else
1577                         peerlast = peer;
1578                 peer=peernext;
1579         }
1580         ast_mutex_unlock(&peerl.lock);
1581 }
1582
1583 int reload(void)
1584 {
1585         delete_users();
1586         delete_aliases();
1587         prune_peers();
1588
1589         if (strlen(gatekeeper)) {
1590                 h323_gk_urq();
1591         }
1592
1593         reload_config();
1594
1595 #if 0
1596         /* Possibly register with a GK */
1597         if (gatekeeper_disable == 0) {
1598                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1599                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1600                         h323_end_process();
1601                         return -1;
1602                 }
1603         }
1604 #endif
1605         restart_monitor();
1606         return 0;
1607 }
1608
1609
1610 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
1611 {
1612         struct oh323_pvt *p;
1613         p = chan->pvt->pvt;
1614         if (p && p->rtp && p->bridge) {
1615                 return p->rtp;
1616         }
1617         return NULL;
1618 }
1619
1620 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
1621 {
1622         return NULL;
1623 }
1624
1625 static char *convertcap(int cap)
1626 {
1627         switch (cap) {
1628         case AST_FORMAT_G723_1:
1629                 return "G.723";
1630         case AST_FORMAT_GSM:
1631                 return "GSM";
1632         case AST_FORMAT_ULAW:
1633                 return "ULAW";
1634         case AST_FORMAT_ALAW:
1635                 return "ALAW";
1636         case AST_FORMAT_ADPCM:
1637                 return "G.728";
1638         case AST_FORMAT_G729A:
1639                 return "G.729";
1640         case AST_FORMAT_SPEEX:
1641                 return "SPEEX";
1642         case AST_FORMAT_ILBC:
1643                 return "ILBC";
1644         default:
1645                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
1646                 return NULL;
1647         }
1648
1649 }
1650
1651 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp)
1652 {
1653         /* XXX Deal with Video */
1654         struct oh323_pvt *p;
1655         struct sockaddr_in them;
1656         struct sockaddr_in us;
1657         char *mode;
1658
1659         mode = convertcap(chan->writeformat); 
1660
1661         if (!rtp) {
1662                 return 0;
1663         }
1664
1665         p = chan->pvt->pvt;
1666         if (!p) {
1667                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
1668                 return -1;
1669         }
1670
1671         ast_rtp_get_peer(rtp, &them);   
1672         ast_rtp_get_us(rtp, &us);
1673
1674         printf("peer is now: %s:%d\n", inet_ntoa(them.sin_addr), htons(them.sin_port));
1675         printf("Us is: %s\n", inet_ntoa(us.sin_addr));
1676                 
1677
1678         h323_native_bridge(p->cd.call_token, inet_ntoa(them.sin_addr), mode);
1679         
1680         return 0;
1681         
1682 }
1683
1684 static struct ast_rtp_protocol oh323_rtp = {
1685         get_rtp_info: oh323_get_rtp_peer,
1686         get_vrtp_info: oh323_get_vrtp_peer,
1687         set_rtp_peer: oh323_set_rtp_peer,
1688 };
1689
1690
1691 int load_module()
1692 {
1693         int res;
1694
1695         /* fire up the H.323 Endpoint */ 
1696         h323_end_point_create();
1697
1698         res = reload_config();
1699         if (!res) {
1700         /* Make sure we can register our channel type */
1701                 if (ast_channel_register(type, tdesc, capability, oh323_request)) {
1702                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1703                         h323_end_process();
1704                         return -1;
1705                 }
1706                 ast_cli_register(&cli_debug);
1707                 ast_cli_register(&cli_no_debug);
1708                 ast_cli_register(&cli_trace);
1709                 ast_cli_register(&cli_no_trace);
1710                 ast_cli_register(&cli_show_codecs);
1711                 ast_cli_register(&cli_gk_cycle);
1712
1713                 oh323_rtp.type = type;
1714                 ast_rtp_proto_register(&oh323_rtp);
1715
1716                 sched = sched_context_create();
1717                 if (!sched) {
1718                         ast_log(LOG_WARNING, "Unable to create schedule context\n");
1719                 }
1720                 io = io_context_create();
1721                 if (!io) {
1722                         ast_log(LOG_WARNING, "Unable to create I/O context\n");
1723                 }
1724                 
1725                 /* Register our callback functions */
1726                 h323_callback_register(setup_incoming_call, 
1727                                                            setup_outgoing_call,                                                  
1728                                                            create_connection, 
1729                                                            setup_rtp_connection, 
1730                                                            cleanup_connection, 
1731                                                            connection_made, send_digit);        
1732         
1733
1734                 /* start the h.323 listener */
1735                 if (h323_start_listener(port, bindaddr)) {
1736                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
1737 //                      h323_end_process();
1738                         return -1;
1739                 }
1740
1741                 /* Possibly register with a GK */
1742                 if (gatekeeper_disable == 0) {
1743                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1744                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1745 //                              h323_end_process();
1746                                 return -1;
1747                         }
1748                 }
1749                 /* And start the monitor for the first time */
1750                 restart_monitor();
1751         } else {
1752                 h323_end_process();
1753         }
1754         return res;
1755 }
1756 int unload_module() 
1757 {
1758         struct oh323_pvt *p, *pl;
1759                 
1760         if (!ast_mutex_lock(&iflock)) {
1761         /* hangup all interfaces if they have an owner */
1762         p = iflist;
1763         while(p) {
1764                 if (p->owner)
1765                         ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1766                 p = p->next;
1767         }
1768         iflist = NULL;
1769         ast_mutex_unlock(&iflock);
1770         } else {
1771                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1772                 return -1;
1773         }
1774                 
1775         if (!ast_mutex_lock(&iflock)) {
1776                 /* destroy all the interfaces and free their memory */
1777                 p = iflist;
1778                 while(p) {
1779                         pl = p;
1780                         p = p->next;
1781                         /* free associated memory */
1782                         free(pl);
1783                 }
1784                 iflist = NULL;
1785                 ast_mutex_unlock(&iflock);
1786         } else {
1787                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1788                 return -1;
1789         }
1790         h323_gk_urq();
1791         h323_end_process();
1792
1793         /* unregister rtp */
1794         ast_rtp_proto_unregister(&oh323_rtp);
1795         
1796         /* unregister commands */
1797         ast_cli_unregister(&cli_debug);
1798         ast_cli_unregister(&cli_no_debug);
1799         ast_cli_unregister(&cli_trace);
1800         ast_cli_unregister(&cli_no_trace);
1801         ast_cli_unregister(&cli_show_codecs);
1802         ast_cli_unregister(&cli_gk_cycle);
1803
1804         /* unregister channel type */
1805         ast_channel_unregister(type);
1806
1807         return 0;
1808
1809 }
1810
1811 int usecount()
1812 {
1813         int res;
1814         ast_mutex_lock(&usecnt_lock);
1815         res = usecnt;
1816         ast_mutex_unlock(&usecnt_lock);
1817         return res;
1818 }
1819
1820 char *description()
1821 {
1822         return desc;
1823 }
1824
1825 char *key()
1826 {
1827         return ASTERISK_GPL_KEY;
1828 }
1829
1830
1831
1832