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