e912302004ad7c5912059d302419fed9c6108574
[asterisk/asterisk.git] / channels / h323 / ast_h323.cpp
1 /*
2  * ast_h323.cpp
3  *
4  * OpenH323 Channel Driver for ASTERISK PBX.
5  *                      By  Jeremy McNamara
6  *                      For The NuFone Network
7  * 
8  * This code has been derived from code created by
9  *              Michael Manousos and Mark Spencer
10  *
11  * This file is part of the chan_h323 driver for Asterisk
12  *
13  * chan_h323 is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version. 
17  *
18  * chan_h323 is distributed WITHOUT ANY WARRANTY; without even 
19  * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
20  * PURPOSE. See the GNU General Public License for more details. 
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 
25  *
26  * Version Info: $Id$
27  */
28 #include <asterisk/logger.h>
29 #include "ast_h323.h"
30
31
32 /* PWlib Required Components  */
33 #define MAJOR_VERSION 1
34 #define MINOR_VERSION 0
35 #define BUILD_TYPE    ReleaseCode
36 #define BUILD_NUMBER  0
37
38 /** Counter for the number of connections */
39 int channelsOpen;
40
41 /* DTMF Mode */
42 int mode = H323_DTMF_RFC2833;
43
44 /** Options for connections creation */
45 BOOL    noFastStart;
46 BOOL    noH245Tunnelling;
47 BOOL    noSilenceSuppression;
48
49 /**
50  * We assume that only one endPoint should exist.
51  * The application cannot run the h323_end_point_create() more than once
52  * FIXME: Singleton this, for safety
53  */
54 MyH323EndPoint *endPoint = NULL;
55
56 /** PWLib entry point */
57 MyProcess *localProcess = NULL;
58
59
60 MyProcess::MyProcess(): PProcess("The NuFone Network's", "H.323 Channel Driver for Asterisk",
61              MAJOR_VERSION, MINOR_VERSION, BUILD_TYPE, BUILD_NUMBER)
62 {
63         Resume();
64 }
65
66 void MyProcess::Main()
67 {
68         ast_verbose("  == Creating H.323 Endpoint\n");
69         endPoint = new MyH323EndPoint();
70         PTrace::Initialise(0, NULL, PTrace::Timestamp | PTrace::Thread | PTrace::FileAndLine);
71 }
72
73 #define H323_NAME OPAL_G7231_6k3"{sw}"
74 #define H323_G729  OPAL_G729 "{sw}"
75 #define H323_G729A OPAL_G729A"{sw}"
76
77 H323_REGISTER_CAPABILITY(H323_G7231Capability, H323_NAME);
78 H323_REGISTER_CAPABILITY(AST_G729Capability,  H323_G729);
79 H323_REGISTER_CAPABILITY(AST_G729ACapability, H323_G729A);
80
81 H323_G7231Capability::H323_G7231Capability(BOOL annexA_)
82   : H323AudioCapability(7, 4)
83 {
84   annexA = annexA_;
85 }
86
87 PObject::Comparison H323_G7231Capability::Compare(const PObject & obj) const
88 {
89   Comparison result = H323AudioCapability::Compare(obj);
90   if (result != EqualTo)
91     return result;
92
93   PINDEX otherAnnexA = ((const H323_G7231Capability &)obj).annexA;
94   if (annexA < otherAnnexA)
95     return LessThan;
96   if (annexA > otherAnnexA)
97     return GreaterThan;
98   return EqualTo;
99 }
100
101 PObject * H323_G7231Capability::Clone() const
102 {
103   return new H323_G7231Capability(*this);
104 }
105
106
107 PString H323_G7231Capability::GetFormatName() const
108 {
109   return H323_NAME;
110 }
111
112
113 unsigned H323_G7231Capability::GetSubType() const
114 {
115   return H245_AudioCapability::e_g7231;
116 }
117
118
119 BOOL H323_G7231Capability::OnSendingPDU(H245_AudioCapability & cap,
120                                           unsigned packetSize) const
121 {
122   cap.SetTag(H245_AudioCapability::e_g7231);
123
124   H245_AudioCapability_g7231 & g7231 = cap;
125   g7231.m_maxAl_sduAudioFrames = packetSize;
126   g7231.m_silenceSuppression = annexA;
127
128   return TRUE;
129 }
130
131
132 BOOL H323_G7231Capability::OnReceivedPDU(const H245_AudioCapability & cap,
133                                            unsigned & packetSize)
134 {
135   if (cap.GetTag() != H245_AudioCapability::e_g7231)
136     return FALSE;
137
138   const H245_AudioCapability_g7231 & g7231 = cap;
139   packetSize = g7231.m_maxAl_sduAudioFrames;
140   annexA = g7231.m_silenceSuppression;
141
142   return TRUE;
143 }
144
145
146 H323Codec * H323_G7231Capability::CreateCodec(H323Codec::Direction direction) const
147 {
148   return NULL;
149 }
150
151
152 /////////////////////////////////////////////////////////////////////////////
153
154 AST_G729Capability::AST_G729Capability()
155   : H323AudioCapability(24, 6)
156 {
157 }
158
159
160 PObject * AST_G729Capability::Clone() const
161 {
162   return new AST_G729Capability(*this);
163 }
164
165
166 unsigned AST_G729Capability::GetSubType() const
167 {
168   return H245_AudioCapability::e_g729;
169 }
170
171
172 PString AST_G729Capability::GetFormatName() const
173 {
174   return H323_G729;
175 }
176
177
178 H323Codec * AST_G729Capability::CreateCodec(H323Codec::Direction direction) const
179 {
180   return NULL;
181 }
182 /////////////////////////////////////////////////////////////////////////////
183
184 AST_G729ACapability::AST_G729ACapability()
185   : H323AudioCapability(24, 6)
186 {
187 }
188
189
190 PObject * AST_G729ACapability::Clone() const
191 {
192   return new AST_G729ACapability(*this);
193 }
194
195
196 unsigned AST_G729ACapability::GetSubType() const
197 {
198   return H245_AudioCapability::e_g729AnnexA;
199 }
200
201
202 PString AST_G729ACapability::GetFormatName() const
203 {
204   return H323_G729A;
205 }
206
207
208 H323Codec * AST_G729ACapability::CreateCodec(H323Codec::Direction direction) const
209 {
210   return NULL;
211 }
212
213 /** MyH323EndPoint 
214   * The fullAddress parameter is used directly in the MakeCall method so
215   * the General form for the fullAddress argument is :
216   * [alias@][transport$]host[:port]
217   * default values:     alias = the same value as host.
218   *                                     transport = ip.
219   *                                     port = 1720.
220   */
221 int MyH323EndPoint::MakeCall(const PString & dest, PString & token, 
222                                                                                 unsigned int *callReference, unsigned int port, char *callerid)
223 {
224         PString fullAddress;
225         MyH323Connection * connection;
226
227         /* Determine whether we are using a gatekeeper or not. */
228         if (GetGatekeeper() != NULL) {
229                 fullAddress = dest;
230                 if (h323debug)
231                         cout << " -- Making call to " << fullAddress << " using gatekeeper." << endl;
232         } else {
233                         fullAddress = dest; /* host */
234                         if (h323debug)
235                                 cout << " -- Making call to " << fullAddress << "." << endl;
236         }
237
238         if (!(connection = (MyH323Connection *)H323EndPoint::MakeCallLocked(fullAddress, token))) {
239                 if (h323debug)
240                         cout << "Error making call to \"" << fullAddress << '"' << endl;
241                 return 1;
242         }
243         
244         *callReference = connection->GetCallReference();
245         
246         if (callerid)
247                 connection->SetLocalPartyName(PString(callerid));
248
249         connection->Unlock();   
250
251         if (h323debug) {
252                 cout << "       -- " << GetLocalUserName() << " is calling host " << fullAddress << endl;
253                 cout << "       -- " << "Call token is " << (const char *)token << endl;
254                 cout << "       -- Call reference is " << *callReference << endl;
255         }
256         return 0;
257 }
258
259 void MyH323EndPoint::SetEndpointTypeInfo( H225_EndpointType & info ) const
260 {
261   H323EndPoint::SetEndpointTypeInfo(info);
262   info.m_gateway.IncludeOptionalField(H225_GatewayInfo::e_protocol);
263   info.m_gateway.m_protocol.SetSize(1);
264   H225_SupportedProtocols &protocol=info.m_gateway.m_protocol[0];
265   protocol.SetTag(H225_SupportedProtocols::e_voice);
266   PINDEX as=SupportedPrefixes.GetSize();
267   ((H225_VoiceCaps &)protocol).m_supportedPrefixes.SetSize(as);
268   for (PINDEX p=0; p<as; p++) {
269     H323SetAliasAddress(SupportedPrefixes[p], ((H225_VoiceCaps &)protocol).m_supportedPrefixes[p].m_prefix);
270   }
271 }
272
273 void MyH323EndPoint::SetGateway(void)
274 {
275         terminalType = e_GatewayOnly;
276 }
277
278 H323Capabilities MyH323EndPoint::GetCapabilities(void)
279 {
280         return capabilities;
281 }
282
283 BOOL MyH323EndPoint::ClearCall(const PString & token)
284 {
285         if (h323debug) {
286                 cout << "       -- ClearCall: Request to clear call with token " << token << endl;
287         }
288         return H323EndPoint::ClearCall(token);
289 }
290
291 void MyH323EndPoint::SendUserTone(const PString &token, char tone)
292 {
293         H323Connection *connection = NULL;
294                 
295         connection = FindConnectionWithLock(token);
296         if (connection != NULL) {
297                 connection->SendUserInputTone(tone, 500);
298                 connection->Unlock();
299         }
300 }
301
302 void MyH323EndPoint::OnClosedLogicalChannel(H323Connection & connection, const H323Channel & channel)
303 {
304         channelsOpen--;
305         if (h323debug)
306                 cout << "               channelsOpen = " << channelsOpen << endl;
307         H323EndPoint::OnClosedLogicalChannel(connection, channel);
308 }
309
310 BOOL MyH323EndPoint::OnConnectionForwarded(H323Connection & connection,
311                 const PString & forwardParty,
312                 const H323SignalPDU & pdu)
313  {
314         if (h323debug) {
315                 cout << "       -- Call Forwarded to " << forwardParty << endl;
316         }
317         return FALSE;
318  }
319  
320 BOOL MyH323EndPoint::ForwardConnection(H323Connection & connection,
321                 const PString & forwardParty,
322                 const H323SignalPDU & pdu)
323 {
324         if (h323debug) {
325                 cout << "       -- Forwarding call to " << forwardParty << endl;
326         }
327         return H323EndPoint::ForwardConnection(connection, forwardParty, pdu);
328 }
329
330 void MyH323EndPoint::OnConnectionEstablished(H323Connection & connection, const PString & estCallToken)
331 {
332         if (h323debug) {
333                 cout << "       -- Connection Established with \"" << connection.GetRemotePartyName() << "\"" << endl;
334         }
335         on_connection_established(connection.GetCallReference());
336 }
337
338 /** OnConnectionCleared callback function is called upon the dropping of an established
339   * H323 connection. 
340   */
341 void MyH323EndPoint::OnConnectionCleared(H323Connection & connection, const PString & clearedCallToken)
342 {
343         PString remoteName = connection.GetRemotePartyName();
344         
345         call_details_t cd;
346
347         cd.call_reference = connection.GetCallReference();
348         cd.call_token = (const char *)connection.GetCallToken();
349         cd.call_source_aliases = (const char *)connection.GetRemotePartyName();
350         
351         /* Convert complex strings */
352         char *s;
353         if ((s = strchr(cd.call_source_aliases, ' ')) != NULL)
354                 *s = '\0';
355
356         /* Invoke the PBX application registered callback */
357         on_connection_cleared(cd);
358
359         switch (connection.GetCallEndReason()) {
360                 case H323Connection::EndedByCallForwarded :
361                         if (h323debug)
362                                 cout << " -- " << remoteName << " has forwarded the call" << endl;
363                         break;
364                 case H323Connection::EndedByRemoteUser :
365                         if (h323debug)
366                                 cout << " -- " << remoteName << " has cleared the call" << endl;
367                         break;
368                 case H323Connection::EndedByCallerAbort :
369                         if (h323debug)
370                                 cout << " -- " << remoteName << " has stopped calling" << endl;
371                         break;
372                 case H323Connection::EndedByRefusal :
373                         if (h323debug)
374                                 cout << " -- " << remoteName << " did not accept your call" << endl;
375                         break;
376                 case H323Connection::EndedByRemoteBusy :
377                         if (h323debug)
378                         cout << " -- " << remoteName << " was busy" << endl;
379                         break;
380                 case H323Connection::EndedByRemoteCongestion :
381                         if (h323debug)
382                                 cout << " -- Congested link to " << remoteName << endl;
383                         break;
384                 case H323Connection::EndedByNoAnswer :
385                         if (h323debug)
386                                 cout << " -- " << remoteName << " did not answer your call" << endl;
387                         break;
388                 case H323Connection::EndedByTransportFail :
389                         if (h323debug)
390                                 cout << " -- Call with " << remoteName << " ended abnormally" << endl;
391                         break;
392                 case H323Connection::EndedByCapabilityExchange :
393                         if (h323debug)
394                                 cout << " -- Could not find common codec with " << remoteName << endl;
395                         break;
396                 case H323Connection::EndedByNoAccept :
397                         if (h323debug)
398                                 cout << " -- Did not accept incoming call from " << remoteName << endl;
399                         break;
400                 case H323Connection::EndedByAnswerDenied :
401                         if (h323debug)
402                                 cout << " -- Refused incoming call from " << remoteName << endl;
403                         break;
404                 case H323Connection::EndedByNoUser :
405                         if (h323debug)
406                                 cout << " -- Remote endpoint could not find user: " << remoteName << endl;
407                         break;
408                 case H323Connection::EndedByNoBandwidth :
409                         if (h323debug)
410                                 cout << " -- Call to " << remoteName << " aborted, insufficient bandwidth." << endl;
411                         break;
412                 case H323Connection::EndedByUnreachable :
413                         if (h323debug)
414                                 cout << " -- " << remoteName << " could not be reached." << endl;
415                         break;
416                 case H323Connection::EndedByHostOffline :
417                         if (h323debug)
418                                 cout << " -- " << remoteName << " is not online." << endl;
419                         break;
420                 case H323Connection::EndedByNoEndPoint :
421                         if (h323debug)
422                                 cout << " -- No phone running for " << remoteName << endl;
423                         break;
424                 case H323Connection::EndedByConnectFail :
425                         if (h323debug)
426                                 cout << " -- Transport error calling " << remoteName << endl;
427                         break;
428                 default :
429                         if (h323debug)
430                                 cout << " -- Call with " << remoteName << " completed (" << connection.GetCallEndReason() << ")" << endl;
431
432         }
433
434         if(connection.IsEstablished()) 
435                 if (h323debug)
436                         cout << "        -- Call duration " << setprecision(0) << setw(5) << (PTime() - connection.GetConnectionStartTime()) << endl;
437 }
438
439
440 H323Connection * MyH323EndPoint::CreateConnection(unsigned callReference, void *outbound)
441 {
442         unsigned options = 0;
443
444         if (noFastStart)
445                 options |= H323Connection::FastStartOptionDisable;
446
447         if (noH245Tunnelling)
448                 options |= H323Connection::H245TunnelingOptionDisable;
449
450         return new MyH323Connection(*this, callReference, options);
451 }
452
453 /* MyH323Connection */    
454 MyH323Connection::MyH323Connection(MyH323EndPoint & ep, unsigned callReference,
455                                                         unsigned options)
456         : H323Connection(ep, callReference, options)
457 {
458         remoteIpAddress = 0;    // IP Address of remote endpoint
459         remotePort      = 0;    // remote endpoint Data port (control is dataPort+1)
460
461         if (h323debug) {
462                 cout << "       == New H.323 Connection created." << endl;
463         }
464         return;
465 }
466
467 MyH323Connection::~MyH323Connection()
468 {
469         if (h323debug) {
470                 cout << "       == H.323 Connection deleted." << endl;
471         }
472         return;
473 }
474
475 H323Connection::AnswerCallResponse MyH323Connection::OnAnswerCall(const PString & caller,
476                                                                                                                                    const H323SignalPDU & /*setupPDU*/,
477                                                                                                                                    H323SignalPDU & /*connectPDU*/)
478 {
479         /* The call will be answered later with "AnsweringCall()" function.
480          */ 
481         return H323Connection::AnswerCallAlertWithMedia;
482 }
483
484 BOOL  MyH323Connection::OnAlerting(const H323SignalPDU & /*alertingPDU*/, const PString & username)
485 {
486         
487         if (h323debug) {
488                 cout << "       -- Ringing phone for \"" << username << "\"" << endl;
489         }
490         return TRUE;
491 }
492
493 BOOL MyH323Connection::OnReceivedSignalSetup(const H323SignalPDU & setupPDU)
494 {
495         
496         if (h323debug) {
497                 ast_verbose("   -- Received SETUP message\n");
498         }
499         
500         call_details_t cd;
501         PString sourceE164;
502         PString destE164;
503         PString sourceAliases;  
504         PString destAliases;
505         PString sourceIp;       
506         PIPSocket::Address Ip;
507         WORD sourcePort;
508
509         sourceAliases = setupPDU.GetSourceAliases();
510         destAliases = setupPDU.GetDestinationAlias();
511                         
512         sourceE164 = "";
513         setupPDU.GetSourceE164(sourceE164);
514         destE164 = "";
515         setupPDU.GetDestinationE164(destE164);
516
517         /* Convert complex strings */
518         //  FIXME: deal more than one source alias 
519         char *s; 
520         if ((s = strchr(sourceAliases, ' ')) != NULL)
521                 *s = '\0';
522         if ((s = strchr(sourceAliases, '\t')) != NULL)
523                 *s = '\0';
524         char *s1;
525         if ((s1 = strchr(destAliases, ' ')) != NULL)
526                 *s1 = '\0';
527         if ((s1 = strchr(destAliases, '\t')) != NULL)
528                 *s1 = '\0';
529
530         GetSignallingChannel()->GetRemoteAddress().GetIpAndPort(Ip, sourcePort);
531
532         sourceIp = Ip.AsString();
533
534         cd.call_reference               = GetCallReference();
535         cd.call_token                   = (const char *)GetCallToken();
536         cd.call_source_aliases  = (const char *)sourceAliases;
537         cd.call_dest_alias              = (const char *)destAliases;
538         cd.call_source_e164             = (const char *)sourceE164;
539         cd.call_dest_e164               = (const char *)destE164;
540         cd.sourceIp                             = (const char *)sourceIp;
541         
542         /* Notify Asterisk of the request */
543         int res = on_incoming_call(cd); 
544
545         if (!res) {
546                 if (h323debug) {
547                         cout << "       -- Call Failed" << endl;
548                 }
549                 return FALSE;
550         }
551         
552         return H323Connection::OnReceivedSignalSetup(setupPDU);
553 }
554
555 BOOL MyH323Connection::OnSendSignalSetup(H323SignalPDU & setupPDU)
556 {
557         call_details_t cd;
558         
559         if (h323debug) { 
560                 cout << "       -- Sending SETUP message" << endl;
561         }
562         sourceAliases = setupPDU.GetSourceAliases();
563         destAliases = setupPDU.GetDestinationAlias();
564
565         sourceE164 = "";
566         setupPDU.GetSourceE164(sourceE164);
567         destE164 = "";
568         setupPDU.GetDestinationE164(destE164);
569
570         /* Convert complex strings */
571         //  FIXME: deal more than one source alias 
572         char *s; 
573         if ((s = strchr(sourceAliases, ' ')) != NULL)
574                 *s = '\0';
575         if ((s = strchr(sourceAliases, '\t')) != NULL)
576                 *s = '\0';
577         char *s1;
578         if ((s1 = strchr(destAliases, ' ')) != NULL)
579                  *s1 = '\0';
580         if ((s1 = strchr(destAliases, '\t')) != NULL)
581                 *s1 = '\0';
582
583         cd.call_reference               = GetCallReference();
584         cd.call_token                   = (const char *)GetCallToken();
585         cd.call_source_aliases  = (const char *)sourceAliases;
586         cd.call_dest_alias              = (const char *)destAliases;
587         cd.call_source_e164             = (const char *)sourceE164;
588         cd.call_dest_e164               = (const char *)destE164;
589
590         int res = on_outgoing_call(cd); 
591                 
592         if (!res) {
593                 if (h323debug) {
594                         cout << "       -- Call Failed" << endl;
595                 }
596                 return FALSE;
597         }
598
599         return H323Connection::OnSendSignalSetup(setupPDU);
600 }
601
602 BOOL MyH323Connection::OnSendReleaseComplete(H323SignalPDU & releaseCompletePDU)
603 {
604         if (h323debug) {
605                 cout << "       -- Sending RELEASE COMPLETE" << endl;
606         }
607         return H323Connection::OnSendReleaseComplete(releaseCompletePDU);
608 }
609
610 BOOL MyH323Connection::OnReceivedFacility(const H323SignalPDU & pdu)
611 {
612         if (h323debug) {
613                 cout << "       -- Received Facility message... " << endl;
614         }       
615         return H323Connection::OnReceivedFacility(pdu);
616 }
617
618 void MyH323Connection::OnReceivedReleaseComplete(const H323SignalPDU & pdu)
619 {
620         if (h323debug) {
621                 cout <<  "      -- Received RELEASE COMPLETE message..." << endl;
622         }
623         return H323Connection::OnReceivedReleaseComplete(pdu);
624 }
625
626 BOOL MyH323Connection::OnClosingLogicalChannel(H323Channel & channel)
627 {
628         if (h323debug) {
629                 cout << "       -- Closing logical channel..." << endl;
630         }
631         return H323Connection::OnClosingLogicalChannel(channel);
632 }
633
634
635 void MyH323Connection::SendUserInputTone(char tone, unsigned duration)
636 {
637         if (h323debug) {
638                 cout << "       -- Sending user input tone (" << tone << ") to remote" << endl;
639         }
640         on_send_digit(GetCallReference(), tone);        
641         H323Connection::SendUserInputTone(tone, duration);
642 }
643
644 void MyH323Connection::OnUserInputTone(char tone, unsigned duration, unsigned logicalChannel, unsigned rtpTimestamp)
645 {
646         if (mode == H323_DTMF_INBAND) {
647                 if (h323debug) {
648                         cout << "       -- Received user input tone (" << tone << ") from remote" << endl;
649                 }
650                 on_send_digit(GetCallReference(), tone);
651         }
652         H323Connection::OnUserInputTone(tone, duration, logicalChannel, rtpTimestamp);
653 }
654
655 void MyH323Connection::OnUserInputString(const PString &value)
656 {
657         if (mode == H323_DTMF_RFC2833) {
658                 if (h323debug) {
659                         cout <<  "      -- Received user input string (" << value << ") from remote." << endl;
660                 }
661                 on_send_digit(GetCallReference(), value[0]);
662         }       
663 }
664
665 H323Channel * MyH323Connection::CreateRealTimeLogicalChannel(const H323Capability & capability, 
666                                                                    H323Channel::Directions dir,
667                                                                    unsigned sessionID,
668                                                                    const H245_H2250LogicalChannelParameters * /*param*/)
669 {
670         struct rtp_info *info;
671         WORD port;
672
673         /* Determine the Local (A side) IP Address and port */
674         info = on_create_connection(GetCallReference()); 
675
676         if (!info) {
677                 return NULL;
678         }
679
680         GetControlChannel().GetLocalAddress().GetIpAndPort(externalIpAddress, port);
681         externalPort = info->port;
682         
683         if (h323debug) {
684                 cout << "       =*= In CreateRealTimeLogicalChannel for call " << GetCallReference() << endl;
685                 cout << "               -- externalIpAddress: " << externalIpAddress << endl;
686                 cout << "               -- externalPort: " << externalPort << endl;
687                 cout << "               -- SessionID: " << sessionID << endl;
688                 cout << "               -- Direction: " << dir << endl;
689         }
690         return new MyH323_ExternalRTPChannel(*this, capability, dir, sessionID, externalIpAddress, externalPort);
691 }
692
693 /** This callback function is invoked once upon creation of each
694   * channel for an H323 session 
695   */
696 BOOL MyH323Connection::OnStartLogicalChannel(H323Channel & channel)
697 {    
698         if (h323debug) {
699                 cout << "        -- Started logical channel: "; 
700                 cout << ((channel.GetDirection()==H323Channel::IsTransmitter)?"sending ":((channel.GetDirection()==H323Channel::IsReceiver)?"receiving ":" ")); 
701                 cout << (const char *)(channel.GetCapability()).GetFormatName() << endl;
702         }
703         // adjust the count of channels we have open
704         channelsOpen++;
705         if (h323debug) {
706                 cout <<  "              -- channelsOpen = " << channelsOpen << endl;
707         }
708         H323_ExternalRTPChannel & external = (H323_ExternalRTPChannel &)channel;
709         external.GetRemoteAddress(remoteIpAddress, remotePort); 
710
711         if (h323debug) {
712                 cout << "               -- remoteIpAddress: " << remoteIpAddress << endl;
713                 cout << "               -- remotePort: " << remotePort << endl;
714                 cout << "               -- ExternalIpAddress: " << externalIpAddress << endl;
715                 cout << "               -- ExternalPort: " << externalPort << endl;
716         }
717         /* Notify Asterisk of remote RTP information */
718         on_start_logical_channel(GetCallReference(), (const char *)remoteIpAddress.AsString(), remotePort);
719
720         return TRUE;    
721 }
722
723 /* MyH323_ExternalRTPChannel */
724 MyH323_ExternalRTPChannel::MyH323_ExternalRTPChannel(MyH323Connection & connection,
725                                                                                                         const H323Capability & capability,
726                                                                                                         Directions direction,
727                                                                                                         unsigned sessionID,
728                                                                                                         const PIPSocket::Address & ip,
729                                                                                                         WORD dataPort)
730         : H323_ExternalRTPChannel(connection, capability, direction, sessionID, ip, dataPort)
731 {
732         if (h323debug) {
733                 cout << "       == New H.323 ExternalRTPChannel created." << endl;
734         }
735         return;
736 }
737
738 MyH323_ExternalRTPChannel::~MyH323_ExternalRTPChannel()
739 {
740         if (h323debug) {
741                 cout << "       == H.323 ExternalRTPChannel deleted." << endl;
742         }
743         return;
744 }
745
746 BOOL MyH323_ExternalRTPChannel::OnReceivedPDU(
747                                 const H245_H2250LogicalChannelParameters & param,
748                                 unsigned & errorCode)
749 {
750         if (h323debug) {
751                 cout << "       MyH323_ExternalRTPChannel::OnReceivedPDU " << endl;
752         }
753         return H323_ExternalRTPChannel::OnReceivedPDU( param, errorCode );
754 }
755
756 BOOL MyH323_ExternalRTPChannel::OnReceivedAckPDU(
757                                 const H245_H2250LogicalChannelAckParameters & param)
758 {
759
760         PIPSocket::Address remoteIpAddress;             // IP Address of remote endpoint
761         WORD                       remotePort;                  // remote endpoint Data port (control is dataPort+1)
762
763         if (h323debug) {
764                 cout << "       MyH323_ExternalRTPChannel::OnReceivedAckPDU " << endl;
765         }
766
767         if (H323_ExternalRTPChannel::OnReceivedAckPDU( param )) {
768                 GetRemoteAddress(remoteIpAddress, remotePort);
769                 if (h323debug) {
770                         cout << "               -- remoteIpAddress: " << remoteIpAddress << endl;
771                         cout << "               -- remotePort: " << remotePort << endl;
772                 }
773                 /* Notify Asterisk of remote RTP information */
774                 on_start_logical_channel(connection.GetCallReference(), (const char *)remoteIpAddress.AsString(), remotePort);
775                 return TRUE;
776         }
777         return FALSE;
778 }
779
780
781 /** IMPLEMENTATION OF C FUNCTIONS */
782
783 /**
784  * The extern "C" directive takes care for 
785  * the ANSI-C representation of linkable symbols 
786  */
787 extern "C" {
788
789 int h323_end_point_exist(void)
790 {
791         if (!endPoint) {
792                 return 0;
793         }
794         return 1;
795 }
796     
797 void h323_end_point_create(void)
798 {
799         channelsOpen = 0;
800         localProcess = new MyProcess(); 
801         localProcess->Main();
802 }
803
804 void h323_gk_urq(void)
805 {
806         if (!h323_end_point_exist()) {
807                 cout << " ERROR: [h323_gk_urq] No Endpoint, this is bad" << endl;
808                 return;
809         }       
810         endPoint->RemoveGatekeeper();
811 }
812
813 void h323_end_process(void)
814 {
815         endPoint->ClearAllCalls();
816         endPoint->RemoveListener(NULL);
817         delete endPoint;
818         delete localProcess;
819 }
820
821 void h323_debug(int flag, unsigned level)
822 {
823         if (flag) {
824                 PTrace:: SetLevel(level); 
825         } else { 
826                 PTrace:: SetLevel(0); 
827         }
828 }
829         
830 /** Installs the callback functions on behalf of the PBX application  */
831 void h323_callback_register(setup_incoming_cb   ifunc,
832                             setup_outbound_cb   sfunc,
833                             on_connection_cb    confunc,
834                             start_logchan_cb    lfunc,
835                             clear_con_cb        clfunc,
836                             con_established_cb  efunc,
837                             send_digit_cb       dfunc)
838 {
839         on_incoming_call = ifunc;
840         on_outgoing_call = sfunc;
841         on_create_connection = confunc;
842         on_start_logical_channel = lfunc;
843         on_connection_cleared = clfunc;
844         on_connection_established = efunc;
845         on_send_digit = dfunc;
846 }
847
848 /**
849  * Add capability to the capability table of the end point. 
850  */
851 int h323_set_capability(int cap, int dtmfMode)
852 {
853         H323Capabilities oldcaps;
854         int g711Frames = 30;
855         int gsmFrames  = 4;
856
857         if (!h323_end_point_exist()) {
858                 cout << " ERROR: [h323_set_capablity] No Endpoint, this is bad" << endl;
859                 return 1;
860         }
861
862         /* clean up old capabilities list before changing */
863         oldcaps = endPoint->GetCapabilities();
864         oldcaps.RemoveAll();
865
866         mode = dtmfMode;
867         if (dtmfMode == H323_DTMF_INBAND) {
868             endPoint->SetSendUserInputMode(H323Connection::SendUserInputAsTone);
869         } else {
870                 endPoint->SetSendUserInputMode(H323Connection::SendUserInputAsInlineRFC2833);
871         }
872         if (cap & AST_FORMAT_SPEEX) {
873                 /* Not real sure if Asterisk acutally supports all
874                    of the various different bit rates so add them 
875                    all and figure it out later*/
876
877                 endPoint->SetCapability(0, 0, new SpeexNarrow2AudioCapability());
878                 endPoint->SetCapability(0, 0, new SpeexNarrow3AudioCapability());
879                 endPoint->SetCapability(0, 0, new SpeexNarrow4AudioCapability());
880                 endPoint->SetCapability(0, 0, new SpeexNarrow5AudioCapability());
881                 endPoint->SetCapability(0, 0, new SpeexNarrow6AudioCapability());
882         }
883
884         if (cap & AST_FORMAT_G729A) {
885                 AST_G729ACapability *g729aCap;
886                 AST_G729Capability *g729Cap;
887                 endPoint->SetCapability(0, 0, g729aCap = new AST_G729ACapability);
888                 endPoint->SetCapability(0, 0, g729Cap = new AST_G729Capability);
889         }
890         
891         if (cap & AST_FORMAT_G723_1) {
892                 H323_G7231Capability *g7231Cap;
893                 endPoint->SetCapability(0, 0, g7231Cap = new H323_G7231Capability);
894         } 
895
896         if (cap & AST_FORMAT_GSM) {
897                 H323_GSM0610Capability *gsmCap;
898                 endPoint->SetCapability(0, 0, gsmCap = new H323_GSM0610Capability);
899                 gsmCap->SetTxFramesInPacket(gsmFrames);
900         } 
901
902         if (cap & AST_FORMAT_ULAW) {
903                 H323_G711Capability *g711uCap;
904                 endPoint->SetCapability(0, 0, g711uCap = new H323_G711Capability(H323_G711Capability::muLaw));
905                 g711uCap->SetTxFramesInPacket(g711Frames);
906         } 
907
908         if (cap & AST_FORMAT_ALAW) {
909                 H323_G711Capability *g711aCap;
910                 endPoint->SetCapability(0, 0, g711aCap = new H323_G711Capability(H323_G711Capability::ALaw));
911                 g711aCap->SetTxFramesInPacket(g711Frames);
912         } 
913
914         if (h323debug) {
915                 cout <<  "Allowed Codecs:\n\t" << setprecision(2) << endPoint->GetCapabilities() << endl;
916         }
917         return 0;
918 }
919
920 /** Start the H.323 listener */
921 int h323_start_listener(int listenPort, struct sockaddr_in bindaddr)
922 {
923         
924         if (!h323_end_point_exist()) {
925                 cout << "ERROR: [h323_start_listener] No Endpoint, this is bad!" << endl;
926                 return 1;
927         }
928         
929         PIPSocket::Address interfaceAddress(bindaddr.sin_addr);
930
931         if (!listenPort) {
932                 listenPort = 1720;
933         }
934
935         /** H.323 listener */  
936         H323ListenerTCP *tcpListener;
937
938         tcpListener = new H323ListenerTCP(*endPoint, interfaceAddress, (WORD)listenPort);
939
940         if (!endPoint->StartListener(tcpListener)) {
941                 cout << "ERROR: Could not open H.323 listener port on " << ((H323ListenerTCP *) tcpListener)->GetListenerPort() << endl;
942                 delete tcpListener;
943                 return 1;
944                 
945         }
946         cout << "  == H.323 listener started" << endl;
947
948         return 0;
949 };
950  
951    
952 int h323_set_alias(struct oh323_alias *alias)
953 {
954         char *p;
955         char *num;
956         PString h323id(alias->name);
957         PString e164(alias->e164);
958         
959         if (!h323_end_point_exist()) {
960                 cout << "ERROR: [h323_set_alias] No Endpoint, this is bad!" << endl;
961                 return 1;
962         }
963
964         cout << "  == Adding alias \"" << h323id << "\" to endpoint" << endl;
965         endPoint->AddAliasName(h323id); 
966         endPoint->RemoveAliasName(localProcess->GetUserName());
967
968         if (!e164.IsEmpty()) {
969                 cout << "  == Adding E.164 \"" << e164 << "\" to endpoint" << endl;
970                 endPoint->AddAliasName(e164);
971         }
972         if (strlen(alias->prefix)) {
973                 p = alias->prefix;
974                 num = strsep(&p, ",");
975                 while(num) {
976                 cout << "  == Adding Prefix \"" << num << "\" to endpoint" << endl;
977                         endPoint->SupportedPrefixes += PString(num);
978                         endPoint->SetGateway();
979                 num = strsep(&p, ",");          
980                 }
981         }
982
983         return 0;
984 }
985
986
987 void h323_set_id(char *id)
988 {
989         PString h323id(id);
990
991         if (h323debug) {
992                 cout << "  == Using '" << h323id << "' as our H.323ID for this call" << endl;
993         }
994
995         /* EVIL HACK */
996         endPoint->SetLocalUserName(h323id);
997 }
998
999 void h323_show_tokens(void)
1000 {
1001         cout << "Current call tokens: " << setprecision(2) << endPoint->GetAllConnections() << endl;
1002 }
1003
1004
1005 /** Establish Gatekeeper communiations, if so configured, 
1006   *     register aliases for the H.323 endpoint to respond to.
1007   */
1008 int h323_set_gk(int gatekeeper_discover, char *gatekeeper, char *secret)
1009 {
1010         PString gkName = PString(gatekeeper);
1011         PString pass   = PString(secret);
1012         H323TransportUDP *rasChannel;
1013
1014         if (!h323_end_point_exist()) {
1015                 cout << "ERROR: [h323_set_gk] No Endpoint, this is bad!" << endl;
1016                 return 1;
1017         }
1018
1019         if (!gatekeeper) {
1020                 cout << "Error: Gatekeeper cannot be NULL" << endl;
1021                 return 1;
1022         }
1023
1024         if (strlen(secret)) {
1025                 endPoint->SetGatekeeperPassword(pass);
1026         }
1027
1028         if (gatekeeper_discover) {
1029                 /* discover the gk using multicast */
1030                 if (endPoint->DiscoverGatekeeper(new H323TransportUDP(*endPoint))) {
1031                         cout << "  == Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
1032                 } else {
1033                         cout << "  *** Could not find a gatekeeper." << endl;
1034                         return 1;
1035                 }       
1036         } else {
1037                 rasChannel = new H323TransportUDP(*endPoint);
1038
1039                 if (!rasChannel) {
1040                         cout << "  *** No RAS Channel, this is bad" << endl;
1041                         return 1;
1042                 }
1043                 if (endPoint->SetGatekeeper(gkName, rasChannel)) {
1044                         cout << "  == Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
1045                 } else {
1046                         cout << "  *** Error registering with gatekeeper \"" << gkName << "\". " << endl;
1047                         
1048                         /* XXX Maybe we should fire a new thread to attempt to re-register later and not kill asterisk here? */
1049                         return 1;
1050                 }
1051         }
1052         
1053         return 0;
1054 }
1055
1056 /** Send a DTMF tone over the H323Connection with the
1057   * specified token.
1058   */
1059 void h323_send_tone(const char *call_token, char tone)
1060 {
1061         if (!h323_end_point_exist()) {
1062                 cout << "ERROR: [h323_send_tone] No Endpoint, this is bad!" << endl;
1063                 return;
1064         }
1065
1066         PString token = PString(call_token);
1067         endPoint->SendUserTone(token, tone);
1068 }
1069
1070 /** Make a call to the remote endpoint.
1071   */
1072 int h323_make_call(char *host, call_details_t *cd, call_options_t call_options)
1073 {
1074         int res;
1075         PString token;
1076
1077         if (!h323_end_point_exist()) {
1078                 return 1;
1079         }
1080         
1081         PString dest(host);
1082
1083         res = endPoint->MakeCall(dest, token, &cd->call_reference, call_options.port, call_options.callerid);
1084         memcpy((char *)(cd->call_token), (const unsigned char *)token, token.GetLength());
1085         
1086         return res;
1087 };
1088
1089 int h323_clear_call(const char *call_token)
1090 {
1091         if (!h323_end_point_exist()) {
1092                 return 1;
1093         }
1094
1095         endPoint->ClearCall(PString(call_token));
1096         return 0;
1097 };
1098
1099 /** This function tells the h.323 stack to either 
1100     answer or deny an incoming call  */
1101 int h323_answering_call(const char *token, int busy) 
1102 {
1103         const PString currentToken(token);
1104         H323Connection * connection;
1105         
1106         connection = endPoint->FindConnectionWithLock(currentToken);
1107         
1108         if (connection == NULL) {
1109                 cout << "No connection found for " << token << endl;
1110                 return -1;
1111         }
1112
1113         if (!busy){
1114                 connection->AnsweringCall(H323Connection::AnswerCallNow);
1115                 connection->Unlock();
1116
1117         } else {
1118                 connection->AnsweringCall(H323Connection::AnswerCallDenied);
1119                 connection->Unlock();
1120         };
1121
1122         return 0;
1123 }
1124
1125
1126 int h323_show_codec(int fd, int argc, char *argv[])
1127 {
1128         cout <<  "Allowed Codecs:\n\t" << setprecision(2) << endPoint->GetCapabilities() << endl;
1129         return 0;
1130 }
1131
1132 int h323_soft_hangup(const char *data)
1133 {
1134         PString token(data);
1135         BOOL result;
1136         
1137         result = endPoint->ClearCall(token);    
1138         return result;
1139 }
1140
1141 /* alas, this doesn't work :(   */
1142 void h323_native_bridge(const char *token, char *them, char *capability)
1143 {
1144         H323Channel *channel;
1145         MyH323Connection *connection = (MyH323Connection *)endPoint->FindConnectionWithLock(token);
1146         
1147         if (!connection){
1148                 cout << "ERROR: No connection found, this is bad\n";
1149                 return;
1150         }
1151
1152         cout << "Native Bridge:  them [" << them << "]" << endl; 
1153
1154         channel = connection->FindChannel(connection->sessionId, TRUE);
1155         connection->bridging = TRUE;
1156         connection->CloseLogicalChannelNumber(channel->GetNumber());
1157         
1158         connection->Unlock();
1159         return;
1160
1161 }
1162
1163 } /* extern "C" */
1164