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