forked from localtunnel/localtunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
325 lines (245 loc) · 8.09 KB
/
server.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
// builtin
var http = require('http');
var net = require('net');
var url = require('url');
// here be dragons
var HTTPParser = process.binding('http_parser').HTTPParser;
// vendor
var log = require('book');
var createRawServer = require('http-raw');
// local
var rand_id = require('./lib/rand_id');
// id -> client http server
var clients = {};
// available parsers
var parsers = http.parsers;
// send this request to the appropriate client
// in -> incoming request stream
function proxy_request(client, req, res, rs, ws) {
rs = rs || req.createRawStream();
ws = ws || res.createRawStream();
// socket is a tcp connection back to the user hosting the site
var sock = client.sockets.shift();
// queue request
if (!sock) {
log.info('no more clients, queued: %s', req.url);
rs.pause();
client.waiting.push([req, res, rs, ws]);
return;
}
log.info('handle req: %s', req.url);
// pipe incoming request into tcp socket
// incoming request isn't allowed to end the socket back to lt client
rs.pipe(sock, { end: false });
sock.ws = ws;
sock.req = req;
// since tcp connection to upstream are kept open
// invoke parsing so we know when the response is complete
var parser = sock.parser;
parser.reinitialize(HTTPParser.RESPONSE);
parser.socket = sock;
// we have completed a response
// the tcp socket is free again
parser.onIncoming = function (res) {
parser.onMessageComplete = function() {
log.info('ended response: %s', req.url);
// any request we had going on is now done
ws.end();
// no more forwarding
delete sock.ws;
delete parser.onIncoming;
// return socket to available pool
client.sockets.push(sock);
var next = client.waiting.shift();
if (next) {
log.trace('popped');
proxy_request(client, next[0], next[1], next[2], next[3]);
}
};
};
rs.resume();
}
function upstream_response(d, start, end) {
var socket = this;
var ws = socket.ws;
if (!ws) {
log.warn('no stream set for req:', socket.req.url);
return;
}
ws.write(d.slice(start, end));
if (socket.upgraded) {
return;
}
var ret = socket.parser.execute(d, start, end - start);
if (ret instanceof Error) {
log.error(ret);
parsers.free(parser);
socket.destroy(ret);
}
}
var handle_req = function (req, res) {
var max_tcp_sockets = req.socket.server.max_tcp_sockets;
// ignore favicon
if (req.url === '/favicon.ico') {
res.writeHead(404);
return res.end();
}
var hostname = req.headers.host;
if (!hostname) {
log.trace('no hostname: %j', req.headers);
return res.end();
}
var match = hostname.match(/^([a-z]+)[.].*/);
if (match) {
var client_id = match[1];
var client = clients[client_id];
// no such subdomain
if (!client) {
log.trace('no client found for id: ' + client_id);
res.statusCode = 404;
return res.end();
}
return proxy_request(client, req, res);
}
var parsed = url.parse(req.url, true);
// redirect main page to github reference
if (req.url === '/' && !parsed.query.new) {
res.writeHead(301, { Location: 'http://shtylman.github.com/localtunnel/' });
res.end();
return;
}
// at this point, the client is requesting a new tunnel setup
// either generate an id or use the one they requested
var match = req.url.match(/\/([a-z]+)?/);
// user can request a particular set of characters
// will be given if not already taken
// this is useful when the main server is restarted
// users can keep testing with their expected ids
var requested_id;
if (match && match[1]) {
requested_id = match[1];
}
var id = requested_id || rand_id();
// if the id already exists, this client must use something else
if (clients[id]) {
id = rand_id();
}
// sockets is a list of available sockets for the connection
// waiting is?
var client = clients[id] = {
sockets: [],
waiting: []
};
var client_server = net.createServer();
client_server.listen(function() {
var port = client_server.address().port;
log.info('tcp server listening on port: %d', port);
var url = 'http://' + id + '.' + req.headers.host;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
url: url,
id: id,
port: port,
max_conn_count: max_tcp_sockets
}));
});
var conn_timeout;
// user has 5 seconds to connect before their slot is given up
function maybe_tcp_close() {
conn_timeout = setTimeout(client_server.close.bind(client_server), 5000);
}
maybe_tcp_close();
// no longer accepting connections for this id
client_server.on('close', function() {
log.warn('Unclaimed before timeout.');
log.trace('closed tcp socket for client(%s)', id);
clearTimeout(conn_timeout);
delete clients[id];
});
client_server.on('connection', function(socket) {
// no more socket connections allowed
if (client.sockets.length >= max_tcp_sockets) {
return socket.end();
}
log.trace('new connection for id: %s', id);
// no need to close the client server
clearTimeout(conn_timeout);
// allocate a response parser for the socket
// it only needs one since it will reuse it
socket.parser = parsers.alloc();
socket._orig_ondata = socket.ondata;
socket.ondata = upstream_response;
client.sockets.push(socket);
socket.once('close', function(had_error) {
log.trace('client %s closed socket', id);
// remove this socket
var idx = client.sockets.indexOf(socket);
client.sockets.splice(idx, 1);
log.trace('remaining client sockets: %s', client.sockets.length);
// no more sockets for this ident
if (client.sockets.length === 0) {
log.trace('all client(%s) sockets disconnected', id);
maybe_tcp_close();
}
});
// close will be emitted after this
socket.on('error', function(err) {
log.error(err);
socket.end();
});
});
client_server.on('error', function(err) {
log.error(err);
});
};
var handle_upgrade = function(req, ws) {
if (req.headers.connection !== 'Upgrade') {
return;
}
var hostname = req.headers.host;
if (!hostname) {
return res.end();
}
var match = hostname.match(/^([a-z]{4})[.].*/);
// not a valid client
if (!match) {
return res.end();
}
var client_id = match[1];
var client = clients[client_id];
if (!client) {
// no such subdomain
return res.end();
}
var socket = client.sockets.shift();
if (!socket) {
// no available sockets to upgrade to
return res.end();
}
var stream = req.createRawStream();
socket.ws = ws;
socket.upgraded = true;
stream.once('end', function() {
delete socket.ws;
// when this ends, we just reset the socket to the lt client
// this is easier than trying to figure anything else out
socket.end();
// put socket back into available pool
client.sockets.push(socket);
var next = client.waiting.shift();
if (next) {
log.trace('popped');
proxy_request(client, next[0], next[1], next[2], next[3]);
}
});
stream.pipe(socket, {end: false});
socket.once('end', ws.end.bind(ws));
};
module.exports = function(opt) {
opt = opt || {};
var server = createRawServer();
server.max_tcp_sockets = opt.max_tcp_sockets || 5;
server.on('request', handle_req);
server.on('upgrade', handle_upgrade);
return server;
};