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