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