Compare commits

...
28 Commits
Author SHA1 Message Date
Sam Machin 70a09c10b3 Fix/200 (#202)
* Update call-session.js

* Update call-session.js
2025-10-28 16:58:54 -04:00
Dave Horton 49bc11bbb6 update pino and eslint (#201) 2025-10-21 07:52:29 -04:00
Sam Machin 2ebe4d3d78 bump db_helpers for cache change (#199) 2025-10-15 11:40:12 -04:00
Sam Machin cd0d360561 Redirect outbound user calls to private IP of other SBC (#197)
* redirect client calls to private address of other SBC

* remove unused util

* use address not port
2025-10-04 20:08:57 -04:00
Sam Machin 32d82ed67d Fix/193 (#195)
* pass sip failure reason back to FS

* Update call-session.js

* update drachtio-srf dep
2025-09-12 09:21:13 -04:00
Dave Horton c17f27ab2c fix prev commit (#192) 2025-09-04 07:57:38 -04:00
Dave Horton 2fc570f731 when sending to retell with user starting with call_ dont prepend plus (#191) 2025-09-03 23:35:56 -04:00
Sam Machin c87f831868 Fix/transport in contact (#190)
* use the req transport param in the From and Contact headers if set.

* Update call-session.js
2025-09-03 13:53:51 -04:00
Sam Machin 616228bf09 update isPrivateVoipNetwork function (#189) 2025-09-02 08:02:59 -04:00
Dave Horton 55fef10f0e revert change (for now) that caused audio issues when reinviting to partial media (#187) 2025-08-18 12:45:48 -04:00
Sam Machin 9357920f76 set strict source (#185)
* set strict source

RTPBleed

* change to env var for strict source

* Update srtp-transcoding.json

* lint

* lint

* reverse the logic

* and argghhh

* clarification

* change
2025-08-03 19:44:31 -04:00
Dave Horton 6771cbdefc bump version 2025-07-15 11:46:40 -04:00
Vinod Dharashive e422c2ed9c increase dtmf volume (#184)
https://github.com/jambonz/jambonz-feature-server/issues/1272
2025-07-09 08:22:53 -04:00
rammohan-y fd5e2f1a6c Remove video sdp incase of reinvite (#183)
https://github.com/jambonz/sbc-outbound/issues/182
2025-07-08 09:17:16 -04:00
sathish kumar pasham 5cc37265a9 Fix vulnerabilities by adding @babel/helpers@7.26.10 to dependencies (#181) 2025-06-27 08:04:03 -04:00
Dave Horton 1a9c438321 update version 2025-05-14 15:42:31 -04:00
Dave Horton fb62fd9bf4 update db-helpers 2025-05-13 10:36:08 -04:00
rammohan-y e02e0fa8c1 Updated drachtio version to 5.0.5 (#177)
https://github.com/drachtio/drachtio-server/issues/424
2025-04-22 11:05:45 -04:00
Hoan Luu Huu dd198105e3 update drachtio srf 5.0.4 (#176) 2025-04-18 07:50:21 -04:00
rammohan-y a34491a356 Updated db-helper to 0.9.11 (#175)
https://github.com/jambonz/jambonz-feature-server/issues/1151
2025-04-14 08:22:09 -04:00
Dave Horton 3a467921a6 return 482 loop detected if call to a sip uri would loop back to us (#173)
* return 482 loop detected if call to a sip uri would loop back to us

* this pr fixes #172

* typo

* wip

* wip
2025-03-20 11:25:08 -04:00
rammohan-y 9cb75a0b6b updated realtimedb-helper to 0.8.13 (#169) 2025-03-10 09:53:49 -04:00
Dave Horton 28dae50202 REFER should have sips contact if far end is using sips (#168) 2025-02-24 09:47:47 -05:00
Dave Horton 0b45e766b9 update drachtio-srf 2025-02-20 10:16:59 -05:00
Dave Horton 7380457b5a reject calls on hosted jambonz with no activ (#166)
e subscriptions
2025-02-19 13:04:44 -05:00
Hoan Luu Huu 9feb6f3c8f support voip carrier sip proxy (#165)
* support voiip carrier sip proxy

* wip

* wip

* wip
2025-02-17 09:47:59 -05:00
Hoan Luu Huu c449feeb9c support sip recording from siprec call (#164)
* support sip recording from siprec call

* update srsclient version
2025-02-12 09:24:33 -05:00
Dave Horton b2abe9891e refined the method for syncing call count updates and added debugging (#163)
* refined the method for syncing call count updates and added debugging

* wip

* include callId in debug key
2025-02-05 13:01:04 -05:00
11 changed files with 911 additions and 760 deletions
-1
View File
@@ -1 +0,0 @@
test/*
-126
View File
@@ -1,126 +0,0 @@
{
"env": {
"node": true,
"es6": true
},
"parserOptions": {
"ecmaFeatures": {
"jsx": false,
"modules": false
},
"ecmaVersion": 2020
},
"plugins": ["promise"],
"rules": {
"promise/always-return": "error",
"promise/no-return-wrap": "error",
"promise/param-names": "error",
"promise/catch-or-return": "error",
"promise/no-native": "off",
"promise/no-nesting": "warn",
"promise/no-promise-in-callback": "warn",
"promise/no-callback-in-promise": "warn",
"promise/no-return-in-finally": "warn",
// Possible Errors
// http://eslint.org/docs/rules/#possible-errors
"comma-dangle": [2, "only-multiline"],
"no-control-regex": 2,
"no-debugger": 2,
"no-dupe-args": 2,
"no-dupe-keys": 2,
"no-duplicate-case": 2,
"no-empty-character-class": 2,
"no-ex-assign": 2,
"no-extra-boolean-cast" : 2,
"no-extra-parens": [2, "functions"],
"no-extra-semi": 2,
"no-func-assign": 2,
"no-invalid-regexp": 2,
"no-irregular-whitespace": 2,
"no-negated-in-lhs": 2,
"no-obj-calls": 2,
"no-proto": 2,
"no-unexpected-multiline": 2,
"no-unreachable": 2,
"use-isnan": 2,
"valid-typeof": 2,
// Best Practices
// http://eslint.org/docs/rules/#best-practices
"no-fallthrough": 2,
"no-octal": 2,
"no-redeclare": 2,
"no-self-assign": 2,
"no-unused-labels": 2,
// Strict Mode
// http://eslint.org/docs/rules/#strict-mode
"strict": [2, "never"],
// Variables
// http://eslint.org/docs/rules/#variables
"no-delete-var": 2,
"no-undef": 2,
"no-unused-vars": [2, {"args": "none"}],
// Node.js and CommonJS
// http://eslint.org/docs/rules/#nodejs-and-commonjs
"no-mixed-requires": 2,
"no-new-require": 2,
"no-path-concat": 2,
"no-restricted-modules": [2, "sys", "_linklist"],
// Stylistic Issues
// http://eslint.org/docs/rules/#stylistic-issues
"comma-spacing": 2,
"eol-last": 2,
"indent": [2, 2, {"SwitchCase": 1}],
"keyword-spacing": 2,
"max-len": [2, 120, 2],
"new-parens": 2,
"no-mixed-spaces-and-tabs": 2,
"no-multiple-empty-lines": [2, {"max": 2}],
"no-trailing-spaces": [2, {"skipBlankLines": false }],
"quotes": [2, "single", "avoid-escape"],
"semi": 2,
"space-before-blocks": [2, "always"],
"space-before-function-paren": [2, "never"],
"space-in-parens": [2, "never"],
"space-infix-ops": 2,
"space-unary-ops": 2,
// ECMAScript 6
// http://eslint.org/docs/rules/#ecmascript-6
"arrow-parens": [2, "always"],
"arrow-spacing": [2, {"before": true, "after": true}],
"constructor-super": 2,
"no-class-assign": 2,
"no-confusing-arrow": 2,
"no-const-assign": 2,
"no-dupe-class-members": 2,
"no-new-symbol": 2,
"no-this-before-super": 2,
"prefer-const": 2
},
"globals": {
"DTRACE_HTTP_CLIENT_REQUEST" : false,
"LTTNG_HTTP_CLIENT_REQUEST" : false,
"COUNTER_HTTP_CLIENT_REQUEST" : false,
"DTRACE_HTTP_CLIENT_RESPONSE" : false,
"LTTNG_HTTP_CLIENT_RESPONSE" : false,
"COUNTER_HTTP_CLIENT_RESPONSE" : false,
"DTRACE_HTTP_SERVER_REQUEST" : false,
"LTTNG_HTTP_SERVER_REQUEST" : false,
"COUNTER_HTTP_SERVER_REQUEST" : false,
"DTRACE_HTTP_SERVER_RESPONSE" : false,
"LTTNG_HTTP_SERVER_RESPONSE" : false,
"COUNTER_HTTP_SERVER_RESPONSE" : false,
"DTRACE_NET_STREAM_END" : false,
"LTTNG_NET_STREAM_END" : false,
"COUNTER_NET_SERVER_CONNECTION_CLOSE" : false,
"DTRACE_NET_SERVER_CONNECTION" : false,
"LTTNG_NET_SERVER_CONNECTION" : false,
"COUNTER_NET_SERVER_CONNECTION" : false
}
}
+2
View File
@@ -69,6 +69,7 @@ const {
retrieveSet,
isMemberOfSet,
addKey,
deleteKey,
retrieveKey
} = require('@jambonz/realtimedb-helpers')({}, logger);
@@ -104,6 +105,7 @@ srf.locals = {...srf.locals,
realtimeDbHelpers: {
client: redisClient,
addKey,
deleteKey,
retrieveKey,
createHash,
retrieveHash,
+1 -1
View File
@@ -3,6 +3,6 @@
"DTLS": "off",
"SDES": "off",
"ICE": "remove",
"flags": ["media handover", "port latching"],
"flags": ["port latching"],
"rtcp-mux": ["demux"]
}
+2 -2
View File
@@ -3,13 +3,13 @@
"transport-protocol": "UDP/TLS/RTP/SAVPF",
"ICE": "force",
"SDES": "off",
"flags": ["generate mid", "SDES-no", "media handover", "port latching"],
"flags": ["generate mid", "SDES-no", "port latching"],
"rtcp-mux": ["require"]
},
"teams": {
"transport-protocol": "RTP/SAVP",
"ICE": "force",
"flags": ["generate mid", "media handover",
"flags": ["generate mid",
"SDES-no-AES_CM_128_HMAC_SHA1_32",
"SDES-no-F8_128_HMAC_SHA1_80",
"SDES-no-F8_128_HMAC_SHA1_32",
+137
View File
@@ -0,0 +1,137 @@
const promisePlugin = require('eslint-plugin-promise');
module.exports = [
{
ignores: ['test/*']
},
{
files: ['**/*.js'],
languageOptions: {
ecmaVersion: 2020,
sourceType: 'commonjs',
globals: {
// Node.js globals
console: 'readonly',
process: 'readonly',
Buffer: 'readonly',
__dirname: 'readonly',
__filename: 'readonly',
module: 'readonly',
require: 'readonly',
exports: 'readonly',
setTimeout: 'readonly',
clearTimeout: 'readonly',
setInterval: 'readonly',
clearInterval: 'readonly',
setImmediate: 'readonly',
clearImmediate: 'readonly',
// DTrace/LTTNG globals
DTRACE_HTTP_CLIENT_REQUEST: false,
LTTNG_HTTP_CLIENT_REQUEST: false,
COUNTER_HTTP_CLIENT_REQUEST: false,
DTRACE_HTTP_CLIENT_RESPONSE: false,
LTTNG_HTTP_CLIENT_RESPONSE: false,
COUNTER_HTTP_CLIENT_RESPONSE: false,
DTRACE_HTTP_SERVER_REQUEST: false,
LTTNG_HTTP_SERVER_REQUEST: false,
COUNTER_HTTP_SERVER_REQUEST: false,
DTRACE_HTTP_SERVER_RESPONSE: false,
LTTNG_HTTP_SERVER_RESPONSE: false,
COUNTER_HTTP_SERVER_RESPONSE: false,
DTRACE_NET_STREAM_END: false,
LTTNG_NET_STREAM_END: false,
COUNTER_NET_SERVER_CONNECTION_CLOSE: false,
DTRACE_NET_SERVER_CONNECTION: false,
LTTNG_NET_SERVER_CONNECTION: false,
COUNTER_NET_SERVER_CONNECTION: false
}
},
plugins: {
promise: promisePlugin
},
rules: {
// Promise plugin rules
'promise/always-return': 'error',
'promise/no-return-wrap': 'error',
'promise/param-names': 'error',
'promise/catch-or-return': 'error',
'promise/no-native': 'off',
'promise/no-nesting': 'warn',
'promise/no-promise-in-callback': 'warn',
'promise/no-callback-in-promise': 'warn',
'promise/no-return-in-finally': 'warn',
// Possible Errors
'comma-dangle': [2, 'only-multiline'],
'no-control-regex': 2,
'no-debugger': 2,
'no-dupe-args': 2,
'no-dupe-keys': 2,
'no-duplicate-case': 2,
'no-empty-character-class': 2,
'no-ex-assign': 2,
'no-extra-boolean-cast': 2,
'no-extra-parens': [2, 'functions'],
'no-extra-semi': 2,
'no-func-assign': 2,
'no-invalid-regexp': 2,
'no-irregular-whitespace': 2,
'no-obj-calls': 2,
'no-proto': 2,
'no-unexpected-multiline': 2,
'no-unreachable': 2,
'use-isnan': 2,
'valid-typeof': 2,
// Best Practices
'no-fallthrough': 2,
'no-octal': 2,
'no-redeclare': 2,
'no-self-assign': 2,
'no-unused-labels': 2,
// Strict Mode
'strict': [2, 'never'],
// Variables
'no-delete-var': 2,
'no-undef': 2,
'no-unused-vars': [2, {args: 'none'}],
// Node.js and CommonJS
'no-mixed-requires': 2,
'no-new-require': 2,
'no-path-concat': 2,
// Stylistic Issues
'comma-spacing': 2,
'eol-last': 2,
'indent': [2, 2, {SwitchCase: 1}],
'keyword-spacing': 2,
'max-len': [2, 120, 2],
'new-parens': 2,
'no-mixed-spaces-and-tabs': 2,
'no-multiple-empty-lines': [2, {max: 2}],
'no-trailing-spaces': [2, {skipBlankLines: false}],
'quotes': [2, 'single', 'avoid-escape'],
'semi': 2,
'space-before-blocks': [2, 'always'],
'space-before-function-paren': [2, 'never'],
'space-in-parens': [2, 'never'],
'space-infix-ops': 2,
'space-unary-ops': 2,
// ECMAScript 6
'arrow-parens': [2, 'always'],
'arrow-spacing': [2, {before: true, after: true}],
'constructor-super': 2,
'no-class-assign': 2,
'no-confusing-arrow': 2,
'no-const-assign': 2,
'no-dupe-class-members': 2,
'no-new-symbol': 2,
'no-this-before-super': 2,
'prefer-const': 2
}
}
];
+68 -23
View File
@@ -7,7 +7,9 @@ const {
isPrivateVoipNetwork,
isBlackListedSipGateway,
makeFullMediaReleaseKey,
makePartnerFullMediaReleaseKey
makePartnerFullMediaReleaseKey,
isValidDomainOrIP,
removeVideoSdp
} = require('./utils');
const { MediaPath } = require('./constants.json');
const {forwardInDialogRequests} = require('drachtio-fn-b2b-sugar');
@@ -101,7 +103,7 @@ const updateRtpEngineFlags = (sdp, opts) => {
opts.flags.push(`codec-accept-${codec}`);
opts.flags.push('codec-accept-telephone-event');
}
} catch (err) {}
} catch {}
return opts;
};
@@ -320,7 +322,7 @@ class CallSession extends Emitter {
const prefix = vc.tech_prefix || '';
const transport = o.protocol?.startsWith('tls') ? 'tls' : (o.protocol || 'udp');
const hostport = !o.port || 5060 === o.port ? o.ipv4 : `${o.ipv4}:${o.port}`;
const prependPlus = vc.e164_leading_plus && !this.req.calledNumber.startsWith('0') ? '+' : '';
const prependPlus = vc.e164_leading_plus && /^[1-9]/.test(calledNumber) ? '+' : '';
const scheme = transport === 'tls' && !process.env.JAMBONES_USE_BEST_EFFORT_TLS && o.use_sips_scheme ?
'sips' : 'sip';
let u = `${scheme}:${prefix}${prependPlus}${calledNumber}@${hostport};transport=${transport}`;
@@ -342,6 +344,14 @@ class CallSession extends Emitter {
proxy = u;
u = `${scheme}:${prefix}${prependPlus}${calledNumber}@${vc.register_sip_realm};transport=${transport}`;
this.logger.debug({uri: u}, `using outbound proxy for this registered trunk: ${proxy}`);
} else if (vc.outbound_sip_proxy && vc.outbound_sip_proxy.length > 0) {
if (vc.outbound_sip_proxy.includes('sip:') || vc.outbound_sip_proxy.includes('sips:')) {
proxy = vc.outbound_sip_proxy;
} else if (isValidDomainOrIP(vc.outbound_sip_proxy)) {
proxy =
`${scheme}:${prefix}${prependPlus}${calledNumber}@${vc.outbound_sip_proxy};transport=${transport}`;
this.logger.debug({uri: u}, `using outbound proxy for this trunk: ${proxy}`);
}
}
mapGateways.set(u, obj);
uris.push(u);
@@ -487,16 +497,19 @@ class CallSession extends Emitter {
};
}
else {
const uri = parseUri(this.req.uri);
hdrs = {
...hdrs,
'From': createBLegFromHeader({
logger: this.logger,
req: this.req,
transport: uri.params.transport,
...(private_network && {host: this.privateSipAddress})
}),
'Contact': createBLegFromHeader({
logger: this.logger,
req: this.req,
transport: uri.params.transport,
...(private_network && {host: this.privateSipAddress})
})
};
@@ -618,8 +631,18 @@ class CallSession extends Emitter {
const abandoned = err.message && err.message.includes('rtpengine failed: Unknown call-id');
const status = err.status || (abandoned ? 487 : 500);
if (err instanceof SipError) this.logger.info(`final call failure ${status}`);
else if (!abandoned) this.logger.error(err, 'unexpected call failure');
debug(`got final outdial error: ${err}`);
else if (!abandoned) {
const {writeCallCount, writeCallCountSP, writeCallCountApp} = this.req.srf.locals;
this.logger.error({err}, 'unexpected call failure');
nudgeCallCounts(this.req, 'failure', {
service_provider_sid: this.service_provider_sid,
account_sid: this.account_sid,
application_sid: this.application_sid,
callId: this.req.locals.callId
}, this.decrKey, {writeCallCountSP, writeCallCount, writeCallCountApp})
.catch((err) => this.logger.error(err, 'Error decrementing call counts'));
}
this.logger.debug(`got final outdial error: ${err}`);
if (!passFailure) this.res.send(status);
this.emit('failed');
this.rtpEngineResource.destroy()
@@ -643,7 +666,7 @@ class CallSession extends Emitter {
}
}
} catch (err) {
if ('abandonded' !== err.message) this.logger.error(err, `Error setting up outbound call to: ${uris}`);
if ('abandonded' !== err.message) this.logger.error({err}, `Error setting up outbound call to: ${uris}`);
this.emit('failed');
this.srf.endSession(this.req);
this.rtpEngineResource.destroy();
@@ -686,7 +709,7 @@ class CallSession extends Emitter {
if (!IMMUTABLE_HEADERS.includes(h)) headers[h] = bye.headers[h];
});
await other.destroy({headers});
} catch (err) {}
} catch {}
const trackingOn = process.env.JAMBONES_TRACK_ACCOUNT_CALLS ||
process.env.JAMBONES_TRACK_SP_CALLS ||
@@ -694,16 +717,14 @@ class CallSession extends Emitter {
if (process.env.JAMBONES_HOSTING || trackingOn) {
const {writeCallCount, writeCallCountSP, writeCallCountApp} = this.req.srf.locals;
if (!this.req.locals.callCountNudged) {
this.req.locals.callCountNudged = true;
this.logger.debug('decrementing call count at end of call');
await nudgeCallCounts(this.logger, {
service_provider_sid: this.service_provider_sid,
account_sid: this.account_sid,
application_sid: this.application_sid
}, this.decrKey, {writeCallCountSP, writeCallCount, writeCallCountApp})
.catch((err) => this.logger.error(err, 'Error decrementing call counts'));
}
this.logger.debug('decrementing call count at end of call');
await nudgeCallCounts(this.req, 'complete', {
service_provider_sid: this.service_provider_sid,
account_sid: this.account_sid,
application_sid: this.application_sid,
callId: this.req.locals.callId
}, this.decrKey, {writeCallCountSP, writeCallCount, writeCallCountApp})
.catch((err) => this.logger.error(err, 'Error decrementing call counts'));
}
/* write cdr for connected call */
@@ -867,9 +888,9 @@ Duration=${payload.duration} `
const acceptCodecs = process.env.JAMBONES_ACCEPT_AND_TRANSCODE ?
process.env.JAMBONES_ACCEPT_AND_TRANSCODE :
process.env.JAMBONES_ACCEPT_G729 ? 'g729' : '';
offerMedia = { ...offerMedia, ...(acceptCodecs && dlg.type === 'uac' &&
offerMedia = { ...offerMedia, ...(acceptCodecs && dlg.type === 'uac' &&
{ codec: { mask: acceptCodecs, transcode: 'pcmu,pcma' } })};
answerMedia = { ...answerMedia, ...(process.env.JAMBONES_CODEC_OFFER_WITH_ORDER && dlg.type === 'uac' &&
answerMedia = { ...answerMedia, ...(process.env.JAMBONES_CODEC_OFFER_WITH_ORDER && dlg.type === 'uac' &&
{ codec: {offer: process.env.JAMBONES_CODEC_OFFER_WITH_ORDER.split(','), strip: 'all' }})};
let opts = {
...this.rtpEngineOpts.common,
@@ -921,8 +942,12 @@ Duration=${payload.duration} `
throw new Error(`_onReinvite: rtpengine failed: ${JSON.stringify(response)}`);
}
this.logger.debug({opts, sdp: response.sdp}, 'CallSession:_onReinvite: (answer) sending back upstream');
let responseSdp = response.sdp;
if (process.env.JAMBONES_VIDEO_CALLS_ENABLED_IN_FS) {
responseSdp = removeVideoSdp(responseSdp);
}
res.send(200, {
body: response.sdp,
body: responseSdp,
headers: {
'Contact': this.contactHeader
}
@@ -1001,7 +1026,8 @@ Duration=${payload.duration} `
blockMedia: this.blockMedia,
unblockMedia: this.unblockMedia,
unsubscribe: this.unsubscribe,
headers
headers,
isSipRecCall: Array.isArray(this.req.payload) && this.req.payload.length > 1
}));
try {
this._startRecordingNoAnswerTimer(res);
@@ -1083,11 +1109,13 @@ Duration=${payload.duration} `
const code = arr[1];
const arr2 = /Duration=\s*(\d+)/.exec(req.body);
const duration = arr2 ? arr2[1] : 250;
const volume = 13;
const dtmfOpts = {
...this.rtpEngineOpts.common,
'from-tag': this.rtpEngineOpts.uas.tag,
code,
duration
duration,
volume
};
const response = await this.playDTMF(dtmfOpts);
if ('ok' !== response.result) {
@@ -1155,7 +1183,7 @@ Duration=${payload.duration} `
// eslint-disable-next-line no-unused-vars
'content-length': _contentlength, 'refer-to': _referto, 'referred-by': referredby,
// eslint-disable-next-line no-unused-vars
'X-Refer-To-Leave-Untouched': _leave,
'X-Refer-To-Leave-Untouched': _leave, contact: _contact,
...customHeaders
} = req.headers;
@@ -1175,6 +1203,7 @@ Duration=${payload.duration} `
headers: {
'Refer-To': `<${stringifyUri(uri)}>`,
'Referred-By': referredby,
'Contact': this.contactHeader,
...customHeaders
}
});
@@ -1202,6 +1231,22 @@ Duration=${payload.duration} `
this.activeCallIds.delete(this.req.get('Call-ID'));
if (this.activeCallIds.size === 0) this.idleEmitter.emit('idle');
uac.other.destroy();
if (this.req.locals.cdr) {
const now = Date.now();
const day = new Date();
const recordAllCalls = this.req.locals.record_all_calls;
let recording_url = `/Accounts/${this.account_sid}/RecentCalls/${this.req.locals.cdr.call_sid}/record`;
recording_url += `/${day.getFullYear()}/${(day.getMonth() + 1).toString().padStart(2, '0')}`;
recording_url += `/${day.getDate().toString().padStart(2, '0')}/${recordAllCalls}`;
this.writeCdrs({...this.req.locals.cdr,
terminated_at: now,
termination_reason: 'caller hungup',
sip_status: 200,
answered: true,
duration: Math.floor((now - this.req.locals.cdr.answered_at) / 1000),
...(recordAllCalls && {recording_url})
}).catch((err) => this.logger.error({err}, 'Error writing cdr for completed call'));
}
this.srf.endSession(this.req);
});
+33 -13
View File
@@ -1,7 +1,7 @@
const debug = require('debug')('jambonz:sbc-outbound');
const parseUri = require('drachtio-srf').parseUri;
const Registrar = require('@jambonz/mw-registrar');
const {selectHostPort, nudgeCallCounts} = require('./utils');
const { nudgeCallCounts} = require('./utils');
const FS_UUID_SET_NAME = 'fsUUIDs';
module.exports = (srf, logger, redisClient) => {
@@ -17,6 +17,8 @@ module.exports = (srf, logger, redisClient) => {
const initLocals = async(req, res, next) => {
req.locals = req.locals || {};
const callId = req.get('Call-ID');
req.locals.nudge = 0;
req.locals.callId = callId;
req.locals.account_sid = req.get('X-Account-Sid');
req.locals.application_sid = req.get('X-Application-Sid');
req.locals.record_all_calls = req.get('X-Record-All-Calls');
@@ -60,7 +62,7 @@ module.exports = (srf, logger, redisClient) => {
});
return req.srf.endSession(req);
}
} catch (err) {
} catch {
res.send(500);
return req.srf.endSession(req);
}
@@ -106,13 +108,12 @@ module.exports = (srf, logger, redisClient) => {
try {
/* decrement count if INVITE is later rejected */
res.once('end', async({status}) => {
if (status > 200 && !req.locals.callCountNudged) {
req.locals.callCountNudged = true;
logger.debug('decrementing call count due to call rejection');
nudgeCallCounts(logger, {
if (status > 200) {
nudgeCallCounts(req, 'failure', {
service_provider_sid,
account_sid,
application_sid
application_sid,
callId: req.locals.callId
}, decrKey, {writeCallCountSP, writeCallCount, writeCallCountApp})
.catch((err) => logger.error(err, 'Error decrementing call counts'));
const tags = ['accepted:no', `sipStatus:${status}`];
@@ -125,10 +126,11 @@ module.exports = (srf, logger, redisClient) => {
});
/* increment the call count */
const {callsSP, calls} = await nudgeCallCounts(logger, {
const {callsSP, calls} = await nudgeCallCounts(req, 'init', {
service_provider_sid,
account_sid,
application_sid
application_sid,
callId: req.locals.callId
}, incrKey, {writeCallCountSP, writeCallCount, writeCallCountApp});
/* compare to account's limit, though avoid db hit when call count is low */
@@ -172,6 +174,11 @@ module.exports = (srf, logger, redisClient) => {
});
return req.srf.endSession(req);
}
if (!account_limit && !sp_limit && process.env.JAMBONES_HOSTING) {
logger.info(`checkLimits: no active subscription found for account ${account_sid}, rejecting call`);
res.send(503, 'No Active Subscription');
return req.srf.endSession(req);
}
if (process.env.JAMBONES_TRACK_SP_CALLS && sp_limit > 0 && callsSP > sp_limit) {
logger.info({callsSP, sp_limit}, 'checkLimits: service provider limits exceeded');
writeAlerts({
@@ -227,8 +234,8 @@ module.exports = (srf, logger, redisClient) => {
logger.info({details: reg}, `sending call to registered user ${aor}`);
if (req.server.hostport !== reg.sbcAddress) {
/* redirect to the correct SBC where this user is connected */
const proxyAddress = selectHostPort(reg.sbcAddress, 'tcp');
const redirectUri = `<sip:${proxyAddress[1]}>`;
const proxyAddress = reg.privateSbcAddress.split(':');
const redirectUri = `<sip:${proxyAddress[0]}>`;
logger.info({
myHostPort: req.server.hostport,
registeredHostPort: reg.sbcAddress,
@@ -253,9 +260,22 @@ module.exports = (srf, logger, redisClient) => {
else if ('sip' === desiredRouting) {
// call that needs to be forwarded to a sip endpoint
logger.info(`forwarding call to sip endpoint ${req.uri}`);
// check if the domain is one of ours
if (process.env.JAMBONES_LOCAL_SIP_DOMAINS) {
const allowedDomains = process.env.JAMBONES_LOCAL_SIP_DOMAINS.split(',');
const domain = uri.host;
const isLoop = allowedDomains.some((allowed) =>
domain === allowed.trim() || domain.endsWith(`.${allowed.trim()}`)
);
if (isLoop) {
logger.info({ host: domain }, `returning 482 Loop Detected for attempt to send to: ${req.uri}`);
res.send(482, 'Loop Detected');
return req.srf.endSession(req);
}
}
req.locals.target = 'forward';
}
else if ('phone' === desiredRouting) {
} else if ('phone' === desiredRouting) {
debug('sending call to LCR');
req.locals.target = 'lcr';
}
+116 -5
View File
@@ -3,6 +3,7 @@ const srtpCharacteristics = require('../data/srtp-transcoding');
const debug = require('debug')('jambonz:sbc-outbound');
const CIDRMatcher = require('cidr-matcher');
const dns = require('dns');
const sdpTransform = require('sdp-transform');
function makeRtpEngineOpts(req, srcIsUsingSrtp, dstIsUsingSrtp, padCrypto, teams) {
const from = req.getParsedHeader('from');
@@ -27,6 +28,14 @@ function makeRtpEngineOpts(req, srcIsUsingSrtp, dstIsUsingSrtp, padCrypto, teams
srcOpts.flags.push('inject DTMF');
}
}
/** By default, and for backwards compatibility, use media handover
* set env var to true to use strict source instead (needed for rtpbleed vulnerability)
*/
const enableStrictSource = !!process.env.RTPENGINE_ENABLE_STRICT_SOURCE;
dstOpts.flags.push(enableStrictSource ? 'strict source' : 'media handover');
srcOpts.flags.push(enableStrictSource ? 'strict source' : 'media handover');
const common = {
'call-id': req.get('Call-ID'),
'replace': ['origin', 'session-connection'],
@@ -131,13 +140,96 @@ const createHealthCheckApp = (port, logger) => {
});
};
const nudgeCallCounts = async(logger, sids, nudgeOperator, writers) => {
const {service_provider_sid, account_sid, application_sid} = sids;
/**
* nudgeCallCounts - increment or decrement call counts in redis
*
* current nudge value
* -----------------------------------------
* why | -1 | 0 | 1 |
* -----------------------------------------
* init | no-op | +1 | N/A |
* failure | N/A | -1 | -1 |
* complete| N/A | N/A | -1 |
*
*
*/
const shouldNudge = (why, req) => {
const {nudge, logger} = req.locals;
let modifyCount = false;
const originalNudge = nudge;
switch (why) {
case 'init':
if (nudge === 0) {
// normal case: new call, increment call count
req.locals.nudge = 1;
modifyCount = true;
}
else if (nudge === -1) {
// extremely quick cancel, don't increment call count
req.locals.nudge = 0;
}
else {
logger.info(`shouldNudge: unexpected nudge value ${nudge} for ${why}`);
}
break;
case 'failure':
if (nudge === 1) {
// normal case of call failed for any reason, decrement call count
req.locals.nudge = 0;
modifyCount = true;
}
else if (nudge === 0) {
// very quick failure dont decrement call count
req.locals.nudge = -1;
}
else {
logger.info(`shouldNudge: unexpected nudge value ${nudge} for ${why}`);
}
break;
case 'complete':
if (nudge === 1) {
// normal case of call completed, decrement call count
req.locals.nudge = 0;
modifyCount = true;
}
else {
logger.info(`shouldNudge: unexpected nudge value ${nudge} for ${why}`);
}
break;
default:
logger.info(`shouldNudge: unexpected why value ${why}`);
break;
}
logger.info(`shouldNudge: '${why}': updating count: ${modifyCount}, nudge: ${originalNudge} -> ${req.locals.nudge}`);
return modifyCount;
};
const nudgeCallCounts = async(req, why, sids, nudgeOperator, writers) => {
const {logger} = req.locals;
const {service_provider_sid, account_sid, application_sid, callId} = sids;
const {writeCallCount, writeCallCountSP, writeCallCountApp} = writers;
const nudges = [];
const writes = [];
logger.debug(sids, 'nudgeCallCounts');
if (!shouldNudge(why, req)) {
return {callsSP: null, calls: null, callsApp: null};
}
if (process.env.JAMBONES_DEBUG_CALL_COUNTS) {
const {srf} = require('..');
const {addKey, deleteKey} = srf.locals.realtimeDbHelpers;
if (why === 'init') {
// save for 3 days
await addKey(`debug:outcalls:${account_sid}:${callId}`, new Date().toISOString(), 259200);
}
else {
await deleteKey(`debug:outcalls:${account_sid}:${callId}`);
}
}
if (process.env.JAMBONES_TRACK_SP_CALLS) {
const key = makeSPCallCountKey(service_provider_sid);
@@ -198,7 +290,7 @@ const isPrivateVoipNetwork = async(uri) => {
if (privateNetworkCidr) {
try {
const matcher = new CIDRMatcher(privateNetworkCidr.split(','));
const arr = /sips?:.*@(.*?)(:\d+)?(;.*)$/.exec(uri);
const arr = /sips?:.*@(.*?)(:\d+)?(;.*)?$/.exec(uri);
if (arr) {
const input = arr[1];
let addresses;
@@ -240,6 +332,23 @@ const makePartnerFullMediaReleaseKey = (callId) => {
return `a_sdp:${callId}`;
};
function isValidDomainOrIP(input) {
const domainRegex = /^(?!:\/\/)([a-zA-Z0-9.-]+)(:\d+)?$/;
// eslint-disable-next-line max-len
const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(:\d+)?$/;
if (domainRegex.test(input) || ipRegex.test(input)) {
return true;
}
return false; // Invalid input
}
const removeVideoSdp = (sdp) => {
const parsedSdp = sdpTransform.parse(sdp);
// Filter out video media sections, keeping only non-video media
parsedSdp.media = parsedSdp.media.filter((media) => media.type !== 'video');
return sdpTransform.write(parsedSdp);
};
module.exports = {
makeRtpEngineOpts,
selectHostPort,
@@ -253,5 +362,7 @@ module.exports = {
isPrivateVoipNetwork,
isBlackListedSipGateway,
makeFullMediaReleaseKey,
makePartnerFullMediaReleaseKey
makePartnerFullMediaReleaseKey,
isValidDomainOrIP,
removeVideoSdp
};
+542 -580
View File
File diff suppressed because it is too large Load Diff
+10 -9
View File
@@ -1,6 +1,6 @@
{
"name": "sbc-outbound",
"version": "0.9.3",
"version": "0.9.5",
"main": "app.js",
"engines": {
"node": ">= 18.0.0"
@@ -24,29 +24,30 @@
"start": "node app",
"test": "NODE_ENV=test HTTP_PORT=3050 JAMBONES_HOSTING=1 JAMBONES_NETWORK_CIDR=127.0.0.1/32 JAMBONES_MYSQL_HOST=127.0.0.1 JAMBONES_MYSQL_USER=jambones_test JAMBONES_MYSQL_PASSWORD=jambones_test JAMBONES_MYSQL_DATABASE=jambones_test JAMBONES_REDIS_HOST=localhost JAMBONES_REDIS_PORT=16379 JAMBONES_TIME_SERIES_HOST=127.0.0.1 JAMBONES_LOGLEVEL=error DRACHTIO_SECRET=cymru DRACHTIO_HOST=127.0.0.1 DRACHTIO_PORT=9060 JAMBONES_RTPENGINES=127.0.0.1:12222 node test/ ",
"coverage": "./node_modules/.bin/nyc --reporter html --report-dir ./coverage npm run test",
"jslint": "eslint app.js lib --fix"
"jslint": "eslint app.js lib --fix"
},
"dependencies": {
"@jambonz/db-helpers": "^0.9.7",
"@jambonz/realtimedb-helpers": "^0.8.9",
"@babel/helpers": "^7.26.10",
"@jambonz/db-helpers": "^0.9.18",
"@jambonz/http-health-check": "^0.0.1",
"@jambonz/mw-registrar": "0.2.7",
"@jambonz/realtimedb-helpers": "^0.8.13",
"@jambonz/rtpengine-utils": "^0.4.4",
"@jambonz/siprec-client-utils": "^0.2.9",
"@jambonz/siprec-client-utils": "^0.2.10",
"@jambonz/stats-collector": "^0.1.10",
"@jambonz/time-series": "^0.2.10",
"cidr-matcher": "^2.1.1",
"debug": "^4.3.4",
"drachtio-fn-b2b-sugar": "^0.2.1",
"drachtio-srf": "^5.0.1",
"drachtio-srf": "^5.0.12",
"express": "^4.19.2",
"pino": "^8.20.0",
"pino": "^10.1.0",
"sdp-transform": "^2.15.0"
},
"devDependencies": {
"bent": "^7.3.12",
"eslint": "^7.32.0",
"eslint-plugin-promise": "^6.1.1",
"eslint": "^9.17.0",
"eslint-plugin-promise": "^7.2.1",
"nyc": "^15.1.0",
"tape": "^5.7.5"
}