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