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