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