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