var to let or const, better lints, code style and more

This commit is contained in:
2017-06-25 02:10:26 +02:00
parent a3d253994f
commit 7cc0f4f94d
16 changed files with 2887 additions and 2682 deletions
+60 -56
View File
@@ -1,55 +1,56 @@
'use strict';
var log = require('winston'),
merge = require('utils-merge'),
net = require('net'),
tls = require('tls'),
session = require('./session');
const topLogPrefix = 'larvitsmpp: lib/client.js: ',
session = require(__dirname + '/session'),
merge = require('utils-merge'),
log = require('winston'),
net = require('net'),
tls = require('tls');
function login() {
var that = this,
loginPdu;
const logPrefix = topLogPrefix + 'login() - ',
that = this;
let loginPdu;
loginPdu = {
'cmdName': 'bind_transceiver',
'seqNr': this.ourSeqNr,
'cmdName': 'bind_transceiver',
'seqNr': that.ourSeqNr,
'params': {
'system_id': this.options.username,
'password': this.options.password
'system_id': that.options.username,
'password': that.options.password
}
};
this.send(loginPdu, function(err, retPduObj) {
if (err) {
that.emit('loginFailed');
return;
}
that.send(loginPdu, function (err, retPduObj) {
if (err) return that.emit('loginFailed');
if (retPduObj.cmdStatus === 'ESME_ROK') {
log.info('larvitsmpp: lib/client.js: login() - Successful login system_id: "' + loginPdu.params.system_id + '"');
log.info(logPrefix + 'Successful login system_id: "' + loginPdu.params.system_id + '"');
that.loggedIn = true;
that.emit('loggedIn');
} else {
log.info('larvitsmpp: lib/client.js: login() - Login failed system_id: "' + loginPdu.params.system_id + '". Status msg: ' + retPduObj.cmdStatus);
log.info(logPrefix + 'Login failed system_id: "' + loginPdu.params.system_id + '". Status msg: ' + retPduObj.cmdStatus);
that.emit('loginFailed');
}
});
}
function resetEnqLinkTimer() {
var that = this;
const logPrefix = topLogPrefix + 'resetEnqLinkTimer() - ',
that = this;
log.silly('larvitsmpp: lib/client.js: resetEnqLinkTimer() - Resetting the kill timer');
if (this.enqLinkTimer) {
clearTimeout(this.enqLinkTimer);
log.silly(logPrefix + 'Resetting the kill timer');
if (that.enqLinkTimer) {
clearTimeout(that.enqLinkTimer);
}
this.enqLinkTimer = setTimeout(function() {
that.enqLinkTimer = setTimeout(function () {
that.send({
cmdName: 'enquire_link',
seqNr: that.ourSeqNr
cmdName: 'enquire_link',
seqNr: that.ourSeqNr
});
}, this.options.enqLinkTiming);
}, that.options.enqLinkTiming);
}
/**
@@ -60,26 +61,27 @@ function resetEnqLinkTimer() {
* @return {object} (returnObj)
*/
function clientSession(sock, options) {
var returnObj = session(sock);
const returnObj = session(sock),
logPrefix = topLogPrefix + 'clientSession() - ';
returnObj.options = options;
returnObj.login = login;
returnObj.resetEnqLinkTimer = resetEnqLinkTimer;
returnObj.options = options;
returnObj.login = login;
returnObj.resetEnqLinkTimer = resetEnqLinkTimer;
returnObj.login();
returnObj.resetEnqLinkTimer();
// Handle incoming Pdu Objects
returnObj.on('incomingPduObj', function(pduObj) {
returnObj.on('incomingPduObj', function (pduObj) {
// Call the appropriate handleCmd function
if (typeof returnObj.handleCmd[pduObj.cmdName] === 'function') {
log.debug('larvitsmpp: lib/client.js: clientSession() - returnObj.on(incomingPduObj) - Running cmd handling function returnObj.handleCmd.' + pduObj.cmdName + '()');
log.debug(logPrefix + 'returnObj.on(incomingPduObj) - Running cmd handling function returnObj.handleCmd.' + pduObj.cmdName + '()');
returnObj.handleCmd[pduObj.cmdName](pduObj);
} else {
// No command handling function is registered, return error "invalid command"
log.info('larvitsmpp: lib/client.js: clientSession() - returnObj.on(incomingPduObj) - No handling function found for command: "' + pduObj.cmdName + '"');
log.info(logPrefix + 'returnObj.on(incomingPduObj) - No handling function found for command: "' + pduObj.cmdName + '"');
returnObj.sendReturn(pduObj, 'ESME_RINVCMDID');
}
@@ -92,46 +94,48 @@ function clientSession(sock, options) {
* Setup a client.
*
* @param {object} options - host, port, username, password, tls, enqLinkTiming
* @param {function} callback(err, session)
* @param {function} cb(err, session)
*/
function client(options, callback) {
var sock;
function client(options, cb) {
const logPrefix = topLogPrefix + 'client() - ';
let sock;
if (typeof options === 'function') {
callback = options;
options = {};
cb = options;
options = {};
}
// Set default options
options = merge({
'host': 'localhost',
'port': 2775,
'username': 'user',
'password': 'pass',
'tls': false,
'enqLinkTiming': 20000 // 20 sec
'host': 'localhost',
'port': 2775,
'username': 'user',
'password': 'pass',
'tls': false,
'enqLinkTiming': 20000 // 20 sec
}, options || {});
if (options && options.tls && options.tls === true) {
sock = new tls.Socket();
sock = new tls.Socket();
} else {
sock = new net.Socket();
sock = new net.Socket();
}
log.debug('larvitsmpp: lib/client.js: client() - Connecting to ' + options.host + ':' + options.port);
sock.connect(options, function() {
var session = clientSession(sock, options);
log.debug(logPrefix + 'Connecting to ' + options.host + ':' + options.port);
sock.connect(options, function () {
const session = clientSession(sock, options);
log.info('larvitsmpp: lib/client.js: client() - Connected to ' + sock.remoteAddress + ':' + sock.remotePort);
log.info(logPrefix + 'Connected to ' + sock.remoteAddress + ':' + sock.remotePort);
session.on('loggedIn', function() {
callback(null, session);
session.on('loggedIn', function () {
cb(null, session);
});
session.on('loginFailed', function() {
var err = new Error('Remote host refused login.');
log.warn('larvitsmpp: lib/client.js: client() - ' + err.message);
callback(err);
session.on('loginFailed', function () {
const err = new Error('Remote host refused login.');
log.warn(logPrefix + err.message);
cb(err);
});
});
}
+1090 -1101
View File
File diff suppressed because it is too large Load Diff
+59 -62
View File
@@ -1,11 +1,12 @@
'use strict';
var log = require('winston'),
merge = require('utils-merge'),
net = require('net'),
tls = require('tls'),
session = require('./session'),
smppUtils = require('./utils');
const topLogPrefix = 'larvitsmpp: lib/server.js: ',
smppUtils = require(__dirname + '/utils'),
session = require(__dirname + '/session'),
merge = require('utils-merge'),
log = require('winston'),
net = require('net'),
tls = require('tls');
/**
* Try to log a connecting peer in
@@ -13,22 +14,20 @@ var log = require('winston'),
* @param {object} pduObj
*/
function login(pduObj) {
var that = this;
const logPrefix = topLogPrefix + 'login() - ',
that = this;
log.debug('larvitsmpp: lib/server.js: login() - Data received and session is not loggedIn');
log.debug(logPrefix + 'Data received and session is not loggedIn');
// Pause socket so we do not receive any other commands until we have processed the login
this.sock.pause();
that.sock.pause();
// Only bind_* is accepted when the client is not logged in
if (pduObj.cmdName !== 'bind_transceiver' && pduObj.cmdName !== 'bind_receiver' && pduObj.cmdName !== 'bind_transmitter') {
log.debug('larvitsmpp: lib/server.js: login() - Session is not loggedIn and no bind_* command is given. Return error "ESME_RINVBNDSTS');
log.debug(logPrefix + 'Session is not loggedIn and no bind_* command is given. Return error "ESME_RINVBNDSTS');
smppUtils.pduReturn(pduObj, 'ESME_RINVBNDSTS', function(err, retPdu) {
if (err) {
that.closeSocket();
return;
}
smppUtils.pduReturn(pduObj, 'ESME_RINVBNDSTS', function (err, retPdu) {
if (err) return that.closeSocket();
that.sock.resume();
that.sockWrite(retPdu);
@@ -38,42 +37,36 @@ function login(pduObj) {
}
// If there is a checkuserpass(), use it to check system_id and password from the PDU
if (typeof this.options.checkuserpass === 'function') {
this.options.checkuserpass(pduObj.params.system_id, pduObj.params.password, function(err, res, userData) {
if (err) {
that.closeSocket();
return;
}
if (typeof that.options.checkuserpass === 'function') {
return that.options.checkuserpass(pduObj.params.system_id, pduObj.params.password, function (err, res, userData) {
if (err) return that.closeSocket();
if ( ! res) {
log.info('larvitsmpp: lib/server.js: serverSession() - login() - Login failed! Connected host: ' + that.sock.remoteAddress + ':' + that.sock.remotePort + ' system_id: "' + pduObj.params.system_id + '"');
log.info(logPrefix + 'Login failed! Connected host: ' + that.sock.remoteAddress + ':' + that.sock.remotePort + ' system_id: "' + pduObj.params.system_id + '"');
that.sock.resume();
that.sendReturn(pduObj, 'ESME_RBINDFAIL');
return;
return that.sendReturn(pduObj, 'ESME_RBINDFAIL');
}
log.verbose('larvitsmpp: lib/server.js: serverSession() - login() - Login successful! Connected host: ' + that.sock.remoteAddress + ':' + that.sock.remotePort + ' system_id: "' + pduObj.params.system_id + '"');
that.loggedIn = true;
log.verbose(logPrefix + 'Login successful! Connected host: ' + that.sock.remoteAddress + ':' + that.sock.remotePort + ' system_id: "' + pduObj.params.system_id + '"');
that.loggedIn = true;
// Set additional user data to the session
if (userData !== undefined) {
that.userData = userData;
that.userData = userData;
}
that.sock.resume();
that.emit('login');
that.sendReturn(pduObj);
});
return;
}
// If we arrived here it means we are not logged in and that a bind_* event happened and no checkuserpass() method exists. Lets login!
this.loggedIn = true;
this.sock.resume();
this.emit('login');
this.sendReturn(pduObj);
that.loggedIn = true;
that.sock.resume();
that.emit('login');
that.sendReturn(pduObj);
}
/**
@@ -81,15 +74,16 @@ function login(pduObj) {
* If this is not ran within options.timeout milliseconds, this session will self terminate
*/
function resetEnqLinkTimer() {
var that = this;
const logPrefix = topLogPrefix + 'resetEnqLinkTimer() - ',
that = this;
log.silly('larvitsmpp: lib/server.js: resetEnqLinkTimer() - Resetting the kill timer');
log.silly(logPrefix + 'Resetting the kill timer');
if (that.enqLinkTimer) {
clearTimeout(that.enqLinkTimer);
}
that.enqLinkTimer = setTimeout(function() {
log.info('larvitsmpp: lib/server.js: resetEnqLinkTimer() - Closing session from ' + that.sock.remoteAddress + ':' + that.sock.remotePort + ' due to timeout');
that.enqLinkTimer = setTimeout(function () {
log.info(logPrefix + 'Closing session from ' + that.sock.remoteAddress + ':' + that.sock.remotePort + ' due to timeout');
that.closeSocket();
}, that.options.timeout);
}
@@ -102,16 +96,17 @@ function resetEnqLinkTimer() {
* @return {object} (returnObj)
*/
function serverSession(sock, options) {
var returnObj = session(sock);
const returnObj = session(sock);
returnObj.options = options;
returnObj.login = login;
returnObj.resetEnqLinkTimer = resetEnqLinkTimer;
returnObj.options = options;
returnObj.login = login;
returnObj.resetEnqLinkTimer = resetEnqLinkTimer;
returnObj.resetEnqLinkTimer();
// Handle incoming Pdu Objects
returnObj.on('incomingPduObj', function(pduObj) {
returnObj.on('incomingPduObj', function (pduObj) {
const logPrefix = topLogPrefix + 'serverSession() - returnObj.handleIncomingPdu() - ';
// Call the appropriate handleCmd function
// Unbind is always ok
@@ -120,18 +115,18 @@ function serverSession(sock, options) {
// If client is not logged in, always run the login function
} else if (returnObj.loggedIn === false) {
log.debug('larvitsmpp: lib/server.js: serverSession() - returnObj.handleIncomingPdu() - Not logged in, running login function');
log.debug(logPrefix + ' Not logged in, running login function');
returnObj.login(pduObj);
// Client is logged in, try to match a handling function
} else if (typeof returnObj.handleCmd[pduObj.cmdName] === 'function') {
log.debug('larvitsmpp: lib/server.js: serverSession() - returnObj.on(incomingPduObj) - Running cmd handling function returnObj.handleCmd.' + pduObj.cmdName + '()');
log.debug(logPrefix + 'Running cmd handling function returnObj.handleCmd.' + pduObj.cmdName + '()');
returnObj.handleCmd[pduObj.cmdName](pduObj);
// No command handling function is registered, return error "invalid command"
} else {
log.info('larvitsmpp: lib/server.js: serverSession() - returnObj.on(incomingPduObj) - No handling function found for command: "' + pduObj.cmdName + '"');
log.info(logPrefix + 'No handling function found for command: "' + pduObj.cmdName + '"');
returnObj.sendReturn(pduObj, 'ESME_RINVCMDID');
}
@@ -144,45 +139,47 @@ function serverSession(sock, options) {
* Setup a server
*
* @param {object} options - host, port, checkuserpass() etc (OPTIONAL)
* @param {function} callback(err, session)
* @param {function} cb(err, session)
*/
function server(options, callback) {
var tlsOrNet;
function server(options, cb) {
const logPrefix = topLogPrefix + 'server() - ';
let tlsOrNet;
if (typeof options === 'function') {
callback = options;
options = {};
cb = options;
options = {};
}
// Set default options
options = merge({
'port': 2775,
'tls': false,
'timeout': 40000 // 40 sec
'port': 2775,
'tls': false,
'timeout': 40000 // 40 sec
}, options || {});
if (options && options.tls && options.tls === true) {
tlsOrNet = tls;
tlsOrNet = tls;
} else {
tlsOrNet = net;
tlsOrNet = net;
}
// Create a server instance, and chain the listen function to it
// The function passed to net.createServer() becomes the event handler for the 'connection' event
// The sock object the callback function receives UNIQUE for each connection
tlsOrNet.createServer(options, function(sock) {
var returnObj = serverSession(sock, options);
// The sock object the cb function receives UNIQUE for each connection
tlsOrNet.createServer(options, function (sock) {
const returnObj = serverSession(sock, options);
// We have a connection - a socket object is assigned to the connection automatically
log.verbose('larvitsmpp: lib/server.js: server() - Incoming connection! From: ' + sock.remoteAddress + ':' + sock.remotePort);
log.verbose(logPrefix + 'Incoming connection! From: ' + sock.remoteAddress + ':' + sock.remotePort);
callback(null, returnObj);
cb(null, returnObj);
}).listen(options.port, options.host);
if (options.host !== undefined) {
log.info('larvitsmpp: lib/server.js: server() - Up and listening at ' + options.host + ':' + options.port);
log.info(logPrefix + 'Up and listening at ' + options.host + ':' + options.port);
} else {
log.info('larvitsmpp: lib/server.js: server() - Up and listening at *:' + options.port);
log.info(logPrefix + 'Up and listening at *:' + options.port);
}
}
+280 -286
View File
@@ -1,67 +1,66 @@
'use strict';
var log = require('winston'),
events = require('events'),
moment = require('moment'),
utils = require('./utils'),
defs = require('./defs'),
async = require('async');
const topLogPrefix = 'larvitsmpp: lib/session.js: ',
events = require('events'),
moment = require('moment'),
utils = require('./utils'),
async = require('async'),
defs = require('./defs'),
log = require('winston');
/*
/**
* Send a response to an sms
* This must be called from an sms object context
*
* @param str status - see list at defs.errors - defaults to 'ESME_ROK' - no error (OPTIONAL)
* @param func callback(err, [retPdu, ...])
* @param {string} status - see list at defs.errors - defaults to 'ESME_ROK' - no error (OPTIONAL)
* @param {function} cb - cb(err, [retPdu, ...])
*/
function smsResp(status, callback) {
var sms = this,
tasks = [],
params,
err,
i;
function smsResp(status, cb) {
const logPrefix = topLogPrefix + 'smsResp() - ',
tasks = [],
sms = this;
let params;
if (typeof status === 'function') {
callback = status;
status = true;
cb = status;
status = true;
}
if (typeof callback !== 'function') {
callback = function() {};
if (typeof cb !== 'function') {
cb = function () {};
}
if (sms.smsId === undefined) {
sms.smsId = '';
sms.smsId = '';
}
// Accept a generic positive status
if (status === 'true' || status === true || status === 0) {
status = 'ESME_ROK';
status = 'ESME_ROK';
}
// Accept a generic negative status
if (status === 'false' || status === false || status === 1) {
status = 'ESME_RUNKNOWNERR'; // Set to unknown error in this case
status = 'ESME_RUNKNOWNERR'; // Set to unknown error in this case
}
if (sms.pduObjs === undefined) {
err = new Error('No pdu objects found to base return PDU upon');
log.warn('larvitsmpp: lib/session.js: smsResp() - ' + err.message);
callback(err);
return;
const err = new Error('No pdu objects found to base return PDU upon');
log.warn(logPrefix + err.message);
return cb(err);
}
// Build async tasks to run the responses in parallel
i = 0;
while (sms.pduObjs[i] !== undefined) {
for (let i = 0; sms.pduObjs[i] !== undefined; i ++) {
if (sms.smsId) {
if (sms.pduObjs[i].pduObj.params.esm_class === 0x40) {
params = {'message_id': sms.smsId + '-' + (i + 1)};
params = {'message_id': sms.smsId + '-' + (i + 1)};
} else {
params = {'message_id': sms.smsId};
params = {'message_id': sms.smsId};
}
} else {
params = {};
params = {};
}
tasks[i] = sms.session.sendReturn.bind(
@@ -71,11 +70,9 @@ function smsResp(status, callback) {
params,
false
);
i ++;
}
async.parallel(tasks, callback);
async.parallel(tasks, cb);
}
function incOurSeqNr() {
@@ -92,9 +89,11 @@ function incOurSeqNr() {
* Always use this function to close the socket so we get it on log
*/
function closeSocket() {
log.verbose('larvitsmpp: lib/session.js: closeSocket() - Closing socket for ' + this.sock.remoteAddress + ':' + this.sock.remotePort);
const logPrefix = topLogPrefix + 'closeSocket() - ';
log.verbose(logPrefix + 'Closing socket for ' + this.sock.remoteAddress + ':' + this.sock.remotePort);
if (this.enqLinkTimer) {
log.debug('larvitsmpp: lib/session.js: closeSocket() - enqLinkTimer found, clearing.');
log.debug(logPrefix + 'enqLinkTimer found, clearing.');
clearTimeout(this.enqLinkTimer);
}
this.sock.destroy();
@@ -107,14 +106,14 @@ function closeSocket() {
* @param {boolean} closeAfterSend - if true will close the socket after sending
*/
function sockWrite(pdu, closeAfterSend) {
var that = this;
const logPrefix = topLogPrefix + 'sockWrite() - ',
that = this;
if ( ! Buffer.isBuffer(pdu)) {
utils.objToPdu(pdu, function(err, buffer) {
utils.objToPdu(pdu, function (err, buffer) {
if (err) {
log.warn('larvitsmpp: lib/session.js: sockWrite() - Could not convert PDU to buffer');
that.closeSocket();
return;
log.warn(logPrefix + 'Could not convert PDU to buffer');
return that.closeSocket();
}
that.sockWrite(buffer);
@@ -123,16 +122,16 @@ function sockWrite(pdu, closeAfterSend) {
}
try {
log.verbose('larvitsmpp: lib/session.js: sockWrite() - sending PDU. SeqNr: ' + pdu.readUInt32BE(12) + ' cmd: ' + defs.cmdsById[pdu.readUInt32BE(4)].command + ' cmdStatus: ' + defs.errorsById[parseInt(pdu.readUInt32BE(8))] + ' hex: ' + pdu.toString('hex'));
} catch (e) {
log.error('larvitsmpp: lib/session.js: sockWrite() - PDU buffer is invalid. Buffer hex: "' + pdu.toString('hex') + '"');
log.verbose(logPrefix + 'sending PDU. SeqNr: ' + pdu.readUInt32BE(12) + ' cmd: ' + defs.cmdsById[pdu.readUInt32BE(4)].command + ' cmdStatus: ' + defs.errorsById[parseInt(pdu.readUInt32BE(8))] + ' hex: ' + pdu.toString('hex'));
} catch (err) {
log.error(logPrefix + 'PDU buffer is invalid. Buffer hex: "' + pdu.toString('hex') + '"');
return;
}
this.sock.write(pdu);
that.sock.write(pdu);
if (closeAfterSend) {
this.closeSocket();
that.closeSocket();
}
}
@@ -141,73 +140,69 @@ function sockWrite(pdu, closeAfterSend) {
*
* @param {buffer|object} pdu
* @param {boolean} closeAfterSend - Will close after return is fetched. Defaults to false (OPTIONAL)
* @param {function} callback(err, retPdu) (OPTIONAL)
* @param {function} cb - cb(err, retPdu) (OPTIONAL)
*/
function send(pdu, closeAfterSend, callback) {
var pduObj = pdu,
err = null,
that = this;
function send(pdu, closeAfterSend, cb) {
const logPrefix = topLogPrefix + 'send() - ',
pduObj = pdu,
that = this;
// Make sure the pdu is an object
if (Buffer.isBuffer(pdu)) {
utils.pduToObj(pdu, function(err, pduObj) {
if (err) {
callback(err);
return;
}
utils.pduToObj(pdu, function (err, pduObj) {
if (err) return cb(err);
that.send(pduObj, closeAfterSend, callback);
that.send(pduObj, closeAfterSend, cb);
});
return;
}
// Make sure the sequence number is set and is correct
pduObj.seqNr = this.ourSeqNr;
pduObj.seqNr = this.ourSeqNr;
log.debug('larvitsmpp: lib/session.js: send() - Sending PDU to remote. pduObj: ' + JSON.stringify(pduObj));
log.debug(logPrefix + 'Sending PDU to remote. pduObj: ' + JSON.stringify(pduObj));
// If closeAndSend is omitted, put callback in its place
// If closeAndSend is omitted, put cb in its place
if (typeof closeAfterSend === 'function') {
callback = closeAfterSend;
closeAfterSend = undefined;
cb = closeAfterSend;
closeAfterSend = undefined;
}
// Make sure the callack is a function
if (typeof callback !== 'function') {
callback = function(){};
if (typeof cb !== 'function') {
cb = function () {};
}
// Response PDUs are not allowed with the send() command, they should use the sendReturn()
if (pduObj.cmdName.substring(pduObj.cmdName - 5) === '_resp') {
err = new Error('Given pduObj is a response, use sendReturn() instead. cmdName: ' + pduObj.cmdName);
callback(err);
return;
const err = new Error('Given pduObj is a response, use sendReturn() instead. cmdName: ' + pduObj.cmdName);
log.verbose(logPrefix + err.message);
return cb(err);
}
// When the return is fetched, call the callback
this.on('incomingPduObj' + pduObj.seqNr, function(incPduObj) {
log.debug('larvitsmpp: lib/session.js: send() - this.on(incomingPduObj) - cmdName: ' + incPduObj.cmdName + ' seqNr: ' + incPduObj.seqNr + ' cmdStatus: ' + incPduObj.cmdStatus);
// When the return is fetched, call the cb
that.on('incomingPduObj' + pduObj.seqNr, function (incPduObj) {
log.debug(logPrefix + 'this.on(incomingPduObj) - cmdName: ' + incPduObj.cmdName + ' seqNr: ' + incPduObj.seqNr + ' cmdStatus: ' + incPduObj.cmdStatus);
// Make sure this is the actual response to the sent PDU
if (incPduObj.isResp() && incPduObj.seqNr === pduObj.seqNr) {
callback(null, incPduObj);
cb(null, incPduObj);
if (closeAfterSend) {
that.closeSocket();
}
} else {
err = new Error('Event triggered but incoming PDU is not a response or seqNr does not match. isResp: ' + incPduObj.isResp().toString() + ' incSeqNr: ' + incPduObj.seqNr + ' expected seqNr: ' + pduObj.seqNr);
log.warn('larvitsmpp: lib/session.js: send() - this.on(incomingPduObj) - ' + err.message);
callback(err);
const err = new Error('Event triggered but incoming PDU is not a response or seqNr does not match. isResp: ' + incPduObj.isResp().toString() + ' incSeqNr: ' + incPduObj.seqNr + ' expected seqNr: ' + pduObj.seqNr);
log.warn(logPrefix + 'this.on(incomingPduObj) - ' + err.message);
cb(err);
}
});
// Increase our internal sequence number
this.incOurSeqNr();
that.incOurSeqNr();
// Write the PDU to socket
this.sockWrite(pduObj);
that.sockWrite(pduObj);
}
/**
@@ -217,70 +212,70 @@ function send(pdu, closeAfterSend, callback) {
* @param {string} status - see list at defs.errors - defaults to 'ESME_ROK' - no error (OPTIONAL)
* @param {object} [params]
* @param {boolean} closeAfterSend - if true will close the socket after sending (OPTIONAL)
* @param {function} [callback(err, retPdu)]
* @param {function} [cb(err, retPdu)]
*/
function sendReturn(pdu, status, params, closeAfterSend, callback) {
var that = this;
function sendReturn(pdu, status, params, closeAfterSend, cb) {
const logPrefix = topLogPrefix + 'sendReturn() - ',
that = this;
log.silly('larvitsmpp: lib/session.js: sendReturn() - ran');
log.silly(logPrefix + 'ran');
if (typeof params === 'function') {
callback = params;
params = undefined;
closeAfterSend = undefined;
cb = params;
params = undefined;
closeAfterSend = undefined;
}
if (typeof closeAfterSend === 'function') {
callback = closeAfterSend;
closeAfterSend = undefined;
cb = closeAfterSend;
closeAfterSend = undefined;
}
if (typeof callback !== 'function') {
callback = function() {};
if (typeof cb !== 'function') {
cb = function () {};
}
utils.pduReturn(pdu, status, params, function(err, retPdu) {
utils.pduReturn(pdu, status, params, function (err, retPdu) {
if (err) {
log.error('larvitsmpp: lib/session.js: sendReturn() - Could not create return PDU: ' + err.message);
log.error(logPrefix + 'Could not create return PDU: ' + err.message);
that.closeSocket();
callback(err);
return;
return cb(err);
}
log.silly('larvitsmpp: lib/session.js: sendReturn() - Sending return PDU: ' + retPdu.toString('hex'));
log.silly(logPrefix + 'Sending return PDU: ' + retPdu.toString('hex'));
that.sockWrite(retPdu, closeAfterSend);
callback(null, retPdu);
cb(null, retPdu);
});
}
/**
* Send an SMS
*
* @param {object} smsOptions
* from - alphanum or international format
* to - international format
* message - string
* dlr - boolean defaults to false
* flash - boolean defaults to false
* @param {function} callback(err, smsIds, retPduObjs)
* @param {object} smsOptions {
* from - alphanum or international format
* to - international format
* message - string
* dlr - boolean defaults to false
* flash - boolean defaults to false
* }
* @param {function} cb(err, smsIds, retPduObjs)
*/
function sendSms(smsOptions, callback) {
var pduObj = {};
function sendSms(smsOptions, cb) {
const logPrefix = topLogPrefix + 'sendSms() - ',
pduObj = {};
pduObj.cmdName = 'submit_sm';
pduObj.cmdName = 'submit_sm';
pduObj.params = {
'source_addr_ton': 1, // Default to international format
'source_addr': smsOptions.from,
'destination_addr': smsOptions.to,
'short_message': smsOptions.message
'source_addr_ton': 1, // Default to international format
'source_addr': smsOptions.from,
'destination_addr': smsOptions.to,
'short_message': smsOptions.message
};
// Flash messages overrides default data_coding
if (smsOptions.flash) {
log.debug('larvitsmpp: lib/session.js: sendSms() - Flash SMS detected, set data_coding to 0x10!');
log.debug(logPrefix + 'Flash SMS detected, set data_coding to 0x10!');
pduObj.params.data_coding = 0x10;
}
@@ -291,18 +286,18 @@ function sendSms(smsOptions, callback) {
// Check if we must split this message into multiple
if (utils.bitCount(smsOptions.message) > 1120) {
log.debug('larvitsmpp: lib/session.js: sendSms() - Message larger than 1120 bits, send it as long message!');
log.debug(logPrefix + 'Message larger than 1120 bits, send it as long message!');
this.sendLongSms(smsOptions, callback);
this.sendLongSms(smsOptions, cb);
return;
}
log.debug('larvitsmpp: lib/session.js: sendSms() - pduObj: ' + JSON.stringify(pduObj));
log.debug(logPrefix + 'pduObj: ' + JSON.stringify(pduObj));
this.send(pduObj, function(err, retPduObj) {
if (typeof callback === 'function') {
callback(err, [retPduObj.params.message_id], [retPduObj]);
this.send(pduObj, function (err, retPduObj) {
if (typeof cb === 'function') {
cb(err, [retPduObj.params.message_id], [retPduObj]);
}
});
}
@@ -310,31 +305,33 @@ function sendSms(smsOptions, callback) {
/**
* Send a longer SMS than 1120 bits
*
* @param {object} smsOptions
* from - alphanum or international format
* to - international format
* message - string
* dlr - boolean defaults to false
* @param {function} callback(err, smsId, retPduObj)
* @param {object} smsOptions {
* from - alphanum or international format
* to - international format
* message - string
* dlr - boolean defaults to false
* }
* @param {function} cb - cb(err, smsId, retPduObj)
*/
function sendLongSms(smsOptions, callback) {
var that = this,
smsIds = [],
retPduObjs = [],
msgs = utils.splitMsg(smsOptions.message),
encoding = defs.encodings.detect(smsOptions.message); // Set encoding once for all message parts
function sendLongSms(smsOptions, cb) {
const retPduObjs = [],
logPrefix = topLogPrefix + 'sendLongSms() - ',
encoding = defs.encodings.detect(smsOptions.message), // Set encoding once for all message parts
smsIds = [],
that = this,
msgs = utils.splitMsg(smsOptions.message);
function sendPart(i) {
var pduObj = {
'cmdName': 'submit_sm',
const pduObj = {
'cmdName': 'submit_sm',
'params': {
'source_addr_ton': 1, // Default to international format
'esm_class': 0x40, // This indicates that there is a UDH in the short_message
'source_addr': smsOptions.from,
'destination_addr': smsOptions.to,
'data_coding': defs.consts.ENCODING[encoding],
'short_message': msgs[i],
'sm_length': msgs[i].length
'source_addr_ton': 1, // Default to international format
'esm_class': 0x40, // This indicates that there is a UDH in the short_message
'source_addr': smsOptions.from,
'destination_addr': smsOptions.to,
'data_coding': defs.consts.ENCODING[encoding],
'short_message': msgs[i],
'sm_length': msgs[i].length
}
};
@@ -343,17 +340,17 @@ function sendLongSms(smsOptions, callback) {
pduObj.params.registered_delivery = 0x01;
}
log.debug('larvitsmpp: lib/session.js: sendLongSms() - pduObj: ' + JSON.stringify(pduObj));
log.debug(logPrefix + 'pduObj: ' + JSON.stringify(pduObj));
that.send(pduObj, function(err, retPduObj) {
that.send(pduObj, function (err, retPduObj) {
smsIds.push(retPduObj.params.message_id);
retPduObjs.push(retPduObj);
log.silly('larvitsmpp: lib/session.js: sendLongSms() - Got callback from that.send()');
log.silly(logPrefix + 'Got cb from that.send()');
if (typeof callback === 'function' && smsIds.length === msgs.length) {
log.silly('larvitsmpp: lib/session.js: sendLongSms() - All callbacks returned, run the parent callback.');
callback(err, smsIds, retPduObjs);
if (typeof cb === 'function' && smsIds.length === msgs.length) {
log.silly(logPrefix + 'All cbs returned, run the parent cb.');
cb(err, smsIds, retPduObjs);
}
});
@@ -367,39 +364,39 @@ function sendLongSms(smsOptions, callback) {
// Store long smses in the temporary storage
function longSms(pduObj) {
// Fix: UDH values are stored in HEX and decoding them make it garbage. First OCTET contains
// the size of UDH data header. If UDH data header size is 0x05 then field 4 i.e. CSMS
// reference number is of one octet otherwise it consists of 2 octets. Other fields can
// be found from below reference.
// reference: https://en.wikipedia.org/wiki/Concatenated_SMS
var udhHeaderSize = pduObj.params.short_message[0], // First octet is the size of UDH Header
headerSize = pduObj.params.short_message[2], // Header size other than first 2 octets
csmsReference = pduObj.params.short_message.slice(3, 3 + headerSize - 2), // CSMS Reference starts from
// 4th octet and length is
// header size -2 octets
partsCount = pduObj.params.short_message[2 + csmsReference.length + 1],
partNr = pduObj.params.short_message[2 + csmsReference.length + 2],
longSmsId = pduObj.params.source_addr + '_' + pduObj.params.destination_addr + '_' + csmsReference;
// Fix: UDH values are stored in HEX and decoding them make it garbage. First OCTET contains
// the size of UDH data header. If UDH data header size is 0x05 then field 4 i.e. CSMS
// reference number is of one octet otherwise it consists of 2 octets. Other fields can
// be found from below reference.
// reference: https://en.wikipedia.org/wiki/Concatenated_SMS
if (this.longSmses[longSmsId] === undefined) {
this.longSmses[longSmsId] = {
'created': new Date(),
'partsCount': partsCount,
'udhSize': udhHeaderSize, // Saving udh size to remove garbage from message
const udhHeaderSize = pduObj.params.short_message[0], // First octet is the size of UDH Header
headerSize = pduObj.params.short_message[2], // Header size other than first 2 octets
csmsReference = pduObj.params.short_message.slice(3, 3 + headerSize - 2), // CSMS Reference starts from 4th octet and length is header size -2 octets
partsCount = pduObj.params.short_message[2 + csmsReference.length + 1],
longSmsId = pduObj.params.source_addr + '_' + pduObj.params.destination_addr + '_' + csmsReference,
partNr = pduObj.params.short_message[2 + csmsReference.length + 2],
that = this;
if (that.longSmses[longSmsId] === undefined) {
that.longSmses[longSmsId] = {
'created': new Date(),
'partsCount': partsCount,
'udhSize': udhHeaderSize, // Saving udh size to remove garbage from message
'pduObjs': [{
'partNr': partNr, // We save this here to easier sort the array later on
'pduObj': pduObj
'partNr': partNr, // We save this here to easier sort the array later on
'pduObj': pduObj
}]
};
} else {
this.longSmses[longSmsId].pduObjs.push({
'partNr': partNr, // We save this here to easier sort the array later on
'pduObj': pduObj
that.longSmses[longSmsId].pduObjs.push({
'partNr': partNr, // We save this here to easier sort the array later on
'pduObj': pduObj
});
}
// Check the long messages tmp storage to see if we should handle them
this.checkLongSmses();
that.checkLongSmses();
}
// Sort function to sort group parts
@@ -418,15 +415,11 @@ function sortLongSmsPdus(a, b) {
// Walk through the long sms storage to investigate if we can send complete messages along
// or should remove old ones
function checkLongSmses() {
var that = this,
smsGroupId,
smsGroup,
udhSize, // UDH Size from longSms() function
smsObj,
i,
curPduObj;
const logPrefix = topLogPrefix + 'checkLongSmses() - ',
smsObj = {},
that = this;
log.silly('larvitsmpp: lib/session.js: checkLongSmses() - Running');
log.silly(logPrefix + 'Running');
// Call when complete SMS is received
function smsReceived() {
@@ -436,44 +429,41 @@ function checkLongSmses() {
delete that.longSmses[smsObj.smsGroupId];
}
for (smsGroupId in this.longSmses) {
smsGroup = this.longSmses[smsGroupId];
udhSize = smsGroup.udhSize;
for (const smsGroupId in this.longSmses) {
const smsGroup = this.longSmses[smsGroupId],
udhSize = smsGroup.udhSize;
// All parts are accounted for! Emit sms event and clear from tmp storage
if (smsGroup.partsCount === smsGroup.pduObjs.length) {
log.debug('larvitsmpp: lib/session.js: checkLongSmses() - All parts accounted for in smsGroupId "' + smsGroupId + '", emitting sms event.');
log.debug(logPrefix + 'All parts accounted for in smsGroupId "' + smsGroupId + '", emitting sms event.');
smsObj = {
// These are needed for references here and there in functions
'session': that,
'smsGroupId': smsGroupId,
'pduObjs': smsGroup.pduObjs,
'from': smsGroup.pduObjs[0].pduObj.params.source_addr,
'to': smsGroup.pduObjs[0].pduObj.params.destination_addr,
'submitTime': new Date(),
'message': '',
'dlr': Boolean(smsGroup.pduObjs[0].pduObj.params.registered_delivery),
'sendResp': smsResp,
'sendDlr': utils.smsDlr
};
// These are needed for references here and there in functions
smsObj.session = that;
smsObj.smsGroupId = smsGroupId;
smsObj.pduObjs = smsGroup.pduObjs;
smsObj.from = smsGroup.pduObjs[0].pduObj.params.source_addr;
smsObj.to = smsGroup.pduObjs[0].pduObj.params.destination_addr;
smsObj.submitTime = new Date();
smsObj.message = '';
smsObj.dlr = Boolean(smsGroup.pduObjs[0].pduObj.params.registered_delivery);
smsObj.sendResp = smsResp;
smsObj.sendDlr = utils.smsDlr;
// Concatenate all the parts messages to one and set references to the session
// First we need to sort the parts, since they can come in random order
smsObj.pduObjs.sort(sortLongSmsPdus);
i = 0;
while (smsObj.pduObjs[i] !== undefined) {
curPduObj = smsObj.pduObjs[i].pduObj;
curPduObj.session = this;
for (let i = 0; smsObj.pduObjs[i] !== undefined; i ++) {
const curPduObj = smsObj.pduObjs[i].pduObj;
smsObj.message += utils.decodeMsg(curPduObj.params.short_message, curPduObj.params.data_coding, udhSize + 1);
curPduObj.session = this;
i ++;
smsObj.message += utils.decodeMsg(curPduObj.params.short_message, curPduObj.params.data_coding, udhSize + 1);
}
smsReceived();
} else if (moment(new Date()).diff(smsGroup.created, 'hours') > 24) {
log.info('larvitsmpp: lib/session.js: checkLongSmses() - smsGroupId "' + smsGroupId + '" is removed from this.longSmses due to being older than 24 hours.');
log.info(logPrefix + 'smsGroupId "' + smsGroupId + '" is removed from this.longSmses due to being older than 24 hours.');
delete this.longSmses[smsGroupId];
}
@@ -487,49 +477,46 @@ function checkLongSmses() {
* @return {object} (returnObj)
*/
function session(sock) {
var returnObj = new events.EventEmitter();
const logPrefix = topLogPrefix + 'session() - socket address: ' + sock.remoteAddress + ':' + sock.remotePort + ' - ',
returnObj = new events.EventEmitter();
log.silly('larvitsmpp: lib/session.js: session() - New session started from ' + sock.remoteAddress + ':' + sock.remotePort);
log.silly(logPrefix + 'New session started');
returnObj.loggedIn = false;
// Sequence number used for commands initiated from us
returnObj.ourSeqNr = 1;
// Make the socket transparent via the returned emitter
returnObj.sock = sock;
returnObj.incOurSeqNr = incOurSeqNr;
returnObj.closeSocket = closeSocket;
returnObj.sockWrite = sockWrite;
returnObj.send = send;
returnObj.sendReturn = sendReturn;
returnObj.sendSms = sendSms;
returnObj.utils = utils;
returnObj.loggedIn = false;
returnObj.ourSeqNr = 1; // Sequence number used for commands initiated from us
returnObj.sock = sock; // Make the socket transparent via the returned emitter
returnObj.incOurSeqNr = incOurSeqNr;
returnObj.closeSocket = closeSocket;
returnObj.sockWrite = sockWrite;
returnObj.send = send;
returnObj.sendReturn = sendReturn;
returnObj.sendSms = sendSms;
returnObj.utils = utils;
// Temporary storage for long sms parts
// These should be cleared if they linger to long to avoid memory leaks
returnObj.longSmses = {};
returnObj.longSmses = {};
// Temporary storage for DLRs to long SMSes
// We keep them like this to be able to simulate a single DLR when all parts have gotten DLRs
returnObj.longSmsDlrs = {};
returnObj.longSmsDlrs = {};
returnObj.sendLongSms = sendLongSms;
returnObj.longSms = longSms;
returnObj.checkLongSmses = checkLongSmses;
returnObj.sendLongSms = sendLongSms;
returnObj.longSms = longSms;
returnObj.checkLongSmses = checkLongSmses;
// Handle incomming commands.
// This is intended to be extended
returnObj.handleCmd = {};
returnObj.handleCmd = {};
// Handle incoming deliver_sm
returnObj.handleCmd.deliver_sm = function(pduObj) {
var dlrObj;
returnObj.handleCmd.deliver_sm = function deliver_sm(pduObj) {
const thisLogPrefix = logPrefix + 'deliver_sm() - ',
dlrObj = {};
// TLV message_state must exists
if (pduObj.tlvs.message_state === undefined) {
log.info('larvitsmpp: lib/session.js: session() - returnObj.handleCmd.deliver_sm() - TLV message_state is missing. SeqNr: ' + pduObj.seqNr);
log.info(thisLogPrefix + 'TLV message_state is missing. SeqNr: ' + pduObj.seqNr);
returnObj.sendReturn(pduObj, 'ESME_RINVTLVSTREAM');
return;
@@ -537,7 +524,7 @@ function session(sock) {
// TLV message_state needs to be valid
if (defs.constsById.MESSAGE_STATE[pduObj.tlvs.message_state.tagValue] === undefined) {
log.info('larvitsmpp: lib/session.js: session() - returnObj.handleCmd.deliver_sm() - Invalid TLV message_state: "' + pduObj.tlvs.message_state.tagValue + '". SeqNr: ' + pduObj.seqNr);
log.info(thisLogPrefix + 'Invalid TLV message_state: "' + pduObj.tlvs.message_state.tagValue + '". SeqNr: ' + pduObj.seqNr);
returnObj.sendReturn(pduObj, 'ESME_RINVTLVSTREAM');
return;
@@ -545,98 +532,98 @@ function session(sock) {
// TLV receipted_message_id must exist
if (pduObj.tlvs.receipted_message_id === undefined) {
log.info('larvitsmpp: lib/session.js: session() - returnObj.handleCmd.deliver_sm() - TLV receipted_message_id is missing. SeqNr: ' + pduObj.seqNr);
log.info(thisLogPrefix + 'TLV receipted_message_id is missing. SeqNr: ' + pduObj.seqNr);
returnObj.sendReturn(pduObj, 'ESME_RINVTLVSTREAM');
return;
}
dlrObj = {
'statusMsg': defs.constsById.MESSAGE_STATE[pduObj.tlvs.message_state.tagValue],
'statusId': pduObj.tlvs.message_state.tagValue,
'smsId': pduObj.tlvs.receipted_message_id.tagValue
};
dlrObj.statusMsg = defs.constsById.MESSAGE_STATE[pduObj.tlvs.message_state.tagValue];
dlrObj.statusId = pduObj.tlvs.message_state.tagValue;
dlrObj.smsId = pduObj.tlvs.receipted_message_id.tagValue;
returnObj.emit('dlr', dlrObj, pduObj);
returnObj.sendReturn(pduObj);
};
// Enquire link
returnObj.handleCmd.enquire_link = function(pduObj) {
log.silly('larvitsmpp: lib/session.js: session() - enquireLink() - Enquiring link');
returnObj.handleCmd.enquire_link = function enquire_link(pduObj) {
const thisLogPrefix = logPrefix + 'enquire_link() - ';
log.silly(thisLogPrefix + 'Enquiring link');
returnObj.resetEnqLinkTimer();
returnObj.sendReturn(pduObj);
};
// Handle incoming submit_sm
returnObj.handleCmd.submit_sm = function(pduObj) {
var smsObj = {};
returnObj.handleCmd.submit_sm = function submit_sm(pduObj) {
const thisLogPrefix = logPrefix + 'submit_sm() - ',
smsObj = {};
log.silly('larvitsmpp: lib/session.js: session() - returnObj.handleCmd.submit_sm() - ran');
log.silly(thisLogPrefix + 'ran');
// If esm_class is 0x40 it means this is just a part of a larger message
//if (pduObj.params.esm_class === 0x40) {
// Fix: esm_class can be combination of bits. We need to extract 0x40 and then compare
if ((pduObj.params.esm_class & 0x40) === 0x40) {
log.debug('larvitsmpp: lib/session.js: session() - returnObj.handleCmd.submit_sm() - long sms detected, esm_class 0x40.');
log.debug(thisLogPrefix + 'long sms detected, esm_class 0x40.');
returnObj.longSms(pduObj);
return; // Long messages should not get handled here at all, so cancel execution here
}
smsObj = {
// These are needed for references here and there in functions
'session': returnObj,
'pduObjs': [{'pduObj': pduObj}],
'from': pduObj.params.source_addr,
'to': pduObj.params.destination_addr,
'submitTime': new Date(),
'message': pduObj.params.short_message,
'dlr': Boolean(pduObj.params.registered_delivery),
'sendResp': smsResp,
'sendDlr': utils.smsDlr
};
// These are needed for references here and there in functions
smsObj.session = returnObj;
smsObj.pduObjs = [{'pduObj': pduObj}];
smsObj.from = pduObj.params.source_addr;
smsObj.to = pduObj.params.destination_addr;
smsObj.submitTime = new Date();
smsObj.message = pduObj.params.short_message;
smsObj.dlr = Boolean(pduObj.params.registered_delivery);
smsObj.sendResp = smsResp;
smsObj.sendDlr = utils.smsDlr;
if (pduObj.params.data_coding === 0x10) {
smsObj.flash = true;
smsObj.flash = true;
}
log.silly('larvitsmpp: lib/session.js: session() - returnObj.handleCmd.submit_sm() - Emitting sms object');
log.silly(thisLogPrefix + 'Emitting sms object');
returnObj.emit('sms', smsObj);
};
// Handle incoming unbind
returnObj.handleCmd.unbind = function(pduObj) {
returnObj.handleCmd.unbind = function unbind(pduObj) {
returnObj.sendReturn(pduObj, 'ESME_ROK', undefined, true);
};
// Dummy, should be extended by serverSession or clientSession
returnObj.login = function() {
log.info('larvitsmpp: lib/session.js: session() - login() - Dummy login function ran, this might be a mistake');
returnObj.login = function login() {
const thisLogPrefix = logPrefix + 'login() - ';
log.info(thisLogPrefix + 'Dummy login function ran, this might be a mistake');
returnObj.loggedIn = true;
};
// Dummy method - should be used by serverSession or clientSession
returnObj.resetEnqLinkTimer = function() {
log.silly('larvitsmpp: lib/session.js: session() - resetEnqLinkTimer() - Resetting the kill timer');
returnObj.resetEnqLinkTimer = function resetEnqLinkTimer() {
const thisLogPrefix = logPrefix + 'resetEnqLinkTimer() - ';
log.silly(thisLogPrefix + 'Resetting the kill timer');
};
// Unbind this session
returnObj.unbind = function() {
returnObj.unbind = function () {
returnObj.send({
'cmdName': 'unbind'
'cmdName': 'unbind'
}, true);
};
// Setup a data queue in case we only get partial data on the socket
// This way we can concatenate them later on
returnObj.dataQueue = new Buffer(0);
returnObj.dataQueue = new Buffer(0);
// Add a 'data' event handler to this instance of socket
sock.on('data', function(data) {
var cmdLength,
pdu;
sock.on('data', function (data) {
const thisLogPrefix = logPrefix + 'sock.on(data) - ';
// Pass the data along to the returnObj
returnObj.emit('data', data);
@@ -644,20 +631,22 @@ function session(sock) {
// Reset the enquire link timer
returnObj.resetEnqLinkTimer();
log.debug('larvitsmpp: lib/session.js: session() - sock.on(data) - Incoming data: ' + data.toString('hex'));
log.debug(thisLogPrefix + 'Incoming data: ' + data.toString('hex'));
// Add this data to the dataQueue for processing
returnObj.dataQueue = Buffer.concat([returnObj.dataQueue, data]);
returnObj.dataQueue = Buffer.concat([returnObj.dataQueue, data]);
// Process queue
while (returnObj.dataQueue.length > 4) {
// Get this commands length
cmdLength = parseInt(returnObj.dataQueue.readUInt32BE(0));
log.silly('larvitsmpp: lib/session.js: session() - sock.on(data) - Processing ' + cmdLength + ' bytes of data');
const cmdLength = parseInt(returnObj.dataQueue.readUInt32BE(0)); // Get this commands length
let pdu;
log.silly(thisLogPrefix + 'Processing ' + cmdLength + ' bytes of data');
// If there is at least enough bytes in the dataQueue to fill this PDU, do it!
if (cmdLength <= returnObj.dataQueue.length) {
log.silly('larvitsmpp: lib/session.js: session() - sock.on(data) - Full PDU found in dataQueue, processing ' + cmdLength + ' bytes of queue total ' + returnObj.dataQueue.length + ' bytes');
log.silly(thisLogPrefix + 'Full PDU found in dataQueue, processing ' + cmdLength + ' bytes of queue total ' + returnObj.dataQueue.length + ' bytes');
// Slice up the dataQueue buffer to this commands length
pdu = returnObj.dataQueue.slice(0, cmdLength);
@@ -667,34 +656,35 @@ function session(sock) {
returnObj.emit('incomingPdu', pdu);
} else {
log.debug('larvitsmpp: lib/session.js: session() - sock.on(data) - Tried to process ' + cmdLength + ' bytes, but only ' + returnObj.dataQueue.length + ' bytes found. Awaiting more data. Current data in queue: ' + returnObj.dataQueue.toString('hex'));
log.debug(thisLogPrefix + 'Tried to process ' + cmdLength + ' bytes, but only ' + returnObj.dataQueue.length + ' bytes found. Awaiting more data. Current data in queue: ' + returnObj.dataQueue.toString('hex'));
break;
}
if (returnObj.dataQueue.length === 0) {
log.silly('larvitsmpp: lib/session.js: session() - sock.on(data) - All queue handled, breaking while loop.');
log.silly(thisLogPrefix + 'All queue handled, breaking while loop.');
break;
}
// If the command length is larger than the queue, we need to wait for more data. Stop processing!
if (cmdLength > returnObj.dataQueue) {
log.debug('larvitsmpp: lib/session.js: session() - sock.on(data) - Incomplete PDU found in dataQueue, waiting for more data to continue. Current cmdLength: ' + cmdLength + ' current queue: ' + returnObj.dataQueue.toString('hex'));
log.debug(thisLogPrefix + 'Incomplete PDU found in dataQueue, waiting for more data to continue. Current cmdLength: ' + cmdLength + ' current queue: ' + returnObj.dataQueue.toString('hex'));
break;
}
}
});
});
// Handle incoming Pdu Buffers
returnObj.on('incomingPdu', function(pdu) {
utils.pduToObj(pdu, function(err, pduObj) {
returnObj.on('incomingPdu', function (pdu) {
const thisLogPrefix = logPrefix + 'sock.on(incomingPdu) - ';
utils.pduToObj(pdu, function (err, pduObj) {
if (err) {
log.warn('larvitsmpp: lib/session.js: session() - returnObj.on(incomingPdu) - Invalid PDU, closing socket.');
log.warn(thisLogPrefix + 'Invalid PDU, closing socket.');
returnObj.closeSocket();
} else {
log.verbose('larvitsmpp: lib/session.js: session() - returnObj.on(incomingPdu) - Incoming PDU parsed. Seqnr: ' + pduObj.seqNr + ' cmd: ' + pduObj.cmdName + ' cmdStatus: ' + pduObj.cmdStatus + ' hex: ' + pdu.toString('hex'));
log.verbose(thisLogPrefix + 'Incoming PDU parsed. Seqnr: ' + pduObj.seqNr + ' cmd: ' + pduObj.cmdName + ' cmdStatus: ' + pduObj.cmdStatus + ' hex: ' + pdu.toString('hex'));
if (pduObj.isResp()) {
// We do this so we can remove the dynamic event listeners to not have a memory leak
@@ -710,19 +700,23 @@ function session(sock) {
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function() {
sock.on('close', function () {
const thisLogPrefix = logPrefix + 'sock.on(close) - ';
returnObj.emit('close');
if (returnObj.enqLinkTimer) {
log.debug('larvitsmpp: lib/session.js: session() - sock.on(close) - enqLinkTimer found, clearing.');
log.debug(thisLogPrefix + 'enqLinkTimer found, clearing.');
clearTimeout(returnObj.enqLinkTimer);
}
log.debug('larvitsmpp: lib/session.js: session() - sock.on(close) - socket closed');
log.debug(thisLogPrefix + 'socket closed');
});
sock.on('error', function() {
log.warn('larvitsmpp: lib/session.js: session() - sock.on(error) - Socket error detected!');
sock.on('error', function () {
const thisLogPrefix = logPrefix + 'sock.on(error) - ';
log.warn(thisLogPrefix + 'Socket error detected!');
if (returnObj.enqLinkTimer) {
log.debug('larvitsmpp: lib/session.js: session() - sock.on(error) - enqLinkTimer found, clearing.');
log.debug(thisLogPrefix + 'enqLinkTimer found, clearing.');
clearTimeout(returnObj.enqLinkTimer);
}
});
+267 -316
View File
@@ -1,49 +1,46 @@
'use strict';
var log = require('winston'),
defs = require('./defs'),
bundleMsgId = 0;
const topLogPrefix = 'larvitsmpp: lib/utils.js: ',
defs = require(__dirname + '/defs.js'),
log = require('winston');
let bundleMsgId = 0;
/**
* Calculate cmdLength from object
*
* @param {object} obj
* @param {function} callback(err, cmdLength)
* @param {function} cb - cb(err, cmdLength)
*/
function calcCmdLength(obj, callback) {
var cmdLength = 16, // All commands are at least 16 octets long
err,
param,
paramType,
tlvValue,
tlvName,
tlvDef;
function calcCmdLength(obj, cb) {
const logPrefix = topLogPrefix + 'calcCmdLength() - ';
let cmdLength = 16; // All commands are at least 16 octets long
// Handle params - All command params should always exists, even if they do not contain data.
for (param in defs.cmds[obj.cmdName].params) {
for (const param in defs.cmds[obj.cmdName].params) {
// Get the parameter type, int, string, cstring etc.
// This is needed so we can calculate length etc
paramType = defs.cmds[obj.cmdName].params[param].type;
const paramType = defs.cmds[obj.cmdName].params[param].type;
if (obj.params[param] === undefined) {
obj.params[param] = paramType.default;
obj.params[param] = paramType.default;
}
if (isNaN(paramType.size(obj.params[param]))) {
err = new Error('Invalid param value "' + obj.params[param] + '" for param "' + param + '" and command "' + obj.cmdName + '". Is it of the right type?');
log.error('larvitsmpp: lib/utils.js: calcCmdLength() - ' + err.message);
callback(err);
return;
const err = new Error('Invalid param value "' + obj.params[param] + '" for param "' + param + '" and command "' + obj.cmdName + '". Is it of the right type?');
log.error(logPrefix + err.message);
return cb(err);
}
cmdLength += paramType.size(obj.params[param]);
}
// TLV params - optional parameters
for (tlvName in obj.tlvs) {
tlvValue = obj.tlvs[tlvName].tagValue;
tlvDef = defs.tlvsById[obj.tlvs[tlvName].tagId];
for (const tlvName in obj.tlvs) {
const tlvValue = obj.tlvs[tlvName].tagValue;
let tlvDef = defs.tlvsById[obj.tlvs[tlvName].tagId];
if (tlvDef === undefined) {
tlvDef = defs.tlvs.default;
@@ -51,15 +48,14 @@ function calcCmdLength(obj, callback) {
try {
cmdLength += tlvDef.type.size(tlvValue) + 4;
} catch(e) {
err = new Error('Could not get size of TLV parameter "' + tlvName + '" with value "' + tlvValue + '"');
log.error('larvitsmpp: lib/utils.js: calcCmdLength() - ' + err.message);
callback(err);
return;
} catch (err) {
const manErr = new Error('Could not get size of TLV parameter "' + tlvName + '" with value "' + tlvValue + '", err: ' + err.message);
log.error(logPrefix + manErr.message);
return cb(manErr);
}
}
callback(null, cmdLength);
cb(null, cmdLength);
}
/**
@@ -67,63 +63,53 @@ function calcCmdLength(obj, callback) {
*
* @param {object} obj - the PDU object to be written to buffer
* @param {number} cmdLength - The length of the pdu buffer
* @param {function} callback(err, buff)
* @param {function} cb - cb(err, buff)
*/
function writeBuffer(obj, cmdLength, callback) {
var offset = 16, // Start the offset on the body
buff,
param,
paramType,
paramSize,
tlvId,
tlvName,
tlvValue,
tlvDef,
tlvSize,
err;
function writeBuffer(obj, cmdLength, cb) {
const logPrefix = topLogPrefix + 'writeBuffer() - ';
if (isNaN(cmdLength) || cmdLength < 16) {
if (isNaN(cmdLength)) {
err = new Error('cmdLength is NaN');
}
let offset = 16, // Start the offset on the body
buff;
if (cmdLength < 16) {
err = new Error('cmdLength is less than 16 (' + cmdLength + ')');
}
if (isNaN(cmdLength)) {
const err = new Error('cmdLength is NaN');
log.error(logPrefix + err.message);
return cb(err);
}
log.error('larvitsmpp: lib/utils.js: objToPdu() - writeBuffer() - ' + err.message);
callback(err);
return;
if (cmdLength < 16) {
const err = new Error('cmdLength is less than 16 (' + cmdLength + ')');
log.error(logPrefix + err.message);
return cb(err);
}
buff = new Buffer(cmdLength);
// Write PDU header
try {
buff.writeUInt32BE(cmdLength, 0); // Command length for the first 4 octets
buff.writeUInt32BE(defs.cmds[obj.cmdName].id, 4); // Command id for the second 4 octets
buff.writeUInt32BE(defs.errors[obj.cmdStatus], 8); // Command status for the third 4 octets
buff.writeUInt32BE(obj.seqNr, 12); // Sequence number as the fourth 4 octets
} catch (e) {
err = new Error('Could not write PDU header, catched err: ' + e.message, obj);
log.error('larvitsmpp: lib/utils.js: writeBuffer() - ' + err.message);
callback(err);
return;
buff.writeUInt32BE(cmdLength, 0); // Command length for the first 4 octets
buff.writeUInt32BE(defs.cmds[obj.cmdName].id, 4); // Command id for the second 4 octets
buff.writeUInt32BE(defs.errors[obj.cmdStatus], 8); // Command status for the third 4 octets
buff.writeUInt32BE(obj.seqNr, 12); // Sequence number as the fourth 4 octets
} catch (err) {
const manErr = new Error('Could not write PDU header, catched err: ' + err.message, obj);
log.error(logPrefix + manErr.message);
return cb(manErr);
}
// Cycle through the defs list to make sure the params are in the right order
for (param in defs.cmds[obj.cmdName].params) {
paramType = defs.cmds[obj.cmdName].params[param].type;
paramSize = paramType.size(obj.params[param]);
for (const param in defs.cmds[obj.cmdName].params) {
const paramType = defs.cmds[obj.cmdName].params[param].type,
paramSize = paramType.size(obj.params[param]);
if (Buffer.isBuffer(obj.params[param])) {
log.silly('larvitsmpp: lib/utils.js: writeBuffer() - Writing param "' + param + '" with content "' + obj.params[param].toString('hex') + '" and size "' + paramSize + '"');
log.silly(logPrefix + 'Writing param "' + param + '" with content "' + obj.params[param].toString('hex') + '" and size "' + paramSize + '"');
} else {
if (param === 'sm_length') {
log.silly('larvitsmpp: lib/utils.js: writeBuffer() - sm_length is calculated by short_message: "' + obj.params.short_message.toString('hex') + '"');
log.silly(logPrefix + 'sm_length is calculated by short_message: "' + obj.params.short_message.toString('hex') + '"');
}
log.silly('larvitsmpp: lib/utils.js: writeBuffer() - Writing param "' + param + '" with content "' + obj.params[param] + '"');
log.silly(logPrefix + 'Writing param "' + param + '" with content "' + obj.params[param] + '"');
}
// Write parameter value to buffer using the types method write()
@@ -134,18 +120,20 @@ function writeBuffer(obj, cmdLength, callback) {
}
// Cycle through the tlvs
for (tlvName in obj.tlvs) {
tlvId = obj.tlvs[tlvName].tagId;
tlvValue = obj.tlvs[tlvName].tagValue;
tlvDef = defs.tlvsById[tlvId];
for (const tlvName in obj.tlvs) {
const tlvValue = obj.tlvs[tlvName].tagValue,
tlvId = obj.tlvs[tlvName].tagId;
let tlvDef = defs.tlvsById[tlvId],
tlvSize;
if (tlvDef === undefined) {
tlvDef = defs.tlvs.default;
}
tlvSize = tlvDef.type.size(tlvValue);
tlvSize = tlvDef.type.size(tlvValue);
log.silly('larvitsmpp: lib/utils.js: writeBuffer() - Writing TLV "' + tlvName + '" offset: ' + offset + ' value: "' + tlvValue + '"');
log.silly(logPrefix + 'Writing TLV "' + tlvName + '" offset: ' + offset + ' value: "' + tlvValue + '"');
buff.writeUInt16BE(tlvId, offset);
buff.writeUInt16BE(tlvSize, offset + 2);
@@ -154,9 +142,9 @@ function writeBuffer(obj, cmdLength, callback) {
offset += tlvDef.type.size(tlvValue) + 4;
}
log.silly('larvitsmpp: lib/utils.js: writeBuffer() - Complete PDU: "' + buff.toString('hex') + '"');
log.silly(logPrefix + 'Complete PDU: "' + buff.toString('hex') + '"');
callback(null, buff);
cb(null, buff);
}
/**
@@ -168,30 +156,30 @@ function writeBuffer(obj, cmdLength, callback) {
* @return {string} in utf8 format
*/
function decodeMsg(buffer, encoding, offset) {
var checkEnc;
const logPrefix = topLogPrefix + 'decodeMsg() - ';
if (offset === undefined) {
offset = 0;
}
for (checkEnc in defs.consts.ENCODING) {
for (const checkEnc in defs.consts.ENCODING) {
if (parseInt(encoding) === defs.consts.ENCODING[checkEnc] || encoding === checkEnc) {
encoding = checkEnc;
}
}
if (defs.encodings[encoding] === undefined) {
log.info('larvitsmpp: lib/utils.js: decodeMsg() - Invalid encoding "' + encoding + '" given. Falling back to ASCII (0x01).');
log.info(logPrefix + 'Invalid encoding "' + encoding + '" given. Falling back to ASCII (0x01).');
encoding = 'ASCII';
}
log.debug('larvitsmpp: lib/utils.js: decodeMsg() - Decoding msg. Encoding: "' + encoding + '" offset: "' + offset + '" buffer: "' + buffer.toString('hex') + '"');
log.debug(logPrefix + 'Decoding msg. Encoding: "' + encoding + '" offset: "' + offset + '" buffer: "' + buffer.toString('hex') + '"');
return defs.encodings[encoding].decode(buffer.slice(offset));
}
function encodeMsg(str) {
var encoding = defs.encodings.detect(str);
const encoding = defs.encodings.detect(str);
return defs.encodings[encoding].encode(str);
}
@@ -201,107 +189,104 @@ function encodeMsg(str) {
*
* @param {buffer} pdu
* @param {boolean} stupidNullByte - Define if the short_message should be followed by a stupid NULL byte - will be auto resolved if left undefined
* @param {function} callback(err, obj)
* @param {function} cb - cb(err, obj)
*/
function pduToObj(pdu, stupidNullByte, callback) {
var retObj = {'params': {}, 'tlvs': {}},
err = null,
offset,
command,
param,
tlvCmdId,
tlvLength,
tlvValue,
paramSize;
function pduToObj(pdu, stupidNullByte, cb) {
const logPrefix = topLogPrefix + 'pduToObj() - ',
retObj = {'params': {}, 'tlvs': {}};
let offset = 16, // 0-15 is the header, so the body starts at 16
command;
if (typeof stupidNullByte === 'function') {
callback = stupidNullByte;
stupidNullByte = undefined;
cb = stupidNullByte;
stupidNullByte = undefined;
}
// Returns true if this PDU is a response to another PDU
retObj.isResp = function() {
retObj.isResp = function () {
return ! ! (this.cmdId & 0x80000000);
};
log.silly('larvitsmpp: lib/utils.js: pduToObj() - Decoding PDU to Obj. PDU buff in hex: ' + pdu.toString('hex'));
log.silly(logPrefix + 'Decoding PDU to Obj. PDU buff in hex: ' + pdu.toString('hex'));
if (pdu.length < 16) {
err = new Error('PDU is to small, minimum size is 16, given size is ' + pdu.length);
log.warn('larvitsmpp: lib/utils.js: pduToObj() - ' + err.message);
callback(err);
return;
const err = new Error('PDU is to small, minimum size is 16, given size is ' + pdu.length);
log.warn(logPrefix + '' + err.message);
return cb(err);
}
// Read the PDU Header
retObj.cmdLength = parseInt(pdu.readUInt32BE(0));
retObj.cmdId = parseInt(pdu.readUInt32BE(4));
retObj.cmdStatus = defs.errorsById[parseInt(pdu.readUInt32BE(8))];
retObj.seqNr = parseInt(pdu.readUInt32BE(12));
retObj.cmdLength = parseInt(pdu.readUInt32BE(0));
retObj.cmdId = parseInt(pdu.readUInt32BE(4));
retObj.cmdStatus = defs.errorsById[parseInt(pdu.readUInt32BE(8))];
retObj.seqNr = parseInt(pdu.readUInt32BE(12));
// Lookup the command id in the definitions
if (defs.cmdsById[retObj.cmdId] === undefined) {
err = new Error('Unknown PDU command id: ' + retObj.cmdId + ' PDU buff in hex: ' + pdu.toString('hex'));
const err = new Error('Unknown PDU command id: ' + retObj.cmdId + ' PDU buff in hex: ' + pdu.toString('hex'));
log.warn(logPrefix + '' + err.message);
return cb(err);
}
if (isNaN(retObj.seqNr)) {
err = new Error('Invalid seqNr, is not an interger: "' + retObj.seqNr + '"');
} else if (retObj.seqNr > 2147483646) {
err = new Error('Invalid seqNr, maximum size of 2147483646 (0x7fffffff) exceeded.');
const err = new Error('Invalid seqNr, is not an interger: "' + retObj.seqNr + '"');
log.warn(logPrefix + '' + err.message);
return cb(err);
}
// If error is found, do not proceed with execution
if (err !== null) {
log.warn('larvitsmpp: lib/utils.js: pduToObj() - ' + err.message);
callback(err);
return;
if (retObj.seqNr > 2147483646) {
const err = new Error('Invalid seqNr, maximum size of 2147483646 (0x7fffffff) exceeded.');
log.warn(logPrefix + '' + err.message);
return cb(err);
}
command = defs.cmdsById[retObj.cmdId];
retObj.cmdName = command.command;
command = defs.cmdsById[retObj.cmdId];
retObj.cmdName = command.command;
// Get all parameters from the body that should exists with this command
offset = 16; // 0-15 is the header, so the body starts at 16
for (param in command.params) {
for (const param in command.params) {
// Get the parameter value by using the definition type read() function
try {
retObj.params[param] = command.params[param].type.read(pdu, offset, retObj.params.sm_length);
paramSize = command.params[param].type.size(retObj.params[param]);
let paramSize;
log.silly('larvitsmpp: lib/utils.js: pduToObj() - Reading param "' + param + '" at offset ' + offset + ' with calculated size: ' + paramSize + ' content in hex: ' + pdu.slice(offset, offset + paramSize).toString('hex'));
retObj.params[param] = command.params[param].type.read(pdu, offset, retObj.params.sm_length);
paramSize = command.params[param].type.size(retObj.params[param]);
log.silly(logPrefix + 'Reading param "' + param + '" at offset ' + offset + ' with calculated size: ' + paramSize + ' content in hex: ' + pdu.slice(offset, offset + paramSize).toString('hex'));
if (param === 'short_message') {
// Check if we have a trailing NULL octet after the short_message. Some idiot thought that would be a good idea
// in some implementations, so we need to account for that.
if (stupidNullByte === true) {
log.silly('larvitsmpp: lib/utils.js: pduToObj() - stupidNullByte is set, so short_message is followed by a NULL octet, increase paramSize one extra to account for that');
log.silly(logPrefix + 'stupidNullByte is set, so short_message is followed by a NULL octet, increase paramSize one extra to account for that');
paramSize ++;
}
}
// Increase the offset by the current params length
offset += paramSize;
} catch (e) {
err = new Error('Failed to read param "' + param + '": ' + e.message);
log.error('larvitsmpp: lib/utils.js: pduToObj() - ' + err.message);
callback(err);
return;
} catch (err) {
const manErr = new Error('Failed to read param "' + param + '", err: ' + err.message);
log.error(logPrefix + '' + manErr.message);
return cb(err);
}
}
// If the length is greater than the current offset, there must be TLVs - resolve them!
// The minimal size for a TLV is its head, 4 octets
while ((offset + 4) < retObj.cmdLength) {
let tlvLength,
tlvCmdId,
tlvValue;
try {
tlvCmdId = pdu.readInt16BE(offset);
tlvLength = pdu.readInt16BE(offset + 2);
} catch (e) {
err = new Error('Unable to read TLV at offset "' + offset + '", given cmdLength: "' + retObj.cmdLength + '" pdu: ' + pdu.toString('hex'));
log.error('larvitsmpp: lib/utils.js: pduToObj() - ' + err.message);
callback(err);
return;
tlvCmdId = pdu.readInt16BE(offset);
tlvLength = pdu.readInt16BE(offset + 2);
} catch (err) {
const manErr = new Error('Unable to read TLV at offset "' + offset + '", given cmdLength: "' + retObj.cmdLength + '" pdu: ' + pdu.toString('hex') + ', err: ' + err.message);
log.error(logPrefix + '' + manErr.message);
return cb(manErr);
}
if (defs.tlvsById[tlvCmdId] === undefined) {
@@ -313,7 +298,7 @@ function pduToObj(pdu, stupidNullByte, callback) {
'tagValue': tlvValue
};
log.verbose('larvitsmpp: lib/utils.js: pduToObj() - Unknown TLV found. Hex ID: ' + tlvCmdId.toString(16) + ' length: ' + tlvLength + ' hex value: ' + tlvValue);
log.verbose(logPrefix + 'Unknown TLV found. Hex ID: ' + tlvCmdId.toString(16) + ' length: ' + tlvLength + ' hex value: ' + tlvValue);
} else {
tlvValue = defs.tlvsById[tlvCmdId].type.read(pdu, offset + 4, tlvLength);
@@ -322,116 +307,112 @@ function pduToObj(pdu, stupidNullByte, callback) {
}
retObj.tlvs[defs.tlvsById[tlvCmdId].tag] = {
'tagId': tlvCmdId,
'tagName': defs.tlvsById[tlvCmdId].tag,
'tagValue': tlvValue
'tagId': tlvCmdId,
'tagName': defs.tlvsById[tlvCmdId].tag,
'tagValue': tlvValue
};
log.silly('larvitsmpp: lib/utils.js: pduToObj() - TLV found: "' + defs.tlvsById[tlvCmdId].tag + '" ID: "' + tlvCmdId + '" value: "' + tlvValue + '"');
log.silly(logPrefix + 'TLV found: "' + defs.tlvsById[tlvCmdId].tag + '" ID: "' + tlvCmdId + '" value: "' + tlvValue + '"');
}
offset = offset + 4 + tlvLength;
}
if (offset !== retObj.cmdLength && stupidNullByte === undefined) {
log.verbose('larvitsmpp: lib/utils.js: pduToObj() - Offset (' + offset + ') !== cmdLength (' + retObj.cmdLength + ') for seqNr: ' + retObj.seqNr + ' - retry with the stupid NULL byte for short_message');
log.verbose(logPrefix + 'Offset (' + offset + ') !== cmdLength (' + retObj.cmdLength + ') for seqNr: ' + retObj.seqNr + ' - retry with the stupid NULL byte for short_message');
pduToObj(pdu, true, callback);
return;
return pduToObj(pdu, true, cb);
}
if (offset !== retObj.cmdLength) {
log.warn('larvitsmpp: lib/utils.js: pduToObj() - Offset (' + offset + ') !== cmdLength (' + retObj.cmdLength + ') for seqNr: ' + retObj.seqNr);
log.warn(logPrefix + 'Offset (' + offset + ') !== cmdLength (' + retObj.cmdLength + ') for seqNr: ' + retObj.seqNr);
}
// Decode the short message if it is set and esm_class is 0
// The esm_class 0x40 (64 int) means the short_message have a UDH
// Thats why we return the short_message as a buffer
if (retObj.params.short_message !== undefined && (retObj.params.esm_class & 0x40) !== 0x40) {
retObj.params.short_message = decodeMsg(retObj.params.short_message, retObj.params.data_coding);
retObj.params.short_message = decodeMsg(retObj.params.short_message, retObj.params.data_coding);
}
log.debug('larvitsmpp: lib/utils.js: pduToObj() - Complete decoded PDU: ' + JSON.stringify(retObj));
log.debug(logPrefix + 'Complete decoded PDU: ' + JSON.stringify(retObj));
callback(null, retObj);
cb(null, retObj);
}
/**
* Transform an object to a PDU
*
* @param {object} obj - example {'cmdName': 'bind_transceiver_resp', 'cmdStatus': 'ESME_ROK', 'seqNr': 2} - to add parameters add a key 'params' as object
* @param {function} callback(err, pdu)
* @param {function} cb - cb(err, pdu)
*/
function objToPdu(obj, callback) {
var err = null,
shortMsg,
seqNr;
function objToPdu(obj, cb) {
const logPrefix = topLogPrefix + 'objToPdu() - ',
seqNr = parseInt(obj.seqNr);
// Check so the command is ok
if (defs.cmds[obj.cmdName] === undefined) {
err = new Error('larvitsmpp: lib/utils.js: objToPdu() - Invalid cmdName: "' + obj.cmdName + '"');
const err = new Error('Invalid cmdName: "' + obj.cmdName + '"');
log.warn(logPrefix + err.message);
return cb(err);
}
// Check so the command status is ok
if (obj.cmdStatus === undefined) {
// Default to OK
obj.cmdStatus = 'ESME_ROK';
obj.cmdStatus = 'ESME_ROK'; // Default to OK
}
if (defs.errors[obj.cmdStatus] === undefined) {
err = new Error('larvitsmpp: lib/utils.js: objToPdu() - Invalid cmdStatus: "' + obj.cmdStatus + '"');
const err = new Error('Invalid cmdStatus: "' + obj.cmdStatus + '"');
log.warn(logPrefix + err.message);
return cb(err);
}
// Check so seqNr is ok
seqNr = parseInt(obj.seqNr);
if (isNaN(seqNr)) {
err = new Error('larvitsmpp: lib/utils.js: objToPdu() - Invalid seqNr, is not an interger: "' + obj.seqNr + '"');
} else if (seqNr > 2147483646) {
err = new Error('larvitsmpp: lib/utils.js: objToPdu() - Invalid seqNr, maximum size of 2147483646 (0x7fffffff) exceeded.');
const err = new Error('Invalid seqNr, is not an interger: "' + obj.seqNr + '"');
log.warn(logPrefix + err.message);
return cb(err);
}
// If error is found, do not proceed with execution
if (err !== null) {
log.warn(err.message);
callback(err);
return;
if (seqNr > 2147483646) {
const err = new Error('Invalid seqNr, maximum size of 2147483646 (0x7fffffff) exceeded.');
log.warn(logPrefix + err.message);
return cb(err);
}
// Params must be an object
if (obj.params === undefined) {
obj.params = {};
obj.params = {};
}
// If param "short_message" exists, encode it and set parameter "data_coding" accordingly
if (obj.params.short_message !== undefined && ! Buffer.isBuffer(obj.params.short_message)) {
let shortMsg;
// Detect encoding if is not set already
if (obj.params.data_coding === undefined) {
obj.params.data_coding = defs.encodings.detect(obj.params.short_message);
log.silly('larvitsmpp: lib/utils.js: objToPdu() - data_coding "' + obj.params.data_coding + '" detected');
log.silly(logPrefix + 'data_coding "' + obj.params.data_coding + '" detected');
// Now set the hex value
obj.params.data_coding = defs.consts.ENCODING[obj.params.data_coding];
obj.params.data_coding = defs.consts.ENCODING[obj.params.data_coding];
}
// Acutally encode the string
shortMsg = obj.params.short_message;
obj.params.short_message = encodeMsg(obj.params.short_message);
obj.params.sm_length = obj.params.short_message.length;
log.silly('larvitsmpp: lib/utils.js: objToPdu() - encoding message "' + shortMsg + '" to "' + obj.params.short_message.toString('hex') + '"');
shortMsg = obj.params.short_message;
obj.params.short_message = encodeMsg(obj.params.short_message);
obj.params.sm_length = obj.params.short_message.length;
log.silly(logPrefix + 'Encoding message "' + shortMsg + '" to "' + obj.params.short_message.toString('hex') + '"');
}
log.debug('larvitsmpp: lib/utils.js: objToPdu() - Complete object to encode: ' + JSON.stringify(obj));
log.debug(logPrefix + 'Complete object to encode: ' + JSON.stringify(obj));
calcCmdLength(obj, function(err, cmdLength) {
if (err) {
callback(err);
return;
}
calcCmdLength(obj, function (err, cmdLength) {
if (err) return cb(err);
writeBuffer(obj, cmdLength, callback);
writeBuffer(obj, cmdLength, cb);
});
}
@@ -442,93 +423,76 @@ function objToPdu(obj, callback) {
* @param {string} status - see list at defs.errors - defaults to 'ESME_ROK' - no error (OPTIONAL)
* @param {object} [params]
* @param {object} [tlvs]
* @param {function} [callback(err, pduBuffer)]
* @param {function} [cb(err, pduBuffer)]
*/
function pduReturn(pdu, status, params, tlvs, callback) {
var err = null,
retPdu = {},
param;
function pduReturn(pdu, status, params, tlvs, cb) {
const logPrefix = topLogPrefix + 'pduReturn() - ',
retPdu = {};
let err = null;
if (Buffer.isBuffer(pdu)) {
log.silly('larvitsmpp: lib/utils.js: pduReturn() - ran with pdu as buffer, run pduToObj() and retry');
log.silly(logPrefix + 'Ran with pdu as buffer, run pduToObj() and retry');
pduToObj(pdu, function(err, pduObj) {
if (err) {
callback(err);
return;
}
pduToObj(pdu, function (err, pduObj) {
if (err) return cb(err);
pduReturn(pduObj, status, params, tlvs, callback);
pduReturn(pduObj, status, params, tlvs, cb);
});
return;
}
log.silly('larvitsmpp: lib/utils.js: pduReturn() - ran');
log.silly(logPrefix + 'ran');
if (typeof tlvs === 'function') {
callback = tlvs;
tlvs = undefined;
cb = tlvs;
tlvs = undefined;
}
if (typeof params === 'function') {
callback = params;
params = {};
tlvs = undefined;
cb = params;
params = {};
tlvs = undefined;
}
if (typeof status === 'function') {
callback = status;
status = 'ESME_ROK';
params = {};
tlvs = undefined;
cb = status;
status = 'ESME_ROK';
params = {};
tlvs = undefined;
}
if (status === undefined) {
status = 'ESME_ROK';
status = 'ESME_ROK';
}
if (callback === undefined) {
callback = function() {};
if (cb === undefined) {
cb = function () {};
}
if (params === undefined) {
params = {};
params = {};
}
if (pdu === undefined) {
err = new Error('larvitsmpp: lib/utils.js: pduReturn() - PDU is undefined, cannot create response PDU');
}
if (pdu.cmdName === undefined) {
err = new Error('larvitsmpp: lib/utils.js: pduReturn() - pdu.cmdName is undefined, cannot create response PDU');
}
if (pdu.seqNr === undefined) {
err = new Error('larvitsmpp: lib/utils.js: pduReturn() - pdu.seqNr is undefined, cannot create response PDU');
}
if (err === null && defs.errors[status] === undefined) {
err = new Error('larvitsmpp: lib/utils.js: pduReturn() - Invalid status: "' + status + '"');
}
if (err === null && defs.cmds[pdu.cmdName + '_resp'] === undefined) {
err = new Error('larvitsmpp: lib/utils.js: pduReturn() - This command does not have a response listed. Given command: "' + pdu.cmdName + '"');
}
if (pdu === undefined) err = new Error('PDU is undefined, cannot create response PDU');
if (pdu.cmdName === undefined) err = new Error('pdu.cmdName is undefined, cannot create response PDU');
if (pdu.seqNr === undefined) err = new Error('pdu.seqNr is undefined, cannot create response PDU');
if (err === null && defs.errors[status] === undefined) err = new Error('Invalid status: "' + status + '"');
if (err === null && defs.cmds[pdu.cmdName + '_resp'] === undefined) err = new Error('This command does not have a response listed. Given command: "' + pdu.cmdName + '"');
if (err !== null) {
log.warn(err.message);
callback(err);
return;
log.warn(logPrefix + err.message);
return cb(err);
}
retPdu.cmdName = pdu.cmdName + '_resp';
retPdu.cmdStatus = status;
retPdu.seqNr = pdu.seqNr;
retPdu.params = params;
retPdu.tlvs = tlvs;
retPdu.cmdName = pdu.cmdName + '_resp';
retPdu.cmdStatus = status;
retPdu.seqNr = pdu.seqNr;
retPdu.params = params;
retPdu.tlvs = tlvs;
// Populate parameters that should exist in the response
for (param in defs.cmds[pdu.cmdName + '_resp'].params) {
for (const param in defs.cmds[pdu.cmdName + '_resp'].params) {
// Do not override the manually supplied parameters
if (retPdu.params[param] === undefined) {
@@ -536,9 +500,7 @@ function pduReturn(pdu, status, params, tlvs, callback) {
}
}
objToPdu(retPdu, function(err, retPdu) {
callback(err, retPdu);
});
objToPdu(retPdu, cb);
}
/**
@@ -548,7 +510,7 @@ function pduReturn(pdu, status, params, tlvs, callback) {
* @return {string}
*/
function smppDate(jsDateObj) {
var uglyStr = '';
let uglyStr = '';
uglyStr += jsDateObj.getFullYear().toString().substring(2);
@@ -606,20 +568,20 @@ function bitCount(msg, encoding) {
* @return array of buffers
*/
function splitMsg(msg, encoding) {
var msgPart = '',
msgs = [],
encoding = encoding || defs.encodings.detect(msg),
totBitCount = bitCount(msg, encoding),
udh,
i,
i2,
partCharLimit;
const resolvedEncoding = encoding || defs.encodings.detect(msg),
totBitCount = bitCount(msg, resolvedEncoding),
logPrefix = topLogPrefix + 'splitMsg() - ',
msgs = [];
let msgPart = '',
partCharLimit,
i2;
// A single message could contain up to 1120 bits
// Return directly if the message fits into that
if (totBitCount < 1121) {
log.silly('larvitsmpp: lib/utils.js: splitMsg() - bitCount below 1121 (' + totBitCount + ') return only one part');
return [defs.encodings[encoding].encode(msg)];
log.silly(logPrefix + 'bitCount below 1121 (' + totBitCount + ') return only one part');
return [defs.encodings[resolvedEncoding].encode(msg)];
}
bundleMsgId ++; // This will identify this message "bundle"
@@ -628,17 +590,16 @@ function splitMsg(msg, encoding) {
bundleMsgId = 1;
}
log.silly('larvitsmpp: lib/utils.js: splitMsg() - bundleMsgId set to ' + bundleMsgId);
log.silly(logPrefix + 'bundleMsgId set to ' + bundleMsgId);
if (encoding === 'ASCII') {
if (resolvedEncoding === 'ASCII') {
partCharLimit = 153;
} else {
partCharLimit = 67;
}
i = 0;
i2 = 0;
while (msg[i] !== undefined) {
i2 = 0;
for (let i = 0; msg[i] !== undefined; i ++) {
msgPart += msg[i];
i2 ++;
@@ -650,7 +611,7 @@ function splitMsg(msg, encoding) {
i2 = 0;
// Add this msgPart minus the last character to the msgs array as an encoded buffer
msgs.push(defs.encodings[encoding].encode(msgPart.slice(0, - 1)));
msgs.push(defs.encodings[resolvedEncoding].encode(msgPart.slice(0, - 1)));
// Reset msgPart
msgPart = '';
@@ -658,30 +619,24 @@ function splitMsg(msg, encoding) {
// Put i back one to account for the last character we removed from the msgPart
i --;
}
i ++;
}
// Add the last msgPart to the msgs array
msgs.push(defs.encodings[encoding].encode(msgPart));
msgs.push(defs.encodings[resolvedEncoding].encode(msgPart));
// Add the UDH (http://en.wikipedia.org/wiki/Concatenated_SMS)
i = 0;
while (msgs[i] !== undefined) {
for (let i = 0; msgs[i] !== undefined; i ++) {
// Create the UDH buffer
udh = new Buffer([
0x05, // Length of User Data Header, in this case 05.
0x00, // Information Element Identifier, equal to 00 (Concatenated short messages, 8-bit reference number)
0x03, // Length of the header, excluding the first two fields; equal to 03
bundleMsgId, // CSMS reference number, must be same for all the SMS parts in the CSMS
msgs.length, // Total number of parts. The value shall remain constant for every short message which makes up the concatenated short message. If the value is zero then the receiving entity shall ignore the whole information element
i + 1 // This part's number in the sequence. The value shall start at 1 and increment for every short message which makes up the concatenated short message.
const udh = new Buffer([
0x05, // Length of User Data Header, in this case 05.
0x00, // Information Element Identifier, equal to 00 (Concatenated short messages, 8-bit reference number)
0x03, // Length of the header, excluding the first two fields; equal to 03
bundleMsgId, // CSMS reference number, must be same for all the SMS parts in the CSMS
msgs.length, // Total number of parts. The value shall remain constant for every short message which makes up the concatenated short message. If the value is zero then the receiving entity shall ignore the whole information element
i + 1 // This part's number in the sequence. The value shall start at 1 and increment for every short message which makes up the concatenated short message.
]);
msgs[i] = Buffer.concat([udh, msgs[i]]);
i ++;
msgs[i] = Buffer.concat([udh, msgs[i]]);
}
return msgs;
@@ -692,83 +647,79 @@ function splitMsg(msg, encoding) {
* This must be called from an sms object context
*
* @param {string} status - see list at defs.consts.MESSAGE_STATE - defaults to 'DELIVERED'
* @param {function} callback(err, retPdu, dlrPduObj)
* @param {function} cb - cb(err, retPdu, dlrPduObj)
*/
function smsDlr(status, callback) {
var shortMessage,
dlrPduObj,
err,
sms = this;
function smsDlr(status, cb) {
const logPrefix = topLogPrefix + 'smsDlr() - ',
dlrPduObj = {},
sms = this;
let shortMessage = 'id:' + sms.smsId + ' sub:001 ';
if (typeof status === 'function') {
callback = status;
status = undefined;
cb = status;
status = undefined;
}
if (status === undefined || status === true || status === 2 || status === 'true') {
status = 2;
status = 2;
} else if (defs.consts.MESSAGE_STATE[status] !== undefined) {
status = defs.consts.MESSAGE_STATE[status];
status = defs.consts.MESSAGE_STATE[status];
} else if (defs.constsById.MESSAGE_STATE[status]) {
status = parseInt(status);
status = parseInt(status);
} else {
status = 5; // UNDELIVERABLE
status = 5; // UNDELIVERABLE
}
if (typeof callback !== 'function') {
callback = function() {};
if (typeof cb !== 'function') {
cb = function () {};
}
if (sms.smsId === undefined) {
err = new Error('Trying to send DLR with no smsId.');
log.warn('larvitsmpp: lib/utils.js: smsDlr() - ' + err.message);
callback(err);
return;
const err = new Error('Trying to send DLR with no smsId.');
log.warn(logPrefix + err.message);
return cb(err);
}
shortMessage = 'id:' + sms.smsId + ' sub:001 ';
if (status === 2) {
shortMessage += 'dlvrd:1 ';
shortMessage += 'dlvrd:1 ';
} else {
shortMessage += 'dlvrd:0 ';
shortMessage += 'dlvrd:0 ';
}
shortMessage += 'submit date:' + smppDate(sms.submitTime);
shortMessage += ' done date:' + smppDate(new Date());
shortMessage += 'submit date:' + smppDate(sms.submitTime);
shortMessage += ' done date:' + smppDate(new Date());
if (status === 2) {
shortMessage += ' stat:DELIVRD err:0 text:xxx';
shortMessage += ' stat:DELIVRD err:0 text:xxx';
} else {
shortMessage += ' stat:UNDELIVERABLE err:1 text:xxx';
shortMessage += ' stat:UNDELIVERABLE err:1 text:xxx';
}
log.verbose('larvitsmpp: lib/utils.js: smsDlr() - Sending DLR message: "' + shortMessage + '"');
log.verbose(logPrefix + 'Sending DLR message: "' + shortMessage + '"');
dlrPduObj = {
'cmdName': 'deliver_sm',
'params': {
'source_addr': sms.from,
'destination_addr': sms.to,
'esm_class': 4,
'short_message': shortMessage
dlrPduObj.cmdName = 'deliver_sm';
dlrPduObj.params = {
'source_addr': sms.from,
'destination_addr': sms.to,
'esm_class': 4,
'short_message': shortMessage
};
dlrPduObj.tlvs = {
'receipted_message_id': {
'tagId': 0x001E,
'tagName': 'receipted_message_id',
'tagValue': sms.smsId
},
'tlvs': {
'receipted_message_id': {
'tagId': 0x001E,
'tagName': 'receipted_message_id',
'tagValue': sms.smsId
},
'message_state': {
'tagId': 0x0427,
'tagName': 'message_state',
'tagValue': status
}
'message_state': {
'tagId': 0x0427,
'tagName': 'message_state',
'tagValue': status
}
};
sms.session.send(dlrPduObj, false, function(err, retPdu) {
callback(err, retPdu, dlrPduObj);
sms.session.send(dlrPduObj, false, function (err, retPdu) {
cb(err, retPdu, dlrPduObj);
});
}