b29f6977be96775b687853553c69ca59e582d4e7
[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 address*/
79 static int  userbyalias = 1;
80
81 static int  bridge_default = 1;
82
83 /* Just about everybody seems to support ulaw, so make it a nice default */
84 static int capability = AST_FORMAT_ULAW;
85
86 /* TOS flag */
87 static int tos = 0;
88
89 static int dtmfmode = H323_DTMF_RFC2833;
90
91 static char secret[50];
92
93 /** Private structure of a OpenH323 channel */
94 struct oh323_pvt {
95         ast_mutex_t lock;                                       /* Channel private lock */
96         call_options_t calloptions;                             /* Options to be used during call setup */
97         int alreadygone;                                        /* Whether or not we've already been destroyed by or peer */
98         int needdestroy;                                        /* if we need to be destroyed */
99         call_details_t cd;                                      /* Call details */
100         struct ast_channel *owner;                              /* Who owns us */
101         int capability;                                         /* audio capability */
102         int nonCodecCapability;                                 /* non-audio capability */
103         int outgoing;                                           /* Outgoing or incoming call? */
104         int nat;                                                /* Are we talking to a NAT EP?*/
105         int bridge;                                             /* Determine of we should native bridge or not*/
106         char exten[AST_MAX_EXTENSION];                          /* Requested extension */
107         char context[AST_MAX_EXTENSION];                        /* Context where to start */
108         char username[81];                                      /* H.323 alias using this channel */
109         char accountcode[256];                                  /* Account code */
110         int amaflags;                                           /* AMA Flags */
111         char callerid[80];                                      /* Caller*ID if available */
112         struct ast_rtp *rtp;                                    /* RTP Session */
113         int dtmfmode;                                           /* What DTMF Mode is being used */
114         struct ast_dsp *vad;                                    /* Used for in-band DTMF detection */
115         struct oh323_pvt *next;                                 /* Next channel in list */
116 } *iflist = NULL;
117
118 static struct ast_user_list {
119         struct oh323_user *users;
120         ast_mutex_t lock;
121 } userl = { NULL, AST_MUTEX_INITIALIZER };
122
123 static struct ast_peer_list {
124         struct oh323_peer *peers;
125         ast_mutex_t lock;
126 } peerl = { NULL, AST_MUTEX_INITIALIZER };
127
128 static struct ast_alias_list {
129         struct oh323_alias *aliases;
130         ast_mutex_t lock;
131 } aliasl = { NULL, AST_MUTEX_INITIALIZER };
132
133 /** Asterisk RTP stuff*/
134 static struct sched_context *sched;
135 static struct io_context *io;
136
137 /** Protect the interface list (of oh323_pvt's) */
138 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
139
140 /** Usage counter and associated lock */
141 static int usecnt =0;
142 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
143
144 /* Protect the monitoring thread, so only one process can kill or start it, and not
145    when it's doing something critical. */
146 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
147
148 /* This is the thread for the monitor which checks for input on the channels
149    which are not currently in use.  */
150 static pthread_t monitor_thread = AST_PTHREADT_NULL;
151
152 static int restart_monitor(void);
153
154 static void __oh323_destroy(struct oh323_pvt *p)
155 {
156         struct oh323_pvt *cur, *prev = NULL;
157         
158         if (p->rtp) {
159                 ast_rtp_destroy(p->rtp);
160         }
161         
162         /* Unlink us from the owner if we have one */
163         if (p->owner) {
164                 ast_mutex_lock(&p->owner->lock);
165                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
166                 p->owner->pvt->pvt = NULL;
167                 ast_mutex_unlock(&p->owner->lock);
168         }
169         cur = iflist;
170         while(cur) {
171                 if (cur == p) {
172                         if (prev)
173                                 prev->next = cur->next;
174                         else
175                                 iflist = cur->next;
176                         break;
177                 }
178                 prev = cur;
179                 cur = cur->next;
180         }
181         if (!cur) {
182                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
183         } else
184                 free(p);
185 }
186
187 static void oh323_destroy(struct oh323_pvt *p)
188 {
189         ast_mutex_lock(&iflock);
190         __oh323_destroy(p);
191         ast_mutex_unlock(&iflock);
192 }
193
194 static struct oh323_alias *build_alias(char *name, struct ast_variable *v)
195 {
196         struct oh323_alias *alias;
197
198         alias = (struct oh323_alias *)malloc(sizeof(struct oh323_alias));
199
200         if (alias) {
201                 memset(alias, 0, sizeof(struct oh323_alias));
202                 strncpy(alias->name, name, sizeof(alias->name)-1);
203
204                 while (v) {
205                         if (!strcasecmp(v->name, "e164")) {
206                                 strncpy(alias->e164,  v->value, sizeof(alias->e164)-1);
207                         } else if (!strcasecmp(v->name, "prefix")) {
208                                 strncpy(alias->prefix,  v->value, sizeof(alias->prefix)-1);
209                         } else if (!strcasecmp(v->name, "context")) {
210                                 strncpy(alias->context,  v->value, sizeof(alias->context)-1);
211                         } else if (!strcasecmp(v->name, "secret")) {
212                                 strncpy(alias->secret,  v->value, sizeof(alias->secret)-1);
213                         } else {
214                                 if (strcasecmp(v->value, "h323")) {     
215                                         ast_log(LOG_WARNING, "Keyword %s does not make sense in type=h323\n", v->value);
216                                 }
217                         }
218                         v = v->next;
219                 }
220         }
221         return alias;
222 }
223
224 static struct oh323_user *build_user(char *name, struct ast_variable *v)
225 {
226         struct oh323_user *user;
227         int format;
228         
229         user = (struct oh323_user *)malloc(sizeof(struct oh323_user));
230         if (user) {
231                 memset(user, 0, sizeof(struct oh323_user));
232                 strncpy(user->name, name, sizeof(user->name)-1);
233                 
234                 /* set the usage flag to a sane starting value*/
235                 user->inUse = 0;
236                 /* Assume we can native bridge */
237                 user->bridge = bridge_default; 
238
239                 while(v) {
240                         if (!strcasecmp(v->name, "context")) {
241                                 strncpy(user->context, v->value, sizeof(user->context)-1);
242                         } else if (!strcasecmp(v->name, "bridge")) {
243                                 user->bridge = ast_true(v->value);
244                       } else if (!strcasecmp(v->name, "nat")) {
245                               user->nat = ast_true(v->value);
246                         } else if (!strcasecmp(v->name, "noFastStart")) {
247                                 user->noFastStart = ast_true(v->value);
248                         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
249                                 user->noH245Tunneling = ast_true(v->value);
250                         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
251                                 user->noSilenceSuppression = ast_true(v->value);
252                         } else if (!strcasecmp(v->name, "secret")) {
253                                 strncpy(user->secret, v->value, sizeof(user->secret)-1);
254                         } else if (!strcasecmp(v->name, "callerid")) {
255                                 strncpy(user->callerid, v->value, sizeof(user->callerid)-1);
256                         } else if (!strcasecmp(v->name, "accountcode")) {
257                                 strncpy(user->accountcode, v->value, sizeof(user->accountcode)-1);
258                         } else if (!strcasecmp(v->name, "incominglimit")) {
259                                 user->incominglimit = atoi(v->value);
260                                 if (user->incominglimit < 0)
261                                         user->incominglimit = 0;
262                         } else if (!strcasecmp(v->name, "host")) {
263                                 if (!strcasecmp(v->value, "dynamic")) {
264                                         ast_log(LOG_ERROR, "Dynamic host configuration not implemented, yet!\n");
265                                         free(user);
266                                         return NULL;
267                                 } else if (ast_get_ip(&user->addr, v->value)) {
268                                         free(user);
269                                         return NULL;
270                                 } 
271                                 /* Let us know we need to use ip authentication */
272                                 user->host = 1;
273                         } else if (!strcasecmp(v->name, "amaflags")) {
274                                 format = ast_cdr_amaflags2int(v->value);
275                                 if (format < 0) {
276                                         ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
277                                 } else {
278                                         user->amaflags = format;
279                                 }
280                         }
281                         v = v->next;
282                 }
283         }
284         return user;
285 }
286
287
288 static struct oh323_peer *build_peer(char *name, struct ast_variable *v)
289 {
290         struct oh323_peer *peer;
291         struct oh323_peer *prev;
292         int found=0;
293         
294         prev = NULL;
295         ast_mutex_lock(&peerl.lock);
296         peer = peerl.peers;
297
298         while(peer) {
299                 if (!strcasecmp(peer->name, name)) {    
300                         break;
301                 }
302                 prev = peer;
303                 peer = peer->next;
304         }
305
306         if (peer) {
307                 found++;
308                 /* Already in the list, remove it and it will be added back (or FREE'd) */
309                 if (prev) {
310                         prev->next = peer->next;
311                 } else {
312                         peerl.peers = peer->next;
313                 }
314                 ast_mutex_unlock(&peerl.lock);
315         } else {
316                 ast_mutex_unlock(&peerl.lock);
317                 peer = malloc(sizeof(struct oh323_peer));
318                 memset(peer, 0, sizeof(struct oh323_peer));
319         }
320         if (peer) {
321                 if (!found) {
322                         strncpy(peer->name, name, sizeof(peer->name)-1);
323                 }
324                 
325                 /* set the usage flag to a sane starting value*/
326                 peer->inUse = 0;
327
328                 while(v) {
329                         if (!strcasecmp(v->name, "context")) {
330                                 strncpy(peer->context, v->value, sizeof(peer->context)-1);
331                         }  else if (!strcasecmp(v->name, "bridge")) {
332                                 peer->bridge = ast_true(v->value);
333                         } else if (!strcasecmp(v->name, "noFastStart")) {
334                                 peer->noFastStart = ast_true(v->value);
335                         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
336                                 peer->noH245Tunneling = ast_true(v->value);
337                         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
338                                 peer->noSilenceSuppression = ast_true(v->value);
339                         } else if (!strcasecmp(v->name, "outgoinglimit")) {
340                                 peer->outgoinglimit = atoi(v->value);
341                                 if (peer->outgoinglimit > 0)
342                                         peer->outgoinglimit = 0;
343                         } else if (!strcasecmp(v->name, "host")) {
344                                 if (!strcasecmp(v->value, "dynamic")) {
345                                         ast_log(LOG_ERROR, "Dynamic host configuration not implemented, yet!\n");
346                                         free(peer);
347                                         return NULL;
348                                 }
349                                 if (ast_get_ip(&peer->addr, v->value)) {
350                                                 free(peer);
351                                                 return NULL;
352                                 }
353                         } 
354                         v=v->next;
355                 }
356         }
357         return peer;
358 }
359
360
361
362 /**
363  * Send (play) the specified digit to the channel.
364  * 
365  */
366 static int oh323_digit(struct ast_channel *c, char digit)
367 {
368         struct oh323_pvt *p = c->pvt->pvt;
369         if (p && p->rtp && (p->dtmfmode & H323_DTMF_RFC2833)) {
370                 ast_rtp_senddigit(p->rtp, digit);
371         }
372         /* If in-band DTMF is desired, send that */
373         if (p->dtmfmode & H323_DTMF_INBAND)
374                 h323_send_tone(p->cd.call_token, digit);
375         return 0;
376 }
377
378
379 /**
380  * Make a call over the specified channel to the specified 
381  * destination. This function will parse the destination string
382  * and determine the address-number to call.
383  * Return -1 on error, 0 on success.
384  */
385 static int oh323_call(struct ast_channel *c, char *dest, int timeout)
386 {
387         int res;
388         struct oh323_pvt *p = c->pvt->pvt;
389         char called_addr[256];
390         char *tmp;
391
392         strtok_r(dest, "/", &(tmp));
393
394         ast_log(LOG_DEBUG, "dest=%s, timeout=%d.\n", dest, timeout);
395
396         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
397                 ast_log(LOG_WARNING, "Line is already in use (%s)\n", c->name);
398                 return -1;
399         }
400         
401         /* outgoing call */
402         p->outgoing = 1;
403
404         /* Clear the call token */
405         if ((p->cd).call_token == NULL)
406                 (p->cd).call_token = (char *)malloc(128);
407
408         memset((char *)(p->cd).call_token, 0, 128);
409         
410         if (p->cd.call_token == NULL) {
411                 ast_log(LOG_ERROR, "Not enough memory.\n");
412                 return -1;
413         }
414
415         /* Build the address to call */
416         memset(called_addr, 0, sizeof(dest));
417         memcpy(called_addr, dest, sizeof(called_addr));
418
419         /* Copy callerid, if there is any */
420         if (c->callerid) {
421                 char *tmp = strchr(c->callerid, '"');
422                 if (!tmp) {
423                         p->calloptions.callerid = malloc(80); // evil
424                         // sprintf(p->calloptions.callerid, "\"%s\"", c->callerid);
425                         sprintf(p->calloptions.callerid, "\"\" <%s>", c->callerid);
426                 } else {
427                         p->calloptions.callerid = strdup(c->callerid);
428                 }       
429          }
430
431         res = h323_make_call(called_addr, &(p->cd), p->calloptions);
432
433         if (res) {
434                 ast_log(LOG_NOTICE, "h323_make_call failed(%s)\n", c->name);
435                 return -1;
436         }
437
438         ast_setstate(c, AST_STATE_RINGING);
439         return 0;
440 }
441
442
443 static int oh323_answer(struct ast_channel *c)
444 {
445         int res;
446
447         struct oh323_pvt *p = c->pvt->pvt;
448
449         res = h323_answering_call(p->cd.call_token, 0);
450         
451         if (c->_state != AST_STATE_UP)
452                 ast_setstate(c, AST_STATE_UP);
453
454         return res;
455 }
456
457 static int oh323_hangup(struct ast_channel *c)
458 {
459         struct oh323_pvt *p = c->pvt->pvt;
460         int needcancel = 0;
461         if (h323debug)
462                 ast_log(LOG_DEBUG, "oh323_hangup(%s)\n", c->name);
463         if (!c->pvt->pvt) {
464                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
465                 return 0;
466         }
467         ast_mutex_lock(&p->lock);
468         /* Determine how to disconnect */
469         if (p->owner != c) {
470                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
471                 ast_mutex_unlock(&p->lock);
472                 return 0;
473         }
474         if (!c || (c->_state != AST_STATE_UP))
475                 needcancel = 1;
476         /* Disconnect */
477         p = c->pvt->pvt;
478         
479         /* Free dsp used for in-band DTMF detection */
480         if (p->vad) {
481                 ast_dsp_free(p->vad);
482         }
483
484         p->owner = NULL;
485         c->pvt->pvt = NULL;
486
487         /* Start the process if it's not already started */
488         if (!p->alreadygone) {
489                 p->needdestroy = 1;
490                 if (h323_clear_call((p->cd).call_token)) { 
491                         ast_log(LOG_DEBUG, "ClearCall failed.\n");
492                 }
493         }
494
495         /* Update usage counter */
496         ast_mutex_lock(&usecnt_lock);
497         usecnt--;
498         if (usecnt < 0)
499                 ast_log(LOG_WARNING, "Usecnt < 0\n");
500         ast_mutex_unlock(&usecnt_lock);
501         ast_update_use_count();
502
503         ast_mutex_unlock(&p->lock);
504         return 0;
505 }
506
507 static struct ast_frame *oh323_rtp_read(struct oh323_pvt *p)
508 {
509         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
510         struct ast_frame *f;
511         static struct ast_frame null_frame = { AST_FRAME_NULL, };
512
513       /* Only apply it for the first packet, we just need the correct ip/port */
514       if(p->nat)
515       {
516               ast_rtp_setnat(p->rtp,p->nat);
517               p->nat = 0;
518       }
519
520         f = ast_rtp_read(p->rtp);
521         /* Don't send RFC2833 if we're not supposed to */
522         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & H323_DTMF_RFC2833))
523                 return &null_frame;
524         if (p->owner) {
525                 /* We already hold the channel lock */
526                 if (f->frametype == AST_FRAME_VOICE) {
527                         if (f->subclass != p->owner->nativeformats) {
528                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
529                                 p->owner->nativeformats = f->subclass;
530                                 ast_set_read_format(p->owner, p->owner->readformat);
531                                 ast_set_write_format(p->owner, p->owner->writeformat);
532                         }
533                 
534                         /* Do in-band DTMF detection */
535                         if (p->dtmfmode & H323_DTMF_INBAND) {
536                    f = ast_dsp_process(p->owner,p->vad,f);
537                                    if (f->frametype == AST_FRAME_DTMF)
538                                         ast_log(LOG_DEBUG, "Got in-band digit %c.\n", f->subclass);
539             }
540                         
541                         
542                 }
543         }
544         return f;
545 }
546
547
548 static struct ast_frame  *oh323_read(struct ast_channel *c)
549 {
550         struct ast_frame *fr;
551         struct oh323_pvt *p = c->pvt->pvt;
552         ast_mutex_lock(&p->lock);
553         fr = oh323_rtp_read(p);
554         ast_mutex_unlock(&p->lock);
555         return fr;
556 }
557
558 static int oh323_write(struct ast_channel *c, struct ast_frame *frame)
559 {
560         struct oh323_pvt *p = c->pvt->pvt;
561         int res = 0;
562         if (frame->frametype != AST_FRAME_VOICE) {
563                 if (frame->frametype == AST_FRAME_IMAGE)
564                         return 0;
565                 else {
566                         ast_log(LOG_WARNING, "Can't send %d type frames with H323 write\n", frame->frametype);
567                         return 0;
568                 }
569         } else {
570                 if (!(frame->subclass & c->nativeformats)) {
571                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
572                                 frame->subclass, c->nativeformats, c->readformat, c->writeformat);
573                         return -1;
574                 }
575         }
576         if (p) {
577                 ast_mutex_lock(&p->lock);
578                 if (p->rtp) {
579                         res =  ast_rtp_write(p->rtp, frame);
580                 }
581                 ast_mutex_unlock(&p->lock);
582         }
583         return res;
584 }
585
586 /** FIXME: Can I acutally use this or does Open H.323 take care of everything? */
587 static int oh323_indicate(struct ast_channel *c, int condition)
588 {
589
590         struct oh323_pvt *p = c->pvt->pvt;
591         
592         switch(condition) {
593         case AST_CONTROL_RINGING:
594                 if (c->_state == AST_STATE_RING) {
595                 //      transmit_response(p, "180 Ringing", &p->initreq);
596                         break;
597                 }
598                 return 0;
599         case AST_CONTROL_BUSY:
600                 if (c->_state != AST_STATE_UP) {
601                 //      transmit_response(p, "600 Busy everywhere", &p->initreq);
602                         p->alreadygone = 1;
603                         ast_softhangup(c, AST_SOFTHANGUP_DEV);
604                         break;
605                 }
606                 return 0;
607         case AST_CONTROL_CONGESTION:
608                 if (c->_state != AST_STATE_UP) {
609                 //      transmit_response(p, "486 Busy here", &p->initreq);
610                         p->alreadygone = 1;
611                         ast_softhangup(c, AST_SOFTHANGUP_DEV);
612                         break;
613                 }
614                 return 0;
615         case -1:
616                 return -1;
617         default:
618                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
619                 return -1;
620         }
621         return 0;
622 }
623
624 // FIXME: WTF is this? Do I need this???
625 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
626 {
627         struct oh323_pvt *p = newchan->pvt->pvt;
628
629         ast_mutex_lock(&p->lock);
630         if (p->owner != oldchan) {
631                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
632                 return -1;
633         }
634         p->owner = newchan;
635         ast_mutex_unlock(&p->lock);
636         return 0;
637 }
638
639 static struct ast_channel *oh323_new(struct oh323_pvt *i, int state, const char *host)
640 {
641         struct ast_channel *ch;
642         int fmt;
643         ch = ast_channel_alloc(1);
644         
645         if (ch) {
646                 
647                 snprintf(ch->name, sizeof(ch->name)-1, "H323/%s", host);
648                 ch->nativeformats = i->capability;
649                 if (!ch->nativeformats)
650                         ch->nativeformats = capability;
651                 fmt = ast_best_codec(ch->nativeformats);
652                 ch->type = type;
653                 ch->fds[0] = ast_rtp_fd(i->rtp);
654                 ast_setstate(ch, state);
655                 
656                 if (state == AST_STATE_RING)
657                         ch->rings = 1;
658                 
659                 ch->writeformat = fmt;
660                 ch->pvt->rawwriteformat = fmt;
661                 ch->readformat = fmt;
662                 ch->pvt->rawreadformat = fmt;
663                 
664                 /* Allocate dsp for in-band DTMF support */
665                 if (i->dtmfmode & H323_DTMF_INBAND) {
666                         i->vad = ast_dsp_new();
667                         ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
668                 }
669
670                 /* Register the OpenH323 channel's functions. */
671                 ch->pvt->pvt = i;
672                 ch->pvt->send_digit = oh323_digit;
673                 ch->pvt->call = oh323_call;
674                 ch->pvt->hangup = oh323_hangup;
675                 ch->pvt->answer = oh323_answer;
676                 ch->pvt->read = oh323_read;
677                 ch->pvt->write = oh323_write;
678                 ch->pvt->indicate = oh323_indicate;
679                 ch->pvt->fixup = oh323_fixup;
680 //              ch->pvt->bridge = ast_rtp_bridge;
681
682                 /*  Set the owner of this channel */
683                 i->owner = ch;
684                 
685                 ast_mutex_lock(&usecnt_lock);
686                 usecnt++;
687                 ast_mutex_unlock(&usecnt_lock);
688                 ast_update_use_count();
689                 strncpy(ch->context, i->context, sizeof(ch->context)-1);
690                 strncpy(ch->exten, i->exten, sizeof(ch->exten)-1);              
691                 ch->priority = 1;
692                 if (strlen(i->callerid))
693                         ch->callerid = strdup(i->callerid);
694                 if (strlen(i->accountcode))
695                         strncpy(ch->accountcode, i->accountcode, sizeof(ch->accountcode)-1);
696                 if (i->amaflags)
697                         ch->amaflags = i->amaflags;
698                 if (state != AST_STATE_DOWN) {
699                         if (ast_pbx_start(ch)) {
700                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ch->name);
701                                 ast_hangup(ch);
702                                 ch = NULL;
703                         }
704                 }
705         } else
706                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
707         return ch;
708 }
709
710 static struct oh323_pvt *oh323_alloc(int callid)
711 {
712         struct oh323_pvt *p;
713
714         p = malloc(sizeof(struct oh323_pvt));
715         if (!p) {
716                 ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
717                 return NULL;
718         }
719
720         /* Keep track of stuff */
721         memset(p, 0, sizeof(struct oh323_pvt));
722         p->rtp = ast_rtp_new(sched, io, 1, 0);
723
724         if (!p->rtp) {
725                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
726                 free(p);
727                 return NULL;
728         }
729         ast_rtp_settos(p->rtp, tos);
730         ast_mutex_init(&p->lock);
731         
732         p->cd.call_reference = callid;
733         p->bridge = bridge_default;
734         
735         p->dtmfmode = dtmfmode;
736         if (p->dtmfmode & H323_DTMF_RFC2833)
737                 p->nonCodecCapability |= AST_RTP_DTMF;
738
739         /* Add to interface list */
740         ast_mutex_lock(&iflock);
741         p->next = iflist;
742         iflist = p;
743         ast_mutex_unlock(&iflock);
744         return p;
745 }
746
747 static struct oh323_pvt *find_call(int call_reference)
748 {  
749         struct oh323_pvt *p;
750
751                 ast_mutex_lock(&iflock);
752         p = iflist; 
753
754         while(p) {
755                 if (p->cd.call_reference == call_reference) {
756                         /* Found the call */                                            
757                                                 ast_mutex_unlock(&iflock);
758                                                 return p;
759                 }
760                 p = p->next; 
761         }
762         ast_mutex_unlock(&iflock);
763                 return NULL;
764         
765 }
766
767 static struct ast_channel *oh323_request(char *type, int format, void *data)
768 {
769
770         int oldformat;
771         struct oh323_pvt *p;
772         struct ast_channel *tmpc = NULL;
773         char *dest = data;
774         char *ext, *host;
775         char *h323id = NULL;
776         char tmp[256];
777
778         
779         ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
780
781         oldformat = format;
782         format &= capability;
783         if (!format) {
784                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
785                 return NULL;
786         }
787         
788         strncpy(tmp, dest, sizeof(tmp) - 1);
789                 
790         host = strchr(tmp, '@');
791         if (host) {
792                 *host = '\0';
793                 host++;
794                 ext = tmp;
795         } else {
796                 host = tmp;
797                 ext = NULL;
798         }
799
800         strtok_r(host, "/", &(h323id));
801                 
802         if (*h323id) {
803                 h323_set_id(h323id);
804         }
805                 
806         p = oh323_alloc(0);
807
808         if (!p) {
809                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
810                 return NULL;
811         }
812
813         /* Assign a default capability */
814         p->capability = capability;
815         
816         if (p->dtmfmode) {
817                 if (p->dtmfmode & H323_DTMF_RFC2833)
818                         p->nonCodecCapability |= AST_RTP_DTMF;
819                 else
820                         p->nonCodecCapability &= ~AST_RTP_DTMF;
821         }
822         /* pass on our preferred codec to the H.323 stack */
823         h323_set_capability(format, dtmfmode);
824
825         if (ext) {
826                 strncpy(p->username, ext, sizeof(p->username) - 1);
827         }
828         ast_log(LOG_DEBUG, "Host: %s\tUsername: %s\n", host, p->username);
829
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);   
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);
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                 /* Wait for sched or io */
1242                 res = ast_sched_wait(sched);
1243                 if ((res < 0) || (res > 1000))
1244                         res = 1000;
1245                 res = ast_io_wait(io, res);
1246
1247                 pthread_testcancel();
1248
1249                 ast_mutex_lock(&monlock);
1250                 if (res >= 0) 
1251                         ast_sched_runq(sched);
1252                 ast_mutex_unlock(&monlock);
1253         }
1254         /* Never reached */
1255         return NULL;
1256         
1257 }
1258
1259 static int restart_monitor(void)
1260 {
1261         /* If we're supposed to be stopped -- stay stopped */
1262         if (monitor_thread == AST_PTHREADT_STOP)
1263                 return 0;
1264         if (ast_mutex_lock(&monlock)) {
1265                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1266                 return -1;
1267         }
1268         if (monitor_thread == pthread_self()) {
1269                 ast_mutex_unlock(&monlock);
1270                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1271                 return -1;
1272         }
1273         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
1274                 /* Wake up the thread */
1275                 pthread_kill(monitor_thread, SIGURG);
1276         } else {
1277                 /* Start a new monitor */
1278                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1279                         ast_mutex_unlock(&monlock);
1280                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1281                         return -1;
1282                 }
1283         }
1284         ast_mutex_unlock(&monlock);
1285         return 0;
1286 }
1287
1288 static int h323_do_trace(int fd, int argc, char *argv[])
1289 {
1290         if (argc != 3) {
1291                 return RESULT_SHOWUSAGE;
1292         }
1293         h323_debug(1, atoi(argv[2]));
1294         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1295         return RESULT_SUCCESS;
1296 }
1297
1298 static int h323_no_trace(int fd, int argc, char *argv[])
1299 {
1300         if (argc != 3) {
1301                 return RESULT_SHOWUSAGE;
1302         }
1303         h323_debug(0,0);
1304         ast_cli(fd, "H.323 trace disabled\n");
1305         return RESULT_SUCCESS;
1306 }
1307
1308 static int h323_do_debug(int fd, int argc, char *argv[])
1309 {
1310         if (argc != 2) {
1311                 return RESULT_SHOWUSAGE;
1312         }
1313         h323debug = 1;
1314         ast_cli(fd, "H323 debug enabled\n");
1315         return RESULT_SUCCESS;
1316 }
1317
1318 static int h323_no_debug(int fd, int argc, char *argv[])
1319 {
1320         if (argc != 3) {
1321                 return RESULT_SHOWUSAGE;
1322         }
1323         h323debug = 0;
1324         ast_cli(fd, "H323 Debug disabled\n");
1325         return RESULT_SUCCESS;
1326 }
1327
1328 static int h323_gk_cycle(int fd, int argc, char *argv[])
1329 {
1330         return RESULT_SUCCESS;
1331 #if 0
1332         if (argc != 3) {
1333                 return RESULT_SHOWUSAGE;
1334         }       
1335         h323_gk_urq();
1336         
1337         /* Possibly register with a GK */
1338         if (!gatekeeper_disable) {
1339                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1340                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1341                 }
1342         }
1343         return RESULT_SUCCESS;
1344 #endif
1345 }
1346
1347 static int h323_ep_hangup(int fd, int argc, char *argv[])
1348 {
1349
1350         if (argc != 3) {
1351                 return RESULT_SHOWUSAGE;
1352         }
1353
1354         if (h323_soft_hangup(argv[2])) {
1355                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
1356         } else { 
1357                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
1358         }
1359
1360         return RESULT_SUCCESS;
1361 }
1362
1363 static int h323_tokens_show(int fd, int argc, char *argv[])
1364 {
1365
1366         if (argc != 3) {
1367                 return RESULT_SHOWUSAGE;
1368         }
1369         h323_show_tokens();
1370
1371         return RESULT_SUCCESS;
1372 }
1373
1374
1375 static char trace_usage[] = 
1376 "Usage: h.323 trace <level num>\n"
1377 "       Enables H.323 stack tracing for debugging purposes\n";
1378
1379 static char no_trace_usage[] = 
1380 "Usage: h.323 no trace\n"
1381 "       Disables H.323 stack tracing for debugging purposes\n";
1382
1383 static char debug_usage[] = 
1384 "Usage: h.323 debug\n"
1385 "       Enables chan_h323 debug output\n";
1386
1387 static char no_debug_usage[] = 
1388 "Usage: h.323 no debug\n"
1389 "       Disables chan_h323 debug output\n";
1390
1391 static char show_codec_usage[] = 
1392 "Usage: h.323 show codec\n"
1393 "       Shows all enabled codecs\n";
1394
1395 static char show_cycle_usage[] = 
1396 "Usage: h.323 gk cycle\n"
1397 "       Manually re-register with the Gatekeper\n";
1398
1399 static char show_hangup_usage[] = 
1400 "Usage: h.323 hangup <token>\n"
1401 "       Manually try to hang up call identified by <token>\n";
1402
1403 static char show_tokens_usage[] = 
1404 "Usage: h.323 show tokens\n"
1405 "       Print out all active call tokens\n";
1406
1407 static struct ast_cli_entry  cli_trace =
1408         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1409 static struct ast_cli_entry  cli_no_trace =
1410         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1411 static struct ast_cli_entry  cli_debug =
1412         { { "h.323", "debug", NULL }, h323_do_debug, "Enable chan_h323 debug", debug_usage };
1413 static struct ast_cli_entry  cli_no_debug =
1414         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable chan_h323 debug", no_debug_usage };
1415 static struct ast_cli_entry  cli_show_codecs =
1416         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1417 static struct ast_cli_entry  cli_gk_cycle =
1418         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1419 static struct ast_cli_entry  cli_hangup_call =
1420         { { "h.323", "hangup", NULL }, h323_ep_hangup, "Manually try to hang up a call", show_hangup_usage };
1421 static struct ast_cli_entry  cli_show_tokens =
1422         { { "h.323", "show", "tokens", NULL }, h323_tokens_show, "Manually try to hang up a call", show_tokens_usage };
1423
1424
1425
1426 int reload_config(void)
1427 {
1428         
1429         int format;
1430         struct ast_config *cfg;
1431         struct ast_variable *v;
1432         struct oh323_peer *peer   = NULL;
1433         struct oh323_user *user   = NULL;
1434         struct oh323_alias *alias = NULL;
1435         struct hostent *hp;
1436         char *cat;
1437         char *utype;
1438         
1439         cfg = ast_load(config);
1440
1441         /* We *must* have a config file otherwise stop immediately */
1442         if (!cfg) {
1443                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
1444                 return 1;
1445         }
1446         
1447        /* fire up the H.323 Endpoint */       
1448         if (!h323_end_point_exist()) {
1449                h323_end_point_create();        
1450         }
1451         h323debug=0;
1452         dtmfmode = H323_DTMF_RFC2833;
1453
1454         memset(&bindaddr, 0, sizeof(bindaddr));
1455
1456         v = ast_variable_browse(cfg, "general");
1457         while(v) {
1458                 /* Create the interface list */
1459                 if (!strcasecmp(v->name, "port")) {
1460                         port = (int)strtol(v->value, NULL, 10);
1461                 } else if (!strcasecmp(v->name, "bindaddr")) {
1462                         if (!(hp = gethostbyname(v->value))) {
1463                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1464                         } else {
1465                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1466                         }
1467                 } else if (!strcasecmp(v->name, "allow")) {
1468                         format = ast_getformatbyname(v->value);
1469                         if (format < 1) 
1470                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1471                         else
1472                                 capability |= format;
1473                 } else if (!strcasecmp(v->name, "disallow")) {
1474                         format = ast_getformatbyname(v->value);
1475                         if (format < 1) 
1476                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1477                         else
1478                                 capability &= ~format;
1479                 } else if (!strcasecmp(v->name, "tos")) {
1480                         if (sscanf(v->value, "%i", &format) == 1)
1481                                 tos = format & 0xff;
1482                         else if (!strcasecmp(v->value, "lowdelay"))
1483                                 tos = IPTOS_LOWDELAY;
1484                         else if (!strcasecmp(v->value, "throughput"))
1485                                 tos = IPTOS_THROUGHPUT;
1486                         else if (!strcasecmp(v->value, "reliability"))
1487                                 tos = IPTOS_RELIABILITY;
1488                         else if (!strcasecmp(v->value, "mincost"))
1489                                 tos = IPTOS_MINCOST;
1490                         else if (!strcasecmp(v->value, "none"))
1491                                 tos = 0;
1492                         else
1493                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
1494                 } else if (!strcasecmp(v->name, "gatekeeper")) {
1495                         if (!strcasecmp(v->value, "DISABLE")) {
1496                                 gatekeeper_disable = 1;
1497                                 usingGk = 0;
1498                         } else if (!strcasecmp(v->value, "DISCOVER")) {
1499                                 gatekeeper_disable = 0;
1500                                 gatekeeper_discover = 1;
1501                                 usingGk = 1;
1502                         } else {
1503                                 gatekeeper_disable = 0;
1504                                 usingGk = 1;
1505                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper)-1);
1506                         }
1507                 } else if (!strcasecmp(v->name, "secret")) {
1508                                 strncpy(secret, v->value, sizeof(secret)-1);
1509                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
1510                                 gkroute = ast_true(v->value);
1511                 } else if (!strcasecmp(v->name, "context")) {
1512                         strncpy(default_context, v->value, sizeof(default_context)-1);
1513                         ast_verbose(VERBOSE_PREFIX_3 "  == Setting default context to %s\n", default_context);  
1514                 } else if (!strcasecmp(v->name, "dtmfmode")) {
1515                         if (!strcasecmp(v->value, "inband"))
1516                                 dtmfmode=H323_DTMF_INBAND;
1517                         else if (!strcasecmp(v->value, "rfc2833"))
1518                                 dtmfmode = H323_DTMF_RFC2833;
1519                         else {
1520                                 ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1521                                 dtmfmode = H323_DTMF_RFC2833;
1522                         }
1523                 } else if (!strcasecmp(v->name, "UserByAlias")) {
1524                         userbyalias = ast_true(v->value);
1525                 } else if (!strcasecmp(v->name, "bridge")) {
1526                         bridge_default = ast_true(v->value);
1527                 }
1528                 v = v->next;    
1529         }
1530         
1531         cat = ast_category_browse(cfg, NULL);
1532         while(cat) {
1533                 if (strcasecmp(cat, "general")) {
1534                         utype = ast_variable_retrieve(cfg, cat, "type");
1535                         if (utype) {
1536                                 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
1537                                         user = build_user(cat, ast_variable_browse(cfg, cat));
1538                                         if (user) {
1539                                                 ast_mutex_lock(&userl.lock);
1540                                                 user->next = userl.users;
1541                                                 userl.users = user;
1542                                                 ast_mutex_unlock(&userl.lock);
1543                                         }
1544                                 }  else if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
1545                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
1546                                         if (peer) {
1547                                                 ast_mutex_lock(&peerl.lock);
1548                                                 peer->next = peerl.peers;
1549                                                 peerl.peers = peer;
1550                                                 ast_mutex_unlock(&peerl.lock);
1551                                         }
1552                                 }  else if (!strcasecmp(utype, "h323")) {                       
1553                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
1554                                         if (alias) {
1555                                                 ast_mutex_lock(&aliasl.lock);
1556                                                 alias->next = aliasl.aliases;
1557                                                 aliasl.aliases = alias;
1558                                                 ast_mutex_unlock(&aliasl.lock);
1559                                         }
1560                                 } else {
1561                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
1562                                 }
1563                         } else
1564                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
1565                 }
1566                 cat = ast_category_browse(cfg, cat);
1567         }
1568
1569         /* Register our H.323 aliases if any*/
1570         while (alias) {         
1571                 if (h323_set_alias(alias)) {
1572                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
1573                         return -1;
1574                 }       
1575                 alias = alias->next;
1576         }
1577
1578         /* Add some capabilities */
1579         if(h323_set_capability(capability, dtmfmode)) {
1580                 ast_log(LOG_ERROR, "Capabilities failure, this is bad.\n");
1581                 return -1;
1582         }       
1583         ast_destroy(cfg);
1584
1585         return 0;
1586 }
1587
1588 void delete_users(void)
1589 {
1590         struct oh323_user *user, *userlast;
1591         struct oh323_peer *peer;
1592         
1593         /* Delete all users */
1594         ast_mutex_lock(&userl.lock);
1595         for (user=userl.users;user;) {
1596                 userlast = user;
1597                 user=user->next;
1598                 free(userlast);
1599         }
1600         userl.users=NULL;
1601         ast_mutex_unlock(&userl.lock);
1602         ast_mutex_lock(&peerl.lock);
1603         for (peer=peerl.peers;peer;) {
1604                 /* Assume all will be deleted, and we'll find out for sure later */
1605                 peer->delme = 1;
1606                 peer = peer->next;
1607         }
1608         ast_mutex_unlock(&peerl.lock);
1609 }
1610
1611 void delete_aliases(void)
1612 {
1613         struct oh323_alias *alias, *aliaslast;
1614                 
1615         /* Delete all users */
1616         ast_mutex_lock(&aliasl.lock);
1617         for (alias=aliasl.aliases;alias;) {
1618                 aliaslast = alias;
1619                 alias=alias->next;
1620                 free(aliaslast);
1621         }
1622         aliasl.aliases=NULL;
1623         ast_mutex_unlock(&aliasl.lock);
1624 }
1625
1626 void prune_peers(void)
1627 {
1628         /* Prune peers who still are supposed to be deleted */
1629         struct oh323_peer *peer, *peerlast, *peernext;
1630         ast_mutex_lock(&peerl.lock);
1631         peerlast = NULL;
1632         for (peer=peerl.peers;peer;) {
1633                 peernext = peer->next;
1634                 if (peer->delme) {
1635                         free(peer);
1636                         if (peerlast)
1637                                 peerlast->next = peernext;
1638                         else
1639                                 peerl.peers = peernext;
1640                 } else
1641                         peerlast = peer;
1642                 peer=peernext;
1643         }
1644         ast_mutex_unlock(&peerl.lock);
1645 }
1646
1647 int reload(void)
1648 {
1649         delete_users();
1650         delete_aliases();
1651         prune_peers();
1652
1653 #if 0
1654         if (strlen(gatekeeper)) {
1655                 h323_gk_urq();
1656         }
1657 #endif
1658
1659         reload_config();
1660
1661 #if 0
1662         /* Possibly register with a GK */
1663         if (gatekeeper_disable == 0) {
1664                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1665                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1666                         h323_end_process();
1667                         return -1;
1668                 }
1669         }
1670 #endif
1671         restart_monitor();
1672         return 0;
1673 }
1674
1675
1676 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
1677 {
1678         struct oh323_pvt *p;
1679         p = chan->pvt->pvt;
1680         if (p && p->rtp && p->bridge) {
1681                 return p->rtp;
1682         }
1683         return NULL;
1684 }
1685
1686 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
1687 {
1688         return NULL;
1689 }
1690
1691 static char *convertcap(int cap)
1692 {
1693         switch (cap) {
1694         case AST_FORMAT_G723_1:
1695                 return "G.723";
1696         case AST_FORMAT_GSM:
1697                 return "GSM";
1698         case AST_FORMAT_ULAW:
1699                 return "ULAW";
1700         case AST_FORMAT_ALAW:
1701                 return "ALAW";
1702         case AST_FORMAT_ADPCM:
1703                 return "G.728";
1704         case AST_FORMAT_G729A:
1705                 return "G.729";
1706         case AST_FORMAT_SPEEX:
1707                 return "SPEEX";
1708         case AST_FORMAT_ILBC:
1709                 return "ILBC";
1710         default:
1711                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
1712                 return NULL;
1713         }
1714
1715 }
1716
1717 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp)
1718 {
1719         /* XXX Deal with Video */
1720         struct oh323_pvt *p;
1721         struct sockaddr_in them;
1722         struct sockaddr_in us;
1723         char *mode;
1724
1725         mode = convertcap(chan->writeformat); 
1726
1727         if (!rtp) {
1728                 return 0;
1729         }
1730
1731         p = chan->pvt->pvt;
1732         if (!p) {
1733                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
1734                 return -1;
1735         }
1736
1737         ast_rtp_get_peer(rtp, &them);   
1738         ast_rtp_get_us(rtp, &us);
1739
1740
1741         h323_native_bridge(p->cd.call_token, inet_ntoa(them.sin_addr), mode);
1742         
1743         return 0;
1744         
1745 }
1746
1747 static struct ast_rtp_protocol oh323_rtp = {
1748         get_rtp_info: oh323_get_rtp_peer,
1749         get_vrtp_info: oh323_get_vrtp_peer,
1750         set_rtp_peer: oh323_set_rtp_peer,
1751 };
1752
1753
1754 int load_module()
1755 {
1756         int res;
1757
1758         res = reload_config();
1759
1760         if (res) {
1761                 return 0;
1762         } else {
1763                 /* Make sure we can register our channel type */
1764                 if (ast_channel_register(type, tdesc, capability, oh323_request)) {
1765                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1766                         h323_end_process();
1767                         return -1;
1768                 }
1769                 ast_cli_register(&cli_debug);
1770                 ast_cli_register(&cli_no_debug);
1771                 ast_cli_register(&cli_trace);
1772                 ast_cli_register(&cli_no_trace);
1773                 ast_cli_register(&cli_show_codecs);
1774                 ast_cli_register(&cli_gk_cycle);
1775                 ast_cli_register(&cli_hangup_call);
1776                 ast_cli_register(&cli_show_tokens);
1777
1778                 oh323_rtp.type = type;
1779                 ast_rtp_proto_register(&oh323_rtp);
1780
1781                 sched = sched_context_create();
1782                 if (!sched) {
1783                         ast_log(LOG_WARNING, "Unable to create schedule context\n");
1784                 }
1785                 io = io_context_create();
1786                 if (!io) {
1787                         ast_log(LOG_WARNING, "Unable to create I/O context\n");
1788                 }
1789                 
1790                 /* Register our callback functions */
1791                 h323_callback_register(setup_incoming_call, 
1792                                        setup_outgoing_call,                                                      
1793                                        create_connection, 
1794                                        setup_rtp_connection, 
1795                                        cleanup_connection, 
1796                                        connection_made, 
1797                                        send_digit);     
1798         
1799
1800                 /* start the h.323 listener */
1801                 if (h323_start_listener(port, bindaddr)) {
1802                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
1803 //                      h323_end_process();
1804                         return -1;
1805                 }
1806
1807                 /* Possibly register with a GK */
1808                 if (gatekeeper_disable == 0) {
1809                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1810                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1811 //                              h323_end_process();
1812                                 return 0;
1813                         }
1814                 }
1815                 /* And start the monitor for the first time */
1816                 restart_monitor();
1817         }
1818         return res;
1819 }
1820
1821
1822 int unload_module() 
1823 {
1824         struct oh323_pvt *p, *pl;
1825                 
1826         if (!ast_mutex_lock(&iflock)) {
1827         /* hangup all interfaces if they have an owner */
1828         p = iflist;
1829         while(p) {
1830                 if (p->owner)
1831                         ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1832                 p = p->next;
1833         }
1834         iflist = NULL;
1835         ast_mutex_unlock(&iflock);
1836         } else {
1837                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1838                 return -1;
1839         }
1840
1841         if (!ast_mutex_lock(&monlock)) {
1842                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
1843                         pthread_cancel(monitor_thread);
1844                         pthread_kill(monitor_thread, SIGURG);
1845                         pthread_join(monitor_thread, NULL);
1846                  }
1847                 monitor_thread = AST_PTHREADT_STOP;
1848                 ast_mutex_unlock(&monlock);
1849         } else {
1850                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1851                 return -1;
1852         }
1853                 
1854         if (!ast_mutex_lock(&iflock)) {
1855                 /* destroy all the interfaces and free their memory */
1856                 p = iflist;
1857                 while(p) {
1858                         pl = p;
1859                         p = p->next;
1860                         /* free associated memory */
1861                         free(pl);
1862                 }
1863                 iflist = NULL;
1864                 ast_mutex_unlock(&iflock);
1865         } else {
1866                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1867                 return -1;
1868         }
1869         h323_gk_urq();
1870         h323_end_process();
1871
1872         /* unregister rtp */
1873         ast_rtp_proto_unregister(&oh323_rtp);
1874         
1875         /* unregister commands */
1876         ast_cli_unregister(&cli_debug);
1877         ast_cli_unregister(&cli_no_debug);
1878         ast_cli_unregister(&cli_trace);
1879         ast_cli_unregister(&cli_no_trace);   
1880         ast_cli_unregister(&cli_show_codecs);
1881         ast_cli_unregister(&cli_gk_cycle);
1882         ast_cli_unregister(&cli_hangup_call);
1883         ast_cli_unregister(&cli_show_tokens);
1884                         
1885         /* unregister channel type */
1886         ast_channel_unregister(type);
1887
1888         return 0; 
1889
1890
1891 int usecount()
1892 {
1893         int res;
1894         ast_mutex_lock(&usecnt_lock);
1895         res = usecnt;
1896         ast_mutex_unlock(&usecnt_lock);
1897         return res;
1898 }
1899
1900 char *description()
1901 {
1902         return desc;
1903 }
1904
1905 char *key()
1906 {
1907         return ASTERISK_GPL_KEY;
1908 }
1909
1910
1911
1912