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