Disable fastStart if requested by remote side
[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 = (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 = (RTP_DataFrame::PayloadTypes)opts->dtmfcodec;
668         dtmfMode = opts->dtmfmode;
669
670         if (isIncoming) {
671                 fastStartState = (opts->fastStart ? FastStartInitiate : FastStartDisabled);
672                 h245Tunneling = (opts->h245Tunneling ? TRUE : FALSE);
673         } else {
674                 SetLocalPartyName(PString(opts->cid_num));
675                 SetDisplayName(PString(opts->cid_name));
676                 if (opts->redirect_reason >= 0) {
677                         rdnis = PString(opts->cid_rdnis);
678                         redirect_reason = opts->redirect_reason;
679                 }
680         }
681         tunnelOptions = opts->tunnelOptions;
682 }
683
684 void MyH323Connection::SetCallDetails(void *callDetails, const H323SignalPDU &setupPDU, BOOL isIncoming)
685 {
686         PString sourceE164;
687         PString destE164;
688         PString sourceAliases;
689         PString destAliases;
690         char *s, *s1;
691         call_details_t *cd = (call_details_t *)callDetails;
692
693         memset(cd, 0, sizeof(*cd));
694         cd->call_reference = GetCallReference();
695         cd->call_token = strdup((const char *)GetCallToken());
696
697         sourceE164 = "";
698         setupPDU.GetSourceE164(sourceE164);
699         cd->call_source_e164 = strdup((const char *)sourceE164);
700
701         destE164 = "";
702         setupPDU.GetDestinationE164(destE164);
703         cd->call_dest_e164 = strdup((const char *)destE164);
704
705         /* XXX Is it possible to have this information for outgoing calls too? XXX */
706         if (isIncoming) {
707                 PString sourceName;
708                 PIPSocket::Address Ip;
709                 WORD sourcePort;
710                 PString redirect_number;
711                 unsigned redirect_reason;
712
713                 sourceName = setupPDU.GetQ931().GetDisplayName();
714                 cd->call_source_name = strdup((const char *)sourceName);
715
716                 GetSignallingChannel()->GetRemoteAddress().GetIpAndPort(Ip, sourcePort);
717                 cd->sourceIp = strdup((const char *)Ip.AsString());
718
719                 if(setupPDU.GetQ931().GetRedirectingNumber(redirect_number, NULL, NULL, NULL, NULL, &redirect_reason, 0, 0, 0)) {
720                         cd->redirect_number = strdup((const char *)redirect_number);
721                         cd->redirect_reason = redirect_reason;
722                 }
723                 else
724                         cd->redirect_reason = -1;
725         }
726
727         /* Convert complex strings */
728         //  FIXME: deal more than one source alias
729         sourceAliases = setupPDU.GetSourceAliases();
730         s1 = strdup((const char *)sourceAliases);
731         if ((s = strchr(s1, ' ')) != NULL)
732                 *s = '\0';
733         if ((s = strchr(s1, '\t')) != NULL)
734                 *s = '\0';
735         cd->call_source_aliases = s1;
736
737         destAliases = setupPDU.GetDestinationAlias();
738         s1 = strdup((const char *)destAliases);
739         if ((s = strchr(s1, ' ')) != NULL)
740                 *s = '\0';
741         if ((s = strchr(s1, '\t')) != NULL)
742                 *s = '\0';
743         cd->call_dest_alias = s1;
744 }
745
746 #ifdef TUNNELLING
747 static BOOL FetchInformationElements(Q931 &q931, const PBYTEArray &data)
748 {
749         PINDEX offset = 0;
750
751         while (offset < data.GetSize()) {
752                 // Get field discriminator
753                 int discriminator = data[offset++];
754
755 #if 0
756                 /* Do not overwrite existing IEs */
757                 if (q931.HasIE((Q931::InformationElementCodes)discriminator)) {
758                         if ((discriminatir & 0x80) == 0)
759                                 offset += data[offset++];
760                         if (offset > data.GetSize())
761                                 return FALSE;
762                         continue;
763                 }
764 #endif
765
766                 PBYTEArray * item = new PBYTEArray;
767
768                 // For discriminator with high bit set there is no data
769                 if ((discriminator & 0x80) == 0) {
770                         int len = data[offset++];
771
772 #if 0           // That is not H.225 but regular Q.931 (ISDN) IEs
773                         if (discriminator == UserUserIE) {
774                                 // Special case of User-user field. See 7.2.2.31/H.225.0v4.
775                                 len <<= 8;
776                                 len |= data[offset++];
777
778                                 // we also have a protocol discriminator, which we ignore
779                                 offset++;
780
781                                 // before decrementing the length, make sure it is not zero
782                                 if (len == 0)
783                                         return FALSE;
784
785                                 // adjust for protocol discriminator
786                                 len--;
787                         }
788 #endif
789
790                         if (offset + len > data.GetSize()) {
791                                 delete item;
792                                 return FALSE;
793                         }
794
795                         memcpy(item->GetPointer(len), (const BYTE *)data+offset, len);
796                         offset += len;
797                 }
798
799                 q931.SetIE((Q931::InformationElementCodes)discriminator, *item);
800                 delete item;
801         }
802         return TRUE;
803 }
804
805 static BOOL FetchCiscoTunneledInfo(Q931 &q931, const H323SignalPDU &pdu)
806 {
807         BOOL res = FALSE;
808         const H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
809
810         if(uuPDU.HasOptionalField(H225_H323_UU_PDU::e_nonStandardControl)) {
811                 for(int i = 0; i < uuPDU.m_nonStandardControl.GetSize(); ++i) {
812                         const H225_NonStandardParameter &np = uuPDU.m_nonStandardControl[i];
813                         const H225_NonStandardIdentifier &id = np.m_nonStandardIdentifier;
814                         if (id.GetTag() == H225_NonStandardIdentifier::e_h221NonStandard) {
815                                 const H225_H221NonStandard &ni = id;
816                                 /* Check for Cisco */
817                                 if ((ni.m_t35CountryCode == 181) && (ni.m_t35Extension == 0) && (ni.m_manufacturerCode == 18)) {
818                                         const PBYTEArray &data = np.m_data;
819                                         if (h323debug)
820                                                 cout << setprecision(0) << "Received non-standard Cisco extension data " << np.m_data << endl;
821                                         CISCO_H225_H323_UU_NonStdInfo c;
822                                         PPER_Stream strm(data);
823                                         if (c.Decode(strm)) {
824                                                 BOOL haveIEs = FALSE;
825                                                 if (h323debug)
826                                                         cout << setprecision(0) << "H323_UU_NonStdInfo = " << c << endl;
827                                                 if (c.HasOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_protoParam)) {
828                                                         FetchInformationElements(q931, c.m_protoParam.m_qsigNonStdInfo.m_rawMesg);
829                                                         haveIEs = TRUE;
830                                                 }
831                                                 if (c.HasOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_commonParam)) {
832                                                         FetchInformationElements(q931, c.m_commonParam.m_redirectIEinfo.m_redirectIE);
833                                                         haveIEs = TRUE;
834                                                 }
835                                                 if (haveIEs && h323debug)
836                                                         cout << setprecision(0) << "Information elements collected:" << q931 << endl;
837                                                 res = TRUE;
838                                         } else {
839                                                 cout << "ERROR while decoding non-standard Cisco extension" << endl;
840                                                 return FALSE;
841                                         }
842                                 }
843                         }
844                 }
845         }
846         return res;
847 }
848
849 static BOOL EmbedCiscoTunneledInfo(H323SignalPDU &pdu)
850 {
851         const static Q931::InformationElementCodes codes[] =
852         { Q931::RedirectingNumberIE, Q931::FacilityIE };
853
854         BOOL res = FALSE;
855         BOOL notRedirOnly = FALSE;
856         Q931 tmpQ931;
857         Q931 &q931 = pdu.GetQ931();
858
859         for(unsigned i = 0; i < (sizeof(codes) / sizeof(codes[0])); ++i) {
860                 if (q931.HasIE(codes[i])) {
861                         tmpQ931.SetIE(codes[i], q931.GetIE(codes[i]));
862                         q931.RemoveIE(codes[i]);
863                         if (codes[i] != Q931::RedirectingNumberIE)
864                                 notRedirOnly = TRUE;
865                         res = TRUE;
866                 }
867         }
868         /* Have something to embed */
869         if (res) {
870                 PBYTEArray msg;
871                 if (!tmpQ931.Encode(msg))
872                         return FALSE;
873                 PBYTEArray ies(msg.GetPointer() + 5, msg.GetSize() - 5);
874
875                 H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
876                 if(!uuPDU.HasOptionalField(H225_H323_UU_PDU::e_nonStandardControl)) {
877                         uuPDU.IncludeOptionalField(H225_H323_UU_PDU::e_nonStandardControl);
878                         uuPDU.m_nonStandardControl.SetSize(0);
879                 }
880                 H225_NonStandardParameter *np = new H225_NonStandardParameter;
881                 uuPDU.m_nonStandardControl.Append(np);
882                 H225_NonStandardIdentifier &nsi = (*np).m_nonStandardIdentifier;
883                 nsi.SetTag(H225_NonStandardIdentifier::e_h221NonStandard);
884                 H225_H221NonStandard &ns = nsi;
885                 ns.m_t35CountryCode = 181;
886                 ns.m_t35Extension = 0;
887                 ns.m_manufacturerCode = 18;
888
889                 CISCO_H225_H323_UU_NonStdInfo c;
890                 c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_version);
891                 c.m_version = 0;
892
893                 if (notRedirOnly) {
894                         c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_protoParam);
895                         CISCO_H225_QsigNonStdInfo &qsigInfo = c.m_protoParam.m_qsigNonStdInfo;
896                         qsigInfo.m_iei = ies[0];
897                         qsigInfo.m_rawMesg = ies;
898                 } else {
899                         c.IncludeOptionalField(CISCO_H225_H323_UU_NonStdInfo::e_commonParam);
900                         c.m_commonParam.m_redirectIEinfo.m_redirectIE = ies;
901                 }
902                 PPER_Stream stream;
903                 c.Encode(stream);
904                 stream.CompleteEncoding();
905                 (*np).m_data = stream;
906         }
907         return res;
908 }
909
910 static const char OID_QSIG[] = "1.3.12.9";
911
912 static BOOL FetchQSIGTunneledInfo(Q931 &q931, const H323SignalPDU &pdu)
913 {
914         BOOL res = FALSE;
915         const H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
916         if (uuPDU.HasOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage)) {
917                 const H225_H323_UU_PDU_tunnelledSignallingMessage &sig = uuPDU.m_tunnelledSignallingMessage;
918                 const H225_TunnelledProtocol_id &proto = sig.m_tunnelledProtocolID.m_id;
919                 if ((proto.GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
920                                 (((const PASN_ObjectId &)proto).AsString() == OID_QSIG)) {
921                         const H225_ArrayOf_PASN_OctetString &sigs = sig.m_messageContent;
922                         for(int i = 0; i < sigs.GetSize(); ++i) {
923                                 const PASN_OctetString &msg = sigs[i];
924                                 if (h323debug)
925                                         cout << setprecision(0) << "Q.931 message data is " << msg << endl;
926                                 if(!q931.Decode((const PBYTEArray &)msg)) {
927                                         cout << "Error while decoding Q.931 message" << endl;
928                                         return FALSE;
929                                 }
930                                 res = TRUE;
931                                 if (h323debug)
932                                         cout << setprecision(0) << "Received QSIG message " << q931 << endl;
933                         }
934                 }
935         }
936         return res;
937 }
938
939 static H225_EndpointType *GetEndpointType(H323SignalPDU &pdu)
940 {
941         if (!pdu.GetQ931().HasIE(Q931::UserUserIE))
942                 return NULL;
943
944         H225_H323_UU_PDU_h323_message_body &body = pdu.m_h323_uu_pdu.m_h323_message_body;
945         switch (body.GetTag()) {
946         case H225_H323_UU_PDU_h323_message_body::e_setup:
947                 return &((H225_Setup_UUIE &)body).m_sourceInfo;
948         case H225_H323_UU_PDU_h323_message_body::e_callProceeding:
949                 return &((H225_CallProceeding_UUIE &)body).m_destinationInfo;
950         case H225_H323_UU_PDU_h323_message_body::e_connect:
951                 return &((H225_Connect_UUIE &)body).m_destinationInfo;
952         case H225_H323_UU_PDU_h323_message_body::e_alerting:
953                 return &((H225_Alerting_UUIE &)body).m_destinationInfo;
954         case H225_H323_UU_PDU_h323_message_body::e_facility:
955                 return &((H225_Facility_UUIE &)body).m_destinationInfo;
956         case H225_H323_UU_PDU_h323_message_body::e_progress:
957                 return &((H225_Progress_UUIE &)body).m_destinationInfo;
958         }
959         return NULL;
960 }
961
962 static BOOL QSIGTunnelRequested(H323SignalPDU &pdu)
963 {
964         H225_EndpointType *epType = GetEndpointType(pdu);
965         if (epType) {
966                 if (!(*epType).HasOptionalField(H225_EndpointType::e_supportedTunnelledProtocols)) {
967                         return FALSE;
968                 }
969                 H225_ArrayOf_TunnelledProtocol &protos = (*epType).m_supportedTunnelledProtocols;
970                 for (int i = 0; i < protos.GetSize(); ++i)
971                 {
972                         if ((protos[i].GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
973                                         (((const PASN_ObjectId &)protos[i]).AsString() == OID_QSIG)) {
974                                 return TRUE;
975                         }
976                 }
977         }
978         return FALSE;
979 }
980
981 static BOOL EmbedQSIGTunneledInfo(H323SignalPDU &pdu)
982 {
983         const static Q931::InformationElementCodes codes[] =
984         { Q931::RedirectingNumberIE, Q931::FacilityIE };
985
986         Q931 &q931 = pdu.GetQ931();
987         PBYTEArray message;
988
989         q931.Encode(message);
990
991         /* Remove non-standard IEs */
992         for(unsigned i = 0; i < (sizeof(codes) / sizeof(codes[0])); ++i) {
993                 if (q931.HasIE(codes[i])) {
994                         q931.RemoveIE(codes[i]);
995                 }
996         }
997
998         H225_H323_UU_PDU &uuPDU = pdu.m_h323_uu_pdu;
999         H225_EndpointType *epType = GetEndpointType(pdu);
1000         if (epType) {
1001                 if (!(*epType).HasOptionalField(H225_EndpointType::e_supportedTunnelledProtocols)) {
1002                         (*epType).IncludeOptionalField(H225_EndpointType::e_supportedTunnelledProtocols);
1003                         (*epType).m_supportedTunnelledProtocols.SetSize(0);
1004                 }
1005                 H225_ArrayOf_TunnelledProtocol &protos = (*epType).m_supportedTunnelledProtocols;
1006                 BOOL addQSIG = TRUE;
1007                 for (int i = 0; i < protos.GetSize(); ++i)
1008                 {
1009                         if ((protos[i].GetTag() == H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) &&
1010                                         (((const PASN_ObjectId &)protos[i]).AsString() == OID_QSIG)) {
1011                                 addQSIG = FALSE;
1012                                 break;
1013                         }
1014                 }
1015                 if (addQSIG) {
1016                         H225_TunnelledProtocol *proto = new H225_TunnelledProtocol;
1017                         (*proto).m_id.SetTag(H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID);
1018                         (PASN_ObjectId &)(proto->m_id) = OID_QSIG;
1019                         protos.Append(proto);
1020                 }
1021         }
1022         if (!uuPDU.HasOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage))
1023                 uuPDU.IncludeOptionalField(H225_H323_UU_PDU::e_tunnelledSignallingMessage);
1024         H225_H323_UU_PDU_tunnelledSignallingMessage &sig = uuPDU.m_tunnelledSignallingMessage;
1025         H225_TunnelledProtocol_id &proto = sig.m_tunnelledProtocolID.m_id;
1026         if ((proto.GetTag() != H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID) ||
1027                         (((const PASN_ObjectId &)proto).AsString() != OID_QSIG)) {
1028                 proto.SetTag(H225_TunnelledProtocol_id::e_tunnelledProtocolObjectID);
1029                 (PASN_ObjectId &)proto = OID_QSIG;
1030                 sig.m_messageContent.SetSize(0);
1031         }
1032         PASN_OctetString *msg = new PASN_OctetString;
1033         sig.m_messageContent.Append(msg);
1034         *msg = message;
1035         return TRUE;
1036 }
1037
1038 BOOL MyH323Connection::EmbedTunneledInfo(H323SignalPDU &pdu)
1039 {
1040         if ((tunnelOptions & H323_TUNNEL_QSIG) || (remoteTunnelOptions & H323_TUNNEL_QSIG))
1041                 EmbedQSIGTunneledInfo(pdu);
1042         if ((tunnelOptions & H323_TUNNEL_CISCO) || (remoteTunnelOptions & H323_TUNNEL_CISCO))
1043                 EmbedCiscoTunneledInfo(pdu);
1044
1045         return TRUE;
1046 }
1047
1048 /* Handle tunneled messages */
1049 BOOL MyH323Connection::HandleSignalPDU(H323SignalPDU &pdu)
1050 {
1051         if (pdu.GetQ931().HasIE(Q931::UserUserIE)) {
1052                 Q931 tunneledInfo;
1053                 const Q931 *q931Info;
1054
1055                 q931Info = NULL;
1056                 if (FetchCiscoTunneledInfo(tunneledInfo, pdu)) {
1057                         q931Info = &tunneledInfo;
1058                         remoteTunnelOptions |= H323_TUNNEL_CISCO;
1059                 }
1060                 if (FetchQSIGTunneledInfo(tunneledInfo, pdu)) {
1061                         q931Info = &tunneledInfo;
1062                         remoteTunnelOptions |= H323_TUNNEL_QSIG;
1063                 }
1064                 if (!(remoteTunnelOptions & H323_TUNNEL_QSIG) && QSIGTunnelRequested(pdu)) {
1065                         remoteTunnelOptions |= H323_TUNNEL_QSIG;
1066                 }
1067                 if (q931Info) {
1068                         if (q931Info->HasIE(Q931::RedirectingNumberIE)) {
1069                                 pdu.GetQ931().SetIE(Q931::RedirectingNumberIE, q931Info->GetIE(Q931::RedirectingNumberIE));
1070                                 if (h323debug) {
1071                                         PString number;
1072                                         unsigned reason;
1073                                         if(q931Info->GetRedirectingNumber(number, NULL, NULL, NULL, NULL, &reason, 0, 0, 0))
1074                                                 cout << "Got redirection from " << number << ", reason " << reason << endl;
1075                                 }
1076                         }
1077                 }
1078         }
1079
1080         return H323Connection::HandleSignalPDU(pdu);
1081 }
1082 #endif
1083
1084 BOOL MyH323Connection::OnReceivedSignalSetup(const H323SignalPDU & setupPDU)
1085 {
1086         call_details_t cd;
1087
1088         if (h323debug) {
1089                 cout << "\t--Received SETUP message" << endl;
1090         }
1091
1092         if (connectionState == ShuttingDownConnection)
1093                 return FALSE;
1094
1095         SetCallDetails(&cd, setupPDU, TRUE);
1096
1097         /* Notify Asterisk of the request */
1098         call_options_t *res = on_incoming_call(&cd);
1099
1100         if (!res) {
1101                 if (h323debug) {
1102                         cout << "\t-- Call Failed" << endl;
1103                 }
1104                 return FALSE;
1105         }
1106
1107         SetCallOptions(res, TRUE);
1108
1109         /* Disable fastStart if requested by remote side */
1110         if (h245Tunneling && !setupPDU.m_h323_uu_pdu.m_h245Tunneling) {
1111                 masterSlaveDeterminationProcedure->Stop();
1112                 capabilityExchangeProcedure->Stop();
1113                 PTRACE(3, "H225\tFast Start DISABLED!");
1114                 h245Tunneling = FALSE;
1115         }
1116
1117         return H323Connection::OnReceivedSignalSetup(setupPDU);
1118 }
1119
1120 BOOL MyH323Connection::OnSendSignalSetup(H323SignalPDU & setupPDU)
1121 {
1122         call_details_t cd;
1123
1124         if (h323debug) {
1125                 cout << "\t-- Sending SETUP message" << endl;
1126         }
1127
1128         if (connectionState == ShuttingDownConnection)
1129                 return FALSE;
1130
1131         if (progressSetup)
1132                 setupPDU.GetQ931().SetProgressIndicator(progressSetup);
1133
1134         if (redirect_reason >= 0) {
1135                 setupPDU.GetQ931().SetRedirectingNumber(rdnis, 0, 0, 0, 0, redirect_reason);
1136                 /* OpenH323 incorrectly fills number IE when redirecting reason is specified - fix it */
1137                 PBYTEArray IE(setupPDU.GetQ931().GetIE(Q931::RedirectingNumberIE));
1138                 IE[0] = IE[0] & 0x7f;
1139                 IE[1] = IE[1] & 0x7f;
1140                 setupPDU.GetQ931().SetIE(Q931::RedirectingNumberIE, IE);
1141         }
1142
1143         SetCallDetails(&cd, setupPDU, FALSE);
1144
1145         int res = on_outgoing_call(&cd);
1146         if (!res) {
1147                 if (h323debug) {
1148                         cout << "\t-- Call Failed" << endl;
1149                 }
1150                 return FALSE;
1151         }
1152
1153 #ifdef TUNNELLING
1154         EmbedTunneledInfo(setupPDU);
1155 #endif
1156
1157         return H323Connection::OnSendSignalSetup(setupPDU);
1158 }
1159
1160 BOOL MyH323Connection::OnSendReleaseComplete(H323SignalPDU & releaseCompletePDU)
1161 {
1162         if (h323debug) {
1163                 cout << "\t-- Sending RELEASE COMPLETE" << endl;
1164         }
1165         if (cause > 0)
1166                 releaseCompletePDU.GetQ931().SetCause((Q931::CauseValues)cause);
1167
1168 #ifdef TUNNELLING
1169         EmbedTunneledInfo(releaseCompletePDU);
1170 #endif
1171
1172         return H323Connection::OnSendReleaseComplete(releaseCompletePDU);
1173 }
1174
1175 BOOL MyH323Connection::OnReceivedFacility(const H323SignalPDU & pdu)
1176 {
1177         if (h323debug) {
1178                 cout << "\t-- Received Facility message... " << endl;
1179         }
1180         return H323Connection::OnReceivedFacility(pdu);
1181 }
1182
1183 void MyH323Connection::OnReceivedReleaseComplete(const H323SignalPDU & pdu)
1184 {
1185         if (h323debug) {
1186                 cout << "\t-- Received RELEASE COMPLETE message..." << endl;
1187         }
1188         if (on_hangup)
1189                 on_hangup(GetCallReference(), (const char *)GetCallToken(), pdu.GetQ931().GetCause());
1190         return H323Connection::OnReceivedReleaseComplete(pdu);
1191 }
1192
1193 BOOL MyH323Connection::OnClosingLogicalChannel(H323Channel & channel)
1194 {
1195         if (h323debug) {
1196                 cout << "\t-- Closing logical channel..." << endl;
1197         }
1198         return H323Connection::OnClosingLogicalChannel(channel);
1199 }
1200
1201 void MyH323Connection::SendUserInputTone(char tone, unsigned duration, unsigned logicalChannel, unsigned rtpTimestamp)
1202 {
1203         SendUserInputModes mode = GetRealSendUserInputMode();
1204 //      That is recursive call... Why?
1205 //      on_receive_digit(GetCallReference(), tone, (const char *)GetCallToken());
1206         if ((tone != ' ') || (mode == SendUserInputAsTone) || (mode == SendUserInputAsInlineRFC2833)) {
1207                 if (h323debug) {
1208                         cout << "\t-- Sending user input tone (" << tone << ") to remote" << endl;
1209                 }
1210                 H323Connection::SendUserInputTone(tone, duration);
1211         }
1212 }
1213
1214 void MyH323Connection::OnUserInputTone(char tone, unsigned duration, unsigned logicalChannel, unsigned rtpTimestamp)
1215 {
1216         if ((dtmfMode & H323_DTMF_RFC2833)) {
1217                 if (h323debug) {
1218                         cout << "\t-- Received user input tone (" << tone << ") from remote" << endl;
1219                 }
1220                 on_receive_digit(GetCallReference(), tone, (const char *)GetCallToken(), duration);
1221         }
1222 }
1223
1224 void MyH323Connection::OnUserInputString(const PString &value)
1225 {
1226         if (h323debug) {
1227                 cout << "\t-- Received user input string (" << value << ") from remote." << endl;
1228         }
1229         on_receive_digit(GetCallReference(), value[0], (const char *)GetCallToken(), 0);
1230 }
1231
1232 void MyH323Connection::OnSendCapabilitySet(H245_TerminalCapabilitySet & pdu)
1233 {
1234         PINDEX i;
1235
1236         H323Connection::OnSendCapabilitySet(pdu);
1237
1238         H245_ArrayOf_CapabilityTableEntry & tables = pdu.m_capabilityTable;
1239         for(i = 0; i < tables.GetSize(); i++)
1240         {
1241                 H245_CapabilityTableEntry & entry = tables[i];
1242                 if (entry.HasOptionalField(H245_CapabilityTableEntry::e_capability)) {
1243                         H245_Capability & cap = entry.m_capability;
1244                         if (cap.GetTag() == H245_Capability::e_receiveRTPAudioTelephonyEventCapability) {
1245                                 H245_AudioTelephonyEventCapability & atec = cap;
1246                                 atec.m_dynamicRTPPayloadType = dtmfCodec;
1247 //                              on_set_rfc2833_payload(GetCallReference(), (const char *)GetCallToken(), (int)dtmfCodec);
1248                                 if (h323debug) {
1249                                         cout << "\t-- Transmitting RFC2833 on payload " <<
1250                                                 atec.m_dynamicRTPPayloadType << endl;
1251                                 }
1252                         }
1253                 }
1254         }
1255 }
1256
1257 void MyH323Connection::OnSetLocalCapabilities()
1258 {
1259         if (on_setcapabilities)
1260                 on_setcapabilities(GetCallReference(), (const char *)callToken);
1261 }
1262
1263 BOOL MyH323Connection::OnReceivedCapabilitySet(const H323Capabilities & remoteCaps,
1264                                                         const H245_MultiplexCapability * muxCap,
1265                                                         H245_TerminalCapabilitySetReject & reject)
1266 {
1267         struct __codec__ {
1268                 unsigned int asterisk_codec;
1269                 unsigned int h245_cap;
1270                 const char *oid;
1271                 const char *formatName;
1272         };
1273         static const struct __codec__ codecs[] = {
1274                 { AST_FORMAT_G723_1, H245_AudioCapability::e_g7231 },
1275                 { AST_FORMAT_GSM, H245_AudioCapability::e_gsmFullRate },
1276                 { AST_FORMAT_ULAW, H245_AudioCapability::e_g711Ulaw64k },
1277                 { AST_FORMAT_ALAW, H245_AudioCapability::e_g711Alaw64k },
1278                 { AST_FORMAT_G729A, H245_AudioCapability::e_g729AnnexA },
1279                 { AST_FORMAT_G729A, H245_AudioCapability::e_g729 },
1280                 { AST_FORMAT_G726_AAL2, H245_AudioCapability::e_nonStandard, NULL, CISCO_G726r32 },
1281 #ifdef AST_FORMAT_MODEM
1282                 { AST_FORMAT_MODEM, H245_DataApplicationCapability_application::e_t38fax },
1283 #endif
1284                 { 0 }
1285         };
1286
1287 #if 0
1288         static const struct __codec__ vcodecs[] = {
1289 #ifdef HAVE_H261
1290                 { AST_FORMAT_H261, H245_VideoCapability::e_h261VideoCapability },
1291 #endif
1292 #ifdef HAVE_H263
1293                 { AST_FORMAT_H263, H245_VideoCapability::e_h263VideoCapability },
1294 #endif
1295 #ifdef HAVE_H264
1296                 { AST_FORMAT_H264, H245_VideoCapability::e_genericVideoCapability, "0.0.8.241.0.0.1" },
1297 #endif
1298                 { 0 }
1299         };
1300 #endif
1301         struct ast_codec_pref prefs;
1302
1303         if (!H323Connection::OnReceivedCapabilitySet(remoteCaps, muxCap, reject)) {
1304                 return FALSE;
1305         }
1306
1307         const H323Capability * cap = remoteCaps.FindCapability(H323_UserInputCapability::SubTypeNames[H323_UserInputCapability::SignalToneRFC2833]);
1308         if (cap != NULL) {
1309                 RTP_DataFrame::PayloadTypes pt = ((H323_UserInputCapability*)cap)->GetPayloadType();
1310                 on_set_rfc2833_payload(GetCallReference(), (const char *)GetCallToken(), (int)pt);
1311                 if ((dtmfMode & H323_DTMF_RFC2833) && (sendUserInputMode == SendUserInputAsTone))
1312                         sendUserInputMode = SendUserInputAsInlineRFC2833;
1313                 if (h323debug) {
1314                         cout << "\t-- Inbound RFC2833 on payload " << pt << endl;
1315                 }
1316         }
1317         memset(&prefs, 0, sizeof(prefs));
1318         int peer_capabilities = 0;
1319         for (int i = 0; i < remoteCapabilities.GetSize(); ++i) {
1320                 unsigned int subType = remoteCapabilities[i].GetSubType();
1321                 if (h323debug) {
1322                         cout << "Peer capability is " << remoteCapabilities[i] << endl;
1323                 }
1324                 switch(remoteCapabilities[i].GetMainType()) {
1325                 case H323Capability::e_Audio:
1326                         for (int x = 0; codecs[x].asterisk_codec > 0; ++x) {
1327                                 if ((subType == codecs[x].h245_cap) && (!codecs[x].formatName || (!strcmp(codecs[x].formatName, (const char *)remoteCapabilities[i].GetFormatName())))) {
1328                                         int ast_codec = codecs[x].asterisk_codec;
1329                                         int ms = 0;
1330                                         if (!(peer_capabilities & ast_codec)) {
1331                                                 struct ast_format_list format;
1332                                                 ast_codec_pref_append(&prefs, ast_codec);
1333                                                 format = ast_codec_pref_getsize(&prefs, ast_codec);
1334                                                 if ((ast_codec == AST_FORMAT_ALAW) || (ast_codec == AST_FORMAT_ULAW)) {
1335                                                         ms = remoteCapabilities[i].GetTxFramesInPacket();
1336                                                         if (ms > 60)
1337                                                                 ms = format.cur_ms;
1338                                                 } else
1339                                                         ms = remoteCapabilities[i].GetTxFramesInPacket() * format.inc_ms;
1340                                                 ast_codec_pref_setsize(&prefs, ast_codec, ms);
1341                                         }
1342                                         if (h323debug) {
1343                                                 cout << "Found peer capability " << remoteCapabilities[i] << ", Asterisk code is " << ast_codec << ", frame size (in ms) is " << ms << endl;
1344                                         }
1345                                         peer_capabilities |= ast_codec;
1346                                 }
1347                         }
1348                         break;
1349 #if 0
1350                 case H323Capability::e_Video:
1351                         for (int x = 0; vcodecs[x].asterisk_codec > 0; ++x) {
1352                                 if (subType == vcodecs[x].h245_cap) {
1353                                         H245_CapabilityIdentifier *cap = NULL;
1354                                         H245_GenericCapability y;
1355                                         if (vcodecs[x].oid) {
1356                                                 cap = new H245_CapabilityIdentifier(H245_CapabilityIdentifier::e_standard);
1357                                                 PASN_ObjectId &object_id = *cap;
1358                                                 object_id = vcodecs[x].oid;
1359                                                 y.m_capabilityIdentifier = *cap;
1360                                         }
1361                                         if ((subType != H245_VideoCapability::e_genericVideoCapability) ||
1362                                                         (vcodecs[x].oid && ((const H323GenericVideoCapability &)remoteCapabilities[i]).IsGenericMatch((const H245_GenericCapability)y))) {
1363                                                 if (h323debug) {
1364                                                         cout << "Found peer video capability " << remoteCapabilities[i] << ", Asterisk code is " << vcodecs[x].asterisk_codec << endl;
1365                                                 }
1366                                                 peer_capabilities |= vcodecs[x].asterisk_codec;
1367                                         }
1368                                         if (cap)
1369                                                 delete(cap);
1370                                 }
1371                         }
1372                         break;
1373 #endif
1374                 default:
1375                         break;
1376                 }
1377         }
1378         if (h323debug) {
1379                 char caps_str[1024], caps2_str[1024];
1380                 ast_codec_pref_string(&prefs, caps2_str, sizeof(caps2_str));
1381                 cout << "Peer capabilities = " << ast_getformatname_multiple(caps_str, sizeof(caps_str), peer_capabilities)
1382                                 << ", ordered list is " << caps2_str << endl;
1383         }
1384 #if 0
1385         redir_capabilities &= peer_capabilities;
1386 #endif
1387         if (on_setpeercapabilities)
1388                 on_setpeercapabilities(GetCallReference(), (const char *)callToken, peer_capabilities, &prefs);
1389
1390         return TRUE;
1391 }
1392
1393 H323Channel * MyH323Connection::CreateRealTimeLogicalChannel(const H323Capability & capability,
1394                                                                         H323Channel::Directions dir,
1395                                                                         unsigned sessionID,
1396                                                                         const H245_H2250LogicalChannelParameters * /*param*/,
1397                                                                         RTP_QOS * /*param*/ )
1398 {
1399         return new MyH323_ExternalRTPChannel(*this, capability, dir, sessionID);
1400 }
1401
1402 /** This callback function is invoked once upon creation of each
1403   * channel for an H323 session
1404   */
1405 BOOL MyH323Connection::OnStartLogicalChannel(H323Channel & channel)
1406 {
1407         /* Increase the count of channels we have open */
1408         channelsOpen++;
1409
1410         if (h323debug) {
1411                 cout << "\t-- Started logical channel: "
1412                                 << ((channel.GetDirection() == H323Channel::IsTransmitter) ? "sending " : ((channel.GetDirection() == H323Channel::IsReceiver) ? "receiving " : " "))
1413                                 << (const char *)(channel.GetCapability()).GetFormatName() << endl;
1414                 cout << "\t\t-- channelsOpen = " << channelsOpen << endl;
1415         }
1416         return connectionState != ShuttingDownConnection;
1417 }
1418
1419 void MyH323Connection::SetCapabilities(int cap, int dtmf_mode, void *_prefs, int pref_codec)
1420 {
1421         PINDEX lastcap = -1; /* last common capability index */
1422         int alreadysent = 0;
1423         int codec;
1424         int x, y;
1425         char caps_str[1024];
1426         struct ast_codec_pref *prefs = (struct ast_codec_pref *)_prefs;
1427         struct ast_format_list format;
1428         int frames_per_packet;
1429         int max_frames_per_packet;
1430
1431         localCapabilities.RemoveAll();
1432
1433         if (h323debug) {
1434                 cout << "Setting capabilities to " << ast_getformatname_multiple(caps_str, sizeof(caps_str), cap) << endl;
1435                 ast_codec_pref_string(prefs, caps_str, sizeof(caps_str));
1436                 cout << "Capabilities in preference order is " << caps_str << endl;
1437         }
1438         /* Add audio codecs in preference order first, then
1439            audio codecs without preference as allowed by mask */
1440         for (y = 0, x = -1; x < 32 + 32; ++x) {
1441                 if (x < 0)
1442                         codec = pref_codec;
1443                 else if (y || (!(codec = ast_codec_pref_index(prefs, x)))) {
1444                         if (!y)
1445                                 y = 1;
1446                         else if (y == AST_FORMAT_MAX_AUDIO)
1447                                 break;
1448                         else
1449                                 y <<= 1;
1450                         codec = y;
1451                 }
1452                 if (!(cap & codec) || (alreadysent & codec) || !(codec & AST_FORMAT_AUDIO_MASK))
1453                         continue;
1454                 alreadysent |= codec;
1455                 format = ast_codec_pref_getsize(prefs, codec);
1456                 frames_per_packet = (format.inc_ms ? format.cur_ms / format.inc_ms : format.cur_ms);
1457                 max_frames_per_packet = (format.inc_ms ? format.max_ms / format.inc_ms : 0);
1458                 switch(codec) {
1459 #if 0
1460                 case AST_FORMAT_SPEEX:
1461                         /* Not real sure if Asterisk acutally supports all
1462                            of the various different bit rates so add them
1463                            all and figure it out later*/
1464
1465                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow2AudioCapability());
1466                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow3AudioCapability());
1467                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow4AudioCapability());
1468                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow5AudioCapability());
1469                         lastcap = localCapabilities.SetCapability(0, 0, new SpeexNarrow6AudioCapability());
1470                         break;
1471 #endif
1472                 case AST_FORMAT_G729A:
1473                         AST_G729ACapability *g729aCap;
1474                         AST_G729Capability *g729Cap;
1475                         lastcap = localCapabilities.SetCapability(0, 0, g729aCap = new AST_G729ACapability(frames_per_packet));
1476                         lastcap = localCapabilities.SetCapability(0, 0, g729Cap = new AST_G729Capability(frames_per_packet));
1477                         if (max_frames_per_packet) {
1478                                 g729aCap->SetTxFramesInPacket(max_frames_per_packet);
1479                                 g729Cap->SetTxFramesInPacket(max_frames_per_packet);
1480                         }
1481                         break;
1482                 case AST_FORMAT_G723_1:
1483                         AST_G7231Capability *g7231Cap;
1484                         lastcap = localCapabilities.SetCapability(0, 0, g7231Cap = new AST_G7231Capability(frames_per_packet, TRUE));
1485                         if (max_frames_per_packet)
1486                                 g7231Cap->SetTxFramesInPacket(max_frames_per_packet);
1487                         lastcap = localCapabilities.SetCapability(0, 0, g7231Cap = new AST_G7231Capability(frames_per_packet, FALSE));
1488                         if (max_frames_per_packet)
1489                                 g7231Cap->SetTxFramesInPacket(max_frames_per_packet);
1490                         break;
1491                 case AST_FORMAT_GSM:
1492                         AST_GSM0610Capability *gsmCap;
1493                         lastcap = localCapabilities.SetCapability(0, 0, gsmCap = new AST_GSM0610Capability(frames_per_packet));
1494                         if (max_frames_per_packet)
1495                                 gsmCap->SetTxFramesInPacket(max_frames_per_packet);
1496                         break;
1497                 case AST_FORMAT_ULAW:
1498                         AST_G711Capability *g711uCap;
1499                         lastcap = localCapabilities.SetCapability(0, 0, g711uCap = new AST_G711Capability(format.cur_ms, H323_G711Capability::muLaw));
1500                         if (format.max_ms)
1501                                 g711uCap->SetTxFramesInPacket(format.max_ms);
1502                         break;
1503                 case AST_FORMAT_ALAW:
1504                         AST_G711Capability *g711aCap;
1505                         lastcap = localCapabilities.SetCapability(0, 0, g711aCap = new AST_G711Capability(format.cur_ms, H323_G711Capability::ALaw));
1506                         if (format.max_ms)
1507                                 g711aCap->SetTxFramesInPacket(format.max_ms);
1508                         break;
1509                 case AST_FORMAT_G726_AAL2:
1510                         AST_CiscoG726Capability *g726Cap;
1511                         lastcap = localCapabilities.SetCapability(0, 0, g726Cap = new AST_CiscoG726Capability(frames_per_packet));
1512                         if (max_frames_per_packet)
1513                                 g726Cap->SetTxFramesInPacket(max_frames_per_packet);
1514                         break;
1515                 default:
1516                         alreadysent &= ~codec;
1517                         break;
1518                 }
1519         }
1520
1521         lastcap++;
1522         lastcap = localCapabilities.SetCapability(0, lastcap, new H323_UserInputCapability(H323_UserInputCapability::HookFlashH245));
1523
1524         lastcap++;
1525         dtmfMode = dtmf_mode;
1526         if ((dtmfMode & H323_DTMF_INBAND)) {
1527                 localCapabilities.SetCapability(0, lastcap, new H323_UserInputCapability(H323_UserInputCapability::BasicString));
1528                 sendUserInputMode = SendUserInputAsString;
1529         } else {
1530                 lastcap = localCapabilities.SetCapability(0, lastcap, new H323_UserInputCapability(H323_UserInputCapability::SignalToneRFC2833));
1531                 /* Cisco sends DTMF only through h245-alphanumeric or h245-signal, no support for RFC2833 */
1532                 lastcap = localCapabilities.SetCapability(0, lastcap, new H323_UserInputCapability(H323_UserInputCapability::SignalToneH245));
1533                 sendUserInputMode = SendUserInputAsTone;        /* RFC2833 transmission handled at Asterisk level */
1534         }
1535
1536         if (h323debug) {
1537                 cout << "Allowed Codecs:\n\t" << setprecision(2) << localCapabilities << endl;
1538         }
1539 }
1540
1541 BOOL MyH323Connection::StartControlChannel(const H225_TransportAddress & h245Address)
1542 {
1543         // Check that it is an IP address, all we support at the moment
1544         if (h245Address.GetTag() != H225_TransportAddress::e_ipAddress
1545 #if P_HAS_IPV6
1546                 && h245Address.GetTag() != H225_TransportAddress::e_ip6Address
1547 #endif
1548         ) {
1549                 PTRACE(1, "H225\tConnect of H245 failed: Unsupported transport");
1550                 return FALSE;
1551         }
1552
1553         // Already have the H245 channel up.
1554         if (controlChannel != NULL)
1555                 return TRUE;
1556
1557         PIPSocket::Address addr;
1558         WORD port;
1559         GetSignallingChannel()->GetLocalAddress().GetIpAndPort(addr, port);
1560         if (addr) {
1561                 if (h323debug)
1562                         cout << "Using " << addr << " for outbound H.245 transport" << endl;
1563                 controlChannel = new MyH323TransportTCP(endpoint, addr);
1564         } else
1565                 controlChannel = new H323TransportTCP(endpoint);
1566         if (!controlChannel->SetRemoteAddress(h245Address)) {
1567                 PTRACE(1, "H225\tCould not extract H245 address");
1568                 delete controlChannel;
1569                 controlChannel = NULL;
1570                 return FALSE;
1571         }
1572         if (!controlChannel->Connect()) {
1573                 PTRACE(1, "H225\tConnect of H245 failed: " << controlChannel->GetErrorText());
1574                 delete controlChannel;
1575                 controlChannel = NULL;
1576                 return FALSE;
1577         }
1578
1579         controlChannel->StartControlChannel(*this);
1580         return TRUE;
1581 }
1582
1583 /* MyH323_ExternalRTPChannel */
1584 MyH323_ExternalRTPChannel::MyH323_ExternalRTPChannel(MyH323Connection & connection,
1585                                                         const H323Capability & capability,
1586                                                         Directions direction,
1587                                                         unsigned id)
1588         : H323_ExternalRTPChannel::H323_ExternalRTPChannel(connection, capability, direction, id)
1589 {
1590         struct rtp_info *info;
1591
1592         /* Determine the Local (A side) IP Address and port */
1593         info = on_external_rtp_create(connection.GetCallReference(), (const char *)connection.GetCallToken());
1594         if (!info) {
1595                 cout << "\tERROR: on_external_rtp_create failure" << endl;
1596                 return;
1597         } else {
1598                 localIpAddr = info->addr;
1599                 localPort = info->port;
1600                 /* tell the H.323 stack */
1601                 SetExternalAddress(H323TransportAddress(localIpAddr, localPort), H323TransportAddress(localIpAddr, localPort + 1));
1602                 /* clean up allocated memory */
1603                 free(info);
1604         }
1605
1606         /* Get the payload code */
1607         OpalMediaFormat format(capability.GetFormatName(), FALSE);
1608         payloadCode = format.GetPayloadType();
1609 }
1610
1611 MyH323_ExternalRTPChannel::~MyH323_ExternalRTPChannel()
1612 {
1613         if (h323debug) {
1614                 cout << "\tExternalRTPChannel Destroyed" << endl;
1615         }
1616 }
1617
1618 BOOL MyH323_ExternalRTPChannel::Start(void)
1619 {
1620         /* Call ancestor first */
1621         if (!H323_ExternalRTPChannel::Start()) {
1622                 return FALSE;
1623         }
1624
1625         if (h323debug) {
1626                 cout << "\t\tExternal RTP Session Starting" << endl;
1627                 cout << "\t\tRTP channel id " << sessionID << " parameters:" << endl;
1628         }
1629
1630         /* Collect the remote information */
1631         H323_ExternalRTPChannel::GetRemoteAddress(remoteIpAddr, remotePort);
1632
1633         if (h323debug) {
1634                 cout << "\t\t-- remoteIpAddress: " << remoteIpAddr << endl;
1635                 cout << "\t\t-- remotePort: " << remotePort << endl;
1636                 cout << "\t\t-- ExternalIpAddress: " << localIpAddr << endl;
1637                 cout << "\t\t-- ExternalPort: " << localPort << endl;
1638         }
1639         /* Notify Asterisk of remote RTP information */
1640         on_start_rtp_channel(connection.GetCallReference(), (const char *)remoteIpAddr.AsString(), remotePort,
1641                 (const char *)connection.GetCallToken(), (int)payloadCode);
1642         return TRUE;
1643 }
1644
1645 BOOL MyH323_ExternalRTPChannel::OnReceivedAckPDU(const H245_H2250LogicalChannelAckParameters & param)
1646 {
1647         if (h323debug) {
1648                 cout << "       MyH323_ExternalRTPChannel::OnReceivedAckPDU" << endl;
1649         }
1650
1651         if (H323_ExternalRTPChannel::OnReceivedAckPDU(param)) {
1652                 GetRemoteAddress(remoteIpAddr, remotePort);
1653                 if (h323debug) {
1654                         cout << "               -- remoteIpAddress: " << remoteIpAddr << endl;
1655                         cout << "               -- remotePort: " << remotePort << endl;
1656                 }
1657                 on_start_rtp_channel(connection.GetCallReference(), (const char *)remoteIpAddr.AsString(),
1658                                 remotePort, (const char *)connection.GetCallToken(), (int)payloadCode);
1659                 return TRUE;
1660         }
1661         return FALSE;
1662 }
1663
1664
1665 /** IMPLEMENTATION OF C FUNCTIONS */
1666
1667 /**
1668  * The extern "C" directive takes care for
1669  * the ANSI-C representation of linkable symbols
1670  */
1671
1672 extern "C" {
1673
1674 int h323_end_point_exist(void)
1675 {
1676         if (!endPoint) {
1677                 return 0;
1678         }
1679         return 1;
1680 }
1681
1682 void h323_end_point_create(void)
1683 {
1684         channelsOpen = 0;
1685         logstream = new PAsteriskLog();
1686         localProcess = new MyProcess();
1687         localProcess->Main();
1688 }
1689
1690 void h323_gk_urq(void)
1691 {
1692         if (!h323_end_point_exist()) {
1693                 cout << " ERROR: [h323_gk_urq] No Endpoint, this is bad" << endl;
1694                 return;
1695         }
1696         endPoint->RemoveGatekeeper();
1697 }
1698
1699 void h323_debug(int flag, unsigned level)
1700 {
1701         if (flag) {
1702                 PTrace:: SetLevel(level);
1703         } else {
1704                 PTrace:: SetLevel(0);
1705         }
1706 }
1707
1708 /** Installs the callback functions on behalf of the PBX application */
1709 void h323_callback_register(setup_incoming_cb           ifunc,
1710                                                         setup_outbound_cb               sfunc,
1711                                                         on_rtp_cb                               rtpfunc,
1712                                                         start_rtp_cb                    lfunc,
1713                                                         clear_con_cb                    clfunc,
1714                                                         chan_ringing_cb                 rfunc,
1715                                                         con_established_cb              efunc,
1716                                                         receive_digit_cb                dfunc,
1717                                                         answer_call_cb                  acfunc,
1718                                                         progress_cb                             pgfunc,
1719                                                         rfc2833_cb                              dtmffunc,
1720                                                         hangup_cb                               hangupfunc,
1721                                                         setcapabilities_cb              capabilityfunc,
1722                                                         setpeercapabilities_cb  peercapabilityfunc)
1723 {
1724         on_incoming_call = ifunc;
1725         on_outgoing_call = sfunc;
1726         on_external_rtp_create = rtpfunc;
1727         on_start_rtp_channel = lfunc;
1728         on_connection_cleared = clfunc;
1729         on_chan_ringing = rfunc;
1730         on_connection_established = efunc;
1731         on_receive_digit = dfunc;
1732         on_answer_call = acfunc;
1733         on_progress = pgfunc;
1734         on_set_rfc2833_payload = dtmffunc;
1735         on_hangup = hangupfunc;
1736         on_setcapabilities = capabilityfunc;
1737         on_setpeercapabilities = peercapabilityfunc;
1738 }
1739
1740 /**
1741  * Add capability to the capability table of the end point.
1742  */
1743 int h323_set_capabilities(const char *token, int cap, int dtmf_mode, struct ast_codec_pref *prefs, int pref_codec)
1744 {
1745         MyH323Connection *conn;
1746
1747         if (!h323_end_point_exist()) {
1748                 cout << " ERROR: [h323_set_capablities] No Endpoint, this is bad" << endl;
1749                 return 1;
1750         }
1751         if (!token || !*token) {
1752                 cout << " ERROR: [h323_set_capabilities] Invalid call token specified." << endl;
1753                 return 1;
1754         }
1755
1756         PString myToken(token);
1757         conn = (MyH323Connection *)endPoint->FindConnectionWithLock(myToken);
1758         if (!conn) {
1759                 cout << " ERROR: [h323_set_capabilities] Unable to find connection " << token << endl;
1760                 return 1;
1761         }
1762         conn->SetCapabilities((/*conn->bridging ? conn->redir_capabilities :*/ cap), dtmf_mode, prefs, pref_codec);
1763         conn->Unlock();
1764
1765         return 0;
1766 }
1767
1768 /** Start the H.323 listener */
1769 int h323_start_listener(int listenPort, struct sockaddr_in bindaddr)
1770 {
1771
1772         if (!h323_end_point_exist()) {
1773                 cout << "ERROR: [h323_start_listener] No Endpoint, this is bad!" << endl;
1774                 return 1;
1775         }
1776
1777         PIPSocket::Address interfaceAddress(bindaddr.sin_addr);
1778         if (!listenPort) {
1779                 listenPort = 1720;
1780         }
1781         /** H.323 listener */
1782         H323ListenerTCP *tcpListener;
1783         tcpListener = new H323ListenerTCP(*endPoint, interfaceAddress, (WORD)listenPort);
1784         if (!endPoint->StartListener(tcpListener)) {
1785                 cout << "ERROR: Could not open H.323 listener port on " << ((H323ListenerTCP *) tcpListener)->GetListenerPort() << endl;
1786                 delete tcpListener;
1787                 return 1;
1788         }
1789         cout << "  == H.323 listener started" << endl;
1790         return 0;
1791 };
1792
1793 int h323_set_alias(struct oh323_alias *alias)
1794 {
1795         char *p;
1796         char *num;
1797         PString h323id(alias->name);
1798         PString e164(alias->e164);
1799         char *prefix;
1800
1801         if (!h323_end_point_exist()) {
1802                 cout << "ERROR: [h323_set_alias] No Endpoint, this is bad!" << endl;
1803                 return 1;
1804         }
1805
1806         cout << "== Adding alias \"" << h323id << "\" to endpoint" << endl;
1807         endPoint->AddAliasName(h323id);
1808         endPoint->RemoveAliasName(localProcess->GetUserName());
1809
1810         if (!e164.IsEmpty()) {
1811                 cout << "== Adding E.164 \"" << e164 << "\" to endpoint" << endl;
1812                 endPoint->AddAliasName(e164);
1813         }
1814         if (strlen(alias->prefix)) {
1815                 p = prefix = strdup(alias->prefix);
1816                 while((num = strsep(&p, ",")) != (char *)NULL) {
1817                         cout << "== Adding Prefix \"" << num << "\" to endpoint" << endl;
1818                         endPoint->SupportedPrefixes += PString(num);
1819                         endPoint->SetGateway();
1820                 }
1821                 if (prefix)
1822                         free(prefix);
1823         }
1824         return 0;
1825 }
1826
1827 void h323_set_id(char *id)
1828 {
1829         PString h323id(id);
1830
1831         if (h323debug) {
1832                 cout << "  == Using '" << h323id << "' as our H.323ID for this call" << endl;
1833         }
1834         /* EVIL HACK */
1835         endPoint->SetLocalUserName(h323id);
1836 }
1837
1838 void h323_show_tokens(void)
1839 {
1840         cout << "Current call tokens: " << setprecision(2) << endPoint->GetAllConnections() << endl;
1841 }
1842
1843 /** Establish Gatekeeper communiations, if so configured,
1844   *     register aliases for the H.323 endpoint to respond to.
1845   */
1846 int h323_set_gk(int gatekeeper_discover, char *gatekeeper, char *secret)
1847 {
1848         PString gkName = PString(gatekeeper);
1849         PString pass = PString(secret);
1850         H323TransportUDP *rasChannel;
1851
1852         if (!h323_end_point_exist()) {
1853                 cout << "ERROR: [h323_set_gk] No Endpoint, this is bad!" << endl;
1854                 return 1;
1855         }
1856
1857         if (!gatekeeper) {
1858                 cout << "Error: Gatekeeper cannot be NULL" << endl;
1859                 return 1;
1860         }
1861         if (strlen(secret)) {
1862                 endPoint->SetGatekeeperPassword(pass);
1863         }
1864         if (gatekeeper_discover) {
1865                 /* discover the gk using multicast */
1866                 if (endPoint->DiscoverGatekeeper(new MyH323TransportUDP(*endPoint))) {
1867                         cout << "== Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
1868                 } else {
1869                         cout << "Warning: Could not find a gatekeeper." << endl;
1870                         return 1;
1871                 }
1872         } else {
1873                 rasChannel = new MyH323TransportUDP(*endPoint);
1874
1875                 if (!rasChannel) {
1876                         cout << "Error: No RAS Channel, this is bad" << endl;
1877                         return 1;
1878                 }
1879                 if (endPoint->SetGatekeeper(gkName, rasChannel)) {
1880                         cout << "== Using " << (endPoint->GetGatekeeper())->GetName() << " as our Gatekeeper." << endl;
1881                 } else {
1882                         cout << "Error registering with gatekeeper \"" << gkName << "\". " << endl;
1883                         /* XXX Maybe we should fire a new thread to attempt to re-register later and not kill asterisk here? */
1884                         return 1;
1885                 }
1886         }
1887         return 0;
1888 }
1889
1890 /** Send a DTMF tone over the H323Connection with the
1891   * specified token.
1892   */
1893 void h323_send_tone(const char *call_token, char tone)
1894 {
1895         if (!h323_end_point_exist()) {
1896                 cout << "ERROR: [h323_send_tone] No Endpoint, this is bad!" << endl;
1897                 return;
1898         }
1899         PString token = PString(call_token);
1900         endPoint->SendUserTone(token, tone);
1901 }
1902
1903 /** Make a call to the remote endpoint.
1904   */
1905 int h323_make_call(char *dest, call_details_t *cd, call_options_t *call_options)
1906 {
1907         int res;
1908         PString token;
1909         PString host(dest);
1910
1911         if (!h323_end_point_exist()) {
1912                 return 1;
1913         }
1914
1915         res = endPoint->MyMakeCall(host, token, &cd->call_reference, call_options);
1916         memcpy((char *)(cd->call_token), (const unsigned char *)token, token.GetLength());
1917         return res;
1918 };
1919
1920 int h323_clear_call(const char *call_token, int cause)
1921 {
1922         H225_ReleaseCompleteReason dummy;
1923         H323Connection::CallEndReason r = H323Connection::EndedByLocalUser;
1924         MyH323Connection *connection;
1925         const PString currentToken(call_token);
1926
1927         if (!h323_end_point_exist()) {
1928                 return 1;
1929         }
1930
1931         if (cause) {
1932                 r = H323TranslateToCallEndReason((Q931::CauseValues)(cause), dummy);
1933         }
1934
1935         connection = (MyH323Connection *)endPoint->FindConnectionWithLock(currentToken);
1936         if (connection) {
1937                 connection->SetCause(cause);
1938                 connection->SetCallEndReason(r);
1939                 connection->Unlock();
1940         }
1941         endPoint->ClearCall(currentToken, r);
1942         return 0;
1943 };
1944
1945 /* Send Alerting PDU to H.323 caller */
1946 int h323_send_alerting(const char *token)
1947 {
1948         const PString currentToken(token);
1949         H323Connection * connection;
1950
1951         if (h323debug) {
1952                 cout << "\tSending alerting" << endl;
1953         }
1954         connection = endPoint->FindConnectionWithLock(currentToken);
1955         if (!connection) {
1956                 cout << "No connection found for " << token << endl;
1957                 return -1;
1958         }
1959         connection->AnsweringCall(H323Connection::AnswerCallPending);
1960         connection->Unlock();
1961         return 0;
1962 }
1963
1964 /* Send Progress PDU to H.323 caller */
1965 int h323_send_progress(const char *token)
1966 {
1967         const PString currentToken(token);
1968         H323Connection * connection;
1969
1970         connection = endPoint->FindConnectionWithLock(currentToken);
1971         if (!connection) {
1972                 cout << "No connection found for " << token << endl;
1973                 return -1;
1974         }
1975         connection->AnsweringCall(H323Connection::AnswerCallDeferredWithMedia);
1976         connection->Unlock();
1977         return 0;
1978 }
1979
1980 /** This function tells the h.323 stack to either
1981     answer or deny an incoming call */
1982 int h323_answering_call(const char *token, int busy)
1983 {
1984         const PString currentToken(token);
1985         H323Connection * connection;
1986
1987         connection = endPoint->FindConnectionWithLock(currentToken);
1988
1989         if (!connection) {
1990                 cout << "No connection found for " << token << endl;
1991                 return -1;
1992         }
1993         if (!busy) {
1994                 if (h323debug) {
1995                         cout << "\tAnswering call " << token << endl;
1996                 }
1997                 connection->AnsweringCall(H323Connection::AnswerCallNow);
1998         } else {
1999                 if (h323debug) {
2000                         cout << "\tdenying call " << token << endl;
2001                 }
2002                 connection->AnsweringCall(H323Connection::AnswerCallDenied);
2003         }
2004         connection->Unlock();
2005         return 0;
2006 }
2007
2008 int h323_soft_hangup(const char *data)
2009 {
2010         PString token(data);
2011         BOOL result;
2012         cout << "Soft hangup" << endl;
2013         result = endPoint->ClearCall(token);
2014         return result;
2015 }
2016
2017 /* alas, this doesn't work :( */
2018 void h323_native_bridge(const char *token, const char *them, char *capability)
2019 {
2020         H323Channel *channel;
2021         MyH323Connection *connection = (MyH323Connection *)endPoint->FindConnectionWithLock(token);
2022
2023         if (!connection) {
2024                 cout << "ERROR: No connection found, this is bad" << endl;
2025                 return;
2026         }
2027
2028         cout << "Native Bridge:  them [" << them << "]" << endl;
2029
2030         channel = connection->FindChannel(connection->sessionId, TRUE);
2031         connection->bridging = TRUE;
2032         connection->CloseLogicalChannelNumber(channel->GetNumber());
2033
2034         connection->Unlock();
2035         return;
2036
2037 }
2038
2039 #undef cout
2040 #undef endl
2041 void h323_end_process(void)
2042 {
2043         if (endPoint) {
2044                 endPoint->ClearAllCalls();
2045                 endPoint->RemoveListener(NULL);
2046                 delete endPoint;
2047                 endPoint = NULL;
2048         }
2049         if (localProcess) {
2050                 delete localProcess;
2051                 localProcess = NULL;
2052                 close(_timerChangePipe[0]);
2053                 close(_timerChangePipe[1]);
2054         }
2055         if (logstream) {
2056                 PTrace::SetLevel(0);
2057                 PTrace::SetStream(&cout);
2058                 delete logstream;
2059                 logstream = NULL;
2060         }
2061 }
2062
2063 } /* extern "C" */
2064