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