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