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