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