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