Introduce Cisco G.726-32 capability (g726aal2 form)
[asterisk/asterisk.git] / channels / h323 / ast_h323.cxx
1 #ifndef _GNU_SOURCE
2 #define _GNU_SOURCE
3 #endif
4 /*
5  * ast_h323.cpp
6  *
7  * OpenH323 Channel Driver for ASTERISK PBX.
8  *                      By  Jeremy McNamara
9  *                      For The NuFone Network
10  *
11  * chan_h323 has been derived from code created by
12  *               Michael Manousos and Mark Spencer
13  *
14  * This file is part of the chan_h323 driver for Asterisk
15  *
16  * chan_h323 is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation; either version 2 of the License, or
19  * (at your option) any later version.
20  *
21  * chan_h323 is distributed WITHOUT ANY WARRANTY; without even
22  * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
23  * PURPOSE. See the GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program; if not, write to the Free Software
27  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28  *
29  * Version Info: $Id$
30  */
31 #include <arpa/inet.h>
32
33 #include <list>
34 #include <string>
35 #include <algorithm>
36
37 #include <ptlib.h>
38 #include <h323.h>
39 #include <h323pdu.h>
40 #include <mediafmt.h>
41 #include <lid.h>
42
43 #ifdef __cplusplus
44 extern "C" {
45 #endif
46 #include "asterisk/logger.h"
47 #include "asterisk/channel.h"
48 #include "asterisk/astobj.h"
49 #ifdef __cplusplus
50 }
51 #endif
52
53 #include "chan_h323.h"
54 #include "ast_h323.h"
55 #include "cisco-h225.h"
56 #include "caps_h323.h"
57
58 /* PWlib Required Components  */
59 #define MAJOR_VERSION 1
60 #define MINOR_VERSION 0
61 #define BUILD_TYPE    ReleaseCode
62 #define BUILD_NUMBER  0
63
64 /** Counter for the number of connections */
65 static int channelsOpen;
66
67 /**
68  * We assume that only one endPoint should exist.
69  * The application cannot run the h323_end_point_create() more than once
70  * FIXME: Singleton this, for safety
71  */
72 static MyH323EndPoint *endPoint = NULL;
73
74 /** PWLib entry point */
75 static MyProcess *localProcess = NULL;
76
77 static int _timerChangePipe[2];
78
79 static unsigned traceOptions = PTrace::Timestamp | PTrace::Thread | PTrace::FileAndLine;
80
81 class PAsteriskLog : public PObject, public iostream {
82         PCLASSINFO(PAsteriskLog, PObject);
83
84         public:
85         PAsteriskLog() : iostream(cout.rdbuf()) { init(&buffer); }
86         ~PAsteriskLog() { flush(); }
87
88         private:
89         PAsteriskLog(const PAsteriskLog &) : iostream(cout.rdbuf()) { }
90         PAsteriskLog & operator=(const PAsteriskLog &) { return *this; }
91
92         class Buffer : public streambuf {
93                 public:
94                 virtual int overflow(int=EOF);
95                 virtual int underflow();
96                 virtual int sync();
97                 PString string;
98         } buffer;
99         friend class Buffer;
100 };
101
102 static PAsteriskLog *logstream = NULL;
103
104 int PAsteriskLog::Buffer::overflow(int c)
105 {
106         if (pptr() >= epptr()) {
107                 int ppos = pptr() - pbase();
108                 char *newptr = string.GetPointer(string.GetSize() + 2000);
109                 setp(newptr, newptr + string.GetSize() - 1);
110                 pbump(ppos);
111         }
112         if (c != EOF) {
113                 *pptr() = (char)c;
114                 pbump(1);
115         }
116         return 0;
117 }
118
119 int PAsteriskLog::Buffer::underflow()
120 {
121         return EOF;
122 }
123
124 int PAsteriskLog::Buffer::sync()
125 {
126         char *str = strdup(string);
127         char *s, *s1;
128         char c;
129
130         /* Pass each line with different ast_verbose() call */
131         for (s = str; s && *s; s = s1) {
132                 s1 = strchr(s, '\n');
133                 if (!s1)
134                         s1 = s + strlen(s);
135                 else
136                         s1++;
137                 c = *s1;
138                 *s1 = '\0';
139                 ast_verbose("%s", s);
140                 *s1 = c;
141         }
142         free(str);
143
144         string = PString();
145         char *base = string.GetPointer(2000);
146         setp(base, base + string.GetSize() - 1);
147         return 0;
148 }
149
150 static ostream &my_endl(ostream &os)
151 {
152         if (logstream) {
153                 PTrace::SetOptions(traceOptions);
154                 return PTrace::End(os);
155         }
156         return endl(os);
157 }
158
159 #define cout \
160         (logstream ? (PTrace::ClearOptions((unsigned)-1), PTrace::Begin(0, __FILE__, __LINE__)) : std::cout)
161 #define endl my_endl
162
163 /* Special class designed to call cleanup code on module destruction */
164 class MyH323_Shutdown {
165         public:
166         MyH323_Shutdown() { };
167         ~MyH323_Shutdown()
168         {
169                 h323_end_process();
170         };
171 };
172
173 MyProcess::MyProcess(): PProcess("The NuFone Network's",
174                         "H.323 Channel Driver for Asterisk",
175                         MAJOR_VERSION, MINOR_VERSION, BUILD_TYPE, BUILD_NUMBER)
176 {
177         /* Call shutdown when module being unload or asterisk has been stopped */
178         static MyH323_Shutdown x;
179
180         /* Fix missed one in PWLib */
181         PX_firstTimeStart = FALSE;
182         Resume();
183 }
184
185 MyProcess::~MyProcess()
186 {
187         _timerChangePipe[0] = timerChangePipe[0];
188         _timerChangePipe[1] = timerChangePipe[1];
189 }
190
191 void MyProcess::Main()
192 {
193         PTrace::Initialise(PTrace::GetLevel(), NULL, traceOptions);
194         PTrace::SetStream(logstream);
195
196         cout << "  == Creating H.323 Endpoint" << endl;
197         if (endPoint) {
198                 cout << "  == ENDPOINT ALREADY CREATED" << endl;
199                 return;
200         }
201         endPoint = new MyH323EndPoint();
202         /* Due to a bug in the H.323 recomendation/stack we should request a sane
203            amount of bandwidth from the GK - this function is ignored if not using a GK
204            We are requesting 128 (64k in each direction), which is the worst case codec. */
205         endPoint->SetInitialBandwidth(1280);
206 }
207
208 void PAssertFunc(const char *msg)
209 {
210         ast_log(LOG_ERROR, "%s\n", msg);
211         /* XXX: Probably we need to crash here */
212 }
213
214
215 /** MyH323EndPoint
216   */
217 MyH323EndPoint::MyH323EndPoint()
218                 : H323EndPoint()
219 {
220         // Capabilities will be negotiated on per-connection basis
221         capabilities.RemoveAll();
222 }
223
224 /** The fullAddress parameter is used directly in the MakeCall method so
225   * the General form for the fullAddress argument is :
226   * [alias@][transport$]host[:port]
227   * default values:     alias = the same value as host.
228   *                                     transport = ip.
229   *                                     port = 1720.
230   */
231 int MyH323EndPoint::MyMakeCall(const PString & dest, PString & token, void *_callReference, void *_opts)
232 {
233         PString fullAddress;
234         MyH323Connection * connection;
235         H323Transport *transport = NULL;
236         unsigned int *callReference = (unsigned int *)_callReference;
237         call_options_t *opts = (call_options_t *)_opts;
238
239         /* Determine whether we are using a gatekeeper or not. */
240         if (GetGatekeeper()) {
241                 fullAddress = dest;
242                 if (h323debug) {
243                         cout << " -- Making call to " << fullAddress << " using gatekeeper." << endl;
244                 }
245         } else {
246                 fullAddress = dest;
247                 if (h323debug) {
248                         cout << " -- Making call to " << fullAddress << " without gatekeeper." << endl;
249                 }
250                 /* Use bindaddr for outgoing calls too if we don't use gatekeeper */
251                 if (listeners.GetSize() > 0) {
252                         H323TransportAddress taddr = listeners[0].GetTransportAddress();
253                         PIPSocket::Address addr;
254                         WORD port;
255                         if (taddr.GetIpAndPort(addr, port)) {
256                                 /* Create own transport for specific addresses only */
257                                 if (addr) {
258                                         if (h323debug)
259                                                 cout << "Using " << addr << " for outbound call" << endl;
260                                         transport = new MyH323TransportTCP(*this, addr);
261                                         if (!transport)
262                                                 cout << "Unable to create transport for outgoing call" << endl;
263                                 }
264                         } else
265                                 cout << "Unable to get address and port" << endl;
266                 }
267         }
268         if (!(connection = (MyH323Connection *)H323EndPoint::MakeCallLocked(fullAddress, token, opts, transport))) {
269                 if (h323debug) {
270                         cout << "Error making call to \"" << fullAddress << '"' << endl;
271                 }
272                 return 1;
273         }
274         *callReference = connection->GetCallReference();
275
276         if (h323debug) {
277                 cout << "\t-- " << GetLocalUserName() << " is calling host " << fullAddress << endl;
278                 cout << "\t-- Call token is " << (const char *)token << endl;
279                 cout << "\t-- Call reference is " << *callReference << endl;
280                 cout << "\t-- DTMF Payload is " << connection->dtmfCodec << endl;
281         }
282         connection->Unlock();
283         return 0;
284 }
285
286 void MyH323EndPoint::SetEndpointTypeInfo( H225_EndpointType & info ) const
287 {
288         H323EndPoint::SetEndpointTypeInfo(info);
289
290         if (terminalType == e_GatewayOnly){
291                 info.RemoveOptionalField(H225_EndpointType::e_terminal);
292                 info.IncludeOptionalField(H225_EndpointType::e_gateway);
293         }
294
295         info.m_gateway.IncludeOptionalField(H225_GatewayInfo::e_protocol);
296         info.m_gateway.m_protocol.SetSize(1);
297         H225_SupportedProtocols &protocol=info.m_gateway.m_protocol[0];
298         protocol.SetTag(H225_SupportedProtocols::e_voice);
299         PINDEX as=SupportedPrefixes.GetSize();
300         ((H225_VoiceCaps &)protocol).m_supportedPrefixes.SetSize(as);
301         for (PINDEX p=0; p<as; p++) {
302                 H323SetAliasAddress(SupportedPrefixes[p], ((H225_VoiceCaps &)protocol).m_supportedPrefixes[p].m_prefix, H225_AliasAddress::e_dialedDigits);
303         }
304 }
305
306 void MyH323EndPoint::SetGateway(void)
307 {
308         terminalType = e_GatewayOnly;
309 }
310
311 BOOL MyH323EndPoint::ClearCall(const PString & token, H323Connection::CallEndReason reason)
312 {
313         if (h323debug) {
314 #ifdef PTRACING
315                 cout << "\t-- ClearCall: Request to clear call with token " << token << ", cause " << reason << endl;
316 #else
317                 cout << "\t-- ClearCall: Request to clear call with token " << token << ", cause [" << (int)reason << "]" << endl;
318 #endif
319         }
320         return H323EndPoint::ClearCall(token, reason);
321 }
322
323 BOOL MyH323EndPoint::ClearCall(const PString & token)
324 {
325         if (h323debug) {
326                 cout << "\t-- ClearCall: Request to clear call with token " << token << endl;
327         }
328         return H323EndPoint::ClearCall(token, H323Connection::EndedByLocalUser);
329 }
330
331 void MyH323EndPoint::SendUserTone(const PString &token, char tone)
332 {
333         H323Connection *connection = NULL;
334
335         connection = FindConnectionWithLock(token);
336         if (connection != NULL) {
337                 connection->SendUserInputTone(tone, 500);
338                 connection->Unlock();
339         }
340 }
341
342 void MyH323EndPoint::OnClosedLogicalChannel(H323Connection & connection, const H323Channel & channel)
343 {
344         channelsOpen--;
345         if (h323debug) {
346                 cout << "\t\tchannelsOpen = " << channelsOpen << endl;
347         }
348         H323EndPoint::OnClosedLogicalChannel(connection, channel);
349 }
350
351 BOOL MyH323EndPoint::OnConnectionForwarded(H323Connection & connection,
352                 const PString & forwardParty,
353                 const H323SignalPDU & pdu)
354 {
355         if (h323debug) {
356                 cout << "\t-- Call Forwarded to " << forwardParty << endl;
357         }
358         return FALSE;
359 }
360
361 BOOL MyH323EndPoint::ForwardConnection(H323Connection & connection,
362                 const PString & forwardParty,
363                 const H323SignalPDU & pdu)
364 {
365         if (h323debug) {
366                 cout << "\t-- Forwarding call to " << forwardParty << endl;
367         }
368         return H323EndPoint::ForwardConnection(connection, forwardParty, pdu);
369 }
370
371 void MyH323EndPoint::OnConnectionEstablished(H323Connection & connection, const PString & estCallToken)
372 {
373         if (h323debug) {
374                 cout << "\t=-= In OnConnectionEstablished for call " << connection.GetCallReference() << endl;
375                 cout << "\t\t-- Connection Established with \"" << connection.GetRemotePartyName() << "\"" << endl;
376         }
377         on_connection_established(connection.GetCallReference(), (const char *)connection.GetCallToken());
378 }
379
380 /** OnConnectionCleared callback function is called upon the dropping of an established
381   * H323 connection.
382   */
383 void MyH323EndPoint::OnConnectionCleared(H323Connection & connection, const PString & clearedCallToken)
384 {
385         PString remoteName = connection.GetRemotePartyName();
386
387         switch (connection.GetCallEndReason()) {
388                 case H323Connection::EndedByCallForwarded:
389                         if (h323debug) {
390                                 cout << "-- " << remoteName << " has forwarded the call" << endl;
391                         }
392                         break;
393                 case H323Connection::EndedByRemoteUser:
394                         if (h323debug) {
395                                 cout << "-- " << remoteName << " has cleared the call" << endl;
396                         }
397                         break;
398                 case H323Connection::EndedByCallerAbort:
399                         if (h323debug) {
400                                 cout << "-- " << remoteName << " has stopped calling" << endl;
401                         }
402                         break;
403                 case H323Connection::EndedByRefusal:
404                         if (h323debug) {
405                                 cout << "-- " << remoteName << " did not accept your call" << endl;
406                         }
407                         break;
408                 case H323Connection::EndedByRemoteBusy:
409                         if (h323debug) {
410                                 cout << "-- " << remoteName << " was busy" << endl;
411                         }
412                         break;
413                 case H323Connection::EndedByRemoteCongestion:
414                         if (h323debug) {
415                                 cout << "-- Congested link to " << remoteName << endl;
416                         }
417                         break;
418                 case H323Connection::EndedByNoAnswer:
419                         if (h323debug) {
420                                 cout << "-- " << remoteName << " did not answer your call" << endl;
421                         }
422                         break;
423                 case H323Connection::EndedByTransportFail:
424                         if (h323debug) {
425                                 cout << "-- Call with " << remoteName << " ended abnormally" << endl;
426                         }
427                         break;
428                 case H323Connection::EndedByCapabilityExchange:
429                         if (h323debug) {
430                                 cout << "-- Could not find common codec with " << remoteName << endl;
431                         }
432                         break;
433                 case H323Connection::EndedByNoAccept:
434                         if (h323debug) {
435                                 cout << "-- Did not accept incoming call from " << remoteName << endl;
436                         }
437                         break;
438                 case H323Connection::EndedByAnswerDenied:
439                         if (h323debug) {
440                                 cout << "-- Refused incoming call from " << remoteName << endl;
441                         }
442                         break;
443                 case H323Connection::EndedByNoUser:
444                         if (h323debug) {
445                                 cout << "-- Remote endpoint could not find user: " << remoteName << endl;
446                         }
447                         break;
448                 case H323Connection::EndedByNoBandwidth:
449                         if (h323debug) {
450                                 cout << "-- Call to " << remoteName << " aborted, insufficient bandwidth." << endl;
451                         }
452                         break;
453                 case H323Connection::EndedByUnreachable:
454                         if (h323debug) {
455                                 cout << "-- " << remoteName << " could not be reached." << endl;
456                         }
457                         break;
458                 case H323Connection::EndedByHostOffline:
459                         if (h323debug) {
460                                 cout << "-- " << remoteName << " is not online." << endl;
461                         }
462                         break;
463                 case H323Connection::EndedByNoEndPoint:
464                         if (h323debug) {
465                                 cout << "-- No phone running for " << remoteName << endl;
466                         }
467                         break;
468                 case H323Connection::EndedByConnectFail:
469                         if (h323debug) {
470                                 cout << "-- Transport error calling " << remoteName << endl;
471                         }
472                         break;
473                 default:
474                         if (h323debug) {
475 #ifdef PTRACING
476                                 cout << " -- Call with " << remoteName << " completed (" << connection.GetCallEndReason() << ")" << endl;
477 #else
478                                 cout << " -- Call with " << remoteName << " completed ([" << (int)connection.GetCallEndReason() << "])" << endl;
479 #endif
480                         }
481         }
482
483         if (connection.IsEstablished()) {
484                 if (h323debug) {
485                         cout << "\t-- Call duration " << setprecision(0) << setw(5) << (PTime() - connection.GetConnectionStartTime()) << endl;
486                 }
487         }
488         /* Invoke the PBX application registered callback */
489         on_connection_cleared(connection.GetCallReference(), clearedCallToken);
490         return;
491 }
492
493 H323Connection * MyH323EndPoint::CreateConnection(unsigned callReference, void *userData, H323Transport *transport, H323SignalPDU *setupPDU)
494 {
495         unsigned options = 0;
496         call_options_t *opts = (call_options_t *)userData;
497         MyH323Connection *conn;
498
499         if (opts && opts->fastStart) {
500                 options |= H323Connection::FastStartOptionEnable;
501         } else {
502                 options |= H323Connection::FastStartOptionDisable;
503         }
504         if (opts && opts->h245Tunneling) {
505                 options |= H323Connection::H245TunnelingOptionEnable;
506         } else {
507                 options |= H323Connection::H245TunnelingOptionDisable;
508         }
509 /* Disable until I can figure out the proper way to deal with this */
510 #if 0
511         if (opts->silenceSuppression) {
512                 options |= H323Connection::SilenceSuppresionOptionEnable;
513         } else {
514                 options |= H323Connection::SilenceSUppressionOptionDisable;
515         }
516 #endif
517         conn = new MyH323Connection(*this, callReference, options);
518         if (conn) {
519                 if (opts)
520                         conn->SetCallOptions(opts, (setupPDU ? TRUE : FALSE));
521         }
522         return conn;
523 }
524
525 /* MyH323Connection Implementation */
526 MyH323Connection::MyH323Connection(MyH323EndPoint & ep, unsigned callReference,
527                                                         unsigned options)
528         : H323Connection(ep, callReference, options)
529 {
530         cause = -1;
531         sessionId = 0;
532         bridging = FALSE;
533         progressSetup = progressAlert = 0;
534         dtmfMode = 0;
535         dtmfCodec = (RTP_DataFrame::PayloadTypes)0;
536         redirect_reason = -1;
537 #ifdef TUNNELLING
538         tunnelOptions = remoteTunnelOptions = 0;
539 #endif
540         if (h323debug) {
541                 cout << "       == New H.323 Connection created." << endl;
542         }
543         return;
544 }
545
546 MyH323Connection::~MyH323Connection()
547 {
548         if (h323debug) {
549                 cout << "       == H.323 Connection deleted." << endl;
550         }
551         return;
552 }
553
554 BOOL MyH323Connection::OnReceivedProgress(const H323SignalPDU &pdu)
555 {
556         BOOL isInband;
557         unsigned pi;
558
559         if (!H323Connection::OnReceivedProgress(pdu)) {
560                 return FALSE;
561         }
562
563         if (!pdu.GetQ931().GetProgressIndicator(pi))
564                 pi = 0;
565         if (h323debug) {
566                 cout << "\t- Progress Indicator: " << pi << endl;
567         }
568
569         switch(pi) {
570         case Q931::ProgressNotEndToEndISDN:
571         case Q931::ProgressInbandInformationAvailable:
572                 isInband = TRUE;
573                 break;
574         default:
575                 isInband = FALSE;
576         }
577         on_progress(GetCallReference(), (const char *)GetCallToken(), isInband);
578
579         return connectionState != ShuttingDownConnection;
580 }
581
582 H323Connection::AnswerCallResponse MyH323Connection::OnAnswerCall(const PString & caller,
583                                                                 const H323SignalPDU & setupPDU,
584                                                                 H323SignalPDU & connectPDU)
585 {
586         unsigned pi;
587
588         if (h323debug) {
589                 cout << "\t=-= In OnAnswerCall for call " << GetCallReference() << endl;
590         }
591
592         if (connectionState == ShuttingDownConnection)
593                 return H323Connection::AnswerCallDenied;
594
595         if (!setupPDU.GetQ931().GetProgressIndicator(pi)) {
596                 pi = 0;
597         }
598         if (h323debug) {
599                 cout << "\t\t- Progress Indicator: " << pi << endl;
600         }
601         if (progressAlert) {
602                 pi = progressAlert;
603         } else if (pi == Q931::ProgressOriginNotISDN) {
604                 pi = Q931::ProgressInbandInformationAvailable;
605         }
606         if (pi && alertingPDU) {
607                 alertingPDU->GetQ931().SetProgressIndicator(pi);
608         }
609         if (h323debug) {
610                 cout << "\t\t- Inserting PI of " << pi << " into ALERTING message" << endl;
611         }
612
613 #ifdef TUNNELLING
614         if (alertingPDU)
615                 EmbedTunneledInfo(*alertingPDU);
616         EmbedTunneledInfo(connectPDU);
617 #endif
618
619         if (!on_answer_call(GetCallReference(), (const char *)GetCallToken())) {
620                 return H323Connection::AnswerCallDenied;
621         }
622         /* The call will be answered later with "AnsweringCall()" function.
623          */
624         return ((pi || (fastStartState != FastStartDisabled)) ? AnswerCallDeferredWithMedia : AnswerCallDeferred);
625 }
626
627 BOOL MyH323Connection::OnAlerting(const H323SignalPDU & alertingPDU, const PString & username)
628 {
629         if (h323debug) {
630                 cout << "\t=-= In OnAlerting for call " << GetCallReference()
631                         << ": sessionId=" << sessionId << endl;
632                 cout << "\t-- Ringing phone for \"" << username << "\"" << endl;
633         }
634
635         if (on_progress) {
636                 BOOL isInband;
637                 unsigned alertingPI;
638
639                 if (!alertingPDU.GetQ931().GetProgressIndicator(alertingPI)) {
640                         alertingPI = 0;
641                 }
642                 if (h323debug) {
643                         cout << "\t\t- Progress Indicator: " << alertingPI << endl;
644                 }
645
646                 switch(alertingPI) {
647                 case Q931::ProgressNotEndToEndISDN:
648                 case Q931::ProgressInbandInformationAvailable:
649                         isInband = TRUE;
650                         break;
651                 default:
652                         isInband = FALSE;
653                 }
654                 on_progress(GetCallReference(), (const char *)GetCallToken(), isInband);
655         }
656         on_chan_ringing(GetCallReference(), (const char *)GetCallToken() );
657         return connectionState != ShuttingDownConnection;
658 }
659
660 void MyH323Connection::SetCallOptions(void *o, BOOL isIncoming)
661 {
662         call_options_t *opts = (call_options_t *)o;
663
664         progressSetup = opts->progress_setup;
665         progressAlert = opts->progress_alert;
666         dtmfCodec = (RTP_DataFrame::PayloadTypes)opts->dtmfcodec;
667         dtmfMode = opts->dtmfmode;
668
669         if (isIncoming) {
670                 fastStartState = (opts->fastStart ? FastStartInitiate : FastStartDisabled);
671                 h245Tunneling = (opts->h245Tunneling ? TRUE : FALSE);
672         } else {
673                 SetLocalPartyName(PString(opts->cid_num));
674                 SetDisplayName(PString(opts->cid_name));
675                 if (opts->redirect_reason >= 0) {
676                         rdnis = PString(opts->cid_rdnis);
677                         redirect_reason = opts->redirect_reason;
678                 }
679         }
680         tunnelOptions = opts->tunnelOptions;
681 }
682
683 void MyH323Connection::SetCallDetails(void *callDetails, const H323SignalPDU &setupPDU, BOOL isIncoming)
684 {
685         PString sourceE164;
686         PString destE164;
687         PString sourceAliases;
688         PString destAliases;
689         char *s, *s1;
690         call_details_t *cd = (call_details_t *)callDetails;
691
692         memset(cd, 0, sizeof(*cd));
693         cd->call_reference = GetCallReference();
694         cd->call_token = strdup((const char *)GetCallToken());
695
696         sourceE164 = "";
697         setupPDU.GetSourceE164(sourceE164);
698         cd->call_source_e164 = strdup((const char *)sourceE164);
699
700         destE164 = "";
701         setupPDU.GetDestinationE164(destE164);
702         cd->call_dest_e164 = strdup((const char *)destE164);
703
704         /* XXX Is it possible to have this information for outgoing calls too? XXX */
705         if (isIncoming) {
706                 PString sourceName;
707                 PIPSocket::Address Ip;
708                 WORD sourcePort;
709                 PString redirect_number;
710                 unsigned redirect_reason;
711
712                 sourceName = setupPDU.GetQ931().GetDisplayName();
713                 cd->call_source_name = strdup((const char *)sourceName);
714
715                 GetSignallingChannel()->GetRemoteAddress().GetIpAndPort(Ip, sourcePort);
716                 cd->sourceIp = strdup((const char *)Ip.AsString());
717
718                 if(setupPDU.GetQ931().GetRedirectingNumber(redirect_number, NULL, NULL, NULL, NULL, &redirect_reason, 0, 0, 0)) {
719                         cd->redirect_number = strdup((const char *)redirect_number);
720                         cd->redirect_reason = redirect_reason;
721                 }
722                 else
723                         cd->redirect_reason = -1;
724         }
725
726         /* Convert complex strings */
727         //  FIXME: deal more than one source alias
728         sourceAliases = setupPDU.GetSourceAliases();
729         s1 = strdup((const char *)sourceAliases);
730         if ((s = strchr(s1, ' ')) != NULL)
731                 *s = '\0';
732         if ((s = strchr(s1, '\t')) != NULL)
733                 *s = '\0';
734         cd->call_source_aliases = s1;
735
736         destAliases = setupPDU.GetDestinationAlias();
737         s1 = strdup((const char *)destAliases);
738         if ((s = strchr(s1, ' ')) != NULL)
739                 *s = '\0';
740         if ((s = strchr(s1, '\t')) != NULL)
741                 *s = '\0';
742         cd->call_dest_alias = s1;
743 }
744
745 #ifdef TUNNELLING
746 static BOOL FetchInformationElements(Q931 &q931, const PBYTEArray &data)
747 {
748         PINDEX offset = 0;
749
750         while (offset < data.GetSize()) {
751                 // Get field discriminator
752                 int discriminator = data[offset++];
753
754 #if 0
755                 /* Do not overwrite existing IEs */
756                 if (q931.HasIE((Q931::InformationElementCodes)discriminator)) {
757                         if ((discriminatir & 0x80) == 0)
758                                 offset += data[offset++];
759                         if (offset > data.GetSize())
760                                 return FALSE;
761                         continue;
762                 }
763 #endif
764
765                 PBYTEArray * item = new PBYTEArray;
766
767                 // For discriminator with high bit set there is no data
768                 if ((discriminator & 0x80) == 0) {
769                         int len = data[offset++];
770
771 #if 0           // That is not H.225 but regular Q.931 (ISDN) IEs
772                         if (discriminator == UserUserIE) {
773                                 // Special case of User-user field. See 7.2.2.31/H.225.0v4.
774                                 len <<= 8;
775                                 len |= data[offset++];
776
777                                 // we also have a protocol discriminator, which we ignore
778                                 offset++;
779
780                                 // before decrementing the length, make sure it is not zero
781                                 if (len == 0)
782                                         return FALSE;
783
784                                 // adjust for protocol discriminator
785                                 len--;
786                         }
787 #endif
788
789                         if (offset + len > data.GetSize()) {
790                                 delete item;
791                                 return FALSE;
792                         }
793
794                         memcpy(item->GetPointer(len), (const BYTE *)data+offset, len);
795                         offset += len;
796                 }
797
798                 q931.SetIE((Q931::InformationElementCodes)discriminator, *item);
799                 delete item;
800         }
801         return TRUE;
802 }
803
804 static BOOL FetchCiscoTunneledInfo(Q931 &q931, const H323SignalPDU &pdu)
805 {
806         BOOL res = FALSE;
807         const H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
808
809         if(uuPDU.HasOptionalField(H225_H323_UU_PDU::e_nonStandardControl)) {
810                 for(int i = 0; i < uuPDU.m_nonStandardControl.GetSize(); ++i) {
811                         const H225_NonStandardParameter &np = uuPDU.m_nonStandardControl[i];
812                         const H225_NonStandardIdentifier &id = np.m_nonStandardIdentifier;
813                         if (id.GetTag() == H225_NonStandardIdentifier::e_h221NonStandard) {
814                                 const H225_H221NonStandard &ni = id;
815                                 /* Check for Cisco */
816                                 if ((ni.m_t35CountryCode == 181) && (ni.m_t35Extension == 0) && (ni.m_manufacturerCode == 18)) {
817                                         const PBYTEArray &data = np.m_data;
818                                         if (h323debug)
819                                                 cout << setprecision(0) << "Received non-standard Cisco extension data " << np.m_data << endl;
820                                         CISCO_H225_H323_UU_NonStdInfo c;
821                                         PPER_Stream strm(data);
822                                         if (c.Decode(strm)) {
823                                                 BOOL haveIEs = FALSE;
824                                                 if (h323debug)
825                                                         cout << setprecision(0) << "H323_UU_NonStdInfo = " << c << endl;
826                                                 if (c.HasOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_protoParam)) {
827                                                         FetchInformationElements(q931, c.m_protoParam.m_qsigNonStdInfo.m_rawMesg);
828                                                         haveIEs = TRUE;
829                                                 }
830                                                 if (c.HasOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_commonParam)) {
831                                                         FetchInformationElements(q931, c.m_commonParam.m_redirectIEinfo.m_redirectIE);
832                                                         haveIEs = TRUE;
833                                                 }
834                                                 if (haveIEs && h323debug)
835                                                         cout << setprecision(0) << "Information elements collected:" << q931 << endl;
836                                                 res = TRUE;
837                                         } else {
838                                                 cout << "ERROR while decoding non-standard Cisco extension" << endl;
839                                                 return FALSE;
840                                         }
841                                 }
842                         }
843                 }
844         }
845         return res;
846 }
847
848 static BOOL EmbedCiscoTunneledInfo(H323SignalPDU &pdu)
849 {
850         const static Q931::InformationElementCodes codes[] =
851         { Q931::RedirectingNumberIE, Q931::FacilityIE };
852
853         BOOL res = FALSE;
854         BOOL notRedirOnly = FALSE;
855         Q931 tmpQ931;
856         Q931 &q931 = pdu.GetQ931();
857
858         for(unsigned i = 0; i < (sizeof(codes) / sizeof(codes[0])); ++i) {
859                 if (q931.HasIE(codes[i])) {
860                         tmpQ931.SetIE(codes[i], q931.GetIE(codes[i]));
861                         q931.RemoveIE(codes[i]);
862                         if (codes[i] != Q931::RedirectingNumberIE)
863                                 notRedirOnly = TRUE;
864                         res = TRUE;
865                 }
866         }
867         /* Have something to embed */
868         if (res) {
869                 PBYTEArray msg;
870                 if (!tmpQ931.Encode(msg))
871                         return FALSE;
872                 PBYTEArray ies(msg.GetPointer() + 5, msg.GetSize() - 5);
873
874                 H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
875                 if(!uuPDU.HasOptionalField(H225_H323_UU_PDU::e_nonStandardControl)) {
876                         uuPDU.IncludeOptionalField(H225_H323_UU_PDU::e_nonStandardControl);
877                         uuPDU.m_nonStandardControl.SetSize(0);
878                 }
879                 H225_NonStandardParameter *np = new H225_NonStandardParameter;
880                 uuPDU.m_nonStandardControl.Append(np);
881                 H225_NonStandardIdentifier &nsi = (*np).m_nonStandardIdentifier;
882                 nsi.SetTag(H225_NonStandardIdentifier::e_h221NonStandard);
883                 H225_H221NonStandard &ns = nsi;
884                 ns.m_t35CountryCode = 181;
885                 ns.m_t35Extension = 0;
886                 ns.m_manufacturerCode = 18;
887
888                 CISCO_H225_H323_UU_NonStdInfo c;
889                 c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_version);
890                 c.m_version = 0;
891
892                 if (notRedirOnly) {
893                         c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_protoParam);
894                         CISCO_H225_QsigNonStdInfo &qsigInfo = c.m_protoParam.m_qsigNonStdInfo;
895                         qsigInfo.m_iei = ies[0];
896                         qsigInfo.m_rawMesg = ies;
897                 } else {
898                         c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_commonParam);
899                         c.m_commonParam.m_redirectIEinfo.m_redirectIE = ies;
900                 }
901                 PPER_Stream stream;
902                 c.Encode(stream);
903                 stream.CompleteEncoding();
904                 (*np).m_data = stream;
905         }
906         return res;
907 }
908
909 static const char OID_QSIG[] = "1.3.12.9";
910
911 static BOOL FetchQSIGTunneledInfo(Q931 &q931, const H323SignalPDU &pdu)
912 {
913         BOOL res = FALSE;
914         const H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
915         if (uuPDU.HasOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage)) {
916                 const H225_H323_UU_PDU_tunnelledSignallingMessage &sig = uuPDU.m_tunnelledSignallingMessage;
917                 const H225_TunnelledProtocol_id &proto = sig.m_tunnelledProtocolID.m_id;
918                 if ((proto.GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
919                                 (((const PASN_ObjectId &)proto).AsString() == OID_QSIG)) {
920                         const H225_ArrayOf_PASN_OctetString &sigs = sig.m_messageContent;
921                         for(int i = 0; i < sigs.GetSize(); ++i) {
922                                 const PASN_OctetString &msg = sigs[i];
923                                 if (h323debug)
924                                         cout << setprecision(0) << "Q.931 message data is " << msg << endl;
925                                 if(!q931.Decode((const PBYTEArray &)msg)) {
926                                         cout << "Error while decoding Q.931 message" << endl;
927                                         return FALSE;
928                                 }
929                                 res = TRUE;
930                                 if (h323debug)
931                                         cout << setprecision(0) << "Received QSIG message " << q931 << endl;
932                         }
933                 }
934         }
935         return res;
936 }
937
938 static H225_EndpointType *GetEndpointType(H323SignalPDU &pdu)
939 {
940         if (!pdu.GetQ931().HasIE(Q931::UserUserIE))
941                 return NULL;
942
943         H225_H323_UU_PDU_h323_message_body &body = pdu.m_h323_uu_pdu.m_h323_message_body;
944         switch (body.GetTag()) {
945         case H225_H323_UU_PDU_h323_message_body::e_setup:
946                 return &((H225_Setup_UUIE &)body).m_sourceInfo;
947         case H225_H323_UU_PDU_h323_message_body::e_callProceeding:
948                 return &((H225_CallProceeding_UUIE &)body).m_destinationInfo;
949         case H225_H323_UU_PDU_h323_message_body::e_connect:
950                 return &((H225_Connect_UUIE &)body).m_destinationInfo;
951         case H225_H323_UU_PDU_h323_message_body::e_alerting:
952                 return &((H225_Alerting_UUIE &)body).m_destinationInfo;
953         case H225_H323_UU_PDU_h323_message_body::e_facility:
954                 return &((H225_Facility_UUIE &)body).m_destinationInfo;
955         case H225_H323_UU_PDU_h323_message_body::e_progress:
956                 return &((H225_Progress_UUIE &)body).m_destinationInfo;
957         }
958         return NULL;
959 }
960
961 static BOOL QSIGTunnelRequested(H323SignalPDU &pdu)
962 {
963         H225_EndpointType *epType = GetEndpointType(pdu);
964         if (epType) {
965                 if (!(*epType).HasOptionalField(H225_EndpointType::e_supportedTunnelledProtocols)) {
966                         return FALSE;
967                 }
968                 H225_ArrayOf_TunnelledProtocol &protos = (*epType).m_supportedTunnelledProtocols;
969                 for (int i = 0; i < protos.GetSize(); ++i)
970                 {
971                         if ((protos[i].GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
972                                         (((const PASN_ObjectId &)protos[i]).AsString() == OID_QSIG)) {
973                                 return TRUE;
974                         }
975                 }
976         }
977         return FALSE;
978 }
979
980 static BOOL EmbedQSIGTunneledInfo(H323SignalPDU &pdu)
981 {
982         const static Q931::InformationElementCodes codes[] =
983         { Q931::RedirectingNumberIE, Q931::FacilityIE };
984
985         Q931 &q931 = pdu.GetQ931();
986         PBYTEArray message;
987
988         q931.Encode(message);
989
990         /* Remove non-standard IEs */
991         for(unsigned i = 0; i < (sizeof(codes) / sizeof(codes[0])); ++i) {
992                 if (q931.HasIE(codes[i])) {
993                         q931.RemoveIE(codes[i]);
994                 }
995         }
996
997         H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
998         H225_EndpointType *epType = GetEndpointType(pdu);
999         if (epType) {
1000                 if (!(*epType).HasOptionalField(H225_EndpointType::e_supportedTunnelledProtocols)) {
1001                         (*epType).IncludeOptionalField(H225_EndpointType::e_supportedTunnelledProtocols);
1002                         (*epType).m_supportedTunnelledProtocols.SetSize(0);
1003                 }
1004                 H225_ArrayOf_TunnelledProtocol &protos = (*epType).m_supportedTunnelledProtocols;
1005                 BOOL addQSIG = TRUE;
1006                 for (int i = 0; i < protos.GetSize(); ++i)
1007                 {
1008                         if ((protos[i].GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
1009                                         (((const PASN_ObjectId &)protos[i]).AsString() == OID_QSIG)) {
1010                                 addQSIG = FALSE;
1011                                 break;
1012                         }
1013                 }
1014                 if (addQSIG) {
1015                         H225_TunnelledProtocol *proto = new H225_TunnelledProtocol;
1016                         (*proto).m_id.SetTag(H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID);
1017                         (PASN_ObjectId &)(proto->m_id) = OID_QSIG;
1018                         protos.Append(proto);
1019                 }
1020         }
1021         if (!uuPDU.HasOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage))
1022                 uuPDU.IncludeOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage);
1023         H225_H323_UU_PDU_tunnelledSignallingMessage &sig = uuPDU.m_tunnelledSignallingMessage;
1024         H225_TunnelledProtocol_id &proto = sig.m_tunnelledProtocolID.m_id;
1025         if ((proto.GetTag() != H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) ||
1026                         (((const PASN_ObjectId &)proto).AsString() != OID_QSIG)) {
1027                 proto.SetTag(H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID);
1028                 (PASN_ObjectId &)proto = OID_QSIG;
1029                 sig.m_messageContent.SetSize(0);
1030         }
1031         PASN_OctetString *msg = new PASN_OctetString;
1032         sig.m_messageContent.Append(msg);
1033         *msg = message;
1034         return TRUE;
1035 }
1036
1037 BOOL MyH323Connection::EmbedTunneledInfo(H323SignalPDU &pdu)
1038 {
1039         if ((tunnelOptions & H323_TUNNEL_QSIG) || (remoteTunnelOptions & H323_TUNNEL_QSIG))
1040                 EmbedQSIGTunneledInfo(pdu);
1041         if ((tunnelOptions & H323_TUNNEL_CISCO) || (remoteTunnelOptions & H323_TUNNEL_CISCO))
1042                 EmbedCiscoTunneledInfo(pdu);
1043
1044         return TRUE;
1045 }
1046
1047 /* Handle tunneled messages */
1048 BOOL MyH323Connection::HandleSignalPDU(H323SignalPDU &pdu)
1049 {
1050         if (pdu.GetQ931().HasIE(Q931::UserUserIE)) {
1051                 Q931 tunneledInfo;
1052                 const Q931 *q931Info;
1053
1054                 q931Info = NULL;
1055                 if (FetchCiscoTunneledInfo(tunneledInfo, pdu)) {
1056                         q931Info = &tunneledInfo;
1057                         remoteTunnelOptions |= H323_TUNNEL_CISCO;
1058                 }
1059                 if (FetchQSIGTunneledInfo(tunneledInfo, pdu)) {
1060                         q931Info = &tunneledInfo;
1061                         remoteTunnelOptions |= H323_TUNNEL_QSIG;
1062                 }
1063                 if (!(remoteTunnelOptions & H323_TUNNEL_QSIG) && QSIGTunnelRequested(pdu)) {
1064                         remoteTunnelOptions |= H323_TUNNEL_QSIG;
1065                 }
1066                 if (q931Info) {
1067                         if (q931Info->HasIE(Q931::RedirectingNumberIE)) {
1068                                 pdu.GetQ931().SetIE(Q931::RedirectingNumberIE, q931Info->GetIE(Q931::RedirectingNumberIE));
1069                                 if (h323debug) {
1070                                         PString number;
1071                                         unsigned reason;
1072                                         if(q931Info->GetRedirectingNumber(number, NULL, NULL, NULL, NULL, &reason, 0, 0, 0))
1073                                                 cout << "Got redirection from " << number << ", reason " << reason << endl;
1074                                 }
1075                         }
1076                 }
1077         }
1078
1079         return H323Connection::HandleSignalPDU(pdu);
1080 }
1081 #endif
1082
1083 BOOL MyH323Connection::OnReceivedSignalSetup(const H323SignalPDU & setupPDU)
1084 {
1085         call_details_t cd;
1086
1087         if (h323debug) {
1088                 cout << "\t--Received SETUP message" << endl;
1089         }
1090
1091         if (connectionState == ShuttingDownConnection)
1092                 return FALSE;
1093
1094         SetCallDetails(&cd, setupPDU, TRUE);
1095
1096         /* Notify Asterisk of the request */
1097         call_options_t *res = on_incoming_call(&cd);
1098
1099         if (!res) {
1100                 if (h323debug) {
1101                         cout << "\t-- Call Failed" << endl;
1102                 }
1103                 return FALSE;
1104         }
1105
1106         SetCallOptions(res, TRUE);
1107
1108         return H323Connection::OnReceivedSignalSetup(setupPDU);
1109 }
1110
1111 BOOL MyH323Connection::OnSendSignalSetup(H323SignalPDU & setupPDU)
1112 {
1113         call_details_t cd;
1114
1115         if (h323debug) {
1116                 cout << "\t-- Sending SETUP message" << endl;
1117         }
1118
1119         if (connectionState == ShuttingDownConnection)
1120                 return FALSE;
1121
1122         if (progressSetup)
1123                 setupPDU.GetQ931().SetProgressIndicator(progressSetup);
1124
1125         if (redirect_reason >= 0) {
1126                 setupPDU.GetQ931().SetRedirectingNumber(rdnis, 0, 0, 0, 0, redirect_reason);
1127                 /* OpenH323 incorrectly fills number IE when redirecting reason is specified - fix it */
1128                 PBYTEArray IE(setupPDU.GetQ931().GetIE(Q931::RedirectingNumberIE));
1129                 IE[0] = IE[0] & 0x7f;
1130                 IE[1] = IE[1] & 0x7f;
1131                 setupPDU.GetQ931().SetIE(Q931::RedirectingNumberIE, IE);
1132         }
1133
1134         SetCallDetails(&cd, setupPDU, FALSE);
1135
1136         int res = on_outgoing_call(&cd);
1137         if (!res) {
1138                 if (h323debug) {
1139                         cout << "\t-- Call Failed" << endl;
1140                 }
1141                 return FALSE;
1142         }
1143
1144 #ifdef TUNNELLING
1145         EmbedTunneledInfo(setupPDU);
1146 #endif
1147
1148         return H323Connection::OnSendSignalSetup(setupPDU);
1149 }
1150
1151 BOOL MyH323Connection::OnSendReleaseComplete(H323SignalPDU & releaseCompletePDU)
1152 {
1153         if (h323debug) {
1154                 cout << "\t-- Sending RELEASE COMPLETE" << endl;
1155         }
1156         if (cause > 0)
1157                 releaseCompletePDU.GetQ931().SetCause((Q931::CauseValues)cause);
1158
1159 #ifdef TUNNELLING
1160         EmbedTunneledInfo(releaseCompletePDU);
1161 #endif
1162
1163         return H323Connection::OnSendReleaseComplete(releaseCompletePDU);
1164 }
1165
1166 BOOL MyH323Connection::OnReceivedFacility(const H323SignalPDU & pdu)
1167 {
1168         if (h323debug) {
1169                 cout << "\t-- Received Facility message... " << endl;
1170         }
1171         return H323Connection::OnReceivedFacility(pdu);
1172 }
1173
1174 void MyH323Connection::OnReceivedReleaseComplete(const H323SignalPDU & pdu)
1175 {
1176         if (h323debug) {
1177                 cout << "\t-- Received RELEASE COMPLETE message..." << endl;
1178         }
1179         if (on_hangup)
1180                 on_hangup(GetCallReference(), (const char *)GetCallToken(), pdu.GetQ931().GetCause());
1181         return H323Connection::OnReceivedReleaseComplete(pdu);
1182 }
1183
1184 BOOL MyH323Connection::OnClosingLogicalChannel(H323Channel & channel)
1185 {
1186         if (h323debug) {
1187                 cout << "\t-- Closing logical channel..." << endl;
1188         }
1189         return H323Connection::OnClosingLogicalChannel(channel);
1190 }
1191
1192 void MyH323Connection::SendUserInputTone(char tone, unsigned duration, unsigned logicalChannel, unsigned rtpTimestamp)
1193 {
1194         SendUserInputModes mode = GetRealSendUserInputMode();
1195 //      That is recursive call... Why?
1196 //      on_receive_digit(GetCallReference(), tone, (const char *)GetCallToken());
1197         if ((tone != ' ') || (mode == SendUserInputAsTone) || (mode == SendUserInputAsInlineRFC2833)) {
1198                 if (h323debug) {
1199                         cout << "\t-- Sending user input tone (" << tone << ") to remote" << endl;
1200                 }
1201                 H323Connection::SendUserInputTone(tone, duration);
1202         }
1203 }
1204
1205 void MyH323Connection::OnUserInputTone(char tone, unsigned duration, unsigned logicalChannel, unsigned rtpTimestamp)
1206 {
1207         if (dtmfMode == H323_DTMF_RFC2833) {
1208                 if (h323debug) {
1209                         cout << "\t-- Received user input tone (" << tone << ") from remote" << endl;
1210                 }
1211                 on_receive_digit(GetCallReference(), tone, (const char *)GetCallToken(), duration);
1212         }
1213 }
1214
1215 void MyH323Connection::OnUserInputString(const PString &value)
1216 {
1217         if (h323debug) {
1218                 cout << "\t-- Received user input string (" << value << ") from remote." << endl;
1219         }
1220         on_receive_digit(GetCallReference(), value[0], (const char *)GetCallToken(), 0);
1221 }
1222
1223 void MyH323Connection::OnSendCapabilitySet(H245_TerminalCapabilitySet & pdu)
1224 {
1225         PINDEX i;
1226
1227         H323Connection::OnSendCapabilitySet(pdu);
1228
1229         H245_ArrayOf_CapabilityTableEntry & tables = pdu.m_capabilityTable;
1230         for(i = 0; i < tables.GetSize(); i++)
1231         {
1232                 H245_CapabilityTableEntry & entry = tables[i];
1233                 if (entry.HasOptionalField(H245_CapabilityTableEntry::e_capability)) {
1234                         H245_Capability & cap = entry.m_capability;
1235                         if (cap.GetTag() == H245_Capability::e_receiveRTPAudioTelephonyEventCapability) {
1236                                 H245_AudioTelephonyEventCapability & atec = cap;
1237                                 atec.m_dynamicRTPPayloadType = dtmfCodec;
1238 //                              on_set_rfc2833_payload(GetCallReference(), (const char *)GetCallToken(), (int)dtmfCodec);
1239                                 if (h323debug) {
1240                                         cout << "\t-- Transmitting RFC2833 on payload " <<
1241                                                 atec.m_dynamicRTPPayloadType << endl;
1242                                 }
1243                         }
1244                 }
1245         }
1246 }
1247
1248 void MyH323Connection::OnSetLocalCapabilities()
1249 {
1250         if (on_setcapabilities)
1251                 on_setcapabilities(GetCallReference(), (const char *)callToken);
1252 }
1253
1254 BOOL MyH323Connection::OnReceivedCapabilitySet(const H323Capabilities & remoteCaps,
1255                                                         const H245_MultiplexCapability * muxCap,
1256                                                         H245_TerminalCapabilitySetReject & reject)
1257 {
1258         struct __codec__ {
1259                 unsigned int asterisk_codec;
1260                 unsigned int h245_cap;
1261                 const char *oid;
1262                 const char *formatName;
1263         };
1264         static const struct __codec__ codecs[] = {
1265                 { AST_FORMAT_G723_1, H245_AudioCapability::e_g7231 },
1266                 { AST_FORMAT_GSM, H245_AudioCapability::e_gsmFullRate },
1267                 { AST_FORMAT_ULAW, H245_AudioCapability::e_g711Ulaw64k },
1268                 { AST_FORMAT_ALAW, H245_AudioCapability::e_g711Alaw64k },
1269                 { AST_FORMAT_G729A, H245_AudioCapability::e_g729AnnexA },
1270                 { AST_FORMAT_G729A, H245_AudioCapability::e_g729 },
1271                 { AST_FORMAT_G726_AAL2, H245_AudioCapability::e_nonStandard, NULL, CISCO_G726r32 },
1272 #ifdef AST_FORMAT_MODEM
1273                 { AST_FORMAT_MODEM, H245_DataApplicationCapability_application::e_t38fax },
1274 #endif
1275                 { 0 }
1276         };
1277
1278 #if 0
1279         static const struct __codec__ vcodecs[] = {
1280 #ifdef HAVE_H261
1281                 { AST_FORMAT_H261, H245_VideoCapability::e_h261VideoCapability },
1282 #endif
1283 #ifdef HAVE_H263
1284                 { AST_FORMAT_H263, H245_VideoCapability::e_h263VideoCapability },
1285 #endif
1286 #ifdef HAVE_H264
1287                 { AST_FORMAT_H264, H245_VideoCapability::e_genericVideoCapability, "0.0.8.241.0.0.1" },
1288 #endif
1289                 { 0 }
1290         };
1291 #endif
1292         struct ast_codec_pref prefs;
1293
1294         if (!H323Connection::OnReceivedCapabilitySet(remoteCaps, muxCap, reject)) {
1295                 return FALSE;
1296         }
1297
1298         const H323Capability * cap = remoteCaps.FindCapability(H323_UserInputCapability::SubTypeNames[H323_UserInputCapability::SignalToneRFC2833]);
1299         if (cap != NULL) {
1300                 RTP_DataFrame::PayloadTypes pt = ((H323_UserInputCapability*)cap)->GetPayloadType();
1301                 on_set_rfc2833_payload(GetCallReference(), (const char *)GetCallToken(), (int)pt);
1302                 if ((dtmfMode == H323_DTMF_RFC2833) && (sendUserInputMode == SendUserInputAsTone))
1303                         sendUserInputMode = SendUserInputAsInlineRFC2833;
1304                 if (h323debug) {
1305                         cout << "\t-- Inbound RFC2833 on payload " << pt << endl;
1306                 }
1307         }
1308         memset(&prefs, 0, sizeof(prefs));
1309         int peer_capabilities = 0;
1310         for (int i = 0; i < remoteCapabilities.GetSize(); ++i) {
1311                 unsigned int subType = remoteCapabilities[i].GetSubType();
1312                 if (h323debug) {
1313                         cout << "Peer capability is " << remoteCapabilities[i] << endl;
1314                 }
1315                 switch(remoteCapabilities[i].GetMainType()) {
1316                 case H323Capability::e_Audio:
1317                         for (int x = 0; codecs[x].asterisk_codec > 0; ++x) {
1318                                 if ((subType == codecs[x].h245_cap) && (!codecs[x].formatName || (!strcmp(codecs[x].formatName, (const char *)remoteCapabilities[i].GetFormatName())))) {
1319                                         int ast_codec = codecs[x].asterisk_codec;
1320                                         int ms = 0;
1321                                         if (!(peer_capabilities & ast_codec)) {
1322                                                 struct ast_format_list format;
1323                                                 ast_codec_pref_append(&prefs, ast_codec);
1324                                                 format = ast_codec_pref_getsize(&prefs, ast_codec);
1325                                                 if ((ast_codec == AST_FORMAT_ALAW) || (ast_codec == AST_FORMAT_ULAW)) {
1326                                                         ms = remoteCapabilities[i].GetTxFramesInPacket();
1327                                                         if (ms > 60)
1328                                                                 ms = format.cur_ms;
1329                                                 } else
1330                                                         ms = remoteCapabilities[i].GetTxFramesInPacket() * format.inc_ms;
1331                                                 ast_codec_pref_setsize(&prefs, ast_codec, ms);
1332                                         }
1333                                         if (h323debug) {
1334                                                 cout << "Found peer capability " << remoteCapabilities[i] << ", Asterisk code is " << ast_codec << ", frame size (in ms) is " << ms << endl;
1335                                         }
1336                                         peer_capabilities |= ast_codec;
1337                                 }
1338                         }
1339                         break;
1340 #if 0
1341                 case H323Capability::e_Video:
1342                         for (int x = 0; vcodecs[x].asterisk_codec > 0; ++x) {
1343                                 if (subType == vcodecs[x].h245_cap) {
1344                                         H245_CapabilityIdentifier *cap = NULL;
1345                                         H245_GenericCapability y;
1346                                         if (vcodecs[x].oid) {
1347                                                 cap = new H245_CapabilityIdentifier(H245_CapabilityIdentifier::e_standard);
1348                                                 PASN_ObjectId &object_id = *cap;
1349                                                 object_id = vcodecs[x].oid;
1350                                                 y.m_capabilityIdentifier = *cap;
1351                                         }
1352                                         if ((subType != H245_VideoCapability::e_genericVideoCapability) ||
1353                                                         (vcodecs[x].oid && ((const H323GenericVideoCapability &)remoteCapabilities[i]).IsGenericMatch((const H245_GenericCapability)y))) {
1354                                                 if (h323debug) {
1355                                                         cout << "Found peer video capability " << remoteCapabilities[i] << ", Asterisk code is " << vcodecs[x].asterisk_codec << endl;
1356                                                 }
1357                                                 peer_capabilities |= vcodecs[x].asterisk_codec;
1358                                         }
1359                                         if (cap)
1360                                                 delete(cap);
1361                                 }
1362                         }
1363                         break;
1364 #endif
1365                 default:
1366                         break;
1367                 }
1368         }
1369         if (h323debug) {
1370                 char caps_str[1024], caps2_str[1024];
1371                 ast_codec_pref_string(&prefs, caps2_str, sizeof(caps2_str));
1372                 cout << "Peer capabilities = " << ast_getformatname_multiple(caps_str, sizeof(caps_str), peer_capabilities)
1373                                 << ", ordered list is " << caps2_str << endl;
1374         }
1375 #if 0
1376         redir_capabilities &= peer_capabilities;
1377 #endif
1378         if (on_setpeercapabilities)
1379                 on_setpeercapabilities(GetCallReference(), (const char *)callToken, peer_capabilities, &prefs);
1380
1381         return TRUE;
1382 }
1383
1384 H323Channel * MyH323Connection::CreateRealTimeLogicalChannel(const H323Capability & capability,
1385                                                                         H323Channel::Directions dir,
1386                                                                         unsigned sessionID,
1387                                                                         const H245_H2250LogicalChannelParameters * /*param*/,
1388                                                                         RTP_QOS * /*param*/ )
1389 {
1390         return new MyH323_ExternalRTPChannel(*this, capability, dir, sessionID);
1391 }
1392
1393 /** This callback function is invoked once upon creation of each
1394   * channel for an H323 session
1395   */
1396 BOOL MyH323Connection::OnStartLogicalChannel(H323Channel & channel)
1397 {
1398         /* Increase the count of channels we have open */
1399         channelsOpen++;
1400
1401         if (h323debug) {
1402                 cout << "\t-- Started logical channel: "
1403                                 << ((channel.GetDirection() == H323Channel::IsTransmitter) ? "sending " : ((channel.GetDirection() == H323Channel::IsReceiver) ? "receiving " : " "))
1404                                 << (const char *)(channel.GetCapability()).GetFormatName() << endl;
1405                 cout << "\t\t-- channelsOpen = " << channelsOpen << endl;
1406         }
1407         return connectionState != ShuttingDownConnection;
1408 }
1409
1410 void MyH323Connection::SetCapabilities(int cap, int dtmf_mode, void *_prefs, int pref_codec)
1411 {
1412         PINDEX lastcap = -1; /* last common capability index */
1413         int alreadysent = 0;
1414         int codec;
1415         int x, y;
1416         char caps_str[1024];
1417         struct ast_codec_pref *prefs = (struct ast_codec_pref *)_prefs;
1418         struct ast_format_list format;
1419         int frames_per_packet;
1420         int max_frames_per_packet;
1421
1422         localCapabilities.RemoveAll();
1423
1424         if (h323debug) {
1425                 cout << "Setting capabilities to " << ast_getformatname_multiple(caps_str, sizeof(caps_str), cap) << endl;
1426                 ast_codec_pref_string(prefs, caps_str, sizeof(caps_str));
1427                 cout << "Capabilities in preference order is " << caps_str << endl;
1428         }
1429         /* Add audio codecs in preference order first, then
1430            audio codecs without preference as allowed by mask */
1431         for (y = 0, x = -1; x < 32 + 32; ++x) {
1432                 if (x < 0)
1433                         codec = pref_codec;
1434                 else if (y || (!(codec = ast_codec_pref_index(prefs, x)))) {
1435                         if (!y)
1436                                 y = 1;
1437                         else if (y == AST_FORMAT_MAX_AUDIO)
1438                                 break;
1439                         else
1440                                 y <<= 1;
1441                         codec = y;
1442                 }
1443                 if (!(cap & codec) || (alreadysent & codec) || !(codec & AST_FORMAT_AUDIO_MASK))
1444                         continue;
1445                 alreadysent |= codec;
1446                 format = ast_codec_pref_getsize(prefs, codec);
1447                 frames_per_packet = (format.inc_ms ? format.cur_ms / format.inc_ms : format.cur_ms);
1448                 max_frames_per_packet = (format.inc_ms ? format.max_ms / format.inc_ms : 0);
1449                 switch(codec) {
1450 #if 0
1451                 case AST_FORMAT_SPEEX:
1452                         /* Not real sure if Asterisk acutally supports all
1453                            of the various different bit rates so add them
1454                            all and figure it out later*/
1455
1456                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow2AudioCapability());
1457                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow3AudioCapability());
1458                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow4AudioCapability());
1459                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow5AudioCapability());
1460                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow6AudioCapability());
1461                         break;
1462 #endif
1463                 case AST_FORMAT_G729A:
1464                         AST_G729ACapability *g729aCap;
1465                         AST_G729Capability *g729Cap;
1466                         lastcap = localCapabilities.SetCapability(0, 0, g729aCap = new AST_G729ACapability(frames_per_packet));
1467                         lastcap = localCapabilities.SetCapability(0, 0, g729Cap = new AST_G729Capability(frames_per_packet));
1468                         if (max_frames_per_packet) {
1469                                 g729aCap->SetTxFramesInPacket(max_frames_per_packet);
1470                                 g729Cap->SetTxFramesInPacket(max_frames_per_packet);
1471                         }
1472                         break;
1473                 case AST_FORMAT_G723_1:
1474                         AST_G7231Capability *g7231Cap;
1475                         lastcap = localCapabilities.SetCapability(0, 0, g7231Cap = new AST_G7231Capability(frames_per_packet, TRUE));
1476                         if (max_frames_per_packet)
1477                                 g7231Cap->SetTxFramesInPacket(max_frames_per_packet);
1478                         lastcap = localCapabilities.SetCapability(0, 0, g7231Cap = new AST_G7231Capability(frames_per_packet, FALSE));
1479                         if (max_frames_per_packet)
1480                                 g7231Cap->SetTxFramesInPacket(max_frames_per_packet);
1481                         break;
1482                 case AST_FORMAT_GSM:
1483                         AST_GSM0610Capability *gsmCap;
1484                         lastcap = localCapabilities.SetCapability(0, 0, gsmCap = new AST_GSM0610Capability(frames_per_packet));
1485                         if (max_frames_per_packet)
1486                                 gsmCap->SetTxFramesInPacket(max_frames_per_packet);
1487                         break;
1488                 case AST_FORMAT_ULAW:
1489                         AST_G711Capability *g711uCap;
1490                         lastcap = localCapabilities.SetCapability(0, 0, g711uCap = new AST_G711Capability(format.cur_ms, H323_G711Capability::muLaw));
1491                         if (format.max_ms)
1492                                 g711uCap->SetTxFramesInPacket(format.max_ms);
1493                         break;
1494                 case AST_FORMAT_ALAW:
1495                         AST_G711Capability *g711aCap;
1496                         lastcap = localCapabilities.SetCapability(0, 0, g711aCap = new AST_G711Capability(format.cur_ms, H323_G711Capability::ALaw));
1497                         if (format.max_ms)
1498                                 g711aCap->SetTxFramesInPacket(format.max_ms);
1499                         break;
1500                 case AST_FORMAT_G726_AAL2:
1501                         AST_CiscoG726Capability *g726Cap;
1502                         lastcap = localCapabilities.SetCapability(0, 0, g726Cap = new AST_CiscoG726Capability(frames_per_packet));
1503                         if (max_frames_per_packet)
1504                                 g726Cap->SetTxFramesInPacket(max_frames_per_packet);
1505                         break;
1506                 default:
1507                         alreadysent &= ~codec;
1508                         break;
1509                 }
1510         }
1511
1512         lastcap++;
1513         lastcap = localCapabilities.SetCapability(0, lastcap, new H323_UserInputCapability(H323_UserInputCapability::HookFlashH245));
1514
1515         lastcap++;
1516         dtmfMode = dtmf_mode;
1517         if (dtmf_mode == H323_DTMF_INBAND) {
1518                 localCapabilities.SetCapability(0, lastcap, new H323_UserInputCapability(H323_UserInputCapability::BasicString));
1519                 sendUserInputMode = SendUserInputAsString;
1520         } else {
1521                 lastcap = localCapabilities.SetCapability(0, lastcap, new H323_UserInputCapability(H323_UserInputCapability::SignalToneRFC2833));
1522                 /* Cisco sends DTMF only through h245-alphanumeric or h245-signal, no support for RFC2833 */
1523                 lastcap = localCapabilities.SetCapability(0, lastcap, new H323_UserInputCapability(H323_UserInputCapability::SignalToneH245));
1524                 sendUserInputMode = SendUserInputAsTone;        /* RFC2833 transmission handled at Asterisk level */
1525         }
1526
1527         if (h323debug) {
1528                 cout << "Allowed Codecs:\n\t" << setprecision(2) << localCapabilities << endl;
1529         }
1530 }
1531
1532 BOOL MyH323Connection::StartControlChannel(const H225_TransportAddress & h245Address)
1533 {
1534         // Check that it is an IP address, all we support at the moment
1535         if (h245Address.GetTag() != H225_TransportAddress::e_ipAddress
1536 #if P_HAS_IPV6
1537                 && h245Address.GetTag() != H225_TransportAddress::e_ip6Address
1538 #endif
1539         ) {
1540                 PTRACE(1, "H225\tConnect of H245 failed: Unsupported transport");
1541                 return FALSE;
1542         }
1543
1544         // Already have the H245 channel up.
1545         if (controlChannel != NULL)
1546                 return TRUE;
1547
1548         PIPSocket::Address addr;
1549         WORD port;
1550         GetSignallingChannel()->GetLocalAddress().GetIpAndPort(addr, port);
1551         if (addr) {
1552                 if (h323debug)
1553                         cout << "Using " << addr << " for outbound H.245 transport" << endl;
1554                 controlChannel = new MyH323TransportTCP(endpoint, addr);
1555         } else
1556                 controlChannel = new H323TransportTCP(endpoint);
1557         if (!controlChannel->SetRemoteAddress(h245Address)) {
1558                 PTRACE(1, "H225\tCould not extract H245 address");
1559                 delete controlChannel;
1560                 controlChannel = NULL;
1561                 return FALSE;
1562         }
1563         if (!controlChannel->Connect()) {
1564                 PTRACE(1, "H225\tConnect of H245 failed: " << controlChannel->GetErrorText());
1565                 delete controlChannel;
1566                 controlChannel = NULL;
1567                 return FALSE;
1568         }
1569
1570         controlChannel->StartControlChannel(*this);
1571         return TRUE;
1572 }
1573
1574 /* MyH323_ExternalRTPChannel */
1575 MyH323_ExternalRTPChannel::MyH323_ExternalRTPChannel(MyH323Connection & connection,
1576                                                         const H323Capability & capability,
1577                                                         Directions direction,
1578                                                         unsigned id)
1579         : H323_ExternalRTPChannel::H323_ExternalRTPChannel(connection, capability, direction, id)
1580 {
1581         struct rtp_info *info;
1582
1583         /* Determine the Local (A side) IP Address and port */
1584         info = on_external_rtp_create(connection.GetCallReference(), (const char *)connection.GetCallToken());
1585         if (!info) {
1586                 cout << "\tERROR: on_external_rtp_create failure" << endl;
1587                 return;
1588         } else {
1589                 localIpAddr = info->addr;
1590                 localPort = info->port;
1591                 /* tell the H.323 stack */
1592                 SetExternalAddress(H323TransportAddress(localIpAddr, localPort), H323TransportAddress(localIpAddr, localPort + 1));
1593                 /* clean up allocated memory */
1594                 free(info);
1595         }
1596
1597         /* Get the payload code */
1598         OpalMediaFormat format(capability.GetFormatName(), FALSE);
1599         payloadCode = format.GetPayloadType();
1600 }
1601
1602 MyH323_ExternalRTPChannel::~MyH323_ExternalRTPChannel()
1603 {
1604         if (h323debug) {
1605                 cout << "\tExternalRTPChannel Destroyed" << endl;
1606         }
1607 }
1608
1609 BOOL MyH323_ExternalRTPChannel::Start(void)
1610 {
1611         /* Call ancestor first */
1612         if (!H323_ExternalRTPChannel::Start()) {
1613                 return FALSE;
1614         }
1615
1616         if (h323debug) {
1617                 cout << "\t\tExternal RTP Session Starting" << endl;
1618                 cout << "\t\tRTP channel id " << sessionID << " parameters:" << endl;
1619         }
1620
1621         /* Collect the remote information */
1622         H323_ExternalRTPChannel::GetRemoteAddress(remoteIpAddr, remotePort);
1623
1624         if (h323debug) {
1625                 cout << "\t\t-- remoteIpAddress: " << remoteIpAddr << endl;
1626                 cout << "\t\t-- remotePort: " << remotePort << endl;
1627                 cout << "\t\t-- ExternalIpAddress: " << localIpAddr << endl;
1628                 cout << "\t\t-- ExternalPort: " << localPort << endl;
1629         }
1630         /* Notify Asterisk of remote RTP information */
1631         on_start_rtp_channel(connection.GetCallReference(), (const char *)remoteIpAddr.AsString(), remotePort,
1632                 (const char *)connection.GetCallToken(), (int)payloadCode);
1633         return TRUE;
1634 }
1635
1636 BOOL MyH323_ExternalRTPChannel::OnReceivedAckPDU(const H245_H2250LogicalChannelAckParameters & param)
1637 {
1638         if (h323debug) {
1639                 cout << "       MyH323_ExternalRTPChannel::OnReceivedAckPDU" << endl;
1640         }
1641
1642         if (H323_ExternalRTPChannel::OnReceivedAckPDU(param)) {
1643                 GetRemoteAddress(remoteIpAddr, remotePort);
1644                 if (h323debug) {
1645                         cout << "               -- remoteIpAddress: " << remoteIpAddr << endl;
1646                         cout << "               -- remotePort: " << remotePort << endl;
1647                 }
1648                 on_start_rtp_channel(connection.GetCallReference(), (const char *)remoteIpAddr.AsString(),
1649                                 remotePort, (const char *)connection.GetCallToken(), (int)payloadCode);
1650                 return TRUE;
1651         }
1652         return FALSE;
1653 }
1654
1655
1656 /** IMPLEMENTATION OF C FUNCTIONS */
1657
1658 /**
1659  * The extern "C" directive takes care for
1660  * the ANSI-C representation of linkable symbols
1661  */
1662
1663 extern "C" {
1664
1665 int h323_end_point_exist(void)
1666 {
1667         if (!endPoint) {
1668                 return 0;
1669         }
1670         return 1;
1671 }
1672
1673 void h323_end_point_create(void)
1674 {
1675         channelsOpen = 0;
1676         logstream = new PAsteriskLog();
1677         localProcess = new MyProcess();
1678         localProcess->Main();
1679 }
1680
1681 void h323_gk_urq(void)
1682 {
1683         if (!h323_end_point_exist()) {
1684                 cout << " ERROR: [h323_gk_urq] No Endpoint, this is bad" << endl;
1685                 return;
1686         }
1687         endPoint->RemoveGatekeeper();
1688 }
1689
1690 void h323_debug(int flag, unsigned level)
1691 {
1692         if (flag) {
1693                 PTrace:: SetLevel(level);
1694         } else {
1695                 PTrace:: SetLevel(0);
1696         }
1697 }
1698
1699 /** Installs the callback functions on behalf of the PBX application */
1700 void h323_callback_register(setup_incoming_cb           ifunc,
1701                                                         setup_outbound_cb               sfunc,
1702                                                         on_rtp_cb                               rtpfunc,
1703                                                         start_rtp_cb                    lfunc,
1704                                                         clear_con_cb                    clfunc,
1705                                                         chan_ringing_cb                 rfunc,
1706                                                         con_established_cb              efunc,
1707                                                         receive_digit_cb                dfunc,
1708                                                         answer_call_cb                  acfunc,
1709                                                         progress_cb                             pgfunc,
1710                                                         rfc2833_cb                              dtmffunc,
1711                                                         hangup_cb                               hangupfunc,
1712                                                         setcapabilities_cb              capabilityfunc,
1713                                                         setpeercapabilities_cb  peercapabilityfunc)
1714 {
1715         on_incoming_call = ifunc;
1716         on_outgoing_call = sfunc;
1717         on_external_rtp_create = rtpfunc;
1718         on_start_rtp_channel = lfunc;
1719         on_connection_cleared = clfunc;
1720         on_chan_ringing = rfunc;
1721         on_connection_established = efunc;
1722         on_receive_digit = dfunc;
1723         on_answer_call = acfunc;
1724         on_progress = pgfunc;
1725         on_set_rfc2833_payload = dtmffunc;
1726         on_hangup = hangupfunc;
1727         on_setcapabilities = capabilityfunc;
1728         on_setpeercapabilities = peercapabilityfunc;
1729 }
1730
1731 /**
1732  * Add capability to the capability table of the end point.
1733  */
1734 int h323_set_capabilities(const char *token, int cap, int dtmf_mode, struct ast_codec_pref *prefs, int pref_codec)
1735 {
1736         MyH323Connection *conn;
1737
1738         if (!h323_end_point_exist()) {
1739                 cout << " ERROR: [h323_set_capablities] No Endpoint, this is bad" << endl;
1740                 return 1;
1741         }
1742         if (!token || !*token) {
1743                 cout << " ERROR: [h323_set_capabilities] Invalid call token specified." << endl;
1744                 return 1;
1745         }
1746
1747         PString myToken(token);
1748         conn = (MyH323Connection *)endPoint->FindConnectionWithLock(myToken);
1749         if (!conn) {
1750                 cout << " ERROR: [h323_set_capabilities] Unable to find connection " << token << endl;
1751                 return 1;
1752         }
1753         conn->SetCapabilities((/*conn->bridging ? conn->redir_capabilities :*/ cap), dtmf_mode, prefs, pref_codec);
1754         conn->Unlock();
1755
1756         return 0;
1757 }
1758
1759 /** Start the H.323 listener */
1760 int h323_start_listener(int listenPort, struct sockaddr_in bindaddr)
1761 {
1762
1763         if (!h323_end_point_exist()) {
1764                 cout << "ERROR: [h323_start_listener] No Endpoint, this is bad!" << endl;
1765                 return 1;
1766         }
1767
1768         PIPSocket::Address interfaceAddress(bindaddr.sin_addr);
1769         if (!listenPort) {
1770                 listenPort = 1720;
1771         }
1772         /** H.323 listener */
1773         H323ListenerTCP *tcpListener;
1774         tcpListener = new H323ListenerTCP(*endPoint, interfaceAddress, (WORD)listenPort);
1775         if (!endPoint->StartListener(tcpListener)) {
1776                 cout << "ERROR: Could not open H.323 listener port on " << ((H323ListenerTCP *) tcpListener)->GetListenerPort() << endl;
1777                 delete tcpListener;
1778                 return 1;
1779         }
1780         cout << "  == H.323 listener started" << endl;
1781         return 0;
1782 };
1783
1784 int h323_set_alias(struct oh323_alias *alias)
1785 {
1786         char *p;
1787         char *num;
1788         PString h323id(alias->name);
1789         PString e164(alias->e164);
1790         char *prefix;
1791
1792         if (!h323_end_point_exist()) {
1793                 cout << "ERROR: [h323_set_alias] No Endpoint, this is bad!" << endl;
1794                 return 1;
1795         }
1796
1797         cout << "== Adding alias \"" << h323id << "\" to endpoint" << endl;
1798         endPoint->AddAliasName(h323id);
1799         endPoint->RemoveAliasName(localProcess->GetUserName());
1800
1801         if (!e164.IsEmpty()) {
1802                 cout << "== Adding E.164 \"" << e164 << "\" to endpoint" << endl;
1803                 endPoint->AddAliasName(e164);
1804         }
1805         if (strlen(alias->prefix)) {
1806                 p = prefix = strdup(alias->prefix);
1807                 while((num = strsep(&p, ",")) != (char *)NULL) {
1808                         cout << "== Adding Prefix \"" << num << "\" to endpoint" << endl;
1809                         endPoint->SupportedPrefixes += PString(num);
1810                         endPoint->SetGateway();
1811                 }
1812                 if (prefix)
1813                         free(prefix);
1814         }
1815         return 0;
1816 }
1817
1818 void h323_set_id(char *id)
1819 {
1820         PString h323id(id);
1821
1822         if (h323debug) {
1823                 cout << "  == Using '" << h323id << "' as our H.323ID for this call" << endl;
1824         }
1825         /* EVIL HACK */
1826         endPoint->SetLocalUserName(h323id);
1827 }
1828
1829 void h323_show_tokens(void)
1830 {
1831         cout << "Current call tokens: " << setprecision(2) << endPoint->GetAllConnections() << endl;
1832 }
1833
1834 /** Establish Gatekeeper communiations, if so configured,
1835   *     register aliases for the H.323 endpoint to respond to.
1836   */
1837 int h323_set_gk(int gatekeeper_discover, char *gatekeeper, char *secret)
1838 {
1839         PString gkName = PString(gatekeeper);
1840         PString pass = PString(secret);
1841         H323TransportUDP *rasChannel;
1842
1843         if (!h323_end_point_exist()) {
1844                 cout << "ERROR: [h323_set_gk] No Endpoint, this is bad!" << endl;
1845                 return 1;
1846         }
1847
1848         if (!gatekeeper) {
1849                 cout << "Error: Gatekeeper cannot be NULL" << endl;
1850                 return 1;
1851         }
1852         if (strlen(secret)) {
1853                 endPoint->SetGatekeeperPassword(pass);
1854         }
1855         if (gatekeeper_discover) {
1856                 /* discover the gk using multicast */
1857                 if (endPoint->DiscoverGatekeeper(new MyH323TransportUDP(*endPoint))) {
1858                         cout << "== Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
1859                 } else {
1860                         cout << "Warning: Could not find a gatekeeper." << endl;
1861                         return 1;
1862                 }
1863         } else {
1864                 rasChannel = new MyH323TransportUDP(*endPoint);
1865
1866                 if (!rasChannel) {
1867                         cout << "Error: No RAS Channel, this is bad" << endl;
1868                         return 1;
1869                 }
1870                 if (endPoint->SetGatekeeper(gkName, rasChannel)) {
1871                         cout << "== Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
1872                 } else {
1873                         cout << "Error registering with gatekeeper \"" << gkName << "\". " << endl;
1874                         /* XXX Maybe we should fire a new thread to attempt to re-register later and not kill asterisk here? */
1875                         return 1;
1876                 }
1877         }
1878         return 0;
1879 }
1880
1881 /** Send a DTMF tone over the H323Connection with the
1882   * specified token.
1883   */
1884 void h323_send_tone(const char *call_token, char tone)
1885 {
1886         if (!h323_end_point_exist()) {
1887                 cout << "ERROR: [h323_send_tone] No Endpoint, this is bad!" << endl;
1888                 return;
1889         }
1890         PString token = PString(call_token);
1891         endPoint->SendUserTone(token, tone);
1892 }
1893
1894 /** Make a call to the remote endpoint.
1895   */
1896 int h323_make_call(char *dest, call_details_t *cd, call_options_t *call_options)
1897 {
1898         int res;
1899         PString token;
1900         PString host(dest);
1901
1902         if (!h323_end_point_exist()) {
1903                 return 1;
1904         }
1905
1906         res = endPoint->MyMakeCall(host, token, &cd->call_reference, call_options);
1907         memcpy((char *)(cd->call_token), (const unsigned char *)token, token.GetLength());
1908         return res;
1909 };
1910
1911 int h323_clear_call(const char *call_token, int cause)
1912 {
1913         H225_ReleaseCompleteReason dummy;
1914         H323Connection::CallEndReason r = H323Connection::EndedByLocalUser;
1915         MyH323Connection *connection;
1916         const PString currentToken(call_token);
1917
1918         if (!h323_end_point_exist()) {
1919                 return 1;
1920         }
1921
1922         if (cause) {
1923                 r = H323TranslateToCallEndReason((Q931::CauseValues)(cause), dummy);
1924         }
1925
1926         connection = (MyH323Connection *)endPoint->FindConnectionWithLock(currentToken);
1927         if (connection) {
1928                 connection->SetCause(cause);
1929                 connection->SetCallEndReason(r);
1930                 connection->Unlock();
1931         }
1932         endPoint->ClearCall(currentToken, r);
1933         return 0;
1934 };
1935
1936 /* Send Alerting PDU to H.323 caller */
1937 int h323_send_alerting(const char *token)
1938 {
1939         const PString currentToken(token);
1940         H323Connection * connection;
1941
1942         if (h323debug) {
1943                 cout << "\tSending alerting" << endl;
1944         }
1945         connection = endPoint->FindConnectionWithLock(currentToken);
1946         if (!connection) {
1947                 cout << "No connection found for " << token << endl;
1948                 return -1;
1949         }
1950         connection->AnsweringCall(H323Connection::AnswerCallPending);
1951         connection->Unlock();
1952         return 0;
1953 }
1954
1955 /* Send Progress PDU to H.323 caller */
1956 int h323_send_progress(const char *token)
1957 {
1958         const PString currentToken(token);
1959         H323Connection * connection;
1960
1961         connection = endPoint->FindConnectionWithLock(currentToken);
1962         if (!connection) {
1963                 cout << "No connection found for " << token << endl;
1964                 return -1;
1965         }
1966         connection->AnsweringCall(H323Connection::AnswerCallDeferredWithMedia);
1967         connection->Unlock();
1968         return 0;
1969 }
1970
1971 /** This function tells the h.323 stack to either
1972     answer or deny an incoming call */
1973 int h323_answering_call(const char *token, int busy)
1974 {
1975         const PString currentToken(token);
1976         H323Connection * connection;
1977
1978         connection = endPoint->FindConnectionWithLock(currentToken);
1979
1980         if (!connection) {
1981                 cout << "No connection found for " << token << endl;
1982                 return -1;
1983         }
1984         if (!busy) {
1985                 if (h323debug) {
1986                         cout << "\tAnswering call " << token << endl;
1987                 }
1988                 connection->AnsweringCall(H323Connection::AnswerCallNow);
1989         } else {
1990                 if (h323debug) {
1991                         cout << "\tdenying call " << token << endl;
1992                 }
1993                 connection->AnsweringCall(H323Connection::AnswerCallDenied);
1994         }
1995         connection->Unlock();
1996         return 0;
1997 }
1998
1999 int h323_soft_hangup(const char *data)
2000 {
2001         PString token(data);
2002         BOOL result;
2003         cout << "Soft hangup" << endl;
2004         result = endPoint->ClearCall(token);
2005         return result;
2006 }
2007
2008 /* alas, this doesn't work :( */
2009 void h323_native_bridge(const char *token, const char *them, char *capability)
2010 {
2011         H323Channel *channel;
2012         MyH323Connection *connection = (MyH323Connection *)endPoint->FindConnectionWithLock(token);
2013
2014         if (!connection) {
2015                 cout << "ERROR: No connection found, this is bad" << endl;
2016                 return;
2017         }
2018
2019         cout << "Native Bridge:  them [" << them << "]" << endl;
2020
2021         channel = connection->FindChannel(connection->sessionId, TRUE);
2022         connection->bridging = TRUE;
2023         connection->CloseLogicalChannelNumber(channel->GetNumber());
2024
2025         connection->Unlock();
2026         return;
2027
2028 }
2029
2030 #undef cout
2031 #undef endl
2032 void h323_end_process(void)
2033 {
2034         if (endPoint) {
2035                 endPoint->ClearAllCalls();
2036                 endPoint->RemoveListener(NULL);
2037                 delete endPoint;
2038                 endPoint = NULL;
2039         }
2040         if (localProcess) {
2041                 delete localProcess;
2042                 localProcess = NULL;
2043                 close(_timerChangePipe[0]);
2044                 close(_timerChangePipe[1]);
2045         }
2046         if (logstream) {
2047                 PTrace::SetLevel(0);
2048                 PTrace::SetStream(&cout);
2049                 delete logstream;
2050                 logstream = NULL;
2051         }
2052 }
2053
2054 } /* extern "C" */
2055