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