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