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