7 * OpenH323 Channel Driver for ASTERISK PBX.
9 * For The NuFone Network
11 * chan_h323 has been derived from code created by
12 * Michael Manousos and Mark Spencer
14 * This file is part of the chan_h323 driver for Asterisk
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.
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.
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.
31 #include <arpa/inet.h>
53 #include "asterisk/compat.h"
54 #include "asterisk/logger.h"
55 #include "asterisk/channel.h"
56 #include "asterisk/astobj.h"
61 #include "chan_h323.h"
63 #include "cisco-h225.h"
64 #include "caps_h323.h"
66 /* PWlib Required Components */
67 #define MAJOR_VERSION 1
68 #define MINOR_VERSION 0
69 #define BUILD_TYPE ReleaseCode
70 #define BUILD_NUMBER 0
72 /** Counter for the number of connections */
73 static int channelsOpen;
76 * We assume that only one endPoint should exist.
77 * The application cannot run the h323_end_point_create() more than once
78 * FIXME: Singleton this, for safety
80 static MyH323EndPoint *endPoint = NULL;
82 /** PWLib entry point */
83 static MyProcess *localProcess = NULL;
85 static int _timerChangePipe[2];
87 static unsigned traceOptions = PTrace::Timestamp | PTrace::Thread | PTrace::FileAndLine;
89 class PAsteriskLog : public PObject, public iostream {
90 PCLASSINFO(PAsteriskLog, PObject);
93 PAsteriskLog() : iostream(cout.rdbuf()) { init(&buffer); }
94 ~PAsteriskLog() { flush(); }
97 PAsteriskLog(const PAsteriskLog &) : iostream(cout.rdbuf()) { }
98 PAsteriskLog & operator=(const PAsteriskLog &) { return *this; }
100 class Buffer : public streambuf {
102 virtual int overflow(int=EOF);
103 virtual int underflow();
110 static PAsteriskLog *logstream = NULL;
112 int PAsteriskLog::Buffer::overflow(int c)
114 if (pptr() >= epptr()) {
115 int ppos = pptr() - pbase();
116 char *newptr = string.GetPointer(string.GetSize() + 2000);
117 setp(newptr, newptr + string.GetSize() - 1);
127 int PAsteriskLog::Buffer::underflow()
132 int PAsteriskLog::Buffer::sync()
134 char *str = strdup(string);
138 /* Pass each line with different ast_verbose() call */
139 for (s = str; s && *s; s = s1) {
140 s1 = strchr(s, '\n');
147 ast_verbose("%s", s);
153 char *base = string.GetPointer(2000);
154 setp(base, base + string.GetSize() - 1);
158 static ostream &my_endl(ostream &os)
161 PTrace::SetOptions(traceOptions);
162 return PTrace::End(os);
168 (logstream ? (PTrace::ClearOptions((unsigned)-1), PTrace::Begin(0, __FILE__, __LINE__)) : std::cout)
171 /* Special class designed to call cleanup code on module destruction */
172 class MyH323_Shutdown {
174 MyH323_Shutdown() { };
181 MyProcess::MyProcess(): PProcess("The NuFone Networks",
182 "H.323 Channel Driver for Asterisk",
183 MAJOR_VERSION, MINOR_VERSION, BUILD_TYPE, BUILD_NUMBER)
185 /* Call shutdown when module being unload or asterisk has been stopped */
186 static MyH323_Shutdown x;
188 /* Fix missed one in PWLib */
189 PX_firstTimeStart = FALSE;
193 MyProcess::~MyProcess()
195 _timerChangePipe[0] = timerChangePipe[0];
196 _timerChangePipe[1] = timerChangePipe[1];
199 void MyProcess::Main()
201 PTrace::Initialise(PTrace::GetLevel(), NULL, traceOptions);
202 PTrace::SetStream(logstream);
204 cout << " == Creating H.323 Endpoint" << endl;
206 cout << " == ENDPOINT ALREADY CREATED" << endl;
209 endPoint = new MyH323EndPoint();
210 /* Due to a bug in the H.323 recomendation/stack we should request a sane
211 amount of bandwidth from the GK - this function is ignored if not using a GK
212 We are requesting 128 (64k in each direction), which is the worst case codec. */
213 endPoint->SetInitialBandwidth(1280);
216 void PAssertFunc(const char *msg)
218 ast_log(LOG_ERROR, "%s\n", msg);
219 /* XXX: Probably we need to crash here */
225 MyH323EndPoint::MyH323EndPoint()
228 /* Capabilities will be negotiated on per-connection basis */
229 capabilities.RemoveAll();
231 /* Reset call setup timeout to some more reasonable value than 1 minute */
232 signallingChannelCallTimeout = PTimeInterval(0, 0, 10); /* 10 minutes */
235 /** The fullAddress parameter is used directly in the MakeCall method so
236 * the General form for the fullAddress argument is :
237 * [alias@][transport$]host[:port]
238 * default values: alias = the same value as host.
242 int MyH323EndPoint::MyMakeCall(const PString & dest, PString & token, void *_callReference, void *_opts)
245 MyH323Connection * connection;
246 H323Transport *transport = NULL;
247 unsigned int *callReference = (unsigned int *)_callReference;
248 call_options_t *opts = (call_options_t *)_opts;
250 /* Determine whether we are using a gatekeeper or not. */
251 if (GetGatekeeper()) {
254 cout << " -- Making call to " << fullAddress << " using gatekeeper." << endl;
259 cout << " -- Making call to " << fullAddress << " without gatekeeper." << endl;
261 /* Use bindaddr for outgoing calls too if we don't use gatekeeper */
262 if (listeners.GetSize() > 0) {
263 H323TransportAddress taddr = listeners[0].GetTransportAddress();
264 PIPSocket::Address addr;
266 if (taddr.GetIpAndPort(addr, port)) {
267 /* Create own transport for specific addresses only */
270 cout << "Using " << addr << " for outbound call" << endl;
271 transport = new MyH323TransportTCP(*this, addr);
273 cout << "Unable to create transport for outgoing call" << endl;
276 cout << "Unable to get address and port" << endl;
279 if (!(connection = (MyH323Connection *)H323EndPoint::MakeCallLocked(fullAddress, token, opts, transport))) {
281 cout << "Error making call to \"" << fullAddress << '"' << endl;
285 *callReference = connection->GetCallReference();
288 cout << "\t-- " << GetLocalUserName() << " is calling host " << fullAddress << endl;
289 cout << "\t-- Call token is " << (const char *)token << endl;
290 cout << "\t-- Call reference is " << *callReference << endl;
292 cout << "\t-- DTMF Payload is " << connection->dtmfCodec << endl;
295 connection->Unlock();
299 void MyH323EndPoint::SetEndpointTypeInfo( H225_EndpointType & info ) const
301 H323EndPoint::SetEndpointTypeInfo(info);
303 if (terminalType == e_GatewayOnly){
304 info.RemoveOptionalField(H225_EndpointType::e_terminal);
305 info.IncludeOptionalField(H225_EndpointType::e_gateway);
308 info.m_gateway.IncludeOptionalField(H225_GatewayInfo::e_protocol);
309 info.m_gateway.m_protocol.SetSize(1);
310 H225_SupportedProtocols &protocol=info.m_gateway.m_protocol[0];
311 protocol.SetTag(H225_SupportedProtocols::e_voice);
312 PINDEX as=SupportedPrefixes.GetSize();
313 ((H225_VoiceCaps &)protocol).m_supportedPrefixes.SetSize(as);
314 for (PINDEX p=0; p<as; p++) {
315 H323SetAliasAddress(SupportedPrefixes[p], ((H225_VoiceCaps &)protocol).m_supportedPrefixes[p].m_prefix, H225_AliasAddress::e_dialedDigits);
319 void MyH323EndPoint::SetGateway(void)
321 terminalType = e_GatewayOnly;
324 BOOL MyH323EndPoint::ClearCall(const PString & token, H323Connection::CallEndReason reason)
328 cout << "\t-- ClearCall: Request to clear call with token " << token << ", cause " << reason << endl;
330 cout << "\t-- ClearCall: Request to clear call with token " << token << ", cause [" << (int)reason << "]" << endl;
333 return H323EndPoint::ClearCall(token, reason);
336 BOOL MyH323EndPoint::ClearCall(const PString & token)
339 cout << "\t-- ClearCall: Request to clear call with token " << token << endl;
341 return H323EndPoint::ClearCall(token, H323Connection::EndedByLocalUser);
344 void MyH323EndPoint::SendUserTone(const PString &token, char tone)
346 H323Connection *connection = NULL;
348 connection = FindConnectionWithLock(token);
349 if (connection != NULL) {
350 connection->SendUserInputTone(tone, 500);
351 connection->Unlock();
355 void MyH323EndPoint::OnClosedLogicalChannel(H323Connection & connection, const H323Channel & channel)
359 cout << "\t\tchannelsOpen = " << channelsOpen << endl;
361 H323EndPoint::OnClosedLogicalChannel(connection, channel);
364 BOOL MyH323EndPoint::OnConnectionForwarded(H323Connection & connection,
365 const PString & forwardParty,
366 const H323SignalPDU & pdu)
369 cout << "\t-- Call Forwarded to " << forwardParty << endl;
374 BOOL MyH323EndPoint::ForwardConnection(H323Connection & connection,
375 const PString & forwardParty,
376 const H323SignalPDU & pdu)
379 cout << "\t-- Forwarding call to " << forwardParty << endl;
381 return H323EndPoint::ForwardConnection(connection, forwardParty, pdu);
384 void MyH323EndPoint::OnConnectionEstablished(H323Connection & connection, const PString & estCallToken)
387 cout << "\t=-= In OnConnectionEstablished for call " << connection.GetCallReference() << endl;
388 cout << "\t\t-- Connection Established with \"" << connection.GetRemotePartyName() << "\"" << endl;
390 on_connection_established(connection.GetCallReference(), (const char *)connection.GetCallToken());
393 /** OnConnectionCleared callback function is called upon the dropping of an established
396 void MyH323EndPoint::OnConnectionCleared(H323Connection & connection, const PString & clearedCallToken)
398 PString remoteName = connection.GetRemotePartyName();
400 switch (connection.GetCallEndReason()) {
401 case H323Connection::EndedByCallForwarded:
403 cout << "-- " << remoteName << " has forwarded the call" << endl;
406 case H323Connection::EndedByRemoteUser:
408 cout << "-- " << remoteName << " has cleared the call" << endl;
411 case H323Connection::EndedByCallerAbort:
413 cout << "-- " << remoteName << " has stopped calling" << endl;
416 case H323Connection::EndedByRefusal:
418 cout << "-- " << remoteName << " did not accept your call" << endl;
421 case H323Connection::EndedByRemoteBusy:
423 cout << "-- " << remoteName << " was busy" << endl;
426 case H323Connection::EndedByRemoteCongestion:
428 cout << "-- Congested link to " << remoteName << endl;
431 case H323Connection::EndedByNoAnswer:
433 cout << "-- " << remoteName << " did not answer your call" << endl;
436 case H323Connection::EndedByTransportFail:
438 cout << "-- Call with " << remoteName << " ended abnormally" << endl;
441 case H323Connection::EndedByCapabilityExchange:
443 cout << "-- Could not find common codec with " << remoteName << endl;
446 case H323Connection::EndedByNoAccept:
448 cout << "-- Did not accept incoming call from " << remoteName << endl;
451 case H323Connection::EndedByAnswerDenied:
453 cout << "-- Refused incoming call from " << remoteName << endl;
456 case H323Connection::EndedByNoUser:
458 cout << "-- Remote endpoint could not find user: " << remoteName << endl;
461 case H323Connection::EndedByNoBandwidth:
463 cout << "-- Call to " << remoteName << " aborted, insufficient bandwidth." << endl;
466 case H323Connection::EndedByUnreachable:
468 cout << "-- " << remoteName << " could not be reached." << endl;
471 case H323Connection::EndedByHostOffline:
473 cout << "-- " << remoteName << " is not online." << endl;
476 case H323Connection::EndedByNoEndPoint:
478 cout << "-- No phone running for " << remoteName << endl;
481 case H323Connection::EndedByConnectFail:
483 cout << "-- Transport error calling " << remoteName << endl;
489 cout << " -- Call with " << remoteName << " completed (" << connection.GetCallEndReason() << ")" << endl;
491 cout << " -- Call with " << remoteName << " completed ([" << (int)connection.GetCallEndReason() << "])" << endl;
496 if (connection.IsEstablished()) {
498 cout << "\t-- Call duration " << setprecision(0) << setw(5) << (PTime() - connection.GetConnectionStartTime()) << endl;
501 /* Invoke the PBX application registered callback */
502 on_connection_cleared(connection.GetCallReference(), clearedCallToken);
506 H323Connection * MyH323EndPoint::CreateConnection(unsigned callReference, void *userData, H323Transport *transport, H323SignalPDU *setupPDU)
508 unsigned options = 0;
509 call_options_t *opts = (call_options_t *)userData;
510 MyH323Connection *conn;
512 if (opts && opts->fastStart) {
513 options |= H323Connection::FastStartOptionEnable;
515 options |= H323Connection::FastStartOptionDisable;
517 if (opts && opts->h245Tunneling) {
518 options |= H323Connection::H245TunnelingOptionEnable;
520 options |= H323Connection::H245TunnelingOptionDisable;
522 /* Disable until I can figure out the proper way to deal with this */
524 if (opts->silenceSuppression) {
525 options |= H323Connection::SilenceSuppresionOptionEnable;
527 options |= H323Connection::SilenceSUppressionOptionDisable;
530 conn = new MyH323Connection(*this, callReference, options);
533 conn->SetCallOptions(opts, (setupPDU ? TRUE : FALSE));
538 /* MyH323Connection Implementation */
539 MyH323Connection::MyH323Connection(MyH323EndPoint & ep, unsigned callReference,
541 : H323Connection(ep, callReference, options)
544 /* Dispatcher will free out all registered handlers */
546 delete h450dispatcher;
547 h450dispatcher = new H450xDispatcher(*this);
548 h4502handler = new H4502Handler(*this, *h450dispatcher);
549 h4504handler = new MyH4504Handler(*this, *h450dispatcher);
550 h4506handler = new H4506Handler(*this, *h450dispatcher);
551 h45011handler = new H45011Handler(*this, *h450dispatcher);
556 holdHandling = progressSetup = progressAlert = 0;
558 dtmfCodec[0] = dtmfCodec[1] = (RTP_DataFrame::PayloadTypes)0;
559 redirect_reason = -1;
560 transfer_capability = -1;
562 tunnelOptions = remoteTunnelOptions = 0;
565 cout << " == New H.323 Connection created." << endl;
570 MyH323Connection::~MyH323Connection()
573 cout << " == H.323 Connection deleted." << endl;
578 BOOL MyH323Connection::OnReceivedProgress(const H323SignalPDU &pdu)
583 if (!H323Connection::OnReceivedProgress(pdu)) {
587 if (!pdu.GetQ931().GetProgressIndicator(pi))
590 cout << "\t- Progress Indicator: " << pi << endl;
594 case Q931::ProgressNotEndToEndISDN:
595 case Q931::ProgressInbandInformationAvailable:
601 on_progress(GetCallReference(), (const char *)GetCallToken(), isInband);
603 return connectionState != ShuttingDownConnection;
606 BOOL MyH323Connection::MySendProgress()
608 /* The code taken from H323Connection::AnsweringCall() but ALWAYS send
609 PROGRESS message, including slow start operations */
610 H323SignalPDU progressPDU;
611 H225_Progress_UUIE &prog = progressPDU.BuildProgress(*this);
613 if (!mediaWaitForConnect) {
614 if (SendFastStartAcknowledge(prog.m_fastStart))
615 prog.IncludeOptionalField(H225_Progress_UUIE::e_fastStart);
617 if (connectionState == ShuttingDownConnection)
620 /* Do early H.245 start */
622 if (!h245Tunneling) {
623 if (!H323Connection::StartControlChannel())
625 prog.IncludeOptionalField(H225_Progress_UUIE::e_h245Address);
626 controlChannel->SetUpTransportPDU(prog.m_h245Address, TRUE);
630 progressPDU.GetQ931().SetProgressIndicator(Q931::ProgressInbandInformationAvailable);
633 EmbedTunneledInfo(progressPDU);
635 HandleTunnelPDU(&progressPDU);
636 WriteSignalPDU(progressPDU);
641 H323Connection::AnswerCallResponse MyH323Connection::OnAnswerCall(const PString & caller,
642 const H323SignalPDU & setupPDU,
643 H323SignalPDU & connectPDU)
648 cout << "\t=-= In OnAnswerCall for call " << GetCallReference() << endl;
651 if (connectionState == ShuttingDownConnection)
652 return H323Connection::AnswerCallDenied;
654 if (!setupPDU.GetQ931().GetProgressIndicator(pi)) {
658 cout << "\t\t- Progress Indicator: " << pi << endl;
662 } else if (pi == Q931::ProgressOriginNotISDN) {
663 pi = Q931::ProgressInbandInformationAvailable;
665 if (pi && alertingPDU) {
666 alertingPDU->GetQ931().SetProgressIndicator(pi);
669 cout << "\t\t- Inserting PI of " << pi << " into ALERTING message" << endl;
674 EmbedTunneledInfo(*alertingPDU);
675 EmbedTunneledInfo(connectPDU);
678 if (!on_answer_call(GetCallReference(), (const char *)GetCallToken())) {
679 return H323Connection::AnswerCallDenied;
681 /* The call will be answered later with "AnsweringCall()" function.
683 return ((pi || (fastStartState != FastStartDisabled)) ? AnswerCallDeferredWithMedia : AnswerCallDeferred);
686 BOOL MyH323Connection::OnAlerting(const H323SignalPDU & alertingPDU, const PString & username)
689 cout << "\t=-= In OnAlerting for call " << GetCallReference()
690 << ": sessionId=" << sessionId << endl;
691 cout << "\t-- Ringing phone for \"" << username << "\"" << endl;
698 if (!alertingPDU.GetQ931().GetProgressIndicator(alertingPI)) {
702 cout << "\t\t- Progress Indicator: " << alertingPI << endl;
706 case Q931::ProgressNotEndToEndISDN:
707 case Q931::ProgressInbandInformationAvailable:
713 on_progress(GetCallReference(), (const char *)GetCallToken(), isInband);
715 on_chan_ringing(GetCallReference(), (const char *)GetCallToken() );
716 return connectionState != ShuttingDownConnection;
719 void MyH323Connection::SetCallOptions(void *o, BOOL isIncoming)
721 call_options_t *opts = (call_options_t *)o;
723 progressSetup = opts->progress_setup;
724 progressAlert = opts->progress_alert;
725 holdHandling = opts->holdHandling;
726 dtmfCodec[0] = (RTP_DataFrame::PayloadTypes)opts->dtmfcodec[0];
727 dtmfCodec[1] = (RTP_DataFrame::PayloadTypes)opts->dtmfcodec[1];
728 dtmfMode = opts->dtmfmode;
731 fastStartState = (opts->fastStart ? FastStartInitiate : FastStartDisabled);
732 h245Tunneling = (opts->h245Tunneling ? TRUE : FALSE);
734 sourceE164 = PString(opts->cid_num);
735 SetLocalPartyName(PString(opts->cid_name));
736 SetDisplayName(PString(opts->cid_name));
737 if (opts->redirect_reason >= 0) {
738 rdnis = PString(opts->cid_rdnis);
739 redirect_reason = opts->redirect_reason;
741 cid_presentation = opts->presentation;
742 cid_ton = opts->type_of_number;
743 if (opts->transfer_capability >= 0) {
744 transfer_capability = opts->transfer_capability;
747 tunnelOptions = opts->tunnelOptions;
750 void MyH323Connection::SetCallDetails(void *callDetails, const H323SignalPDU &setupPDU, BOOL isIncoming)
754 PString sourceAliases;
757 call_details_t *cd = (call_details_t *)callDetails;
759 memset(cd, 0, sizeof(*cd));
760 cd->call_reference = GetCallReference();
761 cd->call_token = strdup((const char *)GetCallToken());
764 setupPDU.GetSourceE164(sourceE164);
765 cd->call_source_e164 = strdup((const char *)sourceE164);
768 setupPDU.GetDestinationE164(destE164);
769 cd->call_dest_e164 = strdup((const char *)destE164);
771 /* XXX Is it possible to have this information for outgoing calls too? XXX */
774 PIPSocket::Address Ip;
776 PString redirect_number;
777 unsigned redirect_reason;
778 unsigned plan, type, screening, presentation;
779 Q931::InformationTransferCapability capability;
780 unsigned transferRate, codingStandard, userInfoLayer1;
782 /* Fetch presentation and type information about calling party's number */
783 if (setupPDU.GetQ931().GetCallingPartyNumber(sourceName, &plan, &type, &presentation, &screening, 0, 0)) {
784 /* Construct fields back */
785 cd->type_of_number = (type << 4) | plan;
786 cd->presentation = (presentation << 5) | screening;
787 } else if (cd->call_source_e164[0]) {
788 cd->type_of_number = 0; /* UNKNOWN */
789 cd->presentation = 0x03; /* ALLOWED NETWORK NUMBER - Default */
790 if (setupPDU.GetQ931().HasIE(Q931::UserUserIE)) {
791 const H225_Setup_UUIE &setup_uuie = setupPDU.m_h323_uu_pdu.m_h323_message_body;
792 if (setup_uuie.HasOptionalField(H225_Setup_UUIE::e_presentationIndicator))
793 cd->presentation = (cd->presentation & 0x9f) | (((unsigned int)setup_uuie.m_presentationIndicator.GetTag()) << 5);
794 if (setup_uuie.HasOptionalField(H225_Setup_UUIE::e_screeningIndicator))
795 cd->presentation = (cd->presentation & 0xe0) | (((unsigned int)setup_uuie.m_screeningIndicator.GetValue()) & 0x1f);
798 cd->type_of_number = 0; /* UNKNOWN */
799 cd->presentation = 0x43; /* NUMBER NOT AVAILABLE */
802 sourceName = setupPDU.GetQ931().GetDisplayName();
803 cd->call_source_name = strdup((const char *)sourceName);
805 GetSignallingChannel()->GetRemoteAddress().GetIpAndPort(Ip, sourcePort);
806 cd->sourceIp = strdup((const char *)Ip.AsString());
808 if (setupPDU.GetQ931().GetRedirectingNumber(redirect_number, NULL, NULL, NULL, NULL, &redirect_reason, 0, 0, 0)) {
809 cd->redirect_number = strdup((const char *)redirect_number);
810 cd->redirect_reason = redirect_reason;
813 cd->redirect_reason = -1;
815 /* Fetch Q.931's transfer capability */
816 if (((Q931 &)setupPDU.GetQ931()).GetBearerCapabilities(capability, transferRate, &codingStandard, &userInfoLayer1))
817 cd->transfer_capability = ((unsigned int)capability & 0x1f) | (codingStandard << 5);
819 cd->transfer_capability = 0x00; /* ITU coding of Speech */
821 /* Don't show local username as called party name */
822 SetDisplayName(cd->call_dest_e164);
825 /* Convert complex strings */
826 // FIXME: deal more than one source alias
827 sourceAliases = setupPDU.GetSourceAliases();
828 s1 = strdup((const char *)sourceAliases);
829 if ((s = strchr(s1, ' ')) != NULL)
831 if ((s = strchr(s1, '\t')) != NULL)
833 cd->call_source_aliases = s1;
835 destAliases = setupPDU.GetDestinationAlias();
836 s1 = strdup((const char *)destAliases);
837 if ((s = strchr(s1, ' ')) != NULL)
839 if ((s = strchr(s1, '\t')) != NULL)
841 cd->call_dest_alias = s1;
845 static BOOL FetchInformationElements(Q931 &q931, const PBYTEArray &data)
849 while (offset < data.GetSize()) {
850 // Get field discriminator
851 int discriminator = data[offset++];
854 /* Do not overwrite existing IEs */
855 if (q931.HasIE((Q931::InformationElementCodes)discriminator)) {
856 if ((discriminatir & 0x80) == 0)
857 offset += data[offset++];
858 if (offset > data.GetSize())
864 PBYTEArray * item = new PBYTEArray;
866 // For discriminator with high bit set there is no data
867 if ((discriminator & 0x80) == 0) {
868 int len = data[offset++];
870 #if 0 // That is not H.225 but regular Q.931 (ISDN) IEs
871 if (discriminator == UserUserIE) {
872 // Special case of User-user field. See 7.2.2.31/H.225.0v4.
874 len |= data[offset++];
876 // we also have a protocol discriminator, which we ignore
879 // before decrementing the length, make sure it is not zero
883 // adjust for protocol discriminator
888 if (offset + len > data.GetSize()) {
893 memcpy(item->GetPointer(len), (const BYTE *)data+offset, len);
897 q931.SetIE((Q931::InformationElementCodes)discriminator, *item);
903 static BOOL FetchCiscoTunneledInfo(Q931 &q931, const H323SignalPDU &pdu)
906 const H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
908 if(uuPDU.HasOptionalField(H225_H323_UU_PDU::e_nonStandardControl)) {
909 for(int i = 0; i < uuPDU.m_nonStandardControl.GetSize(); ++i) {
910 const H225_NonStandardParameter &np = uuPDU.m_nonStandardControl[i];
911 const H225_NonStandardIdentifier &id = np.m_nonStandardIdentifier;
912 if (id.GetTag() == H225_NonStandardIdentifier::e_h221NonStandard) {
913 const H225_H221NonStandard &ni = id;
914 /* Check for Cisco */
915 if ((ni.m_t35CountryCode == 181) && (ni.m_t35Extension == 0) && (ni.m_manufacturerCode == 18)) {
916 const PBYTEArray &data = np.m_data;
918 cout << setprecision(0) << "Received non-standard Cisco extension data " << np.m_data << endl;
919 CISCO_H225_H323_UU_NonStdInfo c;
920 PPER_Stream strm(data);
921 if (c.Decode(strm)) {
922 BOOL haveIEs = FALSE;
924 cout << setprecision(0) << "H323_UU_NonStdInfo = " << c << endl;
925 if (c.HasOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_protoParam)) {
926 FetchInformationElements(q931, c.m_protoParam.m_qsigNonStdInfo.m_rawMesg);
929 if (c.HasOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_commonParam)) {
930 FetchInformationElements(q931, c.m_commonParam.m_redirectIEinfo.m_redirectIE);
933 if (haveIEs && h323debug)
934 cout << setprecision(0) << "Information elements collected:" << q931 << endl;
937 cout << "ERROR while decoding non-standard Cisco extension" << endl;
947 static BOOL EmbedCiscoTunneledInfo(H323SignalPDU &pdu)
949 const static struct {
950 Q931::InformationElementCodes ie;
953 { Q931::RedirectingNumberIE, },
954 { Q931::FacilityIE, },
955 // { Q931::CallingPartyNumberIE, TRUE },
959 BOOL notRedirOnly = FALSE;
961 Q931 &q931 = pdu.GetQ931();
963 for(unsigned i = 0; i < (sizeof(codes) / sizeof(codes[0])); ++i) {
964 if (q931.HasIE(codes[i].ie)) {
965 tmpQ931.SetIE(codes[i].ie, q931.GetIE(codes[i].ie));
966 if (!codes[i].dontDelete)
967 q931.RemoveIE(codes[i].ie);
968 if (codes[i].ie != Q931::RedirectingNumberIE)
973 /* Have something to embed */
976 if (!tmpQ931.Encode(msg))
978 PBYTEArray ies(msg.GetPointer() + 5, msg.GetSize() - 5);
980 H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
981 if(!uuPDU.HasOptionalField(H225_H323_UU_PDU::e_nonStandardControl)) {
982 uuPDU.IncludeOptionalField(H225_H323_UU_PDU::e_nonStandardControl);
983 uuPDU.m_nonStandardControl.SetSize(0);
985 H225_NonStandardParameter *np = new H225_NonStandardParameter;
986 uuPDU.m_nonStandardControl.Append(np);
987 H225_NonStandardIdentifier &nsi = (*np).m_nonStandardIdentifier;
988 nsi.SetTag(H225_NonStandardIdentifier::e_h221NonStandard);
989 H225_H221NonStandard &ns = nsi;
990 ns.m_t35CountryCode = 181;
991 ns.m_t35Extension = 0;
992 ns.m_manufacturerCode = 18;
994 CISCO_H225_H323_UU_NonStdInfo c;
995 c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_version);
999 c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_protoParam);
1000 CISCO_H225_QsigNonStdInfo &qsigInfo = c.m_protoParam.m_qsigNonStdInfo;
1001 qsigInfo.m_iei = ies[0];
1002 qsigInfo.m_rawMesg = ies;
1004 c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_commonParam);
1005 c.m_commonParam.m_redirectIEinfo.m_redirectIE = ies;
1009 stream.CompleteEncoding();
1010 (*np).m_data = stream;
1015 static const char OID_QSIG[] = "1.3.12.9";
1017 static BOOL FetchQSIGTunneledInfo(Q931 &q931, const H323SignalPDU &pdu)
1020 const H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
1021 if (uuPDU.HasOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage)) {
1022 const H225_H323_UU_PDU_tunnelledSignallingMessage &sig = uuPDU.m_tunnelledSignallingMessage;
1023 const H225_TunnelledProtocol_id &proto = sig.m_tunnelledProtocolID.m_id;
1024 if ((proto.GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
1025 (((const PASN_ObjectId &)proto).AsString() == OID_QSIG)) {
1026 const H225_ArrayOf_PASN_OctetString &sigs = sig.m_messageContent;
1027 for(int i = 0; i < sigs.GetSize(); ++i) {
1028 const PASN_OctetString &msg = sigs[i];
1030 cout << setprecision(0) << "Q.931 message data is " << msg << endl;
1031 if(!q931.Decode((const PBYTEArray &)msg)) {
1032 cout << "Error while decoding Q.931 message" << endl;
1037 cout << setprecision(0) << "Received QSIG message " << q931 << endl;
1044 static H225_EndpointType *GetEndpointType(H323SignalPDU &pdu)
1046 if (!pdu.GetQ931().HasIE(Q931::UserUserIE))
1049 H225_H323_UU_PDU_h323_message_body &body = pdu.m_h323_uu_pdu.m_h323_message_body;
1050 switch (body.GetTag()) {
1051 case H225_H323_UU_PDU_h323_message_body::e_setup:
1052 return &((H225_Setup_UUIE &)body).m_sourceInfo;
1053 case H225_H323_UU_PDU_h323_message_body::e_callProceeding:
1054 return &((H225_CallProceeding_UUIE &)body).m_destinationInfo;
1055 case H225_H323_UU_PDU_h323_message_body::e_connect:
1056 return &((H225_Connect_UUIE &)body).m_destinationInfo;
1057 case H225_H323_UU_PDU_h323_message_body::e_alerting:
1058 return &((H225_Alerting_UUIE &)body).m_destinationInfo;
1059 case H225_H323_UU_PDU_h323_message_body::e_facility:
1060 return &((H225_Facility_UUIE &)body).m_destinationInfo;
1061 case H225_H323_UU_PDU_h323_message_body::e_progress:
1062 return &((H225_Progress_UUIE &)body).m_destinationInfo;
1067 static BOOL QSIGTunnelRequested(H323SignalPDU &pdu)
1069 H225_EndpointType *epType = GetEndpointType(pdu);
1071 if (!(*epType).HasOptionalField(H225_EndpointType::e_supportedTunnelledProtocols)) {
1074 H225_ArrayOf_TunnelledProtocol &protos = (*epType).m_supportedTunnelledProtocols;
1075 for (int i = 0; i < protos.GetSize(); ++i)
1077 if ((protos[i].GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
1078 (((const PASN_ObjectId &)protos[i]).AsString() == OID_QSIG)) {
1086 static BOOL EmbedQSIGTunneledInfo(H323SignalPDU &pdu)
1088 const static Q931::InformationElementCodes codes[] =
1089 { Q931::RedirectingNumberIE, Q931::FacilityIE };
1091 Q931 &q931 = pdu.GetQ931();
1094 q931.Encode(message);
1096 /* Remove non-standard IEs */
1097 for(unsigned i = 0; i < (sizeof(codes) / sizeof(codes[0])); ++i) {
1098 if (q931.HasIE(codes[i])) {
1099 q931.RemoveIE(codes[i]);
1103 H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
1104 H225_EndpointType *epType = GetEndpointType(pdu);
1106 if (!(*epType).HasOptionalField(H225_EndpointType::e_supportedTunnelledProtocols)) {
1107 (*epType).IncludeOptionalField(H225_EndpointType::e_supportedTunnelledProtocols);
1108 (*epType).m_supportedTunnelledProtocols.SetSize(0);
1110 H225_ArrayOf_TunnelledProtocol &protos = (*epType).m_supportedTunnelledProtocols;
1111 BOOL addQSIG = TRUE;
1112 for (int i = 0; i < protos.GetSize(); ++i)
1114 if ((protos[i].GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
1115 (((PASN_ObjectId &)protos[i]).AsString() == OID_QSIG)) {
1121 H225_TunnelledProtocol *proto = new H225_TunnelledProtocol;
1122 (*proto).m_id.SetTag(H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID);
1123 (PASN_ObjectId &)(proto->m_id) = OID_QSIG;
1124 protos.Append(proto);
1127 if (!uuPDU.HasOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage))
1128 uuPDU.IncludeOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage);
1129 H225_H323_UU_PDU_tunnelledSignallingMessage &sig = uuPDU.m_tunnelledSignallingMessage;
1130 H225_TunnelledProtocol_id &proto = sig.m_tunnelledProtocolID.m_id;
1131 if ((proto.GetTag() != H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) ||
1132 (((const PASN_ObjectId &)proto).AsString() != OID_QSIG)) {
1133 proto.SetTag(H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID);
1134 (PASN_ObjectId &)proto = OID_QSIG;
1135 sig.m_messageContent.SetSize(0);
1137 PASN_OctetString *msg = new PASN_OctetString;
1138 sig.m_messageContent.Append(msg);
1143 BOOL MyH323Connection::EmbedTunneledInfo(H323SignalPDU &pdu)
1145 if ((tunnelOptions & H323_TUNNEL_QSIG) || (remoteTunnelOptions & H323_TUNNEL_QSIG))
1146 EmbedQSIGTunneledInfo(pdu);
1147 if ((tunnelOptions & H323_TUNNEL_CISCO) || (remoteTunnelOptions & H323_TUNNEL_CISCO))
1148 EmbedCiscoTunneledInfo(pdu);
1153 /* Handle tunneled messages */
1154 BOOL MyH323Connection::HandleSignalPDU(H323SignalPDU &pdu)
1156 if (pdu.GetQ931().HasIE(Q931::UserUserIE)) {
1158 const Q931 *q931Info;
1161 if (FetchCiscoTunneledInfo(tunneledInfo, pdu)) {
1162 q931Info = &tunneledInfo;
1163 remoteTunnelOptions |= H323_TUNNEL_CISCO;
1165 if (FetchQSIGTunneledInfo(tunneledInfo, pdu)) {
1166 q931Info = &tunneledInfo;
1167 remoteTunnelOptions |= H323_TUNNEL_QSIG;
1169 if (!(remoteTunnelOptions & H323_TUNNEL_QSIG) && QSIGTunnelRequested(pdu)) {
1170 remoteTunnelOptions |= H323_TUNNEL_QSIG;
1173 if (q931Info->HasIE(Q931::RedirectingNumberIE)) {
1174 pdu.GetQ931().SetIE(Q931::RedirectingNumberIE, q931Info->GetIE(Q931::RedirectingNumberIE));
1178 if(q931Info->GetRedirectingNumber(number, NULL, NULL, NULL, NULL, &reason, 0, 0, 0))
1179 cout << "Got redirection from " << number << ", reason " << reason << endl;
1185 return H323Connection::HandleSignalPDU(pdu);
1189 BOOL MyH323Connection::OnReceivedSignalSetup(const H323SignalPDU & setupPDU)
1194 cout << "\t--Received SETUP message" << endl;
1197 if (connectionState == ShuttingDownConnection)
1200 SetCallDetails(&cd, setupPDU, TRUE);
1202 /* Notify Asterisk of the request */
1203 call_options_t *res = on_incoming_call(&cd);
1207 cout << "\t-- Call Failed" << endl;
1212 SetCallOptions(res, TRUE);
1214 /* Disable fastStart if requested by remote side */
1215 if (h245Tunneling && !setupPDU.m_h323_uu_pdu.m_h245Tunneling) {
1216 masterSlaveDeterminationProcedure->Stop();
1217 capabilityExchangeProcedure->Stop();
1218 PTRACE(3, "H225\tFast Start DISABLED!");
1219 h245Tunneling = FALSE;
1222 return H323Connection::OnReceivedSignalSetup(setupPDU);
1225 BOOL MyH323Connection::OnSendSignalSetup(H323SignalPDU & setupPDU)
1230 cout << "\t-- Sending SETUP message" << endl;
1233 if (connectionState == ShuttingDownConnection)
1237 setupPDU.GetQ931().SetProgressIndicator(progressSetup);
1239 if (redirect_reason >= 0) {
1240 setupPDU.GetQ931().SetRedirectingNumber(rdnis, 0, 0, 0, 0, redirect_reason);
1241 /* OpenH323 incorrectly fills number IE when redirecting reason is specified - fix it */
1242 PBYTEArray IE(setupPDU.GetQ931().GetIE(Q931::RedirectingNumberIE));
1243 IE[0] = IE[0] & 0x7f;
1244 IE[1] = IE[1] & 0x7f;
1245 setupPDU.GetQ931().SetIE(Q931::RedirectingNumberIE, IE);
1248 if (transfer_capability)
1249 setupPDU.GetQ931().SetBearerCapabilities((Q931::InformationTransferCapability)(transfer_capability & 0x1f), 1, ((transfer_capability >> 5) & 3));
1251 SetCallDetails(&cd, setupPDU, FALSE);
1253 int res = on_outgoing_call(&cd);
1256 cout << "\t-- Call Failed" << endl;
1261 /* OpenH323 will build calling party information with default
1262 type and presentation information, so build it to be recorded
1263 by embedding routines */
1264 setupPDU.GetQ931().SetCallingPartyNumber(sourceE164, (cid_ton >> 4) & 0x07,
1265 cid_ton & 0x0f, (cid_presentation >> 5) & 0x03, cid_presentation & 0x1f);
1266 setupPDU.GetQ931().SetDisplayName(GetDisplayName());
1269 EmbedTunneledInfo(setupPDU);
1272 return H323Connection::OnSendSignalSetup(setupPDU);
1275 static BOOL BuildFastStartList(const H323Channel & channel,
1276 H225_ArrayOf_PASN_OctetString & array,
1277 H323Channel::Directions reverseDirection)
1279 H245_OpenLogicalChannel open;
1280 const H323Capability & capability = channel.GetCapability();
1282 if (channel.GetDirection() != reverseDirection) {
1283 if (!capability.OnSendingPDU(open.m_forwardLogicalChannelParameters.m_dataType))
1287 if (!capability.OnSendingPDU(open.m_reverseLogicalChannelParameters.m_dataType))
1290 open.m_forwardLogicalChannelParameters.m_multiplexParameters.SetTag(
1291 H245_OpenLogicalChannel_forwardLogicalChannelParameters_multiplexParameters::e_none);
1292 open.m_forwardLogicalChannelParameters.m_dataType.SetTag(H245_DataType::e_nullData);
1293 open.IncludeOptionalField(H245_OpenLogicalChannel::e_reverseLogicalChannelParameters);
1296 if (!channel.OnSendingPDU(open))
1299 PTRACE(4, "H225\tBuild fastStart:\n " << setprecision(2) << open);
1300 PINDEX last = array.GetSize();
1301 array.SetSize(last+1);
1302 array[last].EncodeSubType(open);
1304 PTRACE(3, "H225\tBuilt fastStart for " << capability);
1308 H323Connection::CallEndReason MyH323Connection::SendSignalSetup(const PString & alias,
1309 const H323TransportAddress & address)
1311 // Start the call, first state is asking gatekeeper
1312 connectionState = AwaitingGatekeeperAdmission;
1314 // Indicate the direction of call.
1315 if (alias.IsEmpty())
1316 remotePartyName = remotePartyAddress = address;
1318 remotePartyName = alias;
1319 remotePartyAddress = alias + '@' + address;
1322 // Start building the setup PDU to get various ID's
1323 H323SignalPDU setupPDU;
1324 H225_Setup_UUIE & setup = setupPDU.BuildSetup(*this, address);
1327 h450dispatcher->AttachToSetup(setupPDU);
1330 // Save the identifiers generated by BuildSetup
1331 setupPDU.GetQ931().GetCalledPartyNumber(remotePartyNumber);
1333 H323TransportAddress gatekeeperRoute = address;
1335 // Check for gatekeeper and do admission check if have one
1336 H323Gatekeeper * gatekeeper = endpoint.GetGatekeeper();
1337 H225_ArrayOf_AliasAddress newAliasAddresses;
1338 if (gatekeeper != NULL) {
1339 H323Gatekeeper::AdmissionResponse response;
1340 response.transportAddress = &gatekeeperRoute;
1341 response.aliasAddresses = &newAliasAddresses;
1342 if (!gkAccessTokenOID)
1343 response.accessTokenData = &gkAccessTokenData;
1344 while (!gatekeeper->AdmissionRequest(*this, response, alias.IsEmpty())) {
1345 PTRACE(1, "H225\tGatekeeper refused admission: "
1346 << (response.rejectReason == UINT_MAX
1347 ? PString("Transport error")
1348 : H225_AdmissionRejectReason(response.rejectReason).GetTagName()));
1350 h4502handler->onReceivedAdmissionReject(H4501_GeneralErrorList::e_notAvailable);
1353 switch (response.rejectReason) {
1354 case H225_AdmissionRejectReason::e_calledPartyNotRegistered:
1355 return EndedByNoUser;
1356 case H225_AdmissionRejectReason::e_requestDenied:
1357 return EndedByNoBandwidth;
1358 case H225_AdmissionRejectReason::e_invalidPermission:
1359 case H225_AdmissionRejectReason::e_securityDenial:
1360 return EndedBySecurityDenial;
1361 case H225_AdmissionRejectReason::e_resourceUnavailable:
1362 return EndedByRemoteBusy;
1363 case H225_AdmissionRejectReason::e_incompleteAddress:
1364 if (OnInsufficientDigits())
1366 // Then default case
1368 return EndedByGatekeeper;
1371 PString lastRemotePartyName = remotePartyName;
1372 while (lastRemotePartyName == remotePartyName) {
1373 Unlock(); // Release the mutex as can deadlock trying to clear call during connect.
1374 digitsWaitFlag.Wait();
1375 if (!Lock()) // Lock while checking for shutting down.
1376 return EndedByCallerAbort;
1380 if (response.gatekeeperRouted) {
1381 setup.IncludeOptionalField(H225_Setup_UUIE::e_endpointIdentifier);
1382 setup.m_endpointIdentifier = gatekeeper->GetEndpointIdentifier();
1383 gatekeeperRouted = TRUE;
1387 #ifdef H323_TRANSNEXUS_OSP
1388 // check for OSP server (if not using GK)
1389 if (gatekeeper == NULL) {
1390 OpalOSP::Provider * ospProvider = endpoint.GetOSPProvider();
1391 if (ospProvider != NULL) {
1392 OpalOSP::Transaction * transaction = new OpalOSP::Transaction();
1393 if (transaction->Open(*ospProvider) != 0) {
1394 PTRACE(1, "H225\tCannot create OSP transaction");
1395 return EndedByOSPRefusal;
1398 OpalOSP::Transaction::DestinationInfo destInfo;
1399 if (!AuthoriseOSPTransaction(*transaction, destInfo)) {
1401 return EndedByOSPRefusal;
1404 // save the transaction for use by the call
1405 ospTransaction = transaction;
1407 // retreive the call information
1408 gatekeeperRoute = destInfo.destinationAddress;
1409 newAliasAddresses.Append(new H225_AliasAddress(destInfo.calledNumber));
1412 setup.IncludeOptionalField(H225_Setup_UUIE::e_tokens);
1413 destInfo.InsertToken(setup.m_tokens);
1418 // Update the field e_destinationAddress in the SETUP PDU to reflect the new
1419 // alias received in the ACF (m_destinationInfo).
1420 if (newAliasAddresses.GetSize() > 0) {
1421 setup.IncludeOptionalField(H225_Setup_UUIE::e_destinationAddress);
1422 setup.m_destinationAddress = newAliasAddresses;
1424 // Update the Q.931 Information Element (if is an E.164 address)
1425 PString e164 = H323GetAliasAddressE164(newAliasAddresses);
1427 remotePartyNumber = e164;
1430 if (addAccessTokenToSetup && !gkAccessTokenOID && !gkAccessTokenData.IsEmpty()) {
1432 PINDEX comma = gkAccessTokenOID.Find(',');
1433 if (comma == P_MAX_INDEX)
1434 oid1 = oid2 = gkAccessTokenOID;
1436 oid1 = gkAccessTokenOID.Left(comma);
1437 oid2 = gkAccessTokenOID.Mid(comma+1);
1439 setup.IncludeOptionalField(H225_Setup_UUIE::e_tokens);
1440 PINDEX last = setup.m_tokens.GetSize();
1441 setup.m_tokens.SetSize(last+1);
1442 setup.m_tokens[last].m_tokenOID = oid1;
1443 setup.m_tokens[last].IncludeOptionalField(H235_ClearToken::e_nonStandard);
1444 setup.m_tokens[last].m_nonStandard.m_nonStandardIdentifier = oid2;
1445 setup.m_tokens[last].m_nonStandard.m_data = gkAccessTokenData;
1448 if (!signallingChannel->SetRemoteAddress(gatekeeperRoute)) {
1449 PTRACE(1, "H225\tInvalid "
1450 << (gatekeeperRoute != address ? "gatekeeper" : "user")
1451 << " supplied address: \"" << gatekeeperRoute << '"');
1452 connectionState = AwaitingTransportConnect;
1453 return EndedByConnectFail;
1456 // Do the transport connect
1457 connectionState = AwaitingTransportConnect;
1459 // Release the mutex as can deadlock trying to clear call during connect.
1462 signallingChannel->SetWriteTimeout(100);
1464 BOOL connectFailed = !signallingChannel->Connect();
1466 // Lock while checking for shutting down.
1468 return EndedByCallerAbort;
1470 // See if transport connect failed, abort if so.
1471 if (connectFailed) {
1472 connectionState = NoConnectionActive;
1473 switch (signallingChannel->GetErrorNumber()) {
1475 return EndedByUnreachable;
1477 return EndedByNoEndPoint;
1479 return EndedByHostOffline;
1481 return EndedByConnectFail;
1484 PTRACE(3, "H225\tSending Setup PDU");
1485 connectionState = AwaitingSignalConnect;
1487 // Put in all the signalling addresses for link
1488 setup.IncludeOptionalField(H225_Setup_UUIE::e_sourceCallSignalAddress);
1489 signallingChannel->SetUpTransportPDU(setup.m_sourceCallSignalAddress, TRUE);
1490 if (!setup.HasOptionalField(H225_Setup_UUIE::e_destCallSignalAddress)) {
1491 setup.IncludeOptionalField(H225_Setup_UUIE::e_destCallSignalAddress);
1492 signallingChannel->SetUpTransportPDU(setup.m_destCallSignalAddress, FALSE);
1495 // If a standard call do Fast Start (if required)
1496 if (setup.m_conferenceGoal.GetTag() == H225_Setup_UUIE_conferenceGoal::e_create) {
1498 // Get the local capabilities before fast start is handled
1499 OnSetLocalCapabilities();
1501 // Ask the application what channels to open
1502 PTRACE(3, "H225\tCheck for Fast start by local endpoint");
1503 fastStartChannels.RemoveAll();
1504 OnSelectLogicalChannels();
1506 // If application called OpenLogicalChannel, put in the fastStart field
1507 if (!fastStartChannels.IsEmpty()) {
1508 PTRACE(3, "H225\tFast start begun by local endpoint");
1509 for (PINDEX i = 0; i < fastStartChannels.GetSize(); i++)
1510 BuildFastStartList(fastStartChannels[i], setup.m_fastStart, H323Channel::IsReceiver);
1511 if (setup.m_fastStart.GetSize() > 0)
1512 setup.IncludeOptionalField(H225_Setup_UUIE::e_fastStart);
1515 // Search the capability set and see if we have video capability
1516 for (PINDEX i = 0; i < localCapabilities.GetSize(); i++) {
1517 switch (localCapabilities[i].GetMainType()) {
1518 case H323Capability::e_Audio:
1519 case H323Capability::e_UserInput:
1522 default: // Is video or other data (eg T.120)
1523 setupPDU.GetQ931().SetBearerCapabilities(Q931::TransferUnrestrictedDigital, 6);
1524 i = localCapabilities.GetSize(); // Break out of the for loop
1530 if (!OnSendSignalSetup(setupPDU))
1531 return EndedByNoAccept;
1533 // Do this again (was done when PDU was constructed) in case
1534 // OnSendSignalSetup() changed something.
1535 // setupPDU.SetQ931Fields(*this, TRUE);
1536 setupPDU.GetQ931().GetCalledPartyNumber(remotePartyNumber);
1538 fastStartState = FastStartDisabled;
1539 BOOL set_lastPDUWasH245inSETUP = FALSE;
1541 if (h245Tunneling && doH245inSETUP) {
1542 h245TunnelTxPDU = &setupPDU;
1544 // Try and start the master/slave and capability exchange through the tunnel
1545 // Note: this used to be disallowed but is now allowed as of H323v4
1546 BOOL ok = StartControlNegotiations();
1548 h245TunnelTxPDU = NULL;
1551 return EndedByTransportFail;
1553 if (setup.m_fastStart.GetSize() > 0) {
1554 // Now if fast start as well need to put this in setup specific field
1555 // and not the generic H.245 tunneling field
1556 setup.IncludeOptionalField(H225_Setup_UUIE::e_parallelH245Control);
1557 setup.m_parallelH245Control = setupPDU.m_h323_uu_pdu.m_h245Control;
1558 setupPDU.m_h323_uu_pdu.RemoveOptionalField(H225_H323_UU_PDU::e_h245Control);
1559 set_lastPDUWasH245inSETUP = TRUE;
1563 // Send the initial PDU
1564 setupTime = PTime();
1565 if (!WriteSignalPDU(setupPDU))
1566 return EndedByTransportFail;
1568 // WriteSignalPDU always resets lastPDUWasH245inSETUP.
1569 // So set it here if required
1570 if (set_lastPDUWasH245inSETUP)
1571 lastPDUWasH245inSETUP = TRUE;
1573 // Set timeout for remote party to answer the call
1574 signallingChannel->SetReadTimeout(endpoint.GetSignallingChannelCallTimeout());
1576 return NumCallEndReasons;
1580 BOOL MyH323Connection::OnSendReleaseComplete(H323SignalPDU & releaseCompletePDU)
1583 cout << "\t-- Sending RELEASE COMPLETE" << endl;
1586 releaseCompletePDU.GetQ931().SetCause((Q931::CauseValues)cause);
1589 EmbedTunneledInfo(releaseCompletePDU);
1592 return H323Connection::OnSendReleaseComplete(releaseCompletePDU);
1595 BOOL MyH323Connection::OnReceivedFacility(const H323SignalPDU & pdu)
1598 cout << "\t-- Received Facility message... " << endl;
1600 return H323Connection::OnReceivedFacility(pdu);
1603 void MyH323Connection::OnReceivedReleaseComplete(const H323SignalPDU & pdu)
1606 cout << "\t-- Received RELEASE COMPLETE message..." << endl;
1609 on_hangup(GetCallReference(), (const char *)GetCallToken(), pdu.GetQ931().GetCause());
1610 return H323Connection::OnReceivedReleaseComplete(pdu);
1613 BOOL MyH323Connection::OnClosingLogicalChannel(H323Channel & channel)
1616 cout << "\t-- Closing logical channel..." << endl;
1618 return H323Connection::OnClosingLogicalChannel(channel);
1621 void MyH323Connection::SendUserInputTone(char tone, unsigned duration, unsigned logicalChannel, unsigned rtpTimestamp)
1623 SendUserInputModes mode = GetRealSendUserInputMode();
1624 // That is recursive call... Why?
1625 // on_receive_digit(GetCallReference(), tone, (const char *)GetCallToken());
1626 if ((tone != ' ') || (mode == SendUserInputAsTone) || (mode == SendUserInputAsInlineRFC2833)) {
1628 cout << "\t-- Sending user input tone (" << tone << ") to remote" << endl;
1630 H323Connection::SendUserInputTone(tone, duration);
1634 void MyH323Connection::OnUserInputTone(char tone, unsigned duration, unsigned logicalChannel, unsigned rtpTimestamp)
1636 /* Why we should check this? */
1637 if ((dtmfMode & (H323_DTMF_CISCO | H323_DTMF_RFC2833 | H323_DTMF_SIGNAL)) != 0) {
1639 cout << "\t-- Received user input tone (" << tone << ") from remote" << endl;
1641 on_receive_digit(GetCallReference(), tone, (const char *)GetCallToken(), duration);
1645 void MyH323Connection::OnUserInputString(const PString &value)
1648 cout << "\t-- Received user input string (" << value << ") from remote." << endl;
1650 on_receive_digit(GetCallReference(), value[0], (const char *)GetCallToken(), 0);
1653 void MyH323Connection::OnSendCapabilitySet(H245_TerminalCapabilitySet & pdu)
1657 H323Connection::OnSendCapabilitySet(pdu);
1659 H245_ArrayOf_CapabilityTableEntry & tables = pdu.m_capabilityTable;
1660 for(i = 0; i < tables.GetSize(); i++)
1662 H245_CapabilityTableEntry & entry = tables[i];
1663 if (entry.HasOptionalField(H245_CapabilityTableEntry::e_capability)) {
1664 H245_Capability & cap = entry.m_capability;
1665 if (cap.GetTag() == H245_Capability::e_receiveRTPAudioTelephonyEventCapability) {
1666 H245_AudioTelephonyEventCapability & atec = cap;
1667 atec.m_dynamicRTPPayloadType = dtmfCodec[0];
1668 // on_set_rfc2833_payload(GetCallReference(), (const char *)GetCallToken(), (int)dtmfCodec[0]);
1671 cout << "\t-- Receiving RFC2833 on payload " <<
1672 atec.m_dynamicRTPPayloadType << endl;
1680 void MyH323Connection::OnSetLocalCapabilities()
1682 if (on_setcapabilities)
1683 on_setcapabilities(GetCallReference(), (const char *)callToken);
1686 BOOL MyH323Connection::OnReceivedCapabilitySet(const H323Capabilities & remoteCaps,
1687 const H245_MultiplexCapability * muxCap,
1688 H245_TerminalCapabilitySetReject & reject)
1691 unsigned int asterisk_codec;
1692 unsigned int h245_cap;
1694 const char *formatName;
1696 static const struct __codec__ codecs[] = {
1697 { AST_FORMAT_G723_1, H245_AudioCapability::e_g7231 },
1698 { AST_FORMAT_GSM, H245_AudioCapability::e_gsmFullRate },
1699 { AST_FORMAT_ULAW, H245_AudioCapability::e_g711Ulaw64k },
1700 { AST_FORMAT_ALAW, H245_AudioCapability::e_g711Alaw64k },
1701 { AST_FORMAT_G729A, H245_AudioCapability::e_g729AnnexA },
1702 { AST_FORMAT_G729A, H245_AudioCapability::e_g729 },
1703 { AST_FORMAT_G726_AAL2, H245_AudioCapability::e_nonStandard, NULL, CISCO_G726r32 },
1704 #ifdef AST_FORMAT_MODEM
1705 { AST_FORMAT_MODEM, H245_DataApplicationCapability_application::e_t38fax },
1711 static const struct __codec__ vcodecs[] = {
1713 { AST_FORMAT_H261, H245_VideoCapability::e_h261VideoCapability },
1716 { AST_FORMAT_H263, H245_VideoCapability::e_h263VideoCapability },
1719 { AST_FORMAT_H264, H245_VideoCapability::e_genericVideoCapability, "0.0.8.241.0.0.1" },
1724 struct ast_codec_pref prefs;
1725 RTP_DataFrame::PayloadTypes pt;
1727 if (!H323Connection::OnReceivedCapabilitySet(remoteCaps, muxCap, reject)) {
1731 memset(&prefs, 0, sizeof(prefs));
1732 int peer_capabilities = 0;
1733 for (int i = 0; i < remoteCapabilities.GetSize(); ++i) {
1734 unsigned int subType = remoteCapabilities[i].GetSubType();
1736 cout << "Peer capability is " << remoteCapabilities[i] << endl;
1738 switch(remoteCapabilities[i].GetMainType()) {
1739 case H323Capability::e_Audio:
1740 for (int x = 0; codecs[x].asterisk_codec > 0; ++x) {
1741 if ((subType == codecs[x].h245_cap) && (!codecs[x].formatName || (!strcmp(codecs[x].formatName, (const char *)remoteCapabilities[i].GetFormatName())))) {
1742 int ast_codec = codecs[x].asterisk_codec;
1744 if (!(peer_capabilities & ast_codec)) {
1745 struct ast_format_list format;
1746 ast_codec_pref_append(&prefs, ast_codec);
1747 format = ast_codec_pref_getsize(&prefs, ast_codec);
1748 if ((ast_codec == AST_FORMAT_ALAW) || (ast_codec == AST_FORMAT_ULAW)) {
1749 ms = remoteCapabilities[i].GetTxFramesInPacket();
1753 ms = remoteCapabilities[i].GetTxFramesInPacket() * format.inc_ms;
1754 ast_codec_pref_setsize(&prefs, ast_codec, ms);
1757 cout << "Found peer capability " << remoteCapabilities[i] << ", Asterisk code is " << ast_codec << ", frame size (in ms) is " << ms << endl;
1759 peer_capabilities |= ast_codec;
1763 case H323Capability::e_Data:
1764 if (!strcmp((const char *)remoteCapabilities[i].GetFormatName(), CISCO_DTMF_RELAY)) {
1765 pt = remoteCapabilities[i].GetPayloadType();
1766 if ((dtmfMode & H323_DTMF_CISCO) != 0) {
1767 on_set_rfc2833_payload(GetCallReference(), (const char *)GetCallToken(), (int)pt, 1);
1768 // if (sendUserInputMode == SendUserInputAsTone)
1769 // sendUserInputMode = SendUserInputAsInlineRFC2833;
1773 cout << "\t-- Outbound Cisco RTP DTMF on payload " << pt << endl;
1778 case H323Capability::e_UserInput:
1779 if (!strcmp((const char *)remoteCapabilities[i].GetFormatName(), H323_UserInputCapability::SubTypeNames[H323_UserInputCapability::SignalToneRFC2833])) {
1780 pt = remoteCapabilities[i].GetPayloadType();
1781 if ((dtmfMode & H323_DTMF_RFC2833) != 0) {
1782 on_set_rfc2833_payload(GetCallReference(), (const char *)GetCallToken(), (int)pt, 0);
1783 // if (sendUserInputMode == SendUserInputAsTone)
1784 // sendUserInputMode = SendUserInputAsInlineRFC2833;
1788 cout << "\t-- Outbound RFC2833 on payload " << pt << endl;
1794 case H323Capability::e_Video:
1795 for (int x = 0; vcodecs[x].asterisk_codec > 0; ++x) {
1796 if (subType == vcodecs[x].h245_cap) {
1797 H245_CapabilityIdentifier *cap = NULL;
1798 H245_GenericCapability y;
1799 if (vcodecs[x].oid) {
1800 cap = new H245_CapabilityIdentifier(H245_CapabilityIdentifier::e_standard);
1801 PASN_ObjectId &object_id = *cap;
1802 object_id = vcodecs[x].oid;
1803 y.m_capabilityIdentifier = *cap;
1805 if ((subType != H245_VideoCapability::e_genericVideoCapability) ||
1806 (vcodecs[x].oid && ((const H323GenericVideoCapability &)remoteCapabilities[i]).IsGenericMatch((const H245_GenericCapability)y))) {
1808 cout << "Found peer video capability " << remoteCapabilities[i] << ", Asterisk code is " << vcodecs[x].asterisk_codec << endl;
1810 peer_capabilities |= vcodecs[x].asterisk_codec;
1823 char caps_str[1024], caps2_str[1024];
1824 ast_codec_pref_string(&prefs, caps2_str, sizeof(caps2_str));
1825 cout << "Peer capabilities = " << ast_getformatname_multiple(caps_str, sizeof(caps_str), peer_capabilities)
1826 << ", ordered list is " << caps2_str << endl;
1829 redir_capabilities &= peer_capabilities;
1831 if (on_setpeercapabilities)
1832 on_setpeercapabilities(GetCallReference(), (const char *)callToken, peer_capabilities, &prefs);
1837 H323Channel * MyH323Connection::CreateRealTimeLogicalChannel(const H323Capability & capability,
1838 H323Channel::Directions dir,
1840 const H245_H2250LogicalChannelParameters * /*param*/,
1841 RTP_QOS * /*param*/ )
1843 /* Do not open tx channel when transmitter has been paused by empty TCS */
1844 if ((dir == H323Channel::IsTransmitter) && transmitterSidePaused)
1847 return new MyH323_ExternalRTPChannel(*this, capability, dir, sessionID);
1850 /** This callback function is invoked once upon creation of each
1851 * channel for an H323 session
1853 BOOL MyH323Connection::OnStartLogicalChannel(H323Channel & channel)
1855 /* Increase the count of channels we have open */
1859 cout << "\t-- Started logical channel: "
1860 << ((channel.GetDirection() == H323Channel::IsTransmitter) ? "sending " : ((channel.GetDirection() == H323Channel::IsReceiver) ? "receiving " : " "))
1861 << (const char *)(channel.GetCapability()).GetFormatName() << endl;
1862 cout << "\t\t-- channelsOpen = " << channelsOpen << endl;
1864 return connectionState != ShuttingDownConnection;
1867 void MyH323Connection::SetCapabilities(int caps, int dtmf_mode, void *_prefs, int pref_codec)
1869 PINDEX lastcap = -1; /* last common capability index */
1870 int alreadysent = 0;
1873 char caps_str[1024];
1874 struct ast_codec_pref *prefs = (struct ast_codec_pref *)_prefs;
1875 struct ast_format_list format;
1876 int frames_per_packet;
1877 int max_frames_per_packet;
1878 H323Capability *cap;
1880 localCapabilities.RemoveAll();
1883 cout << "Setting capabilities to " << ast_getformatname_multiple(caps_str, sizeof(caps_str), caps) << endl;
1884 ast_codec_pref_string(prefs, caps_str, sizeof(caps_str));
1885 cout << "Capabilities in preference order is " << caps_str << endl;
1887 /* Add audio codecs in preference order first, then
1888 audio codecs without preference as allowed by mask */
1889 for (y = 0, x = -1; x < 32 + 32; ++x) {
1892 else if (y || (!(codec = ast_codec_pref_index(prefs, x)))) {
1899 if (!(caps & codec) || (alreadysent & codec) || !(codec & AST_FORMAT_AUDIO_MASK))
1901 alreadysent |= codec;
1902 format = ast_codec_pref_getsize(prefs, codec);
1903 frames_per_packet = (format.inc_ms ? format.cur_ms / format.inc_ms : format.cur_ms);
1904 max_frames_per_packet = (format.inc_ms ? format.max_ms / format.inc_ms : 0);
1907 case AST_FORMAT_SPEEX:
1908 /* Not real sure if Asterisk acutally supports all
1909 of the various different bit rates so add them
1910 all and figure it out later*/
1912 lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow2AudioCapability());
1913 lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow3AudioCapability());
1914 lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow4AudioCapability());
1915 lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow5AudioCapability());
1916 lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow6AudioCapability());
1919 case AST_FORMAT_G729A:
1920 AST_G729ACapability *g729aCap;
1921 AST_G729Capability *g729Cap;
1922 lastcap = localCapabilities.SetCapability(0, 0, g729aCap = new AST_G729ACapability(frames_per_packet));
1923 lastcap = localCapabilities.SetCapability(0, 0, g729Cap = new AST_G729Capability(frames_per_packet));
1924 if (max_frames_per_packet) {
1925 g729aCap->SetTxFramesInPacket(max_frames_per_packet);
1926 g729Cap->SetTxFramesInPacket(max_frames_per_packet);
1929 case AST_FORMAT_G723_1:
1930 AST_G7231Capability *g7231Cap;
1931 lastcap = localCapabilities.SetCapability(0, 0, g7231Cap = new AST_G7231Capability(frames_per_packet, TRUE));
1932 if (max_frames_per_packet)
1933 g7231Cap->SetTxFramesInPacket(max_frames_per_packet);
1934 lastcap = localCapabilities.SetCapability(0, 0, g7231Cap = new AST_G7231Capability(frames_per_packet, FALSE));
1935 if (max_frames_per_packet)
1936 g7231Cap->SetTxFramesInPacket(max_frames_per_packet);
1938 case AST_FORMAT_GSM:
1939 AST_GSM0610Capability *gsmCap;
1940 lastcap = localCapabilities.SetCapability(0, 0, gsmCap = new AST_GSM0610Capability(frames_per_packet));
1941 if (max_frames_per_packet)
1942 gsmCap->SetTxFramesInPacket(max_frames_per_packet);
1944 case AST_FORMAT_ULAW:
1945 AST_G711Capability *g711uCap;
1946 lastcap = localCapabilities.SetCapability(0, 0, g711uCap = new AST_G711Capability(format.cur_ms, H323_G711Capability::muLaw));
1948 g711uCap->SetTxFramesInPacket(format.max_ms);
1950 case AST_FORMAT_ALAW:
1951 AST_G711Capability *g711aCap;
1952 lastcap = localCapabilities.SetCapability(0, 0, g711aCap = new AST_G711Capability(format.cur_ms, H323_G711Capability::ALaw));
1954 g711aCap->SetTxFramesInPacket(format.max_ms);
1956 case AST_FORMAT_G726_AAL2:
1957 AST_CiscoG726Capability *g726Cap;
1958 lastcap = localCapabilities.SetCapability(0, 0, g726Cap = new AST_CiscoG726Capability(frames_per_packet));
1959 if (max_frames_per_packet)
1960 g726Cap->SetTxFramesInPacket(max_frames_per_packet);
1963 alreadysent &= ~codec;
1968 cap = new H323_UserInputCapability(H323_UserInputCapability::HookFlashH245);
1969 if (cap && cap->IsUsable(*this)) {
1971 lastcap = localCapabilities.SetCapability(0, lastcap, cap);
1973 delete cap; /* Capability is not usable */
1975 dtmfMode = dtmf_mode;
1977 cout << "DTMF mode is " << (int)dtmfMode << endl;
1981 if (dtmfMode == H323_DTMF_INBAND) {
1982 cap = new H323_UserInputCapability(H323_UserInputCapability::BasicString);
1983 if (cap && cap->IsUsable(*this)) {
1984 lastcap = localCapabilities.SetCapability(0, lastcap, cap);
1986 delete cap; /* Capability is not usable */
1987 sendUserInputMode = SendUserInputAsString;
1989 if ((dtmfMode & H323_DTMF_RFC2833) != 0) {
1990 cap = new H323_UserInputCapability(H323_UserInputCapability::SignalToneRFC2833);
1991 if (cap && cap->IsUsable(*this))
1992 lastcap = localCapabilities.SetCapability(0, lastcap, cap);
1994 dtmfMode |= H323_DTMF_SIGNAL;
1996 delete cap; /* Capability is not usable */
1999 if ((dtmfMode & H323_DTMF_CISCO) != 0) {
2000 /* Try Cisco's RTP DTMF relay too, but prefer RFC2833 or h245-signal */
2001 cap = new AST_CiscoDtmfCapability();
2002 if (cap && cap->IsUsable(*this)) {
2003 lastcap = localCapabilities.SetCapability(0, lastcap, cap);
2004 /* We cannot send Cisco RTP DTMFs, use h245-signal instead */
2005 dtmfMode |= H323_DTMF_SIGNAL;
2007 dtmfMode |= H323_DTMF_SIGNAL;
2009 delete cap; /* Capability is not usable */
2012 if ((dtmfMode & H323_DTMF_SIGNAL) != 0) {
2013 /* Cisco usually sends DTMF correctly only through h245-alphanumeric or h245-signal */
2014 cap = new H323_UserInputCapability(H323_UserInputCapability::SignalToneH245);
2015 if (cap && cap->IsUsable(*this))
2016 lastcap = localCapabilities.SetCapability(0, lastcap, cap);
2018 delete cap; /* Capability is not usable */
2020 sendUserInputMode = SendUserInputAsTone; /* RFC2833 transmission handled at Asterisk level */
2025 cout << "Allowed Codecs for " << GetCallToken() << " (" << GetSignallingChannel()->GetLocalAddress() << "):\n\t" << setprecision(2) << localCapabilities << endl;
2029 BOOL MyH323Connection::StartControlChannel(const H225_TransportAddress & h245Address)
2031 // Check that it is an IP address, all we support at the moment
2032 if (h245Address.GetTag() != H225_TransportAddress::e_ipAddress
2034 && h245Address.GetTag() != H225_TransportAddress::e_ip6Address
2037 PTRACE(1, "H225\tConnect of H245 failed: Unsupported transport");
2041 // Already have the H245 channel up.
2042 if (controlChannel != NULL)
2045 PIPSocket::Address addr;
2047 GetSignallingChannel()->GetLocalAddress().GetIpAndPort(addr, port);
2050 cout << "Using " << addr << " for outbound H.245 transport" << endl;
2051 controlChannel = new MyH323TransportTCP(endpoint, addr);
2053 controlChannel = new H323TransportTCP(endpoint);
2054 if (!controlChannel->SetRemoteAddress(h245Address)) {
2055 PTRACE(1, "H225\tCould not extract H245 address");
2056 delete controlChannel;
2057 controlChannel = NULL;
2060 if (!controlChannel->Connect()) {
2061 PTRACE(1, "H225\tConnect of H245 failed: " << controlChannel->GetErrorText());
2062 delete controlChannel;
2063 controlChannel = NULL;
2067 controlChannel->StartControlChannel(*this);
2072 void MyH323Connection::OnReceivedLocalCallHold(int linkedId)
2075 on_hold(GetCallReference(), (const char *)GetCallToken(), 1);
2078 void MyH323Connection::OnReceivedLocalCallRetrieve(int linkedId)
2081 on_hold(GetCallReference(), (const char *)GetCallToken(), 0);
2085 void MyH323Connection::MyHoldCall(BOOL isHold)
2087 if (((holdHandling & H323_HOLD_NOTIFY) != 0) || ((holdHandling & H323_HOLD_Q931ONLY) != 0)) {
2088 PBYTEArray x ((const BYTE *)(isHold ? "\xF9" : "\xFA"), 1);
2089 H323SignalPDU signal;
2090 signal.BuildNotify(*this);
2091 signal.GetQ931().SetIE((Q931::InformationElementCodes)39 /* Q931::NotifyIE */, x);
2093 cout << "Sending " << (isHold ? "HOLD" : "RETRIEVE") << " notification: " << signal << endl;
2094 if ((holdHandling & H323_HOLD_Q931ONLY) != 0) {
2096 signal.GetQ931().RemoveIE(Q931::UserUserIE);
2097 signal.GetQ931().Encode(rawData);
2098 signallingChannel->WritePDU(rawData);
2100 WriteSignalPDU(signal);
2103 if ((holdHandling & H323_HOLD_H450) != 0) {
2105 h4504handler->HoldCall(TRUE);
2106 else if (IsLocalHold())
2107 h4504handler->RetrieveCall();
2113 /* MyH323_ExternalRTPChannel */
2114 MyH323_ExternalRTPChannel::MyH323_ExternalRTPChannel(MyH323Connection & connection,
2115 const H323Capability & capability,
2116 Directions direction,
2118 : H323_ExternalRTPChannel::H323_ExternalRTPChannel(connection, capability, direction, id)
2120 struct rtp_info *info;
2122 /* Determine the Local (A side) IP Address and port */
2123 info = on_external_rtp_create(connection.GetCallReference(), (const char *)connection.GetCallToken());
2125 cout << "\tERROR: on_external_rtp_create failure" << endl;
2128 localIpAddr = info->addr;
2129 localPort = info->port;
2130 /* tell the H.323 stack */
2131 SetExternalAddress(H323TransportAddress(localIpAddr, localPort), H323TransportAddress(localIpAddr, localPort + 1));
2132 /* clean up allocated memory */
2136 /* Get the payload code */
2137 OpalMediaFormat format(capability.GetFormatName(), FALSE);
2138 payloadCode = format.GetPayloadType();
2141 MyH323_ExternalRTPChannel::~MyH323_ExternalRTPChannel()
2144 cout << "\tExternalRTPChannel Destroyed" << endl;
2148 BOOL MyH323_ExternalRTPChannel::Start(void)
2150 /* Call ancestor first */
2151 if (!H323_ExternalRTPChannel::Start()) {
2156 cout << "\t\tExternal RTP Session Starting" << endl;
2157 cout << "\t\tRTP channel id " << sessionID << " parameters:" << endl;
2160 /* Collect the remote information */
2161 H323_ExternalRTPChannel::GetRemoteAddress(remoteIpAddr, remotePort);
2164 cout << "\t\t-- remoteIpAddress: " << remoteIpAddr << endl;
2165 cout << "\t\t-- remotePort: " << remotePort << endl;
2166 cout << "\t\t-- ExternalIpAddress: " << localIpAddr << endl;
2167 cout << "\t\t-- ExternalPort: " << localPort << endl;
2169 /* Notify Asterisk of remote RTP information */
2170 on_start_rtp_channel(connection.GetCallReference(), (const char *)remoteIpAddr.AsString(), remotePort,
2171 (const char *)connection.GetCallToken(), (int)payloadCode);
2175 BOOL MyH323_ExternalRTPChannel::OnReceivedAckPDU(const H245_H2250LogicalChannelAckParameters & param)
2178 cout << " MyH323_ExternalRTPChannel::OnReceivedAckPDU" << endl;
2181 if (H323_ExternalRTPChannel::OnReceivedAckPDU(param)) {
2182 GetRemoteAddress(remoteIpAddr, remotePort);
2184 cout << " -- remoteIpAddress: " << remoteIpAddr << endl;
2185 cout << " -- remotePort: " << remotePort << endl;
2187 on_start_rtp_channel(connection.GetCallReference(), (const char *)remoteIpAddr.AsString(),
2188 remotePort, (const char *)connection.GetCallToken(), (int)payloadCode);
2195 MyH4504Handler::MyH4504Handler(MyH323Connection &_conn, H450xDispatcher &_disp)
2196 :H4504Handler(_conn, _disp)
2201 void MyH4504Handler::OnReceivedLocalCallHold(int linkedId)
2205 conn->OnReceivedLocalCallHold(linkedId);
2210 void MyH4504Handler::OnReceivedLocalCallRetrieve(int linkedId)
2214 conn->OnReceivedLocalCallRetrieve(linkedId);
2221 /** IMPLEMENTATION OF C FUNCTIONS */
2224 * The extern "C" directive takes care for
2225 * the ANSI-C representation of linkable symbols
2230 int h323_end_point_exist(void)
2238 void h323_end_point_create(void)
2241 logstream = new PAsteriskLog();
2242 localProcess = new MyProcess();
2243 localProcess->Main();
2246 void h323_gk_urq(void)
2248 if (!h323_end_point_exist()) {
2249 cout << " ERROR: [h323_gk_urq] No Endpoint, this is bad" << endl;
2252 endPoint->RemoveGatekeeper();
2255 void h323_debug(int flag, unsigned level)
2258 PTrace:: SetLevel(level);
2260 PTrace:: SetLevel(0);
2264 /** Installs the callback functions on behalf of the PBX application */
2265 void h323_callback_register(setup_incoming_cb ifunc,
2266 setup_outbound_cb sfunc,
2269 clear_con_cb clfunc,
2270 chan_ringing_cb rfunc,
2271 con_established_cb efunc,
2272 receive_digit_cb dfunc,
2273 answer_call_cb acfunc,
2275 rfc2833_cb dtmffunc,
2276 hangup_cb hangupfunc,
2277 setcapabilities_cb capabilityfunc,
2278 setpeercapabilities_cb peercapabilityfunc,
2281 on_incoming_call = ifunc;
2282 on_outgoing_call = sfunc;
2283 on_external_rtp_create = rtpfunc;
2284 on_start_rtp_channel = lfunc;
2285 on_connection_cleared = clfunc;
2286 on_chan_ringing = rfunc;
2287 on_connection_established = efunc;
2288 on_receive_digit = dfunc;
2289 on_answer_call = acfunc;
2290 on_progress = pgfunc;
2291 on_set_rfc2833_payload = dtmffunc;
2292 on_hangup = hangupfunc;
2293 on_setcapabilities = capabilityfunc;
2294 on_setpeercapabilities = peercapabilityfunc;
2299 * Add capability to the capability table of the end point.
2301 int h323_set_capabilities(const char *token, int cap, int dtmf_mode, struct ast_codec_pref *prefs, int pref_codec)
2303 MyH323Connection *conn;
2305 if (!h323_end_point_exist()) {
2306 cout << " ERROR: [h323_set_capablities] No Endpoint, this is bad" << endl;
2309 if (!token || !*token) {
2310 cout << " ERROR: [h323_set_capabilities] Invalid call token specified." << endl;
2314 PString myToken(token);
2315 conn = (MyH323Connection *)endPoint->FindConnectionWithLock(myToken);
2317 cout << " ERROR: [h323_set_capabilities] Unable to find connection " << token << endl;
2320 conn->SetCapabilities((/*conn->bridging ? conn->redir_capabilities :*/ cap), dtmf_mode, prefs, pref_codec);
2326 /** Start the H.323 listener */
2327 int h323_start_listener(int listenPort, struct sockaddr_in bindaddr)
2330 if (!h323_end_point_exist()) {
2331 cout << "ERROR: [h323_start_listener] No Endpoint, this is bad!" << endl;
2335 PIPSocket::Address interfaceAddress(bindaddr.sin_addr);
2339 /** H.323 listener */
2340 H323ListenerTCP *tcpListener;
2341 tcpListener = new H323ListenerTCP(*endPoint, interfaceAddress, (WORD)listenPort);
2342 if (!endPoint->StartListener(tcpListener)) {
2343 cout << "ERROR: Could not open H.323 listener port on " << ((H323ListenerTCP *) tcpListener)->GetListenerPort() << endl;
2347 cout << " == H.323 listener started" << endl;
2351 int h323_set_alias(struct oh323_alias *alias)
2355 PString h323id(alias->name);
2356 PString e164(alias->e164);
2359 if (!h323_end_point_exist()) {
2360 cout << "ERROR: [h323_set_alias] No Endpoint, this is bad!" << endl;
2364 cout << "== Adding alias \"" << h323id << "\" to endpoint" << endl;
2365 endPoint->AddAliasName(h323id);
2366 endPoint->RemoveAliasName(localProcess->GetUserName());
2368 if (!e164.IsEmpty()) {
2369 cout << "== Adding E.164 \"" << e164 << "\" to endpoint" << endl;
2370 endPoint->AddAliasName(e164);
2372 if (strlen(alias->prefix)) {
2373 p = prefix = strdup(alias->prefix);
2374 while((num = strsep(&p, ",")) != (char *)NULL) {
2375 cout << "== Adding Prefix \"" << num << "\" to endpoint" << endl;
2376 endPoint->SupportedPrefixes += PString(num);
2377 endPoint->SetGateway();
2385 void h323_set_id(char *id)
2390 cout << " == Using '" << h323id << "' as our H.323ID for this call" << endl;
2393 endPoint->SetLocalUserName(h323id);
2396 void h323_show_tokens(void)
2398 cout << "Current call tokens: " << setprecision(2) << endPoint->GetAllConnections() << endl;
2401 /** Establish Gatekeeper communiations, if so configured,
2402 * register aliases for the H.323 endpoint to respond to.
2404 int h323_set_gk(int gatekeeper_discover, char *gatekeeper, char *secret)
2406 PString gkName = PString(gatekeeper);
2407 PString pass = PString(secret);
2408 H323TransportUDP *rasChannel;
2410 if (!h323_end_point_exist()) {
2411 cout << "ERROR: [h323_set_gk] No Endpoint, this is bad!" << endl;
2416 cout << "Error: Gatekeeper cannot be NULL" << endl;
2419 if (strlen(secret)) {
2420 endPoint->SetGatekeeperPassword(pass);
2422 if (gatekeeper_discover) {
2423 /* discover the gk using multicast */
2424 if (endPoint->DiscoverGatekeeper(new MyH323TransportUDP(*endPoint))) {
2425 cout << "== Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
2427 cout << "Warning: Could not find a gatekeeper." << endl;
2431 rasChannel = new MyH323TransportUDP(*endPoint);
2434 cout << "Error: No RAS Channel, this is bad" << endl;
2437 if (endPoint->SetGatekeeper(gkName, rasChannel)) {
2438 cout << "== Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
2440 cout << "Error registering with gatekeeper \"" << gkName << "\". " << endl;
2441 /* XXX Maybe we should fire a new thread to attempt to re-register later and not kill asterisk here? */
2448 /** Send a DTMF tone over the H323Connection with the
2451 void h323_send_tone(const char *call_token, char tone)
2453 if (!h323_end_point_exist()) {
2454 cout << "ERROR: [h323_send_tone] No Endpoint, this is bad!" << endl;
2457 PString token = PString(call_token);
2458 endPoint->SendUserTone(token, tone);
2461 /** Make a call to the remote endpoint.
2463 int h323_make_call(char *dest, call_details_t *cd, call_options_t *call_options)
2469 if (!h323_end_point_exist()) {
2473 res = endPoint->MyMakeCall(host, token, &cd->call_reference, call_options);
2474 memcpy((char *)(cd->call_token), (const unsigned char *)token, token.GetLength());
2478 int h323_clear_call(const char *call_token, int cause)
2480 H225_ReleaseCompleteReason dummy;
2481 H323Connection::CallEndReason r = H323Connection::EndedByLocalUser;
2482 MyH323Connection *connection;
2483 const PString currentToken(call_token);
2485 if (!h323_end_point_exist()) {
2490 r = H323TranslateToCallEndReason((Q931::CauseValues)(cause), dummy);
2493 connection = (MyH323Connection *)endPoint->FindConnectionWithLock(currentToken);
2495 connection->SetCause(cause);
2496 connection->SetCallEndReason(r);
2497 connection->Unlock();
2499 endPoint->ClearCall(currentToken, r);
2503 /* Send Alerting PDU to H.323 caller */
2504 int h323_send_alerting(const char *token)
2506 const PString currentToken(token);
2507 H323Connection * connection;
2510 cout << "\tSending alerting" << endl;
2512 connection = endPoint->FindConnectionWithLock(currentToken);
2514 cout << "No connection found for " << token << endl;
2517 connection->AnsweringCall(H323Connection::AnswerCallPending);
2518 connection->Unlock();
2522 /* Send Progress PDU to H.323 caller */
2523 int h323_send_progress(const char *token)
2525 const PString currentToken(token);
2526 H323Connection * connection;
2528 connection = endPoint->FindConnectionWithLock(currentToken);
2530 cout << "No connection found for " << token << endl;
2534 ((MyH323Connection *)connection)->MySendProgress();
2536 connection->AnsweringCall(H323Connection::AnswerCallDeferredWithMedia);
2538 connection->Unlock();
2542 /** This function tells the h.323 stack to either
2543 answer or deny an incoming call */
2544 int h323_answering_call(const char *token, int busy)
2546 const PString currentToken(token);
2547 H323Connection * connection;
2549 connection = endPoint->FindConnectionWithLock(currentToken);
2552 cout << "No connection found for " << token << endl;
2557 cout << "\tAnswering call " << token << endl;
2559 connection->AnsweringCall(H323Connection::AnswerCallNow);
2562 cout << "\tdenying call " << token << endl;
2564 connection->AnsweringCall(H323Connection::AnswerCallDenied);
2566 connection->Unlock();
2570 int h323_soft_hangup(const char *data)
2572 PString token(data);
2574 cout << "Soft hangup" << endl;
2575 result = endPoint->ClearCall(token);
2579 /* alas, this doesn't work :( */
2580 void h323_native_bridge(const char *token, const char *them, char *capability)
2582 H323Channel *channel;
2583 MyH323Connection *connection = (MyH323Connection *)endPoint->FindConnectionWithLock(token);
2586 cout << "ERROR: No connection found, this is bad" << endl;
2590 cout << "Native Bridge: them [" << them << "]" << endl;
2592 channel = connection->FindChannel(connection->sessionId, TRUE);
2593 connection->bridging = TRUE;
2594 connection->CloseLogicalChannelNumber(channel->GetNumber());
2596 connection->Unlock();
2601 int h323_hold_call(const char *token, int is_hold)
2603 MyH323Connection *conn = (MyH323Connection *)endPoint->FindConnectionWithLock(token);
2605 cout << "ERROR: No connection found, this is bad" << endl;
2608 conn->MyHoldCall((BOOL)is_hold);
2615 void h323_end_process(void)
2618 endPoint->ClearAllCalls();
2619 endPoint->RemoveListener(NULL);
2624 delete localProcess;
2625 localProcess = NULL;
2626 close(_timerChangePipe[0]);
2627 close(_timerChangePipe[1]);
2630 PTrace::SetLevel(0);
2631 PTrace::SetStream(&cout);