-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
217 lines (175 loc) · 6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
var EventEmitter = require('events').EventEmitter,
util = require('util'),
execa = require('execa'),
path = require('path'),
querystring = require('querystring'),
async = require('async'),
circularJSON = require('circular-json');
var callbacks = {};
var magic = "=%5a$ng*a8=";
var magicData = "";
var debugPort = 5859;
function Sandbox(file, id, params, apiHandler, debug) {
EventEmitter.call(this);
if (typeof file !== "string" || file === undefined || file === null) {
throw new Error("First argument should be a path to file to launch in vm");
}
if (typeof id !== "string" || id === undefined || id === null) {
throw new Error("Second argument should be a id of dapp");
}
if (typeof apiHandler !== "function" || apiHandler === undefined || apiHandler === null) {
throw new Error("Third argument should be a api hanlder callback");
}
this.params = params;
this.file = file;
this.id = id;
this.apiHandler = apiHandler;
this.child = null;
this.queue = null;
this.debug = debug || false;
}
util.inherits(Sandbox, EventEmitter);
Sandbox.prototype._parse = function (data) {
try {
var json = JSON.parse(data);
} catch (e) {
return this._onError(new Error("Can't parse JSON response from DApp: \n" + data + "\n" + e.toString()));
}
if (json.callback_id === null || json.callback_id === undefined) {
return this._onError(new Error("Incorrect response from vm, missed callback id field"));
}
try {
var callback_id = parseInt(json.callback_id);
} catch (e) {
return this._onError(new Error("Incorrect callback_id field, callback_id should be a number"));
}
if (isNaN(callback_id)) {
return this._onError(new Error("Incorrect callback_id field, callback_id should be a number"));
}
if (json.type == "dapp_response") {
var callback = callbacks[callback_id];
if (!callback) {
return this._onError(new Error("Shift can't find callback_id from vm"));
}
var error = json.error;
var response = json.response;
setImmediate(callback, error, response);
} else if (json.type == "dapp_call") {
var message = json.message;
if (message === null || message === undefined) {
return this._onError(new Error("Shift can't find message for request from vm"));
}
message.dappid = this.id;
this.apiHandler(message, function (err, response) {
var responseObj = {
type: "lisk_response",
callback_id: callback_id,
error: err,
response: response || {}
};
try {
var responseString = JSON.stringify(responseObj);
} catch (e) {
return this._onError(new Error("Can't make response: " + e.toString()));
}
this.queue.push({message: responseString + magic});
}.bind(this));
} else {
this._onError(new Error("Incorrect response type from vm"));
}
}
Sandbox.prototype.run = function () {
var params = [this.file].concat(this.params);
if (this.debug) {
params.unshift("--debug=" + debugPort);
console.log("DebugPort " + params[1] + " : " + debugPort++);
}
// Child process
this.child = execa(path.join(__dirname, "../../nodejs/node"), params, {
stdio: ['pipe', 'pipe', 'pipe', 'pipe', 'pipe'],
maxBuffer: 1024 * 20000 * 2 // 2MB
});
var self = this;
this.queue = async.queue(function (task, callback) {
try {
var size = Buffer.byteLength(task.message, 'utf8');
if (size > 16000) {
console.log("incoming " + (size) + " bytes");
}
self.child.stdio[3].write(task.message);
} catch (e) {
console.log(e.toString())
} finally {
setTimeout(callback, 10);
}
}, 1);
// Catch errors...
this.child.on('error', this._onError.bind(this));
this.child.stdout.on('error', this._onError.bind(this)); // [0] Catch standard output error
this.child.stdin.on('error', this._onError.bind(this)); // [1] Catch standard input error
this.child.stderr.on('error', this._onError.bind(this)); // [2] Catch standard error
this.child.stdio[3].on('error', this._onError.bind(this));
this.child.stdio[4].on('error', this._onError.bind(this));
this.child.stdio[4].on('data', this._listen.bind(this));
this.child.stdio[1].on('data', this._debug.bind(this));
this.child.stdio[2].on('data', this._debug.bind(this));
}
Sandbox.prototype.setApi = function (apiHandler) {
if (typeof apiHandler != "function" || apiHandler === null || apiHandler === undefined) {
throw new Error("First argument should be a function");
}
this.apiHandler = apiHandler;
}
Sandbox.prototype.sendMessage = function (message, callback) {
var callback_id = Object.keys(callbacks).length + 1;
var messageObj = {
callback_id: callback_id,
type: "lisk_call",
message: message
};
try {
var messageString = circularJSON.stringify(messageObj);
} catch (e) {
return setImmediate(callback, "Can't stringify message: " + e.toString());
}
this.queue.push({message: messageString + magic});
callbacks[callback_id] = callback;
}
Sandbox.prototype.exit = function () {
if (this.child) {
this.child.kill();
this.emit("exit");
}
}
Sandbox.prototype._debug = function (data) {
var p = this.file.split(path.sep);
if (p.length>2 && p[p.length-3]=="dapps")
console.log("APP " + p[p.length-2] + ":"); // prefix with APPID
else
console.log("APP " + this.file + ":");
console.log(data.toString('utf8'));
}
Sandbox.prototype._onError = function (err, exit) {
console.log(err.stack)
if (exit) this.exit();
this.emit("error", err);
}
Sandbox.prototype._listen = function (dataraw) {
var data = querystring.unescape(dataraw.toString('utf8'));
magicData += data;
if (data.substring(data.length - 11) == magic) {
var fullMessage = magicData;
magicData = "";
var parts = fullMessage.split(magic);
parts.pop();
parts.forEach(function (jsonmessage) {
// Fix escaping of: comma, brackets, quote
jsonmessage = jsonmessage.replace(/%2C/g, ',').replace(/ % 2 C/g, ',');
jsonmessage = jsonmessage.replace(/%5B/g, '[').replace(/ % 5 B/g, '[');
jsonmessage = jsonmessage.replace(/%5D/g, ']').replace(/ % 5 D/g, ']');
jsonmessage = jsonmessage.replace(/%22/g, '"').replace(/ % 2 2/g, '"');
this._parse(jsonmessage);
}.bind(this));
}
}
module.exports = Sandbox;