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