-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathapp.js
426 lines (345 loc) · 11.5 KB
/
app.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
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
/* Require modules */
var configfile = require('./config.json'),
http = require('http'),
Router = require('node-simple-router'),
fs = require('fs'),
isRoot = require('is-root'),
shell = require('shelljs/global'),
async = require('async');
// Check if environment variable "HOSTKEEPER_DATABSE" is set
if (process.env.HOSTKEEPER_CONFIG) {
// Check if file exists
fs.exists(process.env.HOSTKEEPER_CONFIG, function(exists) {
if (exists) {
// User custom database
console.log('Using custom config file:' + process.env.HOSTKEEPER_CONFIG)
var config = process.env.HOSTKEEPER_CONFIG;
} else {
// Use default database path from config file
var config = configfile;
}
});
} else {
var config = configfile;
}
/* Functions */
/**
* Function to construct dnsmasq hosts file based on json-server's database
* @param {callback}
* @return {bool} true
*/
function updateHostsFile(callback){
// Load current database
var database = JSON.parse(fs.readFileSync(config.database, 'utf8'));
// Clear hosts file
fs.writeFile(config.dnsmasq.hostsfile, '', function(){
// For each host in database
async.each(database.hosts, function(host, cb){
// Append each host mapping
fs.appendFile(config.dnsmasq.hostsfile, host.ip + ' ' + host.host + '\n');
cb();
}, function (err){
// Restart dnsmasq
exec(config.commands.dnsmasq, { silent:true }, function() {
callback(true);
});
});
});
}
/**
* Function to find the next array element id
* @param {array} hosts object
* @return {integer} host id
*/
function findNextHostId(array){
var lastitem = array[array.length-1];
if (typeof lastitem !== 'undefined' && lastitem) {
return Number(lastitem.id) + 1;
} else {
return 1;
}
}
/**
* Find array element which has a key value of val
* @param {array} input array
* @param {string} key to search
* @param {string} val to search
* @return {bool} success
*/
function find(arr, key, val) {
for (var ai, i = arr.length; i--;)
if ((ai = arr[i]) && ai[key] === val)
return ai;
return null;
}
/**
* Return JSON response defaults
* @return object
*/
function initiateJSONdefaults(){
// Set response defaults
delete json;
var json = {};
json.success = false;
json.payload = {};
return json;
}
/* Logic */
// Function to start hostkeeper server
function startServer(){
// Create router instance
var router = new Router();
var responseHeaders = {
'Content-type': 'application/json',
'Access-Control-Allow-Origin': '*',
};
/* Set routes */
// GET /api/update - to update the hosts file manually
router.get('/api/update', function(request, response) {
// Load JSON defaults
var json = initiateJSONdefaults();
// Adjust response defaults
json.method = 'update';
delete json.payload;
// Update hosts file
updateHostsFile(function(){
// Return 200 response
response.writeHead(200, responseHeaders);
// Construct JSON response
json.success = true;
// Return JSON
response.end(JSON.stringify(json));
});
});
// GET /api/info - show api information
router.get('/api/info', function(request, response) {
// Load JSON defaults
var json = initiateJSONdefaults();
// Load hosts database
var database = JSON.parse(fs.readFileSync(config.database, 'utf8'));
// Adjust response defaults
json.method = 'info';
// Return 200 response
response.writeHead(200, responseHeaders);
// Construct JSON response
json.success = true;
json.payload['hosts'] = database.hosts.length;
json.payload['server-ip'] = exec(config.commands.ipextract, {silent:true}).output.replace('\n', '');
json.payload['node-version'] = exec(config.commands['node-version'], {silent:true}).output.replace('\n', '');
json.payload['dnsmasq-version'] = exec(config.commands['dnsmasq-version'], {silent:true}).output.replace('\n', '');
json.payload.uptime = exec(config.commands.uptime, {silent:true}).output;
// Return JSON
response.end(JSON.stringify(json));
});
// GET /api/show - to list all host entries
router.get('/api/show', function(request, response) {
// Load JSON defaults
var json = initiateJSONdefaults();
// Load hosts database
var database = JSON.parse(fs.readFileSync(config.database, 'utf8'));
// Adjust response defaults
json.method = 'show';
// Return 200 response
response.writeHead(200, responseHeaders);
// Construct JSON response
json.success = true;
json.payload = database.hosts;
// Return JSON
response.end(JSON.stringify(json));
});
// GET /api/show/:host - show specific host
router.get('/api/show/:host', function(request, response) {
// Load JSON defaults
var json = initiateJSONdefaults();
// Load hosts database
var database = JSON.parse(fs.readFileSync(config.database, 'utf8')),
index;
// Adjust response defaults
json.method = 'show/' + request.params.host;
// Find list index of host with id ":host"
for (var i = 0; i < database.hosts.length; i++) {
if (database.hosts[i].id.toString() === request.params.host) {
index = i;
}
}
// Make sure the desired host exists
if (database.hosts[index]) {
// Return 200 response
response.writeHead(200, responseHeaders);
// Construct JSON response
json.success = true;
json.payload = database.hosts[index];
// Return JSON
response.end(JSON.stringify(json));
} else {
// Return 404 response
response.writeHead(404, responseHeaders);
// Construct JSON response
json.payload.error = 'Host does not exist';
// Return JSON
response.end(JSON.stringify(json));
}
});
// POST /api/add - to add new hosts
router.post('/api/add', function(request, response) {
// Load JSON defaults
var json = initiateJSONdefaults();
// Load hosts database
var database = JSON.parse(fs.readFileSync(config.database, 'utf8'));
// Adjust response defaults
json.method = 'add';
// Make sure we haven't already added the host
if (!find(database.hosts, 'host', request.post.host)) {
// Create object for our new host
var newHost = {
id: findNextHostId(database.hosts),
host: request.post.host,
ip: request.post.ip
};
// Push newHost into database object
database.hosts.push(newHost);
// Write database
fs.writeFile(config.database, JSON.stringify(database, null, 2), function(){
// Return 201 CREATED status code
response.writeHead(201, responseHeaders);
// Construct JSON response
json.success = true;
json.payload = newHost;
// Return JSON
response.end(JSON.stringify(json));
});
} else {
// Return response
response.writeHead(400, responseHeaders);
// Construct JSON response
json.payload.error = 'Host already exists';
json.success = false;
console.log(json);
// Return JSON
response.end(JSON.stringify(json));
}
});
// PUT /api/edit/:host - to edit existing hosts
router.put('/api/edit/:host', function(request, response) {
// Load JSON defaults
var json = initiateJSONdefaults();
// Load hosts database
var database = JSON.parse(fs.readFileSync(config.database, 'utf8')),
index;
// Adjust response defaults
json.method = 'edit/' + request.params.host;
// Find list index of host with id ":host"
for (var i = 0; i < database.hosts.length; i++) {
if (database.hosts[i].id.toString() === request.params.host) {
index = i;
}
}
// Make sure the desired host exists
if (database.hosts[index]) {
// Make sure we haven't already added the host
if (!find(database.hosts, 'host', request.post.host) || find(database.hosts, 'host', request.post.host).id === database.hosts[index].id) {
// Update element
database.hosts[index].host = request.post.host;
database.hosts[index].ip = request.post.ip;
// Write database
fs.writeFile(config.database, JSON.stringify(database, null, 2), function(){
// Return response
response.writeHead(200,responseHeaders);
// Construct JSON response
json.success = true;
json.payload = database.hosts[index];
// Return JSON
response.end(JSON.stringify(json));
});
} else {
// Return response
response.writeHead(400, responseHeaders);
// Construct JSON response
json.success = false;
json.payload.error = 'Host already exists';
json.payload.input = {};
json.payload.input.host = request.post.host;
json.payload.input.ip = request.post.ip;
// Return JSON
response.end(JSON.stringify(json));
}
} else {
// Return 404 response
response.writeHead(404, responseHeaders);
// Construct JSON response
json.success = false;
json.payload.error = 'Host does not exist';
json.payload.input = {};
json.payload.input.host = request.post.host;
json.payload.input.ip = request.post.ip;
// Return JSON
response.end(JSON.stringify(json));
}
});
// DELETE /api/delete/:host - to delete existing hosts
router.delete('/api/delete/:host', function(request, response) {
// Load JSON defaults
var json = initiateJSONdefaults();
// Load hosts database
var database = JSON.parse(fs.readFileSync(config.database, 'utf8')),
currentHostAmount = Object.keys(database.hosts).length;
// Adjust response defaults
json.method = 'delete/' + request.params.host;
// Remove :host from database
for(var i = 0; i < database.hosts.length; i++) {
if(database.hosts[i].id.toString() === request.params.host) {
var deletedHost = database.hosts[i];
database.hosts.splice(i, 1);
i--;
}
}
// Store new host amount
var newHostAmount = Object.keys(database.hosts).length;
// Compare if amount changed
if (newHostAmount !== currentHostAmount) {
// Write database
fs.writeFile(config.database, JSON.stringify(database, null, 2), function(){
// Return 200 response
response.writeHead(200, responseHeaders);
// Construct JSON response
json.success = true;
json.payload = deletedHost;
// Return JSON
response.end(JSON.stringify(json));
});
} else {
// Return 404 response
response.writeHead(404, responseHeaders);
// Construct JSON response
json.payload.error = 'Host does not exist';
// Return JSON
response.end(JSON.stringify(json));
}
});
// Create HTTP server
var express = require('express'),
cors = require('cors'),
app = express();
// Add cors middleware
app.use(cors());
// Add static/assets folder
app.use(express.static(__dirname+'/public'));
// Inject GET / route to show actual web interface
app.get('/', function(req, res){
res.sendfile(__dirname + '/public/index.html');
});
// Add API router middleware on top of that
app.use(router);
// Start server on configured port
app.listen(config.port);
console.log('hostkeeper server successfuly started: http://localhost:' + config.port);
}
// Check if run as root
if (!isRoot()){
console.log('Error: This application needs root permissions! Make sure to run as root user.');
// Exit with code 1
process.exit(1);
} else {
// Start server
startServer();
}