|
1 var fs = require('fs'); |
|
2 var path = require('path'); |
|
3 var http2 = require('..'); |
|
4 var tls = require('tls'); |
|
5 |
|
6 var exists = fs.existsSync; |
|
7 var stat = fs.statSync; |
|
8 var read = fs.createReadStream; |
|
9 var join = path.join; |
|
10 |
|
11 // Advertised protocol version |
|
12 var implementedVersion = http2.ImplementedVersion; |
|
13 |
|
14 // Bunyan logger |
|
15 var log = require('../test/util').createLogger('server'); |
|
16 |
|
17 // We cache one file to be able to do simple performance tests without waiting for the disk |
|
18 var cachedFile = fs.readFileSync(path.join(__dirname, './server.js')); |
|
19 var cachedUrl = '/server.js'; |
|
20 |
|
21 // Creating the server |
|
22 tls.createServer({ |
|
23 ALPNProtocols: [implementedVersion], |
|
24 NPNProtocols: [implementedVersion], |
|
25 key: fs.readFileSync(path.join(__dirname, '/localhost.key')), |
|
26 cert: fs.readFileSync(path.join(__dirname, '/localhost.crt')) |
|
27 }).on('secureConnection', onConnection).listen(process.env.HTTP2_PORT || 8080); |
|
28 |
|
29 // Handling incoming connections |
|
30 function onConnection(socket) { |
|
31 var endpoint = new http2.Endpoint(log, 'SERVER', {}); |
|
32 endpoint.pipe(socket).pipe(endpoint); |
|
33 |
|
34 endpoint.on('stream', function(stream) { |
|
35 stream.on('headers', function(headers) { |
|
36 var path = headers[':path']; |
|
37 var filename = join(__dirname, path); |
|
38 |
|
39 // Serving server.js from cache. Useful for microbenchmarks. |
|
40 if (path == cachedUrl) { |
|
41 stream.headers({ ':status': 200 }); |
|
42 stream.end(cachedFile); |
|
43 } |
|
44 |
|
45 // Reading file from disk if it exists and is safe. |
|
46 else if ((filename.indexOf(__dirname) === 0) && exists(filename) && stat(filename).isFile()) { |
|
47 stream.headers({ ':status': 200 }); |
|
48 |
|
49 // If they download the certificate, push the private key too, they might need it. |
|
50 if (path === '/localhost.crt') { |
|
51 var push = stream.promise({ |
|
52 ':method': 'GET', |
|
53 ':scheme': headers[':scheme'], |
|
54 ':authority': headers[':authority'], |
|
55 ':path': '/localhost.key' |
|
56 }); |
|
57 push.headers({ ':status': 200 }); |
|
58 read(join(__dirname, '/localhost.key')).pipe(push); |
|
59 } |
|
60 |
|
61 read(filename).pipe(stream); |
|
62 } |
|
63 |
|
64 // Otherwise responding with 404. |
|
65 else { |
|
66 stream.headers({ ':status': 404 }); |
|
67 stream.end(); |
|
68 } |
|
69 }); |
|
70 }); |
|
71 } |