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