forked from michaljaz/webmc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
194 lines (164 loc) · 4.79 KB
/
proxy.js
File metadata and controls
194 lines (164 loc) · 4.79 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
const net = require('net')
const http = require('http')
const crypto = require('crypto')
const express = require('express')
const expressWs = require('express-ws')
const bodyParser = require('body-parser')
function generateToken () {
return crypto.randomBytes(32).toString('hex')
}
function checkTo (allowed, requested) {
if (!(allowed instanceof Array)) {
allowed = [allowed]
}
// For each rule
for (let i = 0; i < allowed.length; i++) {
const to = allowed[i]
if ((to.host === requested.host || !to.host) && (to.port === requested.port || !to.port)) {
if (to.blacklist) { // This item is blacklisted
return false
} else { // Otheriwse, it's whitelisted
return true
}
}
}
// No rule found, access denied
return false
}
module.exports = function (options, connectionListener) {
options = options || {}
const myLog = options.log
? console.log
: function () {}
const app = express()
const jsonParser = bodyParser.json()
const urlRoot = options.urlRoot || '/api/vm/net'
let server
if (options.server) {
server = options.server
} else {
server = http.createServer()
}
const sockets = {}
if (options.allowOrigin) {
let allowOrigin = options.allowOrigin
if (typeof options.allowOrigin !== 'string') {
allowOrigin = (options.allowOrigin === true) ? '*' : ''
}
if (allowOrigin) {
// Set Access-Control headers (CORS)
app.use(function (req, res, next) {
if (req.path.indexOf(urlRoot) !== 0) {
next()
return
}
res.header('Access-Control-Allow-Origin', allowOrigin)
if (req.method.toUpperCase() === 'OPTIONS') { // Preflighted requests
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
res.header('Access-Control-Allow-Headers', 'Content-Type')
res.header('Access-Control-Max-Age', 1728000) // Access-Control headers cached for 20 days
}
next()
})
}
}
app.post(urlRoot + '/connect', jsonParser, function (req, res) {
const host = req.body.host
const port = req.body.port
if (!host || !port) {
res.status(400).send({
code: 400,
error: 'No host and port specified'
})
return
}
if (options.to) {
if (!checkTo(options.to, { host: host, port: port })) {
res.status(403).send({
code: 403,
error: 'Destination not allowed'
})
return
}
}
const socket = net.connect({
host: host,
port: port
}, function (err) {
if (err) {
res.status(500).send({
code: 500,
error: err
})
return
}
// Generate a token for this connection
const token = generateToken()
sockets[token] = socket
// Remove the socket from the list when closed
socket.on('end', function () {
if (sockets[token]) {
delete sockets[token]
}
})
myLog('Connected to ' + req.body.host + ':' + req.body.port + ' (' + token + ')')
const remote = socket.address()
res.send({
token: token,
remote: remote
})
})
socket.on('error', function (err) {
if (res.finished) {
myLog('Socket error after response closed: ' + err)
return
}
res.status(502).send({
code: 502,
error: 'Socket error: ' + err.code,
details: err
})
})
if (connectionListener) {
connectionListener(socket)
}
})
expressWs(app, server)
app.ws(urlRoot + '/socket', function (ws, req) {
const token = req.query.token
if (!sockets[token]) {
console.warn('WARN: Unknown TCP connection with token "' + token + '"')
ws.close()
return
}
const socket = sockets[token]
// delete sockets[token];
myLog('Forwarding socket with token ' + token)
ws.on('message', function (data) {
socket.write(data, 'binary', function () {
// myLog('Sent: ', data.toString());
})
})
socket.on('data', function (chunk) {
// myLog('Received: ', chunk.toString());
// Providing a callback is important, otherwise errors can be thrown
ws.send(chunk, { binary: true }, function (err) { if (err !== undefined) { console.log(err) } })
})
socket.on('end', function () {
myLog('TCP connection closed by remote (' + token + ')')
ws.close()
})
ws.on('close', function () {
socket.end()
myLog('Websocket connection closed (' + token + ')')
})
})
app.on('mount', function (parentApp) {
// @see https://github.com/strongloop/express/blob/master/lib/application.js#L615
parentApp.listen = function listen () {
server.addListener('request', this)
return server.listen.apply(server, arguments)
}
})
return app
}