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