Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
superafroman committed Mar 12, 2011
0 parents commit fd34425
Show file tree
Hide file tree
Showing 11 changed files with 805 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/test.torrent
/ref
.project
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# node-torrent

A simple bittorrent client for node.

## Notes

This is very much a work in progress. The end goal is a simple
bittorrent client for use in other node applications.

## Usage

var Client = require('node-torrent');
var client = new Client();
client.addTorrent('a.torrent');

## License

(The MIT License)

Copyright (c) 2010 Max Stewart <max.stewart@superafroman.com>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
131 changes: 131 additions & 0 deletions lib/bencode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/**
* Original source:
* https://github.com/WizKid/node-bittorrent/blob/master/lib/bencode.js
*/

var sys = require("sys");

function Decoder(content) {
this.pos = 0;
this.content = content;
}

Decoder.prototype = {
decode: function() {
var ret = this._decode();
if (this.pos != this.content.length)
throw "Wrongly formatted bencoding string. Tried to parse something it didn't understood "+ this.pos +", "+ this.content.length;

return ret;
},

_decode: function () {
if (this.pos >= this.content.length)
throw "Wrongly formatted bencoding string. Pos have passed the length of the string."

var ret;
var c = this.content.charAt(this.pos);
switch (c) {
// Integer
case 'i':
var s = this.pos + 1;
while (this.pos < this.content.length && this.content.charAt(this.pos) != 'e')
this.pos++;

this.pos++;
ret = parseInt(this.content.substring(s, this.pos));
break;

// Dict
case 'd':
ret = {};
this.pos++;
while (this.pos < this.content.length && this.content.charAt(this.pos) != 'e') {
var key = this._decode();
if (key.constructor != String)
throw "Keys in dict must be strings"
ret[key] = this._decode();
}

this.pos++;
break;

// List
case 'l':
ret = [];
this.pos++;
while (this.pos < this.content.length && this.content.charAt(this.pos) != 'e')
ret.push(this._decode());

this.pos++;
break;

// String
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
var s = this.pos;
while (this.pos < this.content.length && this.content.charAt(this.pos) != ':')
this.pos++;

var len = parseInt(this.content.substring(s, this.pos));
s = this.pos + 1;
this.pos = s + len;
ret = this.content.substring(s, this.pos);
break;

default:
throw "Can't decode. No type starts with: "+ c;
break;
}

return ret;
}
}

function encode(obj) {
var ret;
switch(obj.constructor) {
case Number:
if (Math.round(obj) !== obj)
throw "Numbers can only contain integers and not floats";

ret = "i"+ obj.toString() +"e";
break;
case String:
ret = obj.length +":"+ obj;
break;
case Array:
ret = "l";
for (var k in obj)
ret += encode(obj[k]);
ret += "e";
break;
case Object:
ret = "d";
for (var k in obj)
ret += encode(k) + encode(obj[k]);
ret += "e";
break;
default:
throw "Bencode can only encode integers, strings, lists and dicts";
break;
}
return ret;
}

exports.decode = function(content) {
var p = new Decoder(content);
return p.decode();
}

exports.encode = function(obj) {
return encode(obj);
}
41 changes: 41 additions & 0 deletions lib/bufferutils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@

function concat(b1, b2) {
var b = new Buffer(b1.length + b2.length);
b1.copy(b, 0, 0);
b2.copy(b, b1.length, 0);
return b;
}

function equal(b1, b2) {
if (b1.length != b2.length) {
return false;
}
for (var i = 0; i < b1.length; i++) {
if (b1[i] != b2[i]) {
return false;
}
}
return true;
}

function readInt(buffer, offset) {
offset = offset || 0;
return buffer[offset] << 24 |
buffer[offset + 1] << 16 |
buffer[offset + 2] << 8 |
buffer[offset + 3];
}

function fromInt(int) {
var b = new Buffer(4);
b[0] = int >> 24 & 0xff;
b[1] = int >> 16 & 0xff;
b[2] = int >> 8 & 0xff;
b[3] = int & 0xff;
return b;
}

exports.concat = concat;
exports.equal = equal;
exports.fromInt = fromInt;
exports.readInt = readInt;
69 changes: 69 additions & 0 deletions lib/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@

var net = require("net");
var Torrent = require("./torrent");

var Client = function(options) {
options = options || {};
this.clientId = padClientId(options.clientId || '-NT0001-');
this.torrents = {};
this.server = net.createServer(this.handleConnection);
this.port = listen(this.server,
options.portRangeStart || 6881,
options.portRangeEnd || 6889);
};

// TODO: passing around clientId and port..?
// TODO: don't pass in file, or handle multiple types, e.g. urls
Client.prototype.addTorrent = function(file) {
var torrent = new Torrent(this.clientId, this.port, file);
var self = this;
torrent.on('ready', function() {
if (!self.torrents[torrent.infoHash]) {
self.torrents[torrent.infoHash] = torrent;
}
torrent.start();
});
};

Client.prototype.findTorrent = function(infoHash) {
return this.torrents[infoHash];
}

Client.prototype.handleConnection = function(stream) {
console.log('handleConnection: ' + stream);
// dns.reverse - http://nodejs.org/docs/v0.3.1/api/dns.html
};

function listen(server, startPort, endPort) {
var connected = false;
var port = startPort;

do {
try {
server.listen(port);
connected = true;
console.log('Listening for connections on %j', server.address());
} catch(err) {
}
}
while (!connected && port++ != endPort);

if (!connected) {
throw new Error('Could not listen on any ports in range ' + startPort + ' - ' + endPort);
}
return port;
}

function padClientId(clientId) {

var id = new Buffer(20);
id.write(clientId, 0, 'ascii');

var start = clientId.length;
for (var i = start; i < 20; i++) {
id[i] = Math.floor(Math.random() * 255);
}
return id;
}

module.exports = Client;
7 changes: 7 additions & 0 deletions lib/file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

var File = function(path, length) {
this.path = path;
this.length = length;
};

module.exports = File;
34 changes: 34 additions & 0 deletions lib/message.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@

var BufferUtils = require('./bufferutils');

var Message = function(code, payload) {
this.code = code;
this.payload = payload;
};

Message.prototype.writeTo = function(stream) {
var length = 1 + (this.payload ? this.payload.length : 0);
stream.write(BufferUtils.fromInt(length));

var code = new Buffer(1);
code[0] = this.code;
stream.write(code);

if (this.payload) {
stream.write(this.payload);
}
};

Message.KEEPALIVE = -1;
Message.CHOKE = 0;
Message.UNCHOKE = 1;
Message.INTERESTED = 2;
Message.UNINTERESTED = 3;
Message.HAVE = 4;
Message.BITFIELD = 5;
Message.REQUEST = 6;
Message.PIECE = 7;
Message.CANCEL = 8;
Message.PORT = 9;

module.exports = Message;
Loading

0 comments on commit fd34425

Please sign in to comment.