Split capability definitions into own source file
[asterisk/asterisk.git] / channels / h323 / ast_h323.cxx
1 #ifndef _GNU_SOURCE
2 #define _GNU_SOURCE
3 #endif
4 /*
5  * ast_h323.cpp
6  *
7  * OpenH323 Channel Driver for ASTERISK PBX.
8  *                      By  Jeremy McNamara
9  *                      For The NuFone Network
10  *
11  * chan_h323 has been derived from code created by
12  *               Michael Manousos and Mark Spencer
13  *
14  * This file is part of the chan_h323 driver for Asterisk
15  *
16  * chan_h323 is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation; either version 2 of the License, or
19  * (at your option) any later version.
20  *
21  * chan_h323 is distributed WITHOUT ANY WARRANTY; without even
22  * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
23  * PURPOSE. See the GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program; if not, write to the Free Software
27  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28  *
29  * Version Info: $Id$
30  */
31 #include <arpa/inet.h>
32
33 #include <list>
34 #include <string>
35 #include <algorithm>
36
37 #include <ptlib.h>
38 #include <h323.h>
39 #include <h323pdu.h>
40 #include <mediafmt.h>
41 #include <lid.h>
42
43 #ifdef __cplusplus
44 extern "C" {
45 #endif
46 #include "asterisk/logger.h"
47 #include "asterisk/channel.h"
48 #include "asterisk/astobj.h"
49 #ifdef __cplusplus
50 }
51 #endif
52
53 #include "chan_h323.h"
54 #include "ast_h323.h"
55 #include "cisco-h225.h"
56 #include "caps_h323.h"
57
58 /* PWlib Required Components  */
59 #define MAJOR_VERSION 1
60 #define MINOR_VERSION 0
61 #define BUILD_TYPE    ReleaseCode
62 #define BUILD_NUMBER  0
63
64 /** Counter for the number of connections */
65 static int channelsOpen;
66
67 /**
68  * We assume that only one endPoint should exist.
69  * The application cannot run the h323_end_point_create() more than once
70  * FIXME: Singleton this, for safety
71  */
72 static MyH323EndPoint *endPoint = NULL;
73
74 /** PWLib entry point */
75 static MyProcess *localProcess = NULL;
76
77 static int _timerChangePipe[2];
78
79 static unsigned traceOptions = PTrace::Timestamp | PTrace::Thread | PTrace::FileAndLine;
80
81 class PAsteriskLog : public PObject, public iostream {
82         PCLASSINFO(PAsteriskLog, PObject);
83
84         public:
85         PAsteriskLog() : iostream(cout.rdbuf()) { init(&buffer); }
86         ~PAsteriskLog() { flush(); }
87
88         private:
89         PAsteriskLog(const PAsteriskLog &) : iostream(cout.rdbuf()) { }
90         PAsteriskLog & operator=(const PAsteriskLog &) { return *this; }
91
92         class Buffer : public streambuf {
93                 public:
94                 virtual int overflow(int=EOF);
95                 virtual int underflow();
96                 virtual int sync();
97                 PString string;
98         } buffer;
99         friend class Buffer;
100 };
101
102 static PAsteriskLog *logstream = NULL;
103
104 int PAsteriskLog::Buffer::overflow(int c)
105 {
106         if (pptr() >= epptr()) {
107                 int ppos = pptr() - pbase();
108                 char *newptr = string.GetPointer(string.GetSize() + 2000);
109                 setp(newptr, newptr + string.GetSize() - 1);
110                 pbump(ppos);
111         }
112         if (c != EOF) {
113                 *pptr() = (char)c;
114                 pbump(1);
115         }
116         return 0;
117 }
118
119 int PAsteriskLog::Buffer::underflow()
120 {
121         return EOF;
122 }
123
124 int PAsteriskLog::Buffer::sync()
125 {
126         char *str = strdup(string);
127         char *s, *s1;
128         char c;
129
130         /* Pass each line with different ast_verbose() call */
131         for (s = str; s && *s; s = s1) {
132                 s1 = strchr(s, '\n');
133                 if (!s1)
134                         s1 = s + strlen(s);
135                 else
136                         s1++;
137                 c = *s1;
138                 *s1 = '\0';
139                 ast_verbose("%s", s);
140                 *s1 = c;
141         }
142         free(str);
143
144         string = PString();
145         char *base = string.GetPointer(2000);
146         setp(base, base + string.GetSize() - 1);
147         return 0;
148 }
149
150 static ostream &my_endl(ostream &os)
151 {
152         if (logstream) {
153                 PTrace::SetOptions(traceOptions);
154                 return PTrace::End(os);
155         }
156         return endl(os);
157 }
158
159 #define cout \
160         (logstream ? (PTrace::ClearOptions((unsigned)-1), PTrace::Begin(0, __FILE__, __LINE__)) : std::cout)
161 #define endl my_endl
162
163 /* Special class designed to call cleanup code on module destruction */
164 class MyH323_Shutdown {
165         public:
166         MyH323_Shutdown() { };
167         ~MyH323_Shutdown()
168         {
169                 h323_end_process();
170         };
171 };
172
173 MyProcess::MyProcess(): PProcess("The NuFone Network's",
174                         "H.323 Channel Driver for Asterisk",
175                         MAJOR_VERSION, MINOR_VERSION, BUILD_TYPE, BUILD_NUMBER)
176 {
177         /* Call shutdown when module being unload or asterisk has been stopped */
178         static MyH323_Shutdown x;
179
180         /* Fix missed one in PWLib */
181         PX_firstTimeStart = FALSE;
182         Resume();
183 }
184
185 MyProcess::~MyProcess()
186 {
187         _timerChangePipe[0] = timerChangePipe[0];
188         _timerChangePipe[1] = timerChangePipe[1];
189 }
190
191 void MyProcess::Main()
192 {
193         PTrace::Initialise(PTrace::GetLevel(), NULL, traceOptions);
194         PTrace::SetStream(logstream);
195
196         cout << "  == Creating H.323 Endpoint" << endl;
197         if (endPoint) {
198                 cout << "  == ENDPOINT ALREADY CREATED" << endl;
199                 return;
200         }
201         endPoint = new MyH323EndPoint();
202         /* Due to a bug in the H.323 recomendation/stack we should request a sane
203            amount of bandwidth from the GK - this function is ignored if not using a GK
204            We are requesting 128 (64k in each direction), which is the worst case codec. */
205         endPoint->SetInitialBandwidth(1280);
206 }
207
208 void PAssertFunc(const char *msg)
209 {
210         ast_log(LOG_ERROR, "%s\n", msg);
211         /* XXX: Probably we need to crash here */
212 }
213
214
215 /** MyH323EndPoint
216   */
217 MyH323EndPoint::MyH323EndPoint()
218                 : H323EndPoint()
219 {
220         // Capabilities will be negotiated on per-connection basis
221         capabilities.RemoveAll();
222 }
223
224 /** The fullAddress parameter is used directly in the MakeCall method so
225   * the General form for the fullAddress argument is :
226   * [alias@][transport$]host[:port]
227   * default values:     alias = the same value as host.
228   *                                     transport = ip.
229   *                                     port = 1720.
230   */
231 int MyH323EndPoint::MyMakeCall(const PString & dest, PString & token, void *_callReference, void *_opts)
232 {
233         PString fullAddress;
234         MyH323Connection * connection;
235         H323Transport *transport = NULL;
236         unsigned int *callReference = (unsigned int *)_callReference;
237         call_options_t *opts = (call_options_t *)_opts;
238
239         /* Determine whether we are using a gatekeeper or not. */
240         if (GetGatekeeper()) {
241                 fullAddress = dest;
242                 if (h323debug) {
243                         cout << " -- Making call to " << fullAddress << " using gatekeeper." << endl;
244                 }
245         } else {
246                 fullAddress = dest;
247                 if (h323debug) {
248                         cout << " -- Making call to " << fullAddress << " without gatekeeper." << endl;
249                 }
250                 /* Use bindaddr for outgoing calls too if we don't use gatekeeper */
251                 if (listeners.GetSize() > 0) {
252                         H323TransportAddress taddr = listeners[0].GetTransportAddress();
253                         PIPSocket::Address addr;
254                         WORD port;
255                         if (taddr.GetIpAndPort(addr, port)) {
256                                 /* Create own transport for specific addresses only */
257                                 if (addr) {
258                                         if (h323debug)
259                                                 cout << "Using " << addr << " for outbound call" << endl;
260                                         transport = new MyH323TransportTCP(*this, addr);
261                                         if (!transport)
262                                                 cout << "Unable to create transport for outgoing call" << endl;
263                                 }
264                         } else
265                                 cout << "Unable to get address and port" << endl;
266                 }
267         }
268         if (!(connection = (MyH323Connection *)H323EndPoint::MakeCallLocked(fullAddress, token, opts, transport))) {
269                 if (h323debug) {
270                         cout << "Error making call to \"" << fullAddress << '"' << endl;
271                 }
272                 return 1;
273         }
274         *callReference = connection->GetCallReference();
275
276         if (h323debug) {
277                 cout << "\t-- " << GetLocalUserName() << " is calling host " << fullAddress << endl;
278                 cout << "\t-- Call token is " << (const char *)token << endl;
279                 cout << "\t-- Call reference is " << *callReference << endl;
280                 cout << "\t-- DTMF Payload is " << connection->dtmfCodec << endl;
281         }
282         connection->Unlock();
283         return 0;
284 }
285
286 void MyH323EndPoint::SetEndpointTypeInfo( H225_EndpointType & info ) const
287 {
288         H323EndPoint::SetEndpointTypeInfo(info);
289
290         if (terminalType == e_GatewayOnly){
291                 info.RemoveOptionalField(H225_EndpointType::e_terminal);
292                 info.IncludeOptionalField(H225_EndpointType::e_gateway);
293         }
294
295         info.m_gateway.IncludeOptionalField(H225_GatewayInfo::e_protocol);
296         info.m_gateway.m_protocol.SetSize(1);
297         H225_SupportedProtocols &protocol=info.m_gateway.m_protocol[0];
298         protocol.SetTag(H225_SupportedProtocols::e_voice);
299         PINDEX as=SupportedPrefixes.GetSize();
300         ((H225_VoiceCaps &)protocol).m_supportedPrefixes.SetSize(as);
301         for (PINDEX p=0; p<as; p++) {
302                 H323SetAliasAddress(SupportedPrefixes[p], ((H225_VoiceCaps &)protocol).m_supportedPrefixes[p].m_prefix, H225_AliasAddress::e_dialedDigits);
303         }
304 }
305
306 void MyH323EndPoint::SetGateway(void)
307 {
308         terminalType = e_GatewayOnly;
309 }
310
311 BOOL MyH323EndPoint::ClearCall(const PString & token, H323Connection::CallEndReason reason)
312 {
313         if (h323debug) {
314 #ifdef PTRACING
315                 cout << "\t-- ClearCall: Request to clear call with token " << token << ", cause " << reason << endl;
316 #else
317                 cout << "\t-- ClearCall: Request to clear call with token " << token << ", cause [" << (int)reason << "]" << endl;
318 #endif
319         }
320         return H323EndPoint::ClearCall(token, reason);
321 }
322
323 BOOL MyH323EndPoint::ClearCall(const PString & token)
324 {
325         if (h323debug) {
326                 cout << "\t-- ClearCall: Request to clear call with token " << token << endl;
327         }
328         return H323EndPoint::ClearCall(token, H323Connection::EndedByLocalUser);
329 }
330
331 void MyH323EndPoint::SendUserTone(const PString &token, char tone)
332 {
333         H323Connection *connection = NULL;
334
335         connection = FindConnectionWithLock(token);
336         if (connection != NULL) {
337                 connection->SendUserInputTone(tone, 500);
338                 connection->Unlock();
339         }
340 }
341
342 void MyH323EndPoint::OnClosedLogicalChannel(H323Connection & connection, const H323Channel & channel)
343 {
344         channelsOpen--;
345         if (h323debug) {
346                 cout << "\t\tchannelsOpen = " << channelsOpen << endl;
347         }
348         H323EndPoint::OnClosedLogicalChannel(connection, channel);
349 }
350
351 BOOL MyH323EndPoint::OnConnectionForwarded(H323Connection & connection,
352                 const PString & forwardParty,
353                 const H323SignalPDU & pdu)
354 {
355         if (h323debug) {
356                 cout << "\t-- Call Forwarded to " << forwardParty << endl;
357         }
358         return FALSE;
359 }
360
361 BOOL MyH323EndPoint::ForwardConnection(H323Connection & connection,
362                 const PString & forwardParty,
363                 const H323SignalPDU & pdu)
364 {
365         if (h323debug) {
366                 cout << "\t-- Forwarding call to " << forwardParty << endl;
367         }
368         return H323EndPoint::ForwardConnection(connection, forwardParty, pdu);
369 }
370
371 void MyH323EndPoint::OnConnectionEstablished(H323Connection & connection, const PString & estCallToken)
372 {
373         if (h323debug) {
374                 cout << "\t=-= In OnConnectionEstablished for call " << connection.GetCallReference() << endl;
375                 cout << "\t\t-- Connection Established with \"" << connection.GetRemotePartyName() << "\"" << endl;
376         }
377         on_connection_established(connection.GetCallReference(), (const char *)connection.GetCallToken());
378 }
379
380 /** OnConnectionCleared callback function is called upon the dropping of an established
381   * H323 connection.
382   */
383 void MyH323EndPoint::OnConnectionCleared(H323Connection & connection, const PString & clearedCallToken)
384 {
385         PString remoteName = connection.GetRemotePartyName();
386
387         switch (connection.GetCallEndReason()) {
388                 case H323Connection::EndedByCallForwarded:
389                         if (h323debug) {
390                                 cout << "-- " << remoteName << " has forwarded the call" << endl;
391                         }
392                         break;
393                 case H323Connection::EndedByRemoteUser:
394                         if (h323debug) {
395                                 cout << "-- " << remoteName << " has cleared the call" << endl;
396                         }
397                         break;
398                 case H323Connection::EndedByCallerAbort:
399                         if (h323debug) {
400                                 cout << "-- " << remoteName << " has stopped calling" << endl;
401                         }
402                         break;
403                 case H323Connection::EndedByRefusal:
404                         if (h323debug) {
405                                 cout << "-- " << remoteName << " did not accept your call" << endl;
406                         }
407                         break;
408                 case H323Connection::EndedByRemoteBusy:
409                         if (h323debug) {
410                                 cout << "-- " << remoteName << " was busy" << endl;
411                         }
412                         break;
413                 case H323Connection::EndedByRemoteCongestion:
414                         if (h323debug) {
415                                 cout << "-- Congested link to " << remoteName << endl;
416                         }
417                         break;
418                 case H323Connection::EndedByNoAnswer:
419                         if (h323debug) {
420                                 cout << "-- " << remoteName << " did not answer your call" << endl;
421                         }
422                         break;
423                 case H323Connection::EndedByTransportFail:
424                         if (h323debug) {
425                                 cout << "-- Call with " << remoteName << " ended abnormally" << endl;
426                         }
427                         break;
428                 case H323Connection::EndedByCapabilityExchange:
429                         if (h323debug) {
430                                 cout << "-- Could not find common codec with " << remoteName << endl;
431                         }
432                         break;
433                 case H323Connection::EndedByNoAccept:
434                         if (h323debug) {
435                                 cout << "-- Did not accept incoming call from " << remoteName << endl;
436                         }
437                         break;
438                 case H323Connection::EndedByAnswerDenied:
439                         if (h323debug) {
440                                 cout << "-- Refused incoming call from " << remoteName << endl;
441                         }
442                         break;
443                 case H323Connection::EndedByNoUser:
444                         if (h323debug) {
445                                 cout << "-- Remote endpoint could not find user: " << remoteName << endl;
446                         }
447                         break;
448                 case H323Connection::EndedByNoBandwidth:
449                         if (h323debug) {
450                                 cout << "-- Call to " << remoteName << " aborted, insufficient bandwidth." << endl;
451                         }
452                         break;
453                 case H323Connection::EndedByUnreachable:
454                         if (h323debug) {
455                                 cout << "-- " << remoteName << " could not be reached." << endl;
456                         }
457                         break;
458                 case H323Connection::EndedByHostOffline:
459                         if (h323debug) {
460                                 cout << "-- " << remoteName << " is not online." << endl;
461                         }
462                         break;
463                 case H323Connection::EndedByNoEndPoint:
464                         if (h323debug) {
465                                 cout << "-- No phone running for " << remoteName << endl;
466                         }
467                         break;
468                 case H323Connection::EndedByConnectFail:
469                         if (h323debug) {
470                                 cout << "-- Transport error calling " << remoteName << endl;
471                         }
472                         break;
473                 default:
474                         if (h323debug) {
475 #ifdef PTRACING
476                                 cout << " -- Call with " << remoteName << " completed (" << connection.GetCallEndReason() << ")" << endl;
477 #else
478                                 cout << " -- Call with " << remoteName << " completed ([" << (int)connection.GetCallEndReason() << "])" << endl;
479 #endif
480                         }
481         }
482
483         if (connection.IsEstablished()) {
484                 if (h323debug) {
485                         cout << "\t-- Call duration " << setprecision(0) << setw(5) << (PTime() - connection.GetConnectionStartTime()) << endl;
486                 }
487         }
488         /* Invoke the PBX application registered callback */
489         on_connection_cleared(connection.GetCallReference(), clearedCallToken);
490         return;
491 }
492
493 H323Connection * MyH323EndPoint::CreateConnection(unsigned callReference, void *userData, H323Transport *transport, H323SignalPDU *setupPDU)
494 {
495         unsigned options = 0;
496         call_options_t *opts = (call_options_t *)userData;
497         MyH323Connection *conn;
498
499         if (opts && opts->fastStart) {
500                 options |= H323Connection::FastStartOptionEnable;
501         } else {
502                 options |= H323Connection::FastStartOptionDisable;
503         }
504         if (opts && opts->h245Tunneling) {
505                 options |= H323Connection::H245TunnelingOptionEnable;
506         } else {
507                 options |= H323Connection::H245TunnelingOptionDisable;
508         }
509 /* Disable until I can figure out the proper way to deal with this */
510 #if 0
511         if (opts->silenceSuppression) {
512                 options |= H323Connection::SilenceSuppresionOptionEnable;
513         } else {
514                 options |= H323Connection::SilenceSUppressionOptionDisable;
515         }
516 #endif
517         conn = new MyH323Connection(*this, callReference, options);
518         if (conn) {
519                 if (opts)
520                         conn->SetCallOptions(opts, (setupPDU ? TRUE : FALSE));
521         }
522         return conn;
523 }
524
525 /* MyH323Connection Implementation */
526 MyH323Connection::MyH323Connection(MyH323EndPoint & ep, unsigned callReference,
527                                                         unsigned options)
528         : H323Connection(ep, callReference, options)
529 {
530         cause = -1;
531         sessionId = 0;
532         bridging = FALSE;
533         progressSetup = progressAlert = 0;
534         dtmfMode = 0;
535         dtmfCodec = (RTP_DataFrame::PayloadTypes)0;
536         redirect_reason = -1;
537 #ifdef TUNNELLING
538         tunnelOptions = remoteTunnelOptions = 0;
539 #endif
540         if (h323debug) {
541                 cout << "       == New H.323 Connection created." << endl;
542         }
543         return;
544 }
545
546 MyH323Connection::~MyH323Connection()
547 {
548         if (h323debug) {
549                 cout << "       == H.323 Connection deleted." << endl;
550         }
551         return;
552 }
553
554 BOOL MyH323Connection::OnReceivedProgress(const H323SignalPDU &pdu)
555 {
556         BOOL isInband;
557         unsigned pi;
558
559         if (!H323Connection::OnReceivedProgress(pdu)) {
560                 return FALSE;
561         }
562
563         if (!pdu.GetQ931().GetProgressIndicator(pi))
564                 pi = 0;
565         if (h323debug) {
566                 cout << "\t- Progress Indicator: " << pi << endl;
567         }
568
569         switch(pi) {
570         case Q931::ProgressNotEndToEndISDN:
571         case Q931::ProgressInbandInformationAvailable:
572                 isInband = TRUE;
573                 break;
574         default:
575                 isInband = FALSE;
576         }
577         on_progress(GetCallReference(), (const char *)GetCallToken(), isInband);
578
579         return connectionState != ShuttingDownConnection;
580 }
581
582 H323Connection::AnswerCallResponse MyH323Connection::OnAnswerCall(const PString & caller,
583                                                                 const H323SignalPDU & setupPDU,
584                                                                 H323SignalPDU & connectPDU)
585 {
586         unsigned pi;
587
588         if (h323debug) {
589                 cout << "\t=-= In OnAnswerCall for call " << GetCallReference() << endl;
590         }
591
592         if (connectionState == ShuttingDownConnection)
593                 return H323Connection::AnswerCallDenied;
594
595         if (!setupPDU.GetQ931().GetProgressIndicator(pi)) {
596                 pi = 0;
597         }
598         if (h323debug) {
599                 cout << "\t\t- Progress Indicator: " << pi << endl;
600         }
601         if (progressAlert) {
602                 pi = progressAlert;
603         } else if (pi == Q931::ProgressOriginNotISDN) {
604                 pi = Q931::ProgressInbandInformationAvailable;
605         }
606         if (pi && alertingPDU) {
607                 alertingPDU->GetQ931().SetProgressIndicator(pi);
608         }
609         if (h323debug) {
610                 cout << "\t\t- Inserting PI of " << pi << " into ALERTING message" << endl;
611         }
612
613 #ifdef TUNNELLING
614         if (alertingPDU)
615                 EmbedTunneledInfo(*alertingPDU);
616         EmbedTunneledInfo(connectPDU);
617 #endif
618
619         if (!on_answer_call(GetCallReference(), (const char *)GetCallToken())) {
620                 return H323Connection::AnswerCallDenied;
621         }
622         /* The call will be answered later with "AnsweringCall()" function.
623          */
624         return ((pi || (fastStartState != FastStartDisabled)) ? AnswerCallDeferredWithMedia : AnswerCallDeferred);
625 }
626
627 BOOL MyH323Connection::OnAlerting(const H323SignalPDU & alertingPDU, const PString & username)
628 {
629         if (h323debug) {
630                 cout << "\t=-= In OnAlerting for call " << GetCallReference()
631                         << ": sessionId=" << sessionId << endl;
632                 cout << "\t-- Ringing phone for \"" << username << "\"" << endl;
633         }
634
635         if (on_progress) {
636                 BOOL isInband;
637                 unsigned alertingPI;
638
639                 if (!alertingPDU.GetQ931().GetProgressIndicator(alertingPI)) {
640                         alertingPI = 0;
641                 }
642                 if (h323debug) {
643                         cout << "\t\t- Progress Indicator: " << alertingPI << endl;
644                 }
645
646                 switch(alertingPI) {
647                 case Q931::ProgressNotEndToEndISDN:
648                 case Q931::ProgressInbandInformationAvailable:
649                         isInband = TRUE;
650                         break;
651                 default:
652                         isInband = FALSE;
653                 }
654                 on_progress(GetCallReference(), (const char *)GetCallToken(), isInband);
655         }
656         on_chan_ringing(GetCallReference(), (const char *)GetCallToken() );
657         return connectionState != ShuttingDownConnection;
658 }
659
660 void MyH323Connection::SetCallOptions(void *o, BOOL isIncoming)
661 {
662         call_options_t *opts = (call_options_t *)o;
663
664         progressSetup = opts->progress_setup;
665         progressAlert = opts->progress_alert;
666         dtmfCodec = (RTP_DataFrame::PayloadTypes)opts->dtmfcodec;
667         dtmfMode = opts->dtmfmode;
668
669         if (isIncoming) {
670                 fastStartState = (opts->fastStart ? FastStartInitiate : FastStartDisabled);
671                 h245Tunneling = (opts->h245Tunneling ? TRUE : FALSE);
672         } else {
673                 SetLocalPartyName(PString(opts->cid_num));
674                 SetDisplayName(PString(opts->cid_name));
675                 if (opts->redirect_reason >= 0) {
676                         rdnis = PString(opts->cid_rdnis);
677                         redirect_reason = opts->redirect_reason;
678                 }
679         }
680         tunnelOptions = opts->tunnelOptions;
681 }
682
683 void MyH323Connection::SetCallDetails(void *callDetails, const H323SignalPDU &setupPDU, BOOL isIncoming)
684 {
685         PString sourceE164;
686         PString destE164;
687         PString sourceAliases;
688         PString destAliases;
689         char *s, *s1;
690         call_details_t *cd = (call_details_t *)callDetails;
691
692         memset(cd, 0, sizeof(*cd));
693         cd->call_reference = GetCallReference();
694         cd->call_token = strdup((const char *)GetCallToken());
695
696         sourceE164 = "";
697         setupPDU.GetSourceE164(sourceE164);
698         cd->call_source_e164 = strdup((const char *)sourceE164);
699
700         destE164 = "";
701         setupPDU.GetDestinationE164(destE164);
702         cd->call_dest_e164 = strdup((const char *)destE164);
703
704         /* XXX Is it possible to have this information for outgoing calls too? XXX */
705         if (isIncoming) {
706                 PString sourceName;
707                 PIPSocket::Address Ip;
708                 WORD sourcePort;
709                 PString redirect_number;
710                 unsigned redirect_reason;
711
712                 sourceName = setupPDU.GetQ931().GetDisplayName();
713                 cd->call_source_name = strdup((const char *)sourceName);
714
715                 GetSignallingChannel()->GetRemoteAddress().GetIpAndPort(Ip, sourcePort);
716                 cd->sourceIp = strdup((const char *)Ip.AsString());
717
718                 if(setupPDU.GetQ931().GetRedirectingNumber(redirect_number, NULL, NULL, NULL, NULL, &redirect_reason, 0, 0, 0)) {
719                         cd->redirect_number = strdup((const char *)redirect_number);
720                         cd->redirect_reason = redirect_reason;
721                 }
722                 else
723                         cd->redirect_reason = -1;
724         }
725
726         /* Convert complex strings */
727         //  FIXME: deal more than one source alias
728         sourceAliases = setupPDU.GetSourceAliases();
729         s1 = strdup((const char *)sourceAliases);
730         if ((s = strchr(s1, ' ')) != NULL)
731                 *s = '\0';
732         if ((s = strchr(s1, '\t')) != NULL)
733                 *s = '\0';
734         cd->call_source_aliases = s1;
735
736         destAliases = setupPDU.GetDestinationAlias();
737         s1 = strdup((const char *)destAliases);
738         if ((s = strchr(s1, ' ')) != NULL)
739                 *s = '\0';
740         if ((s = strchr(s1, '\t')) != NULL)
741                 *s = '\0';
742         cd->call_dest_alias = s1;
743 }
744
745 #ifdef TUNNELLING
746 static BOOL FetchInformationElements(Q931 &q931, const PBYTEArray &data)
747 {
748         PINDEX offset = 0;
749
750         while (offset < data.GetSize()) {
751                 // Get field discriminator
752                 int discriminator = data[offset++];
753
754 #if 0
755                 /* Do not overwrite existing IEs */
756                 if (q931.HasIE((Q931::InformationElementCodes)discriminator)) {
757                         if ((discriminatir & 0x80) == 0)
758                                 offset += data[offset++];
759                         if (offset > data.GetSize())
760                                 return FALSE;
761                         continue;
762                 }
763 #endif
764
765                 PBYTEArray * item = new PBYTEArray;
766
767                 // For discriminator with high bit set there is no data
768                 if ((discriminator & 0x80) == 0) {
769                         int len = data[offset++];
770
771 #if 0           // That is not H.225 but regular Q.931 (ISDN) IEs
772                         if (discriminator == UserUserIE) {
773                                 // Special case of User-user field. See 7.2.2.31/H.225.0v4.
774                                 len <<= 8;
775                                 len |= data[offset++];
776
777                                 // we also have a protocol discriminator, which we ignore
778                                 offset++;
779
780                                 // before decrementing the length, make sure it is not zero
781                                 if (len == 0)
782                                         return FALSE;
783
784                                 // adjust for protocol discriminator
785                                 len--;
786                         }
787 #endif
788
789                         if (offset + len > data.GetSize()) {
790                                 delete item;
791                                 return FALSE;
792                         }
793
794                         memcpy(item->GetPointer(len), (const BYTE *)data+offset, len);
795                         offset += len;
796                 }
797
798                 q931.SetIE((Q931::InformationElementCodes)discriminator, *item);
799                 delete item;
800         }
801         return TRUE;
802 }
803
804 static BOOL FetchCiscoTunneledInfo(Q931 &q931, const H323SignalPDU &pdu)
805 {
806         BOOL res = FALSE;
807         const H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
808
809         if(uuPDU.HasOptionalField(H225_H323_UU_PDU::e_nonStandardControl)) {
810                 for(int i = 0; i < uuPDU.m_nonStandardControl.GetSize(); ++i) {
811                         const H225_NonStandardParameter &np = uuPDU.m_nonStandardControl[i];
812                         const H225_NonStandardIdentifier &id = np.m_nonStandardIdentifier;
813                         if (id.GetTag() == H225_NonStandardIdentifier::e_h221NonStandard) {
814                                 const H225_H221NonStandard &ni = id;
815                                 /* Check for Cisco */
816                                 if ((ni.m_t35CountryCode == 181) && (ni.m_t35Extension == 0) && (ni.m_manufacturerCode == 18)) {
817                                         const PBYTEArray &data = np.m_data;
818                                         if (h323debug)
819                                                 cout << setprecision(0) << "Received non-standard Cisco extension data " << np.m_data << endl;
820                                         CISCO_H225_H323_UU_NonStdInfo c;
821                                         PPER_Stream strm(data);
822                                         if (c.Decode(strm)) {
823                                                 BOOL haveIEs = FALSE;
824                                                 if (h323debug)
825                                                         cout << setprecision(0) << "H323_UU_NonStdInfo = " << c << endl;
826                                                 if (c.HasOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_protoParam)) {
827                                                         FetchInformationElements(q931, c.m_protoParam.m_qsigNonStdInfo.m_rawMesg);
828                                                         haveIEs = TRUE;
829                                                 }
830                                                 if (c.HasOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_commonParam)) {
831                                                         FetchInformationElements(q931, c.m_commonParam.m_redirectIEinfo.m_redirectIE);
832                                                         haveIEs = TRUE;
833                                                 }
834                                                 if (haveIEs && h323debug)
835                                                         cout << setprecision(0) << "Information elements collected:" << q931 << endl;
836                                                 res = TRUE;
837                                         } else {
838                                                 cout << "ERROR while decoding non-standard Cisco extension" << endl;
839                                                 return FALSE;
840                                         }
841                                 }
842                         }
843                 }
844         }
845         return res;
846 }
847
848 static BOOL EmbedCiscoTunneledInfo(H323SignalPDU &pdu)
849 {
850         const static Q931::InformationElementCodes codes[] =
851         { Q931::RedirectingNumberIE, Q931::FacilityIE };
852
853         BOOL res = FALSE;
854         BOOL notRedirOnly = FALSE;
855         Q931 tmpQ931;
856         Q931 &q931 = pdu.GetQ931();
857
858         for(unsigned i = 0; i < (sizeof(codes) / sizeof(codes[0])); ++i) {
859                 if (q931.HasIE(codes[i])) {
860                         tmpQ931.SetIE(codes[i], q931.GetIE(codes[i]));
861                         q931.RemoveIE(codes[i]);
862                         if (codes[i] != Q931::RedirectingNumberIE)
863                                 notRedirOnly = TRUE;
864                         res = TRUE;
865                 }
866         }
867         /* Have something to embed */
868         if (res) {
869                 PBYTEArray msg;
870                 if (!tmpQ931.Encode(msg))
871                         return FALSE;
872                 PBYTEArray ies(msg.GetPointer() + 5, msg.GetSize() - 5);
873
874                 H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
875                 if(!uuPDU.HasOptionalField(H225_H323_UU_PDU::e_nonStandardControl)) {
876                         uuPDU.IncludeOptionalField(H225_H323_UU_PDU::e_nonStandardControl);
877                         uuPDU.m_nonStandardControl.SetSize(0);
878                 }
879                 H225_NonStandardParameter *np = new H225_NonStandardParameter;
880                 uuPDU.m_nonStandardControl.Append(np);
881                 H225_NonStandardIdentifier &nsi = (*np).m_nonStandardIdentifier;
882                 nsi.SetTag(H225_NonStandardIdentifier::e_h221NonStandard);
883                 H225_H221NonStandard &ns = nsi;
884                 ns.m_t35CountryCode = 181;
885                 ns.m_t35Extension = 0;
886                 ns.m_manufacturerCode = 18;
887
888                 CISCO_H225_H323_UU_NonStdInfo c;
889                 c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_version);
890                 c.m_version = 0;
891
892                 if (notRedirOnly) {
893                         c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_protoParam);
894                         CISCO_H225_QsigNonStdInfo &qsigInfo = c.m_protoParam.m_qsigNonStdInfo;
895                         qsigInfo.m_iei = ies[0];
896                         qsigInfo.m_rawMesg = ies;
897                 } else {
898                         c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_commonParam);
899                         c.m_commonParam.m_redirectIEinfo.m_redirectIE = ies;
900                 }
901                 PPER_Stream stream;
902                 c.Encode(stream);
903                 stream.CompleteEncoding();
904                 (*np).m_data = stream;
905         }
906         return res;
907 }
908
909 static const char OID_QSIG[] = "1.3.12.9";
910
911 static BOOL FetchQSIGTunneledInfo(Q931 &q931, const H323SignalPDU &pdu)
912 {
913         BOOL res = FALSE;
914         const H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
915         if (uuPDU.HasOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage)) {
916                 const H225_H323_UU_PDU_tunnelledSignallingMessage &sig = uuPDU.m_tunnelledSignallingMessage;
917                 const H225_TunnelledProtocol_id &proto = sig.m_tunnelledProtocolID.m_id;
918                 if ((proto.GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
919                                 (((const PASN_ObjectId &)proto).AsString() == OID_QSIG)) {
920                         const H225_ArrayOf_PASN_OctetString &sigs = sig.m_messageContent;
921                         for(int i = 0; i < sigs.GetSize(); ++i) {
922                                 const PASN_OctetString &msg = sigs[i];
923                                 if (h323debug)
924                                         cout << setprecision(0) << "Q.931 message data is " << msg << endl;
925                                 if(!q931.Decode((const PBYTEArray &)msg)) {
926                                         cout << "Error while decoding Q.931 message" << endl;
927                                         return FALSE;
928                                 }
929                                 res = TRUE;
930                                 if (h323debug)
931                                         cout << setprecision(0) << "Received QSIG message " << q931 << endl;
932                         }
933                 }
934         }
935         return res;
936 }
937
938 static H225_EndpointType *GetEndpointType(H323SignalPDU &pdu)
939 {
940         if (!pdu.GetQ931().HasIE(Q931::UserUserIE))
941                 return NULL;
942
943         H225_H323_UU_PDU_h323_message_body &body = pdu.m_h323_uu_pdu.m_h323_message_body;
944         switch (body.GetTag()) {
945         case H225_H323_UU_PDU_h323_message_body::e_setup:
946                 return &((H225_Setup_UUIE &)body).m_sourceInfo;
947         case H225_H323_UU_PDU_h323_message_body::e_callProceeding:
948                 return &((H225_CallProceeding_UUIE &)body).m_destinationInfo;
949         case H225_H323_UU_PDU_h323_message_body::e_connect:
950                 return &((H225_Connect_UUIE &)body).m_destinationInfo;
951         case H225_H323_UU_PDU_h323_message_body::e_alerting:
952                 return &((H225_Alerting_UUIE &)body).m_destinationInfo;
953         case H225_H323_UU_PDU_h323_message_body::e_facility:
954                 return &((H225_Facility_UUIE &)body).m_destinationInfo;
955         case H225_H323_UU_PDU_h323_message_body::e_progress:
956                 return &((H225_Progress_UUIE &)body).m_destinationInfo;
957         }
958         return NULL;
959 }
960
961 static BOOL QSIGTunnelRequested(H323SignalPDU &pdu)
962 {
963         H225_EndpointType *epType = GetEndpointType(pdu);
964         if (epType) {
965                 if (!(*epType).HasOptionalField(H225_EndpointType::e_supportedTunnelledProtocols)) {
966                         return FALSE;
967                 }
968                 H225_ArrayOf_TunnelledProtocol &protos = (*epType).m_supportedTunnelledProtocols;
969                 for (int i = 0; i < protos.GetSize(); ++i)
970                 {
971                         if ((protos[i].GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
972                                         (((const PASN_ObjectId &)protos[i]).AsString() == OID_QSIG)) {
973                                 return TRUE;
974                         }
975                 }
976         }
977         return FALSE;
978 }
979
980 static BOOL EmbedQSIGTunneledInfo(H323SignalPDU &pdu)
981 {
982         const static Q931::InformationElementCodes codes[] =
983         { Q931::RedirectingNumberIE, Q931::FacilityIE };
984
985         Q931 &q931 = pdu.GetQ931();
986         PBYTEArray message;
987
988         q931.Encode(message);
989
990         /* Remove non-standard IEs */
991         for(unsigned i = 0; i < (sizeof(codes) / sizeof(codes[0])); ++i) {
992                 if (q931.HasIE(codes[i])) {
993                         q931.RemoveIE(codes[i]);
994                 }
995         }
996
997         H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
998         H225_EndpointType *epType = GetEndpointType(pdu);
999         if (epType) {
1000                 if (!(*epType).HasOptionalField(H225_EndpointType::e_supportedTunnelledProtocols)) {
1001                         (*epType).IncludeOptionalField(H225_EndpointType::e_supportedTunnelledProtocols);
1002                         (*epType).m_supportedTunnelledProtocols.SetSize(0);
1003                 }
1004                 H225_ArrayOf_TunnelledProtocol &protos = (*epType).m_supportedTunnelledProtocols;
1005                 BOOL addQSIG = TRUE;
1006                 for (int i = 0; i < protos.GetSize(); ++i)
1007                 {
1008                         if ((protos[i].GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
1009                                         (((const PASN_ObjectId &)protos[i]).AsString() == OID_QSIG)) {
1010                                 addQSIG = FALSE;
1011                                 break;
1012                         }
1013                 }
1014                 if (addQSIG) {
1015                         H225_TunnelledProtocol *proto = new H225_TunnelledProtocol;
1016                         (*proto).m_id.SetTag(H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID);
1017                         (PASN_ObjectId &)(proto->m_id) = OID_QSIG;
1018                         protos.Append(proto);
1019                 }
1020         }
1021         if (!uuPDU.HasOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage))
1022                 uuPDU.IncludeOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage);
1023         H225_H323_UU_PDU_tunnelledSignallingMessage &sig = uuPDU.m_tunnelledSignallingMessage;
1024         H225_TunnelledProtocol_id &proto = sig.m_tunnelledProtocolID.m_id;
1025         if ((proto.GetTag() != H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) ||
1026                         (((const PASN_ObjectId &)proto).AsString() != OID_QSIG)) {
1027                 proto.SetTag(H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID);
1028                 (PASN_ObjectId &)proto = OID_QSIG;
1029                 sig.m_messageContent.SetSize(0);
1030         }
1031         PASN_OctetString *msg = new PASN_OctetString;
1032         sig.m_messageContent.Append(msg);
1033         *msg = message;
1034         return TRUE;
1035 }
1036
1037 BOOL MyH323Connection::EmbedTunneledInfo(H323SignalPDU &pdu)
1038 {
1039         if ((tunnelOptions & H323_TUNNEL_QSIG) || (remoteTunnelOptions & H323_TUNNEL_QSIG))
1040                 EmbedQSIGTunneledInfo(pdu);
1041         if ((tunnelOptions & H323_TUNNEL_CISCO) || (remoteTunnelOptions & H323_TUNNEL_CISCO))
1042                 EmbedCiscoTunneledInfo(pdu);
1043
1044         return TRUE;
1045 }
1046
1047 /* Handle tunneled messages */
1048 BOOL MyH323Connection::HandleSignalPDU(H323SignalPDU &pdu)
1049 {
1050         if (pdu.GetQ931().HasIE(Q931::UserUserIE)) {
1051                 Q931 tunneledInfo;
1052                 const Q931 *q931Info;
1053
1054                 q931Info = NULL;
1055                 if (FetchCiscoTunneledInfo(tunneledInfo, pdu)) {
1056                         q931Info = &tunneledInfo;
1057                         remoteTunnelOptions |= H323_TUNNEL_CISCO;
1058                 }
1059                 if (FetchQSIGTunneledInfo(tunneledInfo, pdu)) {
1060                         q931Info = &tunneledInfo;
1061                         remoteTunnelOptions |= H323_TUNNEL_QSIG;
1062                 }
1063                 if (!(remoteTunnelOptions & H323_TUNNEL_QSIG) && QSIGTunnelRequested(pdu)) {
1064                         remoteTunnelOptions |= H323_TUNNEL_QSIG;
1065                 }
1066                 if (q931Info) {
1067                         if (q931Info->HasIE(Q931::RedirectingNumberIE)) {
1068                                 pdu.GetQ931().SetIE(Q931::RedirectingNumberIE, q931Info->GetIE(Q931::RedirectingNumberIE));
1069                                 if (h323debug) {
1070                                         PString number;
1071                                         unsigned reason;
1072                                         if(q931Info->GetRedirectingNumber(number, NULL, NULL, NULL, NULL, &reason, 0, 0, 0))
1073                                                 cout << "Got redirection from " << number << ", reason " << reason << endl;
1074                                 }
1075                         }
1076                 }
1077         }
1078
1079         return H323Connection::HandleSignalPDU(pdu);
1080 }
1081 #endif
1082
1083 BOOL MyH323Connection::OnReceivedSignalSetup(const H323SignalPDU & setupPDU)
1084 {
1085         call_details_t cd;
1086
1087         if (h323debug) {
1088                 cout << "\t--Received SETUP message" << endl;
1089         }
1090
1091         if (connectionState == ShuttingDownConnection)
1092                 return FALSE;
1093
1094         SetCallDetails(&cd, setupPDU, TRUE);
1095
1096         /* Notify Asterisk of the request */
1097         call_options_t *res = on_incoming_call(&cd);
1098
1099         if (!res) {
1100                 if (h323debug) {
1101                         cout << "\t-- Call Failed" << endl;
1102                 }
1103                 return FALSE;
1104         }
1105
1106         SetCallOptions(res, TRUE);
1107
1108         return H323Connection::OnReceivedSignalSetup(setupPDU);
1109 }
1110
1111 BOOL MyH323Connection::OnSendSignalSetup(H323SignalPDU & setupPDU)
1112 {
1113         call_details_t cd;
1114
1115         if (h323debug) {
1116                 cout << "\t-- Sending SETUP message" << endl;
1117         }
1118
1119         if (connectionState == ShuttingDownConnection)
1120                 return FALSE;
1121
1122         if (progressSetup)
1123                 setupPDU.GetQ931().SetProgressIndicator(progressSetup);
1124
1125         if (redirect_reason >= 0) {
1126                 setupPDU.GetQ931().SetRedirectingNumber(rdnis, 0, 0, 0, 0, redirect_reason);
1127                 /* OpenH323 incorrectly fills number IE when redirecting reason is specified - fix it */
1128                 PBYTEArray IE(setupPDU.GetQ931().GetIE(Q931::RedirectingNumberIE));
1129                 IE[0] = IE[0] & 0x7f;
1130                 IE[1] = IE[1] & 0x7f;
1131                 setupPDU.GetQ931().SetIE(Q931::RedirectingNumberIE, IE);
1132         }
1133
1134         SetCallDetails(&cd, setupPDU, FALSE);
1135
1136         int res = on_outgoing_call(&cd);
1137         if (!res) {
1138                 if (h323debug) {
1139                         cout << "\t-- Call Failed" << endl;
1140                 }
1141                 return FALSE;
1142         }
1143
1144 #ifdef TUNNELLING
1145         EmbedTunneledInfo(setupPDU);
1146 #endif
1147
1148         return H323Connection::OnSendSignalSetup(setupPDU);
1149 }
1150
1151 BOOL MyH323Connection::OnSendReleaseComplete(H323SignalPDU & releaseCompletePDU)
1152 {
1153         if (h323debug) {
1154                 cout << "\t-- Sending RELEASE COMPLETE" << endl;
1155         }
1156         if (cause > 0)
1157                 releaseCompletePDU.GetQ931().SetCause((Q931::CauseValues)cause);
1158
1159 #ifdef TUNNELLING
1160         EmbedTunneledInfo(releaseCompletePDU);
1161 #endif
1162
1163         return H323Connection::OnSendReleaseComplete(releaseCompletePDU);
1164 }
1165
1166 BOOL MyH323Connection::OnReceivedFacility(const H323SignalPDU & pdu)
1167 {
1168         if (h323debug) {
1169                 cout << "\t-- Received Facility message... " << endl;
1170         }
1171         return H323Connection::OnReceivedFacility(pdu);
1172 }
1173
1174 void MyH323Connection::OnReceivedReleaseComplete(const H323SignalPDU & pdu)
1175 {
1176         if (h323debug) {
1177                 cout << "\t-- Received RELEASE COMPLETE message..." << endl;
1178         }
1179         if (on_hangup)
1180                 on_hangup(GetCallReference(), (const char *)GetCallToken(), pdu.GetQ931().GetCause());
1181         return H323Connection::OnReceivedReleaseComplete(pdu);
1182 }
1183
1184 BOOL MyH323Connection::OnClosingLogicalChannel(H323Channel & channel)
1185 {
1186         if (h323debug) {
1187                 cout << "\t-- Closing logical channel..." << endl;
1188         }
1189         return H323Connection::OnClosingLogicalChannel(channel);
1190 }
1191
1192 void MyH323Connection::SendUserInputTone(char tone, unsigned duration, unsigned logicalChannel, unsigned rtpTimestamp)
1193 {
1194         SendUserInputModes mode = GetRealSendUserInputMode();
1195 //      That is recursive call... Why?
1196 //      on_receive_digit(GetCallReference(), tone, (const char *)GetCallToken());
1197         if ((tone != ' ') || (mode == SendUserInputAsTone) || (mode == SendUserInputAsInlineRFC2833)) {
1198                 if (h323debug) {
1199                         cout << "\t-- Sending user input tone (" << tone << ") to remote" << endl;
1200                 }
1201                 H323Connection::SendUserInputTone(tone, duration);
1202         }
1203 }
1204
1205 void MyH323Connection::OnUserInputTone(char tone, unsigned duration, unsigned logicalChannel, unsigned rtpTimestamp)
1206 {
1207         if (dtmfMode == H323_DTMF_RFC2833) {
1208                 if (h323debug) {
1209                         cout << "\t-- Received user input tone (" << tone << ") from remote" << endl;
1210                 }
1211                 on_receive_digit(GetCallReference(), tone, (const char *)GetCallToken(), duration);
1212         }
1213 }
1214
1215 void MyH323Connection::OnUserInputString(const PString &value)
1216 {
1217         if (h323debug) {
1218                 cout << "\t-- Received user input string (" << value << ") from remote." << endl;
1219         }
1220         on_receive_digit(GetCallReference(), value[0], (const char *)GetCallToken(), 0);
1221 }
1222
1223 void MyH323Connection::OnSendCapabilitySet(H245_TerminalCapabilitySet & pdu)
1224 {
1225         PINDEX i;
1226
1227         H323Connection::OnSendCapabilitySet(pdu);
1228
1229         H245_ArrayOf_CapabilityTableEntry & tables = pdu.m_capabilityTable;
1230         for(i = 0; i < tables.GetSize(); i++)
1231         {
1232                 H245_CapabilityTableEntry & entry = tables[i];
1233                 if (entry.HasOptionalField(H245_CapabilityTableEntry::e_capability)) {
1234                         H245_Capability & cap = entry.m_capability;
1235                         if (cap.GetTag() == H245_Capability::e_receiveRTPAudioTelephonyEventCapability) {
1236                                 H245_AudioTelephonyEventCapability & atec = cap;
1237                                 atec.m_dynamicRTPPayloadType = dtmfCodec;
1238 //                              on_set_rfc2833_payload(GetCallReference(), (const char *)GetCallToken(), (int)dtmfCodec);
1239                                 if (h323debug) {
1240                                         cout << "\t-- Transmitting RFC2833 on payload " <<
1241                                                 atec.m_dynamicRTPPayloadType << endl;
1242                                 }
1243                         }
1244                 }
1245         }
1246 }
1247
1248 void MyH323Connection::OnSetLocalCapabilities()
1249 {
1250         if (on_setcapabilities)
1251                 on_setcapabilities(GetCallReference(), (const char *)callToken);
1252 }
1253
1254 BOOL MyH323Connection::OnReceivedCapabilitySet(const H323Capabilities & remoteCaps,
1255                                                         const H245_MultiplexCapability * muxCap,
1256                                                         H245_TerminalCapabilitySetReject & reject)
1257 {
1258         struct __codec__ {
1259                 unsigned int asterisk_codec;
1260                 unsigned int h245_cap;
1261                 const char *oid;
1262         };
1263         static const struct __codec__ codecs[] = {
1264                 { AST_FORMAT_G723_1, H245_AudioCapability::e_g7231 },
1265                 { AST_FORMAT_GSM, H245_AudioCapability::e_gsmFullRate },
1266                 { AST_FORMAT_ULAW, H245_AudioCapability::e_g711Ulaw64k },
1267                 { AST_FORMAT_ALAW, H245_AudioCapability::e_g711Alaw64k },
1268                 { AST_FORMAT_G729A, H245_AudioCapability::e_g729AnnexA },
1269                 { AST_FORMAT_G729A, H245_AudioCapability::e_g729 },
1270 #ifdef AST_FORMAT_MODEM
1271                 { AST_FORMAT_MODEM, H245_DataApplicationCapability_application::e_t38fax },
1272 #endif
1273                 { 0 }
1274         };
1275
1276 #if 0
1277         static const struct __codec__ vcodecs[] = {
1278 #ifdef HAVE_H261
1279                 { AST_FORMAT_H261, H245_VideoCapability::e_h261VideoCapability },
1280 #endif
1281 #ifdef HAVE_H263
1282                 { AST_FORMAT_H263, H245_VideoCapability::e_h263VideoCapability },
1283 #endif
1284 #ifdef HAVE_H264
1285                 { AST_FORMAT_H264, H245_VideoCapability::e_genericVideoCapability, "0.0.8.241.0.0.1" },
1286 #endif
1287                 { 0 }
1288         };
1289 #endif
1290         struct ast_codec_pref prefs;
1291
1292         if (!H323Connection::OnReceivedCapabilitySet(remoteCaps, muxCap, reject)) {
1293                 return FALSE;
1294         }
1295
1296         const H323Capability * cap = remoteCaps.FindCapability(H323_UserInputCapability::SubTypeNames[H323_UserInputCapability::SignalToneRFC2833]);
1297         if (cap != NULL) {
1298                 RTP_DataFrame::PayloadTypes pt = ((H323_UserInputCapability*)cap)->GetPayloadType();
1299                 on_set_rfc2833_payload(GetCallReference(), (const char *)GetCallToken(), (int)pt);
1300                 if ((dtmfMode == H323_DTMF_RFC2833) && (sendUserInputMode == SendUserInputAsTone))
1301                         sendUserInputMode = SendUserInputAsInlineRFC2833;
1302                 if (h323debug) {
1303                         cout << "\t-- Inbound RFC2833 on payload " << pt << endl;
1304                 }
1305         }
1306         memset(&prefs, 0, sizeof(prefs));
1307         int peer_capabilities = 0;
1308         for (int i = 0; i < remoteCapabilities.GetSize(); ++i) {
1309                 unsigned int subType = remoteCapabilities[i].GetSubType();
1310                 if (h323debug) {
1311                         cout << "Peer capability is " << remoteCapabilities[i] << endl;
1312                 }
1313                 switch(remoteCapabilities[i].GetMainType()) {
1314                 case H323Capability::e_Audio:
1315                         for (int x = 0; codecs[x].asterisk_codec > 0; ++x) {
1316                                 if (subType == codecs[x].h245_cap) {
1317                                         int ast_codec = codecs[x].asterisk_codec;
1318                                         int ms = 0;
1319                                         if (!(peer_capabilities & ast_codec)) {
1320                                                 struct ast_format_list format;
1321                                                 ast_codec_pref_append(&prefs, ast_codec);
1322                                                 format = ast_codec_pref_getsize(&prefs, ast_codec);
1323                                                 if ((ast_codec == AST_FORMAT_ALAW) || (ast_codec == AST_FORMAT_ULAW)) {
1324                                                         ms = remoteCapabilities[i].GetTxFramesInPacket();
1325                                                         if (ms > 60)
1326                                                                 ms = format.cur_ms;
1327                                                 } else
1328                                                         ms = remoteCapabilities[i].GetTxFramesInPacket() * format.inc_ms;
1329                                                 ast_codec_pref_setsize(&prefs, ast_codec, ms);
1330                                         }
1331                                         if (h323debug) {
1332                                                 cout << "Found peer capability " << remoteCapabilities[i] << ", Asterisk code is " << ast_codec << ", frame size (in ms) is " << ms << endl;
1333                                         }
1334                                         peer_capabilities |= ast_codec;
1335                                 }
1336                         }
1337                         break;
1338 #if 0
1339                 case H323Capability::e_Video:
1340                         for (int x = 0; vcodecs[x].asterisk_codec > 0; ++x) {
1341                                 if (subType == vcodecs[x].h245_cap) {
1342                                         H245_CapabilityIdentifier *cap = NULL;
1343                                         H245_GenericCapability y;
1344                                         if (vcodecs[x].oid) {
1345                                                 cap = new H245_CapabilityIdentifier(H245_CapabilityIdentifier::e_standard);
1346                                                 PASN_ObjectId &object_id = *cap;
1347                                                 object_id = vcodecs[x].oid;
1348                                                 y.m_capabilityIdentifier = *cap;
1349                                         }
1350                                         if ((subType != H245_VideoCapability::e_genericVideoCapability) ||
1351                                                         (vcodecs[x].oid && ((const H323GenericVideoCapability &)remoteCapabilities[i]).IsGenericMatch((const H245_GenericCapability)y))) {
1352                                                 if (h323debug) {
1353                                                         cout << "Found peer video capability " << remoteCapabilities[i] << ", Asterisk code is " << vcodecs[x].asterisk_codec << endl;
1354                                                 }
1355                                                 peer_capabilities |= vcodecs[x].asterisk_codec;
1356                                         }
1357                                         if (cap)
1358                                                 delete(cap);
1359                                 }
1360                         }
1361                         break;
1362 #endif
1363                 default:
1364                         break;
1365                 }
1366         }
1367         if (h323debug) {
1368                 char caps_str[1024], caps2_str[1024];
1369                 ast_codec_pref_string(&prefs, caps2_str, sizeof(caps2_str));
1370                 cout << "Peer capabilities = " << ast_getformatname_multiple(caps_str, sizeof(caps_str), peer_capabilities)
1371                                 << ", ordered list is " << caps2_str << endl;
1372         }
1373 #if 0
1374         redir_capabilities &= peer_capabilities;
1375 #endif
1376         if (on_setpeercapabilities)
1377                 on_setpeercapabilities(GetCallReference(), (const char *)callToken, peer_capabilities, &prefs);
1378
1379         return TRUE;
1380 }
1381
1382 H323Channel * MyH323Connection::CreateRealTimeLogicalChannel(const H323Capability & capability,
1383                                                                         H323Channel::Directions dir,
1384                                                                         unsigned sessionID,
1385                                                                         const H245_H2250LogicalChannelParameters * /*param*/,
1386                                                                         RTP_QOS * /*param*/ )
1387 {
1388         return new MyH323_ExternalRTPChannel(*this, capability, dir, sessionID);
1389 }
1390
1391 /** This callback function is invoked once upon creation of each
1392   * channel for an H323 session
1393   */
1394 BOOL MyH323Connection::OnStartLogicalChannel(H323Channel & channel)
1395 {
1396         /* Increase the count of channels we have open */
1397         channelsOpen++;
1398
1399         if (h323debug) {
1400                 cout << "\t-- Started logical channel: "
1401                                 << ((channel.GetDirection() == H323Channel::IsTransmitter) ? "sending " : ((channel.GetDirection() == H323Channel::IsReceiver) ? "receiving " : " "))
1402                                 << (const char *)(channel.GetCapability()).GetFormatName() << endl;
1403                 cout << "\t\t-- channelsOpen = " << channelsOpen << endl;
1404         }
1405         return connectionState != ShuttingDownConnection;
1406 }
1407
1408 void MyH323Connection::SetCapabilities(int cap, int dtmf_mode, void *_prefs, int pref_codec)
1409 {
1410         PINDEX lastcap = -1; /* last common capability index */
1411         int alreadysent = 0;
1412         int codec;
1413         int x, y;
1414         char caps_str[1024];
1415         struct ast_codec_pref *prefs = (struct ast_codec_pref *)_prefs;
1416         struct ast_format_list format;
1417         int frames_per_packet;
1418         int max_frames_per_packet;
1419
1420         localCapabilities.RemoveAll();
1421
1422         if (h323debug) {
1423                 cout << "Setting capabilities to " << ast_getformatname_multiple(caps_str, sizeof(caps_str), cap) << endl;
1424                 ast_codec_pref_string(prefs, caps_str, sizeof(caps_str));
1425                 cout << "Capabilities in preference order is " << caps_str << endl;
1426         }
1427         /* Add audio codecs in preference order first, then
1428            audio codecs without preference as allowed by mask */
1429         for (y = 0, x = -1; x < 32 + 32; ++x) {
1430                 if (x < 0)
1431                         codec = pref_codec;
1432                 else if (y || (!(codec = ast_codec_pref_index(prefs, x)))) {
1433                         if (!y)
1434                                 y = 1;
1435                         else if (y == AST_FORMAT_MAX_AUDIO)
1436                                 break;
1437                         else
1438                                 y <<= 1;
1439                         codec = y;
1440                 }
1441                 if (!(cap & codec) || (alreadysent & codec) || !(codec & AST_FORMAT_AUDIO_MASK))
1442                         continue;
1443                 alreadysent |= codec;
1444                 format = ast_codec_pref_getsize(prefs, codec);
1445                 frames_per_packet = (format.inc_ms ? format.cur_ms / format.inc_ms : format.cur_ms);
1446                 max_frames_per_packet = (format.inc_ms ? format.max_ms / format.inc_ms : 0);
1447                 switch(codec) {
1448 #if 0
1449                 case AST_FORMAT_SPEEX:
1450                         /* Not real sure if Asterisk acutally supports all
1451                            of the various different bit rates so add them
1452                            all and figure it out later*/
1453
1454                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow2AudioCapability());
1455                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow3AudioCapability());
1456                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow4AudioCapability());
1457                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow5AudioCapability());
1458                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow6AudioCapability());
1459                         break;
1460 #endif
1461                 case AST_FORMAT_G729A:
1462                         AST_G729ACapability *g729aCap;
1463                         AST_G729Capability *g729Cap;
1464                         lastcap = localCapabilities.SetCapability(0, 0, g729aCap = new AST_G729ACapability(frames_per_packet));
1465                         lastcap = localCapabilities.SetCapability(0, 0, g729Cap = new AST_G729Capability(frames_per_packet));
1466                         if (max_frames_per_packet) {
1467                                 g729aCap->SetTxFramesInPacket(max_frames_per_packet);
1468                                 g729Cap->SetTxFramesInPacket(max_frames_per_packet);
1469                         }
1470                         break;
1471                 case AST_FORMAT_G723_1:
1472                         AST_G7231Capability *g7231Cap;
1473                         lastcap = localCapabilities.SetCapability(0, 0, g7231Cap = new AST_G7231Capability(frames_per_packet, TRUE));
1474                         if (max_frames_per_packet)
1475                                 g7231Cap->SetTxFramesInPacket(max_frames_per_packet);
1476                         lastcap = localCapabilities.SetCapability(0, 0, g7231Cap = new AST_G7231Capability(frames_per_packet, FALSE));
1477                         if (max_frames_per_packet)
1478                                 g7231Cap->SetTxFramesInPacket(max_frames_per_packet);
1479                         break;
1480                 case AST_FORMAT_GSM:
1481                         AST_GSM0610Capability *gsmCap;
1482                         lastcap = localCapabilities.SetCapability(0, 0, gsmCap = new AST_GSM0610Capability(frames_per_packet));
1483                         if (max_frames_per_packet)
1484                                 gsmCap->SetTxFramesInPacket(max_frames_per_packet);
1485                         break;
1486                 case AST_FORMAT_ULAW:
1487                         AST_G711Capability *g711uCap;
1488                         lastcap = localCapabilities.SetCapability(0, 0, g711uCap = new AST_G711Capability(format.cur_ms, H323_G711Capability::muLaw));
1489                         if (format.max_ms)
1490                                 g711uCap->SetTxFramesInPacket(format.max_ms);
1491                         break;
1492                 case AST_FORMAT_ALAW:
1493                         AST_G711Capability *g711aCap;
1494                         lastcap = localCapabilities.SetCapability(0, 0, g711aCap = new AST_G711Capability(format.cur_ms, H323_G711Capability::ALaw));
1495                         if (format.max_ms)
1496                                 g711aCap->SetTxFramesInPacket(format.max_ms);
1497                         break;
1498                 default:
1499                         alreadysent &= ~codec;
1500                         break;
1501                 }
1502         }
1503
1504         lastcap++;
1505         lastcap = localCapabilities.SetCapability(0, lastcap, new H323_UserInputCapability(H323_UserInputCapability::HookFlashH245));
1506
1507         lastcap++;
1508         dtmfMode = dtmf_mode;
1509         if (dtmf_mode == H323_DTMF_INBAND) {
1510                 localCapabilities.SetCapability(0, lastcap, new H323_UserInputCapability(H323_UserInputCapability::BasicString));
1511                 sendUserInputMode = SendUserInputAsString;
1512         } else {
1513                 lastcap = localCapabilities.SetCapability(0, lastcap, new H323_UserInputCapability(H323_UserInputCapability::SignalToneRFC2833));
1514                 /* Cisco sends DTMF only through h245-alphanumeric or h245-signal, no support for RFC2833 */
1515                 lastcap = localCapabilities.SetCapability(0, lastcap, new H323_UserInputCapability(H323_UserInputCapability::SignalToneH245));
1516                 sendUserInputMode = SendUserInputAsTone;        /* RFC2833 transmission handled at Asterisk level */
1517         }
1518
1519         if (h323debug) {
1520                 cout << "Allowed Codecs:\n\t" << setprecision(2) << localCapabilities << endl;
1521         }
1522 }
1523
1524 BOOL MyH323Connection::StartControlChannel(const H225_TransportAddress & h245Address)
1525 {
1526         // Check that it is an IP address, all we support at the moment
1527         if (h245Address.GetTag() != H225_TransportAddress::e_ipAddress
1528 #if P_HAS_IPV6
1529                 && h245Address.GetTag() != H225_TransportAddress::e_ip6Address
1530 #endif
1531         ) {
1532                 PTRACE(1, "H225\tConnect of H245 failed: Unsupported transport");
1533                 return FALSE;
1534         }
1535
1536         // Already have the H245 channel up.
1537         if (controlChannel != NULL)
1538                 return TRUE;
1539
1540         PIPSocket::Address addr;
1541         WORD port;
1542         GetSignallingChannel()->GetLocalAddress().GetIpAndPort(addr, port);
1543         if (addr) {
1544                 if (h323debug)
1545                         cout << "Using " << addr << " for outbound H.245 transport" << endl;
1546                 controlChannel = new MyH323TransportTCP(endpoint, addr);
1547         } else
1548                 controlChannel = new H323TransportTCP(endpoint);
1549         if (!controlChannel->SetRemoteAddress(h245Address)) {
1550                 PTRACE(1, "H225\tCould not extract H245 address");
1551                 delete controlChannel;
1552                 controlChannel = NULL;
1553                 return FALSE;
1554         }
1555         if (!controlChannel->Connect()) {
1556                 PTRACE(1, "H225\tConnect of H245 failed: " << controlChannel->GetErrorText());
1557                 delete controlChannel;
1558                 controlChannel = NULL;
1559                 return FALSE;
1560         }
1561
1562         controlChannel->StartControlChannel(*this);
1563         return TRUE;
1564 }
1565
1566 /* MyH323_ExternalRTPChannel */
1567 MyH323_ExternalRTPChannel::MyH323_ExternalRTPChannel(MyH323Connection & connection,
1568                                                         const H323Capability & capability,
1569                                                         Directions direction,
1570                                                         unsigned id)
1571         : H323_ExternalRTPChannel::H323_ExternalRTPChannel(connection, capability, direction, id)
1572 {
1573         struct rtp_info *info;
1574
1575         /* Determine the Local (A side) IP Address and port */
1576         info = on_external_rtp_create(connection.GetCallReference(), (const char *)connection.GetCallToken());
1577         if (!info) {
1578                 cout << "\tERROR: on_external_rtp_create failure" << endl;
1579                 return;
1580         } else {
1581                 localIpAddr = info->addr;
1582                 localPort = info->port;
1583                 /* tell the H.323 stack */
1584                 SetExternalAddress(H323TransportAddress(localIpAddr, localPort), H323TransportAddress(localIpAddr, localPort + 1));
1585                 /* clean up allocated memory */
1586                 free(info);
1587         }
1588
1589         /* Get the payload code */
1590         OpalMediaFormat format(capability.GetFormatName(), FALSE);
1591         payloadCode = format.GetPayloadType();
1592 }
1593
1594 MyH323_ExternalRTPChannel::~MyH323_ExternalRTPChannel()
1595 {
1596         if (h323debug) {
1597                 cout << "\tExternalRTPChannel Destroyed" << endl;
1598         }
1599 }
1600
1601 BOOL MyH323_ExternalRTPChannel::Start(void)
1602 {
1603         /* Call ancestor first */
1604         if (!H323_ExternalRTPChannel::Start()) {
1605                 return FALSE;
1606         }
1607
1608         if (h323debug) {
1609                 cout << "\t\tExternal RTP Session Starting" << endl;
1610                 cout << "\t\tRTP channel id " << sessionID << " parameters:" << endl;
1611         }
1612
1613         /* Collect the remote information */
1614         H323_ExternalRTPChannel::GetRemoteAddress(remoteIpAddr, remotePort);
1615
1616         if (h323debug) {
1617                 cout << "\t\t-- remoteIpAddress: " << remoteIpAddr << endl;
1618                 cout << "\t\t-- remotePort: " << remotePort << endl;
1619                 cout << "\t\t-- ExternalIpAddress: " << localIpAddr << endl;
1620                 cout << "\t\t-- ExternalPort: " << localPort << endl;
1621         }
1622         /* Notify Asterisk of remote RTP information */
1623         on_start_rtp_channel(connection.GetCallReference(), (const char *)remoteIpAddr.AsString(), remotePort,
1624                 (const char *)connection.GetCallToken(), (int)payloadCode);
1625         return TRUE;
1626 }
1627
1628 BOOL MyH323_ExternalRTPChannel::OnReceivedAckPDU(const H245_H2250LogicalChannelAckParameters & param)
1629 {
1630         if (h323debug) {
1631                 cout << "       MyH323_ExternalRTPChannel::OnReceivedAckPDU" << endl;
1632         }
1633
1634         if (H323_ExternalRTPChannel::OnReceivedAckPDU(param)) {
1635                 GetRemoteAddress(remoteIpAddr, remotePort);
1636                 if (h323debug) {
1637                         cout << "               -- remoteIpAddress: " << remoteIpAddr << endl;
1638                         cout << "               -- remotePort: " << remotePort << endl;
1639                 }
1640                 on_start_rtp_channel(connection.GetCallReference(), (const char *)remoteIpAddr.AsString(),
1641                                 remotePort, (const char *)connection.GetCallToken(), (int)payloadCode);
1642                 return TRUE;
1643         }
1644         return FALSE;
1645 }
1646
1647
1648 /** IMPLEMENTATION OF C FUNCTIONS */
1649
1650 /**
1651  * The extern "C" directive takes care for
1652  * the ANSI-C representation of linkable symbols
1653  */
1654
1655 extern "C" {
1656
1657 int h323_end_point_exist(void)
1658 {
1659         if (!endPoint) {
1660                 return 0;
1661         }
1662         return 1;
1663 }
1664
1665 void h323_end_point_create(void)
1666 {
1667         channelsOpen = 0;
1668         logstream = new PAsteriskLog();
1669         localProcess = new MyProcess();
1670         localProcess->Main();
1671 }
1672
1673 void h323_gk_urq(void)
1674 {
1675         if (!h323_end_point_exist()) {
1676                 cout << " ERROR: [h323_gk_urq] No Endpoint, this is bad" << endl;
1677                 return;
1678         }
1679         endPoint->RemoveGatekeeper();
1680 }
1681
1682 void h323_debug(int flag, unsigned level)
1683 {
1684         if (flag) {
1685                 PTrace:: SetLevel(level);
1686         } else {
1687                 PTrace:: SetLevel(0);
1688         }
1689 }
1690
1691 /** Installs the callback functions on behalf of the PBX application */
1692 void h323_callback_register(setup_incoming_cb           ifunc,
1693                                                         setup_outbound_cb               sfunc,
1694                                                         on_rtp_cb                               rtpfunc,
1695                                                         start_rtp_cb                    lfunc,
1696                                                         clear_con_cb                    clfunc,
1697                                                         chan_ringing_cb                 rfunc,
1698                                                         con_established_cb              efunc,
1699                                                         receive_digit_cb                dfunc,
1700                                                         answer_call_cb                  acfunc,
1701                                                         progress_cb                             pgfunc,
1702                                                         rfc2833_cb                              dtmffunc,
1703                                                         hangup_cb                               hangupfunc,
1704                                                         setcapabilities_cb              capabilityfunc,
1705                                                         setpeercapabilities_cb  peercapabilityfunc)
1706 {
1707         on_incoming_call = ifunc;
1708         on_outgoing_call = sfunc;
1709         on_external_rtp_create = rtpfunc;
1710         on_start_rtp_channel = lfunc;
1711         on_connection_cleared = clfunc;
1712         on_chan_ringing = rfunc;
1713         on_connection_established = efunc;
1714         on_receive_digit = dfunc;
1715         on_answer_call = acfunc;
1716         on_progress = pgfunc;
1717         on_set_rfc2833_payload = dtmffunc;
1718         on_hangup = hangupfunc;
1719         on_setcapabilities = capabilityfunc;
1720         on_setpeercapabilities = peercapabilityfunc;
1721 }
1722
1723 /**
1724  * Add capability to the capability table of the end point.
1725  */
1726 int h323_set_capabilities(const char *token, int cap, int dtmf_mode, struct ast_codec_pref *prefs, int pref_codec)
1727 {
1728         MyH323Connection *conn;
1729
1730         if (!h323_end_point_exist()) {
1731                 cout << " ERROR: [h323_set_capablities] No Endpoint, this is bad" << endl;
1732                 return 1;
1733         }
1734         if (!token || !*token) {
1735                 cout << " ERROR: [h323_set_capabilities] Invalid call token specified." << endl;
1736                 return 1;
1737         }
1738
1739         PString myToken(token);
1740         conn = (MyH323Connection *)endPoint->FindConnectionWithLock(myToken);
1741         if (!conn) {
1742                 cout << " ERROR: [h323_set_capabilities] Unable to find connection " << token << endl;
1743                 return 1;
1744         }
1745         conn->SetCapabilities((/*conn->bridging ? conn->redir_capabilities :*/ cap), dtmf_mode, prefs, pref_codec);
1746         conn->Unlock();
1747
1748         return 0;
1749 }
1750
1751 /** Start the H.323 listener */
1752 int h323_start_listener(int listenPort, struct sockaddr_in bindaddr)
1753 {
1754
1755         if (!h323_end_point_exist()) {
1756                 cout << "ERROR: [h323_start_listener] No Endpoint, this is bad!" << endl;
1757                 return 1;
1758         }
1759
1760         PIPSocket::Address interfaceAddress(bindaddr.sin_addr);
1761         if (!listenPort) {
1762                 listenPort = 1720;
1763         }
1764         /** H.323 listener */
1765         H323ListenerTCP *tcpListener;
1766         tcpListener = new H323ListenerTCP(*endPoint, interfaceAddress, (WORD)listenPort);
1767         if (!endPoint->StartListener(tcpListener)) {
1768                 cout << "ERROR: Could not open H.323 listener port on " << ((H323ListenerTCP *) tcpListener)->GetListenerPort() << endl;
1769                 delete tcpListener;
1770                 return 1;
1771         }
1772         cout << "  == H.323 listener started" << endl;
1773         return 0;
1774 };
1775
1776 int h323_set_alias(struct oh323_alias *alias)
1777 {
1778         char *p;
1779         char *num;
1780         PString h323id(alias->name);
1781         PString e164(alias->e164);
1782         char *prefix;
1783
1784         if (!h323_end_point_exist()) {
1785                 cout << "ERROR: [h323_set_alias] No Endpoint, this is bad!" << endl;
1786                 return 1;
1787         }
1788
1789         cout << "== Adding alias \"" << h323id << "\" to endpoint" << endl;
1790         endPoint->AddAliasName(h323id);
1791         endPoint->RemoveAliasName(localProcess->GetUserName());
1792
1793         if (!e164.IsEmpty()) {
1794                 cout << "== Adding E.164 \"" << e164 << "\" to endpoint" << endl;
1795                 endPoint->AddAliasName(e164);
1796         }
1797         if (strlen(alias->prefix)) {
1798                 p = prefix = strdup(alias->prefix);
1799                 while((num = strsep(&p, ",")) != (char *)NULL) {
1800                         cout << "== Adding Prefix \"" << num << "\" to endpoint" << endl;
1801                         endPoint->SupportedPrefixes += PString(num);
1802                         endPoint->SetGateway();
1803                 }
1804                 if (prefix)
1805                         free(prefix);
1806         }
1807         return 0;
1808 }
1809
1810 void h323_set_id(char *id)
1811 {
1812         PString h323id(id);
1813
1814         if (h323debug) {
1815                 cout << "  == Using '" << h323id << "' as our H.323ID for this call" << endl;
1816         }
1817         /* EVIL HACK */
1818         endPoint->SetLocalUserName(h323id);
1819 }
1820
1821 void h323_show_tokens(void)
1822 {
1823         cout << "Current call tokens: " << setprecision(2) << endPoint->GetAllConnections() << endl;
1824 }
1825
1826 /** Establish Gatekeeper communiations, if so configured,
1827   *     register aliases for the H.323 endpoint to respond to.
1828   */
1829 int h323_set_gk(int gatekeeper_discover, char *gatekeeper, char *secret)
1830 {
1831         PString gkName = PString(gatekeeper);
1832         PString pass = PString(secret);
1833         H323TransportUDP *rasChannel;
1834
1835         if (!h323_end_point_exist()) {
1836                 cout << "ERROR: [h323_set_gk] No Endpoint, this is bad!" << endl;
1837                 return 1;
1838         }
1839
1840         if (!gatekeeper) {
1841                 cout << "Error: Gatekeeper cannot be NULL" << endl;
1842                 return 1;
1843         }
1844         if (strlen(secret)) {
1845                 endPoint->SetGatekeeperPassword(pass);
1846         }
1847         if (gatekeeper_discover) {
1848                 /* discover the gk using multicast */
1849                 if (endPoint->DiscoverGatekeeper(new MyH323TransportUDP(*endPoint))) {
1850                         cout << "== Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
1851                 } else {
1852                         cout << "Warning: Could not find a gatekeeper." << endl;
1853                         return 1;
1854                 }
1855         } else {
1856                 rasChannel = new MyH323TransportUDP(*endPoint);
1857
1858                 if (!rasChannel) {
1859                         cout << "Error: No RAS Channel, this is bad" << endl;
1860                         return 1;
1861                 }
1862                 if (endPoint->SetGatekeeper(gkName, rasChannel)) {
1863                         cout << "== Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
1864                 } else {
1865                         cout << "Error registering with gatekeeper \"" << gkName << "\". " << endl;
1866                         /* XXX Maybe we should fire a new thread to attempt to re-register later and not kill asterisk here? */
1867                         return 1;
1868                 }
1869         }
1870         return 0;
1871 }
1872
1873 /** Send a DTMF tone over the H323Connection with the
1874   * specified token.
1875   */
1876 void h323_send_tone(const char *call_token, char tone)
1877 {
1878         if (!h323_end_point_exist()) {
1879                 cout << "ERROR: [h323_send_tone] No Endpoint, this is bad!" << endl;
1880                 return;
1881         }
1882         PString token = PString(call_token);
1883         endPoint->SendUserTone(token, tone);
1884 }
1885
1886 /** Make a call to the remote endpoint.
1887   */
1888 int h323_make_call(char *dest, call_details_t *cd, call_options_t *call_options)
1889 {
1890         int res;
1891         PString token;
1892         PString host(dest);
1893
1894         if (!h323_end_point_exist()) {
1895                 return 1;
1896         }
1897
1898         res = endPoint->MyMakeCall(host, token, &cd->call_reference, call_options);
1899         memcpy((char *)(cd->call_token), (const unsigned char *)token, token.GetLength());
1900         return res;
1901 };
1902
1903 int h323_clear_call(const char *call_token, int cause)
1904 {
1905         H225_ReleaseCompleteReason dummy;
1906         H323Connection::CallEndReason r = H323Connection::EndedByLocalUser;
1907         MyH323Connection *connection;
1908         const PString currentToken(call_token);
1909
1910         if (!h323_end_point_exist()) {
1911                 return 1;
1912         }
1913
1914         if (cause) {
1915                 r = H323TranslateToCallEndReason((Q931::CauseValues)(cause), dummy);
1916         }
1917
1918         connection = (MyH323Connection *)endPoint->FindConnectionWithLock(currentToken);
1919         if (connection) {
1920                 connection->SetCause(cause);
1921                 connection->SetCallEndReason(r);
1922                 connection->Unlock();
1923         }
1924         endPoint->ClearCall(currentToken, r);
1925         return 0;
1926 };
1927
1928 /* Send Alerting PDU to H.323 caller */
1929 int h323_send_alerting(const char *token)
1930 {
1931         const PString currentToken(token);
1932         H323Connection * connection;
1933
1934         if (h323debug) {
1935                 cout << "\tSending alerting" << endl;
1936         }
1937         connection = endPoint->FindConnectionWithLock(currentToken);
1938         if (!connection) {
1939                 cout << "No connection found for " << token << endl;
1940                 return -1;
1941         }
1942         connection->AnsweringCall(H323Connection::AnswerCallPending);
1943         connection->Unlock();
1944         return 0;
1945 }
1946
1947 /* Send Progress PDU to H.323 caller */
1948 int h323_send_progress(const char *token)
1949 {
1950         const PString currentToken(token);
1951         H323Connection * connection;
1952
1953         connection = endPoint->FindConnectionWithLock(currentToken);
1954         if (!connection) {
1955                 cout << "No connection found for " << token << endl;
1956                 return -1;
1957         }
1958         connection->AnsweringCall(H323Connection::AnswerCallDeferredWithMedia);
1959         connection->Unlock();
1960         return 0;
1961 }
1962
1963 /** This function tells the h.323 stack to either
1964     answer or deny an incoming call */
1965 int h323_answering_call(const char *token, int busy)
1966 {
1967         const PString currentToken(token);
1968         H323Connection * connection;
1969
1970         connection = endPoint->FindConnectionWithLock(currentToken);
1971
1972         if (!connection) {
1973                 cout << "No connection found for " << token << endl;
1974                 return -1;
1975         }
1976         if (!busy) {
1977                 if (h323debug) {
1978                         cout << "\tAnswering call " << token << endl;
1979                 }
1980                 connection->AnsweringCall(H323Connection::AnswerCallNow);
1981         } else {
1982                 if (h323debug) {
1983                         cout << "\tdenying call " << token << endl;
1984                 }
1985                 connection->AnsweringCall(H323Connection::AnswerCallDenied);
1986         }
1987         connection->Unlock();
1988         return 0;
1989 }
1990
1991 int h323_soft_hangup(const char *data)
1992 {
1993         PString token(data);
1994         BOOL result;
1995         cout << "Soft hangup" << endl;
1996         result = endPoint->ClearCall(token);
1997         return result;
1998 }
1999
2000 /* alas, this doesn't work :( */
2001 void h323_native_bridge(const char *token, const char *them, char *capability)
2002 {
2003         H323Channel *channel;
2004         MyH323Connection *connection = (MyH323Connection *)endPoint->FindConnectionWithLock(token);
2005
2006         if (!connection) {
2007                 cout << "ERROR: No connection found, this is bad" << endl;
2008                 return;
2009         }
2010
2011         cout << "Native Bridge:  them [" << them << "]" << endl;
2012
2013         channel = connection->FindChannel(connection->sessionId, TRUE);
2014         connection->bridging = TRUE;
2015         connection->CloseLogicalChannelNumber(channel->GetNumber());
2016
2017         connection->Unlock();
2018         return;
2019
2020 }
2021
2022 #undef cout
2023 #undef endl
2024 void h323_end_process(void)
2025 {
2026         if (endPoint) {
2027                 endPoint->ClearAllCalls();
2028                 endPoint->RemoveListener(NULL);
2029                 delete endPoint;
2030                 endPoint = NULL;
2031         }
2032         if (localProcess) {
2033                 delete localProcess;
2034                 localProcess = NULL;
2035                 close(_timerChangePipe[0]);
2036                 close(_timerChangePipe[1]);
2037         }
2038         if (logstream) {
2039                 PTrace::SetLevel(0);
2040                 PTrace::SetStream(&cout);
2041                 delete logstream;
2042                 logstream = NULL;
2043         }
2044 }
2045
2046 } /* extern "C" */
2047