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