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