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