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