michael@0: var fs = require('fs'); michael@0: var path = require('path'); michael@0: var http2 = require('..'); michael@0: var tls = require('tls'); michael@0: michael@0: var exists = fs.existsSync; michael@0: var stat = fs.statSync; michael@0: var read = fs.createReadStream; michael@0: var join = path.join; michael@0: michael@0: // Advertised protocol version michael@0: var implementedVersion = http2.ImplementedVersion; michael@0: michael@0: // Bunyan logger michael@0: var log = require('../test/util').createLogger('server'); michael@0: michael@0: // We cache one file to be able to do simple performance tests without waiting for the disk michael@0: var cachedFile = fs.readFileSync(path.join(__dirname, './server.js')); michael@0: var cachedUrl = '/server.js'; michael@0: michael@0: // Creating the server michael@0: tls.createServer({ michael@0: ALPNProtocols: [implementedVersion], michael@0: NPNProtocols: [implementedVersion], michael@0: key: fs.readFileSync(path.join(__dirname, '/localhost.key')), michael@0: cert: fs.readFileSync(path.join(__dirname, '/localhost.crt')) michael@0: }).on('secureConnection', onConnection).listen(process.env.HTTP2_PORT || 8080); michael@0: michael@0: // Handling incoming connections michael@0: function onConnection(socket) { michael@0: var endpoint = new http2.Endpoint(log, 'SERVER', {}); michael@0: endpoint.pipe(socket).pipe(endpoint); michael@0: michael@0: endpoint.on('stream', function(stream) { michael@0: stream.on('headers', function(headers) { michael@0: var path = headers[':path']; michael@0: var filename = join(__dirname, path); michael@0: michael@0: // Serving server.js from cache. Useful for microbenchmarks. michael@0: if (path == cachedUrl) { michael@0: stream.headers({ ':status': 200 }); michael@0: stream.end(cachedFile); michael@0: } michael@0: michael@0: // Reading file from disk if it exists and is safe. michael@0: else if ((filename.indexOf(__dirname) === 0) && exists(filename) && stat(filename).isFile()) { michael@0: stream.headers({ ':status': 200 }); michael@0: michael@0: // If they download the certificate, push the private key too, they might need it. michael@0: if (path === '/localhost.crt') { michael@0: var push = stream.promise({ michael@0: ':method': 'GET', michael@0: ':scheme': headers[':scheme'], michael@0: ':authority': headers[':authority'], michael@0: ':path': '/localhost.key' michael@0: }); michael@0: push.headers({ ':status': 200 }); michael@0: read(join(__dirname, '/localhost.key')).pipe(push); michael@0: } michael@0: michael@0: read(filename).pipe(stream); michael@0: } michael@0: michael@0: // Otherwise responding with 404. michael@0: else { michael@0: stream.headers({ ':status': 404 }); michael@0: stream.end(); michael@0: } michael@0: }); michael@0: }); michael@0: }