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