diff --git a/config.default.json b/config.default.json index 73a6be43..314f7c9a 100644 --- a/config.default.json +++ b/config.default.json @@ -7,9 +7,7 @@ "ssl": false, "static": false }, - "bin": { - "max-size": 1572864 - }, + "max-request-size": "1MB", "store": { "adapter": "sqlite", "sqlite": { diff --git a/lib/app.js b/lib/app.js index b65c4ea6..38f99299 100644 --- a/lib/app.js +++ b/lib/app.js @@ -128,7 +128,7 @@ app.connect = function (callback) { } app.use(mount, express.static(path.join(app.set('root'), 'public'))); - app.use(middleware.limitContentLength({limit: app.set('bin max-size')})); + app.use(middleware.limitContentLength({limit: app.set('max-request-size')})); app.use(express.cookieParser(app.set('session secret'))); app.use(express.cookieSession({key: 'jsbin'})); app.use(express.urlencoded()); diff --git a/lib/middleware.js b/lib/middleware.js index c712773a..0d98b305 100644 --- a/lib/middleware.js +++ b/lib/middleware.js @@ -123,12 +123,37 @@ module.exports = { // Limit the file size that can be uploaded. limitContentLength: function (options) { + var powers = { k: 1, m: 2, g: 3, t: 4 }, + regexp = /^(\d+(?:.\d+)?)\s*([kmgt]?)b?$/; + + // Parse a string representing a file size and convert it into bytes. + // A number on it's own will be assumed to be bytes. A multiple such as + // "k" or "m" can be appended to the string to handle larger numbers. This + // is case insensitive and uses powers of 1024 rather than (1000). + // So both 1kB and 1kb == 1024. + function parseLimit(string) { + var matches = ('' + string).toLowerCase().match(regexp), + bytes = null, power; + + if (matches) { + bytes = parseFloat(matches[1]); + power = powers[matches[2]]; + + if (bytes && power) { + bytes = Math.pow(bytes * 1024, power); + } + } + + return bytes || null; + } + return function (req, res, next) { if (options && options.limit) { - var contentLength = parseInt(req.header('Content-Length', 0), 10), - message = 'Sorry, the content you have uploaded is larger than JS Bin can handle. Max size is ' + options.limit + ' bytes'; + var limit = options.limit && parseLimit(options.limit), + contentLength = parseInt(req.header('Content-Length', 0), 10), + message = 'Sorry, the content you have uploaded is larger than JS Bin can handle. Max size is ' + options.limit; - if (contentLength > options.limit) { + if (limit && contentLength > limit) { return next(new errors.RequestEntityTooLarge(message)); } }