-
Notifications
You must be signed in to change notification settings - Fork 81
/
index.js
284 lines (217 loc) · 7.57 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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/////////////////////////////////////////////////////////////
// Prey Node.js Client
// Written by Tomás Pollak
// (c) 2011-2014, Fork Ltd. - http://forkhq.com
// Licensed under the GPLv3
/////////////////////////////////////////////////////////////
"use strict";
var common = require('./common'),
updater = require('./updater'),
hooks = require('./hooks'),
plugin = require('./plugin'),
commands = require('./commands'),
actions = require('./actions'),
triggers = require('./triggers'),
reports = require('./reports'),
providers = require('./providers'),
logo = require('./utils/logo');
var config = common.config,
system = common.system,
logger = common.logger,
program = common.program,
helpers = common.helpers,
exceptions = common.exceptions,
plugins = common.plugins,
watch_list = ['connection', 'network', 'power'],
running = false,
connecting = false, // semaphore for connection_down()
started_at = null,
running_as = null;
var loaded_plugins = [];
////////////////////////////////////////////////////////////////////
// helpers
////////////////////////////////////////////////////////////////////
var is_running = function() {
return running;
}
var write_header = function() {
function write(str, color) {
logger.write(logger.paint(str, color))
}
write('\n' + logo, 'grey');
var title = '\n PREY ' + common.version + ' spreads its wings!';
write(title, 'light_red');
write(' Current time: ' + started_at.toString(), 'bold');
var info = ' Running with PID ' + process.pid + ' as ' + running_as + ' over Node.js ' + process.version;
info += [' on a', process.arch, common.os_name, 'system', '(' + common.os_release + ')'].join(' ') + '\n';
write(info);
}
////////////////////////////////////////////////////////////////////
// bootup
////////////////////////////////////////////////////////////////////
var run = function() {
if (running) return;
running = true;
if (program.run)
return run_from_command_line();
process.title = 'prx'; // stealth camouflage FTW!
// env.RUNNING_USER is user by the updater to check if it was called by the agent
running_as = process.env.RUNNING_USER = common.system.get_running_user();
started_at = new Date();
write_header();
if (program.mode == 'console')
return load_plugin('console');
if (!config.get('auto_update'))
return boot();
updater.check(function(err, new_version) {
if (err && err.code != 'NO_VERSIONS_SUPPORT')
handle_error(err);
if (!new_version) return boot();
logger.warn('Updated to version ' + new_version + '! Shutting down.');
});
}
var boot = function() {
hooks.on('error', handle_error);
load_plugins(plugins.get_enabled(), function(err) {
if (err) throw err;
commands.run_stored(); // reload any actions previously in execution
commands.start_watching(); // add/remove from list when started or stopped
if (config.get('auto_update'))
updater.check_every(60 * 60 * 1000); // check every one hour for new releases
logger.info('Initialized.');
// We initialize the triggers after all the plugins have been enabled,
// so the plugins that subscribed to events triggered by the watchers
// work as intended: ie. control-panel's long-polling.
triggers.watch(watch_list);
});
};
var reload = function() {
logger.warn('Reloading!')
config.reload();
unload_plugins(function() {
load_plugins(plugins.get_enabled(), function(err) {
if (err) handle_error(err);
logger.notice('Reload complete.');
});
});
}
var load_plugins = function(list, cb) {
if (!list || !list[0])
return cb(new Error('No plugins set!'));
var count = list.length,
errors = [];
var done = function(err, name) {
if (err) {
handle_error(err, name);
errors.push(err);
}
--count || finished();
}
var finished = function() {
logger.info(list.length + ' plugins loaded with ' + errors.length + ' errors.')
var success = list.length > errors.length; // at least one succeeded
cb(!success && errors[0]);
}
list.forEach(function(name) {
load_plugin(name, done);
});
}
var load_plugin = function(name, cb) {
plugin.load(name, function(err) {
if (err) {
if (err.code == 'MODULE_NOT_FOUND')
return plugins.remove(name, cb);
return cb && cb(err, name);
}
logger.info('Plugin loaded: ' + name);
loaded_plugins.push(name);
cb && cb(null, name);
})
}
////////////////////////////////////////////////////////////////////
// commands, response
////////////////////////////////////////////////////////////////////
var run_from_command_line = function() {
if (!program.debug) logger.pause();
hooks.on('data', console.log);
hooks.on('error', console.log);
hooks.on('report', console.log);
var parsed = commands.parse(program.run);
if (!parsed)
return console.log('Invalid command.');
commands.perform(parsed[1]);
}
////////////////////////////////////////////////////////////////////
// hooks and error handling
////////////////////////////////////////////////////////////////////
var handle_error = function(err, source) {
logger.error(err, source);
if (is_network_error(err)) // no connection
connection_down();
else if (config.get('send_crash_reports'))
exceptions.send(err);
}
var is_network_error = function(err) {
var codes = ['ENETDOWN', 'ENETUNREACH', 'EADDRINFO', 'ENOTFOUND'];
return codes.indexOf(err.code) !== -1;
}
var connection_down = function() {
if (connecting || !config.get('auto_connect'))
return false;
connecting = true;
logger.notice('Lost connection. Trying to connect...');
system.reconnect(function(err, out) {
if (err) hooks.trigger('error', err);
connecting = false;
});
}
////////////////////////////////////////////////////////////////////
// shutdown
////////////////////////////////////////////////////////////////////
var shutdown = function(cb) {
// if a plugin was loaded after unload_plugins() was called
// we need to be able to call unload() on it again. so we need to comment this.
// if (!running) return;
running = false;
commands.stop_watching();
updater.stop_checking();
logger.debug('Unloading plugins.');
unload_plugins(cb);
logger.debug('Stopping actions.');
actions.stop_all();
logger.debug('Unloading hooks.');
hooks.unload();
logger.debug('Canceling reports.');
reports.cancel_all();
logger.debug('Unwatching triggers.');
triggers.unwatch();
logger.debug('Cleaning up temporary files.');
providers.remove_files();
}
var unload_plugins = function(cb) {
var count = loaded_plugins.length;
loaded_plugins.forEach(unload);
function unload(name) {
logger.debug('Unloading ' + name + ' plugin...')
plugin.unload(name, function(err) {
done(err, name);
});
}
function done(err, name) {
logger.debug('Plugin unloaded: ' + name);
// MUTANT THING HERE. for some reason if we uncomment
// these two lines, some (and only some) plugins will fail to be unloaded.
// in other words, it makes the unload() function complete vanish without
// leaving any traces. try/catch doesn't help.
// var index = loaded_plugins.indexOf(name);
// loaded_plugins.splice(index, 1);
--count || (cb && cb());
}
}
////////////////////////////////////////////////////////////////////
// exports
////////////////////////////////////////////////////////////////////
exports.run = run;
exports.reload = reload;
exports.running = is_running;
exports.shutdown = shutdown;