1'use strict';
2const common = require('../common');
3if (!common.hasCrypto)
4  common.skip('missing crypto');
5const fixtures = require('../common/fixtures');
6const SSL_OP_NO_TICKET = require('crypto').constants.SSL_OP_NO_TICKET;
7const tls = require('tls');
8
9// Check that TLS1.2 session resumption callbacks don't explode when made after
10// the tls socket is destroyed. Disable TLS ticket support to force the legacy
11// session resumption mechanism to be used.
12
13// TLS1.2 is the last protocol version to support TLS sessions, after that the
14// new and resume session events will never be emitted on the server.
15
16const options = {
17  secureOptions: SSL_OP_NO_TICKET,
18  key: fixtures.readKey('rsa_private.pem'),
19  cert: fixtures.readKey('rsa_cert.crt')
20};
21
22const server = tls.createServer(options, common.mustCall());
23
24let sessionCb = null;
25let client = null;
26
27server.on('newSession', common.mustCall((key, session, done) => {
28  done();
29}));
30
31server.on('resumeSession', common.mustCall((id, cb) => {
32  sessionCb = cb;
33  // Destroy the client and then call the session cb, to check that the cb
34  // doesn't explode when called after the handle has been destroyed.
35  next();
36}));
37
38server.listen(0, common.mustCall(() => {
39  const clientOpts = {
40    // Don't send a TLS1.3/1.2 ClientHello, they contain a fake session_id,
41    // which triggers a 'resumeSession' event for client1. TLS1.2 ClientHello
42    // won't have a session_id until client2, which will have a valid session.
43    maxVersion: 'TLSv1.2',
44    port: server.address().port,
45    rejectUnauthorized: false,
46    session: false
47  };
48
49  const s1 = tls.connect(clientOpts, common.mustCall(() => {
50    clientOpts.session = s1.getSession();
51    console.log('1st secure');
52
53    s1.destroy();
54    const s2 = tls.connect(clientOpts, (s) => {
55      console.log('2nd secure');
56
57      s2.destroy();
58    }).on('connect', common.mustCall(() => {
59      console.log('2nd connected');
60      client = s2;
61
62      next();
63    }));
64  }));
65}));
66
67function next() {
68  if (!client || !sessionCb)
69    return;
70
71  client.destroy();
72  setTimeout(common.mustCall(() => {
73    sessionCb();
74    server.close();
75  }), 100);
76}
77