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