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