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