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