Reworked chan_ooh323 channel module.
[asterisk/asterisk.git] / addons / chan_ooh323.c
1 /*
2  * Copyright (C) 2004-2005 by Objective Systems, Inc.
3  *
4  * This software is furnished under an open source license and may be 
5  * used and copied only in accordance with the terms of this license. 
6  * The text of the license may generally be found in the root 
7  * directory of this installation in the COPYING file.  It 
8  * can also be viewed online at the following URL:
9  *
10  *   http://www.obj-sys.com/open/license.html
11  *
12  * Any redistributions of this file including modified versions must 
13  * maintain this copyright notice.
14  *
15  *****************************************************************************/
16
17
18 #include "chan_ooh323.h"
19 #include <math.h>
20
21 #define FORMAT_STRING_SIZE      512
22
23 /* Defaults */
24 #define DEFAULT_CONTEXT "default"
25 #define DEFAULT_H323ID "Asterisk PBX"
26 #define DEFAULT_LOGFILE "/var/log/asterisk/h323_log"
27 #define DEFAULT_H323ACCNT "ast_h323"
28
29 /* Flags */
30 #define H323_SILENCESUPPRESSION (1<<0)
31 #define H323_GKROUTED           (1<<1)
32 #define H323_TUNNELING          (1<<2)
33 #define H323_FASTSTART          (1<<3)
34 #define H323_OUTGOING           (1<<4)
35 #define H323_ALREADYGONE        (1<<5)
36 #define H323_NEEDDESTROY        (1<<6)
37 #define H323_DISABLEGK          (1<<7)
38 #define H323_NEEDSTART          (1<<8)
39
40 #define MAXT30  240
41 #define T38TOAUDIOTIMEOUT 30
42 #define T38_DISABLED 0
43 #define T38_ENABLED 1
44 #define T38_FAXGW 1
45
46 /* Channel description */
47 static const char type[] = "OOH323";
48 static const char tdesc[] = "Objective Systems H323 Channel Driver";
49 static const char config[] = "ooh323.conf";
50
51 struct ast_module *myself;
52
53 static struct ast_jb_conf default_jbconf =
54 {
55         .flags = 0,
56         .max_size = -1,
57         .resync_threshold = -1,
58         .impl = ""
59 };
60 static struct ast_jb_conf global_jbconf;
61
62 /* Channel Definition */
63 static struct ast_channel *ooh323_request(const char *type, int format, 
64                         const struct ast_channel *requestor,  void *data, int *cause);
65 static int ooh323_digit_begin(struct ast_channel *ast, char digit);
66 static int ooh323_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
67 static int ooh323_call(struct ast_channel *ast, char *dest, int timeout);
68 static int ooh323_hangup(struct ast_channel *ast);
69 static int ooh323_answer(struct ast_channel *ast);
70 static struct ast_frame *ooh323_read(struct ast_channel *ast);
71 static int ooh323_write(struct ast_channel *ast, struct ast_frame *f);
72 static int ooh323_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
73 static int ooh323_queryoption(struct ast_channel *ast, int option, void *data, int *datalen);
74 static int ooh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
75
76 static enum ast_rtp_glue_result ooh323_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **rtp);
77 static enum ast_rtp_glue_result ooh323_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **rtp);
78 static int ooh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *rtp, 
79           struct ast_rtp_instance *vrtp, struct ast_rtp_instance *trtp, int codecs, int nat_active);
80
81 static struct ast_udptl *ooh323_get_udptl_peer(struct ast_channel *chan);
82 static int ooh323_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
83
84 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
85
86 struct ooh323_peer *find_friend(const char *name, int port);
87
88
89 static const struct ast_channel_tech ooh323_tech = {
90         .type = type,
91         .description = tdesc,
92         .capabilities = -1,
93         .requester = ooh323_request,
94         .send_digit_begin = ooh323_digit_begin,
95         .send_digit_end = ooh323_digit_end,
96         .call = ooh323_call,
97         .hangup = ooh323_hangup,
98         .answer = ooh323_answer,
99         .read = ooh323_read,
100         .write = ooh323_write,
101         .exception = ooh323_read,
102         .indicate = ooh323_indicate,
103         .fixup = ooh323_fixup,
104         .send_html = 0,
105         .queryoption = ooh323_queryoption,
106         .bridge = ast_rtp_instance_bridge,              /* XXX chan unlocked ? */
107         .early_bridge = ast_rtp_instance_early_bridge,
108
109 };
110
111 static struct ast_rtp_glue ooh323_rtp = {
112         .type = type,
113         .get_rtp_info = ooh323_get_rtp_peer,
114         .get_vrtp_info = ooh323_get_vrtp_peer,
115         .update_peer = ooh323_set_rtp_peer,
116 };
117
118 static struct ast_udptl_protocol ooh323_udptl = {
119         type: "H323",
120         get_udptl_info: ooh323_get_udptl_peer,
121         set_udptl_peer: ooh323_set_udptl_peer,
122 };
123
124
125
126 struct ooh323_user;
127
128 /* H.323 channel private structure */
129 static struct ooh323_pvt {
130         ast_mutex_t lock;               /* Channel private lock */
131         struct ast_rtp_instance *rtp;
132         struct ast_rtp_instance *vrtp; /* Placeholder for now */
133
134         int t38support;                 /* T.38 mode - disable, transparent, faxgw */
135         int rtptimeout;
136         struct ast_udptl *udptl;
137         int faxmode;
138         int t38_tx_enable;
139         int t38_init;
140         struct sockaddr_in udptlredirip;
141         time_t lastTxT38;
142         int chmodepend;
143
144         struct ast_channel *owner;      /* Master Channel */
145         union {
146                 char  *user;    /* cooperating user/peer */
147                 char  *peer;
148         } neighbor;
149         time_t lastrtptx;
150         time_t lastrtprx;
151         unsigned int flags;
152         unsigned int call_reference;
153         char *callToken;
154         char *username;
155         char *host;
156         char *callerid_name;
157         char *callerid_num;
158         char caller_h323id[AST_MAX_EXTENSION];
159         char caller_dialedDigits[AST_MAX_EXTENSION];
160         char caller_email[AST_MAX_EXTENSION];
161         char caller_url[256];
162         char callee_h323id[AST_MAX_EXTENSION];
163         char callee_dialedDigits[AST_MAX_EXTENSION];
164         char callee_email[AST_MAX_EXTENSION];
165         char callee_url[AST_MAX_EXTENSION];
166  
167         int port;
168         int readformat;   /* negotiated read format */
169         int writeformat;  /* negotiated write format */
170         int capability;
171         struct ast_codec_pref prefs;
172         int dtmfmode;
173         int dtmfcodec;
174         char exten[AST_MAX_EXTENSION];  /* Requested extension */
175         char context[AST_MAX_EXTENSION];        /* Context where to start */
176         char accountcode[256];  /* Account code */
177         int nat;
178         int amaflags;
179         int progsent;                   /* progress is sent */
180         struct ast_dsp *vad;
181         struct OOH323Regex *rtpmask;    /* rtp ip regexp */
182         char rtpmaskstr[120];
183         struct ooh323_pvt *next;        /* Next entity */
184 } *iflist = NULL;
185
186 /* Protect the channel/interface list (ooh323_pvt) */
187 AST_MUTEX_DEFINE_STATIC(iflock);
188
189 /* Profile of H.323 user registered with PBX*/
190 struct ooh323_user{
191         ast_mutex_t lock;
192         char        name[256];
193         char        context[AST_MAX_EXTENSION];
194         int         incominglimit;
195         unsigned    inUse;
196         char        accountcode[20];
197         int         amaflags;
198         int         capability;
199         struct ast_codec_pref prefs;
200         int         dtmfmode;
201         int         dtmfcodec;
202         int         t38support;
203         int         rtptimeout;
204         int         mUseIP;        /* Use IP address or H323-ID to search user */
205         char        mIP[20];
206         struct OOH323Regex          *rtpmask;
207         char        rtpmaskstr[120];
208         struct ooh323_user *next;
209 };
210
211 /* Profile of valid asterisk peers */
212 struct ooh323_peer{
213         ast_mutex_t lock;
214         char        name[256];
215         unsigned    outgoinglimit;
216         unsigned    outUse;
217         int         capability;
218         struct ast_codec_pref prefs;
219         char        accountcode[20];
220         int         amaflags;
221         int         dtmfmode;
222         int         dtmfcodec;
223         int         t38support;
224         int         mFriend;    /* indicates defined as friend */
225         char        ip[20];
226         int         port;
227         char        *h323id;    /* H323-ID alias, which asterisk will register with gk to reach this peer*/
228         char        *email;     /* Email alias, which asterisk will register with gk to reach this peer*/
229         char        *url;       /* url alias, which asterisk will register with gk to reach this peer*/
230         char        *e164;      /* e164 alias, which asterisk will register with gk to reach this peer*/
231         int         rtptimeout;
232         struct OOH323Regex          *rtpmask;
233         char        rtpmaskstr[120];
234         struct ooh323_peer *next;
235 };
236
237
238 /* List of H.323 users known to PBX */
239 static struct ast_user_list {
240         struct ooh323_user *users;
241         ast_mutex_t lock;
242 } userl;
243
244 static struct ast_peer_list {
245         struct ooh323_peer *peers;
246         ast_mutex_t lock;
247 } peerl;
248
249 /* Mutex to protect H.323 reload process */
250 static int h323_reloading = 0;
251 AST_MUTEX_DEFINE_STATIC(h323_reload_lock);
252
253 /* Mutex to protect usage counter */
254 static int usecnt = 0;
255 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
256
257 AST_MUTEX_DEFINE_STATIC(ooh323c_cmd_lock);
258
259 static long callnumber = 0;
260 AST_MUTEX_DEFINE_STATIC(ooh323c_cn_lock);
261
262 /* stack callbacks */
263 int onAlerting(ooCallData *call);
264 int onProgress(ooCallData *call);
265 int onNewCallCreated(ooCallData *call);
266 int onOutgoingCall(ooCallData *call);
267 int onCallEstablished(ooCallData *call);
268 int onCallCleared(ooCallData *call);
269 void onModeChanged(ooCallData *call, int t38mode);
270
271 static char gLogFile[256] = DEFAULT_LOGFILE;
272 static int  gPort = 1720;
273 static char gIP[20];
274 static char gCallerID[AST_MAX_EXTENSION] = "";
275 static struct ooAliases *gAliasList;
276 static int  gCapability = AST_FORMAT_ULAW;
277 static struct ast_codec_pref gPrefs;
278 static int  gDTMFMode = H323_DTMF_RFC2833;
279 static int  gDTMFCodec = 101;
280 static int  gT38Support = T38_FAXGW;
281 static char gGatekeeper[100];
282 static enum RasGatekeeperMode gRasGkMode = RasNoGatekeeper;
283
284 static int  gIsGateway = 0;
285 static int  gFastStart = 1;
286 static int  gTunneling = 1;
287 static int  gBeMaster = 0;
288 static int  gMediaWaitForConnect = 0;
289 static int  gTOS = 0;
290 static int  gRTPTimeout = 60;
291 static char gAccountcode[80] = DEFAULT_H323ACCNT;
292 static int  gAMAFLAGS;
293 static char gContext[AST_MAX_EXTENSION] = DEFAULT_CONTEXT;
294 static int  gIncomingLimit = 1024;
295 static int  gOutgoingLimit = 1024;
296 OOBOOL gH323Debug = FALSE;
297 static int gTRCLVL = OOTRCLVLERR;
298
299 static int t35countrycode = 0;
300 static int t35extensions = 0;
301 static int manufacturer = 0;
302 static char vendor[AST_MAX_EXTENSION] =  "";
303 static char version[AST_MAX_EXTENSION] = "";
304
305 static struct ooh323_config
306 {
307    int  mTCPPortStart;
308    int  mTCPPortEnd;
309 } ooconfig;
310
311 /** Asterisk RTP stuff*/
312 static struct sched_context *sched;
313 static struct io_context *io;
314
315 /* Protect the monitoring thread, so only one process can kill or start it, 
316    and not when it's doing something critical. */
317 AST_MUTEX_DEFINE_STATIC(monlock);
318
319
320 /* This is the thread for the monitor which checks for input on the channels
321    which are not currently in use.  */
322 static pthread_t monitor_thread = AST_PTHREADT_NULL;
323
324
325 static struct ast_channel *ooh323_new(struct ooh323_pvt *i, int state,
326                                              const char *host, int capability, const char *linkedid) 
327 {
328         struct ast_channel *ch = NULL;
329         int fmt = 0;
330         if (gH323Debug)
331                 ast_verbose("---   ooh323_new - %s, %d\n", host, capability);
332
333
334         /* Don't hold a h323 pvt lock while we allocate a channel */
335         ast_mutex_unlock(&i->lock);
336         ch = ast_channel_alloc(1, state, i->callerid_num, i->callerid_name, 
337                                 i->accountcode, i->exten, i->context, linkedid, i->amaflags,
338                                 "OOH323/%s-%ld", host, callnumber);
339         ast_mutex_lock(&ooh323c_cn_lock);
340         callnumber++;
341         ast_mutex_unlock(&ooh323c_cn_lock);
342    
343         ast_mutex_lock(&i->lock);
344
345         if (ch) {
346                 ast_channel_lock(ch);
347                 ch->tech = &ooh323_tech;
348
349                 if (capability)
350                         fmt = ast_best_codec(capability);
351                 if (!fmt) 
352                         fmt = ast_codec_pref_index(&i->prefs, 0);
353
354                 ch->nativeformats = ch->rawwriteformat = ch->rawreadformat = fmt;
355
356                 ast_channel_set_fd(ch, 0, ast_rtp_instance_fd(i->rtp, 0));
357                 ast_channel_set_fd(ch, 1, ast_rtp_instance_fd(i->rtp, 1));
358                 ast_channel_set_fd(ch, 5, ast_udptl_fd(i->udptl));
359
360                 ast_jb_configure(ch, &global_jbconf);
361
362                 if (state == AST_STATE_RING)
363                         ch->rings = 1;
364
365                 ch->adsicpe = AST_ADSI_UNAVAILABLE;
366                 ast_set_write_format(ch, fmt);
367                 ast_set_read_format(ch, fmt);
368                 ch->tech_pvt = i;
369                 i->owner = ch;
370                 ast_module_ref(myself);
371
372                 /* Allocate dsp for in-band DTMF support */
373                 if (i->dtmfmode & H323_DTMF_INBAND) {
374                         i->vad = ast_dsp_new();
375                         ast_dsp_set_features(i->vad, DSP_FEATURE_DIGIT_DETECT);
376                         ast_dsp_set_features(i->vad,
377                                                 DSP_FEATURE_DIGIT_DETECT | DSP_FEATURE_FAX_DETECT);
378                         ast_dsp_set_faxmode(i->vad,
379                                                 DSP_FAXMODE_DETECT_CNG | DSP_FAXMODE_DETECT_CED);
380
381                         if (i->dtmfmode & H323_DTMF_INBANDRELAX)
382                                 ast_dsp_set_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
383                 }
384
385                 ast_mutex_lock(&usecnt_lock);
386                 usecnt++;
387                 ast_mutex_unlock(&usecnt_lock);
388
389                 /* Notify the module monitors that use count for resource has changed*/
390                 ast_update_use_count();
391
392                 ast_copy_string(ch->context, i->context, sizeof(ch->context));
393                 ast_copy_string(ch->exten, i->exten, sizeof(ch->exten));
394
395                 ch->priority = 1;
396
397                 if(!ast_test_flag(i, H323_OUTGOING)) {
398                 
399                         if (!ast_strlen_zero(i->caller_h323id)) {
400                                 pbx_builtin_setvar_helper(ch, "_CALLER_H323ID", i->caller_h323id);
401
402                         }
403                         if (!ast_strlen_zero(i->caller_dialedDigits)) {
404                                 pbx_builtin_setvar_helper(ch, "_CALLER_H323DIALEDDIGITS", 
405                                 i->caller_dialedDigits);
406                         }
407                         if (!ast_strlen_zero(i->caller_email)) {
408                                 pbx_builtin_setvar_helper(ch, "_CALLER_H323EMAIL", 
409                                 i->caller_email);
410                         }
411                         if (!ast_strlen_zero(i->caller_url)) {
412                                 pbx_builtin_setvar_helper(ch, "_CALLER_H323URL", i->caller_url);
413                         }
414                 }
415
416                 if (!ast_strlen_zero(i->accountcode))
417                         ast_string_field_set(ch, accountcode, i->accountcode);
418                 
419                 if (i->amaflags)
420                         ch->amaflags = i->amaflags;
421
422                 ast_setstate(ch, state);
423                 if (state != AST_STATE_DOWN) {
424                         if (ast_pbx_start(ch)) {
425                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ch->name);
426                                 ast_channel_unlock(ch);
427                                 ast_hangup(ch);
428                                 ch = NULL;
429                         } 
430                 }
431
432                 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate", "Channel: %s\r\nChanneltype: %s\r\n"
433                                 "CallRef: %d\r\n", ch->name, "OOH323", i->call_reference);
434         } else
435                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
436
437
438         if(ch)   ast_channel_unlock(ch);
439
440         if (gH323Debug)
441                 ast_verbose("+++   h323_new\n");
442
443         return ch;
444 }
445
446
447
448 static struct ooh323_pvt *ooh323_alloc(int callref, char *callToken) 
449 {
450         struct ooh323_pvt *pvt = NULL;
451         struct sockaddr_in ouraddr;
452         struct in_addr ipAddr;
453         if (gH323Debug)
454                 ast_verbose("---   ooh323_alloc\n");
455
456         if (!(pvt = ast_calloc(1, sizeof(*pvt)))) {
457                 ast_log(LOG_ERROR, "Couldn't allocate private ooh323 structure\n");
458                 return NULL;
459         }
460
461         ast_mutex_init(&pvt->lock);
462         ast_mutex_lock(&pvt->lock);
463
464
465         if (!inet_aton(gIP, &ipAddr)) {
466                 ast_log(LOG_ERROR, "Invalid OOH323 driver ip address\n");
467                 ast_mutex_unlock(&pvt->lock);
468                 ast_mutex_destroy(&pvt->lock);
469                 ast_free(pvt);
470                 return NULL;
471         }
472
473         ouraddr.sin_addr = ipAddr;
474         if (!(pvt->rtp = ast_rtp_instance_new("asterisk", sched, &ouraddr, NULL))) {
475                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", 
476                                   strerror(errno));
477                 ast_mutex_unlock(&pvt->lock);
478                 ast_mutex_destroy(&pvt->lock);
479                 ast_free(pvt);
480                 return NULL;
481         }
482  
483         ast_rtp_instance_set_qos(pvt->rtp, gTOS, 0, "ooh323-rtp");
484
485         if (!(pvt->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, ipAddr))) {
486                 ast_log(LOG_WARNING, "Unable to create UDPTL session: %s\n",
487                                 strerror(errno));
488                 ast_mutex_unlock(&pvt->lock);
489                 ast_mutex_destroy(&pvt->lock);
490                 ast_free(pvt);
491                 return NULL;
492         }
493
494         ast_udptl_set_error_correction_scheme(pvt->udptl, UDPTL_ERROR_CORRECTION_NONE);
495         pvt->faxmode = 0;
496         pvt->t38support = gT38Support;
497         pvt->rtptimeout = gRTPTimeout;
498
499         pvt->call_reference = callref;
500         if (callToken)
501                 pvt->callToken = strdup(callToken);
502
503         /* whether to use gk for this call */
504         if (gRasGkMode == RasNoGatekeeper)
505                 OO_SETFLAG(pvt->flags, H323_DISABLEGK);
506
507         pvt->dtmfmode = gDTMFMode;
508         pvt->dtmfcodec = gDTMFCodec;
509         ast_copy_string(pvt->context, gContext, sizeof(pvt->context));
510         ast_copy_string(pvt->accountcode, gAccountcode, sizeof(pvt->accountcode));
511
512         pvt->amaflags = gAMAFLAGS;
513         pvt->capability = gCapability;
514         memcpy(&pvt->prefs, &gPrefs, sizeof(pvt->prefs));
515
516         ast_mutex_unlock(&pvt->lock); 
517         /* Add to interface list */
518         ast_mutex_lock(&iflock);
519         pvt->next = iflist;
520         iflist = pvt;
521         ast_mutex_unlock(&iflock);
522
523         if (gH323Debug)
524                 ast_verbose("+++   ooh323_alloc\n");
525
526         return pvt;
527 }
528
529
530 /*
531         Possible data values - peername, exten/peername, exten@ip
532  */
533 static struct ast_channel *ooh323_request(const char *type, int format,
534                 const struct ast_channel *requestor, void *data, int *cause)
535
536 {
537         struct ast_channel *chan = NULL;
538         struct ooh323_pvt *p = NULL;
539         struct ooh323_peer *peer = NULL;
540         char *dest = NULL; 
541         char *ext = NULL;
542         char tmp[256];
543         char formats[FORMAT_STRING_SIZE];
544         int oldformat;
545         int port = 0;
546
547         if (gH323Debug)
548                 ast_verbose("---   ooh323_request - data %s format %s\n", (char*)data,  
549                                                                                 ast_getformatname_multiple(formats,FORMAT_STRING_SIZE,format));
550
551         oldformat = format;
552         format &= AST_FORMAT_AUDIO_MASK;
553         if (!format) {
554                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format "
555                                                                   "'%d'\n", format);
556                 return NULL;
557         }
558
559         p = ooh323_alloc(0,0); /* Initial callRef is zero */
560
561         if (!p) {
562                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char*)data);
563                 return NULL;
564         }
565         ast_mutex_lock(&p->lock);
566
567         /* This is an outgoing call, since ooh323_request is called */
568         ast_set_flag(p, H323_OUTGOING);
569
570
571         ast_copy_string(tmp, data, sizeof(tmp));
572
573         dest = strchr(tmp, '/');
574
575         if (dest) {  
576                 *dest = '\0';
577                 dest++;
578                 ext = dest;
579                 dest = tmp;
580         } else if ((dest = strchr(tmp, '@'))) {
581                 *dest = '\0';
582                 dest++;
583                 ext = tmp;
584         } else {
585                 dest = tmp;
586                 ext = NULL;
587         }
588
589 #if 0
590         if ((sport = strchr(dest, ':'))) {
591                 *sport = '\0';
592                 sport++;
593                 port = atoi(sport);
594         }
595 #endif
596
597         if (dest) {
598                 peer = find_peer(dest, port);
599         } else{
600                 ast_log(LOG_ERROR, "Destination format is not supported\n");
601                 return NULL;
602         }
603
604         if (peer) {
605                 p->username = strdup(peer->name);
606                 p->host = strdup(peer->ip);
607                 p->port = peer->port;
608                 /* Disable gk as we are going to call a known peer*/
609                 /* OO_SETFLAG(p->flags, H323_DISABLEGK); */
610
611                 if (ext)
612                         ast_copy_string(p->exten, ext, sizeof(p->exten));
613
614                 p->capability = peer->capability;
615                 memcpy(&p->prefs, &peer->prefs, sizeof(struct ast_codec_pref));
616                 p->dtmfmode |= peer->dtmfmode;
617                 p->dtmfcodec  = peer->dtmfcodec;
618                 p->t38support = peer->t38support;
619                 p->rtptimeout = peer->rtptimeout;
620                 if (peer->rtpmask && peer->rtpmaskstr[0]) {
621                         p->rtpmask = peer->rtpmask;
622                         ast_copy_string(p->rtpmaskstr, peer->rtpmaskstr, sizeof(p->rtpmaskstr));
623                 }
624                 ast_copy_string(p->accountcode, peer->accountcode, sizeof(p->accountcode));
625                 p->amaflags = peer->amaflags;
626         } else {
627                 p->dtmfmode = gDTMFMode;
628                 p->dtmfcodec = gDTMFCodec;
629                 p->t38support = gT38Support;
630                 p->rtptimeout = gRTPTimeout;
631                 p->capability = gCapability;
632
633                 memcpy(&p->prefs, &gPrefs, sizeof(struct ast_codec_pref));
634                 p->username = strdup(dest);
635
636                 p->host = strdup(dest);
637                 if (port > 0) {
638                         p->port = port;
639                 }
640                 if (ext) {
641                         ast_copy_string(p->exten, ext, sizeof(p->exten));
642                 }
643         }
644
645
646         chan = ooh323_new(p, AST_STATE_DOWN, p->username, format,
647                                  requestor ? requestor->linkedid : NULL);
648         
649         ast_mutex_unlock(&p->lock);
650
651         if (!chan) {
652                 ast_mutex_lock(&iflock);
653                 ooh323_destroy(p);
654                 ast_mutex_unlock(&iflock);
655    } else {
656       ast_mutex_lock(&p->lock);
657       p->callToken = (char*)ast_malloc(AST_MAX_EXTENSION);
658       if(!p->callToken)
659       {
660        ast_mutex_unlock(&p->lock);
661        ast_mutex_lock(&iflock);
662        ooh323_destroy(p);
663        ast_mutex_unlock(&iflock);
664        ast_log(LOG_ERROR, "Failed to allocate memory for callToken\n");
665        return NULL;
666       }
667
668       ast_mutex_unlock(&p->lock);
669       ast_mutex_lock(&ooh323c_cmd_lock);
670       ooMakeCall(data, p->callToken, AST_MAX_EXTENSION, NULL);
671       ast_mutex_unlock(&ooh323c_cmd_lock);
672         }
673
674         restart_monitor();
675         if (gH323Debug)
676                 ast_verbose("+++   ooh323_request\n");
677
678         return chan;
679
680 }
681
682
683 static struct ooh323_pvt* find_call(ooCallData *call)
684 {
685         struct ooh323_pvt *p;
686
687         if (gH323Debug)
688                 ast_verbose("---   find_call\n");
689
690         ast_mutex_lock(&iflock);
691
692         for (p = iflist; p; p = p->next) {
693                 if (p->callToken && !strcmp(p->callToken, call->callToken)) {
694                         break;
695                 }
696         }
697         ast_mutex_unlock(&iflock);
698
699         if (gH323Debug)
700                 ast_verbose("+++   find_call\n");
701
702         return p;
703 }
704
705 struct ooh323_user *find_user(const char * name, const char* ip)
706 {
707         struct ooh323_user *user;
708
709         if (gH323Debug)
710       ast_verbose("---   find_user: %s, %s\n",name,ip);
711
712         ast_mutex_lock(&userl.lock);
713
714         for (user = userl.users; user; user = user->next) {
715                 if (ip && user->mUseIP && !strcmp(user->mIP, ip)) {
716                         break;
717                 }
718                 if (name && !strcmp(user->name, name)) {
719                         break;
720                 }
721         }
722
723         ast_mutex_unlock(&userl.lock);
724
725         if (gH323Debug)
726                 ast_verbose("+++   find_user\n");
727
728         return user;
729 }
730
731 struct ooh323_peer *find_friend(const char *name, int port)
732 {
733         struct ooh323_peer *peer;  
734
735         if (gH323Debug)
736                 ast_verbose("---   find_friend \"%s\"\n", name);
737
738
739         ast_mutex_lock(&peerl.lock);
740         for (peer = peerl.peers; peer; peer = peer->next) {
741                 if (gH323Debug) {
742                         ast_verbose("           comparing with \"%s\"\n", peer->ip);
743                 }
744                 if (!strcmp(peer->ip, name)) {
745                         if (port <= 0 || (port > 0 && peer->port == port)) {
746                                 break;
747                         }
748                 }
749         }
750         ast_mutex_unlock(&peerl.lock);
751
752         if (gH323Debug) {
753                 if (peer) {
754                         ast_verbose("           found matching friend\n");
755                 }
756                 ast_verbose("+++   find_friend \"%s\"\n", name);
757         }
758
759         return peer;            
760 }
761
762
763 struct ooh323_peer *find_peer(const char * name, int port)
764 {
765         struct ooh323_peer *peer;
766
767         if (gH323Debug)
768                 ast_verbose("---   find_peer \"%s\"\n", name);
769
770
771         ast_mutex_lock(&peerl.lock);
772         for (peer = peerl.peers; peer; peer = peer->next) {
773                 if (gH323Debug) {
774                         ast_verbose("           comparing with \"%s\"\n", peer->ip);
775                 }
776                 if (!strcasecmp(peer->name, name))
777                         break;
778                 if (peer->h323id && !strcasecmp(peer->h323id, name))
779                         break;
780                 if (peer->e164 && !strcasecmp(peer->e164, name))
781                         break;
782                 /*
783                 if (!strcmp(peer->ip, name)) {
784                         if (port > 0 && peer->port == port) { break; }
785                         else if (port <= 0) { break; }
786                 }
787                 */
788         }
789         ast_mutex_unlock(&peerl.lock);
790
791         if (gH323Debug) {
792                 if (peer) {
793                         ast_verbose("           found matching peer\n");
794                 }
795                 ast_verbose("+++   find_peer \"%s\"\n", name);
796         }
797
798         return peer;            
799 }
800
801 static int ooh323_digit_begin(struct ast_channel *chan, char digit)
802 {
803         char dtmf[2];
804         struct ooh323_pvt *p = (struct ooh323_pvt *) chan->tech_pvt;
805         
806         if (gH323Debug)
807                 ast_verbose("---   ooh323_digit_begin\n");
808
809         if (!p) {
810                 ast_log(LOG_ERROR, "No private structure for call\n");
811                 return -1;
812         }
813         ast_mutex_lock(&p->lock);
814
815
816         if (digit == 'e' && !p->faxmode && p->t38support != T38_DISABLED)  {
817                 if (!p->chmodepend) {
818                         if (gH323Debug)
819                                 ast_verbose("request to change %s to t.38 because fax cng\n",
820                                                 p->callToken);
821                         p->chmodepend = 1;
822                         ooRequestChangeMode(p->callToken, 1);
823                 }
824
825         } else if (p->rtp && ((p->dtmfmode & H323_DTMF_RFC2833) || (p->dtmfmode & H323_DTMF_CISCO))) {
826                 ast_rtp_instance_dtmf_begin(p->rtp, digit);
827         } else if (((p->dtmfmode & H323_DTMF_Q931) ||
828                                                  (p->dtmfmode & H323_DTMF_H245ALPHANUMERIC) ||
829                                                  (p->dtmfmode & H323_DTMF_H245SIGNAL))) {
830                 dtmf[0] = digit;
831                 dtmf[1] = '\0';
832                 ooSendDTMFDigit(p->callToken, dtmf);
833         }
834         ast_mutex_unlock(&p->lock);
835         if (gH323Debug)
836                 ast_verbose("+++   ooh323_digit_begin\n");
837
838         return 0;
839 }
840
841 static int ooh323_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
842 {
843         struct ooh323_pvt *p = (struct ooh323_pvt *) chan->tech_pvt;
844
845         if (gH323Debug)
846                 ast_verbose("---   ooh323_digit_end\n");
847
848         if (!p) {
849                 ast_log(LOG_ERROR, "No private structure for call\n");
850                 return -1;
851         }
852         ast_mutex_lock(&p->lock);
853         if (p->rtp && ((p->dtmfmode & H323_DTMF_RFC2833) || (p->dtmfmode & H323_DTMF_CISCO)) ) 
854                 ast_rtp_instance_dtmf_end(p->rtp, digit);
855
856         ast_mutex_unlock(&p->lock);
857         if (gH323Debug)
858                 ast_verbose("+++   ooh323_digit_end\n");
859
860         return 0;
861 }
862
863
864 static int ooh323_call(struct ast_channel *ast, char *dest, int timeout)
865 {
866         struct ooh323_pvt *p = ast->tech_pvt;
867         char destination[256];
868         int res=0, i;
869         const char *val = NULL;
870         ooCallOptions opts = {
871                 .fastStart = TRUE,
872                 .tunneling = TRUE,
873                 .disableGk = TRUE,
874                 .callMode = OO_CALLMODE_AUDIOCALL,
875                 .transfercap = 0
876         };
877
878         if (gH323Debug)
879                 ast_verbose("---   ooh323_call- %s\n", dest);
880
881
882    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) 
883    {
884                 ast_log(LOG_WARNING, "ooh323_call called on %s, neither down nor "
885                                                                         "reserved\n", ast->name);
886                 return -1;
887         }
888         ast_mutex_lock(&p->lock);
889         ast_set_flag(p, H323_OUTGOING);
890         if (ast->connected.id.number) {
891                 if(p->callerid_num)   free(p->callerid_num);
892                 p->callerid_num = strdup(ast->connected.id.number);
893         }
894
895         if (ast->connected.id.name) {
896                 if(p->callerid_name)
897                         free(p->callerid_name);
898                 p->callerid_name = strdup(ast->connected.id.name);
899         } else {
900                 ast->connected.id.name = strdup(gCallerID);
901                 if(p->callerid_name)
902                         free(p->callerid_name);
903                 p->callerid_name = strdup(ast->connected.id.name);
904         }
905
906         /* Retrieve vars */
907
908
909         if ((val = pbx_builtin_getvar_helper(ast, "CALLER_H323ID"))) {
910                 ast_copy_string(p->caller_h323id, val, sizeof(p->caller_h323id));
911         }
912         
913         if ((val = pbx_builtin_getvar_helper(ast, "CALLER_H323DIALEDDIGITS"))) {
914                 ast_copy_string(p->caller_dialedDigits, val, sizeof(p->caller_dialedDigits));
915                 if(!p->callerid_num)
916                         p->callerid_num = strdup(val);
917         }
918
919         if ((val = pbx_builtin_getvar_helper(ast, "CALLER_H323EMAIL"))) {
920                 ast_copy_string(p->caller_email, val, sizeof(p->caller_email));
921         }
922
923         if ((val = pbx_builtin_getvar_helper(ast, "CALLER_H323URL"))) {
924                 ast_copy_string(p->caller_url, val, sizeof(p->caller_url));
925         }
926
927         if (p->host && p->port != 0)
928                 snprintf(destination, sizeof(destination), "%s:%d", p->host, p->port);
929         else if (p->host)
930                 snprintf(destination, sizeof(destination), "%s", p->host);
931         else
932                 ast_copy_string(destination, dest, sizeof(destination));
933
934    destination[sizeof(destination)-1]='\0';
935
936    opts.transfercap = ast->transfercapability;
937
938    for (i=0;i<480 && !isRunning(p->callToken);i++) usleep(12000);
939
940    if(OO_TESTFLAG(p->flags, H323_DISABLEGK)) {
941       res = ooRunCall(destination, p->callToken, AST_MAX_EXTENSION, &opts);
942    } else {
943       res = ooRunCall(destination, p->callToken, AST_MAX_EXTENSION, NULL);
944    }
945
946         ast_mutex_unlock(&p->lock);
947         if (res != OO_OK) {
948                 ast_log(LOG_ERROR, "Failed to make call\n");
949                 return -1; /* ToDO: cleanup */
950         }
951         if (gH323Debug)
952                 ast_verbose("+++   ooh323_call\n");
953
954   return 0;
955 }
956
957 static int ooh323_hangup(struct ast_channel *ast)
958 {
959         struct ooh323_pvt *p = ast->tech_pvt;
960         int q931cause = AST_CAUSE_NORMAL_CLEARING;
961
962         if (gH323Debug)
963                 ast_verbose("---   ooh323_hangup\n");
964
965         if (p) {
966                 ast_mutex_lock(&p->lock);
967
968         if (ast->hangupcause) {
969                 q931cause = ast->hangupcause;
970         } else {
971                 const char *cause = pbx_builtin_getvar_helper(ast, "DIALSTATUS");
972                 if (cause) {
973                         if (!strcmp(cause, "CONGESTION")) {
974                                 q931cause = AST_CAUSE_NORMAL_CIRCUIT_CONGESTION;
975                         } else if (!strcmp(cause, "BUSY")) {
976                                 q931cause = AST_CAUSE_USER_BUSY;
977                         } else if (!strcmp(cause, "CHANISUNVAIL")) {
978                                 q931cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL;
979                         } else if (!strcmp(cause, "NOANSWER")) {
980                                 q931cause = AST_CAUSE_NO_ANSWER;
981                         } else if (!strcmp(cause, "CANCEL")) {
982                                 q931cause = AST_CAUSE_CALL_REJECTED;
983                         }
984                 }
985         }
986
987
988
989                 if (gH323Debug)
990                         ast_verbose("    hanging %s with cause: %d\n", p->username, q931cause);
991                 ast->tech_pvt = NULL; 
992                 if (!ast_test_flag(p, H323_ALREADYGONE)) {
993                         ooHangCall(p->callToken, 
994                                 ooh323_convert_hangupcause_asteriskToH323(q931cause), q931cause);
995                         ast_set_flag(p, H323_ALREADYGONE);
996                         /* ast_mutex_unlock(&p->lock); */
997                 } else 
998                         ast_set_flag(p, H323_NEEDDESTROY);
999                 /* detach channel here */
1000                 if (p->owner) {
1001                         p->owner->tech_pvt = NULL;
1002                         p->owner = NULL;
1003                         ast_module_unref(myself);
1004                 }
1005
1006                 ast_mutex_unlock(&p->lock);
1007                 ast_mutex_lock(&usecnt_lock);
1008                 usecnt--;
1009                 ast_mutex_unlock(&usecnt_lock);
1010
1011                 /* Notify the module monitors that use count for resource has changed */
1012                 ast_update_use_count();
1013           
1014         } else {
1015                 ast_log(LOG_DEBUG, "No call to hangup\n" );
1016         }
1017         
1018         if (gH323Debug)
1019                 ast_verbose("+++   ooh323_hangup\n");
1020
1021   return 0;
1022 }
1023
1024 static int ooh323_answer(struct ast_channel *ast)
1025 {
1026         struct ooh323_pvt *p = ast->tech_pvt;
1027
1028         if (gH323Debug)
1029                 ast_verbose("--- ooh323_answer\n");
1030
1031         if (p) {
1032
1033                 ast_mutex_lock(&p->lock);
1034                 if (ast->_state != AST_STATE_UP) {
1035                         ast_channel_lock(ast);
1036                         ast_setstate(ast, AST_STATE_UP);
1037                         if (option_debug)
1038                                 ast_debug(1, "ooh323_answer(%s)\n", ast->name);
1039                         ast_channel_unlock(ast);
1040                         ooAnswerCall(p->callToken);
1041                 }
1042                 ast_mutex_unlock(&p->lock);
1043         }
1044
1045         if (gH323Debug)
1046                 ast_verbose("+++ ooh323_answer\n");
1047
1048   return 0;
1049 }
1050
1051 static struct ast_frame *ooh323_read(struct ast_channel *ast)
1052 {
1053         struct ast_frame *fr;
1054         static struct ast_frame null_frame = { AST_FRAME_NULL, };
1055         struct ooh323_pvt *p = ast->tech_pvt;
1056
1057         if (!p) return &null_frame;
1058
1059         ast_mutex_lock(&p->lock);
1060         if (p->rtp)
1061                 fr = ooh323_rtp_read(ast, p);
1062         else
1063                 fr = &null_frame;
1064         /* time(&p->lastrtprx); */
1065         ast_mutex_unlock(&p->lock);
1066         return fr;
1067 }
1068
1069 static int ooh323_write(struct ast_channel *ast, struct ast_frame *f)
1070 {
1071         struct ooh323_pvt *p = ast->tech_pvt;
1072         int res = 0;
1073
1074         if (p) {
1075                 ast_mutex_lock(&p->lock);
1076
1077                 if (f->frametype == AST_FRAME_MODEM) {
1078                         ast_debug(1, "Send UDPTL %d/%d len %d for %s\n",
1079                                 f->frametype, f->subclass, f->datalen, ast->name);
1080                         if (p->udptl)
1081                                 res = ast_udptl_write(p->udptl, f);
1082                         ast_mutex_unlock(&p->lock);
1083                         return res;
1084                 }
1085
1086         
1087                 if (f->frametype == AST_FRAME_VOICE) {
1088 /* sending progress for first */
1089                         if (!ast_test_flag(p, H323_OUTGOING) && !p->progsent &&
1090                                         p->callToken) {
1091                                 ooManualProgress(p->callToken);
1092                                 p->progsent = 1;
1093                         }
1094
1095
1096                         if (!(f->subclass & ast->nativeformats)) {
1097                                 if (ast->nativeformats != 0) {
1098                                         ast_log(LOG_WARNING, "Asked to transmit frame type %d,"
1099                                                 " while native "
1100                                                  "formats is %d (read/write = %d/%d)\n",
1101                                                 f->subclass, ast->nativeformats, ast->readformat,
1102                                                                                 ast->writeformat);
1103                                         ast_set_write_format(ast, f->subclass);
1104                                 } else {
1105                                         /* ast_set_write_format(ast, f->subclass);
1106                                         ast->nativeformats = f->subclass; */
1107                                 }
1108                         ast_mutex_unlock(&p->lock);
1109                         return 0;
1110                         }
1111
1112                 if (p->rtp)
1113                         res = ast_rtp_instance_write(p->rtp, f);
1114
1115                 ast_mutex_unlock(&p->lock);
1116
1117                 } else if (f->frametype == AST_FRAME_IMAGE) {
1118                         ast_mutex_unlock(&p->lock);
1119                         return 0;
1120                 } else {
1121                         ast_log(LOG_WARNING, "Can't send %d type frames with OOH323 write\n", 
1122                                                                          f->frametype);
1123                         ast_mutex_unlock(&p->lock);
1124                         return 0;
1125                 }
1126
1127         }
1128
1129         return res;
1130 }
1131
1132 static int ooh323_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1133 {
1134
1135         struct ooh323_pvt *p = (struct ooh323_pvt *) ast->tech_pvt;
1136         char *callToken = (char *)NULL;
1137
1138         if (!p) return -1;
1139
1140         ast_mutex_lock(&p->lock);
1141         callToken = (p->callToken ? strdup(p->callToken) : NULL);
1142         ast_mutex_unlock(&p->lock);
1143
1144         if (!callToken) {
1145                 if (gH323Debug)
1146                         ast_verbose("   ooh323_indicate - No callToken\n");
1147                 return -1;
1148         }
1149
1150         if (gH323Debug)
1151                 ast_verbose("----- ooh323_indicate %d on call %s\n", condition, callToken);
1152          
1153         ast_mutex_lock(&p->lock);
1154         switch (condition) {
1155         case AST_CONTROL_CONGESTION:
1156                 if (!ast_test_flag(p, H323_ALREADYGONE)) {
1157                         ooHangCall(callToken, OO_REASON_LOCAL_CONGESTED, 
1158                                                 AST_CAUSE_SWITCH_CONGESTION);
1159                         ast_set_flag(p, H323_ALREADYGONE);
1160                 }
1161                 break;
1162         case AST_CONTROL_BUSY:
1163                 if (!ast_test_flag(p, H323_ALREADYGONE)) {
1164                         ooHangCall(callToken, OO_REASON_LOCAL_BUSY, AST_CAUSE_USER_BUSY);
1165                         ast_set_flag(p, H323_ALREADYGONE);
1166                 }
1167                 break;
1168         case AST_CONTROL_HOLD:
1169                 ast_moh_start(ast, data, NULL);         
1170                 break;
1171         case AST_CONTROL_UNHOLD:
1172                 ast_moh_stop(ast);
1173                 break;
1174         case AST_CONTROL_PROGRESS:
1175                 if (ast->_state != AST_STATE_UP) {
1176                         if (!p->progsent) {
1177                                 if (gH323Debug) 
1178                                         ast_log(LOG_DEBUG,"Sending manual progress for %s, res = %d\n", callToken,
1179                                         ooManualProgress(callToken));   
1180                                 else
1181                                         ooManualProgress(callToken);
1182                                 p->progsent = 1;
1183                         }
1184                 }
1185             break;
1186       case AST_CONTROL_RINGING:
1187             if (ast->_state == AST_STATE_RING || ast->_state == AST_STATE_RINGING) {
1188                 if (gH323Debug) 
1189                         ast_log(LOG_DEBUG,"Sending manual ringback for %s, res = %d\n", 
1190                         callToken,
1191                         ooManualRingback(callToken));
1192                  else
1193                         ooManualRingback(callToken);
1194             }
1195          break;
1196       case AST_CONTROL_SRCUPDATE:
1197                 ast_rtp_instance_new_source(p->rtp);
1198                 break;
1199
1200       case AST_CONTROL_T38_PARAMETERS:
1201                 if (p->t38support != T38_ENABLED) {
1202                         struct ast_control_t38_parameters parameters = { .request_response = 0 };
1203                         parameters.request_response = AST_T38_REFUSED;
1204                         ast_queue_control_data(ast, AST_CONTROL_T38_PARAMETERS,
1205                                                  &parameters, sizeof(parameters));
1206                         break;
1207                 }
1208                 if (datalen != sizeof(struct ast_control_t38_parameters)) {
1209                         ast_log(LOG_ERROR, "Invalid datalen for AST_CONTROL_T38. "
1210                                            "Expected %d, got %d\n",
1211                                 (int)sizeof(enum ast_control_t38), (int)datalen);
1212                 } else {
1213                         const struct ast_control_t38_parameters *parameters = data;
1214                         enum ast_control_t38 message = parameters->request_response;
1215                         switch (message) {
1216
1217                         case AST_T38_REQUEST_NEGOTIATE:
1218
1219                                 if (!p->chmodepend && !p->faxmode) {
1220                                         ooRequestChangeMode(p->callToken, 1);
1221                                         p->chmodepend = 1;
1222                                 }
1223                                 break;
1224
1225                         case AST_T38_REQUEST_TERMINATE:
1226
1227                                 if (!p->chmodepend && p->faxmode) {
1228                                         ooRequestChangeMode(p->callToken, 0);
1229                                         p->chmodepend = 1;
1230                                 }
1231                                 break;
1232
1233
1234                         default:
1235                                 ;
1236
1237                         }
1238
1239                 }
1240                 break;
1241       case AST_CONTROL_PROCEEDING:
1242         case -1:
1243                 break;
1244         default:
1245                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d on %s\n",
1246                                                                         condition, callToken);
1247         }
1248
1249         ast_mutex_unlock(&p->lock);
1250
1251         if (gH323Debug)
1252                 ast_verbose("++++  ooh323_indicate %d on %s\n", condition, callToken);
1253
1254         free(callToken);
1255         return -1;
1256 }
1257
1258 static int ooh323_queryoption(struct ast_channel *ast, int option, void *data, int *datalen)
1259 {
1260
1261         struct ooh323_pvt *p = (struct ooh323_pvt *) ast->tech_pvt;
1262         int res = -1;
1263         enum ast_t38_state state = T38_STATE_UNAVAILABLE;
1264         char* cp;
1265
1266         if (!p) return -1;
1267
1268         ast_mutex_lock(&p->lock);
1269
1270         if (gH323Debug)
1271                 ast_verbose("----- ooh323_queryoption %d on channel %s\n", option, ast->name);
1272          
1273         switch (option) {
1274
1275                 case AST_OPTION_T38_STATE:
1276
1277                         if (*datalen != sizeof(enum ast_t38_state)) {
1278                                 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option."
1279                                 " Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
1280                                 break;
1281                         }
1282                         if (p->t38support != T38_DISABLED)
1283                                 state = T38_STATE_UNKNOWN;
1284                         if (p->faxmode)
1285                                 state = (p->chmodepend) ? T38_STATE_UNKNOWN : T38_STATE_NEGOTIATED;
1286                         else if (p->chmodepend)
1287                                 state = T38_STATE_NEGOTIATING;
1288
1289
1290                         *((enum ast_t38_state *) data) = state;
1291                         res = 0;
1292                         break;
1293
1294
1295                 case AST_OPTION_DIGIT_DETECT:
1296
1297                         cp = (char *) data;
1298                         *cp = p->vad ? 1 : 0;
1299                         ast_debug(1, "Reporting digit detection %sabled on %s\n",
1300                                                          *cp ? "en" : "dis", ast->name);
1301
1302                         res = 0;
1303                         break;
1304
1305                 default:        ;
1306
1307         }
1308
1309         if (gH323Debug)
1310                 ast_verbose("+++++ ooh323_queryoption %d on channel %s\n", option, ast->name);
1311          
1312         ast_mutex_unlock(&p->lock);
1313
1314         return res;
1315 }
1316
1317
1318
1319 static int ooh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1320 {
1321         struct ooh323_pvt *p = newchan->tech_pvt;
1322
1323         if (gH323Debug)
1324                 ast_verbose("--- ooh323c ooh323_fixup\n");
1325
1326         ast_mutex_lock(&p->lock);
1327         if (p->owner != oldchan) {
1328                 ast_log(LOG_WARNING, "Old channel wasn't %p but was %p\n", oldchan, p->owner);
1329                 ast_mutex_unlock(&p->lock);
1330                 return -1;
1331         }
1332
1333         if (p->owner == oldchan) {
1334                 p->owner = newchan;
1335         } else {
1336                 p->owner = oldchan;
1337         }
1338
1339         ast_mutex_unlock(&p->lock);
1340
1341         if (gH323Debug)
1342                 ast_verbose("+++ ooh323c ooh323_fixup \n");
1343
1344         return 0;
1345 }
1346
1347
1348 void ooh323_set_write_format(ooCallData *call, int fmt, int txframes)
1349 {
1350         struct ooh323_pvt *p = NULL;
1351         char formats[FORMAT_STRING_SIZE];
1352
1353         if (gH323Debug)
1354                 ast_verbose("---   ooh323_update_writeformat %s/%d\n", 
1355                                 ast_getformatname_multiple(formats,FORMAT_STRING_SIZE, fmt), txframes);
1356         
1357         p = find_call(call);
1358         if (!p) {
1359                 ast_log(LOG_ERROR, "No matching call found for %s\n", call->callToken);
1360                 return;
1361         }
1362
1363         ast_mutex_lock(&p->lock);
1364
1365         p->writeformat = fmt;
1366
1367         if (p->owner) {
1368                 while (p->owner && ast_channel_trylock(p->owner)) {
1369                         ast_debug(1,"Failed to grab lock, trying again\n");
1370                         DEADLOCK_AVOIDANCE(&p->lock);
1371                 }
1372                 if (!p->owner) {
1373                         ast_mutex_unlock(&p->lock);
1374                         ast_log(LOG_ERROR, "Channel has no owner\n");
1375                         return;
1376                 }
1377                 if (gH323Debug)
1378                         ast_verbose("Writeformat before update %s/%s\n", 
1379                           ast_getformatname_multiple(formats,FORMAT_STRING_SIZE, p->owner->writeformat),
1380                           ast_getformatname_multiple(formats,FORMAT_STRING_SIZE, p->owner->nativeformats));
1381                 if (txframes)
1382                         ast_codec_pref_setsize(&p->prefs, fmt, txframes);
1383                 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
1384                 if (p->dtmfmode & H323_DTMF_RFC2833 && p->dtmfcodec) {
1385                         ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(p->rtp),
1386                                  p->rtp, p->dtmfcodec, "audio", "telephone-event", 0);
1387                 }
1388                 if (p->dtmfmode & H323_DTMF_CISCO && p->dtmfcodec) {
1389                         ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(p->rtp),
1390                                  p->rtp, p->dtmfcodec, "audio", "cisco-telephone-event", 0);
1391                 }
1392
1393                 p->owner->nativeformats = fmt;
1394                 ast_set_write_format(p->owner, p->owner->writeformat);
1395                 ast_set_read_format(p->owner, p->owner->readformat);
1396                 ast_channel_unlock(p->owner);
1397         } else
1398                 ast_log(LOG_ERROR, "No owner found\n");
1399
1400
1401         ast_mutex_unlock(&p->lock);
1402
1403         if (gH323Debug)
1404                 ast_verbose("+++   ooh323_update_writeformat\n");
1405 }
1406
1407 void ooh323_set_read_format(ooCallData *call, int fmt)
1408 {
1409         struct ooh323_pvt *p = NULL;
1410         char formats[FORMAT_STRING_SIZE];
1411
1412         if (gH323Debug)
1413                 ast_verbose("---   ooh323_update_readformat %s\n", 
1414                                 ast_getformatname_multiple(formats,FORMAT_STRING_SIZE, fmt));
1415         
1416         p = find_call(call);
1417         if (!p) {
1418                 ast_log(LOG_ERROR, "No matching call found for %s\n", call->callToken);
1419                 return;
1420         }
1421
1422         ast_mutex_lock(&p->lock);
1423
1424         p->readformat = fmt;
1425
1426
1427         if (p->owner) {
1428                 while (p->owner && ast_channel_trylock(p->owner)) {
1429                         ast_debug(1,"Failed to grab lock, trying again\n");
1430                         DEADLOCK_AVOIDANCE(&p->lock);
1431                 }
1432                 if (!p->owner) {
1433                         ast_mutex_unlock(&p->lock);
1434                         ast_log(LOG_ERROR, "Channel has no owner\n");
1435                         return;
1436                 }
1437
1438                 if (gH323Debug)
1439                         ast_verbose("Readformat before update %s\n", 
1440                                   ast_getformatname_multiple(formats,FORMAT_STRING_SIZE, p->owner->readformat));
1441                 p->owner->nativeformats = fmt;
1442                 ast_set_read_format(p->owner, p->owner->readformat);
1443                 ast_channel_unlock(p->owner);
1444         } else
1445                 ast_log(LOG_ERROR, "No owner found\n");
1446
1447         ast_mutex_unlock(&p->lock);
1448
1449         if (gH323Debug)
1450                 ast_verbose("+++   ooh323_update_readformat\n");
1451 }
1452
1453
1454 int onAlerting(ooCallData *call)
1455 {
1456         struct ooh323_pvt *p = NULL;
1457         struct ast_channel *c = NULL;
1458
1459         if (gH323Debug)
1460                 ast_verbose("--- onAlerting %s\n", call->callToken);
1461
1462         p = find_call(call);
1463
1464         if(!p) {
1465                 ast_log(LOG_ERROR, "No matching call found\n");
1466                 return -1;
1467         }  
1468         ast_mutex_lock(&p->lock);
1469         if (!p->owner) {
1470                 ast_mutex_unlock(&p->lock);
1471                 ast_log(LOG_ERROR, "Channel has no owner\n");
1472                 return 0;
1473         }
1474         while (p->owner && ast_channel_trylock(p->owner)) {
1475                 ast_debug(1,"Failed to grab lock, trying again\n");
1476                 DEADLOCK_AVOIDANCE(&p->lock);
1477         }
1478         if (!p->owner) {
1479                 ast_mutex_unlock(&p->lock);
1480                 ast_log(LOG_ERROR, "Channel has no owner\n");
1481                 return 0;
1482         }
1483         c = p->owner;
1484         if (c->_state != AST_STATE_UP)
1485                 ast_setstate(c, AST_STATE_RINGING);
1486
1487         ast_queue_control(c, AST_CONTROL_RINGING);
1488         ast_channel_unlock(c);
1489         ast_mutex_unlock(&p->lock);
1490
1491         if (gH323Debug)
1492                 ast_verbose("+++ onAlerting %s\n", call->callToken);
1493
1494         return OO_OK;
1495 }
1496
1497 int onProgress(ooCallData *call)
1498 {
1499         struct ooh323_pvt *p = NULL;
1500         struct ast_channel *c = NULL;
1501
1502         if (gH323Debug)
1503                 ast_verbose("--- onProgress %s\n", call->callToken);
1504
1505         p = find_call(call);
1506
1507         if(!p) {
1508                 ast_log(LOG_ERROR, "No matching call found\n");
1509                 return -1;
1510         }  
1511         ast_mutex_lock(&p->lock);
1512         if (!p->owner) {
1513                 ast_mutex_unlock(&p->lock);
1514                 ast_log(LOG_ERROR, "Channel has no owner\n");
1515                 return 0;
1516         }
1517         while (p->owner && ast_channel_trylock(p->owner)) {
1518                 ast_debug(1,"Failed to grab lock, trying again\n");
1519                 DEADLOCK_AVOIDANCE(&p->lock);
1520         }
1521         if (!p->owner) {
1522                 ast_mutex_unlock(&p->lock);
1523                 ast_log(LOG_ERROR, "Channel has no owner\n");
1524                 return 0;
1525         }
1526         c = p->owner;
1527         if (c->_state != AST_STATE_UP)
1528                 ast_setstate(c, AST_STATE_RINGING);
1529
1530         ast_queue_control(c, AST_CONTROL_PROGRESS);
1531         ast_channel_unlock(c);
1532         ast_mutex_unlock(&p->lock);
1533
1534         if (gH323Debug)
1535                 ast_verbose("+++ onProgress %s\n", call->callToken);
1536
1537         return OO_OK;
1538 }
1539
1540 /**
1541   * Callback for sending digits from H.323 up to asterisk
1542   *
1543   */
1544 int ooh323_onReceivedDigit(OOH323CallData *call, const char *digit)
1545 {
1546         struct ooh323_pvt *p = NULL;
1547         struct ast_frame f;
1548         int res;
1549
1550         ast_debug(1, "Received Digit: %c\n", digit[0]);
1551         p = find_call(call);
1552         if (!p) {
1553                 ast_log(LOG_ERROR, "Failed to find a matching call.\n");
1554                 return -1;
1555         }
1556         if (!p->owner) {
1557                 ast_log(LOG_ERROR, "Channel has no owner\n");
1558                 return -1;
1559         }
1560         ast_mutex_lock(&p->lock);
1561         memset(&f, 0, sizeof(f));
1562         f.frametype = AST_FRAME_DTMF;
1563         f.subclass = digit[0];
1564         f.datalen = 0;
1565         f.samples = 800;
1566         f.offset = 0;
1567         f.data.ptr = NULL;
1568         f.mallocd = 0;
1569         f.src = "SEND_DIGIT";
1570
1571         while (p->owner && ast_channel_trylock(p->owner)) {
1572                 ast_debug(1,"Failed to grab lock, trying again\n");
1573                 DEADLOCK_AVOIDANCE(&p->lock);
1574         }
1575         if (!p->owner) {
1576                 ast_mutex_unlock(&p->lock);
1577                 ast_log(LOG_ERROR, "Channel has no owner\n");
1578                 return 0;
1579         }
1580         res = ast_queue_frame(p->owner, &f);
1581         ast_channel_unlock(p->owner);
1582         ast_mutex_unlock(&p->lock);
1583         return res;
1584 }
1585
1586 int ooh323_onReceivedSetup(ooCallData *call, Q931Message *pmsg)
1587 {
1588         struct ooh323_pvt *p = NULL;
1589         struct ooh323_user *user = NULL;
1590         struct ast_channel *c = NULL;
1591         ooAliases *alias = NULL;
1592         char *at = NULL;
1593         char number [OO_MAX_NUMBER_LENGTH];
1594
1595         if (gH323Debug)
1596                 ast_verbose("---   ooh323_onReceivedSetup %s\n", call->callToken);
1597
1598
1599         if (!(p = ooh323_alloc(call->callReference, call->callToken))) {
1600                 ast_log(LOG_ERROR, "Failed to create a new call.\n");
1601                 return -1;
1602         }
1603         ast_mutex_lock(&p->lock);
1604         ast_clear_flag(p, H323_OUTGOING);
1605   
1606
1607         if (call->remoteDisplayName) {
1608                 p->callerid_name = strdup(call->remoteDisplayName);
1609         }
1610
1611         if (ooCallGetCallingPartyNumber(call, number, OO_MAX_NUMBER_LENGTH) == OO_OK) {
1612                 p->callerid_num = strdup(number);
1613         }
1614
1615         if (call->remoteAliases) {
1616                 for (alias = call->remoteAliases; alias; alias = alias->next) {
1617                         if (alias->type == T_H225AliasAddress_h323_ID) {
1618                                 if (!p->callerid_name) {
1619                                         p->callerid_name = strdup(alias->value);
1620                                 }
1621                                 ast_copy_string(p->caller_h323id, alias->value, sizeof(p->caller_h323id));
1622                                 }
1623          else if(alias->type == T_H225AliasAddress_dialedDigits)
1624          {
1625             if(!p->callerid_num)
1626                p->callerid_num = strdup(alias->value);
1627                                 ast_copy_string(p->caller_dialedDigits, alias->value, 
1628                                                                                                                         sizeof(p->caller_dialedDigits));
1629          }
1630          else if(alias->type == T_H225AliasAddress_email_ID)
1631          {
1632                                 ast_copy_string(p->caller_email, alias->value, sizeof(p->caller_email));
1633          }
1634          else if(alias->type == T_H225AliasAddress_url_ID)
1635          {
1636                                 ast_copy_string(p->caller_url, alias->value, sizeof(p->caller_url));
1637                         }
1638                 }
1639         }
1640
1641         number[0] = '\0';
1642         if(ooCallGetCalledPartyNumber(call, number, OO_MAX_NUMBER_LENGTH)== OO_OK) {
1643                 strncpy(p->exten, number, sizeof(p->exten)-1);
1644         } else {
1645                 update_our_aliases(call, p);
1646                 if (!ast_strlen_zero(p->callee_dialedDigits)) {
1647                         ast_copy_string(p->exten, p->callee_dialedDigits, sizeof(p->exten));
1648                 } else if(!ast_strlen_zero(p->callee_h323id)) {
1649                         ast_copy_string(p->exten, p->callee_h323id, sizeof(p->exten));
1650                 } else if(!ast_strlen_zero(p->callee_email)) {
1651                         ast_copy_string(p->exten, p->callee_email, sizeof(p->exten));
1652                         if ((at = strchr(p->exten, '@'))) {
1653                                 *at = '\0';
1654                         }
1655                 }
1656         }
1657
1658         /* if no extension found, set to default 's' */
1659         if (ast_strlen_zero(p->exten)) {
1660                 p->exten[0]='s';
1661                 p->exten[1]='\0';
1662         }
1663
1664         user = find_user(p->callerid_name, call->remoteIP);
1665         if(user && (user->incominglimit == 0 || user->inUse < user->incominglimit)) {
1666                 ast_mutex_lock(&user->lock);
1667                 p->username = strdup(user->name);
1668                 p->neighbor.user = user->mUseIP ? ast_strdup(user->mIP) :
1669                                                   ast_strdup(user->name);
1670                 ast_copy_string(p->context, user->context, sizeof(p->context));
1671                 ast_copy_string(p->accountcode, user->accountcode, sizeof(p->accountcode));
1672                 p->amaflags = user->amaflags;
1673                 p->capability = user->capability;
1674                 memcpy(&p->prefs, &user->prefs, sizeof(struct ast_codec_pref));
1675                 p->dtmfmode |= user->dtmfmode;
1676                 p->dtmfcodec = user->dtmfcodec;
1677                 p->t38support = user->t38support;
1678                 p->rtptimeout = user->rtptimeout;
1679                 if (user->rtpmask && user->rtpmaskstr[0]) {
1680                         p->rtpmask = user->rtpmask;
1681                         ast_copy_string(p->rtpmaskstr, user->rtpmaskstr, 
1682                                                          sizeof(p->rtpmaskstr));
1683                 }
1684                 if (user->incominglimit) user->inUse++;
1685                 ast_mutex_unlock(&user->lock);
1686         } else {
1687          if (!OO_TESTFLAG(p->flags,H323_DISABLEGK)) {
1688                 p->username = strdup(call->remoteIP);
1689         } else {
1690           ast_mutex_unlock(&p->lock);
1691           ast_log(LOG_ERROR, "Unacceptable ip %s\n", call->remoteIP);
1692           if (!user) 
1693            ooHangCall(call->callToken, ooh323_convert_hangupcause_asteriskToH323(AST_CAUSE_CALL_REJECTED), AST_CAUSE_CALL_REJECTED);
1694           else
1695            ooHangCall(call->callToken, ooh323_convert_hangupcause_asteriskToH323(AST_CAUSE_NORMAL_CIRCUIT_CONGESTION), AST_CAUSE_NORMAL_CIRCUIT_CONGESTION);
1696           ast_set_flag(p, H323_NEEDDESTROY);
1697           return -1;
1698          }
1699         }
1700
1701         ooh323c_set_capability_for_call(call, &p->prefs, p->capability, p->dtmfmode, p->dtmfcodec,
1702                                          p->t38support);
1703         configure_local_rtp(p, call);
1704
1705 /* Incoming call */
1706         c = ooh323_new(p, AST_STATE_RING, p->username, 0, NULL);
1707         if(!c) {
1708         ast_mutex_unlock(&p->lock);
1709         ast_log(LOG_ERROR, "Could not create ast_channel\n");
1710          return -1;
1711   }
1712         ast_mutex_unlock(&p->lock);
1713
1714         if (gH323Debug)
1715                 ast_verbose("+++   ooh323_onReceivedSetup - Determined context %s, "
1716                                                 "extension %s\n", p->context, p->exten);
1717
1718         return OO_OK;
1719 }
1720
1721
1722
1723 int onOutgoingCall(ooCallData *call)
1724 {
1725         struct ooh323_pvt *p = NULL;
1726         int i = 0;
1727
1728         if (gH323Debug)
1729                 ast_verbose("---   onOutgoingCall %lx: %s\n", (long unsigned int) call, call->callToken);
1730
1731         if (!strcmp(call->callType, "outgoing")) {
1732                 p = find_call(call);
1733                 if (!p) {
1734                         ast_log(LOG_ERROR, "Failed to find a matching call.\n");
1735                         return -1;
1736                 }
1737                 ast_mutex_lock(&p->lock);
1738
1739                 if (!ast_strlen_zero(p->callerid_name)) {
1740                         ooCallSetCallerId(call, p->callerid_name);
1741                 }
1742                 if (!ast_strlen_zero(p->callerid_num)) {
1743                         i = 0;
1744                         while (*(p->callerid_num + i) != '\0') {
1745                                 if(!isdigit(*(p->callerid_num+i))) { break; }
1746                                 i++;
1747                         }
1748                         if(*(p->callerid_num+i) == '\0')
1749                                 ooCallSetCallingPartyNumber(call, p->callerid_num);
1750                         else {
1751                                 if(!p->callerid_name)
1752                                         ooCallSetCallerId(call, p->callerid_num);
1753                         }
1754                 }
1755                 
1756                 if (!ast_strlen_zero(p->caller_h323id))
1757                         ooCallAddAliasH323ID(call, p->caller_h323id);
1758
1759                 if (!ast_strlen_zero(p->caller_dialedDigits)) {
1760                         if (gH323Debug) {
1761                                 ast_verbose("Setting dialed digits %s\n", p->caller_dialedDigits);
1762                         }
1763                         ooCallAddAliasDialedDigits(call, p->caller_dialedDigits);
1764                 } else if (!ast_strlen_zero(p->callerid_num)) {
1765                         if (ooIsDailedDigit(p->callerid_num)) {
1766                                 if (gH323Debug) {
1767                                         ast_verbose("setting callid number %s\n", p->callerid_num);
1768                                 }
1769                                 ooCallAddAliasDialedDigits(call, p->callerid_num);
1770                         } else if (ast_strlen_zero(p->caller_h323id)) {
1771                                 ooCallAddAliasH323ID(call, p->callerid_num);
1772                         }
1773                 }
1774                 if (p->rtpmask && p->rtpmaskstr[0]) {
1775                         call->rtpMask = p->rtpmask;
1776                         ast_mutex_lock(&call->rtpMask->lock);
1777                         call->rtpMask->inuse++;
1778                         ast_mutex_unlock(&call->rtpMask->lock);
1779                         ast_copy_string(call->rtpMaskStr, p->rtpmaskstr, sizeof(call->rtpMaskStr));
1780                 }
1781
1782                 ast_mutex_unlock(&p->lock);
1783         }
1784
1785         if (gH323Debug)
1786                 ast_verbose("+++   onOutgoingCall %s\n", call->callToken);
1787         return OO_OK;
1788 }
1789
1790
1791 int onNewCallCreated(ooCallData *call)
1792 {
1793         struct ooh323_pvt *p = NULL;
1794         int i = 0;
1795
1796         if (gH323Debug)
1797                 ast_verbose("---   onNewCallCreated %lx: %s\n", (long unsigned int) call, call->callToken);
1798
1799         ast_mutex_lock(&call->Lock);
1800         if (ooh323c_start_call_thread(call)) {
1801                 ast_log(LOG_ERROR,"Failed to create call thread.\n");
1802                 ast_mutex_unlock(&call->Lock);
1803                 return -1;
1804         }
1805
1806         if (!strcmp(call->callType, "outgoing")) {
1807                 p = find_call(call);
1808                 if (!p) {
1809                         ast_log(LOG_ERROR, "Failed to find a matching call.\n");
1810                         ast_mutex_unlock(&call->Lock);
1811                         return -1;
1812                 }
1813                 ast_mutex_lock(&p->lock);
1814
1815                 if (p->callerid_name) {
1816                         ooCallSetCallerId(call, p->callerid_name);
1817                 }
1818                 if (p->callerid_num) {
1819                         i = 0;
1820                         while (*(p->callerid_num + i) != '\0') {
1821                                 if(!isdigit(*(p->callerid_num+i))) { break; }
1822                                 i++;
1823                         }
1824                         if(*(p->callerid_num+i) == '\0')
1825                                 ooCallSetCallingPartyNumber(call, p->callerid_num);
1826                         else {
1827                                 if(!p->callerid_name)
1828                                         ooCallSetCallerId(call, p->callerid_num);
1829                         }
1830                 }
1831                 
1832                 if (!ast_strlen_zero(p->caller_h323id))
1833                         ooCallAddAliasH323ID(call, p->caller_h323id);
1834
1835                 if (!ast_strlen_zero(p->caller_dialedDigits)) {
1836                         if (gH323Debug) {
1837                                 ast_verbose("Setting dialed digits %s\n", p->caller_dialedDigits);
1838                         }
1839                         ooCallAddAliasDialedDigits(call, p->caller_dialedDigits);
1840                 } else if (p->callerid_num) {
1841                         if (ooIsDailedDigit(p->callerid_num)) {
1842                                 if (gH323Debug) {
1843                                         ast_verbose("setting callid number %s\n", p->callerid_num);
1844                                 }
1845                                 ooCallAddAliasDialedDigits(call, p->callerid_num);
1846                         } else if (ast_strlen_zero(p->caller_h323id)) {
1847                                 ooCallAddAliasH323ID(call, p->callerid_num);
1848                         }
1849                 }
1850   
1851
1852                 if (!ast_strlen_zero(p->exten))  {
1853                         if (ooIsDailedDigit(p->exten)) {
1854                                 ooCallSetCalledPartyNumber(call, p->exten);
1855                                 ooCallAddRemoteAliasDialedDigits(call, p->exten);
1856                         } else {
1857                           ooCallAddRemoteAliasH323ID(call, p->exten);
1858                         }
1859                 }
1860
1861                 if (gH323Debug) {
1862                         char prefsBuf[256];
1863                         ast_codec_pref_string(&p->prefs, prefsBuf, sizeof(prefsBuf));
1864                         ast_verbose(" Outgoing call %s(%s) - Codec prefs - %s\n", 
1865                                 p->username?p->username:"NULL", call->callToken, prefsBuf);
1866                 }
1867
1868                 ooh323c_set_capability_for_call(call, &p->prefs, p->capability, 
1869                                      p->dtmfmode, p->dtmfcodec, p->t38support);
1870
1871                 configure_local_rtp(p, call);
1872                 ast_mutex_unlock(&p->lock);
1873         }
1874
1875         ast_mutex_unlock(&call->Lock);
1876         if (gH323Debug)
1877                 ast_verbose("+++   onNewCallCreated %s\n", call->callToken);
1878         return OO_OK;
1879 }
1880
1881 int onCallEstablished(ooCallData *call)
1882 {
1883         struct ooh323_pvt *p = NULL;
1884
1885         if (gH323Debug)
1886                 ast_verbose("---   onCallEstablished %s\n", call->callToken);
1887
1888
1889         if (!(p = find_call(call))) {
1890                 ast_log(LOG_ERROR, "Failed to find a matching call.\n");
1891                 return -1;
1892         }
1893
1894         if(ast_test_flag(p, H323_OUTGOING)) {
1895                 ast_mutex_lock(&p->lock);
1896                 if (!p->owner) {
1897                         ast_mutex_unlock(&p->lock);
1898                         ast_log(LOG_ERROR, "Channel has no owner\n");
1899                         return -1;
1900                 }
1901         
1902                 while (p->owner && ast_channel_trylock(p->owner)) {
1903                         ast_debug(1,"Failed to grab lock, trying again\n");
1904                         DEADLOCK_AVOIDANCE(&p->lock);
1905                 }
1906                 if (p->owner) {
1907                         struct ast_channel* c = p->owner;
1908                         ast_queue_control(c, AST_CONTROL_ANSWER);
1909                         ast_channel_unlock(p->owner);
1910                         manager_event(EVENT_FLAG_SYSTEM,"ChannelUpdate","Channel: %s\r\nChanneltype: %s\r\n"
1911                                 "CallRef: %d\r\n", c->name, "OOH323", p->call_reference);
1912                 }
1913                 ast_mutex_unlock(&p->lock);
1914
1915         }
1916
1917         if (gH323Debug)
1918                 ast_verbose("+++   onCallEstablished %s\n", call->callToken);
1919
1920         return OO_OK;
1921 }
1922
1923 int onCallCleared(ooCallData *call)
1924 {
1925         struct ooh323_pvt *p = NULL;
1926         int ownerLock = 0;
1927
1928         if (gH323Debug)
1929                 ast_verbose("---   onCallCleared %s \n", call->callToken);
1930
1931
1932    if ((p = find_call(call))) {
1933         ast_mutex_lock(&p->lock);
1934   
1935         while (p->owner) {
1936                 if (ast_channel_trylock(p->owner)) {
1937                         ooTrace(OOTRCLVLINFO, "Failed to grab lock, trying again\n");
1938                         ast_log(LOG_DEBUG,"Failed to grab lock, trying again\n");
1939                         DEADLOCK_AVOIDANCE(&p->lock);
1940                 } else {
1941                         ownerLock = 1; break;
1942                 }
1943         }
1944
1945         if (ownerLock) {
1946                 if (!ast_test_flag(p, H323_ALREADYGONE)) { 
1947
1948                         ast_set_flag(p, H323_ALREADYGONE);
1949                         p->owner->hangupcause = call->q931cause;
1950                         p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1951                         ast_queue_hangup_with_cause(p->owner,call->q931cause);
1952                 }
1953         }
1954
1955         if(p->owner) {
1956                 p->owner->tech_pvt = NULL;
1957                 ast_channel_unlock(p->owner);
1958                 p->owner = NULL;
1959                 ast_module_unref(myself);
1960         }
1961
1962         ast_set_flag(p, H323_NEEDDESTROY);
1963
1964         ooh323c_stop_call_thread(call);
1965
1966         ast_mutex_unlock(&p->lock);
1967         ast_mutex_lock(&usecnt_lock);
1968         usecnt--;
1969         ast_mutex_unlock(&usecnt_lock);
1970
1971     }
1972
1973         if (gH323Debug)
1974                 ast_verbose("+++   onCallCleared\n");
1975
1976         return OO_OK;
1977 }
1978
1979 /* static void ooh323_delete_user(struct ooh323_user *user)
1980 {
1981         struct ooh323_user *prev = NULL, *cur = NULL;
1982
1983         if (gH323Debug)
1984                 ast_verbose("---   ooh323_delete_user\n");
1985
1986         if (user) {     
1987                 cur = userl.users;
1988                 ast_mutex_lock(&userl.lock);
1989                 while (cur) {
1990                         if (cur == user) break;
1991                         prev = cur;
1992                         cur = cur->next;
1993                 }
1994
1995                 if (cur) {
1996                         if (prev)
1997                                 prev->next = cur->next;
1998                         else
1999                                 userl.users = cur->next;
2000                 }
2001                 ast_mutex_unlock(&userl.lock);
2002
2003                 free(user);
2004         }  
2005
2006         if (gH323Debug)
2007                 ast_verbose("+++   ooh323_delete_user\n");
2008
2009 } */
2010
2011 void ooh323_delete_peer(struct ooh323_peer *peer)
2012 {
2013         struct ooh323_peer *prev = NULL, *cur = NULL;
2014
2015         if (gH323Debug)
2016                 ast_verbose("---   ooh323_delete_peer\n");
2017
2018         if (peer) {     
2019       cur = peerl.peers;
2020                 ast_mutex_lock(&peerl.lock);
2021       while(cur) {
2022          if(cur==peer) break;
2023          prev = cur;
2024          cur = cur->next;
2025                 }
2026
2027                 if (cur) {
2028          if(prev)
2029                                 prev->next = cur->next;
2030          else
2031                                 peerl.peers = cur->next;
2032                         }
2033                 ast_mutex_unlock(&peerl.lock);
2034
2035       if(peer->h323id)   free(peer->h323id);
2036       if(peer->email)    free(peer->email);
2037       if(peer->url)      free(peer->url);
2038       if(peer->e164)     free(peer->e164);
2039
2040                 free(peer);
2041         }  
2042
2043         if (gH323Debug)
2044                 ast_verbose("+++   ooh323_delete_peer\n");
2045
2046 }
2047
2048
2049
2050 static struct ooh323_user *build_user(const char *name, struct ast_variable *v)
2051 {
2052         struct ooh323_user *user = NULL;
2053
2054         if (gH323Debug)
2055                 ast_verbose("---   build_user\n");
2056
2057         user = ast_calloc(1,sizeof(struct ooh323_user));
2058         if (user) {
2059                 memset(user, 0, sizeof(struct ooh323_user));
2060                 ast_mutex_init(&user->lock);
2061                 ast_copy_string(user->name, name, sizeof(user->name));
2062                 user->capability = gCapability;
2063                 memcpy(&user->prefs, &gPrefs, sizeof(user->prefs));
2064                 user->rtptimeout = gRTPTimeout;
2065                 user->dtmfmode = gDTMFMode;
2066                 user->dtmfcodec = gDTMFCodec;
2067                 user->t38support = gT38Support;
2068                 /* set default context */
2069                 ast_copy_string(user->context, gContext, sizeof(user->context));
2070                 ast_copy_string(user->accountcode, gAccountcode, sizeof(user->accountcode));
2071                 user->amaflags = gAMAFLAGS;
2072
2073                 while (v) {
2074                         if (!strcasecmp(v->name, "context")) {
2075                                 ast_copy_string(user->context, v->value, sizeof(user->context));
2076                         } else if (!strcasecmp(v->name, "incominglimit")) {
2077                                 user->incominglimit = atoi(v->value);
2078                                 if (user->incominglimit < 0)
2079                                         user->incominglimit = 0;
2080                         } else if (!strcasecmp(v->name, "accountcode")) {
2081                                 strncpy(user->accountcode, v->value, 
2082                                                 sizeof(user->accountcode)-1);
2083                         } else if (!strcasecmp(v->name, "rtptimeout")) {
2084                                 user->rtptimeout = atoi(v->value);
2085                                 if (user->rtptimeout < 0)
2086                                         user->rtptimeout = gRTPTimeout;
2087                         } else if (!strcasecmp(v->name, "rtpmask")) {
2088                                 if ((user->rtpmask = malloc(sizeof(struct OOH323Regex))) &&
2089                                         (regcomp(&user->rtpmask->regex, v->value, REG_EXTENDED) 
2090                                                                                         == 0)) {
2091                                         ast_mutex_init(&user->rtpmask->lock);
2092                                         user->rtpmask->inuse = 1;
2093                                         ast_copy_string(user->rtpmaskstr, v->value, 
2094                                                                 sizeof(user->rtpmaskstr));
2095                                 } else user->rtpmask = NULL;
2096                         } else if (!strcasecmp(v->name, "disallow")) {
2097                                 ast_parse_allow_disallow(&user->prefs, 
2098                                         &user->capability,  v->value, 0);
2099                         } else if (!strcasecmp(v->name, "allow")) {
2100                                 const char* tcodecs = v->value;
2101                                 if (!strcasecmp(v->value, "all")) {
2102                                         tcodecs = "ulaw,alaw,g729,g723,gsm";
2103                                 }
2104                                 ast_parse_allow_disallow(&user->prefs,
2105                                          &user->capability,  tcodecs, 1);
2106                         } else if (!strcasecmp(v->name, "amaflags")) {
2107                                 user->amaflags = ast_cdr_amaflags2int(v->value);
2108                         } else if (!strcasecmp(v->name, "ip")) {
2109                                 strncpy(user->mIP, v->value, sizeof(user->mIP)-1);
2110                                 user->mUseIP = 1;
2111                         } else if (!strcasecmp(v->name, "host")) {
2112                                 strncpy(user->mIP, v->value, sizeof(user->mIP)-1);
2113                                 user->mUseIP = 1;
2114                         } else if (!strcasecmp(v->name, "dtmfmode")) {
2115                                 if (!strcasecmp(v->value, "rfc2833"))
2116                                         user->dtmfmode = H323_DTMF_RFC2833;
2117                                 if (!strcasecmp(v->value, "cisco"))
2118                                         user->dtmfmode = H323_DTMF_CISCO;
2119                                 else if (!strcasecmp(v->value, "q931keypad"))
2120                                         user->dtmfmode = H323_DTMF_Q931;
2121                                 else if (!strcasecmp(v->value, "h245alphanumeric"))
2122                                         user->dtmfmode = H323_DTMF_H245ALPHANUMERIC;
2123                                 else if (!strcasecmp(v->value, "h245signal"))
2124                                         user->dtmfmode = H323_DTMF_H245SIGNAL;
2125                                 else if (!strcasecmp(v->value, "inband"))
2126                                         user->dtmfmode = H323_DTMF_INBAND;
2127                         } else if (!strcasecmp(v->name, "relaxdtmf")) {
2128                                 user->dtmfmode |= ast_true(v->value) ? H323_DTMF_INBANDRELAX : 0;
2129                         } else if (!strcasecmp(v->name, "dtmfcodec") && atoi(v->value)) {
2130                                 user->dtmfcodec = atoi(v->value);
2131                         } else if (!strcasecmp(v->name, "t38support")) {
2132                                 if (!strcasecmp(v->value, "disabled"))
2133                                         user->t38support = T38_DISABLED;
2134                                 if (!strcasecmp(v->value, "no"))
2135                                         user->t38support = T38_DISABLED;
2136                                 else if (!strcasecmp(v->value, "faxgw"))
2137                                         user->t38support = T38_FAXGW;
2138                                 else if (!strcasecmp(v->value, "yes"))
2139                                         user->t38support = T38_ENABLED;
2140                         }
2141                         v = v->next;
2142                 }
2143         }
2144
2145         if (gH323Debug)
2146                 ast_verbose("+++   build_user\n");
2147
2148         return user;
2149 }
2150
2151 static struct ooh323_peer *build_peer(const char *name, struct ast_variable *v, int friend_type)
2152 {
2153         struct ooh323_peer *peer = NULL;
2154
2155         if (gH323Debug)
2156                 ast_verbose("---   build_peer\n");
2157
2158         peer = ast_calloc(1, sizeof(*peer));
2159         if (peer) {
2160                 memset(peer, 0, sizeof(struct ooh323_peer));
2161                 ast_mutex_init(&peer->lock);
2162                 ast_copy_string(peer->name, name, sizeof(peer->name));
2163                 peer->capability = gCapability;
2164                 memcpy(&peer->prefs, &gPrefs, sizeof(peer->prefs));
2165                 peer->rtptimeout = gRTPTimeout;
2166                 ast_copy_string(peer->accountcode, gAccountcode, sizeof(peer->accountcode));
2167                 peer->amaflags = gAMAFLAGS;
2168                 peer->dtmfmode = gDTMFMode;
2169                 peer->dtmfcodec = gDTMFCodec;
2170                 peer->t38support = gT38Support;
2171                 peer->port = 1720;
2172                 if (0 == friend_type) {
2173                         peer->mFriend = 1;
2174                 }
2175
2176                 while (v) {
2177                         if (!strcasecmp(v->name, "h323id")) {
2178             if (!(peer->h323id = ast_strdup(v->value))) {
2179                                         ast_log(LOG_ERROR, "Could not allocate memory for h323id of "
2180                                                                                          "peer %s\n", name);
2181                                         ooh323_delete_peer(peer);
2182                                         return NULL;
2183                                 }
2184                         } else if (!strcasecmp(v->name, "e164")) {
2185                                 if (!(peer->e164 = ast_strdup(v->value))) {
2186                                         ast_log(LOG_ERROR, "Could not allocate memory for e164 of "
2187                                                                                          "peer %s\n", name);
2188                                         ooh323_delete_peer(peer);
2189                                         return NULL;
2190                                 }
2191                         } else  if (!strcasecmp(v->name, "email")) {
2192                                 if (!(peer->email = ast_strdup(v->value))) {
2193                                         ast_log(LOG_ERROR, "Could not allocate memory for email of "
2194                                                                                          "peer %s\n", name);
2195                                         ooh323_delete_peer(peer);
2196                                         return NULL;
2197                                 }
2198                         } else if (!strcasecmp(v->name, "url")) {
2199                                 if (!(peer->url = ast_strdup(v->value))) {
2200                                         ast_log(LOG_ERROR, "Could not allocate memory for h323id of "
2201                                                                                          "peer %s\n", name);
2202                                         ooh323_delete_peer(peer);
2203                                         return NULL;
2204                                 }
2205                         } else if (!strcasecmp(v->name, "port")) {
2206                                 peer->port = atoi(v->value);
2207                         } else if (!strcasecmp(v->name, "ip")) {
2208                                 ast_copy_string(peer->ip, v->value, sizeof(peer->ip));
2209                         } else if (!strcasecmp(v->name, "host")) {
2210                                 ast_copy_string(peer->ip, v->value, sizeof(peer->ip));
2211                         } else if (!strcasecmp(v->name, "outgoinglimit")) {
2212                                 peer->outgoinglimit = atoi(v->value);
2213                                 if (peer->outgoinglimit < 0)
2214                                         peer->outgoinglimit = 0;
2215                         } else if (!strcasecmp(v->name, "accountcode")) {
2216                                 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
2217                         } else if (!strcasecmp(v->name, "rtptimeout")) {
2218                                 peer->rtptimeout = atoi(v->value);
2219                                 if(peer->rtptimeout < 0)
2220                                         peer->rtptimeout = gRTPTimeout;
2221                         } else if (!strcasecmp(v->name, "rtpmask")) {
2222                                 if ((peer->rtpmask = malloc(sizeof(struct OOH323Regex))) &&
2223                                         (regcomp(&peer->rtpmask->regex, v->value, REG_EXTENDED) 
2224                                                                                         == 0)) {
2225                                         ast_mutex_init(&peer->rtpmask->lock);
2226                                         peer->rtpmask->inuse = 1;
2227                                         ast_copy_string(peer->rtpmaskstr, v->value, 
2228                                                                 sizeof(peer->rtpmaskstr));
2229                                 } else peer->rtpmask = NULL;
2230                         } else if (!strcasecmp(v->name, "disallow")) {
2231                                 ast_parse_allow_disallow(&peer->prefs, &peer->capability, 
2232                                                                                                  v->value, 0); 
2233                         } else if (!strcasecmp(v->name, "allow")) {
2234                                 const char* tcodecs = v->value;
2235                                 if (!strcasecmp(v->value, "all")) {
2236                                         tcodecs = "ulaw,alaw,g729,g723,gsm";
2237                                 }
2238                                 ast_parse_allow_disallow(&peer->prefs, &peer->capability, 
2239                                                                                                  tcodecs, 1);                            
2240                         } else if (!strcasecmp(v->name,  "amaflags")) {
2241                                 peer->amaflags = ast_cdr_amaflags2int(v->value);
2242                         } else if (!strcasecmp(v->name, "dtmfmode")) {
2243                                 if (!strcasecmp(v->value, "rfc2833"))
2244                                         peer->dtmfmode = H323_DTMF_RFC2833;
2245                                 if (!strcasecmp(v->value, "cisco"))
2246                                         peer->dtmfmode = H323_DTMF_CISCO;
2247                                 else if (!strcasecmp(v->value, "q931keypad"))
2248                                         peer->dtmfmode = H323_DTMF_Q931;
2249                                 else if (!strcasecmp(v->value, "h245alphanumeric"))
2250                                         peer->dtmfmode = H323_DTMF_H245ALPHANUMERIC;
2251                                 else if (!strcasecmp(v->value, "h245signal"))
2252                                         peer->dtmfmode = H323_DTMF_H245SIGNAL;
2253                                 else if (!strcasecmp(v->value, "inband"))
2254                                         peer->dtmfmode = H323_DTMF_INBAND;
2255                         } else if (!strcasecmp(v->name, "relaxdtmf")) {
2256                                 peer->dtmfmode |= ast_true(v->value) ? H323_DTMF_INBANDRELAX : 0;
2257                         } else if (!strcasecmp(v->name, "dtmfcodec") && atoi(v->value)) {
2258                                 peer->dtmfcodec = atoi(v->value);
2259                         } else if (!strcasecmp(v->name, "t38support")) {
2260                                 if (!strcasecmp(v->value, "disabled"))
2261                                         peer->t38support = T38_DISABLED;
2262                                 if (!strcasecmp(v->value, "no"))
2263                                         peer->t38support = T38_DISABLED;
2264                                 else if (!strcasecmp(v->value, "faxgw"))
2265                                         peer->t38support = T38_FAXGW;
2266                                 else if (!strcasecmp(v->value, "yes"))
2267                                         peer->t38support = T38_ENABLED;
2268                         }
2269                         v = v->next;
2270                 }
2271         }
2272
2273         if (gH323Debug)
2274                 ast_verbose("+++   build_peer\n");
2275
2276         return peer;
2277 }
2278
2279 static int ooh323_do_reload(void)
2280 {
2281         if (gH323Debug) {
2282                 ast_verbose("---   ooh323_do_reload\n");
2283         }
2284
2285         reload_config(1);
2286
2287         if (gH323Debug) {
2288                 ast_verbose("+++   ooh323_do_reload\n");
2289         }
2290
2291         return 0;
2292 }
2293
2294 /*--- h323_reload: Force reload of module from cli ---*/
2295
2296 char *handle_cli_ooh323_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2297 {
2298
2299        switch (cmd) {
2300        case CLI_INIT:
2301                e->command = "ooh323 reload";
2302                e->usage =
2303                        "Usage: ooh323 reload\n"
2304                        "                Reload OOH323 config.\n";
2305                return NULL;
2306        case CLI_GENERATE:
2307                return NULL;
2308        }
2309
2310        if (a->argc != 2)
2311                return CLI_SHOWUSAGE;
2312
2313         if (gH323Debug)
2314                 ast_verbose("---   ooh323_reload\n");
2315
2316         ast_mutex_lock(&h323_reload_lock);
2317         if (h323_reloading) {
2318                 ast_verbose("Previous OOH323 reload not yet done\n");
2319    } else {
2320                 h323_reloading = 1;
2321         }
2322         ast_mutex_unlock(&h323_reload_lock);
2323         restart_monitor();
2324
2325         if (gH323Debug)
2326                 ast_verbose("+++   ooh323_reload\n");
2327
2328         return 0;
2329 }
2330
2331 int reload_config(int reload)
2332 {
2333         int format;
2334         struct ooAliases  *pNewAlias = NULL, *cur, *prev;
2335         struct ast_config *cfg;
2336         struct ast_variable *v;
2337         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
2338         struct ooh323_user *user = NULL;
2339         struct ooh323_peer *peer = NULL;
2340         char *cat;
2341         const char *utype;
2342
2343         if (gH323Debug)
2344                 ast_verbose("---   reload_config\n");
2345
2346         cfg = ast_config_load((char*)config, config_flags);
2347
2348         /* We *must* have a config file otherwise stop immediately */
2349         if (!cfg) {
2350                 ast_log(LOG_NOTICE, "Unable to load config %s, OOH323 disabled\n", config);
2351                 return 1;
2352         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
2353                 return RESULT_SUCCESS;
2354
2355         if (reload) {
2356                 delete_users();
2357                 delete_peers();
2358                 if (gH323Debug) {
2359                         ast_verbose("  reload_config - Freeing up alias list\n");
2360                 }
2361                 cur = gAliasList;
2362                 while (cur) {
2363                         prev = cur;
2364                         cur = cur->next;
2365                         free(prev->value);
2366                         free(prev);
2367                 }
2368                 gAliasList = NULL;
2369         }
2370
2371         /* Inintialize everything to default */
2372         strcpy(gLogFile, DEFAULT_LOGFILE);
2373         gPort = 1720;
2374         gIP[0] = '\0';
2375         strcpy(gCallerID, DEFAULT_H323ID);
2376         gCapability = AST_FORMAT_ALAW;
2377         memset(&gPrefs, 0, sizeof(struct ast_codec_pref));
2378         gDTMFMode = H323_DTMF_RFC2833;
2379         gDTMFCodec = 101;
2380         gT38Support = T38_FAXGW;
2381         gTRCLVL = OOTRCLVLERR;
2382         gRasGkMode = RasNoGatekeeper;
2383         gGatekeeper[0] = '\0';
2384         gRTPTimeout = 60;
2385         strcpy(gAccountcode, DEFAULT_H323ACCNT);
2386         gFastStart = 1;
2387         gTunneling = 1;
2388         gTOS = 0;
2389         strcpy(gContext, DEFAULT_CONTEXT);
2390         gAliasList = NULL;
2391         gMediaWaitForConnect = 0;
2392         ooconfig.mTCPPortStart = 12030;
2393         ooconfig.mTCPPortEnd = 12230;
2394         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
2395
2396         v = ast_variable_browse(cfg, "general");
2397         while (v) {
2398
2399                 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
2400                         v = v->next;
2401                         continue;
2402                 }
2403         
2404                 if (!strcasecmp(v->name, "port")) {
2405                         gPort = (int)strtol(v->value, NULL, 10);
2406                 } else if (!strcasecmp(v->name, "bindaddr")) {
2407                         ast_copy_string(gIP, v->value, sizeof(gIP));
2408                 } else if (!strcasecmp(v->name, "h225portrange")) {
2409                         char* endlimit = 0;
2410                         char temp[512];
2411                         ast_copy_string(temp, v->value, sizeof(temp));
2412                         endlimit = strchr(temp, ',');
2413                         if (endlimit) {
2414                                 *endlimit = '\0';
2415                                 endlimit++;
2416                                 ooconfig.mTCPPortStart = atoi(temp);
2417                                 ooconfig.mTCPPortEnd = atoi(endlimit);
2418
2419                         } else {
2420                                 ast_log(LOG_ERROR, "h225portrange: Invalid format, separate port range with \",\"\n");
2421                         }
2422                 } else if (!strcasecmp(v->name, "gateway")) {
2423                         gIsGateway = ast_true(v->value);
2424                 } else if (!strcasecmp(v->name, "faststart")) {
2425                         gFastStart = ast_true(v->value);
2426                         if (gFastStart)
2427                                 ooH323EpEnableFastStart();
2428                         else
2429                                 ooH323EpDisableFastStart();
2430                 } else if (!strcasecmp(v->name, "mediawaitforconnect")) {
2431                         gMediaWaitForConnect = ast_true(v->value);
2432                         if (gMediaWaitForConnect)
2433                                 ooH323EpEnableMediaWaitForConnect();
2434                         else 
2435                                 ooH323EpDisableMediaWaitForConnect();
2436                 } else if (!strcasecmp(v->name, "h245tunneling")) {
2437                         gTunneling = ast_true(v->value);
2438                         if (gTunneling)
2439                                 ooH323EpEnableH245Tunneling();
2440                         else
2441                                 ooH323EpDisableH245Tunneling();
2442                 } else if (!strcasecmp(v->name, "trybemaster")) {
2443                         gBeMaster = ast_true(v->value);
2444                         if (gBeMaster)
2445                                 ooH323EpTryBeMaster(1);
2446                         else 
2447                                 ooH323EpTryBeMaster(0);
2448                 } else if (!strcasecmp(v->name, "h323id")) {
2449                         pNewAlias = malloc(sizeof(struct ooAliases));
2450                         if (!pNewAlias) {
2451                                 ast_log(LOG_ERROR, "Failed to allocate memory for h323id alias\n");
2452                                 return 1;
2453                         }
2454                         if (gAliasList == NULL) { /* first h323id - set as callerid if callerid is not set */
2455                                 ast_copy_string(gCallerID, v->value, sizeof(gCallerID));
2456                         }
2457                         pNewAlias->type =  T_H225AliasAddress_h323_ID;
2458                         pNewAlias->value = strdup(v->value);
2459                         pNewAlias->next = gAliasList;
2460                         gAliasList = pNewAlias;
2461                         pNewAlias = NULL;
2462                 } else if (!strcasecmp(v->name, "e164")) {
2463                         pNewAlias = malloc(sizeof(struct ooAliases));
2464                         if (!pNewAlias) {
2465                                 ast_log(LOG_ERROR, "Failed to allocate memory for e164 alias\n");
2466                                 return 1;
2467                         }
2468                         pNewAlias->type =  T_H225AliasAddress_dialedDigits;
2469                         pNewAlias->value = strdup(v->value);
2470                         pNewAlias->next = gAliasList;
2471                         gAliasList = pNewAlias;
2472                         pNewAlias = NULL;
2473                 } else if (!strcasecmp(v->name, "email")) {
2474                         pNewAlias = malloc(sizeof(struct ooAliases));
2475                         if (!pNewAlias) {
2476                                 ast_log(LOG_ERROR, "Failed to allocate memory for email alias\n");
2477                                 return 1;
2478                         }
2479                         pNewAlias->type =  T_H225AliasAddress_email_ID;
2480                         pNewAlias->value = strdup(v->value);
2481                         pNewAlias->next = gAliasList;
2482                         gAliasList = pNewAlias;
2483                         pNewAlias = NULL;
2484       } else if (!strcasecmp(v->name, "t35country")) {
2485          t35countrycode = atoi(v->value);
2486       } else if (!strcasecmp(v->name, "t35extensions")) {
2487          t35extensions = atoi(v->value);
2488       } else if (!strcasecmp(v->name, "manufacturer")) {
2489          manufacturer = atoi(v->value);
2490       } else if (!strcasecmp(v->name, "vendorid")) {
2491          ast_copy_string(vendor, v->value, sizeof(vendor));
2492       } else if (!strcasecmp(v->name, "versionid")) {
2493          ast_copy_string(version, v->value, sizeof(version));
2494                 } else if (!strcasecmp(v->name, "callerid")) {
2495                         ast_copy_string(gCallerID, v->value, sizeof(gCallerID));
2496                 } else if (!strcasecmp(v->name, "incominglimit")) {
2497                         gIncomingLimit = atoi(v->value);
2498                 } else if (!strcasecmp(v->name, "outgoinglimit")) {
2499                         gOutgoingLimit = atoi(v->value);
2500                 } else if (!strcasecmp(v->name, "gatekeeper")) {
2501                         if (!strcasecmp(v->value, "DISABLE")) {
2502                                 gRasGkMode = RasNoGatekeeper;
2503                         } else if (!strcasecmp(v->value, "DISCOVER")) {
2504                                 gRasGkMode = RasDiscoverGatekeeper;
2505                         } else {
2506                                 gRasGkMode = RasUseSpecificGatekeeper;
2507                                 strncpy(gGatekeeper, v->value, sizeof(gGatekeeper)-1);
2508                         }
2509                 } else if (!strcasecmp(v->name, "logfile")) {
2510          strncpy(gLogFile, v->value, sizeof(gLogFile)-1);
2511                 } else if (!strcasecmp(v->name, "context")) {
2512          strncpy(gContext, v->value, sizeof(gContext)-1);
2513          ast_verbose(VERBOSE_PREFIX_3 "  == Setting default context to %s\n", 
2514                                                       gContext);
2515                 } else if (!strcasecmp(v->name, "rtptimeout")) {
2516                         gRTPTimeout = atoi(v->value);
2517                         if (gRTPTimeout <= 0)
2518                                 gRTPTimeout = 60;
2519                 } else if (!strcasecmp(v->name, "tos")) {
2520                         if (sscanf(v->value, "%30i", &format) == 1)
2521                                 gTOS = format & 0xff;
2522                         else if (!strcasecmp(v->value, "lowdelay"))
2523                                 gTOS = IPTOS_LOWDELAY;
2524                         else if (!strcasecmp(v->value, "throughput"))
2525                                 gTOS = IPTOS_THROUGHPUT;
2526                         else if (!strcasecmp(v->value, "reliability"))
2527                                 gTOS = IPTOS_RELIABILITY;
2528                         else if (!strcasecmp(v->value, "mincost"))
2529                                 gTOS = IPTOS_MINCOST;
2530                         else if (!strcasecmp(v->value, "none"))
2531                                 gTOS = 0;
2532                         else
2533                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be "
2534                                                                                         "'lowdelay', 'throughput', 'reliability', "
2535                                                                                         "'mincost', or 'none'\n", v->lineno);
2536                 } else if (!strcasecmp(v->name, "amaflags")) {
2537                         gAMAFLAGS = ast_cdr_amaflags2int(v->value);
2538                 } else if (!strcasecmp(v->name, "accountcode")) {
2539          ast_copy_string(gAccountcode, v->value, sizeof(gAccountcode));
2540                 } else if (!strcasecmp(v->name, "disallow")) {
2541                         ast_parse_allow_disallow(&gPrefs, &gCapability, v->value, 0);
2542                 } else if (!strcasecmp(v->name, "allow")) {
2543                         const char* tcodecs = v->value;
2544                         if (!strcasecmp(v->value, "all")) {
2545                                 tcodecs = "ulaw,alaw,g729,g723,gsm";
2546                         }
2547                         ast_parse_allow_disallow(&gPrefs, &gCapability, tcodecs, 1);
2548                 } else if (!strcasecmp(v->name, "dtmfmode")) {
2549                         if (!strcasecmp(v->value, "inband"))
2550                                 gDTMFMode = H323_DTMF_INBAND;
2551                         else if (!strcasecmp(v->value, "rfc2833"))
2552                                 gDTMFMode = H323_DTMF_RFC2833;
2553                         else if (!strcasecmp(v->value, "cisco"))
2554                                 gDTMFMode = H323_DTMF_CISCO;
2555                         else if (!strcasecmp(v->value, "q931keypad"))
2556                                 gDTMFMode = H323_DTMF_Q931;
2557                         else if (!strcasecmp(v->value, "h245alphanumeric"))
2558                                 gDTMFMode = H323_DTMF_H245ALPHANUMERIC;
2559                         else if (!strcasecmp(v->value, "h245signal"))
2560                                 gDTMFMode = H323_DTMF_H245SIGNAL;
2561                         else {
2562             ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", 
2563                                                                     v->value);
2564                                 gDTMFMode = H323_DTMF_RFC2833;
2565                         }
2566                 } else if (!strcasecmp(v->name, "relaxdtmf")) {
2567                         gDTMFMode |= ast_true(v->value) ? H323_DTMF_INBANDRELAX : 0;
2568                 } else if (!strcasecmp(v->name, "dtmfcodec") && atoi(v->value)) {
2569                         gDTMFCodec = atoi(v->value);
2570                 } else if (!strcasecmp(v->name, "t38support")) {
2571                         if (!strcasecmp(v->value, "disabled"))
2572                                 gT38Support = T38_DISABLED;
2573                         if (!strcasecmp(v->value, "no"))
2574                                 gT38Support = T38_DISABLED;
2575                         else if (!strcasecmp(v->value, "faxgw"))
2576                                 gT38Support = T38_FAXGW;
2577                         else if (!strcasecmp(v->value, "yes"))
2578                                 gT38Support = T38_ENABLED;
2579                 } else if (!strcasecmp(v->name, "tracelevel")) {
2580                         gTRCLVL = atoi(v->value);
2581                         ooH323EpSetTraceLevel(gTRCLVL);
2582                 }
2583                 v = v->next;
2584         }
2585         
2586         for (cat = ast_category_browse(cfg, NULL); cat; cat = ast_category_browse(cfg, cat)) {
2587                 if (strcasecmp(cat, "general")) {
2588                         int friend_type = 0;
2589                         utype = ast_variable_retrieve(cfg, cat, "type");
2590                         if (utype) {
2591                                 friend_type = strcasecmp(utype, "friend");
2592                                 if (!strcmp(utype, "user") || 0 == friend_type) {
2593                                         user = build_user(cat, ast_variable_browse(cfg, cat));
2594                                         if (user) {
2595                                                 ast_mutex_lock(&userl.lock);
2596                                                 user->next = userl.users;
2597                                                 userl.users = user;
2598                                                 ast_mutex_unlock(&userl.lock);
2599                                         } else {
2600                                                 ast_log(LOG_WARNING, "Failed to build user %s\n", cat);
2601                                         }
2602                                 }
2603                                 if (!strcasecmp(utype, "peer") || 0 == friend_type) {
2604                                         peer = build_peer(cat, ast_variable_browse(cfg, cat), friend_type);
2605                                         if (peer) {
2606                                                 ast_mutex_lock(&peerl.lock);
2607                                                 peer->next = peerl.peers;
2608                                                 peerl.peers = peer;
2609                                                 ast_mutex_unlock(&peerl.lock);
2610                                         } else {
2611                                                 ast_log(LOG_WARNING, "Failed to build peer %s\n", cat);
2612                                         }
2613                                 }
2614                         }
2615                 }
2616         }
2617         ast_config_destroy(cfg);
2618
2619
2620         /* Determine ip address if neccessary */
2621         if (ast_strlen_zero(gIP)) {
2622                 ooGetLocalIPAddress(gIP);
2623                 if (!strcmp(gIP, "127.0.0.1")) {
2624                         ast_log(LOG_NOTICE, "Failed to determine local ip address. Please "
2625                                                                          "specify it in ooh323.conf. OOH323 Disabled\n");
2626                         return 1;
2627                 }
2628         }
2629
2630         if (gH323Debug)
2631                 ast_verbose("+++   reload_config\n");
2632
2633         return 0;
2634
2635 }
2636
2637
2638 static char *handle_cli_ooh323_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2639 {
2640         char ip_port[30];
2641         struct ooh323_peer *prev = NULL, *peer = NULL;
2642         
2643         switch (cmd) {
2644         case CLI_INIT:
2645                 e->command = "ooh323 show peer";
2646                 e->usage =
2647                         "Usage: ooh323 show peer <name>\n"
2648                         "                List details of specific OOH323 peer.\n";
2649                 return NULL;
2650         case CLI_GENERATE:
2651                 return NULL;
2652         }
2653
2654         if (a->argc != 4)
2655                 return CLI_SHOWUSAGE;
2656
2657  
2658         ast_mutex_lock(&peerl.lock);
2659         peer = peerl.peers;
2660         while (peer) {
2661                 ast_mutex_lock(&peer->lock);
2662                 if(!strcmp(peer->name, a->argv[3]))
2663                         break;
2664                 else {
2665                         prev = peer;
2666                         peer = peer->next;
2667                         ast_mutex_unlock(&prev->lock);
2668                 }
2669         }
2670
2671         if (peer) {
2672       sprintf(ip_port, "%s:%d", peer->ip, peer->port);
2673       ast_cli(a->fd, "%-15.15s%s\n", "Name: ", peer->name);
2674       ast_cli(a->fd, "%-15.15s%s", "Format Prefs: ", "(");
2675       print_codec_to_cli(a->fd, &peer->prefs);
2676       ast_cli(a->fd, ")\n");
2677       ast_cli(a->fd, "%-15.15s", "DTMF Mode: ");
2678                 if (peer->dtmfmode & H323_DTMF_CISCO) {
2679          ast_cli(a->fd, "%s\n", "cisco");
2680          ast_cli(a->fd, "%-15.15s%d\n", "DTMF Codec: ", peer->dtmfcodec);
2681                 } else if (peer->dtmfmode & H323_DTMF_RFC2833) {
2682          ast_cli(a->fd, "%s\n", "rfc2833");
2683          ast_cli(a->fd, "%-15.15s%d\n", "DTMF Codec: ", peer->dtmfcodec);
2684                 } else if (peer->dtmfmode & H323_DTMF_Q931)
2685          ast_cli(a->fd, "%s\n", "q931keypad");
2686                 else if (peer->dtmfmode & H323_DTMF_H245ALPHANUMERIC)
2687          ast_cli(a->fd, "%s\n", "h245alphanumeric");
2688                 else if (peer->dtmfmode & H323_DTMF_H245SIGNAL)
2689          ast_cli(a->fd, "%s\n", "h245signal");
2690                 else if (peer->dtmfmode & H323_DTMF_INBAND && peer->dtmfmode & H323_DTMF_INBANDRELAX)
2691          ast_cli(a->fd, "%s\n", "inband-relaxed");
2692                 else if (peer->dtmfmode & H323_DTMF_INBAND)
2693          ast_cli(a->fd, "%s\n", "inband");
2694                 else
2695          ast_cli(a->fd, "%s\n", "unknown");
2696
2697         ast_cli(a->fd,"%-15s", "T.38 Mode: ");
2698         if (peer->t38support == T38_DISABLED)
2699                 ast_cli(a->fd, "%s\n", "disabled");
2700         else if (peer->t38support == T38_FAXGW)
2701                 ast_cli(a->fd, "%s\n", "faxgw/chan_sip compatible");
2702
2703         ast_cli(a->fd, "%-15.15s%s\n", "AccountCode: ", peer->accountcode);
2704         ast_cli(a->fd, "%-15.15s%s\n", "AMA flags: ", 
2705                 ast_cdr_flags2str(peer->amaflags));
2706         ast_cli(a->fd, "%-15.15s%s\n", "IP:Port: ", ip_port);
2707         ast_cli(a->fd, "%-15.15s%d\n", "OutgoingLimit: ", peer->outgoinglimit);
2708         ast_cli(a->fd, "%-15.15s%d\n", "rtptimeout: ", peer->rtptimeout);
2709         if (peer->rtpmaskstr[0])
2710                 ast_cli(a->fd, "%-15.15s%s\n", "rtpmask: ", peer->rtpmaskstr);
2711         ast_mutex_unlock(&peer->lock);
2712         } else {
2713         ast_cli(a->fd, "Peer %s not found\n", a->argv[3]);
2714         ast_cli(a->fd, "\n");
2715         }
2716         ast_mutex_unlock(&peerl.lock);
2717
2718         return CLI_SUCCESS;
2719 }
2720
2721 static char *handle_cli_ooh323_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2722 {
2723         struct ooh323_peer *prev = NULL, *peer = NULL;
2724    char formats[FORMAT_STRING_SIZE];
2725    char ip_port[30];
2726 #define FORMAT  "%-15.15s  %-15.15s  %-23.23s  %-s\n"
2727
2728         switch (cmd) {
2729         case CLI_INIT:
2730                 e->command = "ooh323 show peers";
2731                 e->usage =
2732                         "Usage: ooh323 show peers\n"
2733                         "                Lists all known OOH323 peers.\n";
2734                 return NULL;
2735         case CLI_GENERATE:
2736                 return NULL;
2737         }
2738
2739         if (a->argc != 3)
2740                 return CLI_SHOWUSAGE;
2741
2742    ast_cli(a->fd, FORMAT, "Name", "Accountcode", "ip:port", "Formats");
2743
2744         ast_mutex_lock(&peerl.lock);
2745         peer = peerl.peers;
2746         while (peer) {
2747                 ast_mutex_lock(&peer->lock);
2748                 snprintf(ip_port, sizeof(ip_port), "%s:%d", peer->ip, peer->port);
2749      ast_cli(a->fd, FORMAT, peer->name, 
2750                                         peer->accountcode,
2751                                         ip_port,
2752                  ast_getformatname_multiple(formats,FORMAT_STRING_SIZE,peer->capability));
2753                 prev = peer;
2754                 peer = peer->next;
2755                 ast_mutex_unlock(&prev->lock);
2756
2757         }
2758         ast_mutex_unlock(&peerl.lock);
2759 #undef FORMAT
2760         return CLI_SUCCESS;
2761 }
2762
2763 /*! \brief Print codec list from preference to CLI/manager */
2764 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
2765 {
2766         int x, codec;
2767
2768         for (x = 0; x < 32; x++) {
2769                 codec = ast_codec_pref_index(pref, x);
2770                 if (!codec)
2771                         break;
2772                 ast_cli(fd, "%s", ast_getformatname(codec));
2773                 ast_cli(fd, ":%d", pref->framing[x]);
2774                 if (x < 31 && ast_codec_pref_index(pref, x + 1))
2775                         ast_cli(fd, ",");
2776         }
2777         if (!x)
2778                 ast_cli(fd, "none");
2779 }
2780
2781 static char *handle_cli_ooh323_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2782 {
2783         struct ooh323_user *prev = NULL, *user = NULL;
2784
2785         switch (cmd) {
2786         case CLI_INIT:
2787                 e->command = "ooh323 show user";
2788                 e->usage =
2789                         "Usage: ooh323 show user <name>\n"
2790                         "                List details of specific OOH323 user.\n";
2791                 return NULL;
2792         case CLI_GENERATE:
2793                 return NULL;
2794         }
2795
2796         if (a->argc != 4)
2797                 return CLI_SHOWUSAGE;
2798
2799
2800         ast_mutex_lock(&userl.lock);
2801         user = userl.users;
2802         while (user) {
2803                 ast_mutex_lock(&user->lock);
2804       if(!strcmp(user->name, a->argv[3])) {
2805                         break;
2806       } else {
2807                         prev = user;
2808                         user = user->next;
2809                         ast_mutex_unlock(&prev->lock);
2810                 }
2811         }
2812
2813         if (user) {
2814       ast_cli(a->fd, "%-15.15s%s\n", "Name: ", user->name);
2815       ast_cli(a->fd, "%-15.15s%s", "Format Prefs: ", "(");
2816       print_codec_to_cli(a->fd, &user->prefs);
2817       ast_cli(a->fd, ")\n");
2818       ast_cli(a->fd, "%-15.15s", "DTMF Mode: ");
2819                 if (user->dtmfmode & H323_DTMF_CISCO) {
2820          ast_cli(a->fd, "%s\n", "cisco");
2821          ast_cli(a->fd, "%-15.15s%d\n", "DTMF Codec: ", user->dtmfcodec);
2822                 } else if (user->dtmfmode & H323_DTMF_RFC2833) {
2823          ast_cli(a->fd, "%s\n", "rfc2833");
2824          ast_cli(a->fd, "%-15.15s%d\n", "DTMF Codec: ", user->dtmfcodec);
2825                 } else if (user->dtmfmode & H323_DTMF_Q931)
2826          ast_cli(a->fd, "%s\n", "q931keypad");
2827                 else if (user->dtmfmode & H323_DTMF_H245ALPHANUMERIC)
2828          ast_cli(a->fd, "%s\n", "h245alphanumeric");
2829                 else if (user->dtmfmode & H323_DTMF_H245SIGNAL)
2830          ast_cli(a->fd, "%s\n", "h245signal");
2831                 else if (user->dtmfmode & H323_DTMF_INBAND && user->dtmfmode & H323_DTMF_INBANDRELAX)
2832          ast_cli(a->fd, "%s\n", "inband-relaxed");
2833                 else if (user->dtmfmode & H323_DTMF_INBAND)
2834          ast_cli(a->fd, "%s\n", "inband");
2835                 else
2836          ast_cli(a->fd, "%s\n", "unknown");
2837
2838         ast_cli(a->fd,"%-15s", "T.38 Mode: ");
2839         if (user->t38support == T38_DISABLED)
2840                 ast_cli(a->fd, "%s\n", "disabled");
2841         else if (user->t38support == T38_FAXGW)
2842                 ast_cli(a->fd, "%s\n", "faxgw/chan_sip compatible");
2843
2844       ast_cli(a->fd, "%-15.15s%s\n", "AccountCode: ", user->accountcode);
2845       ast_cli(a->fd, "%-15.15s%s\n", "AMA flags: ", 
2846                                             ast_cdr_flags2str(user->amaflags));
2847       ast_cli(a->fd, "%-15.15s%s\n", "Context: ", user->context);
2848       ast_cli(a->fd, "%-15.15s%d\n", "IncomingLimit: ", user->incominglimit);
2849       ast_cli(a->fd, "%-15.15s%d\n", "InUse: ", user->inUse);
2850       ast_cli(a->fd, "%-15.15s%d\n", "rtptimeout: ", user->rtptimeout);
2851         if (user->rtpmaskstr[0])
2852                 ast_cli(a->fd, "%-15.15s%s\n", "rtpmask: ", user->rtpmaskstr);
2853                 ast_mutex_unlock(&user->lock);
2854         } else {
2855      ast_cli(a->fd, "User %s not found\n", a->argv[3]);
2856      ast_cli(a->fd, "\n");
2857         }
2858         ast_mutex_unlock(&userl.lock);
2859
2860         return CLI_SUCCESS;
2861 }
2862
2863 static char *handle_cli_ooh323_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2864 {
2865         struct ooh323_user *prev = NULL, *user = NULL;
2866    char formats[FORMAT_STRING_SIZE];
2867 #define FORMAT1  "%-15.15s  %-15.15s  %-15.15s  %-s\n"
2868
2869         switch (cmd) {
2870         case CLI_INIT:
2871                 e->command = "ooh323 show users";
2872                 e->usage =
2873                         "Usage: ooh323 show users \n"
2874                         "                Lists all known OOH323 users.\n";
2875                 return NULL;
2876         case CLI_GENERATE:
2877                 return NULL;
2878         }
2879
2880         if (a->argc != 3)
2881                 return CLI_SHOWUSAGE;
2882
2883
2884    ast_cli(a->fd, FORMAT1, "Username", "Accountcode", "Context", "Formats");
2885
2886         ast_mutex_lock(&userl.lock);
2887         user = userl.users;
2888    while(user)
2889    {
2890                 ast_mutex_lock(&user->lock);
2891                 ast_cli(a->fd, FORMAT1, user->name, 
2892                                         user->accountcode, user->context,
2893                                         ast_getformatname_multiple(formats, FORMAT_STRING_SIZE, user->capability));
2894                 prev = user;
2895                 user = user->next;
2896                 ast_mutex_unlock(&prev->lock);
2897
2898         }
2899         ast_mutex_unlock(&userl.lock);
2900 #undef FORMAT1
2901    return RESULT_SUCCESS;
2902
2903 }
2904
2905 static char *handle_cli_ooh323_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2906 {
2907         switch (cmd) {
2908         case CLI_INIT:
2909                 e->command = "ooh323 set debug [off]";
2910                 e->usage =
2911                         "Usage: ooh323 set debug [off]\n"
2912                         "                Enables/Disables debugging of OOH323 channel driver\n";
2913                 return NULL;
2914         case CLI_GENERATE:
2915                 return NULL;
2916         }
2917
2918         if (a->argc < 3 || a->argc > 4)
2919                 return CLI_SHOWUSAGE;
2920         if (a->argc == 4 && strcasecmp(a->argv[3], "off"))
2921                 return CLI_SHOWUSAGE;
2922
2923         gH323Debug = (a->argc == 4) ? FALSE : TRUE;
2924         ast_cli(a->fd, "OOH323 Debugging %s\n", gH323Debug ? "Enabled" : "Disabled");
2925
2926         return CLI_SUCCESS;
2927 }
2928
2929 #if 0
2930 static int ooh323_show_channels(int fd, int argc, char *argv[])
2931 {
2932         return RESULT_SUCCESS;
2933 }
2934 #endif
2935
2936 static char *handle_cli_ooh323_show_config(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2937 {
2938         char value[FORMAT_STRING_SIZE];
2939         ooAliases *pAlias = NULL, *pAliasNext = NULL;;
2940
2941         switch (cmd) {
2942         case CLI_INIT:
2943                 e->command = "ooh323 show config";
2944                 e->usage =
2945                         "Usage: ooh323 show config\n"
2946                         "                Shows global configuration of H.323 channel driver\n";
2947                 return NULL;
2948         case CLI_GENERATE:
2949                 return NULL;
2950         }
2951
2952         if (a->argc != 3)
2953                 return CLI_SHOWUSAGE;
2954
2955
2956
2957    ast_cli(a->fd, "\nObjective Open H.323 Channel Driver's Config:\n");
2958         snprintf(value, sizeof(value), "%s:%d", gIP, gPort);
2959    ast_cli(a->fd, "%-20s%s\n", "IP:Port: ", value);
2960    ast_cli(a->fd, "%-20s%d-%d\n", "H.225 port range: ", 
2961       ooconfig.mTCPPortStart, ooconfig.mTCPPortEnd);
2962    ast_cli(a->fd, "%-20s%s\n", "FastStart", gFastStart?"yes":"no");
2963    ast_cli(a->fd, "%-20s%s\n", "Tunneling", gTunneling?"yes":"no");
2964    ast_cli(a->fd, "%-20s%s\n", "CallerId", gCallerID);
2965    ast_cli(a->fd, "%-20s%s\n", "MediaWaitForConnect", 
2966       gMediaWaitForConnect?"yes":"no");
2967
2968 #if (0)
2969                 extern OOH323EndPoint gH323ep;
2970    ast_cli(a->fd, "%-20s%s\n", "FASTSTART", 
2971                         (OO_TESTFLAG(gH323ep.flags, OO_M_FASTSTART) != 0) ? "yes" : "no");
2972    ast_cli(a->fd, "%-20s%s\n", "TUNNELING", 
2973                         (OO_TESTFLAG(gH323ep.flags, OO_M_TUNNELING) != 0) ? "yes" : "no");
2974    ast_cli(a->fd, "%-20s%s\n", "MEDIAWAITFORCONN",
2975                         (OO_TESTFLAG(gH323ep.flags, OO_M_MEDIAWAITFORCONN) != 0) ? "yes" : "no");
2976 #endif
2977
2978         if (gRasGkMode == RasNoGatekeeper)
2979                 snprintf(value, sizeof(value), "%s", "No Gatekeeper");
2980         else if (gRasGkMode == RasDiscoverGatekeeper)
2981                 snprintf(value, sizeof(value), "%s", "Discover");
2982         else
2983                 snprintf(value, sizeof(value), "%s", gGatekeeper);
2984
2985    ast_cli(a->fd,  "%-20s%s\n", "Gatekeeper:", value);
2986
2987    ast_cli(a->fd,  "%-20s%s\n", "H.323 LogFile:", gLogFile);   
2988
2989    ast_cli(a->fd,  "%-20s%s\n", "Context:", gContext);
2990    
2991    ast_cli(a->fd,  "%-20s%s\n", "Capability:", 
2992            ast_getformatname_multiple(value,FORMAT_STRING_SIZE,gCapability));
2993
2994    ast_cli(a->fd, "%-20s", "DTMF Mode: ");
2995         if (gDTMFMode & H323_DTMF_CISCO) {
2996       ast_cli(a->fd, "%s\n", "cisco");
2997       ast_cli(a->fd, "%-15.15s%d\n", "DTMF Codec: ", gDTMFCodec);
2998         } else if (gDTMFMode & H323_DTMF_RFC2833) {
2999       ast_cli(a->fd, "%s\n", "rfc2833");
3000       ast_cli(a->fd, "%-15.15s%d\n", "DTMF Codec: ", gDTMFCodec);
3001         } else if (gDTMFMode & H323_DTMF_Q931)
3002       ast_cli(a->fd, "%s\n", "q931keypad");
3003         else if (gDTMFMode & H323_DTMF_H245ALPHANUMERIC)
3004       ast_cli(a->fd, "%s\n", "h245alphanumeric");
3005         else if (gDTMFMode & H323_DTMF_H245SIGNAL)
3006       ast_cli(a->fd, "%s\n", "h245signal");
3007                 else if (gDTMFMode & H323_DTMF_INBAND && gDTMFMode & H323_DTMF_INBANDRELAX)
3008          ast_cli(a->fd, "%s\n", "inband-relaxed");
3009                 else if (gDTMFMode & H323_DTMF_INBAND)
3010          ast_cli(a->fd, "%s\n", "inband");
3011         else
3012                 ast_cli(a->fd, "%s\n", "unknown");
3013
3014         ast_cli(a->fd,"%-20s", "T.38 Mode: ");
3015         if (gT38Support == T38_DISABLED)
3016                 ast_cli(a->fd, "%s\n", "disabled");
3017         else if (gT38Support == T38_FAXGW)
3018                 ast_cli(a->fd, "%s\n", "faxgw/chan_sip compatible");
3019
3020    ast_cli(a->fd, "%-20s%ld\n", "Call counter: ", callnumber);
3021    ast_cli(a->fd, "%-20s%s\n", "AccountCode: ", gAccountcode);
3022
3023    ast_cli(a->fd, "%-20s%s\n", "AMA flags: ", ast_cdr_flags2str(gAMAFLAGS));
3024
3025         pAlias = gAliasList;
3026    if(pAlias) {
3027      ast_cli(a->fd, "%-20s\n", "Aliases: ");
3028    }
3029         while (pAlias) {
3030                 pAliasNext = pAlias->next;
3031                 if (pAliasNext) {
3032          ast_cli(a->fd,"\t%-30s\t%-30s\n",pAlias->value, pAliasNext->value);
3033                         pAlias = pAliasNext->next;
3034       }
3035       else{
3036          ast_cli(a->fd,"\t%-30s\n",pAlias->value);
3037                         pAlias = pAlias->next;
3038                 }
3039         }
3040         return CLI_SUCCESS;
3041 }
3042
3043 static struct ast_cli_entry cli_ooh323[] = {
3044         AST_CLI_DEFINE(handle_cli_ooh323_set_debug,     "Enable/Disable OOH323 debugging"),
3045         AST_CLI_DEFINE(handle_cli_ooh323_show_config, "Show details on global configuration of H.323 channel driver"),
3046         AST_CLI_DEFINE(handle_cli_ooh323_show_peer,     "Show details on specific OOH323 peer"),
3047         AST_CLI_DEFINE(handle_cli_ooh323_show_peers,  "Show defined OOH323 peers"),
3048         AST_CLI_DEFINE(handle_cli_ooh323_show_user,     "Show details on specific OOH323 user"),
3049         AST_CLI_DEFINE(handle_cli_ooh323_show_users,  "Show defined OOH323 users"),
3050         AST_CLI_DEFINE(handle_cli_ooh323_reload, "reload ooh323 config")
3051 };
3052
3053
3054 static int load_module(void)
3055 {
3056         int res;
3057         struct ooAliases * pNewAlias = NULL;
3058         struct ooh323_peer *peer = NULL;
3059         OOH225MsgCallbacks h225Callbacks = {0, 0, 0, 0};
3060
3061         OOH323CALLBACKS h323Callbacks = {
3062                 .onNewCallCreated = onNewCallCreated,
3063                 .onAlerting = onAlerting,
3064                 .onProgress = onProgress,
3065                 .onIncomingCall = NULL,
3066                 .onOutgoingCall = onOutgoingCall,
3067                 .onCallEstablished = onCallEstablished,
3068                 .onCallCleared = onCallCleared,
3069                 .openLogicalChannels = NULL,
3070                 .onReceivedDTMF = ooh323_onReceivedDigit,
3071                 .onModeChanged = onModeChanged
3072         };
3073
3074         ast_log(LOG_NOTICE, 
3075                 "---------------------------------------------------------------------------------\n"
3076                 "---  ******* IMPORTANT NOTE ***********\n"
3077                 "---\n"
3078                 "---  This module is currently unsupported.  Use it at your own risk.\n"
3079                 "---\n"
3080                 "---------------------------------------------------------------------------------\n");
3081
3082         myself = ast_module_info->self;
3083
3084         h225Callbacks.onReceivedSetup = &ooh323_onReceivedSetup;
3085
3086         userl.users = NULL;
3087         ast_mutex_init(&userl.lock);
3088         peerl.peers = NULL;
3089         ast_mutex_init(&peerl.lock);
3090  
3091 #if 0           
3092         ast_register_atexit(&ast_ooh323c_exit);
3093 #endif
3094
3095         if (!(sched = sched_context_create())) {
3096                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
3097         }
3098         if (!(io = io_context_create())) {
3099                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
3100         }
3101
3102
3103         if (!(res = reload_config(0))) {
3104                 /* Make sure we can register our OOH323 channel type */
3105                 if (ast_channel_register(&ooh323_tech)) {
3106                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
3107                         return 0;
3108                 }
3109                 ast_rtp_glue_register(&ooh323_rtp);
3110                 ast_udptl_proto_register(&ooh323_udptl);
3111                 ast_cli_register_multiple(cli_ooh323, sizeof(cli_ooh323) / sizeof(struct ast_cli_entry));
3112
3113                  /* fire up the H.323 Endpoint */                
3114                 if (OO_OK != ooH323EpInitialize(OO_CALLMODE_AUDIOCALL, gLogFile)) {
3115          ast_log(LOG_ERROR, "Failed to initialize OOH323 endpoint-"
3116                             "OOH323 Disabled\n");
3117                         return 1;
3118                 }
3119
3120                 if (gIsGateway)
3121                         ooH323EpSetAsGateway();
3122
3123                 ooH323EpSetVersionInfo(t35countrycode, t35extensions, manufacturer,
3124                                                                          vendor, version);
3125                 ooH323EpDisableAutoAnswer();
3126                 ooH323EpSetH225MsgCallbacks(h225Callbacks);
3127                 ooH323EpSetTraceLevel(gTRCLVL);
3128                 ooH323EpSetLocalAddress(gIP, gPort);
3129                 ooH323EpSetCallerID(gCallerID);
3130  
3131       if(ooH323EpSetTCPPortRange(ooconfig.mTCPPortStart, 
3132                                  ooconfig.mTCPPortEnd) == OO_FAILED) {
3133          ast_log(LOG_ERROR, "h225portrange: Failed to set range\n");
3134       }
3135
3136                 /* Set aliases if any */
3137                 for (pNewAlias = gAliasList; pNewAlias; pNewAlias = pNewAlias->next) {
3138                         switch (pNewAlias->type) {
3139                         case T_H225AliasAddress_h323_ID:
3140                                 ooH323EpAddAliasH323ID(pNewAlias->value);
3141                                 break;
3142                         case T_H225AliasAddress_dialedDigits:   
3143                                 ooH323EpAddAliasDialedDigits(pNewAlias->value);
3144                                 break;
3145                         case T_H225AliasAddress_email_ID:       
3146                                 ooH323EpAddAliasEmailID(pNewAlias->value);
3147                                 break;
3148          default:
3149             ;
3150                         }
3151                 }
3152
3153                 ast_mutex_lock(&peerl.lock);
3154                 peer = peerl.peers;
3155                 while (peer) {
3156          if(peer->h323id) ooH323EpAddAliasH323ID(peer->h323id);
3157          if(peer->email)  ooH323EpAddAliasEmailID(peer->email);
3158          if(peer->e164)   ooH323EpAddAliasDialedDigits(peer->e164);
3159          if(peer->url)    ooH323EpAddAliasURLID(peer->url);
3160                         peer = peer->next;
3161                 }
3162                 ast_mutex_unlock(&peerl.lock);
3163         
3164
3165                 if (gMediaWaitForConnect)
3166                         ooH323EpEnableMediaWaitForConnect();
3167                 else 
3168                         ooH323EpDisableMediaWaitForConnect();
3169
3170                 /* Fast start and tunneling options */
3171                 if (gFastStart)
3172                         ooH323EpEnableFastStart();
3173                 else
3174                         ooH323EpDisableFastStart();
3175
3176                 if (!gTunneling)
3177                         ooH323EpDisableH245Tunneling();
3178
3179                 if (gBeMaster)
3180                         ooH323EpTryBeMaster(1);
3181
3182                 ooH323EpEnableManualRingback();
3183
3184                 /* Gatekeeper */
3185                 if (gRasGkMode == RasUseSpecificGatekeeper)
3186                         ooGkClientInit(gRasGkMode, gGatekeeper, 0);
3187                 else if (gRasGkMode == RasDiscoverGatekeeper)
3188                         ooGkClientInit(gRasGkMode, 0, 0);
3189
3190                 /* Register callbacks */
3191                 ooH323EpSetH323Callbacks(h323Callbacks);
3192
3193                 /* Add endpoint capabilities */
3194                 if (ooh323c_set_capability(&gPrefs, gCapability, gDTMFMode, gDTMFCodec) < 0) {
3195                         ast_log(LOG_ERROR, "Capabilities failure for OOH323. OOH323 Disabled.\n");
3196                         return 1;
3197                 }
3198   
3199                 /* Create H.323 listener */
3200                 if (ooCreateH323Listener() != OO_OK) {
3201          ast_log(LOG_ERROR, "OOH323 Listener Creation failure. "
3202                             "OOH323 DISABLED\n");
3203                 
3204                         ooH323EpDestroy();
3205                         return 1;
3206                 }
3207
3208                 if (ooh323c_start_stack_thread() < 0) {
3209          ast_log(LOG_ERROR, "Failed to start OOH323 stack thread. "
3210                             "OOH323 DISABLED\n");
3211                         ooH323EpDestroy();
3212                         return 1;
3213                 }
3214                 /* And start the monitor for the first time */
3215                 restart_monitor();
3216         }
3217
3218         return 0;
3219 }
3220
3221
3222 static void *do_monitor(void *data)
3223 {
3224         int res;
3225         int reloading;
3226         struct ooh323_pvt *h323 = NULL;
3227         time_t t;
3228
3229         for (;;) {
3230                 struct ooh323_pvt *h323_next;
3231                 /* Check for a reload request */
3232                 ast_mutex_lock(&h323_reload_lock);
3233                 reloading = h323_reloading;
3234                 h323_reloading = 0;
3235                 ast_mutex_unlock(&h323_reload_lock);
3236                 if (reloading) {
3237                         ast_verb(1, "Reloading H.323\n");
3238                         ooh323_do_reload();
3239                 }
3240
3241                 /* Check for interfaces needing to be killed */
3242                 ast_mutex_lock(&iflock);
3243                 time(&t);
3244                 h323 = iflist;
3245                 while (h323) {
3246                         h323_next = h323->next;
3247
3248                         /* TODO: Need to add rtptimeout keepalive support */
3249                         if (ast_test_flag(h323, H323_NEEDDESTROY)) {
3250                                 ooh323_destroy (h323);
3251          } /* else if (ast_test_flag(h323, H323_NEEDSTART) && h323->owner) {
3252           ast_channel_lock(h323->owner);
3253           if (ast_pbx_start(h323->owner)) {
3254             ast_log(LOG_WARNING, "Unable to start PBX on %s\n", h323->owner->name);
3255             ast_channel_unlock(h323->owner);
3256             ast_hangup(h323->owner);
3257           }
3258           ast_channel_unlock(h323->owner);
3259           ast_clear_flag(h323, H323_NEEDSTART);
3260          } */
3261                         h323 = h323_next;
3262                 }
3263                 ast_mutex_unlock(&iflock);
3264                 pthread_testcancel();
3265
3266                 /* Wait for sched or io */
3267                 res = ast_sched_wait(sched);
3268                 if ((res < 0) || (res > 1000)) {
3269                         res = 1000;
3270                 }
3271                 res = ast_io_wait(io, res);
3272                 pthread_testcancel();
3273                 ast_mutex_lock(&monlock);
3274                 if (res >= 0) {
3275                         ast_sched_runq(sched);
3276                 }
3277                 ast_mutex_unlock(&monlock);
3278         }
3279         /* Never reached */
3280         return NULL;
3281 }
3282
3283 int restart_monitor(void)
3284 {
3285         pthread_attr_t attr;
3286
3287         /* If we're supposed to be stopped -- stay stopped */
3288         if (monitor_thread == AST_PTHREADT_STOP)
3289                 return 0;
3290         if (ast_mutex_lock(&monlock)) {
3291                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
3292                 return -1;
3293         }
3294         if (monitor_thread == pthread_self()) {
3295                 ast_mutex_unlock(&monlock);
3296                 ast_log(LOG_WARNING, "Cannot kill myself\n");
3297                 return -1;
3298         }
3299         if (monitor_thread != AST_PTHREADT_NULL) {
3300                 /* Wake up the thread */
3301                 pthread_kill(monitor_thread, SIGURG);
3302         } else {
3303                 pthread_attr_init(&attr);
3304                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
3305                 /* Start a new monitor */
3306                 if (ast_pthread_create(&monitor_thread, &attr, do_monitor, NULL) < 0) {
3307                         ast_mutex_unlock(&monlock);
3308                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
3309                         return -1;
3310                 }
3311         }
3312         ast_mutex_unlock(&monlock);
3313         return 0;
3314 }
3315
3316
3317
3318 int ooh323_destroy(struct ooh323_pvt *p)
3319 {
3320         /* NOTE: Assumes iflock already acquired */
3321         struct ooh323_pvt *prev = NULL, *cur = NULL;
3322         struct ooh323_user *user = NULL;
3323
3324         if (gH323Debug) {
3325                 ast_verbose("---   ooh323_destroy \n");
3326
3327                 if (p)
3328                         ast_verbose(" Destroying %s\n", p->username);
3329         }
3330
3331         cur = iflist;
3332         while (cur) {
3333                 if (cur == p) { break; }
3334                 prev = cur;
3335                 cur = cur->next;
3336         }
3337
3338         if (cur) {
3339                 ast_mutex_lock(&cur->lock);
3340                 if (prev)
3341                         prev->next = cur->next;
3342                 else
3343                         iflist = cur->next;
3344
3345                 if (cur->callToken) {
3346                         if (gH323Debug) 
3347                                 ast_verbose(" Destroying %s\n", cur->callToken);
3348                         ast_free(cur->callToken);
3349                         cur->callToken = 0;
3350                 }
3351
3352                 if (cur->username) {
3353                         free(cur->username);
3354                         cur->username = 0;
3355                 }
3356
3357                 if (cur->host) {
3358                         free(cur->host);
3359                         cur->host = 0;
3360                 }
3361
3362                 if (cur->callerid_name) {
3363                         free(cur->callerid_name);
3364                         cur->callerid_name = 0;
3365                 }
3366                 
3367                 if (cur->callerid_num) {
3368                         free(cur->callerid_num);
3369                         cur->callerid_num = 0;
3370                 }
3371
3372                 if (cur->rtp) {
3373                         ast_rtp_instance_destroy(cur->rtp);
3374                         cur->rtp = NULL;
3375                 }
3376
3377                 if (cur->udptl) {
3378                         ast_udptl_destroy(cur->udptl);
3379                         cur->udptl = NULL;
3380                 }
3381         
3382                 /* Unlink us from the owner if we have one */
3383                 if (cur->owner) {
3384                         while(ast_channel_trylock(cur->owner)) {
3385                                 ast_debug(1,"Failed to grab lock, trying again\n");
3386                                 DEADLOCK_AVOIDANCE(&cur->lock);
3387                         }           
3388                         ast_debug(1, "Detaching from %s\n", cur->owner->name);
3389                         cur->owner->tech_pvt = NULL;
3390                         ast_channel_unlock(cur->owner);
3391                         cur->owner = NULL;
3392                         ast_module_unref(myself);
3393                 }
3394   
3395                 if (cur->vad) {
3396                         ast_dsp_free(cur->vad);
3397                         cur->vad = NULL;
3398                 }
3399
3400 /* decrement user/peer count */
3401
3402       if(!ast_test_flag(cur, H323_OUTGOING)) {
3403          if (cur->neighbor.user) {
3404           user = find_user(p->callerid_name, cur->neighbor.user);
3405           if(user && user->inUse > 0) {
3406                 ast_mutex_lock(&user->lock);
3407                 user->inUse--;
3408                 ast_mutex_unlock(&user->lock);
3409           }
3410           free(cur->neighbor.user);
3411          }
3412       } else {
3413 /* outgoing limit decrement here !!! */
3414       }
3415
3416                 ast_mutex_unlock(&cur->lock);
3417                 ast_mutex_destroy(&cur->lock);
3418
3419                 ast_free(cur);
3420         }
3421
3422         if (gH323Debug)
3423                 ast_verbose("+++   ooh323_destroy\n");
3424
3425         return 0;
3426 }
3427
3428 int delete_peers()
3429 {
3430         struct ooh323_peer *cur = NULL, *prev = NULL;
3431         ast_mutex_lock(&peerl.lock);
3432         cur = peerl.peers;
3433         while (cur) {
3434                 prev = cur;
3435                 cur = cur->next;
3436
3437                 ast_mutex_destroy(&prev->lock);
3438       if(prev->h323id)   free(prev->h323id);
3439       if(prev->email)    free(prev->email);
3440       if(prev->url)      free(prev->url);
3441       if(prev->e164)     free(prev->e164);
3442       if(prev->rtpmask) {
3443                 ast_mutex_lock(&prev->rtpmask->lock);
3444                 prev->rtpmask->inuse--;
3445                 ast_mutex_unlock(&prev->rtpmask->lock);
3446                 if (prev->rtpmask->inuse == 0) {
3447                         regfree(&prev->rtpmask->regex);
3448                         ast_mutex_destroy(&prev->rtpmask->lock);
3449                         free(prev->rtpmask);
3450                 }
3451       }
3452                 free(prev);
3453
3454                 if (cur == peerl.peers) {
3455                         break;
3456                 }
3457         }
3458         peerl.peers = NULL;
3459         ast_mutex_unlock(&peerl.lock);
3460         return 0;
3461 }
3462
3463 int delete_users()
3464 {
3465         struct ooh323_user *cur = NULL, *prev = NULL;
3466         ast_mutex_lock(&userl.lock);
3467         cur = userl.users;
3468         while (cur) {
3469                 prev = cur;
3470                 cur = cur->next;
3471                 ast_mutex_destroy(&prev->lock);
3472
3473                 if(prev->rtpmask) {
3474                         ast_mutex_lock(&prev->rtpmask->lock);
3475                         prev->rtpmask->inuse--;
3476                         ast_mutex_unlock(&prev->rtpmask->lock);
3477                         if (prev->rtpmask->inuse == 0) {
3478                                 regfree(&prev->rtpmask->regex);
3479                                 ast_mutex_destroy(&prev->rtpmask->lock);
3480                                 free(prev->rtpmask);
3481                         }
3482                 }
3483                 free(prev);
3484                 if (cur == userl.users) {
3485                         break;
3486                 }
3487         }
3488         userl.users = NULL;
3489         ast_mutex_unlock(&userl.lock);
3490         return 0;
3491 }
3492   
3493 static int unload_module(void)
3494 {
3495         struct ooh323_pvt *p;
3496         struct ooAliases *cur = NULL, *prev = NULL;
3497
3498         if (gH323Debug) {
3499                 ast_verbose("--- ooh323  unload_module \n");
3500         }
3501         /* First, take us out of the channel loop */
3502         ast_cli_unregister_multiple(cli_ooh323, sizeof(cli_ooh323) / sizeof(struct ast_cli_entry));
3503         ast_rtp_glue_unregister(&ooh323_rtp);
3504         ast_udptl_proto_unregister(&ooh323_udptl);
3505         ast_channel_unregister(&ooh323_tech);
3506 #if 0
3507         ast_unregister_atexit(&ast_ooh323c_exit);
3508 #endif
3509
3510         if (gH323Debug) {
3511                 ast_verbose("  unload_module - hanging up all interfaces\n");
3512         }
3513         if (!ast_mutex_lock(&iflock)) {