Skip to content

Commit

Permalink
Will retry creating client indefinitly till success on start
Browse files Browse the repository at this point in the history
Signed-off-by: Yilun <[email protected]>
  • Loading branch information
yilunzhang committed Jul 1, 2020
1 parent 15cf40d commit 9526254
Show file tree
Hide file tree
Showing 4 changed files with 234 additions and 181 deletions.
213 changes: 120 additions & 93 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ let argv = _yargs.default.command('$0', 'start nshd').command('addr', 'show addr
}).help('help').alias('h', 'help').wrap(Math.min(120, _yargs.default.terminalWidth())).argv;

const isWindows = _os.default.platform() === 'win32';
const clientConnectTimeout = 20000;
const pingInterval = 20000;
const forcePingInterval = 60000;
const ptyCols = 120;
Expand Down Expand Up @@ -222,12 +223,6 @@ function getAuthorizedUser(src) {
return null;
}

const client = new _nknSdk.default.MultiClient({
originalClient: true,
seed: wallet.getSeed(),
identifier: identifier
});

class Session {
constructor(client, remoteAddr, options) {
this.client = client;
Expand Down Expand Up @@ -286,10 +281,9 @@ class Session {

}

let sessions = {};
client.onConnect(() => {
console.log('Listening at', client.addr);
var sessions = {};

function keepalive(client) {
for (let c of Object.values(client.clients)) {
setInterval(function () {
try {
Expand Down Expand Up @@ -371,112 +365,145 @@ client.onConnect(() => {
}, 3000);
});
}, forcePingInterval);
});
client.onMessage(async ({
src,
payload,
payloadType,
isEncrypted
}) => {
if (!isEncrypted) {
console.log('Received unencrypted msg from', src);
return false;
}
}

if (src.endsWith(client.getPublicKey()) && !payload) {
return;
}
(async () => {
let client;

let au = getAuthorizedUser(src);
while (true) {
try {
client = new _nknSdk.default.MultiClient({
originalClient: true,
seed: wallet.getSeed(),
identifier: identifier
});
} catch (e) {
console.error('Create client error:', e);
continue;
}

if (!au) {
console.log('Received msg from unauthorized sender', src);
return false;
}
try {
await new Promise((resolve, reject) => {
client.onConnect(resolve);
setTimeout(reject, clientConnectTimeout);
});
} catch (e) {
console.error('Client connect timeout');
client.close().catch(console.error);
continue;
}

if (payloadType !== _nknSdk.default.pb.payloads.PayloadType.TEXT) {
console.log('Received msg with wrong payload type from', src);
return false;
break;
}

let msg = JSON.parse(payload);
console.log('Listening at', client.addr);
keepalive(client);
client.onMessage(async ({
src,
payload,
payloadType,
isEncrypted
}) => {
if (!isEncrypted) {
console.log('Received unencrypted msg from', src);
return false;
}

if (msg.timestamp && Date.now() - Date.parse(msg.timestamp) > 60000) {
return false;
}
if (src.endsWith(client.getPublicKey()) && !payload) {
return;
}

let options = {
uid: au.uid,
gid: au.gid
};
let au = getAuthorizedUser(src);

if (session && msg.resize) {
if (!sessions[src]) {
sessions[src] = new Session(client, src, options);
if (!au) {
console.log('Received msg from unauthorized sender', src);
return false;
}

sessions[src].resize(msg.resize);
console.log('Resize to', msg.resize, 'from', src);
}
if (payloadType !== _nknSdk.default.pb.payloads.PayloadType.TEXT) {
console.log('Received msg with wrong payload type from', src);
return false;
}

let cmd = msg.cmd || msg.content;
let msg = JSON.parse(payload);

if (!cmd) {
return false;
}
if (msg.timestamp && Date.now() - Date.parse(msg.timestamp) > 60000) {
return false;
}

let options = {
uid: au.uid,
gid: au.gid
};

if (session && msg.resize) {
if (!sessions[src]) {
sessions[src] = new Session(client, src, options);
}

console.log('Execute cmd' + (logCmd ? ' ' + cmd : ''), 'from', src);
sessions[src].resize(msg.resize);
console.log('Resize to', msg.resize, 'from', src);
}

if (msg.execSync) {
options.timeout = msg.execTimeout || syncExecTimeout;
let stdout, stderr;
let cmd = msg.cmd || msg.content;

try {
stdout = (0, _child_process.execSync)(cmd, options).toString();
} catch (e) {
stderr = e.stderr ? e.stderr.toString() : e.error;
if (!cmd) {
return false;
}

return JSON.stringify({
stdout,
stderr
});
} else {
options.timeout = msg.execTimeout || asyncExecTimeout;
console.log('Execute cmd' + (logCmd ? ' ' + cmd : ''), 'from', src);

if (session && !msg.content) {
if (!sessions[src]) {
sessions[src] = new Session(client, src, options);
if (msg.execSync) {
options.timeout = msg.execTimeout || syncExecTimeout;
let stdout, stderr;

try {
stdout = (0, _child_process.execSync)(cmd, options).toString();
} catch (e) {
stderr = e.stderr ? e.stderr.toString() : e.error;
}

sessions[src].write(cmd);
return JSON.stringify({
stdout,
stderr
});
} else {
(0, _child_process.exec)(cmd, options, async (error, stdout, stderr) => {
let res;

if (msg.content) {
// d-chat protocol
res = {
content: "```\n" + (stdout || stderr) + "\n```",
contentType: "text",
timestamp: new Date().toUTCString(),
isPrivate: true
};
} else {
res = {
stdout,
stderr
};
}
options.timeout = msg.execTimeout || asyncExecTimeout;

try {
await client.send(src, JSON.stringify(res), {
noReply: true
});
} catch (e) {
console.error("Send msg error:", e);
if (session && !msg.content) {
if (!sessions[src]) {
sessions[src] = new Session(client, src, options);
}
});

sessions[src].write(cmd);
} else {
(0, _child_process.exec)(cmd, options, async (error, stdout, stderr) => {
let res;

if (msg.content) {
// d-chat protocol
res = {
content: "```\n" + (stdout || stderr) + "\n```",
contentType: "text",
timestamp: new Date().toUTCString(),
isPrivate: true
};
} else {
res = {
stdout,
stderr
};
}

try {
await client.send(src, JSON.stringify(res), {
noReply: true
});
} catch (e) {
console.error("Send msg error:", e);
}
});
}
}
}
});
});
})();
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nkn-shell-daemon",
"version": "1.0.9",
"version": "1.1.0",
"description": "NKN Shell Daemon",
"main": "nshd.js",
"bin": {
Expand Down Expand Up @@ -28,7 +28,7 @@
},
"homepage": "https://nkn.org",
"dependencies": {
"nkn-sdk": "^1.1.6",
"nkn-sdk": "^1.1.7",
"node-pty": "^0.9.0",
"yargs": "^14.2.0"
},
Expand Down
Loading

0 comments on commit 9526254

Please sign in to comment.