Answer if it needs it...
[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         int g711Frames = 30;
854         int gsmFrames  = 4;
855
856         if (!h323_end_point_exist()) {
857                 cout << " ERROR: [h323_set_capablity] No Endpoint, this is bad" << endl;
858                 return 1;
859         }
860
861         /* clean up old capabilities list before changing */
862         endPoint->RemoveCapabilities(PStringArray("All"));
863
864         mode = dtmfMode;
865         if (dtmfMode == H323_DTMF_INBAND) {
866             endPoint->SetSendUserInputMode(H323Connection::SendUserInputAsTone);
867         } else {
868                 endPoint->SetSendUserInputMode(H323Connection::SendUserInputAsInlineRFC2833);
869         }
870         if (cap & AST_FORMAT_SPEEX) {
871                 /* Not real sure if Asterisk acutally supports all
872                    of the various different bit rates so add them 
873                    all and figure it out later*/
874
875                 endPoint->SetCapability(0, 0, new SpeexNarrow2AudioCapability());
876                 endPoint->SetCapability(0, 0, new SpeexNarrow3AudioCapability());
877                 endPoint->SetCapability(0, 0, new SpeexNarrow4AudioCapability());
878                 endPoint->SetCapability(0, 0, new SpeexNarrow5AudioCapability());
879                 endPoint->SetCapability(0, 0, new SpeexNarrow6AudioCapability());
880         }
881
882         if (cap & AST_FORMAT_G729A) {
883                 AST_G729ACapability *g729aCap;
884                 AST_G729Capability *g729Cap;
885                 endPoint->SetCapability(0, 0, g729aCap = new AST_G729ACapability);
886                 endPoint->SetCapability(0, 0, g729Cap = new AST_G729Capability);
887         }
888         
889         if (cap & AST_FORMAT_G723_1) {
890                 H323_G7231Capability *g7231Cap;
891                 endPoint->SetCapability(0, 0, g7231Cap = new H323_G7231Capability);
892         } 
893
894         if (cap & AST_FORMAT_GSM) {
895                 H323_GSM0610Capability *gsmCap;
896                 endPoint->SetCapability(0, 0, gsmCap = new H323_GSM0610Capability);
897                 gsmCap->SetTxFramesInPacket(gsmFrames);
898         } 
899
900         if (cap & AST_FORMAT_ULAW) {
901                 H323_G711Capability *g711uCap;
902                 endPoint->SetCapability(0, 0, g711uCap = new H323_G711Capability(H323_G711Capability::muLaw));
903                 g711uCap->SetTxFramesInPacket(g711Frames);
904         } 
905
906         if (cap & AST_FORMAT_ALAW) {
907                 H323_G711Capability *g711aCap;
908                 endPoint->SetCapability(0, 0, g711aCap = new H323_G711Capability(H323_G711Capability::ALaw));
909                 g711aCap->SetTxFramesInPacket(g711Frames);
910         } 
911
912         if (h323debug) {
913                 cout <<  "Allowed Codecs:\n\t" << setprecision(2) << endPoint->GetCapabilities() << endl;
914         }
915         return 0;
916 }
917
918 /** Start the H.323 listener */
919 int h323_start_listener(int listenPort, struct sockaddr_in bindaddr)
920 {
921         
922         if (!h323_end_point_exist()) {
923                 cout << "ERROR: [h323_start_listener] No Endpoint, this is bad!" << endl;
924                 return 1;
925         }
926         
927         PIPSocket::Address interfaceAddress(bindaddr.sin_addr);
928
929         if (!listenPort) {
930                 listenPort = 1720;
931         }
932
933         /** H.323 listener */  
934         H323ListenerTCP *tcpListener;
935
936         tcpListener = new H323ListenerTCP(*endPoint, interfaceAddress, (WORD)listenPort);
937
938         if (!endPoint->StartListener(tcpListener)) {
939                 cout << "ERROR: Could not open H.323 listener port on " << ((H323ListenerTCP *) tcpListener)->GetListenerPort() << endl;
940                 delete tcpListener;
941                 return 1;
942                 
943         }
944         cout << "  == H.323 listener started" << endl;
945
946         return 0;
947 };
948  
949    
950 int h323_set_alias(struct oh323_alias *alias)
951 {
952         char *p;
953         char *num;
954         PString h323id(alias->name);
955         PString e164(alias->e164);
956         
957         if (!h323_end_point_exist()) {
958                 cout << "ERROR: [h323_set_alias] No Endpoint, this is bad!" << endl;
959                 return 1;
960         }
961
962         cout << "  == Adding alias \"" << h323id << "\" to endpoint" << endl;
963         endPoint->AddAliasName(h323id); 
964         endPoint->RemoveAliasName(localProcess->GetUserName());
965
966         if (!e164.IsEmpty()) {
967                 cout << "  == Adding E.164 \"" << e164 << "\" to endpoint" << endl;
968                 endPoint->AddAliasName(e164);
969         }
970         if (strlen(alias->prefix)) {
971                 p = alias->prefix;
972                 num = strsep(&p, ",");
973                 while(num) {
974                 cout << "  == Adding Prefix \"" << num << "\" to endpoint" << endl;
975                         endPoint->SupportedPrefixes += PString(num);
976                         endPoint->SetGateway();
977                 num = strsep(&p, ",");          
978                 }
979         }
980
981         return 0;
982 }
983
984
985 void h323_set_id(char *id)
986 {
987         PString h323id(id);
988
989         if (h323debug) {
990                 cout << "  == Using '" << h323id << "' as our H.323ID for this call" << endl;
991         }
992
993         /* EVIL HACK */
994         endPoint->SetLocalUserName(h323id);
995 }
996
997 void h323_show_tokens(void)
998 {
999         cout << "Current call tokens: " << setprecision(2) << endPoint->GetAllConnections() << endl;
1000 }
1001
1002
1003 /** Establish Gatekeeper communiations, if so configured, 
1004   *     register aliases for the H.323 endpoint to respond to.
1005   */
1006 int h323_set_gk(int gatekeeper_discover, char *gatekeeper, char *secret)
1007 {
1008         PString gkName = PString(gatekeeper);
1009         PString pass   = PString(secret);
1010         H323TransportUDP *rasChannel;
1011
1012         if (!h323_end_point_exist()) {
1013                 cout << "ERROR: [h323_set_gk] No Endpoint, this is bad!" << endl;
1014                 return 1;
1015         }
1016
1017         if (!gatekeeper) {
1018                 cout << "Error: Gatekeeper cannot be NULL" << endl;
1019                 return 1;
1020         }
1021
1022         if (strlen(secret)) {
1023                 endPoint->SetGatekeeperPassword(pass);
1024         }
1025
1026         if (gatekeeper_discover) {
1027                 /* discover the gk using multicast */
1028                 if (endPoint->DiscoverGatekeeper(new H323TransportUDP(*endPoint))) {
1029                         cout << "  == Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
1030                 } else {
1031                         cout << "  *** Could not find a gatekeeper." << endl;
1032                         return 1;
1033                 }       
1034         } else {
1035                 rasChannel = new H323TransportUDP(*endPoint);
1036
1037                 if (!rasChannel) {
1038                         cout << "  *** No RAS Channel, this is bad" << endl;
1039                         return 1;
1040                 }
1041                 if (endPoint->SetGatekeeper(gkName, rasChannel)) {
1042                         cout << "  == Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
1043                 } else {
1044                         cout << "  *** Error registering with gatekeeper \"" << gkName << "\". " << endl;
1045                         
1046                         /* XXX Maybe we should fire a new thread to attempt to re-register later and not kill asterisk here? */
1047                         return 1;
1048                 }
1049         }
1050         
1051         return 0;
1052 }
1053
1054 /** Send a DTMF tone over the H323Connection with the
1055   * specified token.
1056   */
1057 void h323_send_tone(const char *call_token, char tone)
1058 {
1059         if (!h323_end_point_exist()) {
1060                 cout << "ERROR: [h323_send_tone] No Endpoint, this is bad!" << endl;
1061                 return;
1062         }
1063
1064         PString token = PString(call_token);
1065         endPoint->SendUserTone(token, tone);
1066 }
1067
1068 /** Make a call to the remote endpoint.
1069   */
1070 int h323_make_call(char *host, call_details_t *cd, call_options_t call_options)
1071 {
1072         int res;
1073         PString token;
1074
1075         if (!h323_end_point_exist()) {
1076                 return 1;
1077         }
1078         
1079         PString dest(host);
1080
1081         res = endPoint->MakeCall(dest, token, &cd->call_reference, call_options.port, call_options.callerid);
1082         memcpy((char *)(cd->call_token), (const unsigned char *)token, token.GetLength());
1083         
1084         return res;
1085 };
1086
1087 int h323_clear_call(const char *call_token)
1088 {
1089         if (!h323_end_point_exist()) {
1090                 return 1;
1091         }
1092
1093         endPoint->ClearCall(PString(call_token));
1094         return 0;
1095 };
1096
1097 /** This function tells the h.323 stack to either 
1098     answer or deny an incoming call  */
1099 int h323_answering_call(const char *token, int busy) 
1100 {
1101         const PString currentToken(token);
1102         H323Connection * connection;
1103         
1104         connection = endPoint->FindConnectionWithLock(currentToken);
1105         
1106         if (connection == NULL) {
1107                 cout << "No connection found for " << token << endl;
1108                 return -1;
1109         }
1110
1111         if (!busy){
1112                 connection->AnsweringCall(H323Connection::AnswerCallNow);
1113                 connection->Unlock();
1114
1115         } else {
1116                 connection->AnsweringCall(H323Connection::AnswerCallDenied);
1117                 connection->Unlock();
1118         };
1119
1120         return 0;
1121 }
1122
1123
1124 int h323_show_codec(int fd, int argc, char *argv[])
1125 {
1126         cout <<  "Allowed Codecs:\n\t" << setprecision(2) << endPoint->GetCapabilities() << endl;
1127         return 0;
1128 }
1129
1130 int h323_soft_hangup(const char *data)
1131 {
1132         PString token(data);
1133         BOOL result;
1134         
1135         result = endPoint->ClearCall(token);    
1136         return result;
1137 }
1138
1139 /* alas, this doesn't work :(   */
1140 void h323_native_bridge(const char *token, char *them, char *capability)
1141 {
1142         H323Channel *channel;
1143         MyH323Connection *connection = (MyH323Connection *)endPoint->FindConnectionWithLock(token);
1144         
1145         if (!connection){
1146                 cout << "ERROR: No connection found, this is bad\n";
1147                 return;
1148         }
1149
1150         cout << "Native Bridge:  them [" << them << "]" << endl; 
1151
1152         channel = connection->FindChannel(connection->sessionId, TRUE);
1153         connection->bridging = TRUE;
1154         connection->CloseLogicalChannelNumber(channel->GetNumber());
1155         
1156         connection->Unlock();
1157         return;
1158
1159 }
1160
1161 } /* extern "C" */
1162