-
Notifications
You must be signed in to change notification settings - Fork 22
/
forwarding.cxx
351 lines (320 loc) · 11.6 KB
/
forwarding.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
//////////////////////////////////////////////////////////////////
//
// Call Forwarding Poliy for GNU Gatekeeper
//
// Copyright (c) 2012-2019, Jan Willamowius
//
// This work is published under the GNU Public License version 2 (GPLv2)
// see file COPYING for details.
// We also explicitly grant the right to link this code
// with the OpenH323/H323Plus and OpenSSL library.
//
//////////////////////////////////////////////////////////////////
#include "config.h"
#include <ptlib.h>
#include <h323pdu.h>
#include "Routing.h"
#include "Toolkit.h"
#include "gksql.h"
#include "gk_const.h"
#include "h323util.h"
// forwards are handled in ascending order of their type
enum ForwardingTypes {
FORWARD_UNCONDITIONAL = 1,
FORWARD_BUSY = 2,
FORWARD_NOANSWER = 3,
FORWARD_ERROR = 4 };
const unsigned MAX_RECURSION_DEPTH = 25;
const unsigned DEFAULT_PRIORITY = 1;
const unsigned NO_ANSWER_PRIORITY = 900;
namespace Routing {
// a policy to route calls via an SQL database
class ForwardingPolicy : public DynamicPolicy {
public:
ForwardingPolicy();
virtual ~ForwardingPolicy();
protected:
virtual void LoadConfig(const PString & instance);
virtual void RunPolicy(
/*in */
const PString & source,
const PString & calledAlias,
const PString & calledIP,
const PString & caller,
const PString & callingStationId,
const PString & callid,
const PString & messageType,
const PString & clientauthid,
const PString & language,
/* out: */
DestinationRoutes & destination);
// called recursively
virtual bool FindEPForwardingRules(
/* in */
std::map<PString, PString> params,
unsigned recursionDepth,
unsigned priority,
/* out: */
DestinationRoutes & destination);
protected:
// connection to the SQL database
GkSQLConnection* m_sqlConn;
// parametrized query string for the routing query
PString m_query;
// query timeout
long m_timeout;
};
ForwardingPolicy::ForwardingPolicy()
{
m_active = false;
m_sqlConn = NULL;
m_name = "Forwarding";
m_iniSection = "Routing::Forwarding";
m_timeout = -1;
#ifndef HAS_DATABASE
PTRACE(1, m_name << " not available - no database driver compiled into GnuGk");
#endif // HAS_DATABASE
}
ForwardingPolicy::~ForwardingPolicy()
{
delete m_sqlConn;
}
void ForwardingPolicy::LoadConfig(const PString & instance)
{
#if HAS_DATABASE
const PString driverName = GkConfig()->GetString(m_iniSection, "Driver", "");
if (driverName.IsEmpty()) {
PTRACE(2, m_name << "\tmodule creation failed: no SQL driver selected");
SNMP_TRAP(4, SNMPError, Database, PString(m_name) + " creation failed");
return;
}
m_sqlConn = GkSQLConnection::Create(driverName, m_name);
if (m_sqlConn == NULL) {
PTRACE(2, m_name << "\tmodule creation failed: "
"could not find " << driverName << " database driver");
SNMP_TRAP(4, SNMPError, Database, PString(m_name) + " creation failed");
return;
}
m_query = GkConfig()->GetString(m_iniSection, "Query", "");
if (m_query.IsEmpty()) {
PTRACE(2, m_name << "\tmodule creation failed: "
"no query configured");
SNMP_TRAP(4, SNMPError, Database, PString(m_name) + " creation failed");
return;
} else
PTRACE(4, m_name << "\tQuery: " << m_query);
if (!m_sqlConn->Initialize(GkConfig(), m_iniSection)) {
PTRACE(2, m_name << "\tmodule creation failed: "
"could not connect to the database");
SNMP_TRAP(4, SNMPError, Database, PString(m_name) + " creation failed");
return;
}
m_active = true;
#endif
}
void ForwardingPolicy::RunPolicy(
/* in */
const PString & source,
const PString & calledAlias,
const PString & calledIP,
const PString & caller,
const PString & callingStationId,
const PString & callid,
const PString & messageType,
const PString & clientauthid,
const PString & language,
/* out: */
DestinationRoutes & destination)
{
#if HAS_DATABASE
std::map<PString, PString> params;
params["s"] = source;
params["c"] = calledAlias;
params["p"] = calledIP;
params["r"] = caller;
params["Calling-Station-Id"] = callingStationId;
params["i"] = callid;
params["m"] = messageType;
params["client-auth-id"] = clientauthid;
params["language"] = language;
// if IP called, check if its an internal EP and change calledAlias/calledIP
if (calledAlias.IsEmpty() && IsIPAddress(calledIP)) {
PStringArray adr_parts = calledIP.Tokenise(":", FALSE);
PIPSocket::Address ip(adr_parts[0]);
WORD port = (WORD)(adr_parts[1].AsInteger());
if (port == 0)
port = GK_DEF_ENDPOINT_SIGNAL_PORT;
endptr ep = RegistrationTable::Instance()->FindBySignalAdr(SocketToH225TransportAddr(ip, port));
if (ep) {
// call goes to an internal endpoint, use the first alias instead
H225_ArrayOf_AliasAddress aliases = ep->GetAliases();
if (aliases.GetSize() > 0) {
params["c"] = AsString(aliases[0], false);
params["p"] = "";
}
}
}
FindEPForwardingRules(params, 0, DEFAULT_PRIORITY, destination);
PTRACE(5, "Fwd\t" << destination.m_routes.size() << " routes added");
for (std::list<Route>::iterator it = destination.m_routes.begin(); it !=destination.m_routes.end(); ++it) {
PTRACE(5, "Fwd\tRoute=" << it->AsString());
}
if (destination.ChangeAliases()) {
PTRACE(5, "Fwd\tAliases changed to " << destination.GetNewAliases());
}
#endif // HAS_DATABASE
}
bool ForwardingPolicy::FindEPForwardingRules(
/* in */
std::map<PString, PString> params, // pass copies so they can be modified in recursion
unsigned recursionDepth,
unsigned priority,
/* out: */
DestinationRoutes & destination)
{
bool skipOrginalForward = false;
// make sure we don't produce infinite loops
if (recursionDepth > MAX_RECURSION_DEPTH)
return false;
#if HAS_DATABASE
GkSQLResult* result = m_sqlConn->ExecuteQuery(m_query, params, m_timeout);
if (result == NULL) {
PTRACE(2, m_name << ": query failed - timeout or fatal error");
SNMP_TRAP(5, SNMPError, Database, PString(m_name) + " query failed");
return false;
}
if (!result->IsValid()) {
PTRACE(2, m_name << ": query failed (" << result->GetErrorCode()
<< ") - " << result->GetErrorMessage());
SNMP_TRAP(5, SNMPError, Database, PString(m_name) + " query failed");
delete result;
return false;
}
if (result->GetNumRows() < 1) {
PTRACE(5, m_name << ": query returned no rows");
return false;
} else if (result->GetNumFields() != 2) {
PTRACE(2, m_name << ": bad query - didn't return 2 fields");
SNMP_TRAP(5, SNMPError, Database, PString(m_name) + " query failed");
return false;
} else {
// fetch all rows now, recursive checks will invalidate result set
std::vector<GkSQLResult::ResultRow> rows(result->GetNumRows());
for (long i = 0; i < result->GetNumRows(); ++i) {
if (!result->FetchRow(rows[i]) || rows[i].empty()) {
PTRACE(2, m_name << ": query failed - could not fetch the result row");
SNMP_TRAP(5, SNMPError, Database, PString(m_name) + " query failed");
break;
}
}
// look at all rules (ordered by forwarding type)
for (unsigned i = 0; i < rows.size(); ++i) {
unsigned forwardType = rows[i][0].first.AsInteger();
PString forwardDestination = rows[i][1].first;
PTRACE(4, "Fwd\tForward type=" << forwardType << " for call to " << params["c"] << ": new dest=" << forwardDestination);
if (forwardDestination.IsEmpty()) {
// skip rule, if forwardDestination is empty
continue;
}
if ( (forwardType == FORWARD_UNCONDITIONAL)
|| (forwardType == FORWARD_BUSY) ) {
if (IsIPAddress(forwardDestination)) {
// set a route if forward to IP
PString destinationIp = forwardDestination;
PStringArray adr_parts = destinationIp.Tokenise(":", FALSE);
PIPSocket::Address ip(adr_parts[0]);
WORD port = (WORD)(adr_parts[1].AsInteger());
if (port == 0)
port = GK_DEF_ENDPOINT_SIGNAL_PORT;
Route route("ForwardUnconditionalOrBusy", SocketToH225TransportAddr(ip, port), priority + recursionDepth);
route.m_destEndpoint = RegistrationTable::Instance()->FindBySignalAdr(route.m_destAddr);
if ((forwardType == FORWARD_UNCONDITIONAL)
|| (route.m_destEndpoint && CallTable::Instance()->FindCallRec(route.m_destEndpoint))) {
route.m_destNumber = forwardDestination;
route.m_destOutNumber = forwardDestination;
destination.AddRoute(route, false);
skipOrginalForward = true;
}
} else {
// check if we have an EPRec for the new destination (to check for current call or forwards)
H225_ArrayOf_AliasAddress called;
called.SetSize(1);
H323SetAliasAddress(params["c"], called[0]);
endptr ep = RegistrationTable::Instance()->FindByAliases(called);
if ((forwardType == FORWARD_UNCONDITIONAL)
|| (ep && CallTable::Instance()->FindCallRec(ep))) {
// check if new destination is also forwarded
params["c"] = forwardDestination;
params["p"] = "";
if (FindEPForwardingRules(params, recursionDepth+1, DEFAULT_PRIORITY, destination)) {
PTRACE(5, "Fwd\tSkipping forward to " << forwardDestination << " (also redirected uncond/busy)");
} else {
if (priority <= 1) {
// just rewrite the destination if forward to alias
H225_ArrayOf_AliasAddress newAliases;
newAliases.SetSize(1);
H323SetAliasAddress(forwardDestination, newAliases[0]);
destination.SetNewAliases(newAliases);
} else {
// replace an NoAnswer or Error forward
if (ep) {
Route route("ForwardNoAnswerOrError", ep, priority + recursionDepth);
route.m_destNumber = forwardDestination;
route.m_destOutNumber = forwardDestination;
destination.AddRoute(route, false);
} else {
PTRACE(3, "Fwd\tUnconditional Forward or on Busy to non-local or currently not registered alias " << forwardDestination);
}
}
}
skipOrginalForward = true;
}
}
} else if ((forwardType == FORWARD_NOANSWER) || (forwardType == FORWARD_ERROR)) {
if (IsIPAddress(forwardDestination)) {
// set a route if forward to IP
PString destinationIp = forwardDestination;
PStringArray adr_parts = destinationIp.Tokenise(":", FALSE);
PIPSocket::Address ip(adr_parts[0]);
WORD port = (WORD)(adr_parts[1].AsInteger());
if (port == 0)
port = GK_DEF_ENDPOINT_SIGNAL_PORT;
Route route("ForwardNoAnswerOrError", SocketToH225TransportAddr(ip, port), NO_ANSWER_PRIORITY + recursionDepth);
route.m_destNumber = forwardDestination;
route.m_destOutNumber = forwardDestination;
destination.AddRoute(route);
} else {
H225_ArrayOf_AliasAddress forwardAliases;
forwardAliases.SetSize(1);
H323SetAliasAddress(forwardDestination, forwardAliases[0]);
endptr ep = RegistrationTable::Instance()->FindByAliases(forwardAliases);
// check if destination also has uncond/busy forwarding rules
params["c"] = forwardDestination;
params["p"] = "";
if (FindEPForwardingRules(params, recursionDepth+1, NO_ANSWER_PRIORITY, destination)) {
PTRACE(5, "Fwd\tSkipping forward to " << forwardDestination << " (also redirected uncond/busy)");
} else {
if (ep) {
// add a NoAnswer route, lower recursion depth is given more priority
Route route("ForwardNoAnswerOrError", ep, NO_ANSWER_PRIORITY + recursionDepth);
route.m_destNumber = forwardDestination;
route.m_destOutNumber = forwardDestination;
destination.AddRoute(route, false);
} else {
PTRACE(3, "Fwd\tForward on NoAnswer or Error to non-local or currently not registered alias " << forwardDestination);
}
}
}
} else {
PTRACE(1, "Fwd\tUnsupported forward type " << forwardType);
}
}
}
delete result;
#endif // HAS_DATABASE
return skipOrginalForward;
}
namespace { // anonymous namespace
SimpleCreator<ForwardingPolicy> ForwardingPolicyCreator("forwarding");
}
} // end of namespace Routing