11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ciconst common = require('../common');
31cb0ef41Sopenharmony_ciif (!common.hasCrypto)
41cb0ef41Sopenharmony_ci  common.skip('missing crypto');
51cb0ef41Sopenharmony_ci
61cb0ef41Sopenharmony_ciconst assert = require('assert');
71cb0ef41Sopenharmony_ciconst tls = require('tls');
81cb0ef41Sopenharmony_ci
91cb0ef41Sopenharmony_ci// We could get the `tlsSocket.servername` even if the event of "tlsClientError"
101cb0ef41Sopenharmony_ci// is emitted.
111cb0ef41Sopenharmony_ci
121cb0ef41Sopenharmony_ciconst serverOptions = {
131cb0ef41Sopenharmony_ci  requestCert: true,
141cb0ef41Sopenharmony_ci  rejectUnauthorized: false,
151cb0ef41Sopenharmony_ci  SNICallback: function(servername, callback) {
161cb0ef41Sopenharmony_ci    if (servername === 'c.another.com') {
171cb0ef41Sopenharmony_ci      callback(null, {});
181cb0ef41Sopenharmony_ci    } else {
191cb0ef41Sopenharmony_ci      callback(new Error('Invalid SNI context'), null);
201cb0ef41Sopenharmony_ci    }
211cb0ef41Sopenharmony_ci  }
221cb0ef41Sopenharmony_ci};
231cb0ef41Sopenharmony_ci
241cb0ef41Sopenharmony_cifunction test(options) {
251cb0ef41Sopenharmony_ci  const server = tls.createServer(serverOptions, common.mustNotCall());
261cb0ef41Sopenharmony_ci
271cb0ef41Sopenharmony_ci  server.on('tlsClientError', common.mustCall((err, socket) => {
281cb0ef41Sopenharmony_ci    assert.strictEqual(err.message, 'Invalid SNI context');
291cb0ef41Sopenharmony_ci    // The `servername` should match.
301cb0ef41Sopenharmony_ci    assert.strictEqual(socket.servername, options.servername);
311cb0ef41Sopenharmony_ci  }));
321cb0ef41Sopenharmony_ci
331cb0ef41Sopenharmony_ci  server.listen(0, () => {
341cb0ef41Sopenharmony_ci    options.port = server.address().port;
351cb0ef41Sopenharmony_ci    const client = tls.connect(options, common.mustNotCall());
361cb0ef41Sopenharmony_ci
371cb0ef41Sopenharmony_ci    client.on('error', common.mustCall((err) => {
381cb0ef41Sopenharmony_ci      assert.strictEqual(err.message, 'Client network socket' +
391cb0ef41Sopenharmony_ci      ' disconnected before secure TLS connection was established');
401cb0ef41Sopenharmony_ci    }));
411cb0ef41Sopenharmony_ci
421cb0ef41Sopenharmony_ci    client.on('close', common.mustCall(() => server.close()));
431cb0ef41Sopenharmony_ci  });
441cb0ef41Sopenharmony_ci}
451cb0ef41Sopenharmony_ci
461cb0ef41Sopenharmony_citest({
471cb0ef41Sopenharmony_ci  port: undefined,
481cb0ef41Sopenharmony_ci  servername: 'c.another.com',
491cb0ef41Sopenharmony_ci  rejectUnauthorized: false
501cb0ef41Sopenharmony_ci});
511cb0ef41Sopenharmony_ci
521cb0ef41Sopenharmony_citest({
531cb0ef41Sopenharmony_ci  port: undefined,
541cb0ef41Sopenharmony_ci  servername: 'c.wrong.com',
551cb0ef41Sopenharmony_ci  rejectUnauthorized: false
561cb0ef41Sopenharmony_ci});
57