Commit 0e499fab authored by lazorfuzz's avatar lazorfuzz
Browse files

initial commit

parents
Copyright © 2013 lazorfuzz.
Released under the terms of the MIT License:
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.
web: node server.js
\ No newline at end of file
# SignalBuddy
A scalable signaling server for WebRTC using socket.io, NodeJS cluster, and Redis. Made for use with [liowebrtc](https://github.com/lazorfuzz/liowebrtc) and [react-liowebrtc](https://github.com/lazorfuzz/react-liowebrtc).
## What is SignalBuddy?
SignalBuddy is an easy-to-scale signaling solution for WebRTC. SignalBuddy automatically detects and scales across the number of CPU cores in its environment. For instance, if the machine you're testing on has four cores, SignalBuddy will launch a cluster of four processes, each a separate instance of itself, all listening on the same port. Using Redis to store state, peers connected to different worker instances will still be able to broadcast and transmit data to one another.
## Running
First, install and start Redis. Once Redis is listening on the default port (6379), `cd` into the signalbuddy project.
After cd'ing into the signalbuddy project:
```
npm install
```
Build the project:
```
npm build
```
Start in dev mode:
```
npm start
```
If all goes well, your console should display a message like this:
```
Listening at http://localhost:8888/
```
If you open the URL in a web browser, you should see an output displaying which worker process you're currently connected to. Exempli gratia:
```
worker: 4
```
## Production
To run in production mode:
```
NODE_ENV=production node dist/server.js
```
Most likely, you'll want the server to be secure. You can either pass in the paths to your key/cert through the environment variables PRIV_KEY and CERT:
```
NODE_ENV=production PRIV_KEY=/etc/example/privKey.pem CERT=/etc/example/cert.pem node dist/server.js
```
Or you can also add your key/cert paths to the production.json file in the config folder.
---
This project is still in development. In the near future I will add a Dockerfile, as well as additional deployment methods and helpers that will make it easier to deploy on AWS, Digital Ocean, etc.
{
"isDev": true,
"server": {
"port": 8888,
"/* secure */": "/* whether this connects via https */",
"secure": false,
"key": null,
"cert": null,
"password": null
},
"redis": {
"endpoint": "localhost",
"port": 6379
},
"rooms": {
"/* maxClients */": "/* maximum number of clients per room. 0 = no limit */",
"maxClients": 0
},
"stunservers": [
{
"urls": "stun:stun.l.google.com:19302"
}
],
"turnservers": [
{
"urls": ["turn:your.turn.servers.here"],
"secret": "turnserversharedsecret",
"expiry": 86400
}
]
}
{
"isDev": true,
"server": {
"port": 443,
"secure": true,
"key": null,
"cert": null
},
"rooms": {
"/* maxClients */": "/* maximum number of clients per room. 0 = no limit */",
"maxClients": 0
},
"stunservers": [
{
"urls": "stun:stun.l.google.com:19302"
}
],
"turnservers": []
}
'use strict';
var _getconfig = require('getconfig');
var _getconfig2 = _interopRequireDefault(_getconfig);
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
var _os = require('os');
var _os2 = _interopRequireDefault(_os);
var _stickySession = require('sticky-session');
var _stickySession2 = _interopRequireDefault(_stickySession);
var _farmhash = require('farmhash');
var _farmhash2 = _interopRequireDefault(_farmhash);
var _net = require('net');
var _net2 = _interopRequireDefault(_net);
var _cluster = require('cluster');
var _cluster2 = _interopRequireDefault(_cluster);
var _http = require('http');
var _http2 = _interopRequireDefault(_http);
var _https = require('https');
var _https2 = _interopRequireDefault(_https);
var _sockets = require('./sockets');
var _sockets2 = _interopRequireDefault(_sockets);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* global console */
var port = parseInt(process.env.PORT || _getconfig2.default.server.port, 10);
var redisEndpoint = process.env.REDIS_ENDPOINT || _getconfig2.default.redis.endpoint;
var redisPort = process.env.REDIS_PORT || _getconfig2.default.redis.port;
var numProcesses = _os2.default.cpus().length;
if (_cluster2.default.isMaster) {
var workers = [];
var spawn = function spawn(i) {
workers[i] = _cluster2.default.fork();
// Optional: Restart worker on exit
workers[i].on('exit', function (code, signal) {
console.log('respawning worker', i);
spawn(i);
});
};
for (var i = 0; i < numProcesses; i += 1) {
spawn(i);
}
var workerIndex = function workerIndex(ip, len) {
return (// Farmhash is the fastest and works with IPv6, too
_farmhash2.default.fingerprint32(ip) % len
);
};
// Create the outside facing server listening on our port.
var masterServer = _net2.default.createServer({ pauseOnConnect: true }, function (connection) {
// We received a connection and need to pass it to the appropriate
// worker. Get the worker for this connection's source IP and pass
// it the connection.
var worker = workers[workerIndex(connection.remoteAddress, numProcesses)];
worker.send('sticky-session:connection', connection);
}).listen(port);
console.log('Listening at ' + (_getconfig2.default.server.secure ? 'https' : 'http') + '://localhost:' + port + '/');
} else {
var serverHandler = function serverHandler(req, res) {
if (req.url === '/healthcheck') {
console.log(Date.now(), 'healthcheck');
res.writeHead(200);
res.end();
return;
}
res.writeHead(404);
res.end('worker: ' + _cluster2.default.worker.id);
};
var server = null;
// Create an http(s) server instance to that socket.io can listen to
if (_getconfig2.default.server.secure) {
server = _https2.default.Server({
key: _fs2.default.readFileSync(_getconfig2.default.server.key),
cert: _fs2.default.readFileSync(_getconfig2.default.server.cert),
passphrase: _getconfig2.default.server.password
}, serverHandler);
} else {
server = _http2.default.Server(serverHandler);
}
if (!_stickySession2.default.listen(server, port)) {
// Master code
/* server.once('listening', function() {
}); */
} else {
// Worker code
}
server.listen(0);
(0, _sockets2.default)(server, Object.assign({ redisEndpoint: redisEndpoint, redisPort: redisPort }, _getconfig2.default));
if (_getconfig2.default.uid) process.setuid(_getconfig2.default.uid);
process.on('message', function (message, connection) {
if (message !== 'sticky-session:connection') {
return;
}
// Emulate a connection event on the server by emitting the
// event with the connection the master sent us.
server.emit('connection', connection);
connection.resume();
});
}
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _arguments = arguments;
var _socket = require('socket.io');
var _socket2 = _interopRequireDefault(_socket);
var _nodeUuid = require('node-uuid');
var _nodeUuid2 = _interopRequireDefault(_nodeUuid);
var _crypto = require('crypto');
var _crypto2 = _interopRequireDefault(_crypto);
var _socket3 = require('socket.io-redis');
var _socket4 = _interopRequireDefault(_socket3);
var _util = require('./util');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (server, config) {
var io = _socket2.default.listen(server);
io.adapter((0, _socket4.default)({ host: config.redis.host, port: config.redis.port }));
io.on('connection', function (client) {
client.resources = {
screen: false,
video: true,
audio: false
};
// pass a message to another id
client.on('message', function (details) {
if (!details) return;
var otherClient = io.to(details.to);
if (!otherClient) return;
details.from = client.id;
otherClient.emit('message', details);
});
client.on('join', join);
client.on('getClients', getClients);
client.on('getClientCount', getClientCount);
function removeFeed(type) {
if (client.room) {
io.in(client.room).emit('remove', {
id: client.id,
type: type
});
if (!type) {
client.leave(client.room);
client.room = undefined;
}
}
}
function join(name, cb) {
// sanity check
if (typeof name !== 'string') return;
// check if maximum number of clients reached
if (config.rooms && config.rooms.maxClients > 0) {
getClientCount(name).then(function (count) {
if (count > config.rooms.maxClients) {
removeFeed();
}
});
}
// leave any existing rooms
removeFeed();
getClients(name, function (err, clients) {
return (0, _util.safeCb)(cb)(err, clients);
});
client.join(name);
client.room = name;
}
function getClients(roomName, callback) {
describeRoom(roomName).then(function (description) {
var obj = { clients: {} };
description.forEach(function (k, i) {
obj.clients[k] = client.resources;
});
(0, _util.safeCb)(callback)(null, obj);
}).catch(function (err) {
return (0, _util.safeCb)(callback)(err, null);
});
}
function getClientCount(roomName, callback) {
clientsInRoom(roomName).then(function (num) {
if (roomName) (0, _util.safeCb)(callback)(num);
});
}
// we don't want to pass "leave" directly because the
// event type string of "socket end" gets passed too.
client.on('disconnect', function () {
removeFeed();
});
client.on('leave', function () {
removeFeed();
});
client.on('create', function (name, cb) {
if (_arguments.length === 2) {
cb = typeof cb === 'function' ? cb : function () {};
name = name || (0, _nodeUuid2.default)();
} else {
cb = name;
name = (0, _nodeUuid2.default)();
}
// check if exists
var room = io.nsps['/'].adapter.rooms[name];
if (room && room.length) {
(0, _util.safeCb)(cb)('taken');
} else {
join(name);
(0, _util.safeCb)(cb)(null, name);
}
});
// support for logging full webrtc traces to stdout
// useful for large-scale error monitoring
client.on('trace', function (data) {
// console.log('trace', JSON.stringify([data.type, data.session, data.prefix, data.peer, data.time, data.value]));
});
// tell client about stun and turn servers and generate nonces
client.emit('stunservers', config.stunservers || []);
// create shared secret nonces for TURN authentication
// the process is described in draft-uberti-behave-turn-rest
var credentials = [];
// allow selectively vending turn credentials based on origin.
var origin = client.handshake.headers.origin;
if (!config.turnorigins || config.turnorigins.includes(origin)) {
config.turnservers.forEach(function (server) {
var hmac = _crypto2.default.createHmac('sha1', server.secret);
// default to 86400 seconds timeout unless specified
var username = '' + (Math.floor(new Date().getTime() / 1000) + parseInt(server.expiry || 86400, 10));
hmac.update(username);
credentials.push({
username: username,
credential: hmac.digest('base64'),
urls: server.urls || server.url
});
});
}
client.emit('turnservers', credentials);
});
function describeRoom(roomName) {
return new Promise(function (resolve, reject) {
io.in(roomName).clients(function (err, clients) {
if (err) {
reject(err);
return;
}
resolve(clients);
});
});
}
function clientsInRoom(roomName) {
return new Promise(function (resolve, reject) {
io.in(roomName).clients(function (err, clients) {
if (err) {
reject(err);
return;
}
resolve(clients.length);
});
});
}
};
\ No newline at end of file
'use strict';
var _tape = require('tape');
var _tape2 = _interopRequireDefault(_tape);
var _getconfig = require('getconfig');
var _getconfig2 = _interopRequireDefault(_getconfig);
var _server = require('./server');
var _server2 = _interopRequireDefault(_server);
var _socket = require('socket.io-client');
var _socket2 = _interopRequireDefault(_socket);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var test = _tape2.default.createHarness();
var output = test.createStream();
output.pipe(process.stdout);
output.on('end', function () {
console.log('Tests complete, killing server.');
process.exit(0);
});
var socketURL = void 0;
if (_getconfig2.default.server.secure) {
socketURL = 'https://localhost:' + _getconfig2.default.server.port;
} else {
socketURL = 'http://localhost:' + _getconfig2.default.server.port;
}
var socketOptions = {
transports: ['websocket'],
'force new connection': true,
secure: _getconfig2.default.server.secure
};
test('it should not crash when sent an empty message', function (t) {
t.plan(1);
var client = _socket2.default.connect(socketURL, socketOptions);
client.on('connect', function () {
client.emit('message');
t.ok(true);
});
});
\ No newline at end of file
'use strict';
function safeCb(cb) {
if (typeof cb === 'function') {
return cb;
}
return function () {};
}
module.exports = {
safeCb: safeCb
};
\ No newline at end of file
{
"name": "signalbuddy",
"description": "A scalable, socket.io WebRTC signaling solution for LioWebRTC.",
"version": "1.0.0",
"dependencies": {
"farmhash": "^2.1.0",
"getconfig": "^4.3.0",
"node-uuid": "1.2.0",
"socket.io": "^1.7.4",
"socket.io-redis": "4.0.1",
"sticky-session": "^1.1.2"
},
"main": "dist/server.js",
"repository": "https://github.com/lazorfuzz/signalbuddy",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-eslint": "^8.2.3",
"babel-preset-env": "^1.7.0",
"eslint": "^4.19.1",
"eslint-config-airbnb": "^16.1.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-jsx-a11y": "^6.0.2",
"eslint-plugin-react": "^7.4.0",
"precommit-hook": "0.3.10",
"socket.io-client": "^1.7.4",
"tape": "^2.13.1"
},
"license": "MIT",
"scripts": {
"test": "node test.js",
"build": "babel src --presets babel-preset-env --out-dir dist",
"start": "node dist/server.js"
}
}
#!/bin/bash
if [ ! -e server.js ]
then
echo "Error: could not find main application server.js file"
echo "You should run the generate-ssl-certs.sh script from the main application root directory"
echo "i.e: bash scripts/generate-ssl-certs.sh"
exit -1
fi
echo "Generating self-signed certificates..."
mkdir -p ./config/sslcerts
openssl genrsa -out ./config/sslcerts/key.pem 1024
openssl req -new -key ./config/sslcerts/key.pem -out ./config/sslcerts/csr.pem
openssl x509 -req -days 9999 -in ./config/sslcerts/csr.pem -signkey ./config/sslcerts/key.pem -out ./config/sslcerts/cert.pem
rm ./config/sslcerts/csr.pem
chmod 600 ./config/sslcerts/key.pem ./config/sslcerts/cert.pem
/* global console */
import config from 'getconfig';
import fs from 'fs';
import os from 'os';
import sticky from 'sticky-session';
import farmhash from 'farmhash';
import net from 'net';
import cluster from 'cluster';
import http from 'http';
import https from 'https';
import sockets from './sockets';
const port = parseInt(process.env.PORT || config.server.port, 10);
const redisEndpoint = process.env.REDIS_ENDPOINT || config.redis.endpoint;
const redisPort = process.env.REDIS_PORT || config.redis.port;
const numProcesses = os.cpus().length;
if (cluster.isMaster) {
const workers = [];
const spawn = (i) => {
workers[i] = cluster.fork();
// Optional: Restart worker on exit
workers[i].on('exit', (code, signal) => {
console.log('respawning worker', i);
spawn(i);
});
};
for (let i = 0; i < numProcesses; i += 1) {
spawn(i);
}
const workerIndex = (ip, len) => // Farmhash is the fastest and works with IPv6, too
farmhash.fingerprint32(ip) % len;
// Create the outside facing server listening on our port.
const masterServer = net.createServer({ pauseOnConnect: true