This repository has been archived by the owner on Sep 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
231 lines (204 loc) · 7.23 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
/*
* This file is part of Electric Dynamite Network Tools (ednt).
* ednt is copyright 2014 Philipp Geschke <[email protected]>
*
* ednt is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with ednt. If not, see <http://www.gnu.org/licenses/>.
*/
nconf = require('nconf');
nconf.argv()
.env()
.file({ file: 'settings.json' });
nconf.defaults({
"listen": {
"port": 80
},
"plugins": [],
"user": "ednt",
"group": "ednt",
"keeproot": false
});
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var _ = require('underscore');
var router = express.Router();
var routes = require('./routes/index');
app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var su_available = (process.getuid() === 0) ? true: false;
nconf.get('plugins').forEach(function(pluginName){
app.plugins = app.plugins || [];
app.mountpoints = app.mountpoints || [];
try {
var plugin = require(pluginName);
} catch (err) {
console.dir(err);
console.log('Error: Plugin '+pluginName+' not installed. Try "npm install '+pluginName+'"');
return;
}
if(typeof(plugin.init) != "function") {
console.log('Error: Plugin '+pluginName+' does not have a valid \
init() function');
return;
} else {
console.log("Debug: Trying to load plugin: "+pluginName);
if(plugin.SU_REQUIRED && !su_available) {
console.log('Warning: Plugin '+pluginName+' requires root privileges, but we don\'t have them. Aborting load.');
return;
}
/* If the mountpoint is already in use by another plugin, try to
* find another mountpoint by suffixing a number counting up */
var suffix = '';
var mountpoint = plugin.MOUNTPOINT;
while(app.mountpoints[mountpoint] !== undefined) {
suffix++;
mountpoint = plugin.MOUNTPOINT + suffix;
}
if(mountpoint !== plugin.MOUNTPOINT) {
console.log('Warning: Duplicate mountpoint detected while loading\
plugin "'+pluginName+'". Duplicate mountpoint: "'+plugin.MOUNTPOINT+'". \
First defined by plugin "'+app.mountpoints[plugin.MOUNTPOINT]+'". Mounting\
plugin "'+pluginName+'" on "/'+mountpoint+'/".');
}
if(plugin.init()) {
/* loop through routes provided by the plugin to extract them
* and their properties */
console.dir(plugin.ROUTES);
for(var n in plugin.ROUTES) {
var route = plugin.ROUTES[n];
console.dir(route);
if(n === "/") n = n+"?";
var mw = "router."+route.method.toLowerCase()+
"('/"+mountpoint+n+"', routes);"
console.log('evaling: '+mw);
eval(mw);
for(var prop in route) {
}
}
console.log('Plugin '+pluginName+' successfully loaded');
app.plugins[pluginName] = plugin;
app.mountpoints[mountpoint] = pluginName;
} else {
console.log('Error: Plugin '+pluginName+' did not load successfully');
}
}
});
app.use(function(req, res, next) {
/* Try to determine the plugin by checking the URL mountpoint */
var exp = req.url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
var mountpoint = exp[5].split("/")[1]
var plugin = app.mountpoints[req.query['plugin']];
if(plugin != undefined) {
console.log("Detected request for plugin: "+plugin);
req.plugin = app.plugins[plugin];
}
next();
});
router.get('/', routes);
app.use(router);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
//module.exports = app;
app.set('port', nconf.get('listen:port'));
if(app.get('port') < 1024 && !su_available) {
console.log('Error: Can\'t bind to port '+app.get('port')+' without\
root rights. Exiting.');
process.exit(255);
}
var io = require('socket.io').listen(app.listen(app.get('port'), function() {
/*
* Try to drop root privileges, unless explicitly told not to
*/
if(!nconf.get('keeproot')) {
try {
console.log('Old User ID: ' + process.getuid() + ', Old Group ID: ' + process.getgid());
process.setgroups([nconf.get('group')]);
process.setgid(nconf.get('group'));
process.setuid(nconf.get('user'));
console.log('New User ID: ' + process.getuid() + ', New Group ID: ' + process.getgid());
} catch (err) {
console.log('Error: Could not drop root privileges. Make sure user \
'+nconf.get('user')+' and group '+nconf.get('group')+' exist.');
process.exit(1);
}
}
console.log('EDNT server listening on port ' + app.get('port'));
}));
io.sockets.on('connection', function (socket) {
socket.on('newRequest', function (data) {
//console.dir(data);
var pluginName = app.mountpoints[data.plugin];
data.params = data.params || {};
if(pluginName === undefined || pluginName === '') var err = new Error('No plugin defined');
else if(app.plugins[pluginName] === undefined) var err = new Error('Plugin '+pluginName+' not installed');
// If an error occured checking submitted data, return the error and exit fn
if(err !== undefined) {
console.dir(err);
socket.emit('error', err.toString());
return;
}
outputHandler = function(err, data) {
if(err) {
console.dir(err);
socket.emit('error', err.toString());
return;
}
//console.log(data);
socket.emit('output', data);
}
// otherwise, continue and submit the request to the plugin
app.plugins[pluginName].on('output', outputHandler);
app.plugins[pluginName].once('end', function(err) {
app.plugins[pluginName].removeListener('output', outputHandler);
console.log('REQUEST END');
});
app.plugins[pluginName].newRequest(data.params);
});
});