f6c9cd5397b4c1b300cb284ec5c70fc509ce7be5
[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  * chan_h323 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 #include <sys/socket.h>
30 #include <sys/signal.h>
31 #include <sys/param.h>
32 #if defined(BSD)
33 #ifndef IPTOS_MINCOST
34 #define IPTOS_MINCOST 0x02
35 #endif
36 #endif
37 #include <arpa/inet.h>
38 #include <net/if.h>
39 #include <netinet/in.h>
40 #include <netinet/in_systm.h>
41 #include <netinet/ip.h>
42 #include <unistd.h>
43 #include <stdlib.h>
44 #include <netdb.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #ifdef __cplusplus
50 extern "C" {
51 #endif   
52 #include "asterisk/lock.h"
53 #include "asterisk/logger.h"
54 #include "asterisk/channel.h"
55 #include "asterisk/config.h"
56 #include "asterisk/module.h"
57 #include "asterisk/pbx.h"
58 #include "asterisk/options.h"
59 #include "asterisk/utils.h"
60 #include "asterisk/lock.h"
61 #include "asterisk/sched.h"
62 #include "asterisk/io.h"
63 #include "asterisk/rtp.h"
64 #include "asterisk/acl.h"
65 #include "asterisk/callerid.h"
66 #include "asterisk/cli.h"
67 #include "asterisk/dsp.h"
68 #include "asterisk/causes.h"
69 #ifdef __cplusplus
70 }
71 #endif
72 #include "h323/chan_h323.h"
73
74 send_digit_cb on_send_digit; 
75 on_rtp_cb on_external_rtp_create; 
76 start_rtp_cb on_start_rtp_channel; 
77 setup_incoming_cb on_incoming_call;
78 setup_outbound_cb on_outgoing_call; 
79 chan_ringing_cb on_chan_ringing;
80 con_established_cb on_connection_established;
81 clear_con_cb on_connection_cleared;
82 answer_call_cb on_answer_call;
83 progress_cb on_progress;
84 rfc2833_cb on_set_rfc2833_payload;
85 hangup_cb on_hangup;
86 setcapabilities_cb on_setcapabilities;
87
88 /* global debug flag */
89 int h323debug;
90
91 /** Variables required by Asterisk */
92 static const char type[] = "H323";
93 static const char desc[] = "The NuFone Network's Open H.323 Channel Driver";
94 static const char tdesc[] = "The NuFone Network's Open H.323 Channel Driver";
95 static const char config[] = "h323.conf";
96 static char default_context[AST_MAX_EXTENSION] = "default";
97 static struct sockaddr_in bindaddr;
98
99 /** H.323 configuration values */
100 static int h323_signalling_port = 1720;
101 static char gatekeeper[100];
102 static int gatekeeper_disable = 1;
103 static int gatekeeper_discover = 0;
104 static int usingGk = 0;
105 static int gkroute = 0;
106 /* Find user by alias (h.323 id) is default, alternative is the incomming call's source IP address*/
107 static int userbyalias = 1;
108 static int tos = 0;
109 static char secret[50];
110 static unsigned int unique = 0;
111
112 static call_options_t global_options;
113
114 /** Private structure of a OpenH323 channel */
115 struct oh323_pvt {
116         ast_mutex_t lock;                                       /* Channel private lock */
117         call_options_t options;                                 /* Options to be used during call setup */
118         int alreadygone;                                        /* Whether or not we've already been destroyed by our peer */
119         int needdestroy;                                        /* if we need to be destroyed */
120         call_details_t cd;                                      /* Call details */
121         struct ast_channel *owner;                              /* Who owns us */
122         struct sockaddr_in sa;                                  /* Our peer */
123         struct sockaddr_in redirip;                             /* Where our RTP should be going if not to us */
124         int nonCodecCapability;                                 /* non-audio capability */
125         int outgoing;                                           /* Outgoing or incoming call? */
126         char exten[AST_MAX_EXTENSION];                          /* Requested extension */
127         char context[AST_MAX_EXTENSION];                        /* Context where to start */
128         char accountcode[256];                                  /* Account code */
129         char cid_num[80];                                       /* Caller*id number, if available */
130         char cid_name[80];                                      /* Caller*id name, if available */
131         char rdnis[80];                                         /* Referring DNIS, if available */
132         int amaflags;                                           /* AMA Flags */
133         struct ast_rtp *rtp;                                    /* RTP Session */
134         struct ast_dsp *vad;                                    /* Used for in-band DTMF detection */
135         int nativeformats;                                      /* Codec formats supported by a channel */
136         int needhangup;                                         /* Send hangup when Asterisk is ready */
137         int hangupcause;                                        /* Hangup cause from OpenH323 layer */
138         struct oh323_pvt *next;                                 /* Next channel in list */
139 } *iflist = NULL;
140
141 static struct ast_user_list {
142         struct oh323_user *users;
143         ast_mutex_t lock;
144 } userl;
145
146 static struct ast_peer_list {
147         struct oh323_peer *peers;
148         ast_mutex_t lock;
149 } peerl;
150
151 static struct ast_alias_list {
152         struct oh323_alias *aliases;
153         ast_mutex_t lock;
154 } aliasl;
155
156 /** Asterisk RTP stuff */
157 static struct sched_context *sched;
158 static struct io_context *io;
159
160 /** Protect the interface list (oh323_pvt) */
161 AST_MUTEX_DEFINE_STATIC(iflock);
162
163 /** Usage counter and associated lock */
164 static int usecnt = 0;
165 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
166
167 /* Protect the monitoring thread, so only one process can kill or start it, and not
168    when it's doing something critical. */
169 AST_MUTEX_DEFINE_STATIC(monlock);
170
171 /* Protect the H.323 capabilities list, to avoid more than one channel to set the capabilities simultaneaously in the h323 stack. */
172 AST_MUTEX_DEFINE_STATIC(caplock);
173
174 /* Protect the reload process */
175 AST_MUTEX_DEFINE_STATIC(h323_reload_lock);
176 static int h323_reloading = 0;
177
178 /* This is the thread for the monitor which checks for input on the channels
179    which are not currently in use.  */
180 static pthread_t monitor_thread = AST_PTHREADT_NULL;
181 static int restart_monitor(void);
182 static int h323_do_reload(void);
183
184 static struct ast_channel *oh323_request(const char *type, int format, void *data, int *cause);
185 static int oh323_digit(struct ast_channel *c, char digit);
186 static int oh323_call(struct ast_channel *c, char *dest, int timeout);
187 static int oh323_hangup(struct ast_channel *c);
188 static int oh323_answer(struct ast_channel *c);
189 static struct ast_frame *oh323_read(struct ast_channel *c);
190 static int oh323_write(struct ast_channel *c, struct ast_frame *frame);
191 static int oh323_indicate(struct ast_channel *c, int condition);
192 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
193
194 static const struct ast_channel_tech oh323_tech = {
195         .type = type,
196         .description = tdesc,
197         .capabilities = AST_FORMAT_ULAW,
198         .properties = AST_CHAN_TP_WANTSJITTER,
199         .requester = oh323_request,
200         .send_digit = oh323_digit,
201         .call = oh323_call,
202         .hangup = oh323_hangup,
203         .answer = oh323_answer,
204         .read = oh323_read,
205         .write = oh323_write,
206         .indicate = oh323_indicate,
207         .fixup = oh323_fixup,
208         /* disable, for now */
209 #if 0
210         .bridge = ast_rtp_bridge,
211 #endif
212 };
213
214 /* Channel and private structures should be already locked */
215 static void __oh323_update_info(struct ast_channel *c, struct oh323_pvt *pvt)
216 {
217         if (c->nativeformats != pvt->nativeformats) {
218                 if (h323debug)
219                         ast_log(LOG_DEBUG, "Preparing %s for new native format\n", c->name);
220                 c->nativeformats = pvt->nativeformats;
221                 ast_set_read_format(c, c->readformat);
222                 ast_set_write_format(c, c->writeformat);
223         }
224         if (pvt->needhangup) {
225                 if (h323debug)
226                         ast_log(LOG_DEBUG, "Process pending hangup for %s\n", c->name);
227                 c->_softhangup |= AST_SOFTHANGUP_DEV;
228                 c->hangupcause = pvt->hangupcause;
229                 ast_queue_hangup(c);
230                 pvt->needhangup = 0;
231         }
232 }
233
234 /* Only channel structure should be locked */
235 static void oh323_update_info(struct ast_channel *c)
236 {
237         struct oh323_pvt *pvt = c->tech_pvt;
238
239         if (pvt) {
240                 ast_mutex_lock(&pvt->lock);
241                 __oh323_update_info(c, pvt);
242                 ast_mutex_unlock(&pvt->lock);
243         }
244 }
245
246 static void cleanup_call_details(call_details_t *cd) 
247 {
248         if (cd->call_token) {
249                 free(cd->call_token);
250                 cd->call_token = NULL;
251         }
252         if (cd->call_source_aliases) {
253                 free(cd->call_source_aliases);
254                 cd->call_source_aliases = NULL;
255         }
256         if (cd->call_dest_alias) {
257                 free(cd->call_dest_alias);
258                 cd->call_dest_alias = NULL;
259         }
260         if (cd->call_source_name) { 
261                 free(cd->call_source_name);
262                 cd->call_source_name = NULL;
263         }
264         if (cd->call_source_e164) {
265                 free(cd->call_source_e164);
266                 cd->call_source_e164 = NULL;
267         }
268         if (cd->call_dest_e164) {
269                 free(cd->call_dest_e164);
270                 cd->call_dest_e164 = NULL;
271         }
272         if (cd->sourceIp) {
273                 free(cd->sourceIp);
274                 cd->sourceIp = NULL;
275         }
276 }
277
278 static void __oh323_destroy(struct oh323_pvt *pvt)
279 {
280         struct oh323_pvt *cur, *prev = NULL;
281         
282         if (pvt->rtp) {
283                 ast_rtp_destroy(pvt->rtp);
284         }
285         
286         /* Free dsp used for in-band DTMF detection */
287         if (pvt->vad) {
288                 ast_dsp_free(pvt->vad);
289         }
290         cleanup_call_details(&pvt->cd);
291
292         /* Unlink us from the owner if we have one */
293         if (pvt->owner) {
294                 ast_mutex_lock(&pvt->owner->lock);
295                 ast_log(LOG_DEBUG, "Detaching from %s\n", pvt->owner->name);
296                 pvt->owner->tech_pvt = NULL;
297                 ast_mutex_unlock(&pvt->owner->lock);
298         }
299         cur = iflist;
300         while(cur) {
301                 if (cur == pvt) {
302                         if (prev)
303                                 prev->next = cur->next;
304                         else
305                                 iflist = cur->next;
306                         break;
307                 }
308                 prev = cur;
309                 cur = cur->next;
310         }
311         if (!cur) {
312                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
313         } else {
314                 ast_mutex_destroy(&pvt->lock);
315                 free(pvt);
316         }
317 }
318
319 static void oh323_destroy(struct oh323_pvt *pvt)
320 {
321         ast_mutex_lock(&iflock);
322         __oh323_destroy(pvt);
323         ast_mutex_unlock(&iflock);
324 }
325
326 /**
327  * Send (play) the specified digit to the channel.
328  * 
329  */
330 static int oh323_digit(struct ast_channel *c, char digit)
331 {
332         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
333         char *token;
334         if (h323debug)
335                 ast_log(LOG_DEBUG, "Sending digit %c on %s\n", digit, c->name);
336         if (!pvt)
337                 return -1;
338         ast_mutex_lock(&pvt->lock);
339         if (pvt->rtp && (pvt->options.dtmfmode & H323_DTMF_RFC2833)) {
340                 ast_rtp_senddigit(pvt->rtp, digit);
341         }
342         /* If in-band DTMF is desired, send that */
343         if ((pvt->options.dtmfmode & H323_DTMF_INBAND)) {
344                 token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
345                 ast_mutex_unlock(&pvt->lock);
346                 h323_send_tone(token, digit);
347                 if (token)
348                         free(token);
349                 oh323_update_info(c);
350         }
351         else
352                 ast_mutex_unlock(&pvt->lock);
353         return 0;
354 }
355
356 /**
357  * Make a call over the specified channel to the specified 
358  * destination.
359  * Returns -1 on error, 0 on success.
360  */
361 static int oh323_call(struct ast_channel *c, char *dest, int timeout)
362 {  
363         int res = 0;
364         struct oh323_pvt *pvt = (struct oh323_pvt *)c->tech_pvt;
365         char addr[INET_ADDRSTRLEN];
366         char called_addr[1024];
367
368         if (h323debug) {
369                 ast_log(LOG_DEBUG, "Calling to %s on %s\n", dest, c->name);
370         }
371         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
372                 ast_log(LOG_WARNING, "Line is already in use (%s)\n", c->name);
373                 return -1;
374         }
375         ast_mutex_lock(&pvt->lock);
376         if (usingGk) {
377                 if (ast_strlen_zero(pvt->exten)) {
378                         strncpy(called_addr, dest, sizeof(called_addr));
379                 } else {
380                         snprintf(called_addr, sizeof(called_addr), "%s@%s", pvt->exten, dest);
381                 }
382         } else {
383                 ast_inet_ntoa(addr, sizeof(addr), pvt->sa.sin_addr);
384                 res = htons(pvt->sa.sin_port);
385                 if (ast_strlen_zero(pvt->exten)) {
386                         snprintf(called_addr, sizeof(called_addr), "%s:%d", addr, res);
387                 } else {
388                         snprintf(called_addr, sizeof(called_addr), "%s@%s:%d", pvt->exten, addr, res);
389                 }
390         }
391         /* make sure null terminated */
392         called_addr[sizeof(called_addr) - 1] = '\0'; 
393
394         if (c->cid.cid_num) {
395                 strncpy(pvt->options.cid_num, c->cid.cid_num, sizeof(pvt->options.cid_num));
396         }
397         if (c->cid.cid_name) {
398                 strncpy(pvt->options.cid_name, c->cid.cid_name, sizeof(pvt->options.cid_name));
399         }
400
401         /* indicate that this is an outgoing call */
402         pvt->outgoing = 1;
403
404         ast_log(LOG_DEBUG, "Placing outgoing call to %s, %d\n", called_addr, pvt->options.dtmfcodec);
405         ast_mutex_unlock(&pvt->lock);
406         res = h323_make_call(called_addr, &(pvt->cd), &pvt->options);
407         if (res) {
408                 ast_log(LOG_NOTICE, "h323_make_call failed(%s)\n", c->name);
409                 return -1;
410         }
411         oh323_update_info(c);
412         return 0;
413 }
414
415 static int oh323_answer(struct ast_channel *c)
416 {
417         int res;
418         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
419         char *token;
420
421         if (h323debug)
422                 ast_log(LOG_DEBUG, "Answering on %s\n", c->name);
423
424         ast_mutex_lock(&pvt->lock);
425         token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
426         ast_mutex_unlock(&pvt->lock);
427         res = h323_answering_call(token, 0);
428         if (token)
429                 free(token);
430
431         oh323_update_info(c);
432         if (c->_state != AST_STATE_UP) {
433                 ast_setstate(c, AST_STATE_UP);
434         }
435         return res;
436 }
437
438 static int oh323_hangup(struct ast_channel *c)
439 {
440         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
441         int needcancel = 0;
442         int q931cause = AST_CAUSE_NORMAL_CLEARING;
443         char *call_token;
444
445
446         if (h323debug)
447                 ast_log(LOG_DEBUG, "Hanging up call %s\n", c->name);
448
449         if (!c->tech_pvt) {
450                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
451                 return 0;
452         }
453         ast_mutex_lock(&pvt->lock);
454         /* Determine how to disconnect */
455         if (pvt->owner != c) {
456                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
457                 ast_mutex_unlock(&pvt->lock);
458                 return 0;
459         }
460         if (!c || (c->_state != AST_STATE_UP)) {
461                 needcancel = 1;
462         }
463         
464         pvt->owner = NULL;
465         c->tech_pvt = NULL;
466
467         if (c->hangupcause) {
468                 q931cause = c->hangupcause;
469         } else {
470                 char *cause = pbx_builtin_getvar_helper(c, "DIALSTATUS");
471                 if (cause) {
472                         if (!strcmp(cause, "CONGESTION")) {
473                                 q931cause = AST_CAUSE_NORMAL_CIRCUIT_CONGESTION;
474                         } else if (!strcmp(cause, "BUSY")) {
475                                 q931cause = AST_CAUSE_USER_BUSY;
476                         } else if (!strcmp(cause, "CHANISUNVAIL")) {
477                                 q931cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL;
478                         } else if (!strcmp(cause, "NOANSWER")) {
479                                 q931cause = AST_CAUSE_NO_ANSWER;
480                         } else if (!strcmp(cause, "CANCEL")) {
481                                 q931cause = AST_CAUSE_CALL_REJECTED;
482                         }
483                 }
484         }
485
486         /* Start the process if it's not already started */
487         if (!pvt->alreadygone && !pvt->hangupcause) {
488                 call_token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
489                 if (call_token) {
490                         /* Release lock to eliminate deadlock */
491                         ast_mutex_unlock(&pvt->lock);
492                         if (h323_clear_call(call_token, q931cause)) { 
493                                 ast_log(LOG_DEBUG, "ClearCall failed.\n");
494                         }
495                         free(call_token);
496                         ast_mutex_lock(&pvt->lock);
497                 }
498         } 
499         pvt->needdestroy = 1;
500
501         /* Update usage counter */
502         ast_mutex_lock(&usecnt_lock);
503         usecnt--;
504         if (usecnt < 0) {
505                 ast_log(LOG_WARNING, "Usecnt < 0\n");
506         }
507         ast_mutex_unlock(&usecnt_lock);
508         ast_mutex_unlock(&pvt->lock);
509         ast_update_use_count();
510         return 0;
511 }
512
513 static struct ast_frame *oh323_rtp_read(struct oh323_pvt *pvt)
514 {
515         /* Retrieve audio/etc from channel.  Assumes pvt->lock is already held. */
516         struct ast_frame *f;
517         static struct ast_frame null_frame = { AST_FRAME_NULL, };
518
519         /* Only apply it for the first packet, we just need the correct ip/port */
520         if (pvt->options.nat) {
521                 ast_rtp_setnat(pvt->rtp, pvt->options.nat);
522                 pvt->options.nat = 0;
523         }
524
525         f = ast_rtp_read(pvt->rtp);
526         /* Don't send RFC2833 if we're not supposed to */
527         if (f && (f->frametype == AST_FRAME_DTMF) && !(pvt->options.dtmfmode & H323_DTMF_RFC2833)) {
528                 return &null_frame;
529         }
530         if (pvt->owner) {
531                 /* We already hold the channel lock */
532                 if (f->frametype == AST_FRAME_VOICE) {
533                         if (f->subclass != pvt->owner->nativeformats) {
534                                 /* Try to avoid deadlock */
535                                 if (ast_mutex_trylock(&pvt->owner->lock)) {
536                                         ast_log(LOG_NOTICE, "Format changed but channel is locked. Ignoring frame...\n");
537                                         return &null_frame;
538                                 }
539                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
540                                 pvt->owner->nativeformats = f->subclass;
541                                 pvt->nativeformats = f->subclass;
542                                 ast_set_read_format(pvt->owner, pvt->owner->readformat);
543                                 ast_set_write_format(pvt->owner, pvt->owner->writeformat);
544                                 ast_mutex_unlock(&pvt->owner->lock);
545                         }       
546                         /* Do in-band DTMF detection */
547                         if ((pvt->options.dtmfmode & H323_DTMF_INBAND) && pvt->vad) {
548                                 f = ast_dsp_process(pvt->owner,pvt->vad,f);
549                                 if (f &&(f->frametype == AST_FRAME_DTMF)) {
550                                         ast_log(LOG_DEBUG, "Received in-band digit %c.\n", f->subclass);
551                                 }
552                         }
553                         
554                 }
555         }
556         return f;
557 }
558
559 static struct ast_frame  *oh323_read(struct ast_channel *c)
560 {
561         struct ast_frame *fr;
562         struct oh323_pvt *pvt = (struct oh323_pvt *)c->tech_pvt;
563         ast_mutex_lock(&pvt->lock);
564         __oh323_update_info(c, pvt);
565         fr = oh323_rtp_read(pvt);
566         ast_mutex_unlock(&pvt->lock);
567         return fr;
568 }
569
570 static int oh323_write(struct ast_channel *c, struct ast_frame *frame)
571 {
572         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
573         int res = 0;
574         if (frame->frametype != AST_FRAME_VOICE) {
575                 if (frame->frametype == AST_FRAME_IMAGE) {
576                         return 0;
577                 } else {
578                         ast_log(LOG_WARNING, "Can't send %d type frames with H323 write\n", frame->frametype);
579                         return 0;
580                 }
581         } else {
582                 if (!(frame->subclass & c->nativeformats)) {
583                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
584                                 frame->subclass, c->nativeformats, c->readformat, c->writeformat);
585                         return 0;
586                 }
587         }
588         if (pvt) {
589                 ast_mutex_lock(&pvt->lock);
590                 if (pvt->rtp) {
591                         res =  ast_rtp_write(pvt->rtp, frame);
592                 }
593                 ast_mutex_unlock(&pvt->lock);
594         }
595         return res;
596 }
597
598 static int oh323_indicate(struct ast_channel *c, int condition)
599 {
600
601         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
602         char *token = (char *)NULL;
603
604         ast_mutex_lock(&pvt->lock);
605         token = (pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL);
606         ast_mutex_unlock(&pvt->lock);
607
608         if (h323debug)
609                 ast_log(LOG_DEBUG, "OH323: Indicating %d on %s\n", condition, token);
610
611         switch(condition) {
612         case AST_CONTROL_RINGING:
613                 if (c->_state == AST_STATE_RING || c->_state == AST_STATE_RINGING) {
614                         h323_send_alerting(token);
615                         break;
616                 }
617                 if (token)
618                         free(token);
619                 return -1;
620         case AST_CONTROL_PROGRESS:
621                 if (c->_state != AST_STATE_UP) {
622                         h323_send_progress(token);
623                         break;
624                 }
625                 if (token)
626                         free(token);
627                 return -1;
628
629         case AST_CONTROL_BUSY:
630                 if (c->_state != AST_STATE_UP) {
631                         h323_answering_call(token, 1);
632                         ast_mutex_lock(&pvt->lock);
633                         pvt->alreadygone = 1;
634                         ast_mutex_unlock(&pvt->lock);
635                         ast_softhangup_nolock(c, AST_SOFTHANGUP_DEV);                   
636                         break;
637                 }
638                 if (token)
639                         free(token);
640                 return -1;
641         case AST_CONTROL_CONGESTION:
642                 if (c->_state != AST_STATE_UP) {
643                         h323_answering_call(token, 1);
644                         ast_mutex_lock(&pvt->lock);
645                         pvt->alreadygone = 1;
646                         ast_mutex_unlock(&pvt->lock);
647                         ast_softhangup_nolock(c, AST_SOFTHANGUP_DEV);
648                         break;
649                 }
650                 if (token)
651                         free(token);
652                 return -1;
653         case AST_CONTROL_PROCEEDING:
654         case -1:
655                 if (token)
656                         free(token);
657                 return -1;
658         default:
659                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d on %s\n", condition, token);
660                 if (token)
661                         free(token);
662                 return -1;
663         }
664
665         if (h323debug)
666                 ast_log(LOG_DEBUG, "OH323: Indicated %d on %s\n", condition, token);
667         if (token)
668                 free(token);
669         oh323_update_info(c);
670
671         return -1;
672 }
673
674 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
675 {
676         struct oh323_pvt *pvt = (struct oh323_pvt *) newchan->tech_pvt;
677
678         ast_mutex_lock(&pvt->lock);
679         if (pvt->owner != oldchan) {
680                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, pvt->owner);
681                 return -1;
682         }
683         pvt->owner = newchan;
684         ast_mutex_unlock(&pvt->lock);
685         return 0;
686 }
687
688 /* Private structure should be locked on a call */
689 static struct ast_channel *__oh323_new(struct oh323_pvt *pvt, int state, const char *host)
690 {
691         struct ast_channel *ch;
692         int fmt;
693         
694         /* Don't hold a oh323_pvt lock while we allocate a chanel */
695         ast_mutex_unlock(&pvt->lock);
696         ch = ast_channel_alloc(1);
697         /* Update usage counter */
698         ast_mutex_lock(&usecnt_lock);
699         usecnt++;
700         ast_mutex_unlock(&usecnt_lock);
701         ast_update_use_count();
702         ast_mutex_lock(&pvt->lock);
703         if (ch) {
704                 ch->tech = &oh323_tech;
705                 snprintf(ch->name, sizeof(ch->name), "H323/%s", host);
706                 ch->nativeformats = pvt->options.capability;
707                 if (!ch->nativeformats) {
708                         ch->nativeformats = global_options.capability;
709                 }
710                 pvt->nativeformats = ch->nativeformats;
711                 fmt = ast_best_codec(ch->nativeformats);
712                 ch->type = type;
713                 ch->fds[0] = ast_rtp_fd(pvt->rtp);
714                 if (state == AST_STATE_RING) {
715                         ch->rings = 1;
716                 }
717                 ch->writeformat = fmt;
718                 ch->rawwriteformat = fmt;
719                 ch->readformat = fmt;
720                 ch->rawreadformat = fmt;
721                 /* Allocate dsp for in-band DTMF support */
722                 if (pvt->options.dtmfmode & H323_DTMF_INBAND) {
723                         pvt->vad = ast_dsp_new();
724                         ast_dsp_set_features(pvt->vad, DSP_FEATURE_DTMF_DETECT);
725                 }
726                 /* Register channel functions. */
727                 ch->tech_pvt = pvt;
728                 /*  Set the owner of this channel */
729                 pvt->owner = ch;
730                 
731                 strncpy(ch->context, pvt->context, sizeof(ch->context) - 1);
732                 strncpy(ch->exten, pvt->exten, sizeof(ch->exten) - 1);          
733                 ch->priority = 1;
734                 if (!ast_strlen_zero(pvt->accountcode)) {
735                         strncpy(ch->accountcode, pvt->accountcode, sizeof(ch->accountcode) - 1);
736                 }
737                 if (pvt->amaflags) {
738                         ch->amaflags = pvt->amaflags;
739                 }
740                 if (!ast_strlen_zero(pvt->cid_num)) {
741                         ch->cid.cid_num = strdup(pvt->cid_num);
742                 } else if (pvt->cd.call_source_e164 && !ast_strlen_zero(pvt->cd.call_source_e164)) {
743                         ch->cid.cid_num = strdup(pvt->cd.call_source_e164);
744                 }
745                 if (!ast_strlen_zero(pvt->cid_name)) {
746                         ch->cid.cid_name = strdup(pvt->cid_name);
747                 } else if (pvt->cd.call_source_e164 && !ast_strlen_zero(pvt->cd.call_source_name)) {
748                         ch->cid.cid_name = strdup(pvt->cd.call_source_name);
749                 }
750                 if (!ast_strlen_zero(pvt->rdnis)) {
751                         ch->cid.cid_rdnis = strdup(pvt->rdnis);
752                 }
753                 if (!ast_strlen_zero(pvt->exten) && strcmp(pvt->exten, "s")) {
754                         ch->cid.cid_dnid = strdup(pvt->exten);
755                 }
756                 ast_setstate(ch, state);
757                 if (state != AST_STATE_DOWN) {
758                         if (ast_pbx_start(ch)) {
759                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ch->name);
760                                 ast_hangup(ch);
761                                 ch = NULL;
762                         }
763                 }
764         } else  {
765                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
766         }
767         return ch;
768 }
769
770 static struct oh323_pvt *oh323_alloc(int callid)
771 {
772         struct oh323_pvt *pvt;
773
774         pvt = (struct oh323_pvt *) malloc(sizeof(struct oh323_pvt));
775         if (!pvt) {
776                 ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
777                 return NULL;
778         }
779         memset(pvt, 0, sizeof(struct oh323_pvt));
780         pvt->rtp = ast_rtp_new(sched, io, 1, 0);
781         if (!pvt->rtp) {
782                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
783                 free(pvt);
784                 return NULL;
785         }
786         ast_rtp_settos(pvt->rtp, tos);
787         ast_mutex_init(&pvt->lock);
788         /* Ensure the call token is allocated */
789         if ((pvt->cd).call_token == NULL) {
790                 (pvt->cd).call_token = (char *)malloc(128);
791         }
792         if (!pvt->cd.call_token) {
793                 ast_log(LOG_ERROR, "Not enough memory to alocate call token\n");
794                 return NULL;
795         }
796         memset((char *)(pvt->cd).call_token, 0, 128);
797         pvt->cd.call_reference = callid;
798         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
799         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
800                 pvt->nonCodecCapability |= AST_RTP_DTMF;
801         } else {
802                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
803         }
804         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
805         /* Add to interface list */
806         ast_mutex_lock(&iflock);
807         pvt->next = iflist;
808         iflist = pvt;
809         ast_mutex_unlock(&iflock);
810         return pvt;
811 }
812
813 static struct oh323_pvt *find_call_locked(int call_reference, const char *token)
814 {  
815         struct oh323_pvt *pvt;
816
817         ast_mutex_lock(&iflock);
818         pvt = iflist; 
819         while(pvt) {
820                 if (!pvt->needdestroy && ((signed int)pvt->cd.call_reference == call_reference)) {
821                         /* Found the call */             
822                         if ((token != NULL) && (!strcmp(pvt->cd.call_token, token))) {
823                                 ast_mutex_lock(&pvt->lock);
824                                 ast_mutex_unlock(&iflock);
825                                 return pvt;
826                         } else if (token == NULL) {
827                                 ast_log(LOG_WARNING, "Call Token is NULL\n");
828                                 ast_mutex_lock(&pvt->lock);
829                                 ast_mutex_unlock(&iflock);
830                                 return pvt;
831                         }
832                 }
833                 pvt = pvt->next; 
834         }
835         ast_mutex_unlock(&iflock);
836         return NULL;
837 }
838
839 struct oh323_user *find_user(const call_details_t *cd)
840 {
841         struct oh323_user *u;
842         char iabuf[INET_ADDRSTRLEN];
843         u = userl.users;
844         if (userbyalias) {
845                 while(u) {
846                         if (!strcasecmp(u->name, cd->call_source_aliases)) {
847                                 break;
848                         }
849                         u = u->next;
850                 }
851         } else {
852                 while(u) {
853                         if (!strcasecmp(cd->sourceIp, ast_inet_ntoa(iabuf, sizeof(iabuf), u->addr.sin_addr))) {
854                                 break;
855                         }
856                         u = u->next;
857                 }
858         }
859         return u;
860 }
861
862 struct oh323_peer *find_peer(const char *peer, struct sockaddr_in *sin)
863 {
864         struct oh323_peer *p = NULL;
865         static char iabuf[INET_ADDRSTRLEN];
866
867         p = peerl.peers;
868         if (peer) {
869                 while(p) {
870                         if (!strcasecmp(p->name, peer)) {
871                                 ast_log(LOG_DEBUG, "Found peer %s by name\n", peer);
872                                 break;
873                         }
874                         p = p->next;
875                 }
876         } else {
877                 /* find by sin */
878                 if (sin) {
879                         while (p) {
880                                 if ((!inaddrcmp(&p->addr, sin)) || 
881                                         (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
882                                         ast_log(LOG_DEBUG, "Found peer %s/%s by addr\n", peer, ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr));
883                                         break;
884                                 }
885                                 p = p->next;
886                         }
887                 }       
888         }
889         if (!p) {
890                 ast_log(LOG_DEBUG, "Could not find peer %s by name or address\n", peer);
891         }
892         return p;
893 }
894
895 static int create_addr(struct oh323_pvt *pvt, char *opeer)
896 {
897         struct hostent *hp;
898         struct ast_hostent ahp;
899         struct oh323_peer *p;
900         int portno;
901         int found = 0;
902         char *port;
903         char *hostn;
904         char peer[256] = "";
905
906         strncpy(peer, opeer, sizeof(peer) - 1);
907         port = strchr(peer, ':');
908         if (port) {
909                 *port = '\0';
910                 port++;
911         }
912         pvt->sa.sin_family = AF_INET;
913         ast_mutex_lock(&peerl.lock);
914         p = find_peer(peer, NULL);
915         if (p) {
916                 found++;
917                 memcpy(&pvt->options, &p->options, sizeof(pvt->options));
918                 if (pvt->rtp) {
919                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", pvt->options.nat);
920                         ast_rtp_setnat(pvt->rtp, pvt->options.nat);
921                 }
922                 if (pvt->options.dtmfmode) {
923                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
924                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
925                         } else {
926                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
927                         }
928                 }
929                 if (p->addr.sin_addr.s_addr) {
930                         pvt->sa.sin_addr = p->addr.sin_addr;    
931                         pvt->sa.sin_port = p->addr.sin_port;    
932                 } 
933         }
934         ast_mutex_unlock(&peerl.lock);
935         if (!p && !found) {
936                 hostn = peer;
937                 if (port) {
938                         portno = atoi(port);
939                 } else {
940                         portno = h323_signalling_port;
941                 }               
942                 hp = ast_gethostbyname(hostn, &ahp);
943                 if (hp) {
944                         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
945                         memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
946                         pvt->sa.sin_port = htons(portno);
947                         return 0;       
948                 } else {
949                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
950                         return -1;
951                 }
952         } else if (!p) {
953                 return -1;
954         } else {        
955                 return 0;
956         }
957 }
958 static struct ast_channel *oh323_request(const char *type, int format, void *data, int *cause)
959 {
960         int oldformat;
961         struct oh323_pvt *pvt;
962         struct ast_channel *tmpc = NULL;
963         char *dest = (char *)data;
964         char *ext, *host;
965         char *h323id = NULL;
966         char tmp[256], tmp1[256];
967         
968         ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
969         pvt = oh323_alloc(0);
970         if (!pvt) {
971                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
972                 return NULL;
973         }       
974         oldformat = format;
975         format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
976         if (!format) {
977                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
978                 return NULL;
979         }
980         strncpy(tmp, dest, sizeof(tmp) - 1);    
981         host = strchr(tmp, '@');
982         if (host) {
983                 *host = '\0';
984                 host++;
985                 ext = tmp;
986         } else {
987                 host = tmp;
988                 ext = NULL;
989         }
990         strtok_r(host, "/", &(h323id));         
991         if (h323id && !ast_strlen_zero(h323id)) {
992                 h323_set_id(h323id);
993         }
994         if (ext) {
995                 strncpy(pvt->exten, ext, sizeof(pvt->exten) - 1);
996         }
997         ast_log(LOG_DEBUG, "Extension: %s Host: %s\n",  pvt->exten, host);
998         if (!usingGk) {
999                 if (create_addr(pvt, host)) {
1000                         oh323_destroy(pvt);
1001                         return NULL;
1002                 }
1003         }
1004         else {
1005                 memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1006                 if (pvt->rtp) {
1007                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", pvt->options.nat);
1008                         ast_rtp_setnat(pvt->rtp, pvt->options.nat);
1009                 }
1010                 if (pvt->options.dtmfmode) {
1011                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1012                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1013                         } else {
1014                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1015                         }
1016                 }
1017         }
1018
1019         ast_mutex_lock(&caplock);
1020         /* Generate unique channel identifier */
1021         snprintf(tmp1, sizeof(tmp1)-1, "%s-%u", host, ++unique);
1022         tmp1[sizeof(tmp1)-1] = '\0';
1023         ast_mutex_unlock(&caplock);
1024
1025         ast_mutex_lock(&pvt->lock);
1026         tmpc = __oh323_new(pvt, AST_STATE_DOWN, tmp1);
1027         ast_mutex_unlock(&pvt->lock);
1028         if (!tmpc) {
1029                 oh323_destroy(pvt);
1030         }
1031         ast_update_use_count();
1032         restart_monitor();
1033         return tmpc;
1034 }
1035
1036 /** Find a call by alias */
1037 struct oh323_alias *find_alias(const char *source_aliases)
1038 {
1039         struct oh323_alias *a;
1040
1041         a = aliasl.aliases;
1042         while(a) {
1043                 if (!strcasecmp(a->name, source_aliases)) {
1044                         break;
1045                 }
1046                 a = a->next;
1047         }
1048         return a;
1049 }
1050
1051 /**
1052   * Callback for sending digits from H.323 up to asterisk
1053   *
1054   */
1055 int send_digit(unsigned call_reference, char digit, const char *token)
1056 {
1057         struct oh323_pvt *pvt;
1058         struct ast_frame f;
1059         int res;
1060
1061         ast_log(LOG_DEBUG, "Received Digit: %c\n", digit);
1062         pvt = find_call_locked(call_reference, token); 
1063         if (!pvt) {
1064                 ast_log(LOG_ERROR, "Private structure not found in send_digit.\n");
1065                 return -1;
1066         }
1067         memset(&f, 0, sizeof(f));
1068         f.frametype = AST_FRAME_DTMF;
1069         f.subclass = digit;
1070         f.datalen = 0;
1071         f.samples = 800;
1072         f.offset = 0;
1073         f.data = NULL;
1074         f.mallocd = 0;
1075         f.src = "SEND_DIGIT";   
1076         res = ast_queue_frame(pvt->owner, &f);
1077         ast_mutex_unlock(&pvt->lock);
1078         return res;
1079 }
1080
1081 /**
1082   * Callback function used to inform the H.323 stack of the local rtp ip/port details
1083   *
1084   * Returns the local RTP information
1085   */
1086 struct rtp_info *external_rtp_create(unsigned call_reference, const char * token)
1087 {       
1088         struct oh323_pvt *pvt;
1089         struct sockaddr_in us;
1090         struct rtp_info *info;
1091
1092         info = (struct rtp_info *)malloc(sizeof(struct rtp_info));
1093         if (!info) {
1094                 ast_log(LOG_ERROR, "Unable to allocated info structure, this is very bad\n");
1095                 return NULL;
1096         }
1097         pvt = find_call_locked(call_reference, token); 
1098         if (!pvt) {
1099                 free(info);
1100                 ast_log(LOG_ERROR, "Unable to find call %s(%d)\n", token, call_reference);
1101                 return NULL;
1102         }
1103         /* figure out our local RTP port and tell the H.323 stack about it */
1104         ast_rtp_get_us(pvt->rtp, &us);
1105         ast_mutex_unlock(&pvt->lock);
1106         /* evil hack, until I (or someone?) figures out a better way */
1107         ast_inet_ntoa(info->addr, sizeof(info->addr), bindaddr.sin_addr);
1108         info->port = ntohs(us.sin_port);
1109         if (h323debug)
1110                 ast_log(LOG_DEBUG, "Sending RTP 'US' %s:%d\n", info->addr, info->port);
1111         return info;
1112 }
1113
1114 int progress(unsigned call_reference, const char *token, int inband);
1115
1116 /**
1117  * Definition taken from rtp.c for rtpPayloadType because we need it here.
1118  */
1119 struct rtpPayloadType {
1120         int isAstFormat;        /* whether the following code is an AST_FORMAT */
1121         int code;
1122 };
1123
1124 /**
1125   * Call-back function passing remote ip/port information from H.323 to asterisk 
1126   *
1127   * Returns nothing 
1128   */
1129 void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort, const char *token, int pt)
1130 {
1131         struct oh323_pvt *pvt;
1132         struct sockaddr_in them;
1133         struct rtpPayloadType rtptype;
1134
1135         if (h323debug)
1136                 ast_log(LOG_DEBUG, "Setting up RTP connection for %s\n", token);
1137
1138         /* Find the call or allocate a private structure if call not found */
1139         pvt = find_call_locked(call_reference, token); 
1140         if (!pvt) {
1141                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1142                 return;
1143         }
1144         if (pvt->alreadygone) {
1145                 ast_mutex_unlock(&pvt->lock);
1146                 return;
1147         }
1148         rtptype = ast_rtp_lookup_pt(pvt->rtp, pt);
1149         pvt->nativeformats = rtptype.code;
1150         if (pvt->owner && !ast_mutex_trylock(&pvt->owner->lock)) {
1151                 pvt->owner->nativeformats = pvt->nativeformats;
1152                 ast_set_read_format(pvt->owner, pvt->owner->readformat);
1153                 ast_set_write_format(pvt->owner, pvt->owner->writeformat);
1154                 ast_mutex_unlock(&pvt->owner->lock);
1155         }
1156         else if (h323debug)
1157                 ast_log(LOG_DEBUG, "RTP connection preparation for %s is pending...\n", token);
1158
1159         them.sin_family = AF_INET;
1160         /* only works for IPv4 */
1161         them.sin_addr.s_addr = inet_addr(remoteIp); 
1162         them.sin_port = htons(remotePort);
1163         ast_rtp_set_peer(pvt->rtp, &them);
1164
1165         if (pvt->options.progress_audio) {
1166                 ast_mutex_unlock(&pvt->lock);
1167                 progress(call_reference, token, 1);
1168         } else
1169                 ast_mutex_unlock(&pvt->lock);
1170
1171         if (h323debug)
1172                 ast_log(LOG_DEBUG, "RTP connection prepared for %s\n", token);
1173
1174         return;
1175 }
1176
1177 /**  
1178   *     Call-back function to signal asterisk that the channel has been answered 
1179   * Returns nothing
1180   */
1181 void connection_made(unsigned call_reference, const char *token)
1182 {
1183         struct ast_channel *c = NULL;
1184         struct oh323_pvt *pvt;
1185
1186         if (h323debug)
1187                 ast_log(LOG_DEBUG, "Call %s answered\n", token);
1188
1189         pvt = find_call_locked(call_reference, token); 
1190         if (!pvt) {
1191                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1192                 return;
1193         }
1194
1195         /* Inform asterisk about remote party connected only on outgoing calls */
1196         if (!pvt->outgoing) {
1197                 ast_mutex_unlock(&pvt->lock);
1198                 return;
1199         }
1200         if (!pvt->owner) {
1201                 ast_mutex_unlock(&pvt->lock);
1202                 ast_log(LOG_ERROR, "Channel has no owner\n");
1203                 return;
1204         }
1205         ast_mutex_lock(&pvt->owner->lock);
1206         c = pvt->owner; 
1207         ast_setstate(c, AST_STATE_UP);
1208         ast_queue_control(c, AST_CONTROL_ANSWER);
1209         ast_mutex_unlock(&pvt->owner->lock);
1210         ast_mutex_unlock(&pvt->lock);
1211         return;
1212 }
1213
1214 int progress(unsigned call_reference, const char *token, int inband)
1215 {
1216         struct oh323_pvt *pvt;
1217
1218         ast_log(LOG_DEBUG, "Received ALERT/PROGRESS message for %s tones\n", (inband ? "inband" : "self-generated"));
1219
1220         pvt = find_call_locked(call_reference, token);
1221         if (!pvt) {
1222                 ast_log(LOG_ERROR, "Private structure not found in progress.\n");
1223                 return -1;
1224         }
1225         if (!pvt->owner) {
1226                 ast_mutex_unlock(&pvt->lock);
1227                 ast_log(LOG_ERROR, "No Asterisk channel associated with private structure.\n");
1228                 return -1;
1229         }
1230         ast_mutex_lock(&pvt->owner->lock);
1231         ast_queue_control(pvt->owner, (inband ? AST_CONTROL_PROGRESS : AST_CONTROL_RINGING));
1232         ast_mutex_unlock(&pvt->owner->lock);
1233         ast_mutex_unlock(&pvt->lock);
1234
1235         return 0;
1236 }
1237
1238 /**
1239  *  Call-back function for incoming calls
1240  *
1241  *  Returns 1 on success
1242  */
1243 call_options_t *setup_incoming_call(call_details_t *cd)
1244 {
1245         struct oh323_pvt *pvt;
1246         struct oh323_user *user = NULL;
1247         struct oh323_alias *alias = NULL;
1248         char iabuf[INET_ADDRSTRLEN];
1249
1250         if (h323debug)
1251                 ast_log(LOG_DEBUG, "Setting up incoming call for %s\n", cd->call_token);
1252
1253         /* allocate the call*/
1254         pvt = oh323_alloc(cd->call_reference);
1255
1256         if (!pvt) {
1257                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
1258                 return NULL;
1259         }
1260
1261         /* Populate the call details in the private structure */
1262         memcpy(&pvt->cd, cd, sizeof(pvt->cd));
1263         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1264
1265         if (h323debug) {
1266                 ast_verbose(VERBOSE_PREFIX_3 "Setting up Call\n");
1267                 ast_verbose(VERBOSE_PREFIX_3 "\tCall token:  [%s]\n", pvt->cd.call_token);
1268                 ast_verbose(VERBOSE_PREFIX_3 "\tCalling party name:  [%s]\n", pvt->cd.call_source_name);
1269                 ast_verbose(VERBOSE_PREFIX_3 "\tCalling party number:  [%s]\n", pvt->cd.call_source_e164);
1270                 ast_verbose(VERBOSE_PREFIX_3 "\tCalled party name:  [%s]\n", pvt->cd.call_dest_alias);
1271                 ast_verbose(VERBOSE_PREFIX_3 "\tCalled party number:  [%s]\n", pvt->cd.call_dest_e164);
1272         }
1273
1274         /* Decide if we are allowing Gatekeeper routed calls*/
1275         if ((!strcasecmp(cd->sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk)) {
1276                 if (!ast_strlen_zero(cd->call_dest_e164)) {
1277                         strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
1278                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1); 
1279                 } else {
1280                         alias = find_alias(cd->call_dest_alias);
1281                         if (!alias) {
1282                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd->call_dest_alias);
1283                                 return NULL;
1284                         }
1285                         strncpy(pvt->exten, alias->name, sizeof(pvt->exten) - 1);
1286                         strncpy(pvt->context, alias->context, sizeof(pvt->context) - 1);
1287                 }
1288         } else {
1289                 /* Either this call is not from the Gatekeeper 
1290                    or we are not allowing gk routed calls */
1291                 user  = find_user(cd);
1292                 if (!user) {
1293                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
1294                                 strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
1295                         } else {
1296                                 strncpy(pvt->exten, cd->call_dest_alias, sizeof(pvt->exten) - 1);
1297                         }
1298                         if (ast_strlen_zero(default_context)) {
1299                                 ast_log(LOG_ERROR, "Call from '%s' rejected due to no default context\n", pvt->cd.call_source_aliases);
1300                                 return NULL;
1301                         }
1302                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
1303                         ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd->call_source_aliases, pvt->context);
1304                         /* XXX: Is it really required??? */
1305 #if 0
1306                         memset(&pvt->options, 0, sizeof(pvt->options));
1307 #endif
1308                 } else {
1309                         if (user->host) {
1310                                 if (strcasecmp(cd->sourceIp, ast_inet_ntoa(iabuf, sizeof(iabuf), user->addr.sin_addr))) {
1311                                         if (ast_strlen_zero(user->context)) {
1312                                                 if (ast_strlen_zero(default_context)) {
1313                                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s) and no default context\n", user->name, cd->sourceIp);
1314                                                         return NULL;
1315                                                 }
1316                                                 strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
1317                                         } else {
1318                                                 strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
1319                                         }
1320                                         pvt->exten[0] = 'i';
1321                                         pvt->exten[1] = '\0';
1322                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s)s\n", user->name, cd->sourceIp);
1323                                         return NULL;    /* XXX: Hmmm... Why to setup context if we drop connection immediately??? */
1324                                 }
1325                         }
1326                         strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
1327                         memcpy(&pvt->options, &user->options, sizeof(pvt->options));
1328                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
1329                                 strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
1330                         } else {
1331                                 strncpy(pvt->exten, cd->call_dest_alias, sizeof(pvt->exten) - 1);
1332                         }
1333                         if (!ast_strlen_zero(user->accountcode)) {
1334                                 strncpy(pvt->accountcode, user->accountcode, sizeof(pvt->accountcode) - 1);
1335                         } 
1336                         if (user->amaflags) {
1337                                 pvt->amaflags = user->amaflags;
1338                         } 
1339                 } 
1340         }
1341         return &pvt->options;
1342 }
1343
1344 /**
1345  * Call-back function to start PBX when OpenH323 ready to serve incoming call
1346  *
1347  * Returns 1 on success
1348  */
1349 static int answer_call(unsigned call_reference, const char *token)
1350 {
1351         struct oh323_pvt *pvt;
1352         struct ast_channel *c = NULL;
1353
1354         if (h323debug)
1355                 ast_log(LOG_DEBUG, "Preparing Asterisk to answer for %s\n", token);
1356
1357         /* Find the call or allocate a private structure if call not found */
1358         pvt = find_call_locked(call_reference, token); 
1359         if (!pvt) {
1360                 ast_log(LOG_ERROR, "Something is wrong: answer_call\n");
1361                 return 0;
1362         }
1363         /* allocate a channel and tell asterisk about it */
1364         c = __oh323_new(pvt, AST_STATE_RINGING, pvt->cd.call_token);
1365
1366         /* And release when done */
1367         ast_mutex_unlock(&pvt->lock);
1368         if (!c) {
1369                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1370                 return 0;
1371         }
1372         return 1;
1373 }
1374
1375 /**
1376  * Call-back function to establish an outgoing H.323 call
1377  * 
1378  * Returns 1 on success 
1379  */
1380 int setup_outgoing_call(call_details_t *cd)
1381 {
1382         /* Use argument here or free it immediately */
1383         cleanup_call_details(cd);
1384
1385         return 1;
1386 }
1387
1388 /**
1389   *  Call-back function to signal asterisk that the channel is ringing
1390   *  Returns nothing
1391   */
1392 void chan_ringing(unsigned call_reference, const char *token)
1393 {
1394         struct ast_channel *c = NULL;
1395         struct oh323_pvt *pvt;
1396
1397         if (h323debug)
1398                 ast_log(LOG_DEBUG, "Ringing on %s\n", token);
1399
1400         pvt = find_call_locked(call_reference, token); 
1401         if (!pvt) {
1402                 ast_log(LOG_ERROR, "Something is wrong: ringing\n");
1403         }
1404         if (!pvt->owner) {
1405                 ast_mutex_unlock(&pvt->lock);
1406                 ast_log(LOG_ERROR, "Channel has no owner\n");
1407                 return;
1408         }
1409         ast_mutex_lock(&pvt->owner->lock);
1410         c = pvt->owner;
1411         ast_setstate(c, AST_STATE_RINGING);
1412         ast_queue_control(c, AST_CONTROL_RINGING);
1413         ast_mutex_unlock(&pvt->owner->lock);
1414         ast_mutex_unlock(&pvt->lock);
1415         return;
1416 }
1417
1418 /**
1419   * Call-back function to cleanup communication
1420   * Returns nothing,
1421   */
1422 static void cleanup_connection(unsigned call_reference, const char *call_token)
1423 {       
1424         struct oh323_pvt *pvt;
1425
1426         ast_log(LOG_DEBUG, "Cleaning connection to %s\n", call_token);
1427         
1428         while (1) {
1429                 pvt = find_call_locked(call_reference, call_token); 
1430                 if (!pvt) {
1431                         if (h323debug)
1432                                 ast_log(LOG_DEBUG, "No connection for %s\n", call_token);
1433                         return;
1434                 }
1435                 if (!pvt->owner || !ast_mutex_trylock(&pvt->owner->lock))
1436                         break;
1437 #if 1
1438 #ifdef DEBUG_THREADS
1439                 ast_log(LOG_NOTICE, "Avoiding H.323 destory deadlock on %s, locked at %ld/%d by %s (%s:%d)\n", call_token, pvt->owner->lock.thread, pvt->owner->lock.reentrancy, pvt->owner->lock.func, pvt->owner->lock.file, pvt->owner->lock.lineno);
1440 #else
1441                 ast_log(LOG_NOTICE, "Avoiding H.323 destory deadlock on %s\n", call_token);
1442 #endif
1443 #endif
1444                 ast_mutex_unlock(&pvt->lock);
1445                 usleep(1);
1446         }
1447         if (pvt->rtp) {
1448                 /* Immediately stop RTP */
1449                 ast_rtp_destroy(pvt->rtp);
1450                 pvt->rtp = NULL;
1451         }
1452         /* Free dsp used for in-band DTMF detection */
1453         if (pvt->vad) {
1454                 ast_dsp_free(pvt->vad);
1455                 pvt->vad = NULL;
1456         }
1457         cleanup_call_details(&pvt->cd);
1458         pvt->alreadygone = 1;
1459         /* Send hangup */       
1460         if (pvt->owner) {
1461                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1462                 ast_queue_hangup(pvt->owner);
1463                 ast_mutex_unlock(&pvt->owner->lock);
1464         }
1465         ast_mutex_unlock(&pvt->lock);
1466         if (h323debug)
1467                 ast_log(LOG_DEBUG, "Connection to %s cleaned\n", call_token);
1468         return; 
1469 }
1470
1471 static void hangup_connection(unsigned int call_reference, const char *token, int cause)
1472 {
1473         struct oh323_pvt *pvt;
1474
1475         ast_log(LOG_DEBUG, "Hanging up connection to %s with cause %d\n", token, cause);
1476         
1477         pvt = find_call_locked(call_reference, token); 
1478         if (!pvt) {
1479                 return;
1480         }
1481         if (pvt->owner && !ast_mutex_trylock(&pvt->owner->lock)) {
1482                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1483                 pvt->owner->hangupcause = pvt->hangupcause = cause;
1484                 ast_queue_hangup(pvt->owner);
1485                 ast_mutex_unlock(&pvt->owner->lock);
1486         }
1487         else {
1488                 pvt->needhangup = 1;
1489                 pvt->hangupcause = cause;
1490                 ast_log(LOG_DEBUG, "Hangup for %s is pending\n", token);
1491         }
1492         ast_mutex_unlock(&pvt->lock);
1493 }
1494
1495 void set_dtmf_payload(unsigned call_reference, const char *token, int payload)
1496 {
1497         struct oh323_pvt *pvt;
1498
1499         if (h323debug)
1500                 ast_log(LOG_DEBUG, "Setting DTMF payload to %d on %s\n", payload, token);
1501
1502         pvt = find_call_locked(call_reference, token);
1503         if (!pvt) {
1504                 return;
1505         }
1506         if (pvt->rtp) {
1507                 ast_rtp_set_rtpmap_type(pvt->rtp, payload, "audio", "telephone-event");
1508         }
1509         ast_mutex_unlock(&pvt->lock);
1510         if (h323debug)
1511                 ast_log(LOG_DEBUG, "DTMF payload on %s set to %d\n", token, payload);
1512 }
1513
1514 static void set_local_capabilities(unsigned call_reference, const char *token)
1515 {
1516         struct oh323_pvt *pvt;
1517         int capability, dtmfmode;
1518
1519         if (h323debug)
1520                 ast_log(LOG_DEBUG, "Setting capabilities for connection %s\n", token);
1521
1522         pvt = find_call_locked(call_reference, token);
1523         if (!pvt)
1524                 return;
1525         capability = pvt->options.capability;
1526         dtmfmode = pvt->options.dtmfmode;
1527         ast_mutex_unlock(&pvt->lock);
1528         h323_set_capabilities(token, capability, dtmfmode);
1529
1530         if (h323debug)
1531                 ast_log(LOG_DEBUG, "Capabilities for connection %s is set\n", token);
1532 }
1533
1534 static void *do_monitor(void *data)
1535 {
1536         int res;
1537         int reloading;
1538         struct oh323_pvt *oh323 = NULL;
1539         
1540         for(;;) {
1541                 /* Check for a reload request */
1542                 ast_mutex_lock(&h323_reload_lock);
1543                 reloading = h323_reloading;
1544                 h323_reloading = 0;
1545                 ast_mutex_unlock(&h323_reload_lock);
1546                 if (reloading) {
1547                         if (option_verbose > 0) {
1548                                 ast_verbose(VERBOSE_PREFIX_1 "Reloading H.323\n");
1549                         }
1550                         h323_do_reload();
1551                 }
1552                 /* Check for interfaces needing to be killed */
1553                 ast_mutex_lock(&iflock);
1554 restartsearch:          
1555                 oh323 = iflist;
1556                 while(oh323) {
1557                         if (oh323->needdestroy) {
1558                                 __oh323_destroy(oh323);
1559                                 goto restartsearch;
1560                         }
1561                         oh323 = oh323->next;
1562                 }
1563                 ast_mutex_unlock(&iflock);
1564                 pthread_testcancel();
1565                 /* Wait for sched or io */
1566                 res = ast_sched_wait(sched);
1567                 if ((res < 0) || (res > 1000)) {
1568                         res = 1000;
1569                 }
1570                 res = ast_io_wait(io, res);
1571                 pthread_testcancel();
1572                 ast_mutex_lock(&monlock);
1573                 if (res >= 0) {
1574                         ast_sched_runq(sched);
1575                 }
1576                 ast_mutex_unlock(&monlock);
1577         }
1578         /* Never reached */
1579         return NULL;
1580 }
1581
1582 static int restart_monitor(void)
1583 {
1584         pthread_attr_t attr;
1585         /* If we're supposed to be stopped -- stay stopped */
1586         if (monitor_thread == AST_PTHREADT_STOP) {
1587                 return 0;
1588         }
1589         if (ast_mutex_lock(&monlock)) {
1590                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1591                 return -1;
1592         }
1593         if (monitor_thread == pthread_self()) {
1594                 ast_mutex_unlock(&monlock);
1595                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1596                 return -1;
1597         }
1598         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
1599                 /* Wake up the thread */
1600                 pthread_kill(monitor_thread, SIGURG);
1601         } else {        
1602                 pthread_attr_init(&attr);
1603                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1604                 /* Start a new monitor */
1605                 if (ast_pthread_create(&monitor_thread, &attr, do_monitor, NULL) < 0) {
1606                         ast_mutex_unlock(&monlock);
1607                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1608                         return -1;
1609                 }
1610
1611         }
1612         ast_mutex_unlock(&monlock);
1613         return 0;
1614 }
1615
1616 static int h323_do_trace(int fd, int argc, char *argv[])
1617 {
1618         if (argc != 3) {
1619                 return RESULT_SHOWUSAGE;
1620         }
1621         h323_debug(1, atoi(argv[2]));
1622         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1623         return RESULT_SUCCESS;
1624 }
1625
1626 static int h323_no_trace(int fd, int argc, char *argv[])
1627 {
1628         if (argc != 3) {
1629                 return RESULT_SHOWUSAGE;
1630         }
1631         h323_debug(0,0);
1632         ast_cli(fd, "H.323 trace disabled\n");
1633         return RESULT_SUCCESS;
1634 }
1635
1636 static int h323_do_debug(int fd, int argc, char *argv[])
1637 {
1638         if (argc != 2) {
1639                 return RESULT_SHOWUSAGE;
1640         }
1641         h323debug = 1;
1642         ast_cli(fd, "H323 debug enabled\n");
1643         return RESULT_SUCCESS;
1644 }
1645
1646 static int h323_no_debug(int fd, int argc, char *argv[])
1647 {
1648         if (argc != 3) {
1649                 return RESULT_SHOWUSAGE;
1650         }
1651         h323debug = 0;
1652         ast_cli(fd, "H323 Debug disabled\n");
1653         return RESULT_SUCCESS;
1654 }
1655
1656 static int h323_gk_cycle(int fd, int argc, char *argv[])
1657 {
1658 #if 0
1659         if (argc != 3) {
1660                 return RESULT_SHOWUSAGE;
1661         }       
1662         h323_gk_urq();
1663         
1664         /* Possibly register with a GK */
1665         if (!gatekeeper_disable) {
1666                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1667                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1668                 }
1669         }
1670 #endif
1671         return RESULT_SUCCESS;
1672 }
1673
1674 static int h323_ep_hangup(int fd, int argc, char *argv[])
1675 {
1676         if (argc != 3) {
1677                 return RESULT_SHOWUSAGE;
1678         }
1679         if (h323_soft_hangup(argv[2])) {
1680                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
1681         } else { 
1682                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
1683         }
1684         return RESULT_SUCCESS;
1685 }
1686
1687 static int h323_tokens_show(int fd, int argc, char *argv[])
1688 {
1689         if (argc != 3) {
1690                 return RESULT_SHOWUSAGE;
1691         }
1692         h323_show_tokens();
1693         return RESULT_SUCCESS;
1694 }
1695
1696 static char trace_usage[] = 
1697 "Usage: h.323 trace <level num>\n"
1698 "       Enables H.323 stack tracing for debugging purposes\n";
1699
1700 static char no_trace_usage[] = 
1701 "Usage: h.323 no trace\n"
1702 "       Disables H.323 stack tracing for debugging purposes\n";
1703
1704 static char debug_usage[] = 
1705 "Usage: h.323 debug\n"
1706 "       Enables H.323 debug output\n";
1707
1708 static char no_debug_usage[] = 
1709 "Usage: h.323 no debug\n"
1710 "       Disables H.323 debug output\n";
1711
1712 static char show_codec_usage[] = 
1713 "Usage: h.323 show codec\n"
1714 "       Shows all enabled codecs\n";
1715
1716 static char show_cycle_usage[] = 
1717 "Usage: h.323 gk cycle\n"
1718 "       Manually re-register with the Gatekeper (Currently Disabled)\n";
1719
1720 static char show_hangup_usage[] = 
1721 "Usage: h.323 hangup <token>\n"
1722 "       Manually try to hang up call identified by <token>\n";
1723
1724 static char show_tokens_usage[] = 
1725 "Usage: h.323 show tokens\n"
1726 "       Print out all active call tokens\n";
1727
1728 static char h323_reload_usage[] =
1729 "Usage: h323 reload\n"
1730 "       Reloads H.323 configuration from sip.conf\n";
1731
1732 static struct ast_cli_entry  cli_trace =
1733         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1734 static struct ast_cli_entry  cli_no_trace =
1735         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1736 static struct ast_cli_entry  cli_debug =
1737         { { "h.323", "debug", NULL }, h323_do_debug, "Enable H.323 debug", debug_usage };
1738 static struct ast_cli_entry  cli_no_debug =
1739         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable H.323 debug", no_debug_usage };
1740 static struct ast_cli_entry  cli_show_codecs =
1741         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1742 static struct ast_cli_entry  cli_gk_cycle =
1743         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1744 static struct ast_cli_entry  cli_hangup_call =
1745         { { "h.323", "hangup", NULL }, h323_ep_hangup, "Manually try to hang up a call", show_hangup_usage };
1746 static struct ast_cli_entry  cli_show_tokens =
1747         { { "h.323", "show", "tokens", NULL }, h323_tokens_show, "Show all active call tokens", show_tokens_usage };
1748
1749 static int update_common_options(struct ast_variable *v, struct call_options *options)
1750 {
1751         unsigned int format;
1752         int tmp;
1753
1754         if (!strcasecmp(v->name, "allow")) {
1755                 format = ast_getformatbyname(v->value);
1756                 if (format < 1) 
1757                         ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1758                 else
1759                         options->capability |= format;
1760         } else if (!strcasecmp(v->name, "disallow")) {
1761                 format = ast_getformatbyname(v->value);
1762                 if (format < 1) 
1763                         ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1764                 else
1765                         options->capability &= ~format;
1766         } else if (!strcasecmp(v->name, "dtmfmode")) {
1767                 if (!strcasecmp(v->value, "inband")) {
1768                         options->dtmfmode = H323_DTMF_INBAND;
1769                 } else if (!strcasecmp(v->value, "rfc2833")) {
1770                         options->dtmfmode = H323_DTMF_RFC2833;
1771                 } else {
1772                         ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1773                         options->dtmfmode = H323_DTMF_RFC2833;
1774                 }
1775         } else if (!strcasecmp(v->name, "dtmfcodec")) {
1776                 tmp = atoi(v->value);
1777                 if (tmp < 96)
1778                         ast_log(LOG_WARNING, "Invalid global dtmfcodec value %s\n", v->value);
1779                 else
1780                         options->dtmfcodec = tmp;
1781         } else if (!strcasecmp(v->name, "bridge")) {
1782                 options->bridge = ast_true(v->value);
1783         } else if (!strcasecmp(v->name, "nat")) {
1784                 options->nat = ast_true(v->value);
1785         } else if (!strcasecmp(v->name, "noFastStart")) {
1786                 options->noFastStart = ast_true(v->value);
1787         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
1788                 options->noH245Tunneling = ast_true(v->value);
1789         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
1790                 options->noSilenceSuppression = ast_true(v->value);
1791         } else if (!strcasecmp(v->name, "progress_setup")) {
1792                 tmp = atoi(v->value);
1793                 if ((tmp != 0) && (tmp != 1) && (tmp != 3) && (tmp != 8)) {
1794                         ast_log(LOG_WARNING, "Invalid value %d for progress_setup at line %d, assuming 0\n", tmp, v->lineno);
1795                         tmp = 0;
1796                 }
1797                 options->progress_setup = tmp;
1798         } else if (!strcasecmp(v->name, "progress_alert")) {
1799                 tmp = atoi(v->value);
1800                 if ((tmp != 0) && (tmp != 8)) {
1801                         ast_log(LOG_WARNING, "Invalud value %d for progress_alert at line %d, assuming 0\n", tmp, v->lineno);
1802                         tmp = 0;
1803                 }
1804                 options->progress_alert = tmp;
1805         } else if (!strcasecmp(v->name, "progress_audio")) {
1806                 options->progress_audio = ast_true(v->value);
1807         } else
1808                 return 1;
1809
1810         return 0;
1811 }
1812
1813 static struct oh323_alias *build_alias(char *name, struct ast_variable *v)
1814 {
1815         struct oh323_alias *alias;
1816
1817         alias = (struct oh323_alias *)malloc(sizeof(struct oh323_alias));
1818         if (alias) {
1819                 memset(alias, 0, sizeof(struct oh323_alias));
1820                 strncpy(alias->name, name, sizeof(alias->name) - 1);
1821                 while (v) {
1822                         if (!strcasecmp(v->name, "e164")) {
1823                                 strncpy(alias->e164,  v->value, sizeof(alias->e164) - 1);
1824                         } else if (!strcasecmp(v->name, "prefix")) {
1825                                 strncpy(alias->prefix,  v->value, sizeof(alias->prefix) - 1);
1826                         } else if (!strcasecmp(v->name, "context")) {
1827                                 strncpy(alias->context,  v->value, sizeof(alias->context) - 1);
1828                         } else if (!strcasecmp(v->name, "secret")) {
1829                                 strncpy(alias->secret,  v->value, sizeof(alias->secret) - 1);
1830                         } else {
1831                                 if (strcasecmp(v->value, "h323")) {     
1832                                         ast_log(LOG_WARNING, "Keyword %s does not make sense in type=h323\n", v->value);
1833                                 }
1834                         }
1835                         v = v->next;
1836                 }
1837         }
1838         return alias;
1839 }
1840
1841 static struct oh323_user *build_user(char *name, struct ast_variable *v)
1842 {
1843         struct oh323_user *user;
1844         int format;
1845
1846         user = (struct oh323_user *)malloc(sizeof(struct oh323_user));
1847         if (user) {
1848                 memset(user, 0, sizeof(struct oh323_user));
1849                 strncpy(user->name, name, sizeof(user->name) - 1);
1850                 memcpy(&user->options, &global_options, sizeof(user->options));
1851                 /* Set default context */
1852                 strncpy(user->context, default_context, sizeof(user->context) - 1);
1853                 while(v) {
1854                         if (!strcasecmp(v->name, "context")) {
1855                                 strncpy(user->context, v->value, sizeof(user->context) - 1);
1856                         } else if (!update_common_options(v, &user->options)) {
1857                                 /* dummy */
1858                         } else if (!strcasecmp(v->name, "secret")) {
1859                                 strncpy(user->secret, v->value, sizeof(user->secret) - 1);
1860                         } else if (!strcasecmp(v->name, "callerid")) {
1861                                 strncpy(user->callerid, v->value, sizeof(user->callerid) - 1);
1862                         } else if (!strcasecmp(v->name, "accountcode")) {
1863                                 strncpy(user->accountcode, v->value, sizeof(user->accountcode) - 1);
1864                         } else if (!strcasecmp(v->name, "host")) {
1865                                 if (!strcasecmp(v->value, "dynamic")) {
1866                                         ast_log(LOG_ERROR, "A dynamic host on a type=user does not make any sense\n");
1867                                         free(user);
1868                                         return NULL;
1869                                 } else if (ast_get_ip(&user->addr, v->value)) {
1870                                         free(user);
1871                                         return NULL;
1872                                 } 
1873                                 /* Let us know we need to use ip authentication */
1874                                 user->host = 1;
1875                         } else if (!strcasecmp(v->name, "amaflags")) {
1876                                 format = ast_cdr_amaflags2int(v->value);
1877                                 if (format < 0) {
1878                                         ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
1879                                 } else {
1880                                         user->amaflags = format;
1881                                 }
1882                         }
1883                         v = v->next;
1884                 }
1885         }
1886         return user;
1887 }
1888
1889 static struct oh323_peer *build_peer(char *name, struct ast_variable *v)
1890 {
1891         struct oh323_peer *peer;
1892         struct oh323_peer *prev;
1893         struct ast_ha *oldha = NULL;
1894         int found=0;
1895
1896         prev = NULL;
1897         ast_mutex_lock(&peerl.lock);
1898         peer = peerl.peers;
1899
1900         while(peer) {
1901                 if (!strcasecmp(peer->name, name)) {    
1902                         break;
1903                 }
1904                 prev = peer;
1905                 peer = peer->next;
1906         }
1907
1908         if (peer) {
1909                 found++;
1910                 /* Already in the list, remove it and it will be added back (or FREE'd) */
1911                 if (prev) {
1912                         prev->next = peer->next;
1913                 } else {
1914                         peerl.peers = peer->next;
1915                 }
1916                 ast_mutex_unlock(&peerl.lock);
1917         } else {
1918                 ast_mutex_unlock(&peerl.lock);
1919                 peer = (struct oh323_peer*)malloc(sizeof(struct oh323_peer));
1920                 if (peer)
1921                         memset(peer, 0, sizeof(struct oh323_peer));
1922         }
1923         if (peer) {
1924                 if (!found) {
1925                         strncpy(peer->name, name, sizeof(peer->name) - 1);
1926                         peer->addr.sin_port = htons(h323_signalling_port);
1927                         peer->addr.sin_family = AF_INET;
1928                 }
1929                 oldha = peer->ha;
1930                 peer->ha = NULL;
1931                 peer->addr.sin_family = AF_INET;
1932                 memcpy(&peer->options, &global_options, sizeof(peer->options));
1933
1934                 while(v) {
1935                         if (!update_common_options(v, &peer->options)) {
1936                                 /* dummy */
1937                         } else if (!strcasecmp(v->name, "host")) {
1938                                 if (!strcasecmp(v->value, "dynamic")) {
1939                                         ast_log(LOG_ERROR, "Dynamic host configuration not implemented.\n");
1940                                         free(peer);
1941                                         return NULL;
1942                                 }
1943                                 if (ast_get_ip(&peer->addr, v->value)) {
1944                                                 ast_log(LOG_ERROR, "Could not determine IP for %s\n", v->value);
1945                                                 free(peer);
1946                                                 return NULL;
1947                                 }
1948                         } else if (!strcasecmp(v->name, "port")) {
1949                                 peer->addr.sin_port = htons(atoi(v->value));
1950                         }
1951                         v=v->next;
1952                 }
1953         }
1954         return peer;
1955 }
1956
1957 int reload_config(void)
1958 {       
1959         int format;
1960         struct ast_config *cfg;
1961         struct ast_variable *v;
1962         struct oh323_peer *peer   = NULL;
1963         struct oh323_user *user   = NULL;
1964         struct oh323_alias *alias = NULL;
1965         struct ast_hostent ahp; struct hostent *hp;
1966         char *cat;
1967         char *utype;
1968         
1969         cfg = ast_config_load(config);
1970
1971         /* We *must* have a config file otherwise stop immediately */
1972         if (!cfg) {
1973                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
1974                 return 1;
1975         }
1976         
1977        /* fire up the H.323 Endpoint */       
1978         if (!h323_end_point_exist()) {
1979                h323_end_point_create();        
1980         }
1981         h323debug = 0;
1982         memset(&bindaddr, 0, sizeof(bindaddr));
1983         memset(&global_options, 0, sizeof(global_options));
1984         global_options.dtmfcodec = 101;
1985         global_options.dtmfmode = H323_DTMF_RFC2833;
1986         global_options.capability = ~0; /* All capabilities */
1987         global_options.bridge = 1;              /* Do native bridging by default */
1988         v = ast_variable_browse(cfg, "general");
1989         while(v) {
1990                 /* Create the interface list */
1991                 if (!strcasecmp(v->name, "port")) {
1992                         h323_signalling_port = (int)strtol(v->value, NULL, 10);
1993                 } else if (!strcasecmp(v->name, "bindaddr")) {
1994                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
1995                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1996                         } else {
1997                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1998                         }
1999                 } else if (!strcasecmp(v->name, "tos")) {
2000                         if (sscanf(v->value, "%d", &format)) {
2001                                 tos = format & 0xff;
2002                         } else if (!strcasecmp(v->value, "lowdelay")) {
2003                                 tos = IPTOS_LOWDELAY;
2004                         } else if (!strcasecmp(v->value, "throughput")) {
2005                                 tos = IPTOS_THROUGHPUT;
2006                         } else if (!strcasecmp(v->value, "reliability")) {
2007                                 tos = IPTOS_RELIABILITY;
2008                         } else if (!strcasecmp(v->value, "mincost")) {
2009                                 tos = IPTOS_MINCOST;
2010                         } else if (!strcasecmp(v->value, "none")) {
2011                                 tos = 0;
2012                         } else {
2013                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
2014                         }
2015                 } else if (!strcasecmp(v->name, "gatekeeper")) {
2016                         if (!strcasecmp(v->value, "DISABLE")) {
2017                                 gatekeeper_disable = 1;
2018                                 usingGk = 0;
2019                         } else if (!strcasecmp(v->value, "DISCOVER")) {
2020                                 gatekeeper_disable = 0;
2021                                 gatekeeper_discover = 1;
2022                                 usingGk = 1;
2023                         } else {
2024                                 gatekeeper_disable = 0;
2025                                 usingGk = 1;
2026                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper) - 1);
2027                         }
2028                 } else if (!strcasecmp(v->name, "secret")) {
2029                         strncpy(secret, v->value, sizeof(secret) - 1);
2030                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
2031                         gkroute = ast_true(v->value);
2032                 } else if (!strcasecmp(v->name, "context")) {
2033                         strncpy(default_context, v->value, sizeof(default_context) - 1);
2034                         ast_verbose(VERBOSE_PREFIX_2 "Setting default context to %s\n", default_context);       
2035                 } else if (!strcasecmp(v->name, "UserByAlias")) {
2036                         userbyalias = ast_true(v->value);
2037                 } else if (!update_common_options(v, &global_options)) {
2038                         /* dummy */
2039                 }
2040                 v = v->next;    
2041         }
2042         
2043         cat = ast_category_browse(cfg, NULL);
2044         while(cat) {
2045                 if (strcasecmp(cat, "general")) {
2046                         utype = ast_variable_retrieve(cfg, cat, "type");
2047                         if (utype) {
2048                                 if (!strcasecmp(utype, "user")) {
2049                                         user = build_user(cat, ast_variable_browse(cfg, cat));
2050                                         if (user) {
2051                                                 ast_mutex_lock(&userl.lock);
2052                                                 user->next = userl.users;
2053                                                 userl.users = user;
2054                                                 ast_mutex_unlock(&userl.lock);
2055                                         }
2056                                 }  else if (!strcasecmp(utype, "peer")) {
2057                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
2058                                         if (peer) {
2059                                                 ast_mutex_lock(&peerl.lock);
2060                                                 peer->next = peerl.peers;
2061                                                 peerl.peers = peer;
2062                                                 ast_mutex_unlock(&peerl.lock);
2063                                         }
2064                                 }  else if (!strcasecmp(utype, "friend")) {
2065                                         user = build_user(cat, ast_variable_browse(cfg, cat));
2066                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
2067                                         if (user) {
2068                                                 ast_mutex_lock(&userl.lock);
2069                                                 user->next = userl.users;
2070                                                 userl.users = user;
2071                                                 ast_mutex_unlock(&userl.lock);
2072                                         }
2073                                         if (peer) {
2074                                                 ast_mutex_lock(&peerl.lock);
2075                                                 peer->next = peerl.peers;
2076                                                 peerl.peers = peer;
2077                                                 ast_mutex_unlock(&peerl.lock);
2078                                         }
2079                                 }  else if (!strcasecmp(utype, "h323") || !strcasecmp(utype, "alias")) {
2080                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
2081                                         if (alias) {
2082                                                 ast_mutex_lock(&aliasl.lock);
2083                                                 alias->next = aliasl.aliases;
2084                                                 aliasl.aliases = alias;
2085                                                 ast_mutex_unlock(&aliasl.lock);
2086                                         }
2087                                 } else {
2088                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
2089                                 }
2090                         } else {
2091                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
2092                         }
2093                 }
2094                 cat = ast_category_browse(cfg, cat);
2095         }
2096         ast_config_destroy(cfg);
2097
2098         /* Register our H.323 aliases if any*/
2099         while (alias) {         
2100                 if (h323_set_alias(alias)) {
2101                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
2102                         return -1;
2103                 }       
2104                 alias = alias->next;
2105         }
2106
2107         return 0;
2108 }
2109
2110 void delete_users(void)
2111 {
2112         struct oh323_user *user, *userlast;
2113         struct oh323_peer *peer;
2114         
2115         /* Delete all users */
2116         ast_mutex_lock(&userl.lock);
2117         for (user=userl.users;user;) {
2118                 userlast = user;
2119                 user=user->next;
2120                 free(userlast);
2121         }
2122         userl.users=NULL;
2123         ast_mutex_unlock(&userl.lock);
2124         ast_mutex_lock(&peerl.lock);
2125         for (peer=peerl.peers;peer;) {
2126                 /* Assume all will be deleted, and we'll find out for sure later */
2127                 peer->delme = 1;
2128                 peer = peer->next;
2129         }
2130         ast_mutex_unlock(&peerl.lock);
2131 }
2132
2133 void delete_aliases(void)
2134 {
2135         struct oh323_alias *alias, *aliaslast;
2136                 
2137         /* Delete all users */
2138         ast_mutex_lock(&aliasl.lock);
2139         for (alias=aliasl.aliases;alias;) {
2140                 aliaslast = alias;
2141                 alias=alias->next;
2142                 free(aliaslast);
2143         }
2144         aliasl.aliases=NULL;
2145         ast_mutex_unlock(&aliasl.lock);
2146 }
2147
2148 void prune_peers(void)
2149 {
2150         /* Prune peers who still are supposed to be deleted */
2151         struct oh323_peer *peer, *peerlast, *peernext;
2152         ast_mutex_lock(&peerl.lock);
2153         peerlast = NULL;
2154         for (peer=peerl.peers;peer;) {
2155                 peernext = peer->next;
2156                 if (peer->delme) {
2157                         free(peer);
2158                         if (peerlast) {
2159                                 peerlast->next = peernext;
2160                         } else {
2161                                 peerl.peers = peernext;
2162                         }
2163                 } else {
2164                         peerlast = peer;
2165                 }
2166                 peer = peernext;
2167         }
2168         ast_mutex_unlock(&peerl.lock);
2169 }
2170
2171 static int h323_reload(int fd, int argc, char *argv[])
2172 {
2173         ast_mutex_lock(&h323_reload_lock);
2174         if (h323_reloading) {
2175                 ast_verbose("Previous H.323 reload not yet done\n");
2176         } else {
2177                 h323_reloading = 1;
2178         }
2179         ast_mutex_unlock(&h323_reload_lock);
2180         restart_monitor();
2181         return 0;
2182 }
2183
2184 static int h323_do_reload(void)
2185 {
2186         delete_users();
2187         delete_aliases();
2188         prune_peers();
2189         reload_config();
2190         restart_monitor();
2191         return 0;
2192 }
2193
2194 int reload(void)
2195 {
2196         return h323_reload(0, 0, NULL);
2197 }
2198
2199 static struct ast_cli_entry  cli_h323_reload =
2200         { { "h.323", "reload", NULL }, h323_reload, "Reload H.323 configuration", h323_reload_usage };
2201
2202 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
2203 {
2204         struct oh323_pvt *pvt;
2205         pvt = (struct oh323_pvt *) chan->tech_pvt;
2206         if (pvt && pvt->rtp && pvt->options.bridge) {
2207                 return pvt->rtp;
2208         }
2209         return NULL;
2210 }
2211
2212 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
2213 {
2214         return NULL;
2215 }
2216
2217 static char *convertcap(int cap)
2218 {
2219         switch (cap) {
2220         case AST_FORMAT_G723_1:
2221                 return "G.723";
2222         case AST_FORMAT_GSM:
2223                 return "GSM";
2224         case AST_FORMAT_ULAW:
2225                 return "ULAW";
2226         case AST_FORMAT_ALAW:
2227                 return "ALAW";
2228         case AST_FORMAT_ADPCM:
2229                 return "G.728";
2230         case AST_FORMAT_G729A:
2231                 return "G.729";
2232         case AST_FORMAT_SPEEX:
2233                 return "SPEEX";
2234         case AST_FORMAT_ILBC:
2235                 return "ILBC";
2236         default:
2237                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
2238                 return NULL;
2239         }
2240 }
2241
2242 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs)
2243 {
2244         /* XXX Deal with Video */
2245         struct oh323_pvt *pvt;
2246         struct sockaddr_in them;
2247         struct sockaddr_in us;
2248         char *mode;
2249         char iabuf[INET_ADDRSTRLEN];
2250
2251         if (!rtp) {
2252                 return 0;
2253         }
2254
2255         mode = convertcap(chan->writeformat); 
2256         pvt = (struct oh323_pvt *) chan->tech_pvt;
2257         if (!pvt) {
2258                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
2259                 return -1;
2260         }
2261         ast_rtp_get_peer(rtp, &them);   
2262         ast_rtp_get_us(rtp, &us);
2263         h323_native_bridge(pvt->cd.call_token, ast_inet_ntoa(iabuf, sizeof(iabuf), them.sin_addr), mode);
2264         return 0;
2265 }
2266
2267 static struct ast_rtp_protocol oh323_rtp = {
2268         .type = type,
2269         .get_rtp_info = oh323_get_rtp_peer,
2270         .get_vrtp_info = oh323_get_vrtp_peer,
2271         .set_rtp_peer=  oh323_set_rtp_peer,
2272 };
2273
2274 int load_module()
2275 {
2276         int res;
2277         ast_mutex_init(&userl.lock);
2278         ast_mutex_init(&peerl.lock);
2279         ast_mutex_init(&aliasl.lock);
2280         sched = sched_context_create();
2281         if (!sched) {
2282                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2283         }
2284         io = io_context_create();
2285         if (!io) {
2286                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2287         }
2288         res = reload_config();
2289         if (res) {
2290                 return 0;
2291         } else {
2292                 /* Make sure we can register our channel type */
2293                 if (ast_channel_register(&oh323_tech)) {
2294                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
2295                         h323_end_process();
2296                         return -1;
2297                 }
2298                 ast_cli_register(&cli_debug);
2299                 ast_cli_register(&cli_no_debug);
2300                 ast_cli_register(&cli_trace);
2301                 ast_cli_register(&cli_no_trace);
2302                 ast_cli_register(&cli_show_codecs);
2303                 ast_cli_register(&cli_gk_cycle);
2304                 ast_cli_register(&cli_hangup_call);
2305                 ast_cli_register(&cli_show_tokens);
2306                 ast_cli_register(&cli_h323_reload);
2307
2308                 ast_rtp_proto_register(&oh323_rtp);
2309
2310                 /* Register our callback functions */
2311                 h323_callback_register(setup_incoming_call, 
2312                                                 setup_outgoing_call,                                                     
2313                                                 external_rtp_create, 
2314                                                 setup_rtp_connection, 
2315                                                 cleanup_connection, 
2316                                                 chan_ringing,
2317                                                 connection_made, 
2318                                                 send_digit,
2319                                                 answer_call,
2320                                                 progress,
2321                                                 set_dtmf_payload,
2322                                                 hangup_connection,
2323                                                 set_local_capabilities);
2324                 /* start the h.323 listener */
2325                 if (h323_start_listener(h323_signalling_port, bindaddr)) {
2326                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
2327                         return -1;
2328                 }
2329                 /* Possibly register with a GK */
2330                 if (!gatekeeper_disable) {
2331                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
2332                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
2333                                 return 0;
2334                         }
2335                 }
2336                 /* And start the monitor for the first time */
2337                 restart_monitor();
2338         }
2339         return res;
2340 }
2341
2342 int unload_module() 
2343 {
2344         struct oh323_pvt *p, *pl;
2345
2346         /* unregister commands */
2347         ast_cli_unregister(&cli_debug);
2348         ast_cli_unregister(&cli_no_debug);
2349         ast_cli_unregister(&cli_trace);
2350         ast_cli_unregister(&cli_no_trace);   
2351         ast_cli_unregister(&cli_show_codecs);
2352         ast_cli_unregister(&cli_gk_cycle);
2353         ast_cli_unregister(&cli_hangup_call);
2354         ast_cli_unregister(&cli_show_tokens);
2355         ast_cli_unregister(&cli_h323_reload);
2356         ast_rtp_proto_unregister(&oh323_rtp);
2357         ast_channel_unregister(&oh323_tech);
2358                 
2359         if (!ast_mutex_lock(&iflock)) {
2360                 /* hangup all interfaces if they have an owner */
2361                 p = iflist;
2362                 while(p) {
2363                         if (p->owner) {
2364                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
2365                         }
2366                         p = p->next;
2367                 }
2368                 iflist = NULL;
2369                 ast_mutex_unlock(&iflock);
2370         } else {
2371                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
2372                 return -1;
2373         }
2374         if (!ast_mutex_lock(&monlock)) {
2375                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
2376                         /* this causes a seg, anyone know why? */
2377                         pthread_cancel(monitor_thread);
2378                         pthread_kill(monitor_thread, SIGURG);
2379                         pthread_join(monitor_thread, NULL);
2380                 }
2381                 monitor_thread = AST_PTHREADT_STOP;
2382                 ast_mutex_unlock(&monlock);
2383         } else {
2384                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2385                 return -1;
2386         }
2387         if (!ast_mutex_lock(&iflock)) {
2388                 /* destroy all the interfaces and free their memory */
2389                 p = iflist;
2390                 while(p) {
2391                         pl = p;
2392                         p = p->next;
2393                         /* free associated memory */
2394                         ast_mutex_destroy(&pl->lock);
2395                         free(pl);
2396                 }
2397                 iflist = NULL;
2398                 ast_mutex_unlock(&iflock);
2399         } else {
2400                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
2401                 return -1;
2402         }
2403         h323_gk_urq();
2404         h323_end_process();
2405         io_context_destroy(io);
2406         sched_context_destroy(sched);
2407         delete_users();
2408         delete_aliases();
2409         prune_peers();
2410         ast_mutex_destroy(&aliasl.lock);
2411         ast_mutex_destroy(&userl.lock);
2412         ast_mutex_destroy(&peerl.lock);
2413         return 0; 
2414
2415
2416 int usecount()
2417 {
2418         int res;
2419         ast_mutex_lock(&usecnt_lock);
2420         res = usecnt;
2421         ast_mutex_unlock(&usecnt_lock);
2422         return res;
2423 }
2424
2425 char *description()
2426 {
2427         return (char *) desc;
2428 }
2429
2430 char *key()
2431 {
2432         return ASTERISK_GPL_KEY;
2433 }