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