etherpad-lite/node/server.js

505 lines
15 KiB
JavaScript
Raw Normal View History

/**
2011-05-30 16:53:11 +02:00
* This module is started with bin/run.sh. It sets up a Express HTTP and a Socket.IO Server.
* Static file Requests are answered directly from this module, Socket.IO messages are passed
* to MessageHandler and minfied requests are passed to minified.
*/
/*
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
2011-03-26 14:10:41 +01:00
var ERR = require("async-stacktrace");
var log4js = require('log4js');
2011-08-18 22:29:34 +02:00
var os = require("os");
var socketio = require('socket.io');
2011-06-30 21:03:09 +02:00
var fs = require('fs');
2011-07-27 19:52:23 +02:00
var settings = require('./utils/Settings');
var db = require('./db/DB');
2011-05-19 18:36:26 +02:00
var async = require('async');
var express = require('express');
var path = require('path');
2011-07-27 19:52:23 +02:00
var minify = require('./utils/Minify');
var formidable = require('formidable');
var apiHandler;
var exportHandler;
2011-07-21 21:13:58 +02:00
var importHandler;
2011-07-08 19:33:01 +02:00
var exporthtml;
var readOnlyManager;
var padManager;
var securityManager;
var socketIORouter;
2011-05-19 18:36:26 +02:00
2011-06-30 21:03:09 +02:00
//try to get the git version
var version = "";
try
{
var rootPath = path.normalize(__dirname + "/../")
var ref = fs.readFileSync(rootPath + ".git/HEAD", "utf-8");
var refPath = rootPath + ".git/" + ref.substring(5, ref.indexOf("\n"));
2011-06-30 21:03:09 +02:00
version = fs.readFileSync(refPath, "utf-8");
2011-08-19 23:01:33 +02:00
version = version.substring(0, 7);
console.log("Your Etherpad Lite git version is " + version);
2011-06-30 21:03:09 +02:00
}
catch(e)
{
2011-07-31 19:25:51 +02:00
console.warn("Can't get git version for server header\n" + e.message)
2011-06-30 21:03:09 +02:00
}
2011-08-21 20:52:24 +02:00
console.log("Report bugs at https://github.com/Pita/etherpad-lite/issues")
2011-06-30 21:03:09 +02:00
var serverName = "Etherpad-Lite " + version + " (http://j.mp/ep-lite)";
2011-07-21 21:13:58 +02:00
//cache 6 hours
exports.maxAge = 1000*60*60*6;
2011-05-19 18:36:26 +02:00
2011-08-17 18:45:47 +02:00
//set loglevel
log4js.setGlobalLogLevel(settings.loglevel);
2011-05-14 19:57:07 +02:00
async.waterfall([
2011-05-19 18:36:26 +02:00
//initalize the database
2011-05-14 19:57:07 +02:00
function (callback)
{
db.init(callback);
},
2011-05-19 18:36:26 +02:00
//initalize the http server
2011-05-14 19:57:07 +02:00
function (callback)
2011-03-26 14:10:41 +01:00
{
2011-05-19 18:36:26 +02:00
//create server
var app = express.createServer();
app.use(function (req, res, next) {
res.header("Server", serverName);
next();
});
2011-07-08 19:33:01 +02:00
//load modules that needs a initalized db
2011-07-27 19:52:23 +02:00
readOnlyManager = require("./db/ReadOnlyManager");
exporthtml = require("./utils/ExportHtml");
exportHandler = require('./handler/ExportHandler');
importHandler = require('./handler/ImportHandler');
apiHandler = require('./handler/APIHandler');
padManager = require('./db/PadManager');
securityManager = require('./db/SecurityManager');
socketIORouter = require("./handler/SocketIORouter");
2011-07-08 19:33:01 +02:00
2011-07-31 19:25:51 +02:00
//install logging
var httpLogger = log4js.getLogger("http");
app.configure(function()
{
// Activate http basic auth if it has been defined in settings.json
if(settings.httpAuth != null) app.use(basic_auth);
2011-11-03 07:34:51 +01:00
// If the log level specified in the config file is WARN or ERROR the application server never starts listening to requests as reported in issue #158.
// Not installing the log4js connect logger when the log level has a higher severity than INFO since it would not log at that level anyway.
if (!(settings.loglevel === "WARN" || settings.loglevel == "ERROR"))
app.use(log4js.connectLogger(httpLogger, { level: log4js.levels.INFO, format: ':status, :method :url'}));
app.use(express.cookieParser());
2011-07-31 19:25:51 +02:00
});
2011-05-19 18:36:26 +02:00
app.error(function(err, req, res, next){
res.send(500);
console.error(err.stack ? err.stack : err.toString());
gracefulShutdown();
});
//serve minified files
app.get('/minified/:filename', minify.minifyJS);
2011-05-19 18:36:26 +02:00
//serve static files
app.get('/static/js/require-kernel.js', function (req, res, next) {
res.header("Content-Type","application/javascript; charset: utf-8");
res.write(minify.requireDefinition());
res.end();
});
2011-05-19 18:36:26 +02:00
app.get('/static/*', function(req, res)
{
var filePath = path.normalize(__dirname + "/.." +
2011-09-01 23:24:51 +02:00
req.url.replace(/\.\./g, '').split("?")[0]);
res.sendfile(filePath, { maxAge: exports.maxAge });
2011-05-14 19:57:07 +02:00
});
2011-05-19 18:36:26 +02:00
//serve minified files
app.get('/minified/:filename', minify.minifyJS);
2011-08-21 20:43:42 +02:00
//checks for padAccess
function hasPadAccess(req, res, callback)
{
securityManager.checkAccess(req.params.pad, req.cookies.sessionid, req.cookies.token, req.cookies.password, function(err, accessObj)
{
if(ERR(err, callback)) return;
2011-08-21 20:43:42 +02:00
//there is access, continue
if(accessObj.accessStatus == "grant")
{
callback();
}
//no access
else
{
res.send("403 - Can't touch this", 403);
}
});
}
//checks for basic http auth
function basic_auth (req, res, next) {
if (req.headers.authorization && req.headers.authorization.search('Basic ') === 0) {
// fetch login and password
if (new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString() == settings.httpAuth) {
next();
return;
}
}
res.header('WWW-Authenticate', 'Basic realm="Protected Area"');
if (req.headers.authorization) {
setTimeout(function () {
res.send('Authentication required', 401);
2011-12-04 17:27:36 +01:00
}, 1000);
} else {
res.send('Authentication required', 401);
}
}
2011-08-21 20:43:42 +02:00
2011-07-08 19:33:01 +02:00
//serve read only pad
app.get('/ro/:id', function(req, res)
{
var html;
var padId;
var pad;
async.series([
//translate the read only pad to a padId
function(callback)
{
readOnlyManager.getPadId(req.params.id, function(err, _padId)
{
if(ERR(err, callback)) return;
2011-07-08 19:33:01 +02:00
padId = _padId;
2011-08-21 20:43:42 +02:00
//we need that to tell hasPadAcess about the pad
req.params.pad = padId;
callback();
2011-07-08 19:33:01 +02:00
});
},
//render the html document
function(callback)
{
//return if the there is no padId
if(padId == null)
{
callback("notfound");
return;
}
2011-08-21 20:43:42 +02:00
hasPadAccess(req, res, function()
2011-07-08 19:33:01 +02:00
{
2011-08-21 20:43:42 +02:00
//render the html document
exporthtml.getPadHTMLDocument(padId, null, false, function(err, _html)
{
if(ERR(err, callback)) return;
2011-08-21 20:43:42 +02:00
html = _html;
callback();
2011-08-21 20:43:42 +02:00
});
2011-07-08 19:33:01 +02:00
});
}
], function(err)
{
//throw any unexpected error
if(err && err != "notfound")
ERR(err);
2011-07-08 19:33:01 +02:00
if(err == "notfound")
res.send('404 - Not Found', 404);
else
res.send(html);
});
});
2011-12-16 21:41:11 +01:00
//redirects browser to the pad's sanitized url if needed. otherwise, renders the html
function goToPad(req, res, render) {
2011-06-30 13:40:31 +02:00
//ensure the padname is valid and the url doesn't end with a /
if(!padManager.isValidPadId(req.params.pad) || /\/$/.test(req.url))
2011-06-30 13:40:31 +02:00
{
res.send('Such a padname is forbidden', 404);
2011-06-30 13:40:31 +02:00
}
2011-12-16 21:41:11 +01:00
else
{
padManager.sanitizePadId(req.params.pad, function(padId) {
//the pad id was sanitized, so we redirect to the sanitized version
if(padId != req.params.pad)
{
var real_path = req.path.replace(/^\/p\/[^\/]+/, '/p/' + padId);
res.header('Location', real_path);
res.send('You should be redirected to <a href="' + real_path + '">' + real_path + '</a>', 302);
}
//the pad id was fine, so just render it
else
{
render();
}
});
}
}
//serve pad.html under /p
app.get('/p/:pad', function(req, res, next)
{
goToPad(req, res, function() {
var filePath = path.normalize(__dirname + "/../static/pad.html");
res.sendfile(filePath, { maxAge: exports.maxAge });
});
2011-05-19 18:36:26 +02:00
});
//serve timeslider.html under /p/$padname/timeslider
2011-06-30 13:40:31 +02:00
app.get('/p/:pad/timeslider', function(req, res, next)
{
2011-12-16 21:41:11 +01:00
goToPad(req, res, function() {
var filePath = path.normalize(__dirname + "/../static/timeslider.html");
res.sendfile(filePath, { maxAge: exports.maxAge });
});
});
//serve timeslider.html under /p/$padname/timeslider
app.get('/p/:pad/:rev?/export/:type', function(req, res, next)
{
2011-12-16 21:41:11 +01:00
goToPad(req, res, function() {
var types = ["pdf", "doc", "txt", "html", "odt", "dokuwiki"];
//send a 404 if we don't support this filetype
if(types.indexOf(req.params.type) == -1)
{
next();
return;
}
//if abiword is disabled, and this is a format we only support with abiword, output a message
if(settings.abiword == null &&
["odt", "pdf", "doc"].indexOf(req.params.type) !== -1)
{
res.send("Abiword is not enabled at this Etherpad Lite instance. Set the path to Abiword in settings.json to enable this feature");
return;
}
res.header("Access-Control-Allow-Origin", "*");
hasPadAccess(req, res, function()
{
exportHandler.doExport(req, res, req.params.pad, req.params.type);
});
});
});
2011-07-21 21:13:58 +02:00
//handle import requests
app.post('/p/:pad/import', function(req, res, next)
{
2011-12-16 21:41:11 +01:00
goToPad(req, res, function() {
//if abiword is disabled, skip handling this request
if(settings.abiword == null)
{
next();
return;
}
2011-12-16 21:41:11 +01:00
hasPadAccess(req, res, function()
{
importHandler.doImport(req, res, req.params.pad);
});
});
2011-07-21 21:13:58 +02:00
});
2011-08-08 18:45:44 +02:00
var apiLogger = log4js.getLogger("API");
2011-11-19 03:52:12 +01:00
//This is for making an api call, collecting all post information and passing it to the apiHandler
2011-12-16 21:41:11 +01:00
var apiCaller = function(req, res, fields)
{
res.header("Content-Type", "application/json; charset=utf-8");
2011-11-19 03:52:12 +01:00
apiLogger.info("REQUEST, " + req.params.func + ", " + JSON.stringify(fields));
2011-08-08 21:14:01 +02:00
//wrap the send function so we can log the response
res._send = res.send;
res.send = function(response)
{
2011-08-08 21:14:01 +02:00
response = JSON.stringify(response);
apiLogger.info("RESPONSE, " + req.params.func + ", " + response);
2011-08-17 19:24:14 +02:00
//is this a jsonp call, if yes, add the function call
if(req.query.jsonp)
response = req.query.jsonp + "(" + response + ")";
2011-08-08 21:14:01 +02:00
res._send(response);
}
2011-08-08 21:14:01 +02:00
//call the api handler
2011-11-19 03:52:12 +01:00
apiHandler.handle(req.params.func, fields, req, res);
}
//This is a api GET call, collect all post informations and pass it to the apiHandler
app.get('/api/1/:func', function(req, res)
{
apiCaller(req, res, req.query)
});
//This is a api POST call, collect all post informations and pass it to the apiHandler
app.post('/api/1/:func', function(req, res)
{
new formidable.IncomingForm().parse(req, function(err, fields, files)
{
apiCaller(req, res, fields)
});
});
//The Etherpad client side sends information about how a disconnect happen
app.post('/ep/pad/connection-diagnostic-info', function(req, res)
{
new formidable.IncomingForm().parse(req, function(err, fields, files)
{
2011-07-31 19:25:51 +02:00
console.log("DIAGNOSTIC-INFO: " + fields.diagnosticInfo);
res.end("OK");
});
});
//The Etherpad client side sends information about client side javscript errors
app.post('/jserror', function(req, res)
{
new formidable.IncomingForm().parse(req, function(err, fields, files)
{
console.error("CLIENT SIDE JAVASCRIPT ERROR: " + fields.errorInfo);
res.end("OK");
});
});
2011-05-19 18:36:26 +02:00
//serve index.html under /
app.get('/', function(req, res)
{
var filePath = path.normalize(__dirname + "/../static/index.html");
res.sendfile(filePath, { maxAge: exports.maxAge });
2011-05-19 18:36:26 +02:00
});
//serve robots.txt
app.get('/robots.txt', function(req, res)
{
var filePath = path.normalize(__dirname + "/../static/robots.txt");
res.sendfile(filePath, { maxAge: exports.maxAge });
2011-05-19 18:36:26 +02:00
});
//serve favicon.ico
app.get('/favicon.ico', function(req, res)
{
2011-08-20 20:27:41 +02:00
var filePath = path.normalize(__dirname + "/../static/custom/favicon.ico");
res.sendfile(filePath, { maxAge: exports.maxAge }, function(err)
{
//there is no custom favicon, send the default favicon
if(err)
{
filePath = path.normalize(__dirname + "/../static/favicon.ico");
res.sendfile(filePath, { maxAge: exports.maxAge });
}
});
2011-05-19 18:36:26 +02:00
});
//let the server listen
app.listen(settings.port, settings.ip);
console.log("Server is listening at " + settings.ip + ":" + settings.port);
2011-05-14 19:57:07 +02:00
2011-08-17 16:58:42 +02:00
var onShutdown = false;
var gracefulShutdown = function(err)
{
if(err && err.stack)
{
console.error(err.stack);
}
else if(err)
{
console.error(err);
}
//ensure there is only one graceful shutdown running
if(onShutdown) return;
onShutdown = true;
console.log("graceful shutdown...");
//stop the http server
app.close();
//do the db shutdown
db.db.doShutdown(function()
{
console.log("db sucessfully closed.");
process.exit(0);
});
setTimeout(function(){
process.exit(1);
}, 3000);
2011-08-17 16:58:42 +02:00
}
//connect graceful shutdown with sigint and uncaughtexception
if(os.type().indexOf("Windows") == -1)
{
//sigint is so far not working on windows
//https://github.com/joyent/node/issues/1553
process.on('SIGINT', gracefulShutdown);
}
2011-08-17 16:58:42 +02:00
process.on('uncaughtException', gracefulShutdown);
2011-05-19 18:36:26 +02:00
//init socket.io and redirect all requests to the MessageHandler
var io = socketio.listen(app);
2011-07-05 19:26:31 +02:00
//this is only a workaround to ensure it works with all browers behind a proxy
//we should remove this when the new socket.io version is more stable
2011-11-25 19:39:33 +01:00
io.set('transports', ['xhr-polling']);
2011-07-05 19:26:31 +02:00
2011-07-31 19:25:51 +02:00
var socketIOLogger = log4js.getLogger("socket.io");
io.set('logger', {
debug: function (str)
{
2011-11-19 23:14:31 +01:00
socketIOLogger.debug.apply(socketIOLogger, arguments);
2011-07-31 19:25:51 +02:00
},
info: function (str)
{
2011-11-19 23:14:31 +01:00
socketIOLogger.info.apply(socketIOLogger, arguments);
2011-07-31 19:25:51 +02:00
},
warn: function (str)
{
2011-11-19 23:14:31 +01:00
socketIOLogger.warn.apply(socketIOLogger, arguments);
2011-07-31 19:25:51 +02:00
},
error: function (str)
{
2011-11-19 23:14:31 +01:00
socketIOLogger.error.apply(socketIOLogger, arguments);
2011-07-31 19:25:51 +02:00
},
});
2011-07-07 19:15:39 +02:00
2011-07-27 15:46:45 +02:00
//minify socket.io javascript
if(settings.minify)
io.enable('browser client minification');
2011-07-27 19:52:23 +02:00
var padMessageHandler = require("./handler/PadMessageHandler");
var timesliderMessageHandler = require("./handler/TimesliderMessageHandler");
//Initalize the Socket.IO Router
socketIORouter.setSocketIO(io);
socketIORouter.addComponent("pad", padMessageHandler);
socketIORouter.addComponent("timeslider", timesliderMessageHandler);
2011-03-26 14:10:41 +01:00
2011-05-14 19:57:07 +02:00
callback(null);
2011-03-26 14:10:41 +01:00
}
2011-05-14 19:57:07 +02:00
]);