-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
app.js
245 lines (224 loc) · 7.19 KB
/
app.js
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
const assert = require('assert');
const {
JAMBONES_MYSQL_HOST,
JAMBONES_MYSQL_USER,
JAMBONES_MYSQL_PASSWORD,
JAMBONES_MYSQL_DATABASE,
JAMBONES_REDIS_SENTINEL_MASTER_NAME,
JAMBONES_REDIS_SENTINELS,
JAMBONES_REDIS_HOST,
DRACHTIO_HOST,
DRACHTIO_PORT,
DRACHTIO_SECRET,
JAMBONES_TIME_SERIES_HOST,
JAMBONES_LOGLEVEL,
JAMBONES_MYSQL_PORT,
JAMBONES_MYSQL_CONNECTION_LIMIT,
NODE_ENV,
SBC_PUBLIC_ADDRESS_KEEP_ALIVE_IN_MILISECOND
} = require('./lib/config');
assert.ok(JAMBONES_MYSQL_HOST &&
JAMBONES_MYSQL_USER &&
JAMBONES_MYSQL_PASSWORD &&
JAMBONES_MYSQL_DATABASE, 'missing JAMBONES_MYSQL_XXX env vars');
if (JAMBONES_REDIS_SENTINELS) {
assert.ok(JAMBONES_REDIS_SENTINEL_MASTER_NAME,
'missing JAMBONES_REDIS_SENTINEL_MASTER_NAME env var, JAMBONES_REDIS_SENTINEL_PASSWORD env var is optional');
} else {
assert.ok(JAMBONES_REDIS_HOST, 'missing JAMBONES_REDIS_HOST env var');
}
assert.ok(DRACHTIO_HOST, 'missing DRACHTIO_HOST env var');
assert.ok(DRACHTIO_PORT, 'missing DRACHTIO_PORT env var');
assert.ok(DRACHTIO_SECRET, 'missing DRACHTIO_SECRET env var');
assert.ok(JAMBONES_TIME_SERIES_HOST, 'missing JAMBONES_TIME_SERIES_HOST env var');
const logger = require('pino')({ level: JAMBONES_LOGLEVEL || 'info' });
const Srf = require('drachtio-srf');
const srf = new Srf();
const StatsCollector = require('@jambonz/stats-collector');
const stats = new StatsCollector(logger);
const { initLocals, rejectIpv4, checkCache, checkAccountLimits } = require('./lib/middleware');
const responseTime = require('drachtio-mw-response-time');
const regParser = require('drachtio-mw-registration-parser');
const Registrar = require('@jambonz/mw-registrar');
const digestChallenge = require('@jambonz/digest-utils');
const debug = require('debug')('jambonz:sbc-registrar');
const {
lookupAuthHook,
lookupAllVoipCarriers,
lookupSipGatewaysByCarrier,
lookupAccountBySipRealm,
lookupAccountCapacitiesBySid,
addSbcAddress,
cleanSbcAddresses,
updateVoipCarriersRegisterStatus,
lookupClientByAccountAndUsername,
lookupSipGatewaysByFilters,
updateSipGatewayBySid,
lookupCarrierBySid,
lookupSystemInformation
} = require('@jambonz/db-helpers')({
host: JAMBONES_MYSQL_HOST,
user: JAMBONES_MYSQL_USER,
port: JAMBONES_MYSQL_PORT || 3306,
password: JAMBONES_MYSQL_PASSWORD,
database: JAMBONES_MYSQL_DATABASE,
connectionLimit: JAMBONES_MYSQL_CONNECTION_LIMIT || 10
}, logger);
const {
writeAlerts,
AlertType
} = require('@jambonz/time-series')(logger, {
host: JAMBONES_TIME_SERIES_HOST,
commitSize: 50,
commitInterval: 'test' === NODE_ENV ? 7 : 20
});
const {
client,
addKey,
addKeyNx,
retrieveKey,
addToSet,
removeFromSet,
isMemberOfSet,
retrieveSet
} = require('@jambonz/realtimedb-helpers')({}, logger);
const interval = SBC_PUBLIC_ADDRESS_KEEP_ALIVE_IN_MILISECOND || 900000; // Default 15 minutes
srf.locals = {
...srf.locals,
logger,
stats,
addToSet, removeFromSet, isMemberOfSet, retrieveSet,
registrar: new Registrar(logger, client),
dbHelpers: {
lookupAuthHook,
lookupAllVoipCarriers,
lookupSipGatewaysByCarrier,
lookupAccountBySipRealm,
lookupAccountCapacitiesBySid,
updateVoipCarriersRegisterStatus,
lookupClientByAccountAndUsername,
lookupSipGatewaysByFilters,
updateSipGatewayBySid,
lookupCarrierBySid,
lookupSystemInformation
},
realtimeDbHelpers: {
client,
addKey,
addKeyNx,
retrieveKey,
retrieveSet
},
writeAlerts,
AlertType
};
srf.connect({ host: DRACHTIO_HOST, port: DRACHTIO_PORT, secret: DRACHTIO_SECRET });
srf.on('connect', (err, hp) => {
if (err) return logger.error({ err }, 'Error connecting to drachtio server');
logger.info(`connected to drachtio listening on ${hp}`);
// Add SBC Public IP to Database
srf.locals.sbcPublicIpAddress = {};
let defaultIp;
const map = new Map();
const hostports = hp.split(',');
for (const hp of hostports) {
const arr = /^(.*)\/(.*):(\d+)$/.exec(hp);
if (arr) {
const ipv4 = arr[2];
const port = arr[3];
const addr = map.get(ipv4) || {ipv4};
switch (arr[1]) {
case 'udp':
srf.locals.sbcPublicIpAddress = {
...srf.locals.sbcPublicIpAddress,
udp: `${ipv4}:${port}`
};
map.set(ipv4, {...addr, port: port});
defaultIp = ipv4;
break;
case 'tls':
map.set(ipv4, {...addr, tls_port: port});
srf.locals.sbcPublicIpAddress = {
...srf.locals.sbcPublicIpAddress,
tls: `${ipv4}:${port}`
};
break;
case 'wss':
srf.locals.sbcPublicIpAddress = {
...srf.locals.sbcPublicIpAddress,
wss: `${ipv4}:${port}`
};
map.set(ipv4, {...addr, wss_port: port});
break;
}
}
}
// if drachtio server does not tell us the tls ip and port default to standard 5061
if (!srf.locals.sbcPublicIpAddress.tls) {
srf.locals.sbcPublicIpAddress.tls = `${defaultIp}:5061`;
}
logger.info({sbcPublicIpAddress: srf.locals.sbcPublicIpAddress}, 'sbc public ip addresses');
// Function to check if the IP address is in a private subnet (RFC 1918)
const isPrivateSubnet = (ip) => {
const [firstOctet, secondOctet] = ip.split('.').map(Number);
return (
(firstOctet === 10) || // 10.0.0.0/8
(firstOctet === 172 && secondOctet >= 16 && secondOctet <= 31) || // 172.16.0.0/12
(firstOctet === 192 && secondOctet === 168) // 192.168.0.0/16
);
};
logger.info({ips: [...map.entries()]}, 'drachtio sip contacts');
const mapOfPublicAddresses = map.size === 0 ? map : new Map(Array.from(
map.entries())
.filter(([key, value]) => !isPrivateSubnet(key)));
logger.info({ips: [...mapOfPublicAddresses.entries()]}, 'drachtio sip public contacts');
mapOfPublicAddresses.forEach((addr) => {
addSbcAddress(addr.ipv4, addr.port, addr.tls_port, addr.wss_port);
// keep alive for this SBC
setTimeout(() => {
addSbcAddress(addr.ipv4, addr.port, addr.tls_port, addr.wss_port);
}, interval);
});
// first start up, clean sbc address
cleanSbcAddresses();
setTimeout(() => {
cleanSbcAddresses();
}, interval);
/* start regbot */
require('./lib/sip-trunk-register')(logger, srf);
// Start Options bot
require('./lib/sip-trunk-options-ping')(logger, srf);
});
if (NODE_ENV === 'test') {
srf.on('error', (err) => {
logger.info(err, 'Error connecting to drachtio');
});
}
const rttMetric = (req, res, time) => {
if (res.cached) {
stats.histogram('sbc.registration.cached.response_time', time.toFixed(0), [`status:${res.statusCode}`]);
}
else {
stats.histogram('sbc.registration.total.response_time', time.toFixed(0), [`status:${res.statusCode}`]);
}
};
// middleware
srf.use('register', [
initLocals,
responseTime(rttMetric),
rejectIpv4,
regParser,
checkCache,
checkAccountLimits,
digestChallenge]);
srf.use('options', [
initLocals
]);
srf.register(require('./lib/register')({logger}));
srf.options(require('./lib/options')({srf, logger}));
setInterval(async() => {
const count = await srf.locals.registrar.getCountOfUsers();
debug(`count of registered users: ${count}`);
stats.gauge('sbc.users.count', parseInt(count));
}, 30000);
module.exports = { srf, logger };