70 Commits

Author SHA1 Message Date
Roman Shtylman
006ce7733b v1.4.0 2014-08-31 22:59:17 -07:00
Roman Shtylman
624d279c26 History: update 2014-08-31 22:58:43 -07:00
Roman Shtylman
c2b8f2b7ab Merge pull request #57 from kesla/handle-etimedout
don't emit ETIMEDOUT-errors
2014-08-31 22:57:30 -07:00
David Björklund
4d9dcc1711 don't emit ETIMEDOUT-errors 2014-08-28 20:12:09 +02:00
Roman Shtylman
7b1fef982f 1.3.0 2014-05-13 20:33:41 -04:00
Roman Shtylman
b1ebef2b0b fix code style 2014-05-13 20:32:43 -04:00
Tymoteusz Paszun
9ad43778b7 fixed Host header replacement - remembers if header is already replaced and does not remove _transform method 2014-05-13 09:24:08 +02:00
Tymoteusz Paszun
887c444543 added test for chunked requests 2014-05-13 09:16:50 +02:00
Tymoteusz Paszun
828cb2afcb transform Host header when local-host is defined explicitly 2014-05-09 15:07:38 +02:00
Roman Shtylman
8768329fdd update history with two recent minor versions 2014-04-28 19:03:33 -04:00
Roman Shtylman
3026d6a42c 1.2.0 2014-04-28 19:00:12 -04:00
Roman Shtylman
abd461f83a Merge pull request #47 from dscape/patch-1
return client from 'localtunnel' api call
2014-04-28 18:58:54 -04:00
Nuno Job
2acea3d77f Return client
This allows manipulating the client from outside. Allowing, for example, to close a connection.
2014-04-28 23:32:00 +01:00
Roman Shtylman
5d0eb3382a add --version CLI flag to get version info 2014-04-22 19:55:19 -04:00
Roman Shtylman
3b67c8a8ce 1.1.2 2014-04-20 10:51:24 -04:00
Kevin Ingersoll
71552a336e Increase default Mocha timeout 2014-04-20 10:45:21 -04:00
Roman Shtylman
87a23bf28c fix status code check for url request 2014-04-19 19:33:52 -04:00
Roman Shtylman
3d54de851f handle errors from localtunnel server when requesting initial url 2014-04-19 19:30:44 -04:00
Roman Shtylman
92bb807908 fix typo
fixes #45
2014-04-18 09:34:48 -04:00
Roman Shtylman
afbdc3697e 1.1.1 2014-04-15 09:33:34 -04:00
Roman Shtylman
0049f21b55 Merge pull request #38 from LinusU/patch-1
re-throw client errors from bin/lt to let node handle it
2014-04-14 19:27:56 -04:00
Roman Shtylman
509841104b fix for RangeError stack size exceeded
This error would happen when there was a problem connecting to the local
server. The local.on('error') handler should have been a 'once' handler
because we emit the error again if it isn't a CONNREFUSED. So in the
case of a CONNRESET, it would trigger an infinite loop since the error
was being emitted back onto the local variable. Instead we just close
the remote socket and let a new one takes its place.

fixes #36
2014-04-14 15:36:42 -04:00
Linus Unnebäck
92caf2f204 lt: better error handling
Let node handle the displaying of error and setting exit code.
2014-04-14 21:15:11 +02:00
Roman Shtylman
9487797e02 1.1.0 2014-02-24 19:51:14 -05:00
Roman Shtylman
a42f6a8d8d document local-host option 2014-02-24 19:49:40 -05:00
Roman Shtylman
14b4bcb96f add tests for host header transform 2014-02-24 19:43:34 -05:00
Roman Shtylman
4aa65002eb use host header transform only when local-host is specified 2014-02-24 19:43:07 -05:00
Fredi Pevcin
08676ba81d Set Host header accordingly to local-host option 2014-02-24 00:26:38 +01:00
Roman Shtylman
174e7f3982 1.0.0 2014-02-14 00:37:45 -05:00
Roman Shtylman
44be55cd7b readme: fix markdown table
[ci skip]
2014-02-14 00:36:53 -05:00
Roman Shtylman
5c6cd2359c add travis badge
- remove node 0.8
- add node 0.10
2014-02-14 00:34:40 -05:00
Roman Shtylman
2f6f9459ad change main export signature to localtunnel(port, opt, fn)
Makes for a simpler hello world app
2014-02-14 00:32:43 -05:00
Roman Shtylman
7217a08a05 add history.md to track changes 2014-02-13 23:52:12 -05:00
Roman Shtylman
fbfc923a7e remove connect export in favor of single function
Since connect was the only function exported, we can just export the
function directly to make things simpler.
2014-02-13 23:51:29 -05:00
Roman Shtylman
d9bc11b520 default host to localtuunel.me
If no host specified, then default to localtunnel.me

close #31
2014-02-13 23:43:54 -05:00
Roman Shtylman
ad64611bd1 add tests 2014-02-13 23:41:49 -05:00
Roman Shtylman
ac70515143 0.2.2 2014-01-09 11:07:18 -05:00
Roman Shtylman
8d7ccccf21 remove local.unpipe() on remote close
This will happen automatically.

close #28
2014-01-09 11:06:58 -05:00
Roman Shtylman
77091b3d93 0.2.1 2013-12-31 17:34:04 -05:00
Roman Shtylman
4f4a147b45 don't unpipe on local close
Pipe will do this for us
2013-12-31 17:33:49 -05:00
Roman Shtylman
f1d809a84d 0.2.0 2013-12-31 15:39:16 -05:00
Roman Shtylman
eba003bd26 add a .close method to shutdown the tunnel 2013-12-31 15:38:45 -05:00
Roman Shtylman
3354c4c6e3 rework tunnel logic
Refactoring to make things a bit saner and easier to debug.
2013-12-05 11:26:19 -05:00
Roman Shtylman
1c2757e604 Merge pull request #27 from adammck/couldnt-establish-tunnel
Add more verbose error for ECONNREFUSED
2013-11-20 09:34:48 -08:00
Adam Mckaig
790e55e881 Add more verbose error for ECONNREFUSED
If the tunnel server can be reached (at e.g. http://localtunnel.me/?new)
but the tunnel (to e.g. grpi.localtunnel.me:44827) can't actually be
established, the client currently gets stuck in a loop retrying forever
with no indication as to what's wrong. This doesn't fix the loop, since
it does seem desirable to retry forever, but logs:

    [Error: connection refused: localtunnel.me:44827]
2013-11-20 12:29:31 -05:00
Roman Shtylman
a9b0274ff4 0.1.3 2013-11-14 12:10:02 -05:00
Roman Shtylman
83ecb29eff Merge pull request #26 from EverythingMe/override_localhost
Added the --localhost parameter to tunnel the traffic to other hosts
2013-11-14 09:08:47 -08:00
Omri Bahumi
21df257d16 Added the --local-host parameter to tunnel the traffic to other hosts 2013-11-14 18:06:19 +02:00
Roman Shtylman
18ada0854a 0.1.2 2013-11-06 23:25:28 -05:00
Roman Shtylman
34afd6537d more resilient to upstream server failure and restart 2013-11-06 23:25:05 -05:00
Roman Shtylman
2c38aefb9d add go client to readme 2013-10-23 11:31:28 -04:00
Roman Shtylman
aa488f6e76 0.1.1 2013-10-22 15:57:36 -04:00
Roman Shtylman
f6618953f9 Merge pull request #20 from eagleeye/master
Do not call success callback right after error in request_url
2013-10-16 18:49:48 -07:00
Andrii Shumada
092d050fa0 Do not call success callback right after error in request_url 2013-10-16 12:05:37 +03:00
Roman Shtylman
0334ace20b 0.1.0 2013-06-17 02:13:17 -04:00
Roman Shtylman
13afcff1ae fix README api example 2013-06-17 02:12:54 -04:00
Roman Shtylman
ed5aa3f16b remove server components
moved to localtunnel-server repo
2013-06-17 02:11:41 -04:00
Roman Shtylman
2fcac1336c add debug module to deps 2013-06-16 18:35:55 -04:00
Roman Shtylman
0568ae0bef close client tcp sockets after each http response
While a little less efficient than keeping tcp connections open, this
helps ensure that bad things don't happen on the socket connections when
http protocol issues happen.
2013-06-16 18:24:27 -04:00
Roman Shtylman
585a8afad7 fix undefined variable
fixes #8
2013-02-11 14:19:34 -05:00
Roman Shtylman
fbe841a1c5 add node 0.9 for travis testing 2013-01-26 13:01:16 -05:00
Roman Shtylman
929473913f add notes about running your own server 2012-12-24 03:14:19 -05:00
Roman Shtylman
5340659954 0.0.4 2012-12-17 14:32:31 -05:00
Roman Shtylman
5c6558ed91 fix missing query parsing in server 2012-12-17 14:31:05 -05:00
Roman Shtylman
79ca069c38 refactor to use http-raw for lt server incoming
- http raw exposes a socket to the req/res pair
- cleanup client to be more resilient
- add test for queued requests
2012-12-17 14:23:12 -05:00
Roman Shtylman
741db27084 fix domain typo in readme
localtunnel.me not .com
2012-12-14 23:43:06 -05:00
Roman Shtylman
b605e9b823 server: make sure client id are released when unused
When clients disconnect, their tcp server should be shutdown and the id
released after a grace period.
2012-11-14 13:53:33 -05:00
Roman Shtylman
b5830c3840 0.0.3 2012-11-06 10:55:24 -05:00
Roman Shtylman
06b85ad0aa expose client and server api 2012-11-06 10:55:08 -05:00
Roman Shtylman
943a7dc35b typo 2012-11-05 16:05:32 -05:00
11 changed files with 582 additions and 664 deletions

View File

@@ -1,3 +1,3 @@
language: node_js
node_js:
- 0.8
- "0.10"

19
History.md Normal file
View File

@@ -0,0 +1,19 @@
# 1.4.0 (2014-08-31)
* don't emit errors for ETIMEDOUT
# 1.2.0 / 2014-04-28
* return `client` from `localtunnel` API instantiation
# 1.1.0 / 2014-02-24
* add a host header transform to change the 'Host' header in requests
# 1.0.0 / 2014-02-14
* default to localltunnel.me for host
* remove exported `connect` method (just export one function that does the same thing)
* change localtunnel signature to (port, opt, fn)
# 0.2.2 / 2014-01-09

View File

@@ -1,8 +1,8 @@
# localtunnel [![Build Status](https://secure.travis-ci.org/shtylman/localtunnel.png)](http://travis-ci.org/shtylman/localtunnel) #
# localtunnel [![Build Status](https://travis-ci.org/defunctzombie/localtunnel.png?branch=master)](https://travis-ci.org/defunctzombie/localtunnel) #
localtunnel exposes your localhost to the world for easy testing and sharing! No need to mess with DNS or deploy just to have others test out your changes.
Great for working with browser testing tools like browserling or external api callback services like twilio which require a public url for callbacks!
Great for working with browser testing tools like browserling or external api callback services like twilio which require a public url for callbacks.
## installation ##
@@ -10,9 +10,11 @@ Great for working with browser testing tools like browserling or external api ca
npm install -g localtunnel
```
This will install the localtunnel module globally and add the 'lt' client cli tool to your PATH.
## use ##
Super East! Assuming your local server is running on port 8000, just use the ```lt``` command to start the tunnel.
Assuming your local server is running on port 8000, just use the ```lt``` command to start the tunnel.
```
lt --port 8000
@@ -22,27 +24,62 @@ Thats it! It will connect to the tunnel server, setup the tunnel, and tell you w
You can restart your local server all you want, ```lt``` is smart enough to detect this and reconnect once it is back.
### arguments
Below are some common arguments. See `lt --help` for additional arguments
* `--subdomain` request a named subdomain on the localtunnel server (default is random characters)
* `--local-host` proxy to a hostname other than localhost
## API ##
The localtunnel client is also usable through an API (test integration, automation, etc)
The localtunnel client is also usable through an API (for test integration, automation, etc)
### localtunnel(port [,opts], fn)
Creates a new localtunnel to the specified local `port`. `fn` will be called once you have been assigned a public localtunnel url. `opts` can be used to request a specific `subdomain`.
```javascript
var lt_client = require('localtunnel').client;
var localtunnel = require('localtunnel');
var client = lt_client.connect({
// the localtunnel server
host: 'http://localtunnel.com',
// your local application port
port: 12345
});
localtunnel(port, function(err, tunnel) {
if (err) ...
// when your are assigned a url
client.on('url', function(url) {
// you can now make http requests to the url
// they will be proxied to your local server on port [12345]
});
client.on('error', function(err) {
// uh oh!
// the assigned public url for your tunnel
// i.e. https://abcdefgjhij.localtunnel.me
tunnel.url;
});
```
### opts
* `subdomain` A *string* value requesting a specific subdomain on the proxy server. **Note** You may not actually receive this name depending on availablily.
* `local_host` Proxy to this hostname instead of `localhost`. This will also cause the `Host` header to be re-written to this value in proxied requests.
### Tunnel
The `tunnel` instance returned to your callback emits the following events
|event|args|description|
|----|----|----|
|error|err|fires when an error happens on the tunnel|
|close||fires when the tunnel has closed|
The `tunnel instance has the following methods
|method|args|description|
|----|----|----|
|close||close the tunnel|
## other clients ##
Clients in other languages
*go* [gotunnelme](https://github.com/NoahShen/gotunnelme)
## server ##
See defunctzombie/localtunnel-server for details on the server that powers localtunnel.
## License ##
MIT

View File

@@ -1,9 +1,8 @@
#!/usr/bin/env node
var lt_client = require(__dirname + '/../client');
var lt_client = require('../client');
var argv = require('optimist')
.usage('Usage: $0 --port [num]')
.demand(['port'])
.options('host', {
default: 'http://localtunnel.me',
describe: 'upstream server providing forwarding'
@@ -11,24 +10,43 @@ var argv = require('optimist')
.options('subdomain', {
describe: 'request this subdomain'
})
.options('local-host', {
describe: 'tunnel traffic to this host instead of localhost, override Host header to this host'
})
.options('version', {
describe: 'print version and exit'
})
.describe('port', 'internal http server port')
.argv;
if (argv.version) {
console.log(require('../package.json').version);
process.exit(0);
}
if (argv.port == null) {
require('optimist').showHelp();
console.error('Missing required arguments: port');
process.exit(1);
}
var opt = {
host: argv.host,
port: argv.port,
local_host: argv['local-host'],
subdomain: argv.subdomain,
}
};
var client = lt_client.connect(opt);
lt_client(opt.port, opt, function(err, tunnel) {
if (err) {
throw err;
}
// only emitted when the url changes
client.on('url', function(url) {
console.log('your url is: %s', url);
});
console.log('your url is: %s', tunnel.url);
client.on('error', function(err) {
console.error(err);
tunnel.on('error', function(err) {
throw err;
});
});
// vim: ft=javascript

View File

@@ -1,33 +0,0 @@
#!/usr/bin/env node
// vendor
var log = require('book');
var optimist = require('optimist');
var argv = optimist
.usage('Usage: $0 --port [num]')
.options('port', {
default: '80',
describe: 'listen on this port for outside requests'
})
.argv;
if (argv.help) {
optimist.showHelp();
process.exit();
}
process.once('uncaughtException', function(err) {
log.panic(err);
process.exit(-1);
return;
});
var server = require('../server');
server.listen(argv.port, function() {
log.info('server listening on port: %d', server.address().port);
});
// vim: ft=javascript

374
client.js
View File

@@ -1,25 +1,191 @@
// builtin
var net = require('net');
var url = require('url');
var request = require('request');
var EventEmitter = require('events').EventEmitter;
// request upstream url and connection info
var request_url = function(params, cb) {
request(params, function(err, res, body) {
if (err) {
cb(err);
var request = require('request');
var debug = require('debug')('localtunnel:client');
var stream = require('stream');
var util = require('util');
var Transform = stream.Transform;
var HeaderHostTransformer = function(opts) {
if (!(this instanceof HeaderHostTransformer)) {
return new HeaderHostTransformer(opts);
}
opts = opts || {}
Transform.call(this, opts);
var self = this;
self.host = opts.host || 'localhost';
self.replaced = false;
}
util.inherits(HeaderHostTransformer, Transform);
HeaderHostTransformer.prototype._transform = function (chunk, enc, cb) {
var self = this;
chunk = chunk.toString();
// after replacing the first instance of the Host header
// we just become a regular passthrough
if (!self.replaced) {
self.push(chunk.replace(/(\r\nHost: )\S+/, function(match, $1) {
self.replaced = true;
return $1 + self.host;
}));
}
else {
self.push(chunk);
}
cb();
};
// manages groups of tunnels
var TunnelCluster = function(opt) {
if (!(this instanceof TunnelCluster)) {
return new TunnelCluster(opt);
}
var self = this;
self._opt = opt;
EventEmitter.call(self);
};
TunnelCluster.prototype.__proto__ = EventEmitter.prototype;
// establish a new tunnel
TunnelCluster.prototype.open = function() {
var self = this;
var opt = self._opt || {};
var remote_host = opt.remote_host;
var remote_port = opt.remote_port;
var local_host = opt.local_host || 'localhost';
var local_port = opt.local_port;
debug('establishing tunnel %s:%s <> %s:%s', local_host, local_port, remote_host, remote_port);
// connection to localtunnel server
var remote = net.connect({
host: remote_host,
port: remote_port
});
remote.once('error', function(err) {
// emit connection refused errors immediately, because they
// indicate that the tunnel can't be established.
if (err.code === 'ECONNREFUSED') {
self.emit('error', new Error('connection refused: ' + remote_host + ':' + remote_port + ' (check your firewall settings)'));
}
else if (err.code !== 'ETIMEDOUT') {
self.emit('error', err);
}
cb(null, body);
setTimeout(function() {
self.emit('dead');
}, 1000);
});
function conn_local() {
if (remote.destroyed) {
debug('remote destroyed');
self.emit('dead');
return;
}
debug('connecting locally to %s:%d', local_host, local_port);
remote.pause();
// connection to local http server
var local = net.connect({
host: local_host,
port: local_port
});
function remote_close() {
debug('remote close');
self.emit('dead');
local.end();
};
remote.once('close', remote_close);
// TODO some languages have single threaded servers which makes opening up
// multiple local connections impossible. We need a smarter way to scale
// and adjust for such instances to avoid beating on the door of the server
local.once('error', function(err) {
debug('local error %s', err.message);
local.end();
remote.removeListener('close', remote_close);
if (err.code !== 'ECONNREFUSED') {
return remote.end();
}
// retrying connection to local server
setTimeout(conn_local, 1000);
});
local.once('connect', function() {
debug('connected locally');
remote.resume();
var stream = remote;
// if user requested specific local host
// then we use host header transform to replace the host header
if (opt.local_host) {
debug('transform Host header to %s', opt.local_host);
stream = remote.pipe(HeaderHostTransformer({ host: opt.local_host }));
}
stream.pipe(local).pipe(remote);
// when local closes, also get a new remote
local.once('close', function(had_error) {
debug('local connection closed [%s]', had_error);
});
});
}
// tunnel is considered open when remote connects
remote.once('connect', function() {
self.emit('open', remote);
conn_local();
});
};
var connect = function(opt) {
var ev = new EventEmitter();
var Tunnel = function(opt) {
if (!(this instanceof Tunnel)) {
return new Tunnel(opt);
}
// local port
var local_port = opt.port;
var self = this;
self._closed = false;
self._opt = opt || {};
self._opt.host = self._opt.host || 'https://localtunnel.me';
};
Tunnel.prototype.__proto__ = EventEmitter.prototype;
// initialize connection
// callback with connection info
Tunnel.prototype._init = function(cb) {
var self = this;
var opt = self._opt;
var params = {
path: '/',
json: true
};
var base_uri = opt.host + '/';
@@ -29,105 +195,129 @@ var connect = function(opt) {
// no subdomain at first, maybe use requested domain
var assigned_domain = opt.subdomain;
// connect to upstream given connection parameters
var tunnel = function (remote_host, remote_port, max_conn) {
var count = 0;
// open 5 connections to the localtunnel server
// allows for resources to be served faster
for (var count = 0 ; count < max_conn ; ++count) {
var upstream = duplex(remote_host, remote_port, 'localhost', local_port);
upstream.once('end', function() {
// all upstream connections have been closed
if (--count <= 0) {
tunnel(remote_host, remote_port, max_conn);
}
});
upstream.on('error', function(err) {
console.error(err);
});
}
};
var params = {
path: '/',
json: true
};
// where to quest
params.uri = base_uri + ((assigned_domain) ? assigned_domain : '?new');
request_url(params, function(err, body) {
(function get_url() {
request(params, function(err, res, body) {
if (err) {
// TODO (shtylman) don't print to stdout?
console.log('tunnel server offline: ' + err.message + ', retry 1s');
return setTimeout(get_url, 1000);
}
if (err) {
ev.emit('error', new Error('tunnel server not available: %s, retry 1s', err.message));
if (res.statusCode !== 200) {
var err = new Error((body && body.message) || 'localtunnel server returned an error, please try again');
return cb(err);
}
// retry interval for id request
return setTimeout(function() {
connect_proxy(opt);
}, 1000);
}
var port = body.port;
var host = upstream.hostname;
// our assigned hostname and tcp port
var port = body.port;
var host = upstream.hostname;
var max_conn = body.max_conn_count || 1;
// store the id so we can try to get the same one
assigned_domain = body.id;
tunnel(host, port, body.max_conn_count || 1);
ev.emit('url', body.url);
});
return ev;
cb(null, {
remote_host: upstream.hostname,
remote_port: body.port,
name: body.id,
url: body.url,
max_conn: max_conn
});
});
})();
};
var duplex = function(remote_host, remote_port, local_host, local_port) {
var ev = new EventEmitter();
Tunnel.prototype._establish = function(info) {
var self = this;
var opt = self._opt;
// connect to remote tcp server
var upstream = net.createConnection(remote_port, remote_host);
var internal;
info.local_host = opt.local_host;
info.local_port = opt.port;
// when upstream connection is closed, close other associated connections
upstream.once('end', function() {
ev.emit('error', new Error('upstream connection terminated'));
var tunnels = self.tunnel_cluster = TunnelCluster(info);
// sever connection to internal server
// on reconnect we will re-establish
internal.end();
ev.emit('end');
// only emit the url the first time
tunnels.once('open', function() {
self.emit('url', info.url);
});
upstream.on('error', function(err) {
ev.emit('error', err);
var tunnel_count = 0;
// track open count
tunnels.on('open', function(tunnel) {
tunnel_count++;
debug('tunnel open [total: %d]', tunnel_count);
var close_handler = function() {
tunnel.destroy();
};
if (self._closed) {
return close_handler();
}
self.once('close', close_handler);
tunnel.once('close', function() {
self.removeListener('close', close_handler);
});
});
(function connect_internal() {
// when a tunnel dies, open a new one
tunnels.on('dead', function(tunnel) {
tunnel_count--;
debug('tunnel dead [total: %d]', tunnel_count);
internal = net.createConnection(local_port, local_host);
internal.on('error', function() {
ev.emit('error', new Error('error connecting to local server. retrying in 1s'));
setTimeout(function() {
connect_internal();
}, 1000);
});
if (self._closed) {
return;
}
internal.on('end', function() {
ev.emit('error', new Error('disconnected from local server. retrying in 1s'));
setTimeout(function() {
connect_internal();
}, 1000);
});
tunnels.open();
});
upstream.pipe(internal).pipe(upstream);
})();
// establish as many tunnels as allowed
for (var count = 0 ; count < info.max_conn ; ++count) {
tunnels.open();
}
};
return ev;
}
Tunnel.prototype.open = function(cb) {
var self = this;
module.exports.connect = connect;
self._init(function(err, info) {
if (err) {
return cb(err);
}
self.url = info.url;
self._establish(info);
cb();
});
};
// shutdown tunnels
Tunnel.prototype.close = function() {
var self = this;
self._closed = true;
self.emit('close');
};
module.exports = function localtunnel(port, opt, fn) {
if (typeof opt === 'function') {
fn = opt;
opt = {};
}
opt = opt || {};
opt.port = port;
var client = Tunnel(opt);
client.open(function(err) {
if (err) {
return fn(err);
}
fn(null, client);
});
return client;
};

View File

@@ -1,12 +0,0 @@
var chars = 'abcdefghiklmnopqrstuvwxyz';
module.exports = function rand_id() {
var randomstring = '';
for (var i=0; i<4; ++i) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars[rnum];
}
return randomstring;
}

View File

@@ -2,28 +2,24 @@
"author": "Roman Shtylman <shtylman@gmail.com>",
"name": "localtunnel",
"description": "expose localhost to the world",
"version": "0.0.2",
"version": "1.4.0",
"repository": {
"type": "git",
"url": "git://github.com/shtylman/localtunnel.git"
},
"dependencies": {
"request": "2.11.4",
"book": "1.2.0",
"optimist": "0.3.4"
"optimist": "0.3.4",
"debug": "0.7.4"
},
"devDependencies": {
"mocha": "1.6.0"
},
"optionalDependencies": {},
"engines": {
"node": "*"
"mocha": "~1.17.0"
},
"scripts": {
"test": "mocha --ui qunit -- test",
"start": "./bin/server"
"test": "mocha --ui qunit --reporter list --timeout 10000 -- test/index.js"
},
"bin": {
"lt": "./bin/client"
}
}
},
"main": "./client.js"
}

390
server.js
View File

@@ -1,390 +0,0 @@
// builtin
var http = require('http');
var net = require('net');
var url = require('url');
// here be dragons
var HTTPParser = process.binding('http_parser').HTTPParser;
var ServerResponse = http.ServerResponse;
var IncomingMessage = http.IncomingMessage;
// vendor
var log = require('book');
// local
var rand_id = require('./lib/rand_id');
var server = http.createServer();
// id -> client http server
var clients = {};
// available parsers
var parsers = http.parsers;
// data going back to a client (the last client that made a request)
function socketOnData(d, start, end) {
var socket = this;
var req = this._httpMessage;
var response_socket = socket.respond_socket;
if (!response_socket) {
log.error('no response socket assigned for http response from backend');
return;
}
// pass the response from our client back to the requesting socket
response_socket.write(d.slice(start, end));
if (socket.for_websocket) {
return;
}
// invoke parsing so we know when the response is complete
var parser = response_socket.out_parser;
parser.socket = socket;
var ret = parser.execute(d, start, end - start);
if (ret instanceof Error) {
log.error(ret);
freeParser(parser, req);
socket.destroy(ret);
}
}
function freeParser(parser, req) {
if (parser) {
parser._headers = [];
parser.onIncoming = null;
if (parser.socket) {
parser.socket.onend = null;
parser.socket.ondata = null;
parser.socket.parser = null;
}
parser.socket = null;
parser.incoming = null;
parsers.free(parser);
parser = null;
}
if (req) {
req.parser = null;
}
}
// single http connection
// gets a single http response back
server.on('connection', function(socket) {
var self = this;
// parser handles incoming requests for the socket
// the request is what lets us know if we proxy or not
var parser = parsers.alloc();
parser.socket = socket;
parser.reinitialize(HTTPParser.REQUEST);
function our_request(req) {
var res = new ServerResponse(req);
res.assignSocket(socket);
self.emit('request', req, res);
return;
}
// a full request is complete
// we wait for the response from the server
parser.onIncoming = function(req, shouldKeepAlive) {
log.trace('request', req.url);
// default is that the data is not for the client
delete parser.sock;
delete parser.buffer;
delete parser.client;
var hostname = req.headers.host;
if (!hostname) {
log.trace('no hostname: %j', req.headers);
return our_request(req);
}
var match = hostname.match(/^([a-z]{4})[.].*/);
if (!match) {
return our_request(req);
}
var client_id = match[1];
var client = clients[client_id];
// requesting a subdomain that doesn't exist
if (!client) {
return socket.end();
}
parser.client = client;
// assigned socket for the client
var sock = client.sockets.shift();
// no free sockets, queue
if (!sock) {
parser.buffer = true;
return;
}
// for tcp proxying
parser.sock = sock;
// set who we will respond back to
sock.respond_socket = socket;
var out_parser = parsers.alloc();
out_parser.reinitialize(HTTPParser.RESPONSE);
socket.out_parser = out_parser;
// we have completed a response
// the tcp socket is free again
out_parser.onIncoming = function (res) {
res.on('end', function() {
log.trace('done with response for: %s', req.url);
// done with the parser
parsers.free(out_parser);
// unset the response
delete sock.respond_socket;
var next = client.waiting.shift();
if (!next) {
// return socket to available
client.sockets.push(sock);
return;
}
// reuse avail socket for next connection
sock.respond_socket = next;
// needed to know when this response will be done
out_parser.reinitialize(HTTPParser.RESPONSE);
next.out_parser = out_parser;
// write original bytes we held cause we were busy
sock.write(next.queue);
// continue with other bytes
next.resume();
return;
});
};
};
// process new data on the client socket
// we may need to forward this it the backend
socket.ondata = function(d, start, end) {
// run through request parser to determine if we should pass to tcp
// onIncoming will be run before this returns
var ret = parser.execute(d, start, end - start);
// invalid request from the user
if (ret instanceof Error) {
log.error(ret);
socket.destroy(ret);
return;
}
// websocket stuff
if (parser.incoming && parser.incoming.upgrade) {
log.trace('upgrade request');
parser.finish();
var hostname = parser.incoming.headers.host;
var match = hostname.match(/^([a-z]{4})[.].*/);
if (!match) {
return our_request(req);
}
var client_id = match[1];
var client = clients[client_id];
var sock = client.sockets.shift();
sock.respond_socket = socket;
sock.for_websocket = true;
socket.ondata = function(d, start, end) {
sock.write(d.slice(start, end));
};
socket.end = function() {
log.trace('websocket end');
delete sock.respond_socket;
client.sockets.push(sock);
}
sock.write(d.slice(start, end));
return;
}
// if no available socket, buffer the request for later
if (parser.buffer) {
// pause any further data on this socket
socket.pause();
// copy the current data since we have already received it
var copy = Buffer(end - start);
d.copy(copy, 0, start, end);
socket.queue = copy;
// add socket to queue
parser.client.waiting.push(socket);
return;
}
if (!parser.sock) {
return;
}
// assert, respond socket should be set
// send through tcp tunnel
// responses will go back to the respond_socket
parser.sock.write(d.slice(start, end));
};
socket.onend = function() {
var ret = parser.finish();
if (ret instanceof Error) {
log.error(ret);
socket.destroy(ret);
return;
}
socket.end();
};
socket.on('close', function() {
parsers.free(parser);
});
});
server.on('request', function(req, res) {
// ignore favicon
if (req.url === '/favicon.ico') {
res.writeHead(404);
return res.end();
}
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]{4})?/);
// 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();
// maximum number of tcp connections the client can setup
// each tcp channel allows for more parallel requests
var max_tcp_sockets = 4;
// 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
}));
});
// user has 5 seconds to connect before their slot is given up
var conn_timeout = setTimeout(function() {
client_server.close();
}, 5000);
// no longer accepting connections for this id
client_server.on('close', function() {
delete clients[id];
});
var count = 0;
client_server.on('connection', function(socket) {
// no more socket connections allowed
if (count++ >= max_tcp_sockets) {
return socket.end();
}
log.trace('new connection for id: %s', id);
// multiplexes socket data out to clients
socket.ondata = socketOnData;
// no need to close the client server
clearTimeout(conn_timeout);
// add socket to pool for this id
var idx = client.sockets.push(socket) - 1;
socket.on('close', function(had_error) {
count--;
client.sockets.splice(idx, 1);
// no more sockets for this ident
if (client.sockets.length === 0) {
delete clients[id];
}
});
// close will be emitted after this
socket.on('error', function(err) {
log.error(err);
});
});
client_server.on('error', function(err) {
log.error(err);
});
});
module.exports = server;

95
test.js
View File

@@ -1,95 +0,0 @@
var http = require('http');
var url = require('url');
var assert = require('assert');
var localtunnel_server = require('./server');
var localtunnel_client = require('./client');
test('setup localtunnel server', function(done) {
localtunnel_server.listen(3000, function() {
console.log('lt server on:', 3000);
done();
});
});
test('setup local http server', function(done) {
var server = http.createServer();
server.on('request', function(req, res) {
res.write('foo');
res.end();
});
server.listen(function() {
var port = server.address().port;
test._fake_port = port;
console.log('local http on:', port);
done();
});
});
test('setup localtunnel client', function(done) {
var client = localtunnel_client.connect({
host: 'http://localhost:' + 3000,
port: test._fake_port
});
client.on('url', function(url) {
assert.ok(/^http:\/\/.*localhost:3000$/.test(url));
test._fake_url = url;
done();
});
client.on('error', function(err) {
console.error(err);
});
});
test('query localtunnel server w/ ident', function(done) {
var uri = test._fake_url;
var hostname = url.parse(uri).hostname;
var opt = {
host: 'localhost',
port: 3000,
headers: {
host: hostname
},
path: '/'
}
var req = http.request(opt, function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
assert.equal('foo', body);
// TODO(shtylman) shutdown client
done();
});
});
req.end();
});
test('request specific domain', function(done) {
var client = localtunnel_client.connect({
host: 'http://localhost:' + 3000,
port: test._fake_port,
subdomain: 'abcd'
});
client.on('url', function(url) {
assert.ok(/^http:\/\/abcd.localhost:3000$/.test(url));
done();
});
client.on('error', function(err) {
console.error(err);
});
});

188
test/index.js Normal file
View File

@@ -0,0 +1,188 @@
var http = require('http');
var https = require('https');
var url = require('url');
var assert = require('assert');
var localtunnel = require('../');
test('setup local http server', function(done) {
var server = http.createServer();
server.on('request', function(req, res) {
res.write(req.headers.host);
res.end();
});
server.listen(function() {
var port = server.address().port;
test._fake_port = port;
console.log('local http on:', port);
done();
});
});
test('setup localtunnel client', function(done) {
localtunnel(test._fake_port, function(err, tunnel) {
assert.ifError(err);
assert.ok(new RegExp('^https:\/\/.*localtunnel.me' + '$').test(tunnel.url));
test._fake_url = tunnel.url;
done();
});
});
test('query localtunnel server w/ ident', function(done) {
var uri = test._fake_url;
var parsed = url.parse(uri);
var opt = {
host: parsed.host,
port: 443,
headers: {
host: parsed.hostname
},
path: '/'
};
var req = https.request(opt, function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
assert(/.*[.]localtunnel[.]me/.test(body), body);
done();
});
});
req.end();
});
test('request specific domain', function(done) {
localtunnel(test._fake_port, { subdomain: 'abcd' }, function(err, tunnel) {
assert.ifError(err);
assert.ok(new RegExp('^https:\/\/abcd.localtunnel.me' + '$').test(tunnel.url));
tunnel.close();
done();
});
});
suite('--local-host localhost');
test('setup localtunnel client', function(done) {
var opt = {
local_host: 'localhost'
};
localtunnel(test._fake_port, opt, function(err, tunnel) {
assert.ifError(err);
assert.ok(new RegExp('^https:\/\/.*localtunnel.me' + '$').test(tunnel.url));
test._fake_url = tunnel.url;
done();
});
});
test('override Host header with local-host', function(done) {
var uri = test._fake_url;
var parsed = url.parse(uri);
var opt = {
host: parsed.host,
port: 443,
headers: {
host: parsed.hostname
},
path: '/'
};
var req = https.request(opt, function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
assert.equal(body, 'localhost');
done();
});
});
req.end();
});
suite('--local-host 127.0.0.1');
test('setup localtunnel client', function(done) {
var opt = {
local_host: '127.0.0.1'
};
localtunnel(test._fake_port, opt, function(err, tunnel) {
assert.ifError(err);
assert.ok(new RegExp('^https:\/\/.*localtunnel.me' + '$').test(tunnel.url));
test._fake_url = tunnel.url;
done();
});
});
test('override Host header with local-host', function(done) {
var uri = test._fake_url;
var parsed = url.parse(uri);
var opt = {
host: parsed.host,
port: 443,
headers: {
host: parsed.hostname
},
path: '/'
};
var req = https.request(opt, function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
assert.equal(body, '127.0.0.1');
done();
});
});
req.end();
});
test('send chunked request', function(done) {
var uri = test._fake_url;
var parsed = url.parse(uri);
var opt = {
host: parsed.host,
port: 443,
headers: {
host: parsed.hostname,
'Transfer-Encoding': 'chunked'
},
path: '/'
};
var req = https.request(opt, function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
assert.equal(body, '127.0.0.1');
done();
});
});
req.end(require('crypto').randomBytes(1024 * 8).toString('base64'));
});