Add support for parking with IAX2
[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 struct sockaddr_in bindaddr;
72 static char gatekeeper[100];
73 static int  gatekeeper_disable = 1;
74 static int  gatekeeper_discover = 0;
75 static int  usingGk;
76 static int  port = 1720;
77 static int  gkroute = 0;
78
79 /* to find user by alias is default, alternative is the incomming call's source IP 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, int needlock)
627 {
628         struct oh323_pvt *p = newchan->pvt->pvt;
629
630         if (needlock)
631                 ast_mutex_lock(&p->lock);
632         if (p->owner != oldchan) {
633                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
634                 return -1;
635         }
636         p->owner = newchan;
637         if (needlock)
638                 ast_mutex_unlock(&p->lock);
639         return 0;
640 }
641
642 static struct ast_channel *oh323_new(struct oh323_pvt *i, int state, const char *host)
643 {
644         struct ast_channel *ch;
645         int fmt;
646         ch = ast_channel_alloc(1);
647         
648         if (ch) {
649                 
650                 snprintf(ch->name, sizeof(ch->name)-1, "H323/%s", host);
651                 ch->nativeformats = i->capability;
652                 if (!ch->nativeformats)
653                         ch->nativeformats = capability;
654                 fmt = ast_best_codec(ch->nativeformats);
655                 ch->type = type;
656                 ch->fds[0] = ast_rtp_fd(i->rtp);
657                 ast_setstate(ch, state);
658                 
659                 if (state == AST_STATE_RING)
660                         ch->rings = 1;
661                 
662                 ch->writeformat = fmt;
663                 ch->pvt->rawwriteformat = fmt;
664                 ch->readformat = fmt;
665                 ch->pvt->rawreadformat = fmt;
666                 
667                 /* Allocate dsp for in-band DTMF support */
668                 if (i->dtmfmode & H323_DTMF_INBAND) {
669                         i->vad = ast_dsp_new();
670                         ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
671                 }
672
673                 /* Register the OpenH323 channel's functions. */
674                 ch->pvt->pvt = i;
675                 ch->pvt->send_digit = oh323_digit;
676                 ch->pvt->call = oh323_call;
677                 ch->pvt->hangup = oh323_hangup;
678                 ch->pvt->answer = oh323_answer;
679                 ch->pvt->read = oh323_read;
680                 ch->pvt->write = oh323_write;
681                 ch->pvt->indicate = oh323_indicate;
682                 ch->pvt->fixup = oh323_fixup;
683 //              ch->pvt->bridge = ast_rtp_bridge;
684
685                 /*  Set the owner of this channel */
686                 i->owner = ch;
687                 
688                 ast_mutex_lock(&usecnt_lock);
689                 usecnt++;
690                 ast_mutex_unlock(&usecnt_lock);
691                 ast_update_use_count();
692                 strncpy(ch->context, i->context, sizeof(ch->context)-1);
693                 strncpy(ch->exten, i->exten, sizeof(ch->exten)-1);              
694                 ch->priority = 1;
695                 if (strlen(i->callerid))
696                         ch->callerid = strdup(i->callerid);
697                 if (strlen(i->accountcode))
698                         strncpy(ch->accountcode, i->accountcode, sizeof(ch->accountcode)-1);
699                 if (i->amaflags)
700                         ch->amaflags = i->amaflags;
701                 if (state != AST_STATE_DOWN) {
702                         if (ast_pbx_start(ch)) {
703                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ch->name);
704                                 ast_hangup(ch);
705                                 ch = NULL;
706                         }
707                 }
708         } else
709                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
710         return ch;
711 }
712
713 static struct oh323_pvt *oh323_alloc(int callid)
714 {
715         struct oh323_pvt *p;
716
717         p = malloc(sizeof(struct oh323_pvt));
718         if (!p) {
719                 ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
720                 return NULL;
721         }
722
723         /* Keep track of stuff */
724         memset(p, 0, sizeof(struct oh323_pvt));
725         p->rtp = ast_rtp_new(sched, io, 1, 0);
726
727         if (!p->rtp) {
728                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
729                 free(p);
730                 return NULL;
731         }
732         ast_rtp_settos(p->rtp, tos);
733         ast_mutex_init(&p->lock);
734         
735         p->cd.call_reference = callid;
736         p->bridge = bridge_default;
737         
738         p->dtmfmode = dtmfmode;
739         if (p->dtmfmode & H323_DTMF_RFC2833)
740                 p->nonCodecCapability |= AST_RTP_DTMF;
741
742         /* Add to interface list */
743         ast_mutex_lock(&iflock);
744         p->next = iflist;
745         iflist = p;
746         ast_mutex_unlock(&iflock);
747         return p;
748 }
749
750 static struct oh323_pvt *find_call(int call_reference)
751 {  
752         struct oh323_pvt *p;
753
754                 ast_mutex_lock(&iflock);
755         p = iflist; 
756
757         while(p) {
758                 if (p->cd.call_reference == call_reference) {
759                         /* Found the call */                                            
760                                                 ast_mutex_unlock(&iflock);
761                                                 return p;
762                 }
763                 p = p->next; 
764         }
765         ast_mutex_unlock(&iflock);
766                 return NULL;
767         
768 }
769
770 static struct ast_channel *oh323_request(char *type, int format, void *data)
771 {
772
773         int oldformat;
774         struct oh323_pvt *p;
775         struct ast_channel *tmpc = NULL;
776         char *dest = data;
777         char *ext, *host;
778         char *h323id = NULL;
779         char tmp[256];
780
781         
782         ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
783
784         oldformat = format;
785         format &= capability;
786         if (!format) {
787                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
788                 return NULL;
789         }
790         
791         strncpy(tmp, dest, sizeof(tmp) - 1);
792                 
793         host = strchr(tmp, '@');
794         if (host) {
795                 *host = '\0';
796                 host++;
797                 ext = tmp;
798         } else {
799                 host = tmp;
800                 ext = NULL;
801         }
802
803         strtok_r(host, "/", &(h323id));
804                 
805         if (*h323id) {
806                 h323_set_id(h323id);
807         }
808                 
809         
810         p = oh323_alloc(0);
811
812         if (!p) {
813                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
814                 return NULL;
815         }
816
817         /* Assign a default capability */
818         p->capability = capability;
819
820         if (p->dtmfmode) {
821                 if (p->dtmfmode & H323_DTMF_RFC2833)
822                         p->nonCodecCapability |= AST_RTP_DTMF;
823                 else
824                         p->nonCodecCapability &= ~AST_RTP_DTMF;
825         }
826
827         if (ext) {
828                 strncpy(p->username, ext, sizeof(p->username) - 1);
829         }
830         ast_log(LOG_DEBUG, "Host: %s\tUsername: %s\n", host, p->username);
831
832         tmpc = oh323_new(p, AST_STATE_DOWN, host);
833         if (!tmpc)
834                 oh323_destroy(p);
835         
836         restart_monitor();
837         
838         return tmpc;
839 }
840
841 struct oh323_alias *find_alias(const char *source_aliases)
842 {
843         struct oh323_alias *a;
844
845         a = aliasl.aliases;
846
847         while(a) {
848
849                 if (!strcasecmp(a->name, source_aliases)) {
850                         break;
851                 }
852                 a = a->next;
853         }
854         return a;
855 }
856
857 struct oh323_user *find_user(const call_details_t cd)
858 {
859         struct oh323_user *u;
860
861         u = userl.users;
862         if(userbyalias == 1){
863                 while(u) {
864                         if (!strcasecmp(u->name, cd.call_source_aliases)) {
865                                 break;
866                         }
867                         u = u->next;
868                 }
869
870         } else {
871                 while(u) {
872                         if (!strcasecmp(cd.sourceIp, inet_ntoa(u->addr.sin_addr))) {
873                                 break;
874                         }
875                         u = u->next;
876                 }
877
878         
879         }
880         return u;
881
882 }
883
884 struct oh323_peer *find_peer(char *dest_peer)
885 {
886         struct oh323_peer *p;
887
888         p = peerl.peers;
889
890         while(p) {
891                 if (!strcasecmp(p->name, dest_peer)) {
892                         break;
893                 }
894                 p = p->next;
895         }
896         return p;
897
898 }
899
900 /**
901   * Callback for sending digits from H.323 up to asterisk
902   *
903   */
904 int send_digit(unsigned call_reference, char digit)
905 {
906         struct oh323_pvt *p;
907         struct ast_frame f;
908
909         ast_log(LOG_DEBUG, "Recieved Digit: %c\n", digit);
910         p = find_call(call_reference);
911         
912         if (!p) {
913                 ast_log(LOG_ERROR, "Private structure not found in send_digit.\n");
914                 return -1;
915         }
916         memset(&f, 0, sizeof(f));
917         f.frametype = AST_FRAME_DTMF;
918     f.subclass = digit;
919     f.datalen = 0;
920     f.samples = 300;
921         f.offset = 0;
922         f.data = NULL;
923     f.mallocd = 0;
924     f.src = "SEND_DIGIT";
925         
926         return ast_queue_frame(p->owner, &f, 1);        
927 }
928
929 /**
930   * Call-back function that gets called when any H.323 connection is made
931   *
932   * Returns the local RTP information
933   */
934 struct rtp_info *create_connection(unsigned call_reference)
935 {       
936         struct oh323_pvt *p;
937         struct sockaddr_in us;
938         struct sockaddr_in them;
939         struct rtp_info *info;
940
941         info = malloc(sizeof(struct rtp_info));
942
943         p = find_call(call_reference);
944
945         if (!p) {
946                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is very bad.\n");
947                 return NULL;
948         }
949
950         /* figure out our local RTP port and tell the H.323 stack about it*/
951         ast_rtp_get_us(p->rtp, &us);
952         ast_rtp_get_peer(p->rtp, &them);
953
954
955         info->addr = inet_ntoa(us.sin_addr);
956         info->port = ntohs(us.sin_port);
957
958
959         return info;
960 }
961
962 /**
963  *  Call-back function for incoming calls
964  *
965  *  Returns 1 on success
966  */
967
968 int setup_incoming_call(call_details_t cd)
969 {
970         
971         struct oh323_pvt *p = NULL;
972         struct ast_channel *c = NULL;
973         struct oh323_user *user = NULL;
974         struct oh323_alias *alias = NULL;
975
976         /* allocate the call*/
977         p = oh323_alloc(cd.call_reference);
978
979         if (!p) {
980                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
981                 return 0;
982         }
983
984         /* Populate the call details in the private structure */
985         p->cd.call_token = cd.call_token;
986         p->cd.call_source_aliases = cd.call_source_aliases;
987         p->cd.call_dest_alias = cd.call_dest_alias;
988         p->cd.call_source_e164 = cd.call_source_e164;
989         p->cd.call_dest_e164 = cd.call_dest_e164;
990
991         if (h323debug) {
992                 ast_verbose(VERBOSE_PREFIX_3 "Setting up Call\n");
993                 ast_verbose(VERBOSE_PREFIX_3 "     Call token:  [%s]\n", p->cd.call_token);
994                 ast_verbose(VERBOSE_PREFIX_3 "     Calling party name:  [%s]\n", p->cd.call_source_aliases);
995                 ast_verbose(VERBOSE_PREFIX_3 "     Calling party number:  [%s]\n", p->cd.call_source_e164);
996                 ast_verbose(VERBOSE_PREFIX_3 "     Called  party name:  [%s]\n", p->cd.call_dest_alias);
997                 ast_verbose(VERBOSE_PREFIX_3 "     Called  party number:  [%s]\n", p->cd.call_dest_e164);
998         }
999
1000         /* Decide if we are allowing Gatekeeper routed calls*/
1001         if ((!strcasecmp(cd.sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk == 1)) {
1002                 
1003                 if (strlen(cd.call_dest_e164)) {
1004                         strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1005                         strncpy(p->context, default_context, sizeof(p->context)-1); 
1006                 } else {
1007                         alias = find_alias(cd.call_dest_alias);
1008                 
1009                         if (!alias) {
1010                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd.call_dest_alias);
1011                                 return 0;
1012                         }
1013                         strncpy(p->exten, alias->name, sizeof(p->exten)-1);
1014                         strncpy(p->context, alias->context, sizeof(p->context)-1);
1015                 }
1016
1017
1018                 sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164);
1019
1020         } else { 
1021                 /* Either this call is not from the Gatekeeper 
1022                    or we are not allowing gk routed calls */
1023                 
1024
1025                 user  = find_user(cd);
1026
1027
1028                 if (!user) {
1029                         sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164); 
1030                         if (strlen(p->cd.call_dest_e164)) {
1031                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1032                         } else {
1033                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
1034                         }
1035                         if (!strlen(default_context)) {
1036                                 ast_log(LOG_ERROR, "Call from user '%s' rejected due to no default context\n", p->cd.call_source_aliases);
1037                                 return 0;
1038                         }
1039                         strncpy(p->context, default_context, sizeof(p->context)-1);
1040                         ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd.call_source_aliases, p->context);
1041                 } else {                                        
1042                         if (user->host) {
1043                                 if (strcasecmp(cd.sourceIp, inet_ntoa(user->addr.sin_addr))){
1044                                         
1045                                         if(!strlen(default_context)) {
1046                                                 ast_log(LOG_ERROR, "Call from user '%s' rejected due to non-matching IP address of '%s'\n", user->name, cd.sourceIp);
1047                                                 return 0;
1048                                         }
1049                                         
1050                                         strncpy(p->context, default_context, sizeof(p->context)-1);
1051                                         sprintf(p->exten,"i");
1052
1053                                         goto exit;                                      
1054                                 }
1055                         }
1056                         if (user->incominglimit > 0) {
1057                                 if (user->inUse >= user->incominglimit) {
1058                                         ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", user->name, user->incominglimit);
1059                                         return 0;
1060                                 }
1061                         }
1062                         strncpy(p->context, user->context, sizeof(p->context)-1);
1063                         p->bridge = user->bridge;
1064                       p->nat = user->nat;
1065
1066                         if (strlen(user->callerid)) 
1067                                 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
1068                         else
1069                                 sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164); 
1070
1071                         if (strlen(p->cd.call_dest_e164)) {
1072                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1073                         } else {
1074                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
1075                         }
1076                         if (strlen(user->accountcode)) {
1077                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)-1);
1078                         } 
1079
1080                         /* Increment the usage counter */
1081                         user->inUse++;
1082                 } 
1083         }
1084
1085 /* I know this is horrid, don't kill me saddam */
1086 exit:
1087         /* allocate a channel and tell asterisk about it */
1088         c = oh323_new(p, AST_STATE_RINGING, cd.call_token);
1089         if (!c) {
1090                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1091                 return 0;
1092         }
1093
1094         return 1;
1095 }
1096
1097 /**
1098  * Call-back function to establish an outgoing H.323 call
1099  * 
1100  * Returns 1 on success 
1101  */
1102 int setup_outgoing_call(call_details_t cd)
1103 {       
1104         return 1;
1105 }
1106
1107 #if 0
1108 if (p->inUse >= p->outgoinglimit) {
1109         ast_log(LOG_ERROR, "Call to %s rejected due to usage limit of %d outgoing channels\n", p->name, p->inUse);
1110         return 0;
1111 }
1112
1113 if (!p) {
1114         ast_log(LOG_ERROR, "Rejecting call: peer %s not found\n", dest_peer);
1115         return 0;
1116 }
1117 #endif
1118
1119 /**
1120   * Call-back function that gets called for each rtp channel opened 
1121   *
1122   * Returns nothing 
1123   */
1124 void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort)
1125 {
1126         struct oh323_pvt *p = NULL;
1127         struct sockaddr_in them;
1128
1129         /* Find the call or allocate a private structure if call not found */
1130         p = find_call(call_reference);
1131
1132         if (!p) {
1133                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1134                 return;
1135         }
1136
1137         them.sin_family = AF_INET;
1138         them.sin_addr.s_addr = inet_addr(remoteIp); // only works for IPv4
1139         them.sin_port = htons(remotePort);
1140         ast_rtp_set_peer(p->rtp, &them);
1141
1142         return;
1143 }
1144
1145 /**  
1146   *     Call-back function to signal asterisk that the channel has been answered 
1147   * Returns nothing
1148   */
1149 void connection_made(unsigned call_reference)
1150 {
1151         struct ast_channel *c = NULL;
1152         struct oh323_pvt *p = NULL;
1153         
1154         p = find_call(call_reference);
1155         
1156         if (!p)
1157                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1158
1159
1160         if (!p->owner) {
1161                 ast_log(LOG_ERROR, "Channel has no owner\n");
1162                 return;
1163         }
1164         c = p->owner;   
1165
1166         ast_setstate(c, AST_STATE_UP);
1167         return;
1168 }
1169
1170 /**
1171   * Call-back function to cleanup communication
1172   * Returns nothing,
1173   */
1174 void cleanup_connection(call_details_t cd)
1175 {       
1176         struct oh323_pvt *p = NULL;
1177 //      struct oh323_peer *peer = NULL;
1178         struct oh323_user *user = NULL;
1179         struct ast_rtp *rtp = NULL;
1180
1181         ast_log(LOG_DEBUG, "Cleaning up our mess\n");
1182         
1183         p = find_call(cd.call_reference);
1184
1185         if (!p) {
1186                 return;
1187         }
1188
1189         /* Decrement usage counter */
1190         if (!p->outgoing) {
1191                 user = find_user(cd);
1192                 
1193                 if(user)
1194                         user->inUse--;
1195         }
1196
1197 #if 0
1198                 if (p->outgoing) {
1199                 peer = find_peer(cd.call_dest_alias);
1200                 peer->inUse--;
1201         } else {
1202                 user = find_user(cd);
1203                 user->inUse--;
1204         }
1205 #endif
1206         
1207         if (p->rtp) {
1208                 rtp = p->rtp;
1209                 p->rtp = NULL;
1210                 /* Immediately stop RTP */
1211                 ast_rtp_destroy(rtp);
1212         }
1213         
1214         p->alreadygone = 1;
1215
1216         /* Send hangup */       
1217         if (p->owner)
1218                 ast_queue_hangup(p->owner, 1);
1219
1220         p = NULL;
1221         return; 
1222 }
1223
1224 static void *do_monitor(void *data)
1225 {
1226         int res;
1227         struct oh323_pvt *oh323 = NULL;
1228         
1229                 for(;;) {
1230                 /* Check for interfaces needing to be killed */
1231                 ast_mutex_lock(&iflock);
1232 restartsearch:          
1233                 oh323 = iflist;
1234                 while(oh323) {
1235                         if (oh323->needdestroy) {
1236                                 __oh323_destroy(oh323);
1237                                 goto restartsearch;
1238                         }
1239                         oh323 = oh323->next;
1240                 }
1241                 ast_mutex_unlock(&iflock);
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
1249                 pthread_testcancel();
1250
1251                 ast_mutex_lock(&monlock);
1252                 if (res >= 0) 
1253                         ast_sched_runq(sched);
1254                 ast_mutex_unlock(&monlock);
1255         }
1256         /* Never reached */
1257         return NULL;
1258         
1259 }
1260
1261 static int restart_monitor(void)
1262 {
1263         /* If we're supposed to be stopped -- stay stopped */
1264         if (monitor_thread == -2)
1265                 return 0;
1266         if (ast_mutex_lock(&monlock)) {
1267                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1268                 return -1;
1269         }
1270         if (monitor_thread == pthread_self()) {
1271                 ast_mutex_unlock(&monlock);
1272                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1273                 return -1;
1274         }
1275         if (monitor_thread && (monitor_thread != -2)) {
1276                 /* Wake up the thread */
1277                 pthread_kill(monitor_thread, SIGURG);
1278         } else {
1279                 /* Start a new monitor */
1280                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1281                         ast_mutex_unlock(&monlock);
1282                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1283                         return -1;
1284                 }
1285         }
1286         ast_mutex_unlock(&monlock);
1287         return 0;
1288 }
1289
1290 static int h323_do_trace(int fd, int argc, char *argv[])
1291 {
1292         if (argc != 3) {
1293                 return RESULT_SHOWUSAGE;
1294         }
1295         h323_debug(1, atoi(argv[2]));
1296         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1297         return RESULT_SUCCESS;
1298 }
1299
1300 static int h323_no_trace(int fd, int argc, char *argv[])
1301 {
1302         if (argc != 3) {
1303                 return RESULT_SHOWUSAGE;
1304         }
1305         h323_debug(0,0);
1306         ast_cli(fd, "H.323 trace disabled\n");
1307         return RESULT_SUCCESS;
1308 }
1309
1310 static int h323_do_debug(int fd, int argc, char *argv[])
1311 {
1312         if (argc != 2) {
1313                 return RESULT_SHOWUSAGE;
1314         }
1315         h323debug = 1;
1316         ast_cli(fd, "H323 debug enabled\n");
1317         return RESULT_SUCCESS;
1318 }
1319
1320 static int h323_no_debug(int fd, int argc, char *argv[])
1321 {
1322         if (argc != 3) {
1323                 return RESULT_SHOWUSAGE;
1324         }
1325         h323debug = 0;
1326         ast_cli(fd, "H323 Debug disabled\n");
1327         return RESULT_SUCCESS;
1328 }
1329
1330 static int h323_gk_cycle(int fd, int argc, char *argv[])
1331 {
1332         return RESULT_SUCCESS;
1333 #if 0
1334         if (argc != 3) {
1335                 return RESULT_SHOWUSAGE;
1336         }       
1337         h323_gk_urq();
1338         
1339         /* Possibly register with a GK */
1340         if (!gatekeeper_disable) {
1341                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1342                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1343                 }
1344         }
1345         return RESULT_SUCCESS;
1346 #endif
1347 }
1348
1349 static int h323_ep_hangup(int fd, int argc, char *argv[])
1350 {
1351
1352         if (argc != 3) {
1353                 return RESULT_SHOWUSAGE;
1354         }
1355
1356         if (h323_soft_hangup(argv[2])) {
1357                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
1358         } else { 
1359                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
1360         }
1361
1362         return RESULT_SUCCESS;
1363 }
1364
1365 static int h323_tokens_show(int fd, int argc, char *argv[])
1366 {
1367
1368         if (argc != 3) {
1369                 return RESULT_SHOWUSAGE;
1370         }
1371         h323_show_tokens();
1372
1373         return RESULT_SUCCESS;
1374 }
1375
1376
1377 static char trace_usage[] = 
1378 "Usage: h.323 trace <level num>\n"
1379 "       Enables H.323 stack tracing for debugging purposes\n";
1380
1381 static char no_trace_usage[] = 
1382 "Usage: h.323 no trace\n"
1383 "       Disables H.323 stack tracing for debugging purposes\n";
1384
1385 static char debug_usage[] = 
1386 "Usage: h.323 debug\n"
1387 "       Enables chan_h323 debug output\n";
1388
1389 static char no_debug_usage[] = 
1390 "Usage: h.323 no debug\n"
1391 "       Disables chan_h323 debug output\n";
1392
1393 static char show_codec_usage[] = 
1394 "Usage: h.323 show codec\n"
1395 "       Shows all enabled codecs\n";
1396
1397 static char show_cycle_usage[] = 
1398 "Usage: h.323 gk cycle\n"
1399 "       Manually re-register with the Gatekeper\n";
1400
1401 static char show_hangup_usage[] = 
1402 "Usage: h.323 hangup <token>\n"
1403 "       Manually try to hang up call identified by <token>\n";
1404
1405 static char show_tokens_usage[] = 
1406 "Usage: h.323 show tokens\n"
1407 "       Print out all active call tokens\n";
1408
1409 static struct ast_cli_entry  cli_trace =
1410         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1411 static struct ast_cli_entry  cli_no_trace =
1412         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1413 static struct ast_cli_entry  cli_debug =
1414         { { "h.323", "debug", NULL }, h323_do_debug, "Enable chan_h323 debug", debug_usage };
1415 static struct ast_cli_entry  cli_no_debug =
1416         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable chan_h323 debug", no_debug_usage };
1417 static struct ast_cli_entry  cli_show_codecs =
1418         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1419 static struct ast_cli_entry  cli_gk_cycle =
1420         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1421 static struct ast_cli_entry  cli_hangup_call =
1422         { { "h.323", "hangup", NULL }, h323_ep_hangup, "Manually try to hang up a call", show_hangup_usage };
1423 static struct ast_cli_entry  cli_show_tokens =
1424         { { "h.323", "show", "tokens", NULL }, h323_tokens_show, "Manually try to hang up a call", show_tokens_usage };
1425
1426
1427
1428 int reload_config(void)
1429 {
1430         
1431         int format;
1432         struct ast_config *cfg;
1433         struct ast_variable *v;
1434         struct oh323_peer *peer   = NULL;
1435         struct oh323_user *user   = NULL;
1436         struct oh323_alias *alias = NULL;
1437         struct hostent *hp;
1438         char *cat;
1439     char *utype;
1440         
1441         cfg = ast_load(config);
1442
1443         /* We *must* have a config file otherwise stop immediately */
1444         if (!cfg) {
1445                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
1446                 return 1;
1447         }
1448         
1449        /* fire up the H.323 Endpoint */       
1450         if (!h323_end_point_exist()) {
1451                h323_end_point_create();        
1452         }
1453         h323debug=0;
1454         dtmfmode = H323_DTMF_RFC2833;
1455
1456         memset(&bindaddr, 0, sizeof(bindaddr));
1457
1458         v = ast_variable_browse(cfg, "general");
1459         while(v) {
1460                 /* Create the interface list */
1461                 if (!strcasecmp(v->name, "port")) {
1462                         port = (int)strtol(v->value, NULL, 10);
1463                 } else if (!strcasecmp(v->name, "bindaddr")) {
1464                         if (!(hp = gethostbyname(v->value))) {
1465                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1466                         } else {
1467                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1468                         }
1469                 } else if (!strcasecmp(v->name, "allow")) {
1470                         format = ast_getformatbyname(v->value);
1471                         if (format < 1) 
1472                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1473                         else
1474                                 capability |= format;
1475                 } else if (!strcasecmp(v->name, "disallow")) {
1476                         format = ast_getformatbyname(v->value);
1477                         if (format < 1) 
1478                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1479                         else
1480                                 capability &= ~format;
1481                 } else if (!strcasecmp(v->name, "tos")) {
1482                         if (sscanf(v->value, "%i", &format) == 1)
1483                                 tos = format & 0xff;
1484                         else if (!strcasecmp(v->value, "lowdelay"))
1485                                 tos = IPTOS_LOWDELAY;
1486                         else if (!strcasecmp(v->value, "throughput"))
1487                                 tos = IPTOS_THROUGHPUT;
1488                         else if (!strcasecmp(v->value, "reliability"))
1489                                 tos = IPTOS_RELIABILITY;
1490                         else if (!strcasecmp(v->value, "mincost"))
1491                                 tos = IPTOS_MINCOST;
1492                         else if (!strcasecmp(v->value, "none"))
1493                                 tos = 0;
1494                         else
1495                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
1496                 } else if (!strcasecmp(v->name, "gatekeeper")) {
1497                         if (!strcasecmp(v->value, "DISABLE")) {
1498                                 gatekeeper_disable = 1;
1499                                 usingGk = 0;
1500                         } else if (!strcasecmp(v->value, "DISCOVER")) {
1501                                 gatekeeper_disable = 0;
1502                                 gatekeeper_discover = 1;
1503                                 usingGk = 1;
1504                         } else {
1505                                 gatekeeper_disable = 0;
1506                                 usingGk = 1;
1507                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper)-1);
1508                         }
1509                 } else if (!strcasecmp(v->name, "secret")) {
1510                                 strncpy(secret, v->value, sizeof(secret)-1);
1511                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
1512                                 gkroute = ast_true(v->value);
1513                 } else if (!strcasecmp(v->name, "context")) {
1514                         strncpy(default_context, v->value, sizeof(default_context)-1);
1515                         ast_verbose(VERBOSE_PREFIX_3 "  == Setting default context to %s\n", default_context);  
1516                 } else if (!strcasecmp(v->name, "dtmfmode")) {
1517                         if (!strcasecmp(v->value, "inband"))
1518                                 dtmfmode=H323_DTMF_INBAND;
1519                         else if (!strcasecmp(v->value, "rfc2833"))
1520                                 dtmfmode = H323_DTMF_RFC2833;
1521                         else {
1522                                 ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1523                                 dtmfmode = H323_DTMF_RFC2833;
1524                         }
1525                 } else if (!strcasecmp(v->name, "UserByAlias")) {
1526                         userbyalias = ast_true(v->value);
1527                 } else if (!strcasecmp(v->name, "bridge")) {
1528                         bridge_default = ast_true(v->value);
1529                 }
1530                 v = v->next;    
1531         }
1532         
1533         cat = ast_category_browse(cfg, NULL);
1534         while(cat) {
1535                 if (strcasecmp(cat, "general")) {
1536                         utype = ast_variable_retrieve(cfg, cat, "type");
1537                         if (utype) {
1538                                 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
1539                                         user = build_user(cat, ast_variable_browse(cfg, cat));
1540                                         if (user) {
1541                                                 ast_mutex_lock(&userl.lock);
1542                                                 user->next = userl.users;
1543                                                 userl.users = user;
1544                                                 ast_mutex_unlock(&userl.lock);
1545                                         }
1546                                 }  else if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
1547                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
1548                                         if (peer) {
1549                                                 ast_mutex_lock(&peerl.lock);
1550                                                 peer->next = peerl.peers;
1551                                                 peerl.peers = peer;
1552                                                 ast_mutex_unlock(&peerl.lock);
1553                                         }
1554                                 }  else if (!strcasecmp(utype, "h323")) {                       
1555                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
1556                                         if (alias) {
1557                                                 ast_mutex_lock(&aliasl.lock);
1558                                                 alias->next = aliasl.aliases;
1559                                                 aliasl.aliases = alias;
1560                                                 ast_mutex_unlock(&aliasl.lock);
1561                                         }
1562                                 } else {
1563                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
1564                                 }
1565                         } else
1566                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
1567                 }
1568                 cat = ast_category_browse(cfg, cat);
1569         }
1570
1571         /* Register our H.323 aliases if any*/
1572         while (alias) {         
1573                 if (h323_set_alias(alias)) {
1574                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
1575                         return -1;
1576                 }       
1577                 alias = alias->next;
1578         }
1579
1580         /* Add some capabilities */
1581         if(h323_set_capability(capability, dtmfmode)) {
1582                 ast_log(LOG_ERROR, "Capabilities failure, this is bad.\n");
1583                 return -1;
1584         }       
1585         ast_destroy(cfg);
1586
1587         return 0;
1588 }
1589
1590 void delete_users(void)
1591 {
1592         struct oh323_user *user, *userlast;
1593         struct oh323_peer *peer;
1594         
1595         /* Delete all users */
1596         ast_mutex_lock(&userl.lock);
1597         for (user=userl.users;user;) {
1598                 userlast = user;
1599                 user=user->next;
1600                 free(userlast);
1601         }
1602         userl.users=NULL;
1603         ast_mutex_unlock(&userl.lock);
1604         ast_mutex_lock(&peerl.lock);
1605         for (peer=peerl.peers;peer;) {
1606                 /* Assume all will be deleted, and we'll find out for sure later */
1607                 peer->delme = 1;
1608                 peer = peer->next;
1609         }
1610         ast_mutex_unlock(&peerl.lock);
1611 }
1612
1613 void delete_aliases(void)
1614 {
1615         struct oh323_alias *alias, *aliaslast;
1616                 
1617         /* Delete all users */
1618         ast_mutex_lock(&aliasl.lock);
1619         for (alias=aliasl.aliases;alias;) {
1620                 aliaslast = alias;
1621                 alias=alias->next;
1622                 free(aliaslast);
1623         }
1624         aliasl.aliases=NULL;
1625         ast_mutex_unlock(&aliasl.lock);
1626 }
1627
1628 void prune_peers(void)
1629 {
1630         /* Prune peers who still are supposed to be deleted */
1631         struct oh323_peer *peer, *peerlast, *peernext;
1632         ast_mutex_lock(&peerl.lock);
1633         peerlast = NULL;
1634         for (peer=peerl.peers;peer;) {
1635                 peernext = peer->next;
1636                 if (peer->delme) {
1637                         free(peer);
1638                         if (peerlast)
1639                                 peerlast->next = peernext;
1640                         else
1641                                 peerl.peers = peernext;
1642                 } else
1643                         peerlast = peer;
1644                 peer=peernext;
1645         }
1646         ast_mutex_unlock(&peerl.lock);
1647 }
1648
1649 int reload(void)
1650 {
1651         delete_users();
1652         delete_aliases();
1653         prune_peers();
1654
1655 #if 0
1656         if (strlen(gatekeeper)) {
1657                 h323_gk_urq();
1658         }
1659 #endif
1660
1661         reload_config();
1662
1663 #if 0
1664         /* Possibly register with a GK */
1665         if (gatekeeper_disable == 0) {
1666                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1667                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1668                         h323_end_process();
1669                         return -1;
1670                 }
1671         }
1672 #endif
1673         restart_monitor();
1674         return 0;
1675 }
1676
1677
1678 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
1679 {
1680         struct oh323_pvt *p;
1681         p = chan->pvt->pvt;
1682         if (p && p->rtp && p->bridge) {
1683                 return p->rtp;
1684         }
1685         return NULL;
1686 }
1687
1688 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
1689 {
1690         return NULL;
1691 }
1692
1693 static char *convertcap(int cap)
1694 {
1695         switch (cap) {
1696         case AST_FORMAT_G723_1:
1697                 return "G.723";
1698         case AST_FORMAT_GSM:
1699                 return "GSM";
1700         case AST_FORMAT_ULAW:
1701                 return "ULAW";
1702         case AST_FORMAT_ALAW:
1703                 return "ALAW";
1704         case AST_FORMAT_ADPCM:
1705                 return "G.728";
1706         case AST_FORMAT_G729A:
1707                 return "G.729";
1708         case AST_FORMAT_SPEEX:
1709                 return "SPEEX";
1710         case AST_FORMAT_ILBC:
1711                 return "ILBC";
1712         default:
1713                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
1714                 return NULL;
1715         }
1716
1717 }
1718
1719 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp)
1720 {
1721         /* XXX Deal with Video */
1722         struct oh323_pvt *p;
1723         struct sockaddr_in them;
1724         struct sockaddr_in us;
1725         char *mode;
1726
1727         mode = convertcap(chan->writeformat); 
1728
1729         if (!rtp) {
1730                 return 0;
1731         }
1732
1733         p = chan->pvt->pvt;
1734         if (!p) {
1735                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
1736                 return -1;
1737         }
1738
1739         ast_rtp_get_peer(rtp, &them);   
1740         ast_rtp_get_us(rtp, &us);
1741
1742
1743         h323_native_bridge(p->cd.call_token, inet_ntoa(them.sin_addr), mode);
1744         
1745         return 0;
1746         
1747 }
1748
1749 static struct ast_rtp_protocol oh323_rtp = {
1750         get_rtp_info: oh323_get_rtp_peer,
1751         get_vrtp_info: oh323_get_vrtp_peer,
1752         set_rtp_peer: oh323_set_rtp_peer,
1753 };
1754
1755
1756 int load_module()
1757 {
1758         int res;
1759
1760         res = reload_config();
1761
1762         if (res) {
1763                 return 0;
1764         } else {
1765                 /* Make sure we can register our channel type */
1766                 if (ast_channel_register(type, tdesc, capability, oh323_request)) {
1767                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1768                         h323_end_process();
1769                         return -1;
1770                 }
1771                 ast_cli_register(&cli_debug);
1772                 ast_cli_register(&cli_no_debug);
1773                 ast_cli_register(&cli_trace);
1774                 ast_cli_register(&cli_no_trace);
1775                 ast_cli_register(&cli_show_codecs);
1776                 ast_cli_register(&cli_gk_cycle);
1777                 ast_cli_register(&cli_hangup_call);
1778                 ast_cli_register(&cli_show_tokens);
1779
1780                 oh323_rtp.type = type;
1781                 ast_rtp_proto_register(&oh323_rtp);
1782
1783                 sched = sched_context_create();
1784                 if (!sched) {
1785                         ast_log(LOG_WARNING, "Unable to create schedule context\n");
1786                 }
1787                 io = io_context_create();
1788                 if (!io) {
1789                         ast_log(LOG_WARNING, "Unable to create I/O context\n");
1790                 }
1791                 
1792                 /* Register our callback functions */
1793                 h323_callback_register(setup_incoming_call, 
1794                                        setup_outgoing_call,                                                      
1795                                        create_connection, 
1796                                        setup_rtp_connection, 
1797                                        cleanup_connection, 
1798                                        connection_made, 
1799                                        send_digit);     
1800         
1801
1802                 /* start the h.323 listener */
1803                 if (h323_start_listener(port, bindaddr)) {
1804                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
1805 //                      h323_end_process();
1806                         return -1;
1807                 }
1808
1809                 /* Possibly register with a GK */
1810                 if (gatekeeper_disable == 0) {
1811                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1812                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1813 //                              h323_end_process();
1814                                 return 0;
1815                         }
1816                 }
1817                 /* And start the monitor for the first time */
1818                 restart_monitor();
1819         }
1820         return res;
1821 }
1822
1823
1824 int unload_module() 
1825 {
1826         struct oh323_pvt *p, *pl;
1827                 
1828         if (!ast_mutex_lock(&iflock)) {
1829         /* hangup all interfaces if they have an owner */
1830         p = iflist;
1831         while(p) {
1832                 if (p->owner)
1833                         ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1834                 p = p->next;
1835         }
1836         iflist = NULL;
1837         ast_mutex_unlock(&iflock);
1838         } else {
1839                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1840                 return -1;
1841         }
1842
1843         if (!ast_mutex_lock(&monlock)) {
1844                 if (monitor_thread && (monitor_thread != -2)) {
1845                         pthread_cancel(monitor_thread);
1846                         pthread_kill(monitor_thread, SIGURG);
1847                         pthread_join(monitor_thread, NULL);
1848                  }
1849                 monitor_thread = (pthread_t) -2;
1850                 ast_mutex_unlock(&monlock);
1851         } else {
1852                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1853                 return -1;
1854         }
1855                 
1856         if (!ast_mutex_lock(&iflock)) {
1857                 /* destroy all the interfaces and free their memory */
1858                 p = iflist;
1859                 while(p) {
1860                         pl = p;
1861                         p = p->next;
1862                         /* free associated memory */
1863                         free(pl);
1864                 }
1865                 iflist = NULL;
1866                 ast_mutex_unlock(&iflock);
1867         } else {
1868                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1869                 return -1;
1870         }
1871         h323_gk_urq();
1872         h323_end_process();
1873
1874         /* unregister rtp */
1875         ast_rtp_proto_unregister(&oh323_rtp);
1876         
1877         /* unregister commands */
1878         ast_cli_unregister(&cli_debug);
1879         ast_cli_unregister(&cli_no_debug);
1880         ast_cli_unregister(&cli_trace);
1881         ast_cli_unregister(&cli_no_trace);   
1882         ast_cli_unregister(&cli_show_codecs);
1883         ast_cli_unregister(&cli_gk_cycle);
1884         ast_cli_unregister(&cli_hangup_call);
1885         ast_cli_unregister(&cli_show_tokens);
1886                         
1887         /* unregister channel type */
1888         ast_channel_unregister(type);
1889
1890         return 0; 
1891
1892
1893 int usecount()
1894 {
1895         int res;
1896         ast_mutex_lock(&usecnt_lock);
1897         res = usecnt;
1898         ast_mutex_unlock(&usecnt_lock);
1899         return res;
1900 }
1901
1902 char *description()
1903 {
1904         return desc;
1905 }
1906
1907 char *key()
1908 {
1909         return ASTERISK_GPL_KEY;
1910 }
1911
1912
1913
1914