WTF
[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         GetControlChannel().GetLocalAddress().GetIpAndPort(externalIpAddress, port);
677         externalPort = info->port;
678         
679         if (h323debug) {
680                 cout << "       =*= In CreateRealTimeLogicalChannel for call " << GetCallReference() << endl;
681                 cout << "               -- externalIpAddress: " << externalIpAddress << endl;
682                 cout << "               -- externalPort: " << externalPort << endl;
683                 cout << "               -- SessionID: " << sessionID << endl;
684                 cout << "               -- Direction: " << dir << endl;
685         }
686         return new H323_ExternalRTPChannel(*this, capability, dir, sessionID, externalIpAddress, externalPort);
687 }
688
689 /** This callback function is invoked once upon creation of each
690   * channel for an H323 session 
691   */
692 BOOL MyH323Connection::OnStartLogicalChannel(H323Channel & channel)
693 {    
694         if (h323debug) {
695                 cout << "        -- Started logical channel: "; 
696                 cout << ((channel.GetDirection()==H323Channel::IsTransmitter)?"sending ":((channel.GetDirection()==H323Channel::IsReceiver)?"receiving ":" ")); 
697                 cout << (const char *)(channel.GetCapability()).GetFormatName() << endl;
698         }
699         // adjust the count of channels we have open
700         channelsOpen++;
701         if (h323debug) {
702                 cout <<  "              -- channelsOpen = " << channelsOpen << endl;
703         }
704         H323_ExternalRTPChannel & external = (H323_ExternalRTPChannel &)channel;
705         external.GetRemoteAddress(remoteIpAddress, remotePort); 
706
707         if (h323debug) {
708                 cout << "               -- remoteIpAddress: " << remoteIpAddress << endl;
709                 cout << "               -- remotePort: " << remotePort << endl;
710                 cout << "               -- ExternalIpAddress: " << externalIpAddress << endl;
711                 cout << "               -- ExternalPort: " << externalPort << endl;
712         }
713         /* Notify Asterisk of remote RTP information */
714         on_start_logical_channel(GetCallReference(), (const char *)remoteIpAddress.AsString(), remotePort);
715
716         return TRUE;    
717 }
718
719
720 /** IMPLEMENTATION OF C FUNCTIONS */
721
722 /**
723  * The extern "C" directive takes care for 
724  * the ANSI-C representation of linkable symbols 
725  */
726 extern "C" {
727
728 int h323_end_point_exist(void)
729 {
730         if (!endPoint) {
731                 return 0;
732         }
733         return 1;
734 }
735     
736 void h323_end_point_create(void)
737 {
738         channelsOpen = 0;
739         localProcess = new MyProcess(); 
740         localProcess->Main();
741 }
742
743 void h323_gk_urq(void)
744 {
745         if (!h323_end_point_exist()) {
746                 cout << " ERROR: [h323_gk_urq] No Endpoint, this is bad" << endl;
747                 return;
748         }       
749         endPoint->RemoveGatekeeper();
750 }
751
752 void h323_end_process(void)
753 {
754         endPoint->ClearAllCalls();
755         endPoint->RemoveListener(NULL);
756         delete endPoint;
757         delete localProcess;
758 }
759
760 void h323_debug(int flag, unsigned level)
761 {
762         if (flag) {
763                 PTrace:: SetLevel(level); 
764         } else { 
765                 PTrace:: SetLevel(0); 
766         }
767 }
768         
769 /** Installs the callback functions on behalf of the PBX application  */
770 void h323_callback_register(setup_incoming_cb   ifunc,
771                             setup_outbound_cb   sfunc,
772                             on_connection_cb    confunc,
773                             start_logchan_cb    lfunc,
774                             clear_con_cb        clfunc,
775                             con_established_cb  efunc,
776                             send_digit_cb       dfunc)
777 {
778         on_incoming_call = ifunc;
779         on_outgoing_call = sfunc;
780         on_create_connection = confunc;
781         on_start_logical_channel = lfunc;
782         on_connection_cleared = clfunc;
783         on_connection_established = efunc;
784         on_send_digit = dfunc;
785 }
786
787 /**
788  * Add capability to the capability table of the end point. 
789  */
790 int h323_set_capability(int cap, int dtmfMode)
791 {
792         int g711Frames = 30;
793         int gsmFrames  = 4;
794
795         if (!h323_end_point_exist()) {
796                 cout << " ERROR: [h323_set_capablity] No Endpoint, this is bad" << endl;
797                 return 1;
798         }
799
800         mode = dtmfMode;
801         if (dtmfMode == H323_DTMF_INBAND) {
802             endPoint->SetSendUserInputMode(H323Connection::SendUserInputAsTone);
803         } else {
804                 endPoint->SetSendUserInputMode(H323Connection::SendUserInputAsInlineRFC2833);
805         }
806         if (cap & AST_FORMAT_SPEEX) {
807                 /* Not real sure if Asterisk acutally supports all
808                    of the various different bit rates so add them 
809                    all and figure it out later*/
810
811                 endPoint->SetCapability(0, 0, new SpeexNarrow2AudioCapability());
812                 endPoint->SetCapability(0, 0, new SpeexNarrow3AudioCapability());
813                 endPoint->SetCapability(0, 0, new SpeexNarrow4AudioCapability());
814                 endPoint->SetCapability(0, 0, new SpeexNarrow5AudioCapability());
815                 endPoint->SetCapability(0, 0, new SpeexNarrow6AudioCapability());
816         }
817
818         if (cap & AST_FORMAT_G729A) {
819                 AST_G729ACapability *g729aCap;
820                 AST_G729Capability *g729Cap;
821                 endPoint->SetCapability(0, 0, g729aCap = new AST_G729ACapability);
822                 endPoint->SetCapability(0, 0, g729Cap = new AST_G729Capability);
823         }
824         
825         if (cap & AST_FORMAT_G723_1) {
826                 H323_G7231Capability *g7231Cap;
827                 endPoint->SetCapability(0, 0, g7231Cap = new H323_G7231Capability);
828         } 
829
830         if (cap & AST_FORMAT_GSM) {
831                 H323_GSM0610Capability *gsmCap;
832                 endPoint->SetCapability(0, 0, gsmCap = new H323_GSM0610Capability);
833                 gsmCap->SetTxFramesInPacket(gsmFrames);
834         } 
835
836         if (cap & AST_FORMAT_ULAW) {
837                 H323_G711Capability *g711uCap;
838                 endPoint->SetCapability(0, 0, g711uCap = new H323_G711Capability(H323_G711Capability::muLaw));
839                 g711uCap->SetTxFramesInPacket(g711Frames);
840         } 
841
842         if (cap & AST_FORMAT_ALAW) {
843                 H323_G711Capability *g711aCap;
844                 endPoint->SetCapability(0, 0, g711aCap = new H323_G711Capability(H323_G711Capability::ALaw));
845                 g711aCap->SetTxFramesInPacket(g711Frames);
846         } 
847
848         return 0;
849 }
850
851 /** Start the H.323 listener */
852 int h323_start_listener(int listenPort, struct sockaddr_in bindaddr)
853 {
854         
855         if (!h323_end_point_exist()) {
856                 cout << "ERROR: [h323_start_listener] No Endpoint, this is bad!" << endl;
857                 return 1;
858         }
859         
860         PIPSocket::Address interfaceAddress(bindaddr.sin_addr);
861
862         if (!listenPort) {
863                 listenPort = 1720;
864         }
865
866         /** H.323 listener */  
867         H323ListenerTCP *tcpListener;
868
869         tcpListener = new H323ListenerTCP(*endPoint, interfaceAddress, (WORD)listenPort);
870
871         if (!endPoint->StartListener(tcpListener)) {
872                 cout << "ERROR: Could not open H.323 listener port on " << ((H323ListenerTCP *) tcpListener)->GetListenerPort() << endl;
873                 delete tcpListener;
874                 return 1;
875                 
876         }
877         cout << "  == H.323 listener started" << endl;
878
879         return 0;
880 };
881  
882    
883 int h323_set_alias(struct oh323_alias *alias)
884 {
885         char *p;
886         char *num;
887         PString h323id(alias->name);
888         PString e164(alias->e164);
889         
890         if (!h323_end_point_exist()) {
891                 cout << "ERROR: [h323_set_alias] No Endpoint, this is bad!" << endl;
892                 return 1;
893         }
894
895         cout << "  == Adding alias \"" << h323id << "\" to endpoint" << endl;
896         endPoint->AddAliasName(h323id); 
897         endPoint->RemoveAliasName(localProcess->GetUserName());
898
899         if (!e164.IsEmpty()) {
900                 cout << "  == Adding E.164 \"" << e164 << "\" to endpoint" << endl;
901                 endPoint->AddAliasName(e164);
902         }
903         if (strlen(alias->prefix)) {
904                 p = alias->prefix;
905                 num = strsep(&p, ",");
906                 while(num) {
907                 cout << "  == Adding Prefix \"" << num << "\" to endpoint" << endl;
908                         endPoint->SupportedPrefixes += PString(num);
909                         endPoint->SetGateway();
910                 num = strsep(&p, ",");          
911                 }
912         }
913
914         return 0;
915 }
916
917
918 void h323_set_id(char *id)
919 {
920         PString h323id(id);
921
922         if (h323debug) {
923                 cout << "  == Using '" << h323id << "' as our H.323ID for this call" << endl;
924         }
925
926         /* EVIL HACK */
927         endPoint->SetLocalUserName(h323id);
928 }
929
930 void h323_show_tokens(void)
931 {
932         cout << "Current call tokens: " << setprecision(2) << endPoint->GetAllConnections() << endl;
933 }
934
935
936 /** Establish Gatekeeper communiations, if so configured, 
937   *     register aliases for the H.323 endpoint to respond to.
938   */
939 int h323_set_gk(int gatekeeper_discover, char *gatekeeper, char *secret)
940 {
941         PString gkName = PString(gatekeeper);
942         PString pass   = PString(secret);
943         H323TransportUDP *rasChannel;
944
945         if (!h323_end_point_exist()) {
946                 cout << "ERROR: [h323_set_gk] No Endpoint, this is bad!" << endl;
947                 return 1;
948         }
949
950         if (!gatekeeper) {
951                 cout << "Error: Gatekeeper cannot be NULL" << endl;
952                 return 1;
953         }
954
955         if (strlen(secret)) {
956                 endPoint->SetGatekeeperPassword(pass);
957         }
958
959         if (gatekeeper_discover) {
960                 /* discover the gk using multicast */
961                 if (endPoint->DiscoverGatekeeper(new H323TransportUDP(*endPoint))) {
962                         cout << "  == Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
963                 } else {
964                         cout << "  *** Could not find a gatekeeper." << endl;
965                         return 1;
966                 }       
967         } else {
968                 rasChannel = new H323TransportUDP(*endPoint);
969
970                 if (!rasChannel) {
971                         cout << "  *** No RAS Channel, this is bad" << endl;
972                         return 1;
973                 }
974                 if (endPoint->SetGatekeeper(gkName, rasChannel)) {
975                         cout << "  == Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
976                 } else {
977                         cout << "  *** Error registering with gatekeeper \"" << gkName << "\". " << endl;
978                         
979                         /* XXX Maybe we should fire a new thread to attempt to re-register later and not kill asterisk here? */
980                         return 1;
981                 }
982         }
983         
984         return 0;
985 }
986
987 /** Send a DTMF tone over the H323Connection with the
988   * specified token.
989   */
990 void h323_send_tone(const char *call_token, char tone)
991 {
992         if (!h323_end_point_exist()) {
993                 cout << "ERROR: [h323_send_tone] No Endpoint, this is bad!" << endl;
994                 return;
995         }
996
997         PString token = PString(call_token);
998         endPoint->SendUserTone(token, tone);
999 }
1000
1001 /** Make a call to the remote endpoint.
1002   */
1003 int h323_make_call(char *host, call_details_t *cd, call_options_t call_options)
1004 {
1005         int res;
1006         PString token;
1007
1008         if (!h323_end_point_exist()) {
1009                 return 1;
1010         }
1011         
1012         PString dest(host);
1013
1014         res = endPoint->MakeCall(dest, token, &cd->call_reference, call_options.port, call_options.callerid);
1015         memcpy((char *)(cd->call_token), (const unsigned char *)token, token.GetLength());
1016         
1017         return res;
1018 };
1019
1020 int h323_clear_call(const char *call_token)
1021 {
1022         if (!h323_end_point_exist()) {
1023                 return 1;
1024         }
1025
1026         endPoint->ClearCall(PString(call_token));
1027         return 0;
1028 };
1029
1030 /** This function tells the h.323 stack to either 
1031     answer or deny an incoming call  */
1032 int h323_answering_call(const char *token, int busy) 
1033 {
1034         const PString currentToken(token);
1035         H323Connection * connection;
1036         
1037         connection = endPoint->FindConnectionWithLock(currentToken);
1038         
1039         if (connection == NULL) {
1040                 cout << "No connection found for " << token << endl;
1041                 return -1;
1042         }
1043
1044         if (!busy){
1045                 connection->AnsweringCall(H323Connection::AnswerCallNow);
1046                 connection->Unlock();
1047
1048         } else {
1049                 connection->AnsweringCall(H323Connection::AnswerCallDenied);
1050                 connection->Unlock();
1051         };
1052
1053         return 0;
1054 }
1055
1056
1057 int h323_show_codec(int fd, int argc, char *argv[])
1058 {
1059         cout <<  "Allowed Codecs:\n\t" << setprecision(2) << endPoint->GetCapabilities() << endl;
1060         return 0;
1061 }
1062
1063 int h323_soft_hangup(const char *data)
1064 {
1065         PString token(data);
1066         BOOL result;
1067         
1068         result = endPoint->ClearCall(token);    
1069         return result;
1070 }
1071
1072 /* alas, this doesn't work :(   */
1073 void h323_native_bridge(const char *token, char *them, char *capability)
1074 {
1075         H323Channel *channel;
1076         MyH323Connection *connection = (MyH323Connection *)endPoint->FindConnectionWithLock(token);
1077         
1078         if (!connection){
1079                 cout << "ERROR: No connection found, this is bad\n";
1080                 return;
1081         }
1082
1083         cout << "Native Bridge:  them [" << them << "]" << endl; 
1084
1085         channel = connection->FindChannel(connection->sessionId, TRUE);
1086         connection->bridging = TRUE;
1087         connection->CloseLogicalChannelNumber(channel->GetNumber());
1088         
1089         connection->Unlock();
1090         return;
1091
1092 }
1093
1094 } /* extern "C" */
1095
1096
1097