1'use strict'; 2const common = require('../common.js'); 3const bench = common.createBenchmark(main, { 4 dur: [5], 5 securing: ['SecurePair', 'TLSSocket', 'clear'], 6 size: [100, 1024, 1024 * 1024], 7}, { 8 flags: ['--no-warnings'], 9}); 10 11const fixtures = require('../../test/common/fixtures'); 12const tls = require('tls'); 13const net = require('net'); 14 15const REDIRECT_PORT = 28347; 16 17function main({ dur, size, securing }) { 18 const chunk = Buffer.alloc(size, 'b'); 19 20 const options = { 21 key: fixtures.readKey('rsa_private.pem'), 22 cert: fixtures.readKey('rsa_cert.crt'), 23 ca: fixtures.readKey('rsa_ca.crt'), 24 ciphers: 'AES256-GCM-SHA384', 25 isServer: true, 26 requestCert: true, 27 rejectUnauthorized: true, 28 maxVersion: 'TLSv1.2', 29 }; 30 31 const server = net.createServer(onRedirectConnection); 32 server.listen(REDIRECT_PORT, () => { 33 const proxy = net.createServer(onProxyConnection); 34 proxy.listen(common.PORT, () => { 35 const clientOptions = { 36 port: common.PORT, 37 ca: options.ca, 38 key: options.key, 39 cert: options.cert, 40 isServer: false, 41 rejectUnauthorized: false, 42 maxVersion: options.maxVersion, 43 }; 44 const network = securing === 'clear' ? net : tls; 45 const conn = network.connect(clientOptions, () => { 46 setTimeout(() => { 47 const mbits = (received * 8) / (1024 * 1024); 48 bench.end(mbits); 49 if (conn) 50 conn.destroy(); 51 server.close(); 52 proxy.close(); 53 }, dur * 1000); 54 bench.start(); 55 conn.on('drain', write); 56 write(); 57 }); 58 conn.on('error', (e) => { 59 throw new Error(`Client error: ${e}`); 60 }); 61 62 function write() { 63 while (false !== conn.write(chunk)); 64 } 65 }); 66 }); 67 68 function onProxyConnection(conn) { 69 const client = net.connect(REDIRECT_PORT, () => { 70 switch (securing) { 71 case 'SecurePair': 72 securePair(conn, client); 73 break; 74 case 'TLSSocket': 75 secureTLSSocket(conn, client); 76 break; 77 case 'clear': 78 conn.pipe(client); 79 break; 80 default: 81 throw new Error('Invalid securing method'); 82 } 83 }); 84 } 85 86 function securePair(conn, client) { 87 const serverCtx = tls.createSecureContext(options); 88 const serverPair = tls.createSecurePair(serverCtx, true, true, false); 89 conn.pipe(serverPair.encrypted); 90 serverPair.encrypted.pipe(conn); 91 serverPair.on('error', (error) => { 92 throw new Error(`Pair error: ${error}`); 93 }); 94 serverPair.cleartext.pipe(client); 95 } 96 97 function secureTLSSocket(conn, client) { 98 const serverSocket = new tls.TLSSocket(conn, options); 99 serverSocket.on('error', (e) => { 100 throw new Error(`Socket error: ${e}`); 101 }); 102 serverSocket.pipe(client); 103 } 104 105 let received = 0; 106 function onRedirectConnection(conn) { 107 conn.on('data', (chunk) => { 108 received += chunk.length; 109 }); 110 } 111} 112