aboutsummaryrefslogtreecommitdiffstats
path: root/channels/h323
diff options
context:
space:
mode:
authorjeremy <jeremy@f38db490-d61c-443f-a65b-d21fe96a405b>2003-03-31 07:13:36 +0000
committerjeremy <jeremy@f38db490-d61c-443f-a65b-d21fe96a405b>2003-03-31 07:13:36 +0000
commite87ec82e085f525e025784b59b7c6c963688e876 (patch)
treeb1f49afdb738ce50543831306c4bff41e894c05f /channels/h323
parentd53be73ebe9f97b545594f1c2db16926aaddf524 (diff)
first commit of chan_h323
git-svn-id: http://svn.digium.com/svn/asterisk/trunk@724 f38db490-d61c-443f-a65b-d21fe96a405b
Diffstat (limited to 'channels/h323')
-rwxr-xr-xchannels/h323/ChangeLog39
-rwxr-xr-xchannels/h323/Makefile53
-rwxr-xr-xchannels/h323/README55
-rwxr-xr-xchannels/h323/TODO14
-rwxr-xr-xchannels/h323/ast_h323.cpp1018
-rwxr-xr-xchannels/h323/ast_h323.h249
-rwxr-xr-xchannels/h323/chan_h323.c1717
-rwxr-xr-xchannels/h323/chan_h323.h186
-rwxr-xr-xchannels/h323/h323.conf.sample138
9 files changed, 3469 insertions, 0 deletions
diff --git a/channels/h323/ChangeLog b/channels/h323/ChangeLog
new file mode 100755
index 000000000..83bdff31e
--- /dev/null
+++ b/channels/h323/ChangeLog
@@ -0,0 +1,39 @@
+Build
+0.1.0
+ -- Intergration into the mainline Asterisk codebase
+ -- Remove reduandant debug info
+ -- Add Caller*id support
+ -- Inband DTMF
+ -- Retool port usage (to avoid possible seg fault condition)
+0.0.6
+ -- Configurable support for user-input (DTMF)
+ -- Reworked Gatekeeper support
+ -- Native bridging (but is still broken, help!)
+ -- Locally implement a non-broken G.723.1 Capability
+ -- Utilize the cleaner RTP method implemented by Mark
+ -- AllowGkRouted, thanks to Panny from http://hotlinks.co.uk
+ -- Clened up inbound call flow
+ -- Prefix, E.164 and Gateway support
+ -- Multi-homed support
+ -- Killed more seg's
+0.0.5
+ -- Added H.323 Alias support
+ -- Clened up inbound call flow
+ -- Fixed RTP port logic
+ -- Stomped on possible seg fault conditions thanks to Iain Stevenson
+0.0.4
+ -- Fixed one-way audio on inbound calls. Found
+ race condition in monitor thread.
+
+0.0.3
+ -- Changed name to chan_h323
+ -- Also renamed file names to futher avoid confusion
+
+0.0.2
+ -- First public offering
+ -- removed most hardcoded values
+ -- lots of changes to alias/exension operation
+
+0.0.1
+ -- initial build, lots of hardcoded crap
+ -- Proof of concept for External RTP
diff --git a/channels/h323/Makefile b/channels/h323/Makefile
new file mode 100755
index 000000000..35745004d
--- /dev/null
+++ b/channels/h323/Makefile
@@ -0,0 +1,53 @@
+# include the Makefile of OpenH323
+
+ifndef OPENH323DIR
+OPENH323DIR=$(HOME)/openh323
+endif
+
+ifndef PWLIBDIR
+PWLIBDIR=$(HOME)/pwlib
+endif
+
+ifndef ASTERISKDIR
+ASTERISKDIR= /usr/lib/asterisk/modules
+endif
+
+
+CFLAGS += -DNDEBUG -DDO_CRASH -DDEBUG_THREADS
+CFLAGS = -pipe -Wall -fPIC -Wmissing-prototypes -Wmissing-declarations
+CFLAGS += -DP_LINUX -D_REENTRANT -D_GNU_SOURCE
+# This needs to be updated to deal with more than just little endian machines
+CFLAGS += -march=$(shell uname -m) -DPBYTE_ORDER=PLITTLE_ENDIAN
+CFLAGS += -DP_HAS_SEMAPHORES -DP_SSL -DP_PTHREADS
+CFLAGS += -DPHAS_TEMPLATES -DPTRACING -DP_USE_PRAGMA
+CFLAGS += -I$(PWLIBDIR)/include/ptlib/unix -I$(PWLIBDIR)/include
+CFLAGS += -I$(OPENH323DIR)/include -Wno-missing-prototypes -Wno-missing-declarations
+
+
+all: chan_h323.so
+
+noshared: chan_h323_s.so
+optnoshared: chan_h323_s.so
+debug: chan_h323_d.so
+
+
+install: all
+ install -m 755 chan_h323.so $(ASTERISKDIR)
+
+chan_h323.o: chan_h323.c
+ $(CC) -g -c -o $@ $(CFLAGS) $<
+ast_h323.o: ast_h323.cpp
+ g++ -g -c -o $@ $(CFLAGS) $<
+
+chan_h323.so: chan_h323.o ast_h323.o
+ g++ -shared -Xlinker -x -o chan_h323.so chan_h323.o ast_h323.o -L$(PWLIBDIR)/lib -lpt_linux_x86_r -L$(OPENH323DIR)/lib -lh323_linux_x86_r -L/usr/lib -lpthread -ldl -lcrypto -lssl -lexpat
+
+chan_h323_d.so: chan_h323.o ast_h323.o
+ g++ -shared -Xlinker -x -o chan_h323.so chan_h323.o ast_h323.o -L$(PWLIBDIR)/lib -lpt_linux_x86_d -L$(OPENH323DIR)/lib -lh323_linux_x86_d -L/usr/lib -lpthread -ldl -lcrypto -lssl -lexpat
+
+chan_h323_s.so: chan_h323.o ast_h323.o
+ g++ -shared -Xlinker -x -o chan_h323.so chan_h323.o ast_h323.o -L$(PWLIBDIR)/lib -lpt_linux_x86_r_s -L$(OPENH323DIR)/lib -lh323_linux_x86_r_s -L/usr/lib -lpthread -ldl -lcrypto -lssl -lexpat
+clean:
+ rm -f *.o *.so core.*
+
+
diff --git a/channels/h323/README b/channels/h323/README
new file mode 100755
index 000000000..c56368f3e
--- /dev/null
+++ b/channels/h323/README
@@ -0,0 +1,55 @@
+
+ Open H.323 Channel Driver for Asterisk
+ By Jeremy McNamara
+ The NuFone Network
+
+ First public release on November 10th, 2002
+
+
+ Developed using: RedHat 7.2/7.3/8.0
+ Open H.323 v1.11.8
+ PWLib v1.4.12
+ GCC 2.96/3.1
+
+ Dependancies: openssl-0.9.6b
+ openssl-devel-0.9.6b
+ expat-1.95
+
+Notice: Whatever you do, DO NOT USE distrubution specific installs
+of Open H.323 and PWLib. Check everything out of CVS. If you dont know
+how to deal with cvs, learn. Also, if you are not using the listed
+versions of Open H.323 or PWlib you are on your own, sorry. Older versions
+will NOT work, but newer versions ~should~ work.
+
+We have implemented this driver using Asterisk's RTP stack insted of trying
+to implement a psudo sound card driver.
+
+If you have trouble please contact 'JerJer' in #Asterisk on irc.freenode.net or
+send and email to jj@indie.org
+
+If you happen to be lucky enough to segfault this code please run a backtrace
+and send me the gory details. Segmentation faults are not tolerated!
+
+bt example:
+
+# /usr/sbin/asterisk -vvvgc
+...
+[chan_h323.so]
+Segmentation Fault (core dumped)
+
+# ls core.*
+core.1976
+
+# gdb /usr/sbin/asterisk core.1976
+...
+(gdb) bt
+
+Send whatever shows up right after the 'bt'
+
+
+Also, a full debug screen output is almost needed. Make sure you are in the full console mode (-c) and turn on 'h.323
+debug'. A nice way to capture everything is to use the utility called 'script' (man script)
+
+
+Jeremy McNamara, President
+The NuFone Network
diff --git a/channels/h323/TODO b/channels/h323/TODO
new file mode 100755
index 000000000..1514aef59
--- /dev/null
+++ b/channels/h323/TODO
@@ -0,0 +1,14 @@
+The NuFone Network's Open H.323 Channel Driver for Asterisk
+
+ TODO:
+
+ - Fix Gatekeeper re-registration seg (HELP)
+
+ - Track down why calls to invalid extensions always
+ get sent to 's' in context 'default'
+
+ - H.323 Native Bridging
+
+ - Gatekeeping support (started)
+
+
diff --git a/channels/h323/ast_h323.cpp b/channels/h323/ast_h323.cpp
new file mode 100755
index 000000000..831092fdd
--- /dev/null
+++ b/channels/h323/ast_h323.cpp
@@ -0,0 +1,1018 @@
+/*
+ * ast_h323.cpp
+ *
+ * OpenH323 Channel Driver for ASTERISK PBX.
+ * By Jeremy McNamara
+ * For The NuFone Network
+ *
+ * This code has been derived from code created by
+ * Michael Manousos and Mark Spencer
+ *
+ * This file is part of the chan_h323 driver for Asterisk
+ *
+ * chan_h323 is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * chan_h323 is distributed WITHOUT ANY WARRANTY; without even
+ * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ */
+#include "ast_h323.h"
+#include "h323t38.h"
+
+
+/* PWlib Required Components */
+#define MAJOR_VERSION 0
+#define MINOR_VERSION 1
+#define BUILD_TYPE ReleaseCode
+#define BUILD_NUMBER 0
+
+/** Counter for the number of connections */
+int channelsOpen;
+
+/* DTMF Mode */
+int mode = H323_DTMF_RFC2833;
+
+/** Options for connections creation */
+BOOL noFastStart;
+BOOL noH245Tunnelling;
+BOOL noSilenceSuppression;
+WORD jitter;
+
+/**
+ * We assume that only one endPoint should exist.
+ * The application cannot run the h323_end_point_create() more than once
+ * FIXME: Singleton this, for safety
+ */
+MyH323EndPoint *endPoint = NULL;
+
+/** PWLib entry point */
+MyProcess *localProcess = NULL;
+
+/** H.323 listener */
+H323ListenerTCP *tcpListener;
+
+MyProcess::MyProcess(): PProcess("The NuFone Network's", "H.323 Channel Driver for Asterisk",
+ MAJOR_VERSION, MINOR_VERSION, BUILD_TYPE, BUILD_NUMBER)
+{
+ Resume();
+}
+
+MyProcess::~MyProcess()
+{
+ cout << " == PWLib proces going down." << endl;
+ delete endPoint;
+ endPoint = NULL;
+}
+
+void MyProcess::Main()
+{
+ cout << " == Creating H.323 Endpoint" << endl;
+ endPoint = new MyH323EndPoint();
+ PTrace::Initialise(0, NULL, PTrace::Timestamp | PTrace::Thread | PTrace::FileAndLine);
+}
+
+ClearCallThread::ClearCallThread(const char *tc) : PThread(10000, PThread::NoAutoDeleteThread)
+{
+ token = tc;
+ Resume();
+}
+
+ClearCallThread::~ClearCallThread()
+{
+ if (h323debug)
+ cout << " == ClearCall thread going down." << endl;
+ return;
+}
+
+void ClearCallThread::Main()
+{
+ endPoint->ClearCall(token);
+ return;
+}
+
+
+#define H323_NAME OPAL_G7231_6k3"{sw}"
+
+H323_REGISTER_CAPABILITY(H323_G7231Capability, H323_NAME);
+
+H323_G7231Capability::H323_G7231Capability(BOOL annexA_)
+ : H323AudioCapability(7, 4)
+{
+ annexA = annexA_;
+}
+
+PObject::Comparison H323_G7231Capability::Compare(const PObject & obj) const
+{
+ Comparison result = H323AudioCapability::Compare(obj);
+ if (result != EqualTo)
+ return result;
+
+ PINDEX otherAnnexA = ((const H323_G7231Capability &)obj).annexA;
+ if (annexA < otherAnnexA)
+ return LessThan;
+ if (annexA > otherAnnexA)
+ return GreaterThan;
+ return EqualTo;
+}
+
+PObject * H323_G7231Capability::Clone() const
+{
+ return new H323_G7231Capability(*this);
+}
+
+
+PString H323_G7231Capability::GetFormatName() const
+{
+ return H323_NAME;
+}
+
+
+unsigned H323_G7231Capability::GetSubType() const
+{
+ return H245_AudioCapability::e_g7231;
+}
+
+
+BOOL H323_G7231Capability::OnSendingPDU(H245_AudioCapability & cap,
+ unsigned packetSize) const
+{
+ cap.SetTag(H245_AudioCapability::e_g7231);
+
+ H245_AudioCapability_g7231 & g7231 = cap;
+ g7231.m_maxAl_sduAudioFrames = packetSize;
+ g7231.m_silenceSuppression = annexA;
+
+ return TRUE;
+}
+
+
+BOOL H323_G7231Capability::OnReceivedPDU(const H245_AudioCapability & cap,
+ unsigned & packetSize)
+{
+ if (cap.GetTag() != H245_AudioCapability::e_g7231)
+ return FALSE;
+
+ const H245_AudioCapability_g7231 & g7231 = cap;
+ packetSize = g7231.m_maxAl_sduAudioFrames;
+ annexA = g7231.m_silenceSuppression;
+
+ return TRUE;
+}
+
+
+H323Codec * H323_G7231Capability::CreateCodec(H323Codec::Direction direction) const
+{
+ return NULL;
+}
+
+/** MyH323EndPoint
+ * The fullAddress parameter is used directly in the MakeCall method so
+ * the General form for the fullAddress argument is :
+ * [alias@][transport$]host[:port]
+ * default values: alias = the same value as host.
+ * transport = ip.
+ * port = 1720.
+ */
+int MyH323EndPoint::MakeCall(const PString & dest, PString & token,
+ unsigned int *callReference, unsigned int port)
+{
+ PString fullAddress;
+
+ /* Determine whether we are using a gatekeeper or not. */
+ if (GetGatekeeper() != NULL) {
+ fullAddress = dest;
+ if (h323debug)
+ cout << " -- Making call to " << fullAddress << " using gatekeeper." << endl;
+ } else {
+ fullAddress = dest; /* host */
+ fullAddress += psprintf(":%i", port); /* host:port */
+ if (h323debug)
+ cout << " -- Making call to " << fullAddress << "." << endl;
+ }
+
+ if (!H323EndPoint::MakeCall(fullAddress, token)) {
+ if (h323debug)
+ cout << "Error making call to \"" << fullAddress << '"' << endl;
+ return 1;
+ }
+
+ MyH323Connection * connection = (MyH323Connection *)FindConnectionWithLock(token);
+
+ if (connection != NULL) {
+ *callReference = connection->GetCallReference();
+ connection->Unlock();
+ }
+
+ if (h323debug) {
+ cout << " -- " << GetLocalUserName() << " is calling host " << fullAddress << endl;
+ cout << " -- " << "Call token is " << (const char *)token << endl;
+ cout << " -- Call reference is " << *callReference << endl;
+ }
+ return 0;
+}
+
+void MyH323EndPoint::SetEndpointTypeInfo( H225_EndpointType & info ) const
+{
+ H323EndPoint::SetEndpointTypeInfo(info);
+ info.m_gateway.IncludeOptionalField(H225_GatewayInfo::e_protocol);
+ info.m_gateway.m_protocol.SetSize(1);
+ H225_SupportedProtocols &protocol=info.m_gateway.m_protocol[0];
+ protocol.SetTag(H225_SupportedProtocols::e_voice);
+ PINDEX as=SupportedPrefixes.GetSize();
+ ((H225_VoiceCaps &)protocol).m_supportedPrefixes.SetSize(as);
+ for (PINDEX p=0; p<as; p++) {
+ H323SetAliasAddress(SupportedPrefixes[p], ((H225_VoiceCaps &)protocol).m_supportedPrefixes[p].m_prefix);
+ }
+}
+
+void MyH323EndPoint::SetGateway(void)
+{
+ terminalType = e_GatewayOnly;
+}
+
+H323Capabilities MyH323EndPoint::GetCapabilities(void)
+{
+ return capabilities;
+}
+
+BOOL MyH323EndPoint::ClearCall(const PString & token)
+{
+ if (h323debug)
+ cout << " -- ClearCall: Request to clear call with token " << token << endl;
+ return H323EndPoint::ClearCall(token);
+}
+
+void MyH323EndPoint::SendUserTone(const PString &token, char tone)
+{
+ H323Connection *connection = NULL;
+
+ connection = FindConnectionWithLock(token);
+ if (connection != NULL) {
+ connection->SendUserInputTone(tone, 500);
+ connection->Unlock();
+ }
+}
+
+void MyH323EndPoint::OnClosedLogicalChannel(H323Connection & connection, const H323Channel & channel)
+{
+ channelsOpen--;
+ if (h323debug)
+ cout << " channelsOpen = " << channelsOpen << endl;
+ H323EndPoint::OnClosedLogicalChannel(connection, channel);
+}
+
+void MyH323EndPoint::OnConnectionEstablished(H323Connection & connection, const PString & estCallToken)
+{
+ if (h323debug)
+ cout << " -- Connection Established with \"" << connection.GetRemotePartyName() << "\"" << endl;
+ on_connection_established(connection.GetCallReference());
+}
+
+/** OnConnectionCleared callback function is called upon the dropping of an established
+ * H323 connection.
+ */
+void MyH323EndPoint::OnConnectionCleared(H323Connection & connection, const PString & clearedCallToken)
+{
+ PString remoteName = connection.GetRemotePartyName();
+
+ call_details_t cd;
+
+ cd.call_reference = connection.GetCallReference();
+ cd.call_token = (const char *)connection.GetCallToken();
+ cd.call_source_aliases = (const char *)connection.GetRemotePartyName();
+
+ /* Convert complex strings */
+ char *s;
+ if ((s = strchr(cd.call_source_aliases, ' ')) != NULL)
+ *s = '\0';
+
+ /* Invoke the PBX application registered callback */
+ on_connection_cleared(cd);
+
+ switch (connection.GetCallEndReason()) {
+ case H323Connection::EndedByCallForwarded :
+ break;
+ case H323Connection::EndedByRemoteUser :
+ if (h323debug)
+ cout << " -- " << remoteName << " has cleared the call" << endl;
+ break;
+ case H323Connection::EndedByCallerAbort :
+ if (h323debug)
+ cout << " -- " << remoteName << " has stopped calling" << endl;
+ break;
+ case H323Connection::EndedByRefusal :
+ if (h323debug)
+ cout << " -- " << remoteName << " did not accept your call" << endl;
+ break;
+ case H323Connection::EndedByRemoteBusy :
+ if (h323debug)
+ cout << " -- " << remoteName << " was busy" << endl;
+ break;
+ case H323Connection::EndedByRemoteCongestion :
+ if (h323debug)
+ cout << " -- Congested link to " << remoteName << endl;
+ break;
+ case H323Connection::EndedByNoAnswer :
+ if (h323debug)
+ cout << " -- " << remoteName << " did not answer your call" << endl;
+ break;
+ case H323Connection::EndedByTransportFail :
+ if (h323debug)
+ cout << " -- Call with " << remoteName << " ended abnormally" << endl;
+ break;
+ case H323Connection::EndedByCapabilityExchange :
+ if (h323debug)
+ cout << " -- Could not find common codec with " << remoteName << endl;
+ break;
+ case H323Connection::EndedByNoAccept :
+ if (h323debug)
+ cout << " -- Did not accept incoming call from " << remoteName << endl;
+ break;
+ case H323Connection::EndedByAnswerDenied :
+ if (h323debug)
+ cout << " -- Refused incoming call from " << remoteName << endl;
+ break;
+ case H323Connection::EndedByNoUser :
+ if (h323debug)
+ cout << " -- Gatekeeper could not find user " << remoteName << endl;
+ break;
+ case H323Connection::EndedByNoBandwidth :
+ if (h323debug)
+ cout << " -- Call to " << remoteName << " aborted, insufficient bandwidth." << endl;
+ break;
+ case H323Connection::EndedByUnreachable :
+ if (h323debug)
+ cout << " -- " << remoteName << " could not be reached." << endl;
+ break;
+ case H323Connection::EndedByHostOffline :
+ if (h323debug)
+ cout << " -- " << remoteName << " is not online." << endl;
+ break;
+ case H323Connection::EndedByNoEndPoint :
+ if (h323debug)
+ cout << " -- No phone running for " << remoteName << endl;
+ break;
+ case H323Connection::EndedByConnectFail :
+ if (h323debug)
+ cout << " -- Transport error calling " << remoteName << endl;
+ break;
+ default :
+ if (h323debug)
+ cout << " -- Call with " << remoteName << " completed" << endl;
+ }
+ if(connection.IsEstablished())
+ if (h323debug)
+ cout << " -- Call duration " << setprecision(0) << setw(5) << (PTime() - connection.GetConnectionStartTime()) << endl;
+}
+
+
+H323Connection * MyH323EndPoint::CreateConnection(unsigned callReference, void *outbound)
+{
+ unsigned options = 0;
+
+ if (noFastStart)
+ options |= H323Connection::FastStartOptionDisable;
+
+ if (noH245Tunnelling)
+ options |= H323Connection::H245TunnelingOptionDisable;
+
+ return new MyH323Connection(*this, callReference, options, jitter);
+}
+
+
+/* MyH323Connection */
+MyH323Connection::MyH323Connection(MyH323EndPoint & ep,
+ unsigned callReference,
+ unsigned options,
+ WORD jitter): H323Connection(ep,
+ callReference,
+ options)
+{
+ remoteIpAddress = 0; // IP Address of remote endpoint
+ remotePort = 0; // remote endpoint Data port (control is dataPort+1)
+
+ if (h323debug)
+ cout << " == New H.323 Connection created." << endl;
+ return;
+}
+
+MyH323Connection::~MyH323Connection()
+{
+ if (h323debug)
+ cout << " == H.323 Connection deleted." << endl;
+ return;
+}
+
+H323Connection::AnswerCallResponse MyH323Connection::OnAnswerCall(const PString & caller,
+ const H323SignalPDU & /*setupPDU*/,
+ H323SignalPDU & /*connectPDU*/)
+{
+ /* The call will be answered later with "AnsweringCall()" function.
+ */
+ return H323Connection::AnswerCallAlertWithMedia;
+}
+
+BOOL MyH323Connection::OnAlerting(const H323SignalPDU & /*alertingPDU*/, const PString & username)
+{
+
+ if (h323debug)
+ cout << " -- Ringing phone for \"" << username << "\"" << endl;
+ return TRUE;
+}
+
+BOOL MyH323Connection::OnReceivedSignalSetup(const H323SignalPDU & setupPDU)
+{
+
+ if (h323debug)
+ cout << " -- Received SETUP message..." << endl;
+
+ call_details_t cd;
+
+ PString sourceE164;
+ PString destE164;
+ PString sourceAliases;
+ PString destAliases;
+ PString sourceIp;
+
+ PIPSocket::Address Ip;
+ WORD sourcePort;
+
+ sourceAliases = setupPDU.GetSourceAliases();
+ destAliases = setupPDU.GetDestinationAlias();
+
+ sourceE164 = "";
+ setupPDU.GetSourceE164(sourceE164);
+ destE164 = "";
+ setupPDU.GetDestinationE164(destE164);
+
+ /* Convert complex strings */
+ // FIXME: deal more than one source alias
+ char *s;
+ if ((s = strchr(sourceAliases, ' ')) != NULL)
+ *s = '\0';
+ if ((s = strchr(sourceAliases, '\t')) != NULL)
+ *s = '\0';
+ char *s1;
+ if ((s1 = strchr(destAliases, ' ')) != NULL)
+ *s1 = '\0';
+ if ((s1 = strchr(destAliases, '\t')) != NULL)
+ *s1 = '\0';
+
+ GetSignallingChannel()->GetRemoteAddress().GetIpAndPort(Ip, sourcePort);
+
+ sourceIp = Ip.AsString();
+
+ cd.call_reference = GetCallReference();
+ cd.call_token = (const char *)GetCallToken();
+ cd.call_source_aliases = (const char *)sourceAliases;
+ cd.call_dest_alias = (const char *)destAliases;
+ cd.call_source_e164 = (const char *)sourceE164;
+ cd.call_dest_e164 = (const char *)destE164;
+ cd.sourceIp = (const char *)sourceIp;
+
+ /* Notify Asterisk of the request */
+ int res = on_incoming_call(cd);
+
+ if (!res) {
+ if (h323debug)
+ cout << " -- Call Failed" << endl;
+ return FALSE;
+ }
+
+ return H323Connection::OnReceivedSignalSetup(setupPDU);
+}
+
+BOOL MyH323Connection::OnSendSignalSetup(H323SignalPDU & setupPDU)
+{
+ call_details_t cd;
+
+ if (h323debug)
+ cout << " -- Sending SETUP message" << endl;
+
+ sourceAliases = setupPDU.GetSourceAliases();
+ destAliases = setupPDU.GetDestinationAlias();
+
+ sourceE164 = "";
+ setupPDU.GetSourceE164(sourceE164);
+ destE164 = "";
+ setupPDU.GetDestinationE164(destE164);
+
+ /* Convert complex strings */
+ // FIXME: deal more than one source alias
+ char *s;
+ if ((s = strchr(sourceAliases, ' ')) != NULL)
+ *s = '\0';
+ if ((s = strchr(sourceAliases, '\t')) != NULL)
+ *s = '\0';
+ char *s1;
+ if ((s1 = strchr(destAliases, ' ')) != NULL)
+ *s1 = '\0';
+ if ((s1 = strchr(destAliases, '\t')) != NULL)
+ *s1 = '\0';
+
+ cd.call_reference = GetCallReference();
+ cd.call_token = (const char *)GetCallToken();
+ cd.call_source_aliases = (const char *)sourceAliases;
+ cd.call_dest_alias = (const char *)destAliases;
+ cd.call_source_e164 = (const char *)sourceE164;
+ cd.call_dest_e164 = (const char *)destE164;
+
+ int res = on_outgoing_call(cd);
+
+ if (!res) {
+ if (h323debug)
+ cout << " -- Call Failed" << endl;
+ return FALSE;
+ }
+
+ return H323Connection::OnSendSignalSetup(setupPDU);
+}
+
+void MyH323Connection::OnReceivedReleaseComplete(const H323SignalPDU & pdu)
+{
+ if (h323debug)
+ cout << " -- Received RELEASE COMPLETE message..." << endl;
+ return H323Connection::OnReceivedReleaseComplete(pdu);
+
+}
+
+BOOL MyH323Connection::OnClosingLogicalChannel(H323Channel & channel)
+{
+ if (h323debug)
+ cout << " -- Closing logical channel..." << endl;
+ return H323Connection::OnClosingLogicalChannel(channel);
+}
+
+
+void MyH323Connection::SendUserInputTone(char tone, unsigned duration)
+{
+ if (h323debug)
+ cout << " -- Sending user input tone (" << tone << ") to remote" << endl;
+
+ on_send_digit(GetCallReference(), tone);
+
+ H323Connection::SendUserInputTone(tone, duration);
+}
+
+void MyH323Connection::OnUserInputTone(char tone, unsigned duration, unsigned logicalChannel, unsigned rtpTimestamp)
+{
+ if (mode == H323_DTMF_INBAND) {
+ if (h323debug)
+ cout << " -- Received user input tone (" << tone << ") from remote" << endl;
+ on_send_digit(GetCallReference(), tone);
+ }
+ H323Connection::OnUserInputTone(tone, duration, logicalChannel, rtpTimestamp);
+}
+
+void MyH323Connection::OnUserInputString(const PString &value)
+{
+ if (mode == H323_DTMF_RFC2833) {
+ if (h323debug)
+ cout << " -- Received user input string (" << value << ") from remote." << endl;
+ on_send_digit(GetCallReference(), value[0]);
+ }
+}
+
+H323Channel * MyH323Connection::CreateRealTimeLogicalChannel(const H323Capability & capability,
+ H323Channel::Directions dir,
+ unsigned sessionID,
+ const H245_H2250LogicalChannelParameters * /*param*/)
+{
+ WORD port;
+
+ /* Establish the Local (A side) IP Address */
+ GetControlChannel().GetLocalAddress().GetIpAndPort(externalIpAddress, port);
+
+ /* Notify Asterisk of the request and get the port */
+ externalPort = on_create_connection(GetCallReference());
+
+ if (h323debug) {
+ cout << " =*= In CreateRealTimeLogicalChannel" << endl;
+ cout << " -- externalIpAddress: " << externalIpAddress << endl;
+ cout << " -- externalPort: " << externalPort << endl;
+ cout << " -- Direction: " << dir << endl;
+ }
+
+ return new H323_ExternalRTPChannel(*this, capability, dir, sessionID, externalIpAddress, externalPort);
+}
+
+/** This callback function is invoked once upon creation of each
+ * channel for an H323 session
+ */
+BOOL MyH323Connection::OnStartLogicalChannel(H323Channel & channel)
+{
+ if (h323debug) {
+ cout << " -- Started logical channel: ";
+ cout << ((channel.GetDirection()==H323Channel::IsTransmitter)?"sending ":((channel.GetDirection()==H323Channel::IsReceiver)?"receiving ":" "));
+ cout << (const char *)(channel.GetCapability()).GetFormatName() << endl;
+ }
+ // adjust the count of channels we have open
+ channelsOpen++;
+ if (h323debug)
+ cout << " -- channelsOpen = " << channelsOpen << endl;
+
+ H323_ExternalRTPChannel & external = (H323_ExternalRTPChannel &)channel;
+ external.GetRemoteAddress(remoteIpAddress, remotePort);
+
+ if (h323debug) {
+ cout << " -- remoteIpAddress: " << remoteIpAddress << endl;
+ cout << " -- remotePort: " << remotePort << endl;
+ cout << " -- ExternalIpAddress: " << externalIpAddress << endl;
+ cout << " -- ExternalPort: " << externalPort << endl;
+ }
+ /* Notify Asterisk of remote RTP information */
+ on_start_logical_channel(GetCallReference(), (const char *)remoteIpAddress.AsString(), remotePort);
+
+ return TRUE;
+}
+
+#if 0
+MyGatekeeperServer::MyGatekeeperServer(MyH323EndPoint & ep)
+ : H323GatekeeperServer(ep),
+ endpoint(ep)
+{
+}
+
+
+BOOL MyGatekeeperServer::Initialise()
+{
+ PINDEX i;
+
+ PWaitAndSignal mutex(reconfigurationMutex);
+
+ SetGatekeeperIdentifier("TESTIES");
+
+ // Interfaces to listen on
+ H323TransportAddressArray interfaces;
+ interfaces.Append(new H323TransportAddress(0.0.0.0);
+ AddListeners(interfaces);
+
+ // lots more to come
+
+ return TRUE;
+
+}
+
+#endif
+
+/** IMPLEMENTATION OF C FUNCTIONS */
+
+/**
+ * The extern "C" directive takes care for
+ * the ANSI-C representation of linkable symbols
+ */
+extern "C" {
+
+int end_point_exist(void)
+{
+ if (!endPoint) {
+ return 0;
+ }
+ return 1;
+}
+
+void h323_end_point_create(void)
+{
+ channelsOpen = 0;
+ localProcess = new MyProcess();
+ localProcess->Main();
+}
+
+void h323_gk_urq(void)
+{
+ if (!end_point_exist()) {
+ cout << " ERROR: [h323_gk_urq] No Endpoint, this is bad" << endl;
+ return;
+ }
+
+ endPoint->RemoveGatekeeper();
+}
+
+void h323_end_process(void)
+{
+ delete localProcess;
+}
+
+void h323_debug(int flag, unsigned level)
+{
+ if (flag)
+ PTrace:: SetLevel(level);
+ else
+ PTrace:: SetLevel(0);
+}
+
+/** Installs the callback functions on behalf of the PBX application */
+void h323_callback_register(setup_incoming_cb ifunc,
+ setup_outbound_cb sfunc,
+ on_connection_cb confunc,
+ start_logchan_cb lfunc,
+ clear_con_cb clfunc,
+ con_established_cb efunc,
+ send_digit_cb dfunc)
+{
+ on_incoming_call = ifunc;
+ on_outgoing_call = sfunc;
+ on_create_connection = confunc;
+ on_start_logical_channel = lfunc;
+ on_connection_cleared = clfunc;
+ on_connection_established = efunc;
+ on_send_digit = dfunc;
+}
+
+/**
+ * Add capability to the capability table of the end point.
+ */
+int h323_set_capability(int cap, int dtmfMode)
+{
+ int g711Frames = 30;
+ int gsmFrames = 4;
+
+
+ if (!end_point_exist()) {
+ cout << " ERROR: [h323_set_capablity] No Endpoint, this is bad" << endl;
+ return 1;
+ }
+
+ mode = dtmfMode;
+ if (dtmfMode == H323_DTMF_INBAND)
+ endPoint->SetSendUserInputMode(H323Connection::SendUserInputAsTone);
+ else
+ endPoint->SetSendUserInputMode(H323Connection::SendUserInputAsInlineRFC2833);
+
+
+ /* Hardcode this for now (Someone tell me if T.38 works now
+ or provide me with some debug so we can make this work */
+
+// endPoint->SetCapability(0, 0, new H323_T38Capability(H323_T38Capability::e_UDP));
+
+ if (cap & AST_FORMAT_SPEEX) {
+ /* Not real sure if Asterisk acutally supports all
+ of the various different bit rates so add them
+ all and figure it out later*/
+
+ endPoint->SetCapability(0, 0, new SpeexNarrow2AudioCapability());
+ endPoint->SetCapability(0, 0, new SpeexNarrow3AudioCapability());
+ endPoint->SetCapability(0, 0, new SpeexNarrow4AudioCapability());
+ endPoint->SetCapability(0, 0, new SpeexNarrow5AudioCapability());
+ endPoint->SetCapability(0, 0, new SpeexNarrow6AudioCapability());
+ }
+
+ if (cap & AST_FORMAT_G723_1) {
+ H323_G7231Capability *g7231Cap;
+ endPoint->SetCapability(0, 0, g7231Cap = new H323_G7231Capability);
+ }
+
+ if (cap & AST_FORMAT_GSM) {
+ H323_GSM0610Capability *gsmCap;
+ endPoint->SetCapability(0, 0, gsmCap = new H323_GSM0610Capability);
+ gsmCap->SetTxFramesInPacket(gsmFrames);
+ }
+
+ if (cap & AST_FORMAT_G729A) {
+ H323_G729ACapability *g729aCap;
+ endPoint->SetCapability(0, 0, g729aCap = new H323_G729ACapability);
+ }
+
+ if (cap & AST_FORMAT_ULAW) {
+
+ H323_G711Capability *g711uCap;
+ endPoint->SetCapability(0, 0, g711uCap = new H323_G711Capability(H323_G711Capability::muLaw));
+ g711uCap->SetTxFramesInPacket(g711Frames);
+ }
+
+ if (cap & AST_FORMAT_ALAW) {
+ H323_G711Capability *g711aCap;
+ endPoint->SetCapability(0, 0, g711aCap = new H323_G711Capability(H323_G711Capability::ALaw));
+ g711aCap->SetTxFramesInPacket(g711Frames);
+ }
+
+ return 0;
+}
+
+/** Start the H.323 listener */
+int h323_start_listener(int listenPort, struct sockaddr_in bindaddr, int _jitter)
+{
+
+ if (!end_point_exist()) {
+ cout << "ERROR: [h323_start_listener] No Endpoint, this is bad!" << endl;
+ return 1;
+ }
+
+ jitter = _jitter;
+
+ PIPSocket::Address interfaceAddress(bindaddr.sin_addr);
+
+ tcpListener = new H323ListenerTCP(*endPoint, interfaceAddress, (WORD)listenPort);
+
+ if (!endPoint->StartListener(tcpListener)) {
+ cout << "ERROR: Could not open H.323 listener port on " << ((H323ListenerTCP *) tcpListener)->GetListenerPort() << endl;
+ return 1;
+
+ }
+
+ cout << " == H.323 listener started on " << ((H323ListenerTCP *) tcpListener)->GetTransportAddress() << endl;
+
+ return 0;
+};
+
+
+int h323_set_alias(struct oh323_alias *alias)
+{
+ char *p;
+ char *num;
+ PString h323id(alias->name);
+ PString e164(alias->e164);
+
+ if (!end_point_exist()) {
+ cout << "ERROR: [h323_set_alias] No Endpoint, this is bad!" << endl;
+ return 1;
+ }
+
+ cout << " == Adding alias \"" << h323id << "\" to endpoint" << endl;
+ endPoint->AddAliasName(h323id);
+
+ endPoint->RemoveAliasName(localProcess->GetUserName());
+
+ if (!e164.IsEmpty()) {
+ cout << " == Adding E.164 \"" << e164 << "\" to endpoint" << endl;
+ endPoint->AddAliasName(e164);
+ }
+ if (strlen(alias->prefix)) {
+ p = alias->prefix;
+ num = strsep(&p, ",");
+ while(num) {
+ cout << " == Adding Prefix \"" << num << "\" to endpoint" << endl;
+ endPoint->SupportedPrefixes += PString(num);
+ endPoint->SetGateway();
+ num = strsep(&p, ",");
+ }
+ }
+
+ return 0;
+}
+
+/** Establish Gatekeeper communiations, if so configured,
+ * register aliases for the H.323 endpoint to respond to.
+ */
+int h323_set_gk(int gatekeeper_discover, char *gatekeeper, char *secret)
+{
+ PString gkName = PString(gatekeeper);
+ PString pass = PString(secret);
+
+ cout << "begining" << endl;
+
+ if (!end_point_exist()) {
+ cout << "ERROR: [h323_set_gk] No Endpoint, this is bad!" << endl;
+ return 1;
+ }
+
+ if (!gatekeeper) {
+ cout << "Error: Gatekeeper cannot be NULL" << endl;
+ return 1;
+ }
+
+ if (strlen(secret)) {
+ endPoint->SetGatekeeperPassword(pass);
+ }
+
+
+ if (gatekeeper_discover) {
+ /* discover the gk using multicast */
+ if (endPoint->DiscoverGatekeeper(new H323TransportUDP(*endPoint))) {
+ cout << " == Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
+ } else {
+ cout << " *** Could not find a gatekeeper." << endl;
+ return 1;
+ }
+ } else {
+ /* Gatekeeper operations */
+ H323TransportUDP *rasChannel = new H323TransportUDP(*endPoint);
+
+ if (!rasChannel) {
+ cout << " *** No RAS Channel, this is bad" << endl;
+ return 1;
+ }
+ if (endPoint->SetGatekeeper(gkName, rasChannel)) {
+ cout << " == Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
+ } else {
+ cout << " *** Error registering with gatekeeper \"" << gkName << "\". " << endl;
+ return 1;
+ }
+ }
+
+ cout << "end" << endl;
+ return 0;
+}
+
+/** Send a DTMF tone over the H323Connection with the
+ * specified token.
+ */
+void h323_send_tone(const char *call_token, char tone)
+{
+ if (!end_point_exist()) {
+ cout << "ERROR: [h323_send_tone] No Endpoint, this is bad!" << endl;
+ return;
+ }
+
+ PString token = PString(call_token);
+ endPoint->SendUserTone(token, tone);
+}
+
+/** Make a call to the remote endpoint.
+ */
+int h323_make_call(char *host, call_details_t *cd, call_options_t call_options)
+{
+ int res;
+ PString token;
+
+ if (!end_point_exist()) {
+ return 1;
+ }
+
+ PString dest = PString(host);
+
+ res = endPoint->MakeCall(dest, token, &cd->call_reference, call_options.port);
+ memcpy((char *)(cd->call_token), (const unsigned char *)token, token.GetLength());
+
+ return res;
+};
+
+int h323_clear_call(const char *call_token)
+{
+ if (!end_point_exist()) {
+ return 1;
+ }
+
+ ClearCallThread *clearCallThread = new ClearCallThread(call_token);
+ clearCallThread->WaitForTermination();
+
+ return 0;
+};
+
+/** This function tells the h.323 stack to either
+ answer or deny an incoming call */
+int h323_answering_call(const char *token, int busy)
+{
+ const PString currentToken(token);
+
+ H323Connection * connection;
+
+ connection = endPoint->FindConnectionWithLock(currentToken);
+
+ if (connection == NULL) {
+ cout << "No connection found for " << token << endl;
+ return -1;
+ }
+
+ if (!busy){
+ connection->AnsweringCall(H323Connection::AnswerCallNow);
+ connection->Unlock();
+
+ } else {
+ connection->AnsweringCall(H323Connection::AnswerCallDenied);
+ connection->Unlock();
+ };
+
+ return 0;
+}
+
+
+int h323_show_codec(int fd, int argc, char *argv[])
+{
+ cout << "Allowed Codecs:\n\t" << setprecision(2) << endPoint->GetCapabilities() << endl;
+
+ return 0;
+}
+
+
+/* alas, this doesn't work :( */
+void h323_native_bridge(const char *token, char *them, char *us)
+{
+ H323Channel *channel;
+ H323Connection *connection = endPoint->FindConnectionWithLock(token);
+
+ if (!connection){
+ cout << "ERROR: No connection active.\n";
+ return;
+ }
+
+ connection->Unlock();
+ channel = connection->FindChannel(RTP_Session::DefaultAudioSessionID, TRUE);
+ H323_ExternalRTPChannel *external = (H323_ExternalRTPChannel *)channel;
+ external->SetExternalAddress(them, us); // data (RTP), control (Asterisk)
+ return;
+
+}
+
+} /* extern "C" */
+
+
+
diff --git a/channels/h323/ast_h323.h b/channels/h323/ast_h323.h
new file mode 100755
index 000000000..a7604834e
--- /dev/null
+++ b/channels/h323/ast_h323.h
@@ -0,0 +1,249 @@
+/*
+ * h323wrap.h
+ *
+ * OpenH323 Channel Driver for ASTERISK PBX.
+ * By Jeremy McNamara
+ * For The NuFone Network
+ *
+ * This code has been derived from code created by
+ * Michael Manousos and Mark Spencer
+ *
+ * This file is part of the chan_h323 driver for Asterisk
+ *
+ * chan_h323 is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * chan_h323 is distributed WITHOUT ANY WARRANTY; without even
+ * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ */
+
+
+#include <ptlib.h>
+#include <h323.h>
+#include <h323pdu.h>
+#include <mediafmt.h>
+#include <lid.h>
+
+#include <list>
+#include <string>
+#include <algorithm>
+
+#include "chan_h323.h"
+
+/** These need to be redefined here because the C++
+ side of this driver is blind to the asterisk headers */
+
+/*! G.723.1 compression */
+#define AST_FORMAT_G723_1 (1 << 0)
+/*! GSM compression */
+#define AST_FORMAT_GSM (1 << 1)
+/*! Raw mu-law data (G.711) */
+#define AST_FORMAT_ULAW (1 << 2)
+/*! Raw A-law data (G.711) */
+#define AST_FORMAT_ALAW (1 << 3)
+/*! MPEG-2 layer 3 */
+#define AST_FORMAT_MP3 (1 << 4)
+/*! ADPCM (whose?) */
+#define AST_FORMAT_ADPCM (1 << 5)
+/*! Raw 16-bit Signed Linear (8000 Hz) PCM */
+#define AST_FORMAT_SLINEAR (1 << 6)
+/*! LPC10, 180 samples/frame */
+#define AST_FORMAT_LPC10 (1 << 7)
+/*! G.729A audio */
+#define AST_FORMAT_G729A (1 << 8)
+/*! SpeeX Free Compression */
+#define AST_FORMAT_SPEEX (1 << 9)
+
+
+/**This class describes the G.723.1 codec capability.
+ */
+class H323_G7231Capability : public H323AudioCapability
+{
+ PCLASSINFO(H323_G7231Capability, H323AudioCapability);
+ public:
+ H323_G7231Capability(
+ BOOL annexA = TRUE /// Enable Annex A silence insertion descriptors
+ );
+ Comparison Compare(const PObject & obj) const;
+
+ PObject * Clone() const;
+
+ virtual H323Codec * CreateCodec(
+ H323Codec::Direction direction /// Direction in which this instance runs
+ ) const;
+
+ unsigned GetSubType() const;
+ PString GetFormatName() const;
+ BOOL OnSendingPDU(
+ H245_AudioCapability & pdu, /// PDU to set information on
+ unsigned packetSize /// Packet size to use in capability
+ ) const;
+
+ BOOL OnReceivedPDU(
+ const H245_AudioCapability & pdu, /// PDU to get information from
+ unsigned & packetSize /// Packet size to use in capability
+ );
+
+ protected:
+ BOOL annexA;
+};
+
+class MyH323EndPoint : public H323EndPoint {
+
+ PCLASSINFO(MyH323EndPoint, H323EndPoint);
+
+ public:
+
+ int MakeCall(const PString &, PString &, unsigned int *, unsigned int);
+ BOOL ClearCall(const PString &);
+// BOOL OnIncomingCall( H323Connection & connection, const H323SignalPDU &, H323SignalPDU &);
+
+ void OnClosedLogicalChannel(H323Connection &, const H323Channel &);
+ void OnConnectionEstablished(H323Connection &, const PString &);
+ void OnConnectionCleared(H323Connection &, const PString &);
+ H323Connection * CreateConnection(unsigned, void *);
+ void SendUserTone(const PString &, char);
+ H323Capabilities GetCapabilities(void);
+
+ PStringArray SupportedPrefixes;
+
+ void SetEndpointTypeInfo( H225_EndpointType & info ) const;
+ void SetGateway(void);
+};
+
+
+class MyH323Connection : public H323Connection {
+
+ PCLASSINFO(MyH323Connection, H323Connection);
+
+ public:
+ MyH323Connection(MyH323EndPoint &, unsigned, unsigned, WORD);
+ ~MyH323Connection();
+
+ H323Channel * CreateRealTimeLogicalChannel(const H323Capability &, H323Channel::Directions, unsigned,
+ const H245_H2250LogicalChannelParameters *);
+ H323Connection::AnswerCallResponse OnAnswerCall(const PString &, const H323SignalPDU &, H323SignalPDU &);
+ BOOL OnAlerting(const H323SignalPDU &, const PString &);
+ BOOL OnReceivedSignalSetup(const H323SignalPDU &);
+ void OnReceivedReleaseComplete(const H323SignalPDU &);
+ BOOL OnSendSignalSetup(H323SignalPDU &);
+ BOOL OnStartLogicalChannel(H323Channel &);
+ BOOL OnClosingLogicalChannel(H323Channel &);
+ void SendUserInputTone(char, unsigned);
+ void OnUserInputTone(char, unsigned, unsigned, unsigned);
+ void OnUserInputString(const PString &value);
+
+ PString sourceAliases;
+ PString destAliases;
+ PString sourceE164;
+ PString destE164;
+
+ PIPSocket::Address externalIpAddress; // IP address of media server
+ PIPSocket::Address remoteIpAddress; // IP Address of remote endpoint
+ WORD externalPort; // local media server Data port (control is dataPort+1)
+ WORD remotePort; // remote endpoint Data port (control is dataPort+1)
+};
+
+
+#if 0
+class MyGatekeeperServer : public H323GatekeeperServer
+{
+ PCLASSINFO(MyGatekeeperServer, H323GatekeeperServer);
+ public:
+ MyGatekeeperServer(MyH323EndPoint & ep);
+
+ // Overrides
+ virtual H323GatekeeperCall * CreateCall(
+ const OpalGloballyUniqueID & callIdentifier,
+ H323GatekeeperCall::Direction direction
+ );
+ virtual BOOL TranslateAliasAddressToSignalAddress(
+ const H225_AliasAddress & alias,
+ H323TransportAddress & address
+ );
+
+ // new functions
+ BOOL Initialise();
+
+ private:
+ class RouteMap : public PObject {
+ PCLASSINFO(RouteMap, PObject);
+ public:
+ RouteMap(
+ const PString & alias,
+ const PString & host
+ );
+ RouteMap(
+ const RouteMap & map
+ ) : alias(map.alias), regex(map.alias), host(map.host) { }
+
+ void PrintOn(
+ ostream & strm
+ ) const;
+
+ BOOL IsValid() const;
+
+ BOOL IsMatch(
+ const PString & alias
+ ) const;
+
+ const H323TransportAddress & GetHost() const { return host; }
+
+ private:
+ PString alias;
+ PRegularExpression regex;
+ H323TransportAddress host;
+ };
+ PList<RouteMap> routes;
+
+ PMutex reconfigurationMutex;
+};
+
+#endif
+
+/**
+ * The MyProcess is a necessary descendant PProcess class so that the H323EndPoint
+ * objected to be created from within that class. (Who owns main() problem).
+ */
+class MyProcess : public PProcess {
+
+ PCLASSINFO(MyProcess, PProcess);
+
+ public:
+ MyProcess();
+ ~MyProcess();
+
+ void Main();
+
+
+};
+
+
+/**
+ * This class handles the termination of a call.
+ * Note that OpenH323 Library requires that the termination
+ * of a call should be done inside a separate thread of execution.
+ */
+class ClearCallThread : public PThread {
+
+ PCLASSINFO(ClearCallThread, PThread);
+
+ public:
+ ClearCallThread(const char *tc);
+ ~ClearCallThread();
+
+ void Main();
+
+ protected:
+ PString token;
+};
+
+
diff --git a/channels/h323/chan_h323.c b/channels/h323/chan_h323.c
new file mode 100755
index 000000000..12b64dadb
--- /dev/null
+++ b/channels/h323/chan_h323.c
@@ -0,0 +1,1717 @@
+/*
+ * chan_oh323.c
+ *
+ * OpenH323 Channel Driver for ASTERISK PBX.
+ * By Jeremy McNamara
+ * For The NuFone Network
+ *
+ * This code has been derived from code created by
+ * Michael Manousos and Mark Spencer
+ *
+ * This file is part of the chan_h323 driver for Asterisk
+ *
+ * chan_h323 is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * chan_h323 is distributed WITHOUT ANY WARRANTY; without even
+ * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ */
+
+
+#include <stdio.h>
+#include <pthread.h>
+#include <string.h>
+#include <asterisk/lock.h>
+#include <asterisk/logger.h>
+#include <asterisk/channel.h>
+#include <asterisk/channel_pvt.h>
+#include <asterisk/config.h>
+#include <asterisk/module.h>
+#include <asterisk/pbx.h>
+#include <asterisk/options.h>
+#include <asterisk/lock.h>
+#include <asterisk/sched.h>
+#include <asterisk/io.h>
+#include <asterisk/rtp.h>
+#include <asterisk/acl.h>
+#include <asterisk/callerid.h>
+#include <asterisk/cli.h>
+#include <asterisk/dsp.h>
+#include <sys/socket.h>
+#include <net/if.h>
+#include <errno.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <netdb.h>
+#include <sys/signal.h>
+#include <netinet/ip.h>
+
+
+#include "chan_h323.h"
+
+/** String variables required by ASTERISK */
+static char *type = "H323";
+static char *desc = "The NuFone Network's Open H.323 Channel Driver";
+static char *tdesc = "The NuFone Network's Open H.323 Channel Driver";
+static char *config = "h323.conf";
+
+static char default_context[AST_MAX_EXTENSION];
+
+/** H.323 configuration values */
+static char gatekeeper[100];
+static int gatekeeper_disable = 1;
+static int gatekeeper_discover = 0;
+static int manual = 0;
+static int usingGk;
+static int port = 1720;
+static int jitter;
+static int gkroute = 0;
+
+/* Just about everybody seems to support ulaw, so make it a nice default */
+static int capability = AST_FORMAT_ULAW;
+
+/* TOS flag */
+static int tos = 0;
+
+static int dtmfmode = H323_DTMF_RFC2833;
+
+static char secret[50];
+
+/** Private structure of a OpenH323 channel */
+struct oh323_pvt {
+ pthread_mutex_t lock; /* Channel private lock */
+ call_options_t call_opt; /* Options to be used during call setup */
+ int alreadygone; /* Whether or not we've already been destroyed by or peer */
+ int needdestroy; /* if we need to be destroyed */
+ call_details_t cd; /* Call details */
+ struct ast_channel *owner; /* Who owns us */
+ int capability; /* Special capability */
+ int nonCodecCapability;
+ int outgoing; /* Outgoing or incoming call? */
+ int nat; /* Are we talking to a NAT EP?*/
+ int bridge; /* Determine of we should native bridge or not*/
+ char exten[AST_MAX_EXTENSION]; /* Requested extension */
+ char context[AST_MAX_EXTENSION]; /* Context where to start */
+ char username[81]; /* H.323 alias using this channel */
+ char accountcode[256]; /* Account code */
+ int amaflags; /* AMA Flags */
+ char callerid[80]; /* Caller*ID if available */
+ struct ast_rtp *rtp; /* RTP Session */
+ int dtmfmode;
+ struct ast_dsp *vad; /* Used for in-band DTMF detection */
+ struct oh323_pvt *next; /* Next channel in list */
+} *iflist = NULL;
+
+static struct ast_user_list {
+ struct oh323_user *users;
+ pthread_mutex_t lock;
+} userl = { NULL, AST_MUTEX_INITIALIZER };
+
+static struct ast_peer_list {
+ struct oh323_peer *peers;
+ pthread_mutex_t lock;
+} peerl = { NULL, AST_MUTEX_INITIALIZER };
+
+static struct ast_alias_list {
+ struct oh323_alias *aliases;
+ pthread_mutex_t lock;
+} aliasl = { NULL, AST_MUTEX_INITIALIZER };
+
+/** Asterisk RTP stuff*/
+static struct sched_context *sched;
+static struct io_context *io;
+
+/** Protect the interface list (of oh323_pvt's) */
+static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
+
+/** Usage counter and associated lock */
+static int usecnt =0;
+static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
+
+/* Protect the monitoring thread, so only one process can kill or start it, and not
+ when it's doing something critical. */
+static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
+
+/* This is the thread for the monitor which checks for input on the channels
+ which are not currently in use. */
+static pthread_t monitor_thread = 0;
+
+static int restart_monitor(void);
+
+static void __oh323_destroy(struct oh323_pvt *p)
+{
+ struct oh323_pvt *cur, *prev = NULL;
+
+ if (p->rtp) {
+ ast_rtp_destroy(p->rtp);
+ }
+
+ /* Unlink us from the owner if we have one */
+ if (p->owner) {
+ ast_pthread_mutex_lock(&p->owner->lock);
+ ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
+ p->owner->pvt->pvt = NULL;
+ ast_pthread_mutex_unlock(&p->owner->lock);
+ }
+ cur = iflist;
+ while(cur) {
+ if (cur == p) {
+ if (prev)
+ prev->next = cur->next;
+ else
+ iflist = cur->next;
+ break;
+ }
+ prev = cur;
+ cur = cur->next;
+ }
+ if (!cur) {
+ ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
+ } else
+ free(p);
+}
+
+static void oh323_destroy(struct oh323_pvt *p)
+{
+ ast_pthread_mutex_lock(&iflock);
+ __oh323_destroy(p);
+ ast_pthread_mutex_unlock(&iflock);
+}
+
+static struct oh323_alias *build_alias(char *name, struct ast_variable *v)
+{
+ struct oh323_alias *alias;
+
+ alias = (struct oh323_alias *)malloc(sizeof(struct oh323_alias));
+
+ if (alias) {
+ memset(alias, 0, sizeof(struct oh323_alias));
+ strncpy(alias->name, name, sizeof(alias->name)-1);
+
+ while (v) {
+ if (!strcasecmp(v->name, "e164")) {
+ strncpy(alias->e164, v->value, sizeof(alias->e164)-1);
+ } else if (!strcasecmp(v->name, "prefix")) {
+ strncpy(alias->prefix, v->value, sizeof(alias->prefix)-1);
+ } else if (!strcasecmp(v->name, "context")) {
+ strncpy(alias->context, v->value, sizeof(alias->context)-1);
+ } else if (!strcasecmp(v->name, "secret")) {
+ strncpy(alias->prefix, v->value, sizeof(alias->secret)-1);
+ }
+ v = v->next;
+ }
+ }
+ return alias;
+}
+
+static struct oh323_user *build_user(char *name, struct ast_variable *v)
+{
+ struct oh323_user *user;
+ int format;
+
+ user = (struct oh323_user *)malloc(sizeof(struct oh323_user));
+ if (user) {
+ memset(user, 0, sizeof(struct oh323_user));
+ strncpy(user->name, name, sizeof(user->name)-1);
+
+ /* set the usage flag to a sane starting value*/
+ user->inUse = 0;
+ /* Assume we can native bridge */
+ user->bridge = 1;
+
+ while(v) {
+ if (!strcasecmp(v->name, "context")) {
+ strncpy(user->context, v->value, sizeof(user->context)-1);
+ } else if (!strcasecmp(v->name, "bridge")) {
+ user->bridge = ast_true(v->value);
+ } else if (!strcasecmp(v->name, "noFastStart")) {
+ user->noFastStart = ast_true(v->value);
+ } else if (!strcasecmp(v->name, "noH245Tunneling")) {
+ user->noH245Tunneling = ast_true(v->value);
+ } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
+ user->noSilenceSuppression = ast_true(v->value);
+ } else if (!strcasecmp(v->name, "secret")) {
+ strncpy(user->secret, v->value, sizeof(user->secret)-1);
+ } else if (!strcasecmp(v->name, "accountcode")) {
+ strncpy(user->accountcode, v->value, sizeof(user->accountcode)-1);
+ } else if (!strcasecmp(v->name, "incominglimit")) {
+ user->incominglimit = atoi(v->value);
+ if (user->incominglimit < 0)
+ user->incominglimit = 0;
+ } else if (!strcasecmp(v->name, "host")) {
+ if (!strcasecmp(v->value, "dynamic")) {
+ ast_log(LOG_ERROR, "Dynamic host configuration not implemented, yet!\n");
+ free(user);
+ return NULL;
+ } else if (ast_get_ip(&user->addr, v->value)) {
+ free(user);
+ return NULL;
+ }
+ } else if (!strcasecmp(v->name, "amaflags")) {
+ format = ast_cdr_amaflags2int(v->value);
+ if (format < 0) {
+ ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
+ } else {
+ user->amaflags = format;
+ }
+ }
+ v = v->next;
+ }
+ }
+ return user;
+}
+
+
+static struct oh323_peer *build_peer(char *name, struct ast_variable *v)
+{
+ struct oh323_peer *peer;
+ struct oh323_peer *prev;
+ int found=0;
+
+ prev = NULL;
+ ast_pthread_mutex_lock(&peerl.lock);
+ peer = peerl.peers;
+
+ while(peer) {
+ if (!strcasecmp(peer->name, name)) {
+ break;
+ }
+ prev = peer;
+ peer = peer->next;
+ }
+
+ if (peer) {
+ found++;
+ /* Already in the list, remove it and it will be added back (or FREE'd) */
+ if (prev) {
+ prev->next = peer->next;
+ } else {
+ peerl.peers = peer->next;
+ }
+ ast_pthread_mutex_unlock(&peerl.lock);
+ } else {
+ ast_pthread_mutex_unlock(&peerl.lock);
+ peer = malloc(sizeof(struct oh323_peer));
+ memset(peer, 0, sizeof(struct oh323_peer));
+ }
+ if (peer) {
+ if (!found) {
+ strncpy(peer->name, name, sizeof(peer->name)-1);
+ }
+
+ /* set the usage flag to a sane starting value*/
+ peer->inUse = 0;
+
+ while(v) {
+ if (!strcasecmp(v->name, "context")) {
+ strncpy(peer->context, v->value, sizeof(peer->context)-1);
+ } else if (!strcasecmp(v->name, "bridge")) {
+ peer->bridge = ast_true(v->value);
+ } else if (!strcasecmp(v->name, "noFastStart")) {
+ peer->noFastStart = ast_true(v->value);
+ } else if (!strcasecmp(v->name, "noH245Tunneling")) {
+ peer->noH245Tunneling = ast_true(v->value);
+ } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
+ peer->noSilenceSuppression = ast_true(v->value);
+ } else if (!strcasecmp(v->name, "outgoinglimit")) {
+ peer->outgoinglimit = atoi(v->value);
+ if (peer->outgoinglimit > 0)
+ peer->outgoinglimit = 0;
+ } else if (!strcasecmp(v->name, "host")) {
+ if (!strcasecmp(v->value, "dynamic")) {
+ ast_log(LOG_ERROR, "Dynamic host configuration not implemented, yet!\n");
+ free(peer);
+ return NULL;
+ }
+ if (ast_get_ip(&peer->addr, v->value)) {
+ free(peer);
+ return NULL;
+ }
+ }
+ v=v->next;
+ }
+ }
+ return peer;
+}
+
+
+
+/**
+ * Send (play) the specified digit to the channel.
+ *
+ */
+static int oh323_digit(struct ast_channel *c, char digit)
+{
+ struct oh323_pvt *p = c->pvt->pvt;
+ if (p && p->rtp && (p->dtmfmode & H323_DTMF_RFC2833)) {
+ ast_rtp_senddigit(p->rtp, digit);
+ }
+ /* If in-band DTMF is desired, send that */
+ if (p->dtmfmode & H323_DTMF_INBAND)
+ h323_send_tone(p->cd.call_token, digit);
+ return 0;
+}
+
+
+/**
+ * Make a call over the specified channel to the specified
+ * destination. This function will parse the destination string
+ * and determine the address-number to call.
+ * Return -1 on error, 0 on success.
+ */
+static int oh323_call(struct ast_channel *c, char *dest, int timeout)
+{
+ int res;
+ struct oh323_pvt *p = c->pvt->pvt;
+ char called_addr[256];
+
+
+ ast_log(LOG_DEBUG, "dest=%s, timeout=%d.\n", dest, timeout);
+
+ if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
+ ast_log(LOG_WARNING, "Line is already in use (%s)\n", c->name);
+ return -1;
+ }
+
+ /* set the connect port */
+ p->call_opt.port = port;
+
+ /* outgoing call */
+ p->outgoing = 1;
+
+ /* Clear the call token */
+ if ((p->cd).call_token == NULL)
+ (p->cd).call_token = (char *)malloc(128);
+
+ memset((char *)(p->cd).call_token, 0, 128);
+
+ if (p->cd.call_token == NULL) {
+ ast_log(LOG_ERROR, "Not enough memory.\n");
+ return -1;
+ }
+
+ /* Build the address to call */
+ memset(called_addr, 0, sizeof(dest));
+ memcpy(called_addr, dest, sizeof(called_addr));
+
+ res = h323_make_call(called_addr, &(p->cd), p->call_opt);
+
+ if (res) {
+ printf("h323_make_call failed\n");
+ return -1;
+ }
+
+ ast_setstate(c, AST_STATE_RINGING);
+ return 0;
+}
+
+
+static int oh323_answer(struct ast_channel *c)
+{
+ int res;
+
+ struct oh323_pvt *p = c->pvt->pvt;
+
+ res = h323_answering_call(p->cd.call_token, 0);
+
+ if (c->_state != AST_STATE_UP)
+ ast_setstate(c, AST_STATE_UP);
+
+ return res;
+}
+
+static int oh323_hangup(struct ast_channel *c)
+{
+ struct oh323_pvt *p = c->pvt->pvt;
+ int needcancel = 0;
+ if (h323debug)
+ ast_log(LOG_DEBUG, "oh323_hangup(%s)\n", c->name);
+ if (!c->pvt->pvt) {
+ ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
+ return 0;
+ }
+ ast_pthread_mutex_lock(&p->lock);
+ /* Determine how to disconnect */
+ if (p->owner != c) {
+ ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
+ ast_pthread_mutex_unlock(&p->lock);
+ return 0;
+ }
+ if (!c || (c->_state != AST_STATE_UP))
+ needcancel = 1;
+ /* Disconnect */
+ p = c->pvt->pvt;
+
+ /* Free dsp used for in-band DTMF detection */
+ if (p->vad) {
+ ast_dsp_free(p->vad);
+ }
+
+ p->owner = NULL;
+ c->pvt->pvt = NULL;
+
+ /* Start the process if it's not already started */
+ if (!p->alreadygone) {
+ if (h323_clear_call((p->cd).call_token))
+ ast_log(LOG_DEBUG, "ClearCall failed.\n");
+ p->needdestroy = 1;
+ }
+
+
+ ast_pthread_mutex_unlock(&p->lock);
+ return 0;
+}
+
+static struct ast_frame *oh323_rtp_read(struct oh323_pvt *p)
+{
+ /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
+ struct ast_frame *f;
+ static struct ast_frame null_frame = { AST_FRAME_NULL, };
+ f = ast_rtp_read(p->rtp);
+ /* Don't send RFC2833 if we're not supposed to */
+ if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & H323_DTMF_RFC2833))
+ return &null_frame;
+ if (p->owner) {
+ /* We already hold the channel lock */
+ if (f->frametype == AST_FRAME_VOICE) {
+ if (f->subclass != p->owner->nativeformats) {
+ ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
+ p->owner->nativeformats = f->subclass;
+ ast_set_read_format(p->owner, p->owner->readformat);
+ ast_set_write_format(p->owner, p->owner->writeformat);
+ }
+
+ /* Do in-band DTMF detection */
+ if (p->dtmfmode & H323_DTMF_INBAND) {
+ f = ast_dsp_process(p->owner,p->vad,f,0);
+ if (f->frametype == AST_FRAME_DTMF)
+ ast_log(LOG_DEBUG, "Got in-band digit %c.\n", f->subclass);
+ }
+
+
+ }
+ }
+ return f;
+}
+
+
+static struct ast_frame *oh323_read(struct ast_channel *c)
+{
+ struct ast_frame *fr;
+ struct oh323_pvt *p = c->pvt->pvt;
+ ast_pthread_mutex_lock(&p->lock);
+ fr = oh323_rtp_read(p);
+ ast_pthread_mutex_unlock(&p->lock);
+ return fr;
+}
+
+static int oh323_write(struct ast_channel *c, struct ast_frame *frame)
+{
+ struct oh323_pvt *p = c->pvt->pvt;
+ int res = 0;
+ if (frame->frametype != AST_FRAME_VOICE) {
+ if (frame->frametype == AST_FRAME_IMAGE)
+ return 0;
+ else {
+ ast_log(LOG_WARNING, "Can't send %d type frames with H323 write\n", frame->frametype);
+ return 0;
+ }
+ } else {
+ if (!(frame->subclass & c->nativeformats)) {
+ ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
+ frame->subclass, c->nativeformats, c->readformat, c->writeformat);
+ return -1;
+ }
+ }
+ if (p) {
+ ast_pthread_mutex_lock(&p->lock);
+ if (p->rtp) {
+ res = ast_rtp_write(p->rtp, frame);
+ }
+ ast_pthread_mutex_unlock(&p->lock);
+ }
+ return res;
+}
+
+/** FIXME: Can I acutally use this or does Open H.323 take care of everything? */
+static int oh323_indicate(struct ast_channel *c, int condition)
+{
+
+ struct oh323_pvt *p = c->pvt->pvt;
+
+ switch(condition) {
+ case AST_CONTROL_RINGING:
+ if (c->_state == AST_STATE_RING) {
+ // transmit_response(p, "180 Ringing", &p->initreq);
+ break;
+ }
+ return -1;
+ case AST_CONTROL_BUSY:
+ if (c->_state != AST_STATE_UP) {
+ // transmit_response(p, "600 Busy everywhere", &p->initreq);
+ p->alreadygone = 1;
+ ast_softhangup(c, AST_SOFTHANGUP_DEV);
+ break;
+ }
+ return -1;
+ case AST_CONTROL_CONGESTION:
+ if (c->_state != AST_STATE_UP) {
+ // transmit_response(p, "486 Busy here", &p->initreq);
+ p->alreadygone = 1;
+ ast_softhangup(c, AST_SOFTHANGUP_DEV);
+ break;
+ }
+ return -1;
+ case -1:
+ return -1;
+ default:
+ ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
+ return -1;
+ }
+ return 0;
+}
+
+// FIXME: WTF is this? Do I need this???
+static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
+{
+ struct oh323_pvt *p = newchan->pvt->pvt;
+
+ ast_pthread_mutex_lock(&p->lock);
+ if (p->owner != oldchan) {
+ ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
+ return -1;
+ }
+ p->owner = newchan;
+ ast_pthread_mutex_unlock(&p->lock);
+ return 0;
+}
+
+static struct ast_channel *oh323_new(struct oh323_pvt *i, int state, const char *host)
+{
+ struct ast_channel *tmp;
+ int fmt;
+ tmp = ast_channel_alloc(1);
+
+ if (tmp) {
+
+ snprintf(tmp->name, sizeof(tmp->name)-1, "H323/%s", host);
+ tmp->nativeformats = i->capability;
+ if (!tmp->nativeformats)
+ tmp->nativeformats = capability;
+ fmt = ast_best_codec(tmp->nativeformats);
+ tmp->type = type;
+ tmp->fds[0] = ast_rtp_fd(i->rtp);
+ ast_setstate(tmp, state);
+
+ if (state == AST_STATE_RING)
+ tmp->rings = 1;
+
+ tmp->writeformat = fmt;
+ tmp->pvt->rawwriteformat = fmt;
+ tmp->readformat = fmt;
+ tmp->pvt->rawreadformat = fmt;
+
+ /* Allocate dsp for in-band DTMF support */
+ if (i->dtmfmode & H323_DTMF_INBAND) {
+ i->vad = ast_dsp_new();
+ ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
+ }
+
+ /* Register the OpenH323 channel's functions. */
+ tmp->pvt->pvt = i;
+ tmp->pvt->send_digit = oh323_digit;
+ tmp->pvt->call = oh323_call;
+ tmp->pvt->hangup = oh323_hangup;
+ tmp->pvt->answer = oh323_answer;
+ tmp->pvt->read = oh323_read;
+ tmp->pvt->write = oh323_write;
+ tmp->pvt->indicate = oh323_indicate;
+ tmp->pvt->fixup = oh323_fixup;
+// tmp->pvt->bridge = ast_rtp_bridge;
+
+ /* Set the owner of this channel */
+ i->owner = tmp;
+
+ ast_pthread_mutex_lock(&usecnt_lock);
+ usecnt++;
+ ast_pthread_mutex_unlock(&usecnt_lock);
+ ast_update_use_count();
+ strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
+ strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
+ tmp->priority = 1;
+ if (strlen(i->callerid))
+ tmp->callerid = strdup(i->callerid);
+ if (state != AST_STATE_DOWN) {
+ printf ("oh323_new EXTEN: %s\n", tmp->exten);
+ printf ("oh323_new CONTEXT: %s\n", tmp->context);
+ if (ast_pbx_start(tmp)) {
+ ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
+ ast_hangup(tmp);
+ tmp = NULL;
+ }
+ }
+ } else
+ ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
+ return tmp;
+}
+
+static struct oh323_pvt *oh323_alloc(int callid)
+{
+ struct oh323_pvt *p;
+
+ p = malloc(sizeof(struct oh323_pvt));
+ if (!p) {
+ ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
+ return NULL;
+ }
+
+ /* Keep track of stuff */
+ memset(p, 0, sizeof(struct oh323_pvt));
+ p->rtp = ast_rtp_new(NULL, NULL);
+ if (!p->rtp) {
+ ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
+ free(p);
+ return NULL;
+ }
+ ast_rtp_settos(p->rtp, tos);
+ ast_pthread_mutex_init(&p->lock);
+
+ p->cd.call_reference = callid;
+ p->bridge = 1;
+
+ p->dtmfmode = dtmfmode;
+ if (p->dtmfmode & H323_DTMF_RFC2833)
+ p->nonCodecCapability |= AST_RTP_DTMF;
+
+ /* Add to interface list */
+ ast_pthread_mutex_lock(&iflock);
+ p->next = iflist;
+ iflist = p;
+ ast_pthread_mutex_unlock(&iflock);
+ return p;
+}
+
+static struct oh323_pvt *find_call(int call_reference)
+{
+ struct oh323_pvt *p;
+
+ ast_pthread_mutex_lock(&iflock);
+ p = iflist;
+
+ while(p) {
+ if (p->cd.call_reference == call_reference) {
+ /* Found the call */
+ ast_pthread_mutex_unlock(&iflock);
+ return p;
+ }
+ p = p->next;
+ }
+ ast_pthread_mutex_unlock(&iflock);
+ return NULL;
+
+}
+
+static struct ast_channel *oh323_request(char *type, int format, void *data)
+{
+
+ int oldformat;
+ struct oh323_pvt *p;
+ struct ast_channel *tmpc = NULL;
+ char *dest = data;
+ char *ext, *host;
+ char tmp[256];
+
+ ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
+
+ oldformat = format;
+ format &= capability;
+ if (!format) {
+ ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
+ return NULL;
+ }
+
+ strncpy(tmp, dest, sizeof(tmp) - 1);
+ host = strchr(tmp, '@');
+ if (host) {
+ *host = '\0';
+ host++;
+ ext = tmp;
+ } else {
+ host = tmp;
+ ext = NULL;
+ }
+
+ p = oh323_alloc(0);
+
+ if (!p) {
+ ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
+ return NULL;
+ }
+
+ /* Assign a default capability */
+ p->capability = capability;
+
+ if (p->dtmfmode) {
+ if (p->dtmfmode & H323_DTMF_RFC2833)
+ p->nonCodecCapability |= AST_RTP_DTMF;
+ else
+ p->nonCodecCapability &= ~AST_RTP_DTMF;
+ }
+
+
+ ast_log(LOG_DEBUG, "Host: %s\tUsername: %s\n", host, p->username);
+
+ if (ext)
+ strncpy(p->username, ext, sizeof(p->username) - 1);
+ tmpc = oh323_new(p, AST_STATE_DOWN, host);
+ if (!tmpc)
+ oh323_destroy(p);
+
+ restart_monitor();
+
+ return tmpc;
+}
+
+struct oh323_alias *find_alias(const char *source_aliases)
+{
+ struct oh323_alias *a;
+
+ a = aliasl.aliases;
+
+ while(a) {
+
+ if (!strcasecmp(a->name, source_aliases)) {
+ break;
+ }
+ a = a->next;
+ }
+ return a;
+}
+
+struct oh323_user *find_user(const char *source_aliases)
+{
+ struct oh323_user *u;
+
+ u = userl.users;
+
+ while(u) {
+
+ if (!strcasecmp(u->name, source_aliases)) {
+ break;
+ }
+ u = u->next;
+ }
+ return u;
+
+}
+
+struct oh323_peer *find_peer(char *dest_peer)
+{
+ struct oh323_peer *p;
+
+ p = peerl.peers;
+
+ while(p) {
+ if (!strcasecmp(p->name, dest_peer)) {
+ break;
+ }
+ p = p->next;
+ }
+ return p;
+
+}
+
+/**
+ * Callback for sending digits from H.323 up to asterisk
+ *
+ */
+int send_digit(unsigned call_reference, char digit)
+{
+ struct oh323_pvt *p;
+ struct ast_frame f;
+
+ ast_log(LOG_DEBUG, "Recieved Digit: %c\n", digit);
+ p = find_call(call_reference);
+
+ if (!p) {
+ ast_log(LOG_ERROR, "Private structure not found in send_digit.\n");
+ return -1;
+ }
+ memset(&f, 0, sizeof(f));
+ f.frametype = AST_FRAME_DTMF;
+ f.subclass = digit;
+ f.datalen = 0;
+ f.samples = 300;
+ f.offset = 0;
+ f.data = NULL;
+ f.mallocd = 0;
+ f.src = "SEND_DIGIT";
+
+ return ast_queue_frame(p->owner, &f, 1);
+}
+
+/**
+ * Call-back function that gets called when any H.323 connection is made
+ *
+ * Returns the local RTP port
+ */
+int create_connection(unsigned call_reference)
+{
+ struct oh323_pvt *p;
+ struct sockaddr_in us;
+
+ p = find_call(call_reference);
+
+ if (!p) {
+ ast_log(LOG_ERROR, "Unable to allocate private structure, this is very bad.\n");
+ return -1;
+ }
+
+ /* figure out our local RTP port and tell the H.323 stack about it*/
+ ast_rtp_get_us(p->rtp, &us);
+ return ntohs(us.sin_port);
+}
+
+/**
+ * Call-back function for incoming calls
+ *
+ * Returns 1 on success
+ */
+
+int setup_incoming_call(call_details_t cd)
+{
+
+ ast_log(LOG_DEBUG, "default_context [%s]\n", default_context);
+
+ struct oh323_pvt *p = NULL;
+ struct ast_channel *c = NULL;
+ struct oh323_user *user = NULL;
+ struct oh323_alias *alias = NULL;
+
+ /* allocate the call*/
+ p = oh323_alloc(cd.call_reference);
+
+ if (!p) {
+ ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
+ return 0;
+ }
+
+ /* Populate the call details in the private structure */
+ p->cd.call_token = cd.call_token;
+ p->cd.call_source_aliases = cd.call_source_aliases;
+ p->cd.call_dest_alias = cd.call_dest_alias;
+ p->cd.call_source_e164 = cd.call_source_e164;
+ p->cd.call_dest_e164 = cd.call_dest_e164;
+
+ if (h323debug) {
+ printf(" == Setting up Call\n");
+ printf(" -- Calling party name: %s\n", p->cd.call_source_aliases);
+ printf(" -- Calling party number: %s\n", p->cd.call_source_e164);
+ printf(" -- Called party name: %s\n", p->cd.call_dest_alias);
+ printf(" -- Called party number: %s\n", p->cd.call_dest_e164);
+ }
+
+ /* Decide if we are allowing Gatekeeper routed calls*/
+ if ((!strcasecmp(cd.sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk == 1)) {
+
+ if (strlen(cd.call_dest_e164)) {
+ strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
+ strncpy(p->context, default_context, sizeof(p->context)-1);
+ } else {
+ alias = find_alias(cd.call_dest_alias);
+
+ if (!alias) {
+ ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd.call_dest_alias);
+ return 0;
+ }
+ printf("Alias found: %s and %s\n", alias->name, alias->context);
+
+ strncpy(p->exten, alias->name, sizeof(p->exten)-1);
+ strncpy(p->context, alias->context, sizeof(p->context)-1);
+ }
+
+ sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164);
+
+ } else {
+ /* Either this call is not from the Gatekeeper
+ or we are not allowing gk routed calls */
+
+ user = find_user(cd.call_source_aliases);
+
+ if (!user) {
+ sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164);
+ if (strlen(p->cd.call_dest_e164)) {
+ strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
+ } else {
+ strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);
+ }
+ if (!strlen(default_context)) {
+ ast_log(LOG_ERROR, "Call from user '%s' rejected due to no default context\n", p->cd.call_source_aliases);
+ return 0;
+ }
+ strncpy(p->context, default_context, sizeof(p->context)-1);
+ ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd.call_source_aliases, p->context);
+ } else {
+ if (user->incominglimit > 0) {
+ if (user->inUse >= user->incominglimit) {
+ ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", user->name, user->incominglimit);
+ return 0;
+ }
+ }
+ strncpy(p->context, user->context, sizeof(p->context)-1);
+ p->bridge = user->bridge;
+
+ if (strlen(user->callerid) && strlen(p->callerid))
+ strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
+ else
+ sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164);
+
+ if (strlen(p->cd.call_dest_e164)) {
+ strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
+ } else {
+ strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);
+ }
+
+ if (strlen(user->accountcode)) {
+ strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)-1);
+ }
+
+ /* Increment the usage counter */
+ user->inUse++;
+ }
+ }
+
+ printf ("CONTEXT: [%s]\n", p->context);
+ printf ("EXTEN: [%s]\n", p->exten);
+ /* allocate a channel and tell asterisk about it */
+ c = oh323_new(p, AST_STATE_RINGING, cd.call_token);
+
+ if (!c) {
+ ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
+ return 0;
+ }
+
+ return 1;
+}
+
+/**
+ * Call-back function to establish an outgoing H.323 call
+ *
+ * Returns 1 on success
+ */
+int setup_outgoing_call(call_details_t cd)
+{
+ return 1;
+}
+
+#if 0
+if (p->inUse >= p->outgoinglimit) {
+ ast_log(LOG_ERROR, "Call to %s rejected due to usage limit of %d outgoing channels\n", p->name, p->inUse);
+ return 0;
+}
+
+if (!p) {
+ ast_log(LOG_ERROR, "Rejecting call: peer %s not found\n", dest_peer);
+ return 0;
+}
+#endif
+
+/**
+ * Call-back function that gets called for each rtp channel opened
+ *
+ * Returns nothing
+ */
+void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort)
+{
+ struct oh323_pvt *p = NULL;
+ struct sockaddr_in them;
+
+ /* Find the call or allocate a private structure if call not found */
+ p = find_call(call_reference);
+
+ if (!p) {
+ ast_log(LOG_ERROR, "Something is wrong: rtp\n");
+ return;
+ }
+
+ them.sin_family = AF_INET;
+ them.sin_addr.s_addr = inet_addr(remoteIp); // only works for IPv4
+ them.sin_port = htons(remotePort);
+ ast_rtp_set_peer(p->rtp, &them);
+
+ return;
+}
+
+/**
+ * Call-back function to signal asterisk that the channel has been answered
+ * Returns nothing
+ */
+void connection_made(unsigned call_reference)
+{
+ struct ast_channel *c = NULL;
+ struct oh323_pvt *p = NULL;
+
+ p = find_call(call_reference);
+
+ if (!p)
+ ast_log(LOG_ERROR, "Something is wrong: connection\n");
+
+
+ if (!p->owner) {
+ printf("Channel has no owner\n");
+ return;
+ }
+ c = p->owner;
+
+ ast_setstate(c, AST_STATE_UP);
+ return;
+}
+
+/**
+ * Call-back function to cleanup communication
+ * Returns nothing,
+ */
+void cleanup_connection(call_details_t cd)
+{
+ struct oh323_pvt *p = NULL;
+// struct oh323_peer *peer = NULL;
+ struct oh323_user *user = NULL;
+ struct ast_rtp *rtp = NULL;
+
+ ast_log(LOG_DEBUG, "Cleaning up our mess\n");
+
+ p = find_call(cd.call_reference);
+
+ if (!p) {
+ return;
+ }
+
+ /* Decrement usage counter */
+ if (!p->outgoing) {
+ user = find_user(cd.call_source_aliases);
+
+ if(user)
+ user->inUse--;
+ }
+
+#if 0
+ if (p->outgoing) {
+ peer = find_peer(cd.call_dest_alias);
+ peer->inUse--;
+ } else {
+ user = find_user(cd.call_source_aliases);
+ user->inUse--;
+ }
+#endif
+
+ if (p->rtp) {
+ rtp = p->rtp;
+ p->rtp = NULL;
+ /* Immediately stop RTP */
+ ast_rtp_destroy(rtp);
+ }
+
+ p->alreadygone = 1;
+
+ /* Send hangup */
+ if (p->owner)
+ ast_queue_hangup(p->owner, 1);
+
+ p = NULL;
+ return;
+}
+
+static void *do_monitor(void *data)
+{
+ int res;
+ struct oh323_pvt *oh323 = NULL;
+
+ for(;;) {
+ /* Check for interfaces needing to be killed */
+ ast_pthread_mutex_lock(&iflock);
+restartsearch:
+ oh323 = iflist;
+ while(oh323) {
+ if (oh323->needdestroy) {
+ __oh323_destroy(oh323);
+ goto restartsearch;
+ }
+ oh323 = oh323->next;
+ }
+ ast_pthread_mutex_unlock(&iflock);
+
+ pthread_testcancel();
+
+ /* Wait for sched or io */
+ res = ast_sched_wait(sched);
+ if ((res < 0) || (res > 1000))
+ res = 1000;
+ res = ast_io_wait(io, res);
+ ast_pthread_mutex_lock(&monlock);
+ if (res >= 0)
+ ast_sched_runq(sched);
+ ast_pthread_mutex_unlock(&monlock);
+ }
+ /* Never reached */
+ return NULL;
+
+}
+
+static int restart_monitor(void)
+{
+ /* If we're supposed to be stopped -- stay stopped */
+ if (monitor_thread == -2)
+ return 0;
+ if (ast_pthread_mutex_lock(&monlock)) {
+ ast_log(LOG_WARNING, "Unable to lock monitor\n");
+ return -1;
+ }
+ if (monitor_thread == pthread_self()) {
+ ast_pthread_mutex_unlock(&monlock);
+ ast_log(LOG_WARNING, "Cannot kill myself\n");
+ return -1;
+ }
+ if (monitor_thread) {
+ /* Wake up the thread */
+ pthread_kill(monitor_thread, SIGURG);
+ } else {
+ /* Start a new monitor */
+ if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
+ ast_pthread_mutex_unlock(&monlock);
+ ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
+ return -1;
+ }
+ }
+ ast_pthread_mutex_unlock(&monlock);
+ return 0;
+}
+
+static int h323_do_trace(int fd, int argc, char *argv[])
+{
+ if (argc != 3)
+ return RESULT_SHOWUSAGE;
+
+ h323_debug(1, atoi(argv[2]));
+ ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
+ return RESULT_SUCCESS;
+}
+
+static int h323_no_trace(int fd, int argc, char *argv[])
+{
+ if (argc != 3)
+ return RESULT_SHOWUSAGE;
+
+ h323_debug(0,0);
+ ast_cli(fd, "H.323 trace disabled\n");
+ return RESULT_SUCCESS;
+}
+
+static int h323_do_debug(int fd, int argc, char *argv[])
+{
+ if (argc != 2)
+ return RESULT_SHOWUSAGE;
+
+ h323debug = 1;
+ ast_cli(fd, "H323 debug enabled\n");
+ return RESULT_SUCCESS;
+}
+
+static int h323_no_debug(int fd, int argc, char *argv[])
+{
+ if (argc != 3)
+ return RESULT_SHOWUSAGE;
+
+ h323debug = 0;
+ ast_cli(fd, "H323 Debug disabled\n");
+ return RESULT_SUCCESS;
+}
+
+static int h323_gk_cycle(int fd, int argc, char *argv[])
+{
+ if (argc != 3)
+ return RESULT_SHOWUSAGE;
+
+ h323_gk_urq();
+
+ /* Possibly register with a GK */
+ if (!gatekeeper_disable) {
+ if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
+ ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
+ h323_end_process();
+ }
+ }
+
+ return RESULT_SUCCESS;
+}
+
+
+static char trace_usage[] =
+"Usage: h.323 trace <level num>\n"
+" Enables H.323 stack tracing for debugging purposes\n";
+
+static char no_trace_usage[] =
+"Usage: h.323 no trace\n"
+" Disables H.323 stack tracing for debugging purposes\n";
+
+static char debug_usage[] =
+"Usage: h.323 debug\n"
+" Enables chan_h323 debug output\n";
+
+static char no_debug_usage[] =
+"Usage: h.323 no debug\n"
+" Disables chan_h323 debug output\n";
+
+static char show_codec_usage[] =
+"Usage: h.323 show codec\n"
+" Shows all enabled codecs\n";
+
+static char show_cycle_usage[] =
+"Usage: h.323 gk cycle\n"
+" Manually re-register with the Gatekeper\n";
+
+
+static struct ast_cli_entry cli_trace =
+ { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
+static struct ast_cli_entry cli_no_trace =
+ { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
+static struct ast_cli_entry cli_debug =
+ { { "h.323", "debug", NULL }, h323_do_debug, "Enable chan_h323 debug", debug_usage };
+static struct ast_cli_entry cli_no_debug =
+ { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable chan_h323 debug", no_debug_usage };
+static struct ast_cli_entry cli_show_codecs =
+ { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
+static struct ast_cli_entry cli_gk_cycle =
+ { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
+
+
+
+int reload_config()
+{
+
+ int format;
+ struct ast_config *cfg;
+ struct ast_variable *v;
+ struct oh323_peer *peer = NULL;
+ struct oh323_user *user = NULL;
+ struct oh323_alias *alias = NULL;
+ struct hostent *hp;
+ char *cat;
+ char *utype;
+
+ cfg = ast_load(config);
+
+ /* We *must* have a config file otherwise stop immediately */
+ if (!cfg) {
+ ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
+ return 0;
+ }
+
+ h323debug=0;
+ dtmfmode = H323_DTMF_RFC2833;
+
+ memset(&bindaddr, 0, sizeof(bindaddr));
+
+ v = ast_variable_browse(cfg, "general");
+ while(v) {
+ /* Create the interface list */
+ if (!strcasecmp(v->name, "jitter")) {
+ jitter = (int) strtol(v->value, NULL, 10);
+ if (jitter < 20 || jitter > 10000) {
+ ast_log(LOG_NOTICE, "Invalid jitter value! Valid range: 20ms to 10000ms. Recommended: 100ms");
+ ast_destroy(cfg);
+ return 0;
+ }
+ } else if (!strcasecmp(v->name, "port")) {
+ port = (int)strtol(v->value, NULL, 10);
+ } else if (!strcasecmp(v->name, "bindaddr")) {
+ if (!(hp = gethostbyname(v->value))) {
+ ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
+ } else {
+ memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
+ }
+ } else if (!strcasecmp(v->name, "allow")) {
+ format = ast_getformatbyname(v->value);
+ if (format < 1)
+ ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
+ else
+ capability |= format;
+ } else if (!strcasecmp(v->name, "disallow")) {
+ format = ast_getformatbyname(v->value);
+ if (format < 1)
+ ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
+ else
+ capability &= ~format;
+ } else if (!strcasecmp(v->name, "tos")) {
+ if (sscanf(v->value, "%i", &format) == 1)
+ tos = format & 0xff;
+ else if (!strcasecmp(v->value, "lowdelay"))
+ tos = IPTOS_LOWDELAY;
+ else if (!strcasecmp(v->value, "throughput"))
+ tos = IPTOS_THROUGHPUT;
+ else if (!strcasecmp(v->value, "reliability"))
+ tos = IPTOS_RELIABILITY;
+ else if (!strcasecmp(v->value, "mincost"))
+ tos = IPTOS_MINCOST;
+ else if (!strcasecmp(v->value, "none"))
+ tos = 0;
+ else
+ ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
+ } else if (!strcasecmp(v->name, "gatekeeper")) {
+ if (!strcasecmp(v->value, "DISABLE")) {
+ gatekeeper_disable = 1;
+ usingGk = 0;
+ } else if (!strcasecmp(v->value, "DISCOVER")) {
+ gatekeeper_disable = 0;
+ gatekeeper_discover = 1;
+ usingGk = 1;
+ } else {
+ gatekeeper_disable = 0;
+ usingGk = 1;
+ strncpy(gatekeeper, v->value, sizeof(gatekeeper)-1);
+ }
+ } else if (!strcasecmp(v->name, "secret")) {
+ strncpy(secret, v->value, sizeof(secret)-1);
+ } else if (!strcasecmp(v->name, "AllowGKRouted")) {
+ gkroute = ast_true(v->value);
+ } else if (!strcasecmp(v->name, "context")) {
+ strncpy(default_context, v->value, sizeof(default_context)-1);
+ printf(" == Setting default context to %s\n", default_context);
+ } else if (!strcasecmp(v->name, "manual")) {
+ manual = ast_true(v->value);
+ } else if (!strcasecmp(v->name, "dtmfmode")) {
+ if (!strcasecmp(v->value, "inband"))
+ dtmfmode=H323_DTMF_INBAND;
+ else if (!strcasecmp(v->value, "rfc2833"))
+ dtmfmode = H323_DTMF_RFC2833;
+ else {
+ ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
+ dtmfmode = H323_DTMF_RFC2833;
+ }
+ }
+ v = v->next;
+ }
+
+ cat = ast_category_browse(cfg, NULL);
+ while(cat) {
+ if (strcasecmp(cat, "general")) {
+ utype = ast_variable_retrieve(cfg, cat, "type");
+ if (utype) {
+ if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
+ user = build_user(cat, ast_variable_browse(cfg, cat));
+ if (user) {
+ ast_pthread_mutex_lock(&userl.lock);
+ user->next = userl.users;
+ userl.users = user;
+ ast_pthread_mutex_unlock(&userl.lock);
+ }
+ } else if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
+ peer = build_peer(cat, ast_variable_browse(cfg, cat));
+ if (peer) {
+ ast_pthread_mutex_lock(&peerl.lock);
+ peer->next = peerl.peers;
+ peerl.peers = peer;
+ ast_pthread_mutex_unlock(&peerl.lock);
+ }
+ } else if (!strcasecmp(utype, "h323")) {
+ alias = build_alias(cat, ast_variable_browse(cfg, cat));
+ if (alias) {
+ ast_pthread_mutex_lock(&aliasl.lock);
+ alias->next = aliasl.aliases;
+ aliasl.aliases = alias;
+ ast_pthread_mutex_unlock(&aliasl.lock);
+ }
+ } else {
+ ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
+ }
+ } else
+ ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
+ }
+ cat = ast_category_browse(cfg, cat);
+ }
+
+ /* Register our H.323 aliases if any*/
+ while (alias) {
+ if (h323_set_alias(alias)) {
+ ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
+ return -1;
+ }
+ alias = alias->next;
+ }
+
+ /* Add some capabilities */
+ if(h323_set_capability(capability, dtmfmode)) {
+ ast_log(LOG_ERROR, "Capabilities failure, this is bad.\n");
+ return -1;
+ }
+
+ printf("CONTEXT RELOAD: [%s]\n", default_context);
+
+ ast_destroy(cfg);
+
+ return 0;
+}
+
+void delete_users(void)
+{
+ struct oh323_user *user, *userlast;
+ struct oh323_peer *peer;
+
+ /* Delete all users */
+ ast_pthread_mutex_lock(&userl.lock);
+ for (user=userl.users;user;) {
+ userlast = user;
+ user=user->next;
+ free(userlast);
+ }
+ userl.users=NULL;
+ ast_pthread_mutex_unlock(&userl.lock);
+ ast_pthread_mutex_lock(&peerl.lock);
+ for (peer=peerl.peers;peer;) {
+ /* Assume all will be deleted, and we'll find out for sure later */
+ peer->delme = 1;
+ peer = peer->next;
+ }
+ ast_pthread_mutex_unlock(&peerl.lock);
+}
+
+void delete_aliases(void)
+{
+ struct oh323_alias *alias, *aliaslast;
+
+ /* Delete all users */
+ ast_pthread_mutex_lock(&aliasl.lock);
+ for (alias=aliasl.aliases;alias;) {
+ aliaslast = alias;
+ alias=alias->next;
+ free(aliaslast);
+ }
+ aliasl.aliases=NULL;
+ ast_pthread_mutex_unlock(&aliasl.lock);
+}
+
+void prune_peers(void)
+{
+ /* Prune peers who still are supposed to be deleted */
+ struct oh323_peer *peer, *peerlast, *peernext;
+ ast_pthread_mutex_lock(&peerl.lock);
+ peerlast = NULL;
+ for (peer=peerl.peers;peer;) {
+ peernext = peer->next;
+ if (peer->delme) {
+ free(peer);
+ if (peerlast)
+ peerlast->next = peernext;
+ else
+ peerl.peers = peernext;
+ } else
+ peerlast = peer;
+ peer=peernext;
+ }
+ ast_pthread_mutex_unlock(&peerl.lock);
+}
+
+int reload(void)
+{
+ delete_users();
+ delete_aliases();
+ prune_peers();
+
+ if (strlen(gatekeeper)) {
+ h323_gk_urq();
+ }
+
+ reload_config();
+
+ /* Possibly register with a GK */
+ if (!gatekeeper_disable) {
+ if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
+ ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
+ h323_end_process();
+ return -1;
+ }
+ }
+ restart_monitor();
+ return 0;
+}
+
+
+static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
+{
+ struct oh323_pvt *p;
+ p = chan->pvt->pvt;
+ if (p && p->rtp && p->bridge)
+ return p->rtp;
+ return NULL;
+}
+
+static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp)
+{
+ struct oh323_pvt *p;
+ struct sockaddr_in them;
+ struct sockaddr_in us;
+
+ if (!rtp)
+ return 0;
+
+ p = chan->pvt->pvt;
+ if (!p) {
+ ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
+ return -1;
+ }
+
+ ast_rtp_get_peer(rtp, &them);
+ printf("peer is now: %s\n", inet_ntoa(them.sin_addr));
+
+ ast_rtp_set_peer(p->rtp, &them);
+ ast_rtp_get_us(p->rtp, &us);
+
+ h323_native_bridge(p->cd.call_token, inet_ntoa(them.sin_addr), inet_ntoa(us.sin_addr));
+
+ return 0;
+
+}
+
+static struct ast_rtp_protocol oh323_rtp = {
+ get_rtp_info: oh323_get_rtp_peer,
+ set_rtp_peer: oh323_set_rtp_peer,
+};
+
+int load_module()
+{
+ int res;
+
+ /* fire up the H.323 Endpoint */
+ h323_end_point_create();
+
+ res = reload_config();
+ if (!res) {
+ /* Make sure we can register our channel type */
+ if (ast_channel_register(type, tdesc, capability, oh323_request)) {
+ ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
+ h323_end_process();
+ return -1;
+ }
+ ast_cli_register(&cli_debug);
+ ast_cli_register(&cli_no_debug);
+ ast_cli_register(&cli_trace);
+ ast_cli_register(&cli_no_trace);
+ ast_cli_register(&cli_show_codecs);
+ ast_cli_register(&cli_gk_cycle);
+
+ oh323_rtp.type = type;
+ ast_rtp_proto_register(&oh323_rtp);
+
+ sched = sched_context_create();
+ if (!sched) {
+ ast_log(LOG_WARNING, "Unable to create schedule context\n");
+ }
+ io = io_context_create();
+ if (!io) {
+ ast_log(LOG_WARNING, "Unable to create I/O context\n");
+ }
+
+ /* Register our callback functions */
+ h323_callback_register(setup_incoming_call,
+ setup_outgoing_call,
+ create_connection,
+ setup_rtp_connection,
+ cleanup_connection,
+ connection_made, send_digit);
+
+ /* start the h.323 listener */
+ if (h323_start_listener(port, bindaddr, jitter)) {
+ ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
+ h323_end_process();
+ return -1;
+ }
+
+ /* Possibly register with a GK */
+ if (!gatekeeper_disable) {
+ if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
+ ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
+ h323_end_process();
+ return -1;
+ }
+ }
+ /* And start the monitor for the first time */
+ restart_monitor();
+ } else {
+ h323_end_process();
+ }
+ return res;
+}
+int unload_module()
+{
+ struct oh323_pvt *p, *pl;
+
+ if (!ast_pthread_mutex_lock(&iflock)) {
+ /* hangup all interfaces if they have an owner */
+ p = iflist;
+ while(p) {
+ if (p->owner)
+ ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
+ p = p->next;
+ }
+ iflist = NULL;
+ ast_pthread_mutex_unlock(&iflock);
+ } else {
+ ast_log(LOG_WARNING, "Unable to lock the interface list\n");
+ return -1;
+ }
+
+ if (!ast_pthread_mutex_lock(&iflock)) {
+ /* destroy all the interfaces and free their memory */
+ p = iflist;
+ while(p) {
+ pl = p;
+ p = p->next;
+ /* free associated memory */
+ free(pl);
+ }
+ iflist = NULL;
+ ast_pthread_mutex_unlock(&iflock);
+ } else {
+ ast_log(LOG_WARNING, "Unable to lock the interface list\n");
+ return -1;
+ }
+ h323_gk_urq();
+ h323_end_process();
+
+ /* unregister channel type */
+ ast_channel_unregister(type);
+
+ return 0;
+
+}
+
+int usecount()
+{
+ int res;
+ ast_pthread_mutex_lock(&usecnt_lock);
+ res = usecnt;
+ ast_pthread_mutex_unlock(&usecnt_lock);
+ return res;
+}
+
+char *description()
+{
+ return desc;
+}
+
+char *key()
+{
+ return ASTERISK_GPL_KEY;
+}
+
+
+
+
diff --git a/channels/h323/chan_h323.h b/channels/h323/chan_h323.h
new file mode 100755
index 000000000..ec718f9a1
--- /dev/null
+++ b/channels/h323/chan_h323.h
@@ -0,0 +1,186 @@
+/*
+ * chan_oh323.h
+ *
+ * OpenH323 Channel Driver for ASTERISK PBX.
+ * By Jeremy McNamara
+ * For The NuFone Network
+ *
+ * This code has been derived from code created by
+ * Michael Manousos and Mark Spencer
+ *
+ * This file is part of the chan_oh323 driver for Asterisk
+ *
+ * chan_oh323 is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * chan_oh323 is distributed WITHOUT ANY WARRANTY; without even
+ * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ */
+
+#include <arpa/inet.h>
+
+static struct sockaddr_in bindaddr;
+
+/* structure to hold the valid asterisk users */
+struct oh323_user {
+ char name[80];
+ char context[80];
+ char secret[80];
+ char callerid[80];
+ char accountcode[20];
+ int amaflags;
+ int noFastStart;
+ int noH245Tunneling;
+ int noSilenceSuppression;
+ int inUse;
+ int incominglimit;
+ int bridge;
+ int nat;
+ int dtmfmode;
+ struct ast_ha *ha;
+ struct sockaddr_in addr;
+ struct oh323_user *next;
+};
+
+/* structure to hold the valid asterisk peers
+ All peers are registered to a GK if there is one */
+struct oh323_peer {
+ char name[80];
+ char context[80];
+ int noFastStart;
+ int noH245Tunneling;
+ int noSilenceSuppression;
+ int inUse;
+ int outgoinglimit;
+ int bridge;
+ int nat;
+ int dtmfmode;
+ struct sockaddr_in addr;
+ int delme;
+ struct oh323_peer *next;
+};
+
+/* structure to hold the H.323 aliases which get registered to
+ the H.323 endpoint and gatekeeper */
+struct oh323_alias {
+ char name[80];
+ char e164[20]; /* tells a GK to route this E.164 to this alias */
+ char prefix[500]; /* tells a GK this alias supports these prefixes */
+ char secret[20]; /* the H.235 password to send to the GK for authentication */
+ char context[80];
+ struct oh323_alias *next;
+};
+
+/** call_option struct is filled from the
+ PBX application and passed through make_call
+ function*/
+typedef struct call_options {
+ int noFastStart;
+ int noH245Tunnelling;
+ int noSilenceSuppression;
+ int jitter;
+ unsigned int port;
+} call_options_t;
+
+/** call_details struct call detail records
+ to asterisk for processing and used for matching up
+ asterisk channels to acutal h.323 connections */
+typedef struct call_details {
+ unsigned int call_reference;
+ const char *call_token;
+ const char *call_source_aliases;
+ const char *call_dest_alias;
+ const char *call_source_e164;
+ const char *call_dest_e164;
+ const char *sourceIp;
+} call_details_t;
+
+/* This is a callback prototype function, called pass
+ DTMF down the RTP. */
+typedef int (*send_digit_cb)(unsigned, char);
+send_digit_cb on_send_digit;
+
+/* This is a callback prototype function, called to collect
+ the external RTP port from Asterisk. */
+typedef int (*on_connection_cb)(unsigned);
+on_connection_cb on_create_connection;
+
+/* This is a callback prototype function, called upon
+ an incoming call happens. */
+typedef int (*setup_incoming_cb)(call_details_t);
+setup_incoming_cb on_incoming_call;
+
+/* This is a callback prototype function, called upon
+ an outbound call. */
+typedef int (*setup_outbound_cb)(call_details_t);
+setup_outbound_cb on_outgoing_call;
+
+/* This is a callback prototype function, called when the openh323
+ OnStartLogicalChannel is invoked. */
+typedef void (*start_logchan_cb)(unsigned int, const char *, int);
+start_logchan_cb on_start_logical_channel;
+
+/* This is a callback protoype function, called when the openh323
+ OnConnectionEstablished is inovked */
+typedef void (*con_established_cb)(unsigned);
+con_established_cb on_connection_established;
+
+/* This is a callback prototype function, called when the openH323
+ OnConnectionCleared callback is invoked */
+typedef void (*clear_con_cb)(call_details_t);
+clear_con_cb on_connection_cleared;
+
+/* debug flag */
+int h323debug;
+
+#define H323_DTMF_RFC2833 (1 << 0)
+#define H323_DTMF_INBAND (1 << 1)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ void h323_gk_urq(void);
+ void h323_end_point_create(void);
+ void h323_end_process(void);
+ int end_point_exist(void);
+
+ void h323_debug(int, unsigned);
+
+ /* callback function handler*/
+ void h323_callback_register(setup_incoming_cb, setup_outbound_cb, on_connection_cb, start_logchan_cb, clear_con_cb, con_established_cb, send_digit_cb);
+
+ int h323_set_capability(int, int);
+ int h323_set_alias(struct oh323_alias *);
+ int h323_set_gk(int, char *, char *);
+
+ /* H323 listener related funcions */
+ int h323_start_listener(int, struct sockaddr_in, int);
+
+ void h323_native_bridge(const char *, char *, char *);
+
+ /* Send a DTMF tone to remote endpoint */
+ void h323_send_tone(const char *call_token, char tone);
+
+ /* H323 create and destroy sessions */
+ int h323_make_call(char *host, call_details_t *cd, call_options_t);
+ int h323_clear_call(const char *);
+ int h323_answering_call(const char *token, int);
+
+ int h323_show_codec(int fd, int argc, char *argv[]);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
diff --git a/channels/h323/h323.conf.sample b/channels/h323/h323.conf.sample
new file mode 100755
index 000000000..c3009fb83
--- /dev/null
+++ b/channels/h323/h323.conf.sample
@@ -0,0 +1,138 @@
+; The NuFone Network's
+; Open H.323 driver configuration
+;
+[general]
+port = 1720
+bindaddr = 0.0.0.0
+;tos=lowdelay
+;
+; You may specify a global default AMA flag for iaxtel calls. It must be
+; one of 'default', 'omit', 'billing', or 'documentation'. These flags
+; are used in the generation of call detail records.
+;
+;amaflags = default
+;
+; You may specify a default account for Call Detail Records in addition
+; to specifying on a per-user basis
+;
+;accountcode=lss0101
+;
+; You can fine tune codecs here using "allow" and "disallow" clauses
+; with specific codecs. Use "all" to represent all formats.
+;
+;allow=all ; turns on all installed codecs
+;disallow=g723.1 ; Hm... Proprietary, don't use it...
+;allow=gsm ; Always allow GSM, it's cool :)
+;allow=ulaw
+;
+; Options for broken H.323 stacks
+;noFastStart = no
+;noH245Tunneling = no
+;noSilenceSuppression = no
+;
+; jitter buffer
+;jitter = 100
+;
+; User-Input Mode (DTMF)
+;
+; valid entries are: rfc2833, inband
+; default is rfc2833
+;dtmfmode=rfc2833
+;
+; Set the gatekeeper
+; DISCOVER - Find the Gk address using multicast
+; DISABLE - Disable the use of a GK
+; <IP address> or <Host name> - The acutal IP address or hostname of your GK
+;gatekeeper = DISABLE
+;
+;
+; Tell Asterisk whether or not to accept Gatekeeper
+; routed calls or not. Normally this should always
+; be set to yes, unless you want to have finer control
+; over which users are allowed access to Asterisk.
+; Default: YES
+;
+;AllowGKRouted = yes
+;
+; Default context gets used in siutations where you are using
+; the GK routed model or no type=user was found. This gives you
+; the ability to either play an invalid message or to simply not
+; use user authentication at all.
+;
+;context=default
+;
+; H.323 Alias definitions
+;
+; Type 'h323' will register aliases to the endpoint
+; and Gatekeeper, if there is one.
+;
+; Example: if someone calls time@your.asterisk.box.com
+; Asterisk will send the call to the extension 'time'
+; in the context default
+;
+; [default]
+; exten => time,1,Answer
+; exten => time,2,Playback,current-time
+;
+; Keyword's 'prefix' and 'e164' are only make sense when
+; used with a gatekeeper. You can specify either a prefix
+; or E.164 this endpoint is responsible for terminating.
+;
+; Example: The H.323 alias 'det-gw' will tell the gatekeeper
+; to route any call with the prefix 1248 to this alias. Keyword
+; e164 is used when you want to specifiy a full telephone
+; number. So a call to the number 18102341212 would be
+; routed to the H.323 alias 'time'.
+;
+;[time]
+;type=h323
+;e164=18102341212
+;context=default
+;
+;[det-gw]
+;type=h323
+;prefix=1248,1313
+;context=detroit
+;
+;
+; Inbound H.323 calls from BillyBob would land in the incoming
+; context with a maximum of 4 concurrent incoming calls
+; using a password of 'supersecret'
+;
+; Note: If keywords 'outgoinglimit' or 'incominglimit' are omitted
+; Asterisk will not enforce any maximum number of concurrent calls.
+;
+; If you wish to use Authentication you need to set the approprate
+; auth keyword above.
+;
+;[BillyBob]
+;type=user
+;secret=supersecret
+;context=incoming
+;incominglimit=4
+;
+; Asterisk would allow 2 concurrent outgoing calls to JoeSmow
+; using 192.168.1.15 as his IP and will use the context outbound
+;
+;[JoeSmo]
+;type=peer
+;host=192.168.1.15
+;context=outgoing
+;outgoinglimit=2
+;
+; Asterisk would allow 6 concurrent incoming calls to be
+; recieved from and 4 concurrent outgoing calls to be placed
+; to SouthOffice using 192.168.0.2 as his IP and
+; 'securepassword' has the password and lands in the
+; default context
+;
+;[SouthOffice]
+;type=friend
+;host=192.168.0.2
+;secret=securepassword
+;context=default
+;incominglimit=6
+;outgoinglimit=4
+
+
+