This repository was archived by the owner on Oct 27, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
453 lines (235 loc) · 8.39 KB
/
server.js
File metadata and controls
453 lines (235 loc) · 8.39 KB
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/*!
* @name Backdroid v1.0.1 Beta
* @autor yeikos
* Copyright 2012 - http://www.yeikos.com - https://github.com/yeikos/backdroid
* GNU General Public License
* http://www.gnu.org/licenses/gpl-3.0.txt
*/
var Express = require('express'),
SocketIO = require('socket.io'),
Crypto = require('crypto'),
Path = require('path'),
Aes = require('./aes.js');
var Public = {
aes: Aes(),
sockets: [],
database: [],
setCommand: function(name, value, send, success) {
if (typeof name != 'string' || !name.length)
return { error: 'name' };
// Si el comando es correcto lo añadimos
Public.database.push({
// Identificador único del comando
id: Crypto.randomBytes(16).toString('hex'),
// Fecha actual
date: parseInt(new Date()/1000, 10),
// Nombre del comando
command: name,
// Valor del comando
value: value,
// Marcador de enviado
sent: false,
// Función ejecutada cuando el cliente recibe el comando
onSend: send,
// Función ejecutada cuando el cliente envia una respuesta
onSuccess: success,
// Contenedor de posibles respuestas
response: []
});
return { success: true };
},
createPanelServer: function(option) {
// Las opciones son obligatorias
if (!option || typeof option != 'object')
throw 'Error backdroid.createPanelServer: option';
if (typeof option.public_path != 'string')
throw 'Error backdroid.createPanelServer: option.public_path';
if (typeof option.password != 'string' || !option.password.length)
throw 'Error backdroid.createPanelServer: option.password';
if (isNaN(option.port) || (option.port%1) || option.port <= 0)
throw 'Error backdroid.createPanelServer: option.port';
if (isNaN(option.ws_port) || (option.ws_port%1) || option.ws_port <= 0)
throw 'Error backdroid.createPanelServer: option.ws_port';
/*if (typeof option.ws_encryption_password != 'string' || !option.ws_encryption_password.length)
throw 'Error backdroid.createPanelServer: option.ws_encryption_password';*/
// Servidor HTTP
var httpServer = Express.createServer().listen(option.port),
// Servidor WebSocket
wsServer = SocketIO.listen(option.ws_port);
// Configuración HTTP
if (option.debug)
httpServer.use(Express.logger({ format: '[PANEL] :method :url' }));
httpServer.use(Express.bodyParser());
httpServer.use(httpServer.router);
httpServer.use(Express['static'](Path.dirname(process.mainModule.filename) + '/' + option.public_path));
httpServer.all('/', function(request, response) {
response.redirect('/index.html');
});
// Configuración WebSocket
wsServer.set('log level', 1).sockets.on('connection', function(socket) {
// Identificación
socket.on('login', function(data) {
if (!data || data.password != option.password)
return socket.emit('auth', { error: 'password' });
Public.sockets.push(socket);
socket.authed = true;
socket.emit('auth', { success: true });
socket.emit('commands', { items: Public.database });
});
// Obtención de todos los comandos
socket.on('getCommands', function() {
// Es necesario estár identificado
if (!socket.authed)
return socket.emit('auth', { error: true });
// Enviamos la base de datos
socket.emit('commands', { items: Public.database });
});
// Inserción de comando
socket.on('setCommand', function(data) {
// Es necesario estár identificado
if (!socket.authed)
return socket.emit('auth', { error: true });
// Los datos deben ser un objeto
if (!data || typeof data != 'object')
return socket.emit('setCommand', { error: 'data' });
// Establecemos el comando
var result = Public.setCommand(data.command, data.value);
// Enviamos el resultado al cliente
socket.emit('setCommand', result);
// Si no hubo ningún error enviamos la base de datos actualizada al cliente
if (!result.error)
socket.emit('commands', { items: Public.database });
});
});
},
createCommandServer: function(option) {
// Las opciones son obligatorias
if (isNaN(option.port) || (option.port%1) || option.port <= 0)
throw 'Error backdroid.createCommandServer: option.port';
if (typeof option.password != 'string' || !option.password.length)
throw 'Error backdroid.createCommandServer: option.password';
if (typeof option.encryption_password != 'string' || !option.encryption_password.length)
throw 'Error backdroid.createCommandServer: option.encryption_password';
// Servidor HTTP
var httpServer = Express.createServer().listen(option.port),
sendEncrypt;
if (option.debug)
httpServer.use(Express.logger({ format: '[COMMAND] :method :url' }));
httpServer.use(Express.bodyParser());
httpServer.use(httpServer.router);
httpServer.all('*', function(request, response, next) {
sendEncrypt = function(data) {
return response.send(Public.aes.encrypt(JSON.stringify(data), option.encryption_password, 256));
};
next();
});
// Configuración HTTP
httpServer.post('/getCommands.json', function(request, response) {
// La contraseña de acceso debe ser correcta
if (request.body.password != option.password)
return response.json({ error: 'auth' });
var buffer = [];
// Recorremos la base de datos
Public.database.forEach(function(item) {
// Si aún no ha sido enviado
if (!item.sent) {
// Activamos el marcador sent y lo añadimos al contenedor
item.sent = true;
if (typeof item.onSend == 'function')
item.onSend.apply(item, [item.command, item.value]);
buffer.push(item);
}
});
// Enviamos todos los comandos nuevos
var date = parseInt(new Date()/1000, 10);
Public.sockets.forEach(function(socket) {
if (buffer.length) {
socket.emit('commands', {
date: date,
items: Public.database
});
} else {
socket.emit('commands', {
date: date
});
}
});
sendEncrypt({ items: buffer });
});
// Respuesta de las peticiones
httpServer.post('/setResponse.json', function(request, response) {
var body = request.body,
data = body.data,
date = parseInt(new Date()/1000, 10),
found;
// La contraseña de acceso debe ser correcta
if (body.password != option.password)
return response.json({ error: 'auth' });
// Intentamos convertir los datos a JSON
try {
data = JSON.parse(Public.aes.decrypt(data, option.encryption_password, 256));
} catch (e) {
data = null;
}
// La conversión ha de ser satisfactoria
if (!data || typeof data != 'object')
return sendEncrypt({ error: 'data' });
// El identificador es obligatorio
if (typeof data.id != 'string' || !data.id.length)
return sendEncrypt({ error: 'id' });
// Recorremos la base de datos
Public.database.forEach(function(item) {
// Si el identificador coincide
if (item.id == data.id) {
found = true;
// Añadimos una nueva respuesta al comando con dicho identificador
item.response.push({
// Fecha actual
date: date,
// Datos de la respuesta
value: data.value
});
if (typeof item.onSuccess == 'function')
item.onSuccess.apply(item, [item.command, item.value, data.value]);
}
});
// Si la respuesta no tiene un comando al que permanecer
if (!found) {
// Si no se incluye el comando al que pertenece
if (!data.request || typeof data.request != 'object' || typeof data.request.command != 'string')
// Devolvemos error
return sendEncrypt({ error: 'request' });
// Añadimos un nuevo comando, como enviado, con dicha respuesta
Public.database.push({
// Identificador único del comando
id: data.id,
// Fecha actual
date: date,
// Nombre del comando
command: data.request.command,
// Valor del comando
value: data.request.value,
// Marcador de enviado activado
sent: true,
// Contenedor con la respuesta
response: [{
// Fecha actual
date: date,
// Datos de la respuesta
value: data.value
}]
});
}
// Recorremos los usuarios identificados del panel
Public.sockets.forEach(function(socket) {
// Actualizamos los comandos de los usuarios
socket.emit('commands', {
date: date,
items: Public.database
});
});
sendEncrypt({ success: true });
});
}
};
module.exports = Public;