Allow H.323 Plus library to be used in addition to the OpenH323 library
[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
32 #include "asterisk.h"
33 #define VERSION(a,b,c) ((a)*10000+(b)*100+(c))
34
35 #include <arpa/inet.h>
36
37 #include <list>
38 #include <string>
39 #include <algorithm>
40
41 #include <ptlib.h>
42 #include <h323.h>
43 #include <h323pdu.h>
44 #include <h323neg.h>
45 #include <mediafmt.h>
46
47 /* H323 Plus */
48 #if VERSION(OPENH323_MAJOR, OPENH323_MINOR, OPENH323_BUILD) > VERSION(1,19,4)
49
50 #ifdef H323_H450
51 #include "h450/h4501.h"
52 #include "h450/h4504.h"
53 #include "h450/h45011.h"
54 #include "h450/h450pdu.h"
55 #endif
56
57 #ifdef H323_H460
58 #include <h460/h4601.h>
59 #endif
60
61 #else /* !H323 Plus */
62
63 #include <lid.h>
64 #ifdef H323_H450
65 #include "h4501.h"
66 #include "h4504.h"
67 #include "h45011.h"
68 #include "h450pdu.h"
69 #endif
70
71 #endif /* H323 Plus */
72
73 #include "compat_h323.h"
74
75 #ifdef __cplusplus
76 extern "C" {
77 #endif
78 #include "asterisk/compat.h"
79 #include "asterisk/logger.h"
80 #include "asterisk/channel.h"
81 #include "asterisk/astobj.h"
82 #ifdef __cplusplus
83 }
84 #endif
85
86 #include "chan_h323.h"
87 #include "ast_h323.h"
88 #include "cisco-h225.h"
89 #include "caps_h323.h"
90
91 #if VERSION(PWLIB_MAJOR, PWLIB_MINOR, PWLIB_BUILD) >= VERSION(1,12,0)
92 #define SKIP_PWLIB_PIPE_BUG_WORKAROUND 1
93 #endif
94
95 ///////////////////////////////////////////////
96 /* We have to have a PProcess running for the life of the instance to give
97  * h323plus a static instance of PProcess to get system information.
98  * This class is defined with PDECLARE_PROCESS().  See pprocess.h from pwlib.
99  */
100
101 /* PWlib Required Components  */
102 #if VERSION(OPENH323_MAJOR, OPENH323_MINOR, OPENH323_BUILD) > VERSION(1,19,4)
103 #define MAJOR_VERSION 1
104 #define MINOR_VERSION 19
105 #define BUILD_TYPE    ReleaseCode
106 #define BUILD_NUMBER  6
107 #else
108 #define MAJOR_VERSION 1
109 #define MINOR_VERSION 0
110 #define BUILD_TYPE    ReleaseCode
111 #define BUILD_NUMBER  0
112 #endif
113  
114 const char *h323manufact = "The NuFone Networks";
115 const char *h323product  = "H.323 Channel Driver for Asterisk";
116  
117 PDECLARE_PROCESS(MyProcess,PProcess,h323manufact,h323product,MAJOR_VERSION,MINOR_VERSION,BUILD_TYPE,BUILD_NUMBER)
118 static MyProcess localProcess;  // active for the life of the DLL
119 /* void MyProcess::Main()
120 {
121 }
122 */
123 ////////////////////////////////////////////////
124
125
126 /** Counter for the number of connections */
127 static int channelsOpen;
128
129 /**
130  * We assume that only one endPoint should exist.
131  * The application cannot run the h323_end_point_create() more than once
132  * FIXME: Singleton this, for safety
133  */
134 static MyH323EndPoint *endPoint = NULL;
135
136 static unsigned traceOptions = PTrace::Timestamp | PTrace::Thread | PTrace::FileAndLine;
137
138 class PAsteriskLog : public PObject, public iostream {
139         PCLASSINFO(PAsteriskLog, PObject);
140
141         public:
142         PAsteriskLog() : iostream(cout.rdbuf()) { init(&buffer); }
143         ~PAsteriskLog() { flush(); }
144
145         private:
146         PAsteriskLog(const PAsteriskLog &) : iostream(cout.rdbuf()) { }
147         PAsteriskLog & operator=(const PAsteriskLog &) { return *this; }
148
149         class Buffer : public streambuf {
150                 public:
151                 virtual int overflow(int=EOF);
152                 virtual int underflow();
153                 virtual int sync();
154                 PString string;
155         } buffer;
156         friend class Buffer;
157 };
158
159 static PAsteriskLog *logstream = NULL;
160
161 int PAsteriskLog::Buffer::overflow(int c)
162 {
163         if (pptr() >= epptr()) {
164                 int ppos = pptr() - pbase();
165                 char *newptr = string.GetPointer(string.GetSize() + 2000);
166                 setp(newptr, newptr + string.GetSize() - 1);
167                 pbump(ppos);
168         }
169         if (c != EOF) {
170                 *pptr() = (char)c;
171                 pbump(1);
172         }
173         return 0;
174 }
175
176 int PAsteriskLog::Buffer::underflow()
177 {
178         return EOF;
179 }
180
181 int PAsteriskLog::Buffer::sync()
182 {
183         char *str = ast_strdup(string);
184         char *s, *s1;
185         char c;
186
187         /* Pass each line with different ast_verbose() call */
188         for (s = str; s && *s; s = s1) {
189                 s1 = strchr(s, '\n');
190                 if (!s1)
191                         s1 = s + strlen(s);
192                 else
193                         s1++;
194                 c = *s1;
195                 *s1 = '\0';
196                 ast_verbose("%s", s);
197                 *s1 = c;
198         }
199         ast_free(str);
200
201         string = PString();
202         char *base = string.GetPointer(2000);
203         setp(base, base + string.GetSize() - 1);
204         return 0;
205 }
206
207 static ostream &my_endl(ostream &os)
208 {
209         if (logstream) {
210                 PTrace::SetOptions(traceOptions);
211                 return PTrace::End(os);
212         }
213         return endl(os);
214 }
215
216 #define cout \
217         (logstream ? (PTrace::ClearOptions((unsigned)-1), PTrace::Begin(0, __FILE__, __LINE__)) : std::cout)
218 #define endl my_endl
219
220 void MyProcess::Main()
221 {
222         PTrace::Initialise(PTrace::GetLevel(), NULL, traceOptions);
223         PTrace::SetStream(logstream);
224
225         cout << "  == Creating H.323 Endpoint" << endl;
226         if (endPoint) {
227                 cout << "  == ENDPOINT ALREADY CREATED" << endl;
228                 return;
229         }
230         endPoint = new MyH323EndPoint();
231         /* Due to a bug in the H.323 recomendation/stack we should request a sane
232            amount of bandwidth from the GK - this function is ignored if not using a GK
233            We are requesting 128 (64k in each direction), which is the worst case codec. */
234         endPoint->SetInitialBandwidth(1280);
235 }
236
237 void PAssertFunc(const char *msg)
238 {
239         ast_log(LOG_ERROR, "%s\n", msg);
240         /* XXX: Probably we need to crash here */
241 }
242
243
244 /** MyH323EndPoint
245   */
246 MyH323EndPoint::MyH323EndPoint()
247                 : H323EndPoint()
248 {
249         /* Capabilities will be negotiated on per-connection basis */
250         capabilities.RemoveAll();
251
252         /* Reset call setup timeout to some more reasonable value than 1 minute */
253         signallingChannelCallTimeout = PTimeInterval(0, 0, 10); /* 10 minutes */
254 }
255
256 /** The fullAddress parameter is used directly in the MakeCall method so
257   * the General form for the fullAddress argument is :
258   * [alias@][transport$]host[:port]
259   * default values:     alias = the same value as host.
260   *                                     transport = ip.
261   *                                     port = 1720.
262   */
263 int MyH323EndPoint::MyMakeCall(const PString & dest, PString & token, void *_callReference, void *_opts)
264 {
265         PString fullAddress;
266         MyH323Connection * connection;
267         H323Transport *transport = NULL;
268         unsigned int *callReference = (unsigned int *)_callReference;
269         call_options_t *opts = (call_options_t *)_opts;
270
271         /* Determine whether we are using a gatekeeper or not. */
272         if (GetGatekeeper()) {
273                 fullAddress = dest;
274                 if (h323debug) {
275                         cout << " -- Making call to " << fullAddress << " using gatekeeper." << endl;
276                 }
277         } else {
278                 fullAddress = dest;
279                 if (h323debug) {
280                         cout << " -- Making call to " << fullAddress << " without gatekeeper." << endl;
281                 }
282                 /* Use bindaddr for outgoing calls too if we don't use gatekeeper */
283                 if (listeners.GetSize() > 0) {
284                         H323TransportAddress taddr = listeners[0].GetTransportAddress();
285                         PIPSocket::Address addr;
286                         WORD port;
287                         if (taddr.GetIpAndPort(addr, port)) {
288                                 /* Create own transport for specific addresses only */
289                                 if (addr) {
290                                         if (h323debug)
291                                                 cout << "Using " << addr << " for outbound call" << endl;
292                                         transport = new MyH323TransportTCP(*this, addr);
293                                         if (!transport)
294                                                 cout << "Unable to create transport for outgoing call" << endl;
295                                 }
296                         } else
297                                 cout << "Unable to get address and port" << endl;
298                 }
299         }
300         if (!(connection = (MyH323Connection *)H323EndPoint::MakeCallLocked(fullAddress, token, opts, transport))) {
301                 if (h323debug) {
302                         cout << "Error making call to \"" << fullAddress << '"' << endl;
303                 }
304                 return 1;
305         }
306         *callReference = connection->GetCallReference();
307
308         if (h323debug) {
309                 cout << "\t-- " << GetLocalUserName() << " is calling host " << fullAddress << endl;
310                 cout << "\t-- Call token is " << (const char *)token << endl;
311                 cout << "\t-- Call reference is " << *callReference << endl;
312 #ifdef PTRACING
313                 cout << "\t-- DTMF Payload is " << connection->dtmfCodec << endl;
314 #endif
315         }
316         connection->Unlock();
317         return 0;
318 }
319
320 void MyH323EndPoint::SetEndpointTypeInfo( H225_EndpointType & info ) const
321 {
322         H323EndPoint::SetEndpointTypeInfo(info);
323
324         if (terminalType == e_GatewayOnly){
325                 info.RemoveOptionalField(H225_EndpointType::e_terminal);
326                 info.IncludeOptionalField(H225_EndpointType::e_gateway);
327         }
328
329         info.m_gateway.IncludeOptionalField(H225_GatewayInfo::e_protocol);
330         info.m_gateway.m_protocol.SetSize(1);
331         H225_SupportedProtocols &protocol=info.m_gateway.m_protocol[0];
332         protocol.SetTag(H225_SupportedProtocols::e_voice);
333         PINDEX as=SupportedPrefixes.GetSize();
334         ((H225_VoiceCaps &)protocol).m_supportedPrefixes.SetSize(as);
335         for (PINDEX p=0; p<as; p++) {
336                 H323SetAliasAddress(SupportedPrefixes[p], ((H225_VoiceCaps &)protocol).m_supportedPrefixes[p].m_prefix, H225_AliasAddress::e_dialedDigits);
337         }
338 }
339
340 void MyH323EndPoint::SetGateway(void)
341 {
342         terminalType = e_GatewayOnly;
343 }
344
345 PBoolean MyH323EndPoint::ClearCall(const PString & token, H323Connection::CallEndReason reason)
346 {
347         if (h323debug) {
348 #ifdef PTRACING
349                 cout << "\t-- ClearCall: Request to clear call with token " << token << ", cause " << reason << endl;
350 #else
351                 cout << "\t-- ClearCall: Request to clear call with token " << token << ", cause [" << (int)reason << "]" << endl;
352 #endif
353         }
354         return H323EndPoint::ClearCall(token, reason);
355 }
356
357 PBoolean MyH323EndPoint::ClearCall(const PString & token)
358 {
359         if (h323debug) {
360                 cout << "\t-- ClearCall: Request to clear call with token " << token << endl;
361         }
362         return H323EndPoint::ClearCall(token, H323Connection::EndedByLocalUser);
363 }
364
365 void MyH323EndPoint::SendUserTone(const PString &token, char tone)
366 {
367         H323Connection *connection = NULL;
368
369         connection = FindConnectionWithLock(token);
370         if (connection != NULL) {
371                 connection->SendUserInputTone(tone, 500);
372                 connection->Unlock();
373         }
374 }
375
376 void MyH323EndPoint::OnClosedLogicalChannel(H323Connection & connection, const H323Channel & channel)
377 {
378         channelsOpen--;
379         if (h323debug) {
380                 cout << "\t\tchannelsOpen = " << channelsOpen << endl;
381         }
382         H323EndPoint::OnClosedLogicalChannel(connection, channel);
383 }
384
385 PBoolean MyH323EndPoint::OnConnectionForwarded(H323Connection & connection,
386                 const PString & forwardParty,
387                 const H323SignalPDU & pdu)
388 {
389         if (h323debug) {
390                 cout << "\t-- Call Forwarded to " << forwardParty << endl;
391         }
392         return FALSE;
393 }
394
395 PBoolean MyH323EndPoint::ForwardConnection(H323Connection & connection,
396                 const PString & forwardParty,
397                 const H323SignalPDU & pdu)
398 {
399         if (h323debug) {
400                 cout << "\t-- Forwarding call to " << forwardParty << endl;
401         }
402         return H323EndPoint::ForwardConnection(connection, forwardParty, pdu);
403 }
404
405 void MyH323EndPoint::OnConnectionEstablished(H323Connection & connection, const PString & estCallToken)
406 {
407         if (h323debug) {
408                 cout << "\t=-= In OnConnectionEstablished for call " << connection.GetCallReference() << endl;
409                 cout << "\t\t-- Connection Established with \"" << connection.GetRemotePartyName() << "\"" << endl;
410         }
411         on_connection_established(connection.GetCallReference(), (const char *)connection.GetCallToken());
412 }
413
414 /** OnConnectionCleared callback function is called upon the dropping of an established
415   * H323 connection.
416   */
417 void MyH323EndPoint::OnConnectionCleared(H323Connection & connection, const PString & clearedCallToken)
418 {
419         PString remoteName = connection.GetRemotePartyName();
420
421         switch (connection.GetCallEndReason()) {
422                 case H323Connection::EndedByCallForwarded:
423                         if (h323debug) {
424                                 cout << "-- " << remoteName << " has forwarded the call" << endl;
425                         }
426                         break;
427                 case H323Connection::EndedByRemoteUser:
428                         if (h323debug) {
429                                 cout << "-- " << remoteName << " has cleared the call" << endl;
430                         }
431                         break;
432                 case H323Connection::EndedByCallerAbort:
433                         if (h323debug) {
434                                 cout << "-- " << remoteName << " has stopped calling" << endl;
435                         }
436                         break;
437                 case H323Connection::EndedByRefusal:
438                         if (h323debug) {
439                                 cout << "-- " << remoteName << " did not accept your call" << endl;
440                         }
441                         break;
442                 case H323Connection::EndedByRemoteBusy:
443                         if (h323debug) {
444                                 cout << "-- " << remoteName << " was busy" << endl;
445                         }
446                         break;
447                 case H323Connection::EndedByRemoteCongestion:
448                         if (h323debug) {
449                                 cout << "-- Congested link to " << remoteName << endl;
450                         }
451                         break;
452                 case H323Connection::EndedByNoAnswer:
453                         if (h323debug) {
454                                 cout << "-- " << remoteName << " did not answer your call" << endl;
455                         }
456                         break;
457                 case H323Connection::EndedByTransportFail:
458                         if (h323debug) {
459                                 cout << "-- Call with " << remoteName << " ended abnormally" << endl;
460                         }
461                         break;
462                 case H323Connection::EndedByCapabilityExchange:
463                         if (h323debug) {
464                                 cout << "-- Could not find common codec with " << remoteName << endl;
465                         }
466                         break;
467                 case H323Connection::EndedByNoAccept:
468                         if (h323debug) {
469                                 cout << "-- Did not accept incoming call from " << remoteName << endl;
470                         }
471                         break;
472                 case H323Connection::EndedByAnswerDenied:
473                         if (h323debug) {
474                                 cout << "-- Refused incoming call from " << remoteName << endl;
475                         }
476                         break;
477                 case H323Connection::EndedByNoUser:
478                         if (h323debug) {
479                                 cout << "-- Remote endpoint could not find user: " << remoteName << endl;
480                         }
481                         break;
482                 case H323Connection::EndedByNoBandwidth:
483                         if (h323debug) {
484                                 cout << "-- Call to " << remoteName << " aborted, insufficient bandwidth." << endl;
485                         }
486                         break;
487                 case H323Connection::EndedByUnreachable:
488                         if (h323debug) {
489                                 cout << "-- " << remoteName << " could not be reached." << endl;
490                         }
491                         break;
492                 case H323Connection::EndedByHostOffline:
493                         if (h323debug) {
494                                 cout << "-- " << remoteName << " is not online." << endl;
495                         }
496                         break;
497                 case H323Connection::EndedByNoEndPoint:
498                         if (h323debug) {
499                                 cout << "-- No phone running for " << remoteName << endl;
500                         }
501                         break;
502                 case H323Connection::EndedByConnectFail:
503                         if (h323debug) {
504                                 cout << "-- Transport error calling " << remoteName << endl;
505                         }
506                         break;
507                 default:
508                         if (h323debug) {
509 #ifdef PTRACING
510                                 cout << " -- Call with " << remoteName << " completed (" << connection.GetCallEndReason() << ")" << endl;
511 #else
512                                 cout << " -- Call with " << remoteName << " completed ([" << (int)connection.GetCallEndReason() << "])" << endl;
513 #endif
514                         }
515         }
516
517         if (connection.IsEstablished()) {
518                 if (h323debug) {
519                         cout << "\t-- Call duration " << setprecision(0) << setw(5) << (PTime() - connection.GetConnectionStartTime()) << endl;
520                 }
521         }
522         /* Invoke the PBX application registered callback */
523         on_connection_cleared(connection.GetCallReference(), clearedCallToken);
524         return;
525 }
526
527 H323Connection * MyH323EndPoint::CreateConnection(unsigned callReference, void *userData, H323Transport *transport, H323SignalPDU *setupPDU)
528 {
529         unsigned options = 0;
530         call_options_t *opts = (call_options_t *)userData;
531         MyH323Connection *conn;
532
533         if (opts && opts->fastStart) {
534                 options |= H323Connection::FastStartOptionEnable;
535         } else {
536                 options |= H323Connection::FastStartOptionDisable;
537         }
538         if (opts && opts->h245Tunneling) {
539                 options |= H323Connection::H245TunnelingOptionEnable;
540         } else {
541                 options |= H323Connection::H245TunnelingOptionDisable;
542         }
543 /* Disable until I can figure out the proper way to deal with this */
544 #if 0
545         if (opts->silenceSuppression) {
546                 options |= H323Connection::SilenceSuppresionOptionEnable;
547         } else {
548                 options |= H323Connection::SilenceSUppressionOptionDisable;
549         }
550 #endif
551         conn = new MyH323Connection(*this, callReference, options);
552         if (conn) {
553                 if (opts)
554                         conn->SetCallOptions(opts, (setupPDU ? TRUE : FALSE));
555         }
556         return conn;
557 }
558
559 /* MyH323Connection Implementation */
560 MyH323Connection::MyH323Connection(MyH323EndPoint & ep, unsigned callReference,
561                                                         unsigned options)
562         : H323Connection(ep, callReference, options)
563 {
564 #ifdef H323_H450
565         /* Dispatcher will free out all registered handlers */
566         if (h450dispatcher)
567                 delete h450dispatcher;
568         h450dispatcher = new H450xDispatcher(*this);
569         h4502handler = new H4502Handler(*this, *h450dispatcher);
570         h4504handler = new MyH4504Handler(*this, *h450dispatcher);
571         h4506handler = new H4506Handler(*this, *h450dispatcher);
572         h45011handler = new H45011Handler(*this, *h450dispatcher);
573 #endif
574         cause = -1;
575         sessionId = 0;
576         bridging = FALSE;
577         holdHandling = progressSetup = progressAlert = 0;
578         dtmfMode = 0;
579         dtmfCodec[0] = dtmfCodec[1] = (RTP_DataFrame::PayloadTypes)0;
580         redirect_reason = -1;
581         transfer_capability = -1;
582 #ifdef TUNNELLING
583         tunnelOptions = remoteTunnelOptions = 0;
584 #endif
585         if (h323debug) {
586                 cout << "       == New H.323 Connection created." << endl;
587         }
588         return;
589 }
590
591 MyH323Connection::~MyH323Connection()
592 {
593         if (h323debug) {
594                 cout << "       == H.323 Connection deleted." << endl;
595         }
596         return;
597 }
598
599 PBoolean MyH323Connection::OnReceivedProgress(const H323SignalPDU &pdu)
600 {
601         PBoolean isInband;
602         unsigned pi;
603
604         if (!H323Connection::OnReceivedProgress(pdu)) {
605                 return FALSE;
606         }
607
608         if (!pdu.GetQ931().GetProgressIndicator(pi))
609                 pi = 0;
610         if (h323debug) {
611                 cout << "\t- Progress Indicator: " << pi << endl;
612         }
613
614         switch(pi) {
615         case Q931::ProgressNotEndToEndISDN:
616         case Q931::ProgressInbandInformationAvailable:
617                 isInband = TRUE;
618                 break;
619         default:
620                 isInband = FALSE;
621         }
622         on_progress(GetCallReference(), (const char *)GetCallToken(), isInband);
623
624         return connectionState != ShuttingDownConnection;
625 }
626
627 PBoolean MyH323Connection::MySendProgress()
628 {
629         /* The code taken from H323Connection::AnsweringCall() but ALWAYS send
630            PROGRESS message, including slow start operations */
631         H323SignalPDU progressPDU;
632         H225_Progress_UUIE &prog = progressPDU.BuildProgress(*this);
633
634         if (!mediaWaitForConnect) {
635                 if (SendFastStartAcknowledge(prog.m_fastStart))
636                         prog.IncludeOptionalField(H225_Progress_UUIE::e_fastStart);
637                 else {
638                         if (connectionState == ShuttingDownConnection)
639                                 return FALSE;
640
641                         /* Do early H.245 start */
642                         earlyStart = TRUE;
643                         if (!h245Tunneling) {
644                                 if (!H323Connection::StartControlChannel())
645                                         return FALSE;
646                                 prog.IncludeOptionalField(H225_Progress_UUIE::e_h245Address);
647                                 controlChannel->SetUpTransportPDU(prog.m_h245Address, TRUE);
648                         }
649                 }
650         }
651         progressPDU.GetQ931().SetProgressIndicator(Q931::ProgressInbandInformationAvailable);
652
653 #ifdef TUNNELLING
654         EmbedTunneledInfo(progressPDU);
655 #endif
656         HandleTunnelPDU(&progressPDU);
657         WriteSignalPDU(progressPDU);
658
659         return TRUE;
660 }
661
662 H323Connection::AnswerCallResponse MyH323Connection::OnAnswerCall(const PString & caller,
663                                                                 const H323SignalPDU & setupPDU,
664                                                                 H323SignalPDU & connectPDU)
665 {
666         unsigned pi;
667
668         if (h323debug) {
669                 cout << "\t=-= In OnAnswerCall for call " << GetCallReference() << endl;
670         }
671
672         if (connectionState == ShuttingDownConnection)
673                 return H323Connection::AnswerCallDenied;
674
675         if (!setupPDU.GetQ931().GetProgressIndicator(pi)) {
676                 pi = 0;
677         }
678         if (h323debug) {
679                 cout << "\t\t- Progress Indicator: " << pi << endl;
680         }
681         if (progressAlert) {
682                 pi = progressAlert;
683         } else if (pi == Q931::ProgressOriginNotISDN) {
684                 pi = Q931::ProgressInbandInformationAvailable;
685         }
686         if (pi && alertingPDU) {
687                 alertingPDU->GetQ931().SetProgressIndicator(pi);
688         }
689         if (h323debug) {
690                 cout << "\t\t- Inserting PI of " << pi << " into ALERTING message" << endl;
691         }
692
693 #ifdef TUNNELLING
694         if (alertingPDU)
695                 EmbedTunneledInfo(*alertingPDU);
696         EmbedTunneledInfo(connectPDU);
697 #endif
698
699         if (!on_answer_call(GetCallReference(), (const char *)GetCallToken())) {
700                 return H323Connection::AnswerCallDenied;
701         }
702         /* The call will be answered later with "AnsweringCall()" function.
703          */
704         return ((pi || (fastStartState != FastStartDisabled)) ? AnswerCallDeferredWithMedia : AnswerCallDeferred);
705 }
706
707 PBoolean MyH323Connection::OnAlerting(const H323SignalPDU & alertingPDU, const PString & username)
708 {
709         if (h323debug) {
710                 cout << "\t=-= In OnAlerting for call " << GetCallReference()
711                         << ": sessionId=" << sessionId << endl;
712                 cout << "\t-- Ringing phone for \"" << username << "\"" << endl;
713         }
714
715         if (on_progress) {
716                 PBoolean isInband;
717                 unsigned alertingPI;
718
719                 if (!alertingPDU.GetQ931().GetProgressIndicator(alertingPI)) {
720                         alertingPI = 0;
721                 }
722                 if (h323debug) {
723                         cout << "\t\t- Progress Indicator: " << alertingPI << endl;
724                 }
725
726                 switch(alertingPI) {
727                 case Q931::ProgressNotEndToEndISDN:
728                 case Q931::ProgressInbandInformationAvailable:
729                         isInband = TRUE;
730                         break;
731                 default:
732                         isInband = FALSE;
733                 }
734                 on_progress(GetCallReference(), (const char *)GetCallToken(), isInband);
735         }
736         on_chan_ringing(GetCallReference(), (const char *)GetCallToken() );
737         return connectionState != ShuttingDownConnection;
738 }
739
740 void MyH323Connection::SetCallOptions(void *o, PBoolean isIncoming)
741 {
742         call_options_t *opts = (call_options_t *)o;
743
744         progressSetup = opts->progress_setup;
745         progressAlert = opts->progress_alert;
746         holdHandling = opts->holdHandling;
747         dtmfCodec[0] = (RTP_DataFrame::PayloadTypes)opts->dtmfcodec[0];
748         dtmfCodec[1] = (RTP_DataFrame::PayloadTypes)opts->dtmfcodec[1];
749         dtmfMode = opts->dtmfmode;
750
751         if (isIncoming) {
752                 fastStartState = (opts->fastStart ? FastStartInitiate : FastStartDisabled);
753                 h245Tunneling = (opts->h245Tunneling ? TRUE : FALSE);
754         } else {
755                 sourceE164 = PString(opts->cid_num);
756                 SetLocalPartyName(PString(opts->cid_name));
757                 SetDisplayName(PString(opts->cid_name));
758                 if (opts->redirect_reason >= 0) {
759                         rdnis = PString(opts->cid_rdnis);
760                         redirect_reason = opts->redirect_reason;
761                 }
762                 cid_presentation = opts->presentation;
763                 cid_ton = opts->type_of_number;
764                 if (opts->transfer_capability >= 0) {
765                         transfer_capability = opts->transfer_capability;
766                 }
767         }
768         tunnelOptions = opts->tunnelOptions;
769 }
770
771 void MyH323Connection::SetCallDetails(void *callDetails, const H323SignalPDU &setupPDU, PBoolean isIncoming)
772 {
773         PString sourceE164;
774         PString destE164;
775         PString sourceAliases;
776         PString destAliases;
777         char *s, *s1;
778         call_details_t *cd = (call_details_t *)callDetails;
779
780         memset(cd, 0, sizeof(*cd));
781         cd->call_reference = GetCallReference();
782         cd->call_token = strdup((const char *)GetCallToken());
783
784         sourceE164 = "";
785         setupPDU.GetSourceE164(sourceE164);
786         cd->call_source_e164 = strdup((const char *)sourceE164);
787
788         destE164 = "";
789         setupPDU.GetDestinationE164(destE164);
790         cd->call_dest_e164 = strdup((const char *)destE164);
791
792         /* XXX Is it possible to have this information for outgoing calls too? XXX */
793         if (isIncoming) {
794                 PString sourceName;
795                 PIPSocket::Address Ip;
796                 WORD sourcePort;
797                 PString redirect_number;
798                 unsigned redirect_reason;
799                 unsigned plan, type, screening, presentation;
800                 Q931::InformationTransferCapability capability;
801                 unsigned transferRate, codingStandard, userInfoLayer1;
802
803                 /* Fetch presentation and type information about calling party's number */
804                 if (setupPDU.GetQ931().GetCallingPartyNumber(sourceName, &plan, &type, &presentation, &screening, 0, 0)) {
805                         /* Construct fields back */
806                         cd->type_of_number = (type << 4) | plan;
807                         cd->presentation = (presentation << 5) | screening;
808                 } else if (cd->call_source_e164[0]) {
809                         cd->type_of_number = 0;         /* UNKNOWN */
810                         cd->presentation = 0x03;        /* ALLOWED NETWORK NUMBER - Default */
811                         if (setupPDU.GetQ931().HasIE(Q931::UserUserIE)) {
812                                 const H225_Setup_UUIE &setup_uuie = setupPDU.m_h323_uu_pdu.m_h323_message_body;
813                                 if (setup_uuie.HasOptionalField(H225_Setup_UUIE::e_presentationIndicator))
814                                         cd->presentation = (cd->presentation & 0x9f) | (((unsigned int)setup_uuie.m_presentationIndicator.GetTag()) << 5);
815                                 if (setup_uuie.HasOptionalField(H225_Setup_UUIE::e_screeningIndicator))
816                                         cd->presentation = (cd->presentation & 0xe0) | (((unsigned int)setup_uuie.m_screeningIndicator.GetValue()) & 0x1f);
817                         }
818                 } else {
819                         cd->type_of_number = 0;         /* UNKNOWN */
820                         cd->presentation = 0x43;        /* NUMBER NOT AVAILABLE */
821                 }
822
823                 sourceName = setupPDU.GetQ931().GetDisplayName();
824                 cd->call_source_name = strdup((const char *)sourceName);
825
826                 GetSignallingChannel()->GetRemoteAddress().GetIpAndPort(Ip, sourcePort);
827                 cd->sourceIp = strdup((const char *)Ip.AsString());
828
829                 if (setupPDU.GetQ931().GetRedirectingNumber(redirect_number, NULL, NULL, NULL, NULL, &redirect_reason, 0, 0, 0)) {
830                         cd->redirect_number = strdup((const char *)redirect_number);
831                         cd->redirect_reason = redirect_reason;
832                 }
833                 else
834                         cd->redirect_reason = -1;
835
836                 /* Fetch Q.931's transfer capability */
837                 if (((Q931 &)setupPDU.GetQ931()).GetBearerCapabilities(capability, transferRate, &codingStandard, &userInfoLayer1))
838                         cd->transfer_capability = ((unsigned int)capability & 0x1f) | (codingStandard << 5);
839                 else
840                         cd->transfer_capability = 0x00; /* ITU coding of Speech */
841
842                 /* Don't show local username as called party name */
843                 SetDisplayName(cd->call_dest_e164);
844         }
845
846         /* Convert complex strings */
847         //  FIXME: deal more than one source alias
848         sourceAliases = setupPDU.GetSourceAliases();
849         s1 = strdup((const char *)sourceAliases);
850         if ((s = strchr(s1, ' ')) != NULL)
851                 *s = '\0';
852         if ((s = strchr(s1, '\t')) != NULL)
853                 *s = '\0';
854         cd->call_source_aliases = s1;
855
856         destAliases = setupPDU.GetDestinationAlias();
857         s1 = strdup((const char *)destAliases);
858         if ((s = strchr(s1, ' ')) != NULL)
859                 *s = '\0';
860         if ((s = strchr(s1, '\t')) != NULL)
861                 *s = '\0';
862         cd->call_dest_alias = s1;
863 }
864
865 #ifdef TUNNELLING
866 static PBoolean FetchInformationElements(Q931 &q931, const PBYTEArray &data)
867 {
868         PINDEX offset = 0;
869
870         while (offset < data.GetSize()) {
871                 // Get field discriminator
872                 int discriminator = data[offset++];
873
874 #if 0
875                 /* Do not overwrite existing IEs */
876                 if (q931.HasIE((Q931::InformationElementCodes)discriminator)) {
877                         if ((discriminatir & 0x80) == 0)
878                                 offset += data[offset++];
879                         if (offset > data.GetSize())
880                                 return FALSE;
881                         continue;
882                 }
883 #endif
884
885                 PBYTEArray * item = new PBYTEArray;
886
887                 // For discriminator with high bit set there is no data
888                 if ((discriminator & 0x80) == 0) {
889                         int len = data[offset++];
890
891 #if 0           // That is not H.225 but regular Q.931 (ISDN) IEs
892                         if (discriminator == UserUserIE) {
893                                 // Special case of User-user field. See 7.2.2.31/H.225.0v4.
894                                 len <<= 8;
895                                 len |= data[offset++];
896
897                                 // we also have a protocol discriminator, which we ignore
898                                 offset++;
899
900                                 // before decrementing the length, make sure it is not zero
901                                 if (len == 0)
902                                         return FALSE;
903
904                                 // adjust for protocol discriminator
905                                 len--;
906                         }
907 #endif
908
909                         if (offset + len > data.GetSize()) {
910                                 delete item;
911                                 return FALSE;
912                         }
913
914                         memcpy(item->GetPointer(len), (const BYTE *)data+offset, len);
915                         offset += len;
916                 }
917
918                 q931.SetIE((Q931::InformationElementCodes)discriminator, *item);
919                 delete item;
920         }
921         return TRUE;
922 }
923
924 static PBoolean FetchCiscoTunneledInfo(Q931 &q931, const H323SignalPDU &pdu)
925 {
926         PBoolean res = FALSE;
927         const H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
928
929         if(uuPDU.HasOptionalField(H225_H323_UU_PDU::e_nonStandardControl)) {
930                 for(int i = 0; i < uuPDU.m_nonStandardControl.GetSize(); ++i) {
931                         const H225_NonStandardParameter &np = uuPDU.m_nonStandardControl[i];
932                         const H225_NonStandardIdentifier &id = np.m_nonStandardIdentifier;
933                         if (id.GetTag() == H225_NonStandardIdentifier::e_h221NonStandard) {
934                                 const H225_H221NonStandard &ni = id;
935                                 /* Check for Cisco */
936                                 if ((ni.m_t35CountryCode == 181) && (ni.m_t35Extension == 0) && (ni.m_manufacturerCode == 18)) {
937                                         const PBYTEArray &data = np.m_data;
938                                         if (h323debug)
939                                                 cout << setprecision(0) << "Received non-standard Cisco extension data " << np.m_data << endl;
940                                         CISCO_H225_H323_UU_NonStdInfo c;
941                                         PPER_Stream strm(data);
942                                         if (c.Decode(strm)) {
943                                                 PBoolean haveIEs = FALSE;
944                                                 if (h323debug)
945                                                         cout << setprecision(0) << "H323_UU_NonStdInfo = " << c << endl;
946                                                 if (c.HasOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_protoParam)) {
947                                                         FetchInformationElements(q931, c.m_protoParam.m_qsigNonStdInfo.m_rawMesg);
948                                                         haveIEs = TRUE;
949                                                 }
950                                                 if (c.HasOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_commonParam)) {
951                                                         FetchInformationElements(q931, c.m_commonParam.m_redirectIEinfo.m_redirectIE);
952                                                         haveIEs = TRUE;
953                                                 }
954                                                 if (haveIEs && h323debug)
955                                                         cout << setprecision(0) << "Information elements collected:" << q931 << endl;
956                                                 res = TRUE;
957                                         } else {
958                                                 cout << "ERROR while decoding non-standard Cisco extension" << endl;
959                                                 return FALSE;
960                                         }
961                                 }
962                         }
963                 }
964         }
965         return res;
966 }
967
968 static PBoolean EmbedCiscoTunneledInfo(H323SignalPDU &pdu)
969 {
970         static const struct {
971                 Q931::InformationElementCodes ie;
972                 PBoolean dontDelete;
973         } codes[] = {
974                 { Q931::RedirectingNumberIE, },
975                 { Q931::FacilityIE, },
976 //              { Q931::CallingPartyNumberIE, TRUE },
977         };
978
979         PBoolean res = FALSE;
980         PBoolean notRedirOnly = FALSE;
981         Q931 tmpQ931;
982         Q931 &q931 = pdu.GetQ931();
983
984         for(unsigned i = 0; i < ARRAY_LEN(codes); ++i) {
985                 if (q931.HasIE(codes[i].ie)) {
986                         tmpQ931.SetIE(codes[i].ie, q931.GetIE(codes[i].ie));
987                         if (!codes[i].dontDelete)
988                                 q931.RemoveIE(codes[i].ie);
989                         if (codes[i].ie != Q931::RedirectingNumberIE)
990                                 notRedirOnly = TRUE;
991                         res = TRUE;
992                 }
993         }
994         /* Have something to embed */
995         if (res) {
996                 PBYTEArray msg;
997                 if (!tmpQ931.Encode(msg))
998                         return FALSE;
999                 PBYTEArray ies(msg.GetPointer() + 5, msg.GetSize() - 5);
1000
1001                 H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
1002                 if(!uuPDU.HasOptionalField(H225_H323_UU_PDU::e_nonStandardControl)) {
1003                         uuPDU.IncludeOptionalField(H225_H323_UU_PDU::e_nonStandardControl);
1004                         uuPDU.m_nonStandardControl.SetSize(0);
1005                 }
1006                 H225_NonStandardParameter *np = new H225_NonStandardParameter;
1007                 uuPDU.m_nonStandardControl.Append(np);
1008                 H225_NonStandardIdentifier &nsi = (*np).m_nonStandardIdentifier;
1009                 nsi.SetTag(H225_NonStandardIdentifier::e_h221NonStandard);
1010                 H225_H221NonStandard &ns = nsi;
1011                 ns.m_t35CountryCode = 181;
1012                 ns.m_t35Extension = 0;
1013                 ns.m_manufacturerCode = 18;
1014
1015                 CISCO_H225_H323_UU_NonStdInfo c;
1016                 c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_version);
1017                 c.m_version = 0;
1018
1019                 if (notRedirOnly) {
1020                         c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_protoParam);
1021                         CISCO_H225_QsigNonStdInfo &qsigInfo = c.m_protoParam.m_qsigNonStdInfo;
1022                         qsigInfo.m_iei = ies[0];
1023                         qsigInfo.m_rawMesg = ies;
1024                 } else {
1025                         c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_commonParam);
1026                         c.m_commonParam.m_redirectIEinfo.m_redirectIE = ies;
1027                 }
1028                 PPER_Stream stream;
1029                 c.Encode(stream);
1030                 stream.CompleteEncoding();
1031                 (*np).m_data = stream;
1032         }
1033         return res;
1034 }
1035
1036 static const char OID_QSIG[] = "1.3.12.9";
1037
1038 static PBoolean FetchQSIGTunneledInfo(Q931 &q931, const H323SignalPDU &pdu)
1039 {
1040         PBoolean res = FALSE;
1041         const H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
1042         if (uuPDU.HasOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage)) {
1043                 const H225_H323_UU_PDU_tunnelledSignallingMessage &sig = uuPDU.m_tunnelledSignallingMessage;
1044                 const H225_TunnelledProtocol_id &proto = sig.m_tunnelledProtocolID.m_id;
1045                 if ((proto.GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
1046                                 (((const PASN_ObjectId &)proto).AsString() == OID_QSIG)) {
1047                         const H225_ArrayOf_PASN_OctetString &sigs = sig.m_messageContent;
1048                         for(int i = 0; i < sigs.GetSize(); ++i) {
1049                                 const PASN_OctetString &msg = sigs[i];
1050                                 if (h323debug)
1051                                         cout << setprecision(0) << "Q.931 message data is " << msg << endl;
1052                                 if(!q931.Decode((const PBYTEArray &)msg)) {
1053                                         cout << "Error while decoding Q.931 message" << endl;
1054                                         return FALSE;
1055                                 }
1056                                 res = TRUE;
1057                                 if (h323debug)
1058                                         cout << setprecision(0) << "Received QSIG message " << q931 << endl;
1059                         }
1060                 }
1061         }
1062         return res;
1063 }
1064
1065 static H225_EndpointType *GetEndpointType(H323SignalPDU &pdu)
1066 {
1067         if (!pdu.GetQ931().HasIE(Q931::UserUserIE))
1068                 return NULL;
1069
1070         H225_H323_UU_PDU_h323_message_body &body = pdu.m_h323_uu_pdu.m_h323_message_body;
1071         switch (body.GetTag()) {
1072         case H225_H323_UU_PDU_h323_message_body::e_setup:
1073                 return &((H225_Setup_UUIE &)body).m_sourceInfo;
1074         case H225_H323_UU_PDU_h323_message_body::e_callProceeding:
1075                 return &((H225_CallProceeding_UUIE &)body).m_destinationInfo;
1076         case H225_H323_UU_PDU_h323_message_body::e_connect:
1077                 return &((H225_Connect_UUIE &)body).m_destinationInfo;
1078         case H225_H323_UU_PDU_h323_message_body::e_alerting:
1079                 return &((H225_Alerting_UUIE &)body).m_destinationInfo;
1080         case H225_H323_UU_PDU_h323_message_body::e_facility:
1081                 return &((H225_Facility_UUIE &)body).m_destinationInfo;
1082         case H225_H323_UU_PDU_h323_message_body::e_progress:
1083                 return &((H225_Progress_UUIE &)body).m_destinationInfo;
1084         }
1085         return NULL;
1086 }
1087
1088 static PBoolean QSIGTunnelRequested(H323SignalPDU &pdu)
1089 {
1090         H225_EndpointType *epType = GetEndpointType(pdu);
1091         if (epType) {
1092                 if (!(*epType).HasOptionalField(H225_EndpointType::e_supportedTunnelledProtocols)) {
1093                         return FALSE;
1094                 }
1095                 H225_ArrayOf_TunnelledProtocol &protos = (*epType).m_supportedTunnelledProtocols;
1096                 for (int i = 0; i < protos.GetSize(); ++i)
1097                 {
1098                         if ((protos[i].GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
1099                                         (((const PASN_ObjectId &)protos[i]).AsString() == OID_QSIG)) {
1100                                 return TRUE;
1101                         }
1102                 }
1103         }
1104         return FALSE;
1105 }
1106
1107 static PBoolean EmbedQSIGTunneledInfo(H323SignalPDU &pdu)
1108 {
1109         static const Q931::InformationElementCodes codes[] =
1110         { Q931::RedirectingNumberIE, Q931::FacilityIE };
1111
1112         Q931 &q931 = pdu.GetQ931();
1113         PBYTEArray message;
1114
1115         q931.Encode(message);
1116
1117         /* Remove non-standard IEs */
1118         for(unsigned i = 0; i < ARRAY_LEN(codes); ++i) {
1119                 if (q931.HasIE(codes[i])) {
1120                         q931.RemoveIE(codes[i]);
1121                 }
1122         }
1123
1124         H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
1125         H225_EndpointType *epType = GetEndpointType(pdu);
1126         if (epType) {
1127                 if (!(*epType).HasOptionalField(H225_EndpointType::e_supportedTunnelledProtocols)) {
1128                         (*epType).IncludeOptionalField(H225_EndpointType::e_supportedTunnelledProtocols);
1129                         (*epType).m_supportedTunnelledProtocols.SetSize(0);
1130                 }
1131                 H225_ArrayOf_TunnelledProtocol &protos = (*epType).m_supportedTunnelledProtocols;
1132                 PBoolean addQSIG = TRUE;
1133                 for (int i = 0; i < protos.GetSize(); ++i)
1134                 {
1135                         if ((protos[i].GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
1136                                         (((PASN_ObjectId &)protos[i]).AsString() == OID_QSIG)) {
1137                                 addQSIG = FALSE;
1138                                 break;
1139                         }
1140                 }
1141                 if (addQSIG) {
1142                         H225_TunnelledProtocol *proto = new H225_TunnelledProtocol;
1143                         (*proto).m_id.SetTag(H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID);
1144                         (PASN_ObjectId &)(proto->m_id) = OID_QSIG;
1145                         protos.Append(proto);
1146                 }
1147         }
1148         if (!uuPDU.HasOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage))
1149                 uuPDU.IncludeOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage);
1150         H225_H323_UU_PDU_tunnelledSignallingMessage &sig = uuPDU.m_tunnelledSignallingMessage;
1151         H225_TunnelledProtocol_id &proto = sig.m_tunnelledProtocolID.m_id;
1152         if ((proto.GetTag() != H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) ||
1153                         (((const PASN_ObjectId &)proto).AsString() != OID_QSIG)) {
1154                 proto.SetTag(H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID);
1155                 (PASN_ObjectId &)proto = OID_QSIG;
1156                 sig.m_messageContent.SetSize(0);
1157         }
1158         PASN_OctetString *msg = new PASN_OctetString;
1159         sig.m_messageContent.Append(msg);
1160         *msg = message;
1161         return TRUE;
1162 }
1163
1164 PBoolean MyH323Connection::EmbedTunneledInfo(H323SignalPDU &pdu)
1165 {
1166         if ((tunnelOptions & H323_TUNNEL_QSIG) || (remoteTunnelOptions & H323_TUNNEL_QSIG))
1167                 EmbedQSIGTunneledInfo(pdu);
1168         if ((tunnelOptions & H323_TUNNEL_CISCO) || (remoteTunnelOptions & H323_TUNNEL_CISCO))
1169                 EmbedCiscoTunneledInfo(pdu);
1170
1171         return TRUE;
1172 }
1173
1174 /* Handle tunneled messages */
1175 PBoolean MyH323Connection::HandleSignalPDU(H323SignalPDU &pdu)
1176 {
1177         if (pdu.GetQ931().HasIE(Q931::UserUserIE)) {
1178                 Q931 tunneledInfo;
1179                 const Q931 *q931Info;
1180
1181                 q931Info = NULL;
1182                 if (FetchCiscoTunneledInfo(tunneledInfo, pdu)) {
1183                         q931Info = &tunneledInfo;
1184                         remoteTunnelOptions |= H323_TUNNEL_CISCO;
1185                 }
1186                 if (FetchQSIGTunneledInfo(tunneledInfo, pdu)) {
1187                         q931Info = &tunneledInfo;
1188                         remoteTunnelOptions |= H323_TUNNEL_QSIG;
1189                 }
1190                 if (!(remoteTunnelOptions & H323_TUNNEL_QSIG) && QSIGTunnelRequested(pdu)) {
1191                         remoteTunnelOptions |= H323_TUNNEL_QSIG;
1192                 }
1193                 if (q931Info) {
1194                         if (q931Info->HasIE(Q931::RedirectingNumberIE)) {
1195                                 pdu.GetQ931().SetIE(Q931::RedirectingNumberIE, q931Info->GetIE(Q931::RedirectingNumberIE));
1196                                 if (h323debug) {
1197                                         PString number;
1198                                         unsigned reason;
1199                                         if(q931Info->GetRedirectingNumber(number, NULL, NULL, NULL, NULL, &reason, 0, 0, 0))
1200                                                 cout << "Got redirection from " << number << ", reason " << reason << endl;
1201                                 }
1202                         }
1203                 }
1204         }
1205
1206         return H323Connection::HandleSignalPDU(pdu);
1207 }
1208 #endif
1209
1210 PBoolean MyH323Connection::OnReceivedSignalSetup(const H323SignalPDU & setupPDU)
1211 {
1212         call_details_t cd;
1213
1214         if (h323debug) {
1215                 cout << "\t--Received SETUP message" << endl;
1216         }
1217
1218         if (connectionState == ShuttingDownConnection)
1219                 return FALSE;
1220
1221         SetCallDetails(&cd, setupPDU, TRUE);
1222
1223         /* Notify Asterisk of the request */
1224         call_options_t *res = on_incoming_call(&cd);
1225
1226         if (!res) {
1227                 if (h323debug) {
1228                         cout << "\t-- Call Failed" << endl;
1229                 }
1230                 return FALSE;
1231         }
1232
1233         SetCallOptions(res, TRUE);
1234
1235         /* Disable fastStart if requested by remote side */
1236         if (h245Tunneling && !setupPDU.m_h323_uu_pdu.m_h245Tunneling) {
1237                 masterSlaveDeterminationProcedure->Stop();
1238                 capabilityExchangeProcedure->Stop();
1239                 PTRACE(3, "H225\tFast Start DISABLED!");
1240                 h245Tunneling = FALSE;
1241         }
1242
1243         return H323Connection::OnReceivedSignalSetup(setupPDU);
1244 }
1245
1246 PBoolean MyH323Connection::OnSendSignalSetup(H323SignalPDU & setupPDU)
1247 {
1248         call_details_t cd;
1249
1250         if (h323debug) {
1251                 cout << "\t-- Sending SETUP message" << endl;
1252         }
1253
1254         if (connectionState == ShuttingDownConnection)
1255                 return FALSE;
1256
1257         if (progressSetup)
1258                 setupPDU.GetQ931().SetProgressIndicator(progressSetup);
1259
1260         if (redirect_reason >= 0) {
1261                 setupPDU.GetQ931().SetRedirectingNumber(rdnis, 0, 0, 0, 0, redirect_reason);
1262                 /* OpenH323 incorrectly fills number IE when redirecting reason is specified - fix it */
1263                 PBYTEArray IE(setupPDU.GetQ931().GetIE(Q931::RedirectingNumberIE));
1264                 IE[0] = IE[0] & 0x7f;
1265                 IE[1] = IE[1] & 0x7f;
1266                 setupPDU.GetQ931().SetIE(Q931::RedirectingNumberIE, IE);
1267         }
1268
1269         if (transfer_capability)
1270                 setupPDU.GetQ931().SetBearerCapabilities((Q931::InformationTransferCapability)(transfer_capability & 0x1f), 1, ((transfer_capability >> 5) & 3));
1271
1272         SetCallDetails(&cd, setupPDU, FALSE);
1273
1274         int res = on_outgoing_call(&cd);
1275         if (!res) {
1276                 if (h323debug) {
1277                         cout << "\t-- Call Failed" << endl;
1278                 }
1279                 return FALSE;
1280         }
1281
1282         /* OpenH323 will build calling party information with default
1283            type and presentation information, so build it to be recorded
1284            by embedding routines */
1285         setupPDU.GetQ931().SetCallingPartyNumber(sourceE164, (cid_ton >> 4) & 0x07,
1286                         cid_ton & 0x0f, (cid_presentation >> 5) & 0x03, cid_presentation & 0x1f);
1287         setupPDU.GetQ931().SetDisplayName(GetDisplayName());
1288
1289 #ifdef TUNNELLING
1290         EmbedTunneledInfo(setupPDU);
1291 #endif
1292
1293         return H323Connection::OnSendSignalSetup(setupPDU);
1294 }
1295
1296 static PBoolean BuildFastStartList(const H323Channel & channel,
1297                 H225_ArrayOf_PASN_OctetString & array,
1298                 H323Channel::Directions reverseDirection)
1299 {
1300         H245_OpenLogicalChannel open;
1301         const H323Capability & capability = channel.GetCapability();
1302
1303         if (channel.GetDirection() != reverseDirection) {
1304                 if (!capability.OnSendingPDU(open.m_forwardLogicalChannelParameters.m_dataType))
1305                         return FALSE;
1306         }
1307         else {
1308                 if (!capability.OnSendingPDU(open.m_reverseLogicalChannelParameters.m_dataType))
1309                         return FALSE;
1310
1311                 open.m_forwardLogicalChannelParameters.m_multiplexParameters.SetTag(
1312                                 H245_OpenLogicalChannel_forwardLogicalChannelParameters_multiplexParameters::e_none);
1313                 open.m_forwardLogicalChannelParameters.m_dataType.SetTag(H245_DataType::e_nullData);
1314                 open.IncludeOptionalField(H245_OpenLogicalChannel::e_reverseLogicalChannelParameters);
1315         }
1316
1317         if (!channel.OnSendingPDU(open))
1318                 return FALSE;
1319
1320         PTRACE(4, "H225\tBuild fastStart:\n     " << setprecision(2) << open);
1321         PINDEX last = array.GetSize();
1322         array.SetSize(last+1);
1323         array[last].EncodeSubType(open);
1324
1325         PTRACE(3, "H225\tBuilt fastStart for " << capability);
1326         return TRUE;
1327 }
1328
1329 H323Connection::CallEndReason MyH323Connection::SendSignalSetup(const PString & alias,
1330                 const H323TransportAddress & address)
1331 {
1332         // Start the call, first state is asking gatekeeper
1333         connectionState = AwaitingGatekeeperAdmission;
1334
1335         // Indicate the direction of call.
1336         if (alias.IsEmpty())
1337                 remotePartyName = remotePartyAddress = address;
1338         else {
1339                 remotePartyName = alias;
1340                 remotePartyAddress = alias + '@' + address;
1341         }
1342
1343         // Start building the setup PDU to get various ID's
1344         H323SignalPDU setupPDU;
1345         H225_Setup_UUIE & setup = setupPDU.BuildSetup(*this, address);
1346
1347 #ifdef H323_H450
1348         h450dispatcher->AttachToSetup(setupPDU);
1349 #endif
1350
1351         // Save the identifiers generated by BuildSetup
1352         setupPDU.GetQ931().GetCalledPartyNumber(remotePartyNumber);
1353
1354         H323TransportAddress gatekeeperRoute = address;
1355
1356         // Check for gatekeeper and do admission check if have one
1357         H323Gatekeeper * gatekeeper = endpoint.GetGatekeeper();
1358         H225_ArrayOf_AliasAddress newAliasAddresses;
1359         if (gatekeeper != NULL) {
1360                 H323Gatekeeper::AdmissionResponse response;
1361                 response.transportAddress = &gatekeeperRoute;
1362                 response.aliasAddresses = &newAliasAddresses;
1363                 if (!gkAccessTokenOID)
1364                         response.accessTokenData = &gkAccessTokenData;
1365                 while (!gatekeeper->AdmissionRequest(*this, response, alias.IsEmpty())) {
1366                         PTRACE(1, "H225\tGatekeeper refused admission: "
1367                                         << (response.rejectReason == UINT_MAX
1368                                         ? PString("Transport error")
1369                                         : H225_AdmissionRejectReason(response.rejectReason).GetTagName()));
1370 #ifdef H323_H450
1371                         h4502handler->onReceivedAdmissionReject(H4501_GeneralErrorList::e_notAvailable);
1372 #endif
1373
1374                         switch (response.rejectReason) {
1375                         case H225_AdmissionRejectReason::e_calledPartyNotRegistered:
1376                                 return EndedByNoUser;
1377                         case H225_AdmissionRejectReason::e_requestDenied:
1378                                 return EndedByNoBandwidth;
1379                         case H225_AdmissionRejectReason::e_invalidPermission:
1380                         case H225_AdmissionRejectReason::e_securityDenial:
1381                                 return EndedBySecurityDenial;
1382                         case H225_AdmissionRejectReason::e_resourceUnavailable:
1383                                 return EndedByRemoteBusy;
1384                         case H225_AdmissionRejectReason::e_incompleteAddress:
1385                                 if (OnInsufficientDigits())
1386                                         break;
1387                                 // Then default case
1388                         default:
1389                                 return EndedByGatekeeper;
1390                         }
1391
1392                         PString lastRemotePartyName = remotePartyName;
1393                         while (lastRemotePartyName == remotePartyName) {
1394                                 Unlock(); // Release the mutex as can deadlock trying to clear call during connect.
1395                                 digitsWaitFlag.Wait();
1396                                 if (!Lock()) // Lock while checking for shutting down.
1397                                         return EndedByCallerAbort;
1398                         }
1399                 }
1400                 mustSendDRQ = TRUE;
1401                 if (response.gatekeeperRouted) {
1402                         setup.IncludeOptionalField(H225_Setup_UUIE::e_endpointIdentifier);
1403                         setup.m_endpointIdentifier = gatekeeper->GetEndpointIdentifier();
1404                         gatekeeperRouted = TRUE;
1405                 }
1406         }
1407
1408 #ifdef H323_TRANSNEXUS_OSP
1409         // check for OSP server (if not using GK)
1410         if (gatekeeper == NULL) {
1411                 OpalOSP::Provider * ospProvider = endpoint.GetOSPProvider();
1412                 if (ospProvider != NULL) {
1413                         OpalOSP::Transaction * transaction = new OpalOSP::Transaction();
1414                         if (transaction->Open(*ospProvider) != 0) {
1415                                 PTRACE(1, "H225\tCannot create OSP transaction");
1416                                 return EndedByOSPRefusal;
1417                         }
1418
1419                         OpalOSP::Transaction::DestinationInfo destInfo;
1420                         if (!AuthoriseOSPTransaction(*transaction, destInfo)) {
1421                                 delete transaction;
1422                                 return EndedByOSPRefusal;
1423                         }
1424
1425                         // save the transaction for use by the call
1426                         ospTransaction = transaction;
1427
1428                         // retreive the call information
1429                         gatekeeperRoute = destInfo.destinationAddress;
1430                         newAliasAddresses.Append(new H225_AliasAddress(destInfo.calledNumber));
1431
1432                         // insert the token
1433                         setup.IncludeOptionalField(H225_Setup_UUIE::e_tokens);
1434                         destInfo.InsertToken(setup.m_tokens);
1435                 }
1436         }
1437 #endif
1438
1439         // Update the field e_destinationAddress in the SETUP PDU to reflect the new 
1440         // alias received in the ACF (m_destinationInfo).
1441         if (newAliasAddresses.GetSize() > 0) {
1442                 setup.IncludeOptionalField(H225_Setup_UUIE::e_destinationAddress);
1443                 setup.m_destinationAddress = newAliasAddresses;
1444
1445                 // Update the Q.931 Information Element (if is an E.164 address)
1446                 PString e164 = H323GetAliasAddressE164(newAliasAddresses);
1447                 if (!e164)
1448                         remotePartyNumber = e164;
1449         }
1450
1451         if (addAccessTokenToSetup && !gkAccessTokenOID && !gkAccessTokenData.IsEmpty()) {
1452                 PString oid1, oid2;
1453                 PINDEX comma = gkAccessTokenOID.Find(',');
1454                 if (comma == P_MAX_INDEX)
1455                         oid1 = oid2 = gkAccessTokenOID;
1456                 else {
1457                         oid1 = gkAccessTokenOID.Left(comma);
1458                         oid2 = gkAccessTokenOID.Mid(comma+1);
1459                 }
1460                 setup.IncludeOptionalField(H225_Setup_UUIE::e_tokens);
1461                 PINDEX last = setup.m_tokens.GetSize();
1462                 setup.m_tokens.SetSize(last+1);
1463                 setup.m_tokens[last].m_tokenOID = oid1;
1464                 setup.m_tokens[last].IncludeOptionalField(H235_ClearToken::e_nonStandard);
1465                 setup.m_tokens[last].m_nonStandard.m_nonStandardIdentifier = oid2;
1466                 setup.m_tokens[last].m_nonStandard.m_data = gkAccessTokenData;
1467         }
1468
1469         if (!signallingChannel->SetRemoteAddress(gatekeeperRoute)) {
1470                 PTRACE(1, "H225\tInvalid "
1471                                          << (gatekeeperRoute != address ? "gatekeeper" : "user")
1472                                          << " supplied address: \"" << gatekeeperRoute << '"');
1473                 connectionState = AwaitingTransportConnect;
1474                 return EndedByConnectFail;
1475         }
1476
1477         // Do the transport connect
1478         connectionState = AwaitingTransportConnect;
1479
1480         // Release the mutex as can deadlock trying to clear call during connect.
1481         Unlock();
1482
1483         signallingChannel->SetWriteTimeout(100);
1484
1485         PBoolean connectFailed = !signallingChannel->Connect();
1486
1487         // Lock while checking for shutting down.
1488         if (!Lock())
1489                 return EndedByCallerAbort;
1490
1491         // See if transport connect failed, abort if so.
1492         if (connectFailed) {
1493                 connectionState = NoConnectionActive;
1494                 switch (signallingChannel->GetErrorNumber()) {
1495                         case ENETUNREACH :
1496                                 return EndedByUnreachable;
1497                         case ECONNREFUSED :
1498                                 return EndedByNoEndPoint;
1499                         case ETIMEDOUT :
1500                                 return EndedByHostOffline;
1501                 }
1502                 return EndedByConnectFail;
1503         }
1504
1505         PTRACE(3, "H225\tSending Setup PDU");
1506         connectionState = AwaitingSignalConnect;
1507
1508         // Put in all the signalling addresses for link
1509         setup.IncludeOptionalField(H225_Setup_UUIE::e_sourceCallSignalAddress);
1510         signallingChannel->SetUpTransportPDU(setup.m_sourceCallSignalAddress, TRUE);
1511         if (!setup.HasOptionalField(H225_Setup_UUIE::e_destCallSignalAddress)) {
1512                 setup.IncludeOptionalField(H225_Setup_UUIE::e_destCallSignalAddress);
1513                 signallingChannel->SetUpTransportPDU(setup.m_destCallSignalAddress, FALSE);
1514         }
1515
1516         // If a standard call do Fast Start (if required)
1517         if (setup.m_conferenceGoal.GetTag() == H225_Setup_UUIE_conferenceGoal::e_create) {
1518
1519                 // Get the local capabilities before fast start is handled
1520                 OnSetLocalCapabilities();
1521
1522                 // Ask the application what channels to open
1523                 PTRACE(3, "H225\tCheck for Fast start by local endpoint");
1524                 fastStartChannels.RemoveAll();
1525                 OnSelectLogicalChannels();
1526
1527                 // If application called OpenLogicalChannel, put in the fastStart field
1528                 if (!fastStartChannels.IsEmpty()) {
1529                         PTRACE(3, "H225\tFast start begun by local endpoint");
1530                         for (PINDEX i = 0; i < fastStartChannels.GetSize(); i++)
1531                                 BuildFastStartList(fastStartChannels[i], setup.m_fastStart, H323Channel::IsReceiver);
1532                         if (setup.m_fastStart.GetSize() > 0)
1533                                 setup.IncludeOptionalField(H225_Setup_UUIE::e_fastStart);
1534                 }
1535
1536                 // Search the capability set and see if we have video capability
1537                 for (PINDEX i = 0; i < localCapabilities.GetSize(); i++) {
1538                         switch (localCapabilities[i].GetMainType()) {
1539                         case H323Capability::e_Audio:
1540                         case H323Capability::e_UserInput:
1541                                 break;
1542
1543                         default:        // Is video or other data (eg T.120)
1544                                 setupPDU.GetQ931().SetBearerCapabilities(Q931::TransferUnrestrictedDigital, 6);
1545                                 i = localCapabilities.GetSize(); // Break out of the for loop
1546                                 break;
1547                         }
1548                 }
1549         }
1550
1551         if (!OnSendSignalSetup(setupPDU))
1552                 return EndedByNoAccept;
1553
1554         // Do this again (was done when PDU was constructed) in case
1555         // OnSendSignalSetup() changed something.
1556 //      setupPDU.SetQ931Fields(*this, TRUE);
1557         setupPDU.GetQ931().GetCalledPartyNumber(remotePartyNumber);
1558
1559         fastStartState = FastStartDisabled;
1560         PBoolean set_lastPDUWasH245inSETUP = FALSE;
1561
1562         if (h245Tunneling && doH245inSETUP) {
1563                 h245TunnelTxPDU = &setupPDU;
1564
1565                 // Try and start the master/slave and capability exchange through the tunnel
1566                 // Note: this used to be disallowed but is now allowed as of H323v4
1567                 PBoolean ok = StartControlNegotiations();
1568
1569                 h245TunnelTxPDU = NULL;
1570
1571                 if (!ok)
1572                         return EndedByTransportFail;
1573
1574                 if (setup.m_fastStart.GetSize() > 0) {
1575                         // Now if fast start as well need to put this in setup specific field
1576                         // and not the generic H.245 tunneling field
1577                         setup.IncludeOptionalField(H225_Setup_UUIE::e_parallelH245Control);
1578                         setup.m_parallelH245Control = setupPDU.m_h323_uu_pdu.m_h245Control;
1579                         setupPDU.m_h323_uu_pdu.RemoveOptionalField(H225_H323_UU_PDU::e_h245Control);
1580                         set_lastPDUWasH245inSETUP = TRUE;
1581                 }
1582         }
1583
1584         // Send the initial PDU
1585         setupTime = PTime();
1586         if (!WriteSignalPDU(setupPDU))
1587                 return EndedByTransportFail;
1588
1589         // WriteSignalPDU always resets lastPDUWasH245inSETUP.
1590         // So set it here if required
1591         if (set_lastPDUWasH245inSETUP)
1592                 lastPDUWasH245inSETUP = TRUE;
1593
1594         // Set timeout for remote party to answer the call
1595         signallingChannel->SetReadTimeout(endpoint.GetSignallingChannelCallTimeout());
1596
1597         return NumCallEndReasons;
1598 }
1599
1600
1601 PBoolean MyH323Connection::OnSendReleaseComplete(H323SignalPDU & releaseCompletePDU)
1602 {
1603         if (h323debug) {
1604                 cout << "\t-- Sending RELEASE COMPLETE" << endl;
1605         }
1606         if (cause > 0)
1607                 releaseCompletePDU.GetQ931().SetCause((Q931::CauseValues)cause);
1608
1609 #ifdef TUNNELLING
1610         EmbedTunneledInfo(releaseCompletePDU);
1611 #endif
1612
1613         return H323Connection::OnSendReleaseComplete(releaseCompletePDU);
1614 }
1615
1616 PBoolean MyH323Connection::OnReceivedFacility(const H323SignalPDU & pdu)
1617 {
1618         if (h323debug) {
1619                 cout << "\t-- Received Facility message... " << endl;
1620         }
1621         return H323Connection::OnReceivedFacility(pdu);
1622 }
1623
1624 void MyH323Connection::OnReceivedReleaseComplete(const H323SignalPDU & pdu)
1625 {
1626         if (h323debug) {
1627                 cout << "\t-- Received RELEASE COMPLETE message..." << endl;
1628         }
1629         if (on_hangup)
1630                 on_hangup(GetCallReference(), (const char *)GetCallToken(), pdu.GetQ931().GetCause());
1631         return H323Connection::OnReceivedReleaseComplete(pdu);
1632 }
1633
1634 PBoolean MyH323Connection::OnClosingLogicalChannel(H323Channel & channel)
1635 {
1636         if (h323debug) {
1637                 cout << "\t-- Closing logical channel..." << endl;
1638         }
1639         return H323Connection::OnClosingLogicalChannel(channel);
1640 }
1641
1642 void MyH323Connection::SendUserInputTone(char tone, unsigned duration, unsigned logicalChannel, unsigned rtpTimestamp)
1643 {
1644         SendUserInputModes mode = GetRealSendUserInputMode();
1645 //      That is recursive call... Why?
1646 //      on_receive_digit(GetCallReference(), tone, (const char *)GetCallToken());
1647         if ((tone != ' ') || (mode == SendUserInputAsTone) || (mode == SendUserInputAsInlineRFC2833)) {
1648                 if (h323debug) {
1649                         cout << "\t-- Sending user input tone (" << tone << ") to remote" << endl;
1650                 }
1651                 H323Connection::SendUserInputTone(tone, duration);
1652         }
1653 }
1654
1655 void MyH323Connection::OnUserInputTone(char tone, unsigned duration, unsigned logicalChannel, unsigned rtpTimestamp)
1656 {
1657         /* Why we should check this? */
1658         if ((dtmfMode & (H323_DTMF_CISCO | H323_DTMF_RFC2833 | H323_DTMF_SIGNAL)) != 0) {
1659                 if (h323debug) {
1660                         cout << "\t-- Received user input tone (" << tone << ") from remote" << endl;
1661                 }
1662                 on_receive_digit(GetCallReference(), tone, (const char *)GetCallToken(), duration);
1663         }
1664 }
1665
1666 void MyH323Connection::OnUserInputString(const PString &value)
1667 {
1668         if (h323debug) {
1669                 cout << "\t-- Received user input string (" << value << ") from remote." << endl;
1670         }
1671         on_receive_digit(GetCallReference(), value[0], (const char *)GetCallToken(), 0);
1672 }
1673
1674 void MyH323Connection::OnSendCapabilitySet(H245_TerminalCapabilitySet & pdu)
1675 {
1676         PINDEX i;
1677
1678         H323Connection::OnSendCapabilitySet(pdu);
1679
1680         H245_ArrayOf_CapabilityTableEntry & tables = pdu.m_capabilityTable;
1681         for(i = 0; i < tables.GetSize(); i++)
1682         {
1683                 H245_CapabilityTableEntry & entry = tables[i];
1684                 if (entry.HasOptionalField(H245_CapabilityTableEntry::e_capability)) {
1685                         H245_Capability & cap = entry.m_capability;
1686                         if (cap.GetTag() == H245_Capability::e_receiveRTPAudioTelephonyEventCapability) {
1687                                 H245_AudioTelephonyEventCapability & atec = cap;
1688                                 atec.m_dynamicRTPPayloadType = dtmfCodec[0];
1689 //                              on_set_rfc2833_payload(GetCallReference(), (const char *)GetCallToken(), (int)dtmfCodec[0]);
1690 #ifdef PTRACING
1691                                 if (h323debug) {
1692                                         cout << "\t-- Receiving RFC2833 on payload " <<
1693                                                 atec.m_dynamicRTPPayloadType << endl;
1694                                 }
1695 #endif
1696                         }
1697                 }
1698         }
1699 }
1700
1701 void MyH323Connection::OnSetLocalCapabilities()
1702 {
1703         if (on_setcapabilities)
1704                 on_setcapabilities(GetCallReference(), (const char *)callToken);
1705 }
1706
1707 PBoolean MyH323Connection::OnReceivedCapabilitySet(const H323Capabilities & remoteCaps,
1708                                                         const H245_MultiplexCapability * muxCap,
1709                                                         H245_TerminalCapabilitySetReject & reject)
1710 {
1711         struct __codec__ {
1712                 unsigned int asterisk_codec;
1713                 unsigned int h245_cap;
1714                 const char *oid;
1715                 const char *formatName;
1716         };
1717         static const struct __codec__ codecs[] = {
1718                 { AST_FORMAT_G723_1, H245_AudioCapability::e_g7231 },
1719                 { AST_FORMAT_GSM, H245_AudioCapability::e_gsmFullRate },
1720                 { AST_FORMAT_ULAW, H245_AudioCapability::e_g711Ulaw64k },
1721                 { AST_FORMAT_ALAW, H245_AudioCapability::e_g711Alaw64k },
1722                 { AST_FORMAT_G729A, H245_AudioCapability::e_g729AnnexA },
1723                 { AST_FORMAT_G729A, H245_AudioCapability::e_g729 },
1724                 { AST_FORMAT_G726_AAL2, H245_AudioCapability::e_nonStandard, NULL, CISCO_G726r32 },
1725 #ifdef AST_FORMAT_MODEM
1726                 { AST_FORMAT_MODEM, H245_DataApplicationCapability_application::e_t38fax },
1727 #endif
1728                 { 0 }
1729         };
1730
1731 #if 0
1732         static const struct __codec__ vcodecs[] = {
1733 #ifdef HAVE_H261
1734                 { AST_FORMAT_H261, H245_VideoCapability::e_h261VideoCapability },
1735 #endif
1736 #ifdef HAVE_H263
1737                 { AST_FORMAT_H263, H245_VideoCapability::e_h263VideoCapability },
1738 #endif
1739 #ifdef HAVE_H264
1740                 { AST_FORMAT_H264, H245_VideoCapability::e_genericVideoCapability, "0.0.8.241.0.0.1" },
1741 #endif
1742                 { 0 }
1743         };
1744 #endif
1745         struct ast_codec_pref prefs;
1746         RTP_DataFrame::PayloadTypes pt;
1747
1748         if (!H323Connection::OnReceivedCapabilitySet(remoteCaps, muxCap, reject)) {
1749                 return FALSE;
1750         }
1751
1752         memset(&prefs, 0, sizeof(prefs));
1753         int peer_capabilities = 0;
1754         for (int i = 0; i < remoteCapabilities.GetSize(); ++i) {
1755                 unsigned int subType = remoteCapabilities[i].GetSubType();
1756                 if (h323debug) {
1757                         cout << "Peer capability is " << remoteCapabilities[i] << endl;
1758                 }
1759                 switch(remoteCapabilities[i].GetMainType()) {
1760                 case H323Capability::e_Audio:
1761                         for (int x = 0; codecs[x].asterisk_codec > 0; ++x) {
1762                                 if ((subType == codecs[x].h245_cap) && (!codecs[x].formatName || (!strcmp(codecs[x].formatName, (const char *)remoteCapabilities[i].GetFormatName())))) {
1763                                         int ast_codec = codecs[x].asterisk_codec;
1764                                         int ms = 0;
1765                                         if (!(peer_capabilities & ast_codec)) {
1766                                                 struct ast_format_list format;
1767                                                 ast_codec_pref_append(&prefs, ast_codec);
1768                                                 format = ast_codec_pref_getsize(&prefs, ast_codec);
1769                                                 if ((ast_codec == AST_FORMAT_ALAW) || (ast_codec == AST_FORMAT_ULAW)) {
1770                                                         ms = remoteCapabilities[i].GetTxFramesInPacket();
1771                                                         if (ms > 60)
1772                                                                 ms = format.cur_ms;
1773                                                 } else
1774                                                         ms = remoteCapabilities[i].GetTxFramesInPacket() * format.inc_ms;
1775                                                 ast_codec_pref_setsize(&prefs, ast_codec, ms);
1776                                         }
1777                                         if (h323debug) {
1778                                                 cout << "Found peer capability " << remoteCapabilities[i] << ", Asterisk code is " << ast_codec << ", frame size (in ms) is " << ms << endl;
1779                                         }
1780                                         peer_capabilities |= ast_codec;
1781                                 }
1782                         }
1783                         break;
1784                 case H323Capability::e_Data:
1785                         if (!strcmp((const char *)remoteCapabilities[i].GetFormatName(), CISCO_DTMF_RELAY)) {
1786                                 pt = remoteCapabilities[i].GetPayloadType();
1787                                 if ((dtmfMode & H323_DTMF_CISCO) != 0) {
1788                                         on_set_rfc2833_payload(GetCallReference(), (const char *)GetCallToken(), (int)pt, 1);
1789 //                                      if (sendUserInputMode == SendUserInputAsTone)
1790 //                                              sendUserInputMode = SendUserInputAsInlineRFC2833;
1791                                 }
1792 #ifdef PTRACING
1793                                 if (h323debug) {
1794                                         cout << "\t-- Outbound Cisco RTP DTMF on payload " << pt << endl;
1795                                 }
1796 #endif
1797                         }
1798                         break;
1799                 case H323Capability::e_UserInput:
1800                         if (!strcmp((const char *)remoteCapabilities[i].GetFormatName(), H323_UserInputCapability::SubTypeNames[H323_UserInputCapability::SignalToneRFC2833])) {
1801                                 pt = remoteCapabilities[i].GetPayloadType();
1802                                 if ((dtmfMode & H323_DTMF_RFC2833) != 0) {
1803                                         on_set_rfc2833_payload(GetCallReference(), (const char *)GetCallToken(), (int)pt, 0);
1804 //                                      if (sendUserInputMode == SendUserInputAsTone)
1805 //                                              sendUserInputMode = SendUserInputAsInlineRFC2833;
1806                                 }
1807 #ifdef PTRACING
1808                                 if (h323debug) {
1809                                         cout << "\t-- Outbound RFC2833 on payload " << pt << endl;
1810                                 }
1811 #endif
1812                         }
1813                         break;
1814 #if 0
1815                 case H323Capability::e_Video:
1816                         for (int x = 0; vcodecs[x].asterisk_codec > 0; ++x) {
1817                                 if (subType == vcodecs[x].h245_cap) {
1818                                         H245_CapabilityIdentifier *cap = NULL;
1819                                         H245_GenericCapability y;
1820                                         if (vcodecs[x].oid) {
1821                                                 cap = new H245_CapabilityIdentifier(H245_CapabilityIdentifier::e_standard);
1822                                                 PASN_ObjectId &object_id = *cap;
1823                                                 object_id = vcodecs[x].oid;
1824                                                 y.m_capabilityIdentifier = *cap;
1825                                         }
1826                                         if ((subType != H245_VideoCapability::e_genericVideoCapability) ||
1827                                                         (vcodecs[x].oid && ((const H323GenericVideoCapability &)remoteCapabilities[i]).IsGenericMatch((const H245_GenericCapability)y))) {
1828                                                 if (h323debug) {
1829                                                         cout << "Found peer video capability " << remoteCapabilities[i] << ", Asterisk code is " << vcodecs[x].asterisk_codec << endl;
1830                                                 }
1831                                                 peer_capabilities |= vcodecs[x].asterisk_codec;
1832                                         }
1833                                         if (cap)
1834                                                 delete(cap);
1835                                 }
1836                         }
1837                         break;
1838 #endif
1839                 default:
1840                         break;
1841                 }
1842         }
1843         if (h323debug) {
1844                 char caps_str[1024], caps2_str[1024];
1845                 ast_codec_pref_string(&prefs, caps2_str, sizeof(caps2_str));
1846                 cout << "Peer capabilities = " << ast_getformatname_multiple(caps_str, sizeof(caps_str), peer_capabilities)
1847                                 << ", ordered list is " << caps2_str << endl;
1848         }
1849 #if 0
1850         redir_capabilities &= peer_capabilities;
1851 #endif
1852         if (on_setpeercapabilities)
1853                 on_setpeercapabilities(GetCallReference(), (const char *)callToken, peer_capabilities, &prefs);
1854
1855         return TRUE;
1856 }
1857
1858 H323Channel * MyH323Connection::CreateRealTimeLogicalChannel(const H323Capability & capability,
1859                                                                         H323Channel::Directions dir,
1860                                                                         unsigned sessionID,
1861                                                                         const H245_H2250LogicalChannelParameters * /*param*/,
1862                                                                         RTP_QOS * /*param*/ )
1863 {
1864         /* Do not open tx channel when transmitter has been paused by empty TCS */
1865         if ((dir == H323Channel::IsTransmitter) && transmitterSidePaused)
1866                 return NULL;
1867
1868         return new MyH323_ExternalRTPChannel(*this, capability, dir, sessionID);
1869 }
1870
1871 /** This callback function is invoked once upon creation of each
1872   * channel for an H323 session
1873   */
1874 PBoolean MyH323Connection::OnStartLogicalChannel(H323Channel & channel)
1875 {
1876         /* Increase the count of channels we have open */
1877         channelsOpen++;
1878
1879         if (h323debug) {
1880                 cout << "\t-- Started logical channel: "
1881                                 << ((channel.GetDirection() == H323Channel::IsTransmitter) ? "sending " : ((channel.GetDirection() == H323Channel::IsReceiver) ? "receiving " : " "))
1882                                 << (const char *)(channel.GetCapability()).GetFormatName() << endl;
1883                 cout << "\t\t-- channelsOpen = " << channelsOpen << endl;
1884         }
1885         return connectionState != ShuttingDownConnection;
1886 }
1887
1888 void MyH323Connection::SetCapabilities(int caps, int dtmf_mode, void *_prefs, int pref_codec)
1889 {
1890         PINDEX lastcap = -1; /* last common capability index */
1891         int alreadysent = 0;
1892         int codec;
1893         int x, y;
1894         char caps_str[1024];
1895         struct ast_codec_pref *prefs = (struct ast_codec_pref *)_prefs;
1896         struct ast_format_list format;
1897         int frames_per_packet;
1898         int max_frames_per_packet;
1899         H323Capability *cap;
1900
1901         localCapabilities.RemoveAll();
1902
1903         if (h323debug) {
1904                 cout << "Setting capabilities to " << ast_getformatname_multiple(caps_str, sizeof(caps_str), caps) << endl;
1905                 ast_codec_pref_string(prefs, caps_str, sizeof(caps_str));
1906                 cout << "Capabilities in preference order is " << caps_str << endl;
1907         }
1908         /* Add audio codecs in preference order first, then
1909            audio codecs without preference as allowed by mask */
1910         for (y = 0, x = -1; x < 32 + 32; ++x) {
1911                 if (x < 0)
1912                         codec = pref_codec;
1913                 else if (y || (!(codec = ast_codec_pref_index(prefs, x)))) {
1914                         if (!y)
1915                                 y = 1;
1916                         else
1917                                 y <<= 1;
1918                         codec = y;
1919                 }
1920                 if (!(caps & codec) || (alreadysent & codec) || !(codec & AST_FORMAT_AUDIO_MASK))
1921                         continue;
1922                 alreadysent |= codec;
1923                 format = ast_codec_pref_getsize(prefs, codec);
1924                 frames_per_packet = (format.inc_ms ? format.cur_ms / format.inc_ms : format.cur_ms);
1925                 max_frames_per_packet = (format.inc_ms ? format.max_ms / format.inc_ms : 0);
1926                 switch(codec) {
1927 #if 0
1928                 case AST_FORMAT_SPEEX:
1929                         /* Not real sure if Asterisk acutally supports all
1930                            of the various different bit rates so add them
1931                            all and figure it out later*/
1932
1933                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow2AudioCapability());
1934                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow3AudioCapability());
1935                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow4AudioCapability());
1936                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow5AudioCapability());
1937                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow6AudioCapability());
1938                         break;
1939 #endif
1940                 case AST_FORMAT_G729A:
1941                         AST_G729ACapability *g729aCap;
1942                         AST_G729Capability *g729Cap;
1943                         lastcap = localCapabilities.SetCapability(0, 0, g729aCap = new AST_G729ACapability(frames_per_packet));
1944                         lastcap = localCapabilities.SetCapability(0, 0, g729Cap = new AST_G729Capability(frames_per_packet));
1945                         if (max_frames_per_packet) {
1946                                 g729aCap->SetTxFramesInPacket(max_frames_per_packet);
1947                                 g729Cap->SetTxFramesInPacket(max_frames_per_packet);
1948                         }
1949                         break;
1950                 case AST_FORMAT_G723_1:
1951                         AST_G7231Capability *g7231Cap;
1952                         lastcap = localCapabilities.SetCapability(0, 0, g7231Cap = new AST_G7231Capability(frames_per_packet, TRUE));
1953                         if (max_frames_per_packet)
1954                                 g7231Cap->SetTxFramesInPacket(max_frames_per_packet);
1955                         lastcap = localCapabilities.SetCapability(0, 0, g7231Cap = new AST_G7231Capability(frames_per_packet, FALSE));
1956                         if (max_frames_per_packet)
1957                                 g7231Cap->SetTxFramesInPacket(max_frames_per_packet);
1958                         break;
1959                 case AST_FORMAT_GSM:
1960                         AST_GSM0610Capability *gsmCap;
1961                         lastcap = localCapabilities.SetCapability(0, 0, gsmCap = new AST_GSM0610Capability(frames_per_packet));
1962                         if (max_frames_per_packet)
1963                                 gsmCap->SetTxFramesInPacket(max_frames_per_packet);
1964                         break;
1965                 case AST_FORMAT_ULAW:
1966                         AST_G711Capability *g711uCap;
1967                         lastcap = localCapabilities.SetCapability(0, 0, g711uCap = new AST_G711Capability(format.cur_ms, H323_G711Capability::muLaw));
1968                         if (format.max_ms)
1969                                 g711uCap->SetTxFramesInPacket(format.max_ms);
1970                         break;
1971                 case AST_FORMAT_ALAW:
1972                         AST_G711Capability *g711aCap;
1973                         lastcap = localCapabilities.SetCapability(0, 0, g711aCap = new AST_G711Capability(format.cur_ms, H323_G711Capability::ALaw));
1974                         if (format.max_ms)
1975                                 g711aCap->SetTxFramesInPacket(format.max_ms);
1976                         break;
1977                 case AST_FORMAT_G726_AAL2:
1978                         AST_CiscoG726Capability *g726Cap;
1979                         lastcap = localCapabilities.SetCapability(0, 0, g726Cap = new AST_CiscoG726Capability(frames_per_packet));
1980                         if (max_frames_per_packet)
1981                                 g726Cap->SetTxFramesInPacket(max_frames_per_packet);
1982                         break;
1983                 default:
1984                         alreadysent &= ~codec;
1985                         break;
1986                 }
1987         }
1988
1989         cap = new H323_UserInputCapability(H323_UserInputCapability::HookFlashH245);
1990         if (cap && cap->IsUsable(*this)) {
1991                 lastcap++;
1992                 lastcap = localCapabilities.SetCapability(0, lastcap, cap);
1993         } else if (cap)
1994                 delete cap;                             /* Capability is not usable */
1995
1996         dtmfMode = dtmf_mode;
1997         if (h323debug) {
1998                 cout << "DTMF mode is " << (int)dtmfMode << endl;
1999         }
2000         if (dtmfMode) {
2001                 lastcap++;
2002                 if (dtmfMode == H323_DTMF_INBAND) {
2003                         cap = new H323_UserInputCapability(H323_UserInputCapability::BasicString);
2004                         if (cap && cap->IsUsable(*this)) {
2005                                 lastcap = localCapabilities.SetCapability(0, lastcap, cap);
2006                         } else if (cap)
2007                                 delete cap;             /* Capability is not usable */
2008                         sendUserInputMode = SendUserInputAsString;
2009                 } else {
2010                         if ((dtmfMode & H323_DTMF_RFC2833) != 0) {
2011                                 cap = new H323_UserInputCapability(H323_UserInputCapability::SignalToneRFC2833);
2012                                 if (cap && cap->IsUsable(*this))
2013                                         lastcap = localCapabilities.SetCapability(0, lastcap, cap);
2014                                 else {
2015                                         dtmfMode |= H323_DTMF_SIGNAL;
2016                                         if (cap)
2017                                                 delete cap;     /* Capability is not usable */
2018                                 }
2019                         }
2020                         if ((dtmfMode & H323_DTMF_CISCO) != 0) {
2021                                 /* Try Cisco's RTP DTMF relay too, but prefer RFC2833 or h245-signal */
2022                                 cap = new AST_CiscoDtmfCapability();
2023                                 if (cap && cap->IsUsable(*this)) {
2024                                         lastcap = localCapabilities.SetCapability(0, lastcap, cap);
2025                                         /* We cannot send Cisco RTP DTMFs, use h245-signal instead */
2026                                         dtmfMode |= H323_DTMF_SIGNAL;
2027                                 } else {
2028                                         dtmfMode |= H323_DTMF_SIGNAL;
2029                                         if (cap)
2030                                                 delete cap;     /* Capability is not usable */
2031                                 }
2032                         }
2033                         if ((dtmfMode & H323_DTMF_SIGNAL) != 0) {
2034                                 /* Cisco usually sends DTMF correctly only through h245-alphanumeric or h245-signal */
2035                                 cap = new H323_UserInputCapability(H323_UserInputCapability::SignalToneH245);
2036                                 if (cap && cap->IsUsable(*this))
2037                                         lastcap = localCapabilities.SetCapability(0, lastcap, cap);
2038                                 else if (cap)
2039                                         delete cap;     /* Capability is not usable */
2040                         }
2041                         sendUserInputMode = SendUserInputAsTone;        /* RFC2833 transmission handled at Asterisk level */
2042                 }
2043         }
2044
2045         if (h323debug) {
2046                 cout << "Allowed Codecs for " << GetCallToken() << " (" << GetSignallingChannel()->GetLocalAddress() << "):\n\t" << setprecision(2) << localCapabilities << endl;
2047         }
2048 }
2049
2050 PBoolean MyH323Connection::StartControlChannel(const H225_TransportAddress & h245Address)
2051 {
2052         // Check that it is an IP address, all we support at the moment
2053         if (h245Address.GetTag() != H225_TransportAddress::e_ipAddress
2054 #if P_HAS_IPV6
2055                 && h245Address.GetTag() != H225_TransportAddress::e_ip6Address
2056 #endif
2057         ) {
2058                 PTRACE(1, "H225\tConnect of H245 failed: Unsupported transport");
2059                 return FALSE;
2060         }
2061
2062         // Already have the H245 channel up.
2063         if (controlChannel != NULL)
2064                 return TRUE;
2065
2066         PIPSocket::Address addr;
2067         WORD port;
2068         GetSignallingChannel()->GetLocalAddress().GetIpAndPort(addr, port);
2069         if (addr) {
2070                 if (h323debug)
2071                         cout << "Using " << addr << " for outbound H.245 transport" << endl;
2072                 controlChannel = new MyH323TransportTCP(endpoint, addr);
2073         } else
2074                 controlChannel = new MyH323TransportTCP(endpoint);
2075         if (!controlChannel->SetRemoteAddress(h245Address)) {
2076                 PTRACE(1, "H225\tCould not extract H245 address");
2077                 delete controlChannel;
2078                 controlChannel = NULL;
2079                 return FALSE;
2080         }
2081         if (!controlChannel->Connect()) {
2082                 PTRACE(1, "H225\tConnect of H245 failed: " << controlChannel->GetErrorText());
2083                 delete controlChannel;
2084                 controlChannel = NULL;
2085                 return FALSE;
2086         }
2087
2088         controlChannel->StartControlChannel(*this);
2089         return TRUE;
2090 }
2091
2092 #ifdef H323_H450
2093 void MyH323Connection::OnReceivedLocalCallHold(int linkedId)
2094 {
2095         if (on_hold)
2096                 on_hold(GetCallReference(), (const char *)GetCallToken(), 1);
2097 }
2098
2099 void MyH323Connection::OnReceivedLocalCallRetrieve(int linkedId)
2100 {
2101         if (on_hold)
2102                 on_hold(GetCallReference(), (const char *)GetCallToken(), 0);
2103 }
2104 #endif
2105
2106 void MyH323Connection::MyHoldCall(PBoolean isHold)
2107 {
2108         if (((holdHandling & H323_HOLD_NOTIFY) != 0) || ((holdHandling & H323_HOLD_Q931ONLY) != 0)) {
2109                 PBYTEArray x ((const BYTE *)(isHold ? "\xF9" : "\xFA"), 1);
2110                 H323SignalPDU signal;
2111                 signal.BuildNotify(*this);
2112                 signal.GetQ931().SetIE((Q931::InformationElementCodes)39 /* Q931::NotifyIE */, x);
2113                 if (h323debug)
2114                         cout << "Sending " << (isHold ? "HOLD" : "RETRIEVE") << " notification: " << signal << endl;
2115                 if ((holdHandling & H323_HOLD_Q931ONLY) != 0) {
2116                         PBYTEArray rawData;
2117                         signal.GetQ931().RemoveIE(Q931::UserUserIE);
2118                         signal.GetQ931().Encode(rawData);
2119                         signallingChannel->WritePDU(rawData);
2120                 } else
2121                         WriteSignalPDU(signal);
2122         }
2123 #ifdef H323_H450
2124         if ((holdHandling & H323_HOLD_H450) != 0) {
2125                 if (isHold)
2126                         h4504handler->HoldCall(TRUE);
2127                 else if (IsLocalHold())
2128                         h4504handler->RetrieveCall();
2129         }
2130 #endif
2131 }
2132
2133
2134 /* MyH323_ExternalRTPChannel */
2135 MyH323_ExternalRTPChannel::MyH323_ExternalRTPChannel(MyH323Connection & connection,
2136                                                         const H323Capability & capability,
2137                                                         Directions direction,
2138                                                         unsigned id)
2139         : H323_ExternalRTPChannel::H323_ExternalRTPChannel(connection, capability, direction, id)
2140 {
2141         struct rtp_info *info;
2142
2143         /* Determine the Local (A side) IP Address and port */
2144         info = on_external_rtp_create(connection.GetCallReference(), (const char *)connection.GetCallToken());
2145         if (!info) {
2146                 cout << "\tERROR: on_external_rtp_create failure" << endl;
2147                 return;
2148         } else {
2149                 localIpAddr = info->addr;
2150                 localPort = info->port;
2151                 /* tell the H.323 stack */
2152                 SetExternalAddress(H323TransportAddress(localIpAddr, localPort), H323TransportAddress(localIpAddr, localPort + 1));
2153                 /* clean up allocated memory */
2154                 ast_free(info);
2155         }
2156
2157         /* Get the payload code */
2158         OpalMediaFormat format(capability.GetFormatName(), FALSE);
2159         payloadCode = format.GetPayloadType();
2160 }
2161
2162 MyH323_ExternalRTPChannel::~MyH323_ExternalRTPChannel()
2163 {
2164         if (h323debug) {
2165                 cout << "\tExternalRTPChannel Destroyed" << endl;
2166         }
2167 }
2168
2169 PBoolean MyH323_ExternalRTPChannel::Start(void)
2170 {
2171         /* Call ancestor first */
2172         if (!H323_ExternalRTPChannel::Start()) {
2173                 return FALSE;
2174         }
2175
2176         if (h323debug) {
2177                 cout << "\t\tExternal RTP Session Starting" << endl;
2178                 cout << "\t\tRTP channel id " << sessionID << " parameters:" << endl;
2179         }
2180
2181         /* Collect the remote information */
2182         H323_ExternalRTPChannel::GetRemoteAddress(remoteIpAddr, remotePort);
2183
2184         if (h323debug) {
2185                 cout << "\t\t-- remoteIpAddress: " << remoteIpAddr << endl;
2186                 cout << "\t\t-- remotePort: " << remotePort << endl;
2187                 cout << "\t\t-- ExternalIpAddress: " << localIpAddr << endl;
2188                 cout << "\t\t-- ExternalPort: " << localPort << endl;
2189         }
2190         /* Notify Asterisk of remote RTP information */
2191         on_start_rtp_channel(connection.GetCallReference(), (const char *)remoteIpAddr.AsString(), remotePort,
2192                 (const char *)connection.GetCallToken(), (int)payloadCode);
2193         return TRUE;
2194 }
2195
2196 PBoolean MyH323_ExternalRTPChannel::OnReceivedAckPDU(const H245_H2250LogicalChannelAckParameters & param)
2197 {
2198         if (h323debug) {
2199                 cout << "       MyH323_ExternalRTPChannel::OnReceivedAckPDU" << endl;
2200         }
2201
2202         if (H323_ExternalRTPChannel::OnReceivedAckPDU(param)) {
2203                 GetRemoteAddress(remoteIpAddr, remotePort);
2204                 if (h323debug) {
2205                         cout << "               -- remoteIpAddress: " << remoteIpAddr << endl;
2206                         cout << "               -- remotePort: " << remotePort << endl;
2207                 }
2208                 on_start_rtp_channel(connection.GetCallReference(), (const char *)remoteIpAddr.AsString(),
2209                                 remotePort, (const char *)connection.GetCallToken(), (int)payloadCode);
2210                 return TRUE;
2211         }
2212         return FALSE;
2213 }
2214
2215 #ifdef H323_H450
2216 MyH4504Handler::MyH4504Handler(MyH323Connection &_conn, H450xDispatcher &_disp)
2217         :H4504Handler(_conn, _disp)
2218 {
2219         conn = &_conn;
2220 }
2221
2222 void MyH4504Handler::OnReceivedLocalCallHold(int linkedId)
2223 {
2224         if (conn) {
2225                 conn->Lock();
2226                 conn->OnReceivedLocalCallHold(linkedId);
2227                 conn->Unlock();
2228         }
2229 }
2230
2231 void MyH4504Handler::OnReceivedLocalCallRetrieve(int linkedId)
2232 {
2233         if (conn) {
2234                 conn->Lock();
2235                 conn->OnReceivedLocalCallRetrieve(linkedId);
2236                 conn->Unlock();
2237         }
2238 }
2239 #endif
2240
2241
2242 /** IMPLEMENTATION OF C FUNCTIONS */
2243
2244 /**
2245  * The extern "C" directive takes care for
2246  * the ANSI-C representation of linkable symbols
2247  */
2248
2249 extern "C" {
2250
2251 int h323_end_point_exist(void)
2252 {
2253         if (!endPoint) {
2254                 return 0;
2255         }
2256         return 1;
2257 }
2258
2259 void h323_end_point_create(void)
2260 {
2261         channelsOpen = 0;
2262         logstream = new PAsteriskLog();
2263         endPoint = new MyH323EndPoint();
2264 }
2265
2266 void h323_gk_urq(void)
2267 {
2268         if (!h323_end_point_exist()) {
2269                 cout << " ERROR: [h323_gk_urq] No Endpoint, this is bad" << endl;
2270                 return;
2271         }
2272         endPoint->RemoveGatekeeper();
2273 }
2274
2275 void h323_debug(int flag, unsigned level)
2276 {
2277         if (flag) {
2278                 PTrace:: SetLevel(level);
2279         } else {
2280                 PTrace:: SetLevel(0);
2281         }
2282 }
2283
2284 /** Installs the callback functions on behalf of the PBX application */
2285 void h323_callback_register(setup_incoming_cb           ifunc,
2286                                                         setup_outbound_cb               sfunc,
2287                                                         on_rtp_cb                               rtpfunc,
2288                                                         start_rtp_cb                    lfunc,
2289                                                         clear_con_cb                    clfunc,
2290                                                         chan_ringing_cb                 rfunc,
2291                                                         con_established_cb              efunc,
2292                                                         receive_digit_cb                dfunc,
2293                                                         answer_call_cb                  acfunc,
2294                                                         progress_cb                             pgfunc,
2295                                                         rfc2833_cb                              dtmffunc,
2296                                                         hangup_cb                               hangupfunc,
2297                                                         setcapabilities_cb              capabilityfunc,
2298                                                         setpeercapabilities_cb  peercapabilityfunc,
2299                                                         onhold_cb                               holdfunc)
2300 {
2301         on_incoming_call = ifunc;
2302         on_outgoing_call = sfunc;
2303         on_external_rtp_create = rtpfunc;
2304         on_start_rtp_channel = lfunc;
2305         on_connection_cleared = clfunc;
2306         on_chan_ringing = rfunc;
2307         on_connection_established = efunc;
2308         on_receive_digit = dfunc;
2309         on_answer_call = acfunc;
2310         on_progress = pgfunc;
2311         on_set_rfc2833_payload = dtmffunc;
2312         on_hangup = hangupfunc;
2313         on_setcapabilities = capabilityfunc;
2314         on_setpeercapabilities = peercapabilityfunc;
2315         on_hold = holdfunc;
2316 }
2317
2318 /**
2319  * Add capability to the capability table of the end point.
2320  */
2321 int h323_set_capabilities(const char *token, int cap, int dtmf_mode, struct ast_codec_pref *prefs, int pref_codec)
2322 {
2323         MyH323Connection *conn;
2324
2325         if (!h323_end_point_exist()) {
2326                 cout << " ERROR: [h323_set_capablities] No Endpoint, this is bad" << endl;
2327                 return 1;
2328         }
2329         if (!token || !*token) {
2330                 cout << " ERROR: [h323_set_capabilities] Invalid call token specified." << endl;
2331                 return 1;
2332         }
2333
2334         PString myToken(token);
2335         conn = (MyH323Connection *)endPoint->FindConnectionWithLock(myToken);
2336         if (!conn) {
2337                 cout << " ERROR: [h323_set_capabilities] Unable to find connection " << token << endl;
2338                 return 1;
2339         }
2340         conn->SetCapabilities((/*conn->bridging ? conn->redir_capabilities :*/ cap), dtmf_mode, prefs, pref_codec);
2341         conn->Unlock();
2342
2343         return 0;
2344 }
2345
2346 /** Start the H.323 listener */
2347 int h323_start_listener(int listenPort, struct sockaddr_in bindaddr)
2348 {
2349
2350         if (!h323_end_point_exist()) {
2351                 cout << "ERROR: [h323_start_listener] No Endpoint, this is bad!" << endl;
2352                 return 1;
2353         }
2354
2355         PIPSocket::Address interfaceAddress(bindaddr.sin_addr);
2356         if (!listenPort) {
2357                 listenPort = 1720;
2358         }
2359         /** H.323 listener */
2360         H323ListenerTCP *tcpListener;
2361         tcpListener = new H323ListenerTCP(*endPoint, interfaceAddress, (WORD)listenPort);
2362         if (!endPoint->StartListener(tcpListener)) {
2363                 cout << "ERROR: Could not open H.323 listener port on " << ((H323ListenerTCP *) tcpListener)->GetListenerPort() << endl;
2364                 delete tcpListener;
2365                 return 1;
2366         }
2367         cout << "  == H.323 listener started" << endl;
2368         return 0;
2369 };
2370
2371 /* Addition of functions just to make the channel driver compile with H323Plus */
2372 #if VERSION(OPENH323_MAJOR, OPENH323_MINOR, OPENH323_BUILD) > VERSION(1,19,4)
2373 /* Alternate RTP port information for Same NAT */
2374 BOOL MyH323_ExternalRTPChannel::OnReceivedAltPDU(const H245_ArrayOf_GenericInformation & alternate )
2375 {
2376         return TRUE;
2377 }
2378
2379 /* Alternate RTP port information for Same NAT */
2380 BOOL MyH323_ExternalRTPChannel::OnSendingAltPDU(H245_ArrayOf_GenericInformation & alternate) const
2381 {
2382         return TRUE;
2383 }
2384
2385 /* Alternate RTP port information for Same NAT */
2386 void MyH323_ExternalRTPChannel::OnSendOpenAckAlt(H245_ArrayOf_GenericInformation & alternate) const
2387 {
2388 }
2389
2390 /* Alternate RTP port information for Same NAT */
2391 BOOL MyH323_ExternalRTPChannel::OnReceivedAckAltPDU(const H245_ArrayOf_GenericInformation & alternate)
2392 {
2393         return TRUE;
2394 }
2395 #endif
2396
2397
2398 int h323_set_alias(struct oh323_alias *alias)
2399 {
2400         char *p;
2401         char *num;
2402         PString h323id(alias->name);
2403         PString e164(alias->e164);
2404         char *prefix;
2405
2406         if (!h323_end_point_exist()) {
2407                 cout << "ERROR: [h323_set_alias] No Endpoint, this is bad!" << endl;
2408                 return 1;
2409         }
2410
2411         cout << "== Adding alias \"" << h323id << "\" to endpoint" << endl;
2412         endPoint->AddAliasName(h323id);
2413         endPoint->RemoveAliasName(PProcess::Current().GetName());
2414
2415         if (!e164.IsEmpty()) {
2416                 cout << "== Adding E.164 \"" << e164 << "\" to endpoint" << endl;
2417                 endPoint->AddAliasName(e164);
2418         }
2419         if (strlen(alias->prefix)) {
2420                 p = prefix = strdup(alias->prefix);
2421                 while((num = strsep(&p, ",")) != (char *)NULL) {
2422                         cout << "== Adding Prefix \"" << num << "\" to endpoint" << endl;
2423                         endPoint->SupportedPrefixes += PString(num);
2424                         endPoint->SetGateway();
2425                 }
2426                 if (prefix)
2427                         ast_free(prefix);
2428         }
2429         return 0;
2430 }
2431
2432 void h323_set_id(char *id)
2433 {
2434         PString h323id(id);
2435
2436         if (h323debug) {
2437                 cout << "  == Using '" << h323id << "' as our H.323ID for this call" << endl;
2438         }
2439         /* EVIL HACK */
2440         endPoint->SetLocalUserName(h323id);
2441 }
2442
2443 void h323_show_tokens(void)
2444 {
2445         cout << "Current call tokens: " << setprecision(2) << endPoint->GetAllConnections() << endl;
2446 }
2447
2448 void h323_show_version(void)
2449 {
2450     cout << "H.323 version: " << OPENH323_MAJOR << "." << OPENH323_MINOR << "." << OPENH323_BUILD << endl;
2451 }
2452
2453 /** Establish Gatekeeper communiations, if so configured,
2454   *     register aliases for the H.323 endpoint to respond to.
2455   */
2456 int h323_set_gk(int gatekeeper_discover, char *gatekeeper, char *secret)
2457 {
2458         PString gkName = PString(gatekeeper);
2459         PString pass = PString(secret);
2460         H323TransportUDP *rasChannel;
2461
2462         if (!h323_end_point_exist()) {
2463                 cout << "ERROR: [h323_set_gk] No Endpoint, this is bad!" << endl;
2464                 return 1;
2465         }
2466
2467         if (!gatekeeper) {
2468                 cout << "Error: Gatekeeper cannot be NULL" << endl;
2469                 return 1;
2470         }
2471         if (strlen(secret)) {
2472                 endPoint->SetGatekeeperPassword(pass);
2473         }
2474         if (gatekeeper_discover) {
2475                 /* discover the gk using multicast */
2476                 if (endPoint->DiscoverGatekeeper(new MyH323TransportUDP(*endPoint))) {
2477                         cout << "== Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
2478                 } else {
2479                         cout << "Warning: Could not find a gatekeeper." << endl;
2480                         return 1;
2481                 }
2482         } else {
2483                 rasChannel = new MyH323TransportUDP(*endPoint);
2484
2485                 if (!rasChannel) {
2486                         cout << "Error: No RAS Channel, this is bad" << endl;
2487                         return 1;
2488                 }
2489                 if (endPoint->SetGatekeeper(gkName, rasChannel)) {
2490                         cout << "== Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
2491                 } else {
2492                         cout << "Error registering with gatekeeper \"" << gkName << "\". " << endl;
2493                         /* XXX Maybe we should fire a new thread to attempt to re-register later and not kill asterisk here? */
2494                         return 1;
2495                 }
2496         }
2497         return 0;
2498 }
2499
2500 /** Send a DTMF tone over the H323Connection with the
2501   * specified token.
2502   */
2503 void h323_send_tone(const char *call_token, char tone)
2504 {
2505         if (!h323_end_point_exist()) {
2506                 cout << "ERROR: [h323_send_tone] No Endpoint, this is bad!" << endl;
2507                 return;
2508         }
2509         PString token = PString(call_token);
2510         endPoint->SendUserTone(token, tone);
2511 }
2512
2513 /** Make a call to the remote endpoint.
2514   */
2515 int h323_make_call(char *dest, call_details_t *cd, call_options_t *call_options)
2516 {
2517         int res;
2518         PString token;
2519         PString host(dest);
2520
2521         if (!h323_end_point_exist()) {
2522                 return 1;
2523         }
2524
2525         res = endPoint->MyMakeCall(host, token, &cd->call_reference, call_options);
2526         memcpy((char *)(cd->call_token), (const unsigned char *)token, token.GetLength());
2527         return res;
2528 };
2529
2530 int h323_clear_call(const char *call_token, int cause)
2531 {
2532         H225_ReleaseCompleteReason dummy;
2533         H323Connection::CallEndReason r = H323Connection::EndedByLocalUser;
2534         MyH323Connection *connection;
2535         const PString currentToken(call_token);
2536
2537         if (!h323_end_point_exist()) {
2538                 return 1;
2539         }
2540
2541         if (cause) {
2542                 r = H323TranslateToCallEndReason((Q931::CauseValues)(cause), dummy);
2543         }
2544
2545         connection = (MyH323Connection *)endPoint->FindConnectionWithLock(currentToken);
2546         if (connection) {
2547                 connection->SetCause(cause);
2548                 connection->SetCallEndReason(r);
2549                 connection->Unlock();
2550         }
2551         endPoint->ClearCall(currentToken, r);
2552         return 0;
2553 };
2554
2555 /* Send Alerting PDU to H.323 caller */
2556 int h323_send_alerting(const char *token)
2557 {
2558         const PString currentToken(token);
2559         H323Connection * connection;
2560
2561         if (h323debug) {
2562                 cout << "\tSending alerting" << endl;
2563         }
2564         connection = endPoint->FindConnectionWithLock(currentToken);
2565         if (!connection) {
2566                 cout << "No connection found for " << token << endl;
2567                 return -1;
2568         }
2569         connection->AnsweringCall(H323Connection::AnswerCallPending);
2570         connection->Unlock();
2571         return 0;
2572 }
2573
2574 /* Send Progress PDU to H.323 caller */
2575 int h323_send_progress(const char *token)
2576 {
2577         const PString currentToken(token);
2578         H323Connection * connection;
2579
2580         connection = endPoint->FindConnectionWithLock(currentToken);
2581         if (!connection) {
2582                 cout << "No connection found for " << token << endl;
2583                 return -1;
2584         }
2585 #if 1
2586         ((MyH323Connection *)connection)->MySendProgress();
2587 #else
2588         connection->AnsweringCall(H323Connection::AnswerCallDeferredWithMedia);
2589 #endif
2590         connection->Unlock();
2591         return 0;
2592 }
2593
2594 /** This function tells the h.323 stack to either
2595     answer or deny an incoming call */
2596 int h323_answering_call(const char *token, int busy)
2597 {
2598         const PString currentToken(token);
2599         H323Connection * connection;
2600
2601         connection = endPoint->FindConnectionWithLock(currentToken);
2602
2603         if (!connection) {
2604                 cout << "No connection found for " << token << endl;
2605                 return -1;
2606         }
2607         if (!busy) {
2608                 if (h323debug) {
2609                         cout << "\tAnswering call " << token << endl;
2610                 }
2611                 connection->AnsweringCall(H323Connection::AnswerCallNow);
2612         } else {
2613                 if (h323debug) {
2614                         cout << "\tdenying call " << token << endl;
2615                 }
2616                 connection->AnsweringCall(H323Connection::AnswerCallDenied);
2617         }
2618         connection->Unlock();
2619         return 0;
2620 }
2621
2622 int h323_soft_hangup(const char *data)
2623 {
2624         PString token(data);
2625         PBoolean result;
2626         cout << "Soft hangup" << endl;
2627         result = endPoint->ClearCall(token);
2628         return result;
2629 }
2630
2631 /* alas, this doesn't work :( */
2632 void h323_native_bridge(const char *token, const char *them, char *capability)
2633 {
2634         H323Channel *channel;
2635         MyH323Connection *connection = (MyH323Connection *)endPoint->FindConnectionWithLock(token);
2636
2637         if (!connection) {
2638                 cout << "ERROR: No connection found, this is bad" << endl;
2639                 return;
2640         }
2641
2642         cout << "Native Bridge:  them [" << them << "]" << endl;
2643
2644         channel = connection->FindChannel(connection->sessionId, TRUE);
2645         connection->bridging = TRUE;
2646         connection->CloseLogicalChannelNumber(channel->GetNumber());
2647
2648         connection->Unlock();
2649         return;
2650
2651 }
2652
2653 int h323_hold_call(const char *token, int is_hold)
2654 {
2655         MyH323Connection *conn = (MyH323Connection *)endPoint->FindConnectionWithLock(token);
2656         if (!conn) {
2657                 cout << "ERROR: No connection found, this is bad" << endl;
2658                 return -1;
2659         }
2660         conn->MyHoldCall((PBoolean)is_hold);
2661         conn->Unlock();
2662         return 0;
2663 }
2664
2665 #undef cout
2666 #undef endl
2667 void h323_end_process(void)
2668 {
2669         if (endPoint) {
2670                 delete endPoint;
2671                 endPoint = NULL;
2672         }
2673         if (logstream) {
2674                 delete logstream;
2675                 logstream = NULL;
2676         }
2677 }
2678
2679 } /* extern "C" */
2680