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