node-http-server – Rev 15

Subversion Repositories:
Rev:
#!/usr/bin/env node

/*************************************************************************/
/*    Copyright (C) 2017 Wizardry and Steamworks - License: GNU GPLv3    */
/*************************************************************************/

const url = require('url');
const path = require('path');
const fs = require('fs');
const mime = require('mime');
const auth = require("http-auth");

// Checks whether userPath is a child of rootPath.
function isRooted(userPath, rootPath, separator, callback) {
    process.nextTick(() => {
        userPath = userPath.split(separator).filter(Boolean);
        rootPath = rootPath.split(separator).filter(Boolean);
        callback(userPath.length >= rootPath.length &&
            rootPath.every((e, i) => e === userPath[i]));
    });
}

// Serves files.
function files(config, request, response, resource, callback) {
    // Check if the file is accessible.
    fs.access(resource, fs.constants.R_OK, (error) => {
        if (error) {
            response.statusCode = 403;
            response.end();
            return;
        }

        response.setHeader(
            'Content-Type',
            mime.lookup(resource)
        );

        var readStream = fs.createReadStream(resource)
            .on('open', () => {
                response.statusCode = 200;
                readStream.pipe(response);
            })
            .on('error', () => {
                response.statusCode = 500;
                response.end();
            });

    });
}

// Serves a directory listing or the document index in case it exists.
function index(config, request, response, resource, root, callback) {
    fs.stat(root, (error, stats) => {
        if (error) {
            fs.readdir(resource, (error, paths) => {
                if (error) {
                    process.nextTick(() => {
                        callback('Could not list directory: ' +
                            resource,
                            module.exports.error.level.ERROR
                        );
                    });
                    response.statusCode = 500;
                    response.end();
                    return;
                }
                process.nextTick(() => {
                    callback('Directory listing requested for: ' +
                        resource,
                        module.exports.error.level.INFO
                    );
                });
                response.statusCode = 200;
                response.write(JSON.stringify(paths));
                response.end();
            });

            return;
        }

        // Serve the document index.
        fs.access(resource, fs.constants.R_OK, (error) => {
            if (error) {
                process.nextTick(() => {
                    callback('The server was unable to access the filesystem path: ' +
                        resource,
                        module.exports.error.level.WARN
                    );
                });
                response.statusCode = 403;
                response.end();
                return;
            }

            // Set MIME content type.
            response.setHeader(
                'Content-Type',
                mime.lookup(root)
            );

            var readStream = fs.createReadStream(root)
                .on('open', () => {
                    response.statusCode = 200;
                    readStream.pipe(response);
                })
                .on('error', () => {
                    response.statusCode = 500;
                    response.end();
                });

        });
    });
}

// Determines whether the requested resource is a directory or a file.
function serve(config, request, response, resource, callback) {
    fs.stat(resource, (error, stats) => {
        // Document does not exist.
        if (error) {
            response.statusCode = 404;
            response.end();
            return;
        }

        switch (stats.isDirectory()) {
            case true: // Directory is requested so provide directory indexes.
                index(config, request, response, resource, path.resolve(resource, config.site.index), callback)
                break;
            default: // Browser requesting file.
                files(config, request, response, resource, callback);
                break;
        }
    });
}

module.exports = {
    error: {
        level: {
            INFO: 1,
            WARN: 2,
            ERROR: 3
        }
    },
    process: (config, request, response, root, callback) => {
        process.nextTick(() => {
            // Create digest authentication.
            const authentication = auth.digest({
                realm: config.auth.realm,
                file: path.resolve(
                    path.dirname(require.main.filename),
                    config.auth.digest
                )
            });

            const requestAddress = request.socket.address();
            const requestedURL = url.parse(
                request.url, true
            );

            const trimmedPath = requestedURL
                .pathname
                .split('/')
                .filter(Boolean)
                .join('/');
            const resource = trimmedPath === '/' ?
                path.join(root, trimmedPath) :
                path.resolve(root, trimmedPath);

            isRooted(resource, root, path.sep, (rooted) => {
                if (!rooted) {
                    process.nextTick(() => {
                        callback('Attempted path traversal: ' +
                            requestAddress.address + ':' +
                            requestAddress.port +
                            ' requesting: ' +
                            requestedURL.pathname,
                            module.exports.error.level.WARN
                        );
                    });
                    response.statusCode = 404;
                    response.end();
                    return;
                }

                // Check if the requested path requires authentication.
                switch (config.auth.locations.some(
                    (authPath) => authPath.toUpperCase() === requestedURL.pathname.toUpperCase())) {
                    case true:
                        // Requested location requires authentication.
                        authentication.check(request, response, (request, response) => {
                            process.nextTick(() => {
                                callback('Authenticated client: ' +
                                    requestAddress.address + ':' +
                                    requestAddress.port +
                                    ' accessing: ' +
                                    requestedURL.pathname,
                                    module.exports.error.level.INFO
                                );
                            });
                            serve(config, request, response, resource, callback);
                        });
                        break;
                    default:
                        process.nextTick(() => {
                            callback('Client: ' +
                                requestAddress.address + ':' +
                                requestAddress.port +
                                ' accessing: ' +
                                requestedURL.pathname,
                                module.exports.error.level.INFO
                            );
                        });
                        serve(config, request, response, resource, callback);
                        break;
                }
            });
        });
    }
};

Generated by GNU Enscript 1.6.5.90.