e016b48123f33695e7d97b41be3cb916991fb705
[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 AST_CONTROL_PROCEEDING:
657         case -1:
658                 return -1;
659         default:
660                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
661                 return -1;
662         }
663         return 0;
664 }
665
666 // FIXME: WTF is this? Do I need this???
667 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
668 {
669         struct oh323_pvt *p = newchan->pvt->pvt;
670
671         ast_mutex_lock(&p->lock);
672         if (p->owner != oldchan) {
673                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
674                 return -1;
675         }
676         p->owner = newchan;
677         ast_mutex_unlock(&p->lock);
678         return 0;
679 }
680
681 static struct ast_channel *oh323_new(struct oh323_pvt *i, int state, const char *host)
682 {
683         struct ast_channel *ch;
684         int fmt;
685         ch = ast_channel_alloc(1);
686         
687         if (ch) {
688                 
689                 snprintf(ch->name, sizeof(ch->name)-1, "H323/%s", host);
690                 ch->nativeformats = i->capability;
691                 if (!ch->nativeformats)
692                         ch->nativeformats = capability;
693                 fmt = ast_best_codec(ch->nativeformats);
694                 ch->type = type;
695                 ch->fds[0] = ast_rtp_fd(i->rtp);
696                 
697                 if (state == AST_STATE_RING)
698                         ch->rings = 1;
699                 
700                 ch->writeformat = fmt;
701                 ch->pvt->rawwriteformat = fmt;
702                 ch->readformat = fmt;
703                 ch->pvt->rawreadformat = fmt;
704                 
705                 /* Allocate dsp for in-band DTMF support */
706                 if (i->dtmfmode & H323_DTMF_INBAND) {
707                         i->vad = ast_dsp_new();
708                         ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
709                 }
710
711                 /* Register the OpenH323 channel's functions. */
712                 ch->pvt->pvt = i;
713                 ch->pvt->send_digit = oh323_digit;
714                 ch->pvt->call = oh323_call;
715                 ch->pvt->hangup = oh323_hangup;
716                 ch->pvt->answer = oh323_answer;
717                 ch->pvt->read = oh323_read;
718                 ch->pvt->write = oh323_write;
719                 ch->pvt->indicate = oh323_indicate;
720                 ch->pvt->fixup = oh323_fixup;
721              /* ch->pvt->bridge = ast_rtp_bridge; */
722
723                 /*  Set the owner of this channel */
724                 i->owner = ch;
725                 
726                 ast_mutex_lock(&usecnt_lock);
727                 usecnt++;
728                 ast_mutex_unlock(&usecnt_lock);
729                 ast_update_use_count();
730                 strncpy(ch->context, i->context, sizeof(ch->context)-1);
731                 strncpy(ch->exten, i->exten, sizeof(ch->exten)-1);              
732                 ch->priority = 1;
733                 if (!ast_strlen_zero(i->callerid))
734                         ch->callerid = strdup(i->callerid);
735                 if (!ast_strlen_zero(i->accountcode))
736                         strncpy(ch->accountcode, i->accountcode, sizeof(ch->accountcode)-1);
737                 if (i->amaflags)
738                         ch->amaflags = i->amaflags;
739                 ast_setstate(ch, state);
740                 if (state != AST_STATE_DOWN) {
741                         if (ast_pbx_start(ch)) {
742                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ch->name);
743                                 ast_hangup(ch);
744                                 ch = NULL;
745                         }
746                 }
747         } else
748                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
749         return ch;
750 }
751
752 static struct oh323_pvt *oh323_alloc(int callid)
753 {
754         struct oh323_pvt *p;
755
756         p = malloc(sizeof(struct oh323_pvt));
757         if (!p) {
758                 ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
759                 return NULL;
760         }
761
762         /* Keep track of stuff */
763         memset(p, 0, sizeof(struct oh323_pvt));
764         p->rtp = ast_rtp_new(sched, io, 1, 0);
765
766         if (!p->rtp) {
767                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
768                 free(p);
769                 return NULL;
770         }
771         ast_rtp_settos(p->rtp, tos);
772         ast_mutex_init(&p->lock);
773         
774         p->cd.call_reference = callid;
775         p->bridge = bridge_default;
776         
777         p->dtmfmode = dtmfmode;
778         if (p->dtmfmode & H323_DTMF_RFC2833)
779                 p->nonCodecCapability |= AST_RTP_DTMF;
780
781         /* Add to interface list */
782         ast_mutex_lock(&iflock);
783         p->next = iflist;
784         iflist = p;
785         ast_mutex_unlock(&iflock);
786         return p;
787 }
788
789 static struct oh323_pvt *find_call(int call_reference)
790 {  
791         struct oh323_pvt *p;
792
793                 ast_mutex_lock(&iflock);
794         p = iflist; 
795
796         while(p) {
797                 if (p->cd.call_reference == call_reference) {
798                         /* Found the call */                                            
799                                                 ast_mutex_unlock(&iflock);
800                                                 return p;
801                 }
802                 p = p->next; 
803         }
804         ast_mutex_unlock(&iflock);
805                 return NULL;
806         
807 }
808
809 static struct ast_channel *oh323_request(char *type, int format, void *data)
810 {
811
812         int oldformat;
813         struct oh323_pvt *p;
814         struct ast_channel *tmpc = NULL;
815         char *dest = data;
816         char *ext, *host;
817         char *h323id = NULL;
818         char tmp[256];
819
820         
821         ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
822
823         oldformat = format;
824         format &= capability;
825         if (!format) {
826                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
827                 return NULL;
828         }
829         
830         strncpy(tmp, dest, sizeof(tmp) - 1);
831                 
832         host = strchr(tmp, '@');
833         if (host) {
834                 *host = '\0';
835                 host++;
836                 ext = tmp;
837         } else {
838                 host = tmp;
839                 ext = NULL;
840         }
841
842         strtok_r(host, "/", &(h323id));
843                 
844         if (*h323id) {
845                 h323_set_id(h323id);
846         }
847                 
848         p = oh323_alloc(0);
849
850         if (!p) {
851                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
852                 return NULL;
853         }
854
855         /* Assign a default capability */
856         p->capability = capability;
857         
858         if (p->dtmfmode) {
859                 if (p->dtmfmode & H323_DTMF_RFC2833)
860                         p->nonCodecCapability |= AST_RTP_DTMF;
861                 else
862                         p->nonCodecCapability &= ~AST_RTP_DTMF;
863         }
864         /* pass on our preferred codec to the H.323 stack */
865         h323_set_capability(format, dtmfmode);
866
867         if (ext) {
868                 strncpy(p->username, ext, sizeof(p->username) - 1);
869         }
870         ast_log(LOG_DEBUG, "Host: %s\tUsername: %s\n", host, p->username);
871
872         tmpc = oh323_new(p, AST_STATE_DOWN, host);
873         if (!tmpc)
874                 oh323_destroy(p);
875         
876         restart_monitor();
877         
878         return tmpc;
879 }
880
881 struct oh323_alias *find_alias(const char *source_aliases)
882 {
883         struct oh323_alias *a;
884
885         a = aliasl.aliases;
886
887         while(a) {
888
889                 if (!strcasecmp(a->name, source_aliases)) {
890                         break;
891                 }
892                 a = a->next;
893         }
894         return a;
895 }
896
897 struct oh323_user *find_user(const call_details_t cd)
898 {
899         struct oh323_user *u;
900
901         u = userl.users;
902         if(userbyalias == 1){
903                 while(u) {
904                         if (!strcasecmp(u->name, cd.call_source_aliases)) {
905                                 break;
906                         }
907                         u = u->next;
908                 }
909
910         } else {
911                 while(u) {
912                         if (!strcasecmp(cd.sourceIp, inet_ntoa(u->addr.sin_addr))) {
913                                 break;
914                         }
915                         u = u->next;
916                 }
917
918         
919         }
920         return u;
921
922 }
923
924 struct oh323_peer *find_peer(char *dest_peer)
925 {
926         struct oh323_peer *p;
927
928         p = peerl.peers;
929
930         while(p) {
931                 if (!strcasecmp(p->name, dest_peer)) {
932                         break;
933                 }
934                 p = p->next;
935         }
936         return p;
937
938 }
939
940 /**
941   * Callback for sending digits from H.323 up to asterisk
942   *
943   */
944 int send_digit(unsigned call_reference, char digit)
945 {
946         struct oh323_pvt *p;
947         struct ast_frame f;
948
949         ast_log(LOG_DEBUG, "Recieved Digit: %c\n", digit);
950         p = find_call(call_reference);
951         
952         if (!p) {
953                 ast_log(LOG_ERROR, "Private structure not found in send_digit.\n");
954                 return -1;
955         }
956         memset(&f, 0, sizeof(f));
957         f.frametype = AST_FRAME_DTMF;
958     f.subclass = digit;
959     f.datalen = 0;
960     f.samples = 800;
961     f.offset = 0;
962     f.data = NULL;
963     f.mallocd = 0;
964     f.src = "SEND_DIGIT";
965         
966         return ast_queue_frame(p->owner, &f);   
967 }
968
969 /**
970   * Call-back function that gets called when any H.323 connection is made
971   *
972   * Returns the local RTP information
973   */
974 struct rtp_info *create_connection(unsigned call_reference)
975 {       
976         struct oh323_pvt *p;
977         struct sockaddr_in us;
978         struct sockaddr_in them;
979         struct rtp_info *info;
980
981         info = malloc(sizeof(struct rtp_info));
982
983         p = find_call(call_reference);
984
985         if (!p) {
986                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is very bad.\n");
987                 return NULL;
988         }
989
990         /* figure out our local RTP port and tell the H.323 stack about it*/
991         ast_rtp_get_us(p->rtp, &us);
992         ast_rtp_get_peer(p->rtp, &them);
993
994         info->addr = inet_ntoa(us.sin_addr);
995         info->port = ntohs(us.sin_port);
996
997         return info;
998 }
999
1000 /**
1001  *  Call-back function for incoming calls
1002  *
1003  *  Returns 1 on success
1004  */
1005
1006 int setup_incoming_call(call_details_t cd)
1007 {
1008         
1009         struct oh323_pvt *p = NULL;
1010 /*      struct ast_channel *c = NULL; */
1011         struct oh323_user *user = NULL;
1012         struct oh323_alias *alias = NULL;
1013
1014         /* allocate the call*/
1015         p = oh323_alloc(cd.call_reference);
1016
1017         if (!p) {
1018                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
1019                 return 0;
1020         }
1021
1022         /* Populate the call details in the private structure */
1023         p->cd.call_token = cd.call_token;
1024         p->cd.call_source_aliases = cd.call_source_aliases;
1025         p->cd.call_dest_alias = cd.call_dest_alias;
1026         p->cd.call_source_name = cd.call_source_name;
1027         p->cd.call_source_e164 = cd.call_source_e164;
1028         p->cd.call_dest_e164 = cd.call_dest_e164;
1029
1030         if (h323debug) {
1031                 ast_verbose(VERBOSE_PREFIX_3 "Setting up Call\n");
1032                 ast_verbose(VERBOSE_PREFIX_3 "     Call token:  [%s]\n", p->cd.call_token);
1033                 ast_verbose(VERBOSE_PREFIX_3 "     Calling party name:  [%s]\n", p->cd.call_source_name);
1034                 ast_verbose(VERBOSE_PREFIX_3 "     Calling party number:  [%s]\n", p->cd.call_source_e164);
1035                 ast_verbose(VERBOSE_PREFIX_3 "     Called  party name:  [%s]\n", p->cd.call_dest_alias);
1036                 ast_verbose(VERBOSE_PREFIX_3 "     Called  party number:  [%s]\n", p->cd.call_dest_e164);
1037         }
1038
1039         /* Decide if we are allowing Gatekeeper routed calls*/
1040         if ((!strcasecmp(cd.sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk == 1)) {
1041                 
1042                 if (!ast_strlen_zero(cd.call_dest_e164)) {
1043                         strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1044                         strncpy(p->context, default_context, sizeof(p->context)-1); 
1045                 } else {
1046                         alias = find_alias(cd.call_dest_alias);
1047                 
1048                         if (!alias) {
1049                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd.call_dest_alias);
1050                                 return 0;
1051                         }
1052                         strncpy(p->exten, alias->name, sizeof(p->exten)-1);
1053                         strncpy(p->context, alias->context, sizeof(p->context)-1);
1054                 }
1055                 sprintf(p->callerid, "%s <%s>", p->cd.call_source_name, p->cd.call_source_e164);
1056         } else { 
1057                 /* Either this call is not from the Gatekeeper 
1058                    or we are not allowing gk routed calls */
1059                 user  = find_user(cd);
1060
1061                 if (!user) {
1062                         sprintf(p->callerid, "%s <%s>", p->cd.call_source_name, p->cd.call_source_e164);
1063                         if (!ast_strlen_zero(p->cd.call_dest_e164)) {
1064                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1065                         } else {
1066                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
1067                         }
1068                         if (ast_strlen_zero(default_context)) {
1069                                 ast_log(LOG_ERROR, "Call from '%s' rejected due to no default context\n", p->cd.call_source_aliases);
1070                                 return 0;
1071                         }
1072                         strncpy(p->context, default_context, sizeof(p->context)-1);
1073                         ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd.call_source_aliases, p->context);
1074                 } else {                                        
1075                         if (user->host) {
1076                                 if (strcasecmp(cd.sourceIp, inet_ntoa(user->addr.sin_addr))){                                   
1077                                         if (ast_strlen_zero(user->context)) {
1078                                                 if (ast_strlen_zero(default_context)) {                                 
1079                                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s) and no default context\n", user->name, cd.sourceIp);
1080                                                         return 0;
1081                                                 }
1082                                                 strncpy(p->context, default_context, sizeof(p->context)-1);
1083                                         } else {
1084                                                 strncpy(p->context, user->context, sizeof(p->context)-1);
1085                                         }
1086                                         sprintf(p->exten, "i");
1087                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s)s\n", user->name, cd.sourceIp);
1088                                         goto exit;                                      
1089                                 }
1090                         }
1091                         if (user->incominglimit > 0) {
1092                                 if (user->inUse >= user->incominglimit) {
1093                                         ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", user->name, user->incominglimit);
1094                                         return 0;
1095                                 }
1096                         }
1097                         strncpy(p->context, user->context, sizeof(p->context)-1);
1098                         p->bridge = user->bridge;
1099                         p->nat = user->nat;
1100
1101                         if (!ast_strlen_zero(user->callerid)) {
1102                                 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
1103                         } else {
1104                                  sprintf(p->callerid, "%s <%s>", p->cd.call_source_name, p->cd.call_source_e164); 
1105                         }
1106                         if (!ast_strlen_zero(p->cd.call_dest_e164)) {
1107                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1108                         } else {
1109                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
1110                         }
1111                         if (!ast_strlen_zero(user->accountcode)) {
1112                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)-1);
1113                         } 
1114
1115                         /* Increment the usage counter */
1116                         user->inUse++;
1117                 } 
1118         }
1119
1120 exit:
1121 #if 0
1122         /* allocate a channel and tell asterisk about it */
1123         c = oh323_new(p, AST_STATE_RINGING, cd.call_token);
1124         if (!c) {
1125                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1126                 return 0;
1127         }
1128 #endif
1129         return 1;
1130 }
1131
1132 /**
1133  * Call-back function to start PBX when OpenH323 ready to serve incoming call
1134  *
1135  * Returns 1 on success
1136  */
1137 static int answer_call(unsigned call_reference)
1138 {
1139         struct oh323_pvt *p = NULL;
1140         struct ast_channel *c = NULL;
1141         
1142         /* Find the call or allocate a private structure if call not found */
1143         p = find_call(call_reference);
1144         
1145         if (!p) {
1146                 ast_log(LOG_ERROR, "Something is wrong: answer_call\n");
1147                 return 0;
1148         }
1149         
1150         /* allocate a channel and tell asterisk about it */
1151         c = oh323_new(p, AST_STATE_RINGING, p->cd.call_token);
1152         if (!c) {
1153                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1154                 return 0;
1155         }
1156         return 1;
1157 }
1158
1159 /**
1160  * Call-back function to establish an outgoing H.323 call
1161  * 
1162  * Returns 1 on success 
1163  */
1164 int setup_outgoing_call(call_details_t cd)
1165 {       
1166         return 1;
1167 }
1168
1169 #if 0
1170 if (p->inUse >= p->outgoinglimit) {
1171         ast_log(LOG_ERROR, "Call to %s rejected due to usage limit of %d outgoing channels\n", p->name, p->inUse);
1172         return 0;
1173 }
1174
1175 if (!p) {
1176         ast_log(LOG_ERROR, "Rejecting call: peer %s not found\n", dest_peer);
1177         return 0;
1178 }
1179 #endif
1180
1181 /**
1182   * Call-back function that gets called for each rtp channel opened 
1183   *
1184   * Returns nothing 
1185   */
1186 void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort)
1187 {
1188         struct oh323_pvt *p = NULL;
1189         struct sockaddr_in them;
1190
1191         /* Find the call or allocate a private structure if call not found */
1192         p = find_call(call_reference);
1193
1194         if (!p) {
1195                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1196                 return;
1197         }
1198
1199         them.sin_family = AF_INET;
1200         them.sin_addr.s_addr = inet_addr(remoteIp); // only works for IPv4
1201         them.sin_port = htons(remotePort);
1202         ast_rtp_set_peer(p->rtp, &them);
1203
1204         return;
1205 }
1206
1207 /**  
1208   *     Call-back function to signal asterisk that the channel has been answered 
1209   * Returns nothing
1210   */
1211 void connection_made(unsigned call_reference)
1212 {
1213         struct ast_channel *c = NULL;
1214         struct oh323_pvt *p = NULL;
1215         
1216         p = find_call(call_reference);
1217         
1218         if (!p)
1219                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1220
1221
1222         if (!p->owner) {
1223                 ast_log(LOG_ERROR, "Channel has no owner\n");
1224                 return;
1225         }
1226         c = p->owner;   
1227
1228         ast_setstate(c, AST_STATE_UP);
1229         ast_queue_control(c, AST_CONTROL_ANSWER);
1230         return;
1231 }
1232
1233 /**
1234   *  Call-back function to signal asterisk that the channel is ringing
1235   *  Returns nothing
1236   */
1237 void chan_ringing(unsigned call_reference)
1238 {
1239         struct ast_channel *c = NULL;
1240         struct oh323_pvt *p = NULL;
1241
1242         p = find_call(call_reference);
1243
1244         if (!p) {
1245                 ast_log(LOG_ERROR, "Something is wrong: ringing\n");
1246         }
1247
1248         if (!p->owner) {
1249                 ast_log(LOG_ERROR, "Channel has no owner\n");
1250                 return;
1251         }
1252         c = p->owner;
1253         ast_setstate(c, AST_STATE_RINGING);
1254         ast_queue_control(c, AST_CONTROL_RINGING);
1255         return;
1256 }
1257
1258 /**
1259   * Call-back function to cleanup communication
1260   * Returns nothing,
1261   */
1262 void cleanup_connection(call_details_t cd)
1263 {       
1264         struct oh323_pvt *p = NULL;
1265 /*      struct oh323_peer *peer = NULL; */
1266         struct oh323_user *user = NULL;
1267         struct ast_rtp *rtp = NULL;
1268         
1269         p = find_call(cd.call_reference);
1270
1271         if (!p) {
1272                 return;
1273         }
1274         ast_mutex_lock(&p->lock);
1275
1276         /* Decrement usage counter */
1277         if (!p->outgoing) {
1278                 user = find_user(cd);
1279                 
1280                 if(user) {
1281                         user->inUse--;
1282                 }
1283         }
1284
1285 #if 0
1286         if (p->outgoing) {
1287                 peer = find_peer(cd.call_dest_alias);
1288                 peer->inUse--;
1289         } else {
1290                 user = find_user(cd);
1291                 user->inUse--;
1292         }
1293 #endif
1294         
1295         if (p->rtp) {
1296                 rtp = p->rtp;
1297                 p->rtp = NULL;
1298                 /* Immediately stop RTP */
1299                 ast_rtp_destroy(rtp);
1300         }
1301
1302         p->alreadygone = 1;
1303         
1304         /* Send hangup */       
1305         if (p->owner) {
1306                 ast_queue_hangup(p->owner);
1307         } 
1308
1309         ast_mutex_unlock(&p->lock);
1310         return; 
1311 }
1312
1313 static void *do_monitor(void *data)
1314 {
1315         int res;
1316         struct oh323_pvt *oh323 = NULL;
1317         
1318                 for(;;) {
1319                 /* Check for interfaces needing to be killed */
1320                 ast_mutex_lock(&iflock);
1321 restartsearch:          
1322                 oh323 = iflist;
1323                 while(oh323) {
1324                         if (oh323->needdestroy) {
1325                                 __oh323_destroy(oh323);
1326                                 goto restartsearch;
1327                         }
1328                         oh323 = oh323->next;
1329                 }
1330                 ast_mutex_unlock(&iflock);
1331
1332                 /* Wait for sched or io */
1333                 res = ast_sched_wait(sched);
1334                 if ((res < 0) || (res > 1000))
1335                         res = 1000;
1336                 res = ast_io_wait(io, res);
1337
1338                 pthread_testcancel();
1339
1340                 ast_mutex_lock(&monlock);
1341                 if (res >= 0) 
1342                         ast_sched_runq(sched);
1343                 ast_mutex_unlock(&monlock);
1344         }
1345         /* Never reached */
1346         return NULL;
1347         
1348 }
1349
1350 static int restart_monitor(void)
1351 {
1352         /* If we're supposed to be stopped -- stay stopped */
1353         if (monitor_thread == AST_PTHREADT_STOP)
1354                 return 0;
1355         if (ast_mutex_lock(&monlock)) {
1356                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1357                 return -1;
1358         }
1359         if (monitor_thread == pthread_self()) {
1360                 ast_mutex_unlock(&monlock);
1361                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1362                 return -1;
1363         }
1364         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
1365                 /* Wake up the thread */
1366                 pthread_kill(monitor_thread, SIGURG);
1367         } else {
1368                 /* Start a new monitor */
1369                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1370                         ast_mutex_unlock(&monlock);
1371                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1372                         return -1;
1373                 }
1374         }
1375         ast_mutex_unlock(&monlock);
1376         return 0;
1377 }
1378
1379 static int h323_do_trace(int fd, int argc, char *argv[])
1380 {
1381         if (argc != 3) {
1382                 return RESULT_SHOWUSAGE;
1383         }
1384         h323_debug(1, atoi(argv[2]));
1385         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1386         return RESULT_SUCCESS;
1387 }
1388
1389 static int h323_no_trace(int fd, int argc, char *argv[])
1390 {
1391         if (argc != 3) {
1392                 return RESULT_SHOWUSAGE;
1393         }
1394         h323_debug(0,0);
1395         ast_cli(fd, "H.323 trace disabled\n");
1396         return RESULT_SUCCESS;
1397 }
1398
1399 static int h323_do_debug(int fd, int argc, char *argv[])
1400 {
1401         if (argc != 2) {
1402                 return RESULT_SHOWUSAGE;
1403         }
1404         h323debug = 1;
1405         ast_cli(fd, "H323 debug enabled\n");
1406         return RESULT_SUCCESS;
1407 }
1408
1409 static int h323_no_debug(int fd, int argc, char *argv[])
1410 {
1411         if (argc != 3) {
1412                 return RESULT_SHOWUSAGE;
1413         }
1414         h323debug = 0;
1415         ast_cli(fd, "H323 Debug disabled\n");
1416         return RESULT_SUCCESS;
1417 }
1418
1419 static int h323_gk_cycle(int fd, int argc, char *argv[])
1420 {
1421         return RESULT_SUCCESS;
1422 #if 0
1423         if (argc != 3) {
1424                 return RESULT_SHOWUSAGE;
1425         }       
1426         h323_gk_urq();
1427         
1428         /* Possibly register with a GK */
1429         if (!gatekeeper_disable) {
1430                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1431                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1432                 }
1433         }
1434         return RESULT_SUCCESS;
1435 #endif
1436 }
1437
1438 static int h323_ep_hangup(int fd, int argc, char *argv[])
1439 {
1440
1441         if (argc != 3) {
1442                 return RESULT_SHOWUSAGE;
1443         }
1444
1445         if (h323_soft_hangup(argv[2])) {
1446                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
1447         } else { 
1448                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
1449         }
1450
1451         return RESULT_SUCCESS;
1452 }
1453
1454 static int h323_tokens_show(int fd, int argc, char *argv[])
1455 {
1456
1457         if (argc != 3) {
1458                 return RESULT_SHOWUSAGE;
1459         }
1460         h323_show_tokens();
1461
1462         return RESULT_SUCCESS;
1463 }
1464
1465
1466 static char trace_usage[] = 
1467 "Usage: h.323 trace <level num>\n"
1468 "       Enables H.323 stack tracing for debugging purposes\n";
1469
1470 static char no_trace_usage[] = 
1471 "Usage: h.323 no trace\n"
1472 "       Disables H.323 stack tracing for debugging purposes\n";
1473
1474 static char debug_usage[] = 
1475 "Usage: h.323 debug\n"
1476 "       Enables chan_h323 debug output\n";
1477
1478 static char no_debug_usage[] = 
1479 "Usage: h.323 no debug\n"
1480 "       Disables chan_h323 debug output\n";
1481
1482 static char show_codec_usage[] = 
1483 "Usage: h.323 show codec\n"
1484 "       Shows all enabled codecs\n";
1485
1486 static char show_cycle_usage[] = 
1487 "Usage: h.323 gk cycle\n"
1488 "       Manually re-register with the Gatekeper\n";
1489
1490 static char show_hangup_usage[] = 
1491 "Usage: h.323 hangup <token>\n"
1492 "       Manually try to hang up call identified by <token>\n";
1493
1494 static char show_tokens_usage[] = 
1495 "Usage: h.323 show tokens\n"
1496 "       Print out all active call tokens\n";
1497
1498 static struct ast_cli_entry  cli_trace =
1499         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1500 static struct ast_cli_entry  cli_no_trace =
1501         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1502 static struct ast_cli_entry  cli_debug =
1503         { { "h.323", "debug", NULL }, h323_do_debug, "Enable chan_h323 debug", debug_usage };
1504 static struct ast_cli_entry  cli_no_debug =
1505         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable chan_h323 debug", no_debug_usage };
1506 static struct ast_cli_entry  cli_show_codecs =
1507         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1508 static struct ast_cli_entry  cli_gk_cycle =
1509         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1510 static struct ast_cli_entry  cli_hangup_call =
1511         { { "h.323", "hangup", NULL }, h323_ep_hangup, "Show all active call tokens", show_hangup_usage };
1512 static struct ast_cli_entry  cli_show_tokens =
1513         { { "h.323", "show", "tokens", NULL }, h323_tokens_show, "Manually try to hang up a call", show_tokens_usage };
1514
1515
1516
1517 int reload_config(void)
1518 {
1519         
1520         int format;
1521         struct ast_config *cfg;
1522         struct ast_variable *v;
1523         struct oh323_peer *peer   = NULL;
1524         struct oh323_user *user   = NULL;
1525         struct oh323_alias *alias = NULL;
1526         struct ast_hostent ahp; struct hostent *hp;
1527         char *cat;
1528         char *utype;
1529         
1530         cfg = ast_load(config);
1531
1532         /* We *must* have a config file otherwise stop immediately */
1533         if (!cfg) {
1534                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
1535                 return 1;
1536         }
1537         
1538        /* fire up the H.323 Endpoint */       
1539         if (!h323_end_point_exist()) {
1540                h323_end_point_create();        
1541         }
1542         h323debug=0;
1543         dtmfmode = H323_DTMF_RFC2833;
1544
1545         memset(&bindaddr, 0, sizeof(bindaddr));
1546
1547         v = ast_variable_browse(cfg, "general");
1548         while(v) {
1549                 /* Create the interface list */
1550                 if (!strcasecmp(v->name, "port")) {
1551                         port = (int)strtol(v->value, NULL, 10);
1552                 } else if (!strcasecmp(v->name, "bindaddr")) {
1553                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
1554                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1555                         } else {
1556                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1557                         }
1558                 } else if (!strcasecmp(v->name, "allow")) {
1559                         format = ast_getformatbyname(v->value);
1560                         if (format < 1) 
1561                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1562                         else
1563                                 capability |= format;
1564                 } else if (!strcasecmp(v->name, "disallow")) {
1565                         format = ast_getformatbyname(v->value);
1566                         if (format < 1) 
1567                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1568                         else
1569                                 capability &= ~format;
1570                 } else if (!strcasecmp(v->name, "tos")) {
1571                         if (sscanf(v->value, "%i", &format) == 1)
1572                                 tos = format & 0xff;
1573                         else if (!strcasecmp(v->value, "lowdelay"))
1574                                 tos = IPTOS_LOWDELAY;
1575                         else if (!strcasecmp(v->value, "throughput"))
1576                                 tos = IPTOS_THROUGHPUT;
1577                         else if (!strcasecmp(v->value, "reliability"))
1578                                 tos = IPTOS_RELIABILITY;
1579                         else if (!strcasecmp(v->value, "mincost"))
1580                                 tos = IPTOS_MINCOST;
1581                         else if (!strcasecmp(v->value, "none"))
1582                                 tos = 0;
1583                         else
1584                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
1585                 } else if (!strcasecmp(v->name, "gatekeeper")) {
1586                         if (!strcasecmp(v->value, "DISABLE")) {
1587                                 gatekeeper_disable = 1;
1588                                 usingGk = 0;
1589                         } else if (!strcasecmp(v->value, "DISCOVER")) {
1590                                 gatekeeper_disable = 0;
1591                                 gatekeeper_discover = 1;
1592                                 usingGk = 1;
1593                         } else {
1594                                 gatekeeper_disable = 0;
1595                                 usingGk = 1;
1596                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper)-1);
1597                         }
1598                 } else if (!strcasecmp(v->name, "secret")) {
1599                                 strncpy(secret, v->value, sizeof(secret)-1);
1600                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
1601                                 gkroute = ast_true(v->value);
1602                 } else if (!strcasecmp(v->name, "context")) {
1603                         strncpy(default_context, v->value, sizeof(default_context)-1);
1604                         ast_verbose(VERBOSE_PREFIX_3 "  == Setting default context to %s\n", default_context);  
1605                 } else if (!strcasecmp(v->name, "dtmfmode")) {
1606                         if (!strcasecmp(v->value, "inband"))
1607                                 dtmfmode=H323_DTMF_INBAND;
1608                         else if (!strcasecmp(v->value, "rfc2833"))
1609                                 dtmfmode = H323_DTMF_RFC2833;
1610                         else {
1611                                 ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1612                                 dtmfmode = H323_DTMF_RFC2833;
1613                         }
1614                 } else if (!strcasecmp(v->name, "UserByAlias")) {
1615                         userbyalias = ast_true(v->value);
1616                 } else if (!strcasecmp(v->name, "bridge")) {
1617                         bridge_default = ast_true(v->value);
1618                 }
1619                 v = v->next;    
1620         }
1621         
1622         cat = ast_category_browse(cfg, NULL);
1623         while(cat) {
1624                 if (strcasecmp(cat, "general")) {
1625                         utype = ast_variable_retrieve(cfg, cat, "type");
1626                         if (utype) {
1627                                 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
1628                                         user = build_user(cat, ast_variable_browse(cfg, cat));
1629                                         if (user) {
1630                                                 ast_mutex_lock(&userl.lock);
1631                                                 user->next = userl.users;
1632                                                 userl.users = user;
1633                                                 ast_mutex_unlock(&userl.lock);
1634                                         }
1635                                 }  else if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
1636                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
1637                                         if (peer) {
1638                                                 ast_mutex_lock(&peerl.lock);
1639                                                 peer->next = peerl.peers;
1640                                                 peerl.peers = peer;
1641                                                 ast_mutex_unlock(&peerl.lock);
1642                                         }
1643                                 }  else if (!strcasecmp(utype, "h323")) {                       
1644                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
1645                                         if (alias) {
1646                                                 ast_mutex_lock(&aliasl.lock);
1647                                                 alias->next = aliasl.aliases;
1648                                                 aliasl.aliases = alias;
1649                                                 ast_mutex_unlock(&aliasl.lock);
1650                                         }
1651                                 } else {
1652                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
1653                                 }
1654                         } else
1655                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
1656                 }
1657                 cat = ast_category_browse(cfg, cat);
1658         }
1659
1660         /* Register our H.323 aliases if any*/
1661         while (alias) {         
1662                 if (h323_set_alias(alias)) {
1663                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
1664                         return -1;
1665                 }       
1666                 alias = alias->next;
1667         }
1668
1669         /* Add some capabilities */
1670         if(h323_set_capability(capability, dtmfmode)) {
1671                 ast_log(LOG_ERROR, "Capabilities failure, this is bad.\n");
1672                 return -1;
1673         }       
1674         ast_destroy(cfg);
1675
1676         return 0;
1677 }
1678
1679 void delete_users(void)
1680 {
1681         struct oh323_user *user, *userlast;
1682         struct oh323_peer *peer;
1683         
1684         /* Delete all users */
1685         ast_mutex_lock(&userl.lock);
1686         for (user=userl.users;user;) {
1687                 userlast = user;
1688                 user=user->next;
1689                 free(userlast);
1690         }
1691         userl.users=NULL;
1692         ast_mutex_unlock(&userl.lock);
1693         ast_mutex_lock(&peerl.lock);
1694         for (peer=peerl.peers;peer;) {
1695                 /* Assume all will be deleted, and we'll find out for sure later */
1696                 peer->delme = 1;
1697                 peer = peer->next;
1698         }
1699         ast_mutex_unlock(&peerl.lock);
1700 }
1701
1702 void delete_aliases(void)
1703 {
1704         struct oh323_alias *alias, *aliaslast;
1705                 
1706         /* Delete all users */
1707         ast_mutex_lock(&aliasl.lock);
1708         for (alias=aliasl.aliases;alias;) {
1709                 aliaslast = alias;
1710                 alias=alias->next;
1711                 free(aliaslast);
1712         }
1713         aliasl.aliases=NULL;
1714         ast_mutex_unlock(&aliasl.lock);
1715 }
1716
1717 void prune_peers(void)
1718 {
1719         /* Prune peers who still are supposed to be deleted */
1720         struct oh323_peer *peer, *peerlast, *peernext;
1721         ast_mutex_lock(&peerl.lock);
1722         peerlast = NULL;
1723         for (peer=peerl.peers;peer;) {
1724                 peernext = peer->next;
1725                 if (peer->delme) {
1726                         free(peer);
1727                         if (peerlast)
1728                                 peerlast->next = peernext;
1729                         else
1730                                 peerl.peers = peernext;
1731                 } else
1732                         peerlast = peer;
1733                 peer=peernext;
1734         }
1735         ast_mutex_unlock(&peerl.lock);
1736 }
1737
1738 int reload(void)
1739 {
1740         delete_users();
1741         delete_aliases();
1742         prune_peers();
1743
1744 #if 0
1745         if (!ast_strlen_zero(gatekeeper)) {
1746                 h323_gk_urq();
1747         }
1748 #endif
1749
1750         reload_config();
1751
1752 #if 0
1753         /* Possibly register with a GK */
1754         if (gatekeeper_disable == 0) {
1755                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1756                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1757                         h323_end_process();
1758                         return -1;
1759                 }
1760         }
1761 #endif
1762         restart_monitor();
1763         return 0;
1764 }
1765
1766
1767 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
1768 {
1769         struct oh323_pvt *p;
1770         p = chan->pvt->pvt;
1771         if (p && p->rtp && p->bridge) {
1772                 return p->rtp;
1773         }
1774         return NULL;
1775 }
1776
1777 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
1778 {
1779         return NULL;
1780 }
1781
1782 static char *convertcap(int cap)
1783 {
1784         switch (cap) {
1785         case AST_FORMAT_G723_1:
1786                 return "G.723";
1787         case AST_FORMAT_GSM:
1788                 return "GSM";
1789         case AST_FORMAT_ULAW:
1790                 return "ULAW";
1791         case AST_FORMAT_ALAW:
1792                 return "ALAW";
1793         case AST_FORMAT_ADPCM:
1794                 return "G.728";
1795         case AST_FORMAT_G729A:
1796                 return "G.729";
1797         case AST_FORMAT_SPEEX:
1798                 return "SPEEX";
1799         case AST_FORMAT_ILBC:
1800                 return "ILBC";
1801         default:
1802                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
1803                 return NULL;
1804         }
1805
1806 }
1807
1808 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs)
1809 {
1810         /* XXX Deal with Video */
1811         struct oh323_pvt *p;
1812         struct sockaddr_in them;
1813         struct sockaddr_in us;
1814         char *mode;
1815
1816         mode = convertcap(chan->writeformat); 
1817
1818         if (!rtp) {
1819                 return 0;
1820         }
1821
1822         p = chan->pvt->pvt;
1823         if (!p) {
1824                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
1825                 return -1;
1826         }
1827
1828         ast_rtp_get_peer(rtp, &them);   
1829         ast_rtp_get_us(rtp, &us);
1830
1831         h323_native_bridge(p->cd.call_token, inet_ntoa(them.sin_addr), mode);
1832         
1833         return 0;
1834         
1835 }
1836
1837 static struct ast_rtp_protocol oh323_rtp = {
1838         get_rtp_info: oh323_get_rtp_peer,
1839         get_vrtp_info: oh323_get_vrtp_peer,
1840         set_rtp_peer: oh323_set_rtp_peer,
1841 };
1842
1843
1844 int load_module()
1845 {
1846         int res;
1847
1848         res = reload_config();
1849
1850         if (res) {
1851                 return 0;
1852         } else {
1853                 /* Make sure we can register our channel type */
1854                 if (ast_channel_register(type, tdesc, capability, oh323_request)) {
1855                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1856                         h323_end_process();
1857                         return -1;
1858                 }
1859                 ast_cli_register(&cli_debug);
1860                 ast_cli_register(&cli_no_debug);
1861                 ast_cli_register(&cli_trace);
1862                 ast_cli_register(&cli_no_trace);
1863                 ast_cli_register(&cli_show_codecs);
1864                 ast_cli_register(&cli_gk_cycle);
1865                 ast_cli_register(&cli_hangup_call);
1866                 ast_cli_register(&cli_show_tokens);
1867
1868                 oh323_rtp.type = type;
1869                 ast_rtp_proto_register(&oh323_rtp);
1870
1871                 sched = sched_context_create();
1872                 if (!sched) {
1873                         ast_log(LOG_WARNING, "Unable to create schedule context\n");
1874                 }
1875                 io = io_context_create();
1876                 if (!io) {
1877                         ast_log(LOG_WARNING, "Unable to create I/O context\n");
1878                 }
1879                 
1880                 /* Register our callback functions */
1881                 h323_callback_register(setup_incoming_call, 
1882                                        setup_outgoing_call,                                                      
1883                                        create_connection, 
1884                                        setup_rtp_connection, 
1885                                        cleanup_connection, 
1886                                        chan_ringing,
1887                                        connection_made, 
1888                                        send_digit,
1889                                        answer_call);
1890         
1891
1892                 /* start the h.323 listener */
1893                 if (h323_start_listener(port, bindaddr)) {
1894                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
1895                         return -1;
1896                 }
1897
1898                 /* Possibly register with a GK */
1899                 if (gatekeeper_disable == 0) {
1900                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1901                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1902                                 return 0;
1903                         }
1904                 }
1905                 /* And start the monitor for the first time */
1906                 restart_monitor();
1907         }
1908         return res;
1909 }
1910
1911
1912 int unload_module() 
1913 {
1914         struct oh323_pvt *p, *pl;
1915                 
1916         if (!ast_mutex_lock(&iflock)) {
1917         /* hangup all interfaces if they have an owner */
1918         p = iflist;
1919         while(p) {
1920                 if (p->owner)
1921                         ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1922                 p = p->next;
1923         }
1924         iflist = NULL;
1925         ast_mutex_unlock(&iflock);
1926         } else {
1927                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1928                 return -1;
1929         }
1930
1931         if (!ast_mutex_lock(&monlock)) {
1932                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
1933                         pthread_cancel(monitor_thread);
1934                         pthread_kill(monitor_thread, SIGURG);
1935                         pthread_join(monitor_thread, NULL);
1936                  }
1937                 monitor_thread = AST_PTHREADT_STOP;
1938                 ast_mutex_unlock(&monlock);
1939         } else {
1940                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1941                 return -1;
1942         }
1943                 
1944         if (!ast_mutex_lock(&iflock)) {
1945                 /* destroy all the interfaces and free their memory */
1946                 p = iflist;
1947                 while(p) {
1948                         pl = p;
1949                         p = p->next;
1950                         /* free associated memory */
1951                         free(pl);
1952                 }
1953                 iflist = NULL;
1954                 ast_mutex_unlock(&iflock);
1955         } else {
1956                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1957                 return -1;
1958         }
1959         h323_gk_urq();
1960         h323_end_process();
1961
1962         /* unregister rtp */
1963         ast_rtp_proto_unregister(&oh323_rtp);
1964         
1965         /* unregister commands */
1966         ast_cli_unregister(&cli_debug);
1967         ast_cli_unregister(&cli_no_debug);
1968         ast_cli_unregister(&cli_trace);
1969         ast_cli_unregister(&cli_no_trace);   
1970         ast_cli_unregister(&cli_show_codecs);
1971         ast_cli_unregister(&cli_gk_cycle);
1972         ast_cli_unregister(&cli_hangup_call);
1973         ast_cli_unregister(&cli_show_tokens);
1974                         
1975         /* unregister channel type */
1976         ast_channel_unregister(type);
1977
1978         return 0; 
1979
1980
1981 int usecount()
1982 {
1983         int res;
1984         ast_mutex_lock(&usecnt_lock);
1985         res = usecnt;
1986         ast_mutex_unlock(&usecnt_lock);
1987         return res;
1988 }
1989
1990 char *description()
1991 {
1992         return desc;
1993 }
1994
1995 char *key()
1996 {
1997         return ASTERISK_GPL_KEY;
1998 }
1999
2000
2001
2002