File: _tls_legacy.js

package info (click to toggle)
nodejs-mozilla 8.11.1~dfsg-2~deb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 82,892 kB
  • sloc: cpp: 708,606; ansic: 100,227; python: 36,670; sh: 4,037; makefile: 2,690; perl: 345; lisp: 222; pascal: 115; xml: 95
file content (956 lines) | stat: -rw-r--r-- 24,652 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

const internalUtil = require('internal/util');
internalUtil.assertCrypto();

const assert = require('assert');
const { Buffer } = require('buffer');
const common = require('_tls_common');
const { Connection } = process.binding('crypto');
const EventEmitter = require('events');
const stream = require('stream');
const { Timer } = process.binding('timer_wrap');
const tls = require('tls');
const util = require('util');

const debug = util.debuglog('tls-legacy');

function SlabBuffer() {
  this.create();
}


SlabBuffer.prototype.create = function create() {
  this.isFull = false;
  this.pool = Buffer.allocUnsafe(tls.SLAB_BUFFER_SIZE);
  this.offset = 0;
  this.remaining = this.pool.length;
};


SlabBuffer.prototype.use = function use(context, fn, size) {
  if (this.remaining === 0) {
    this.isFull = true;
    return 0;
  }

  var actualSize = this.remaining;

  if (size !== null) actualSize = Math.min(size, actualSize);

  var bytes = fn.call(context, this.pool, this.offset, actualSize);
  if (bytes > 0) {
    this.offset += bytes;
    this.remaining -= bytes;
  }

  assert(this.remaining >= 0);

  return bytes;
};


var slabBuffer = null;


// Base class of both CleartextStream and EncryptedStream
function CryptoStream(pair, options) {
  stream.Duplex.call(this, options);

  this.pair = pair;
  this._pending = null;
  this._pendingEncoding = '';
  this._pendingCallback = null;
  this._doneFlag = false;
  this._retryAfterPartial = false;
  this._halfRead = false;
  this._sslOutCb = null;
  this._resumingSession = false;
  this._reading = true;
  this._destroyed = false;
  this._ended = false;
  this._finished = false;
  this._opposite = null;

  if (slabBuffer === null) slabBuffer = new SlabBuffer();
  this._buffer = slabBuffer;

  this.once('finish', onCryptoStreamFinish);

  // net.Socket calls .onend too
  this.once('end', onCryptoStreamEnd);
}
util.inherits(CryptoStream, stream.Duplex);


function onCryptoStreamFinish() {
  this._finished = true;

  if (this === this.pair.cleartext) {
    debug('cleartext.onfinish');
    if (this.pair.ssl) {
      // Generate close notify
      // NOTE: first call checks if client has sent us shutdown,
      // second call enqueues shutdown into the BIO.
      if (this.pair.ssl.shutdownSSL() !== 1) {
        if (this.pair.ssl && this.pair.ssl.error)
          return this.pair.error();

        this.pair.ssl.shutdownSSL();
      }

      if (this.pair.ssl && this.pair.ssl.error)
        return this.pair.error();
    }
  } else {
    debug('encrypted.onfinish');
  }

  // Try to read just to get sure that we won't miss EOF
  if (this._opposite.readable) this._opposite.read(0);

  if (this._opposite._ended) {
    this._done();

    // No half-close, sorry
    if (this === this.pair.cleartext) this._opposite._done();
  }
}


function onCryptoStreamEnd() {
  this._ended = true;
  if (this === this.pair.cleartext) {
    debug('cleartext.onend');
  } else {
    debug('encrypted.onend');
  }
}


// NOTE: Called once `this._opposite` is set.
CryptoStream.prototype.init = function init() {
  var self = this;
  this._opposite.on('sslOutEnd', function() {
    if (self._sslOutCb) {
      var cb = self._sslOutCb;
      self._sslOutCb = null;
      cb(null);
    }
  });
};


CryptoStream.prototype._write = function _write(data, encoding, cb) {
  assert(this._pending === null);

  // Black-hole data
  if (!this.pair.ssl) return cb(null);

  // When resuming session don't accept any new data.
  // And do not put too much data into openssl, before writing it from encrypted
  // side.
  //
  // TODO(indutny): Remove magic number, use watermark based limits
  if (!this._resumingSession &&
      this._opposite._internallyPendingBytes() < 128 * 1024) {
    // Write current buffer now
    var written;
    if (this === this.pair.cleartext) {
      debug('cleartext.write called with %d bytes', data.length);
      written = this.pair.ssl.clearIn(data, 0, data.length);
    } else {
      debug('encrypted.write called with %d bytes', data.length);
      written = this.pair.ssl.encIn(data, 0, data.length);
    }

    // Handle and report errors
    if (this.pair.ssl && this.pair.ssl.error) {
      return cb(this.pair.error(true));
    }

    // Force SSL_read call to cycle some states/data inside OpenSSL
    this.pair.cleartext.read(0);

    // Cycle encrypted data
    if (this.pair.encrypted._internallyPendingBytes())
      this.pair.encrypted.read(0);

    // Get ALPN, NPN and Server name when ready
    this.pair.maybeInitFinished();

    // Whole buffer was written
    if (written === data.length) {
      if (this === this.pair.cleartext) {
        debug('cleartext.write succeed with ' + written + ' bytes');
      } else {
        debug('encrypted.write succeed with ' + written + ' bytes');
      }

      // Invoke callback only when all data read from opposite stream
      if (this._opposite._halfRead) {
        assert(this._sslOutCb === null);
        this._sslOutCb = cb;
      } else {
        cb(null);
      }
      return;
    } else if (written !== 0 && written !== -1) {
      assert(!this._retryAfterPartial);
      this._retryAfterPartial = true;
      this._write(data.slice(written), encoding, cb);
      this._retryAfterPartial = false;
      return;
    }
  } else {
    debug('cleartext.write queue is full');

    // Force SSL_read call to cycle some states/data inside OpenSSL
    this.pair.cleartext.read(0);
  }

  // No write has happened
  this._pending = data;
  this._pendingEncoding = encoding;
  this._pendingCallback = cb;

  if (this === this.pair.cleartext) {
    debug('cleartext.write queued with %d bytes', data.length);
  } else {
    debug('encrypted.write queued with %d bytes', data.length);
  }
};


CryptoStream.prototype._writePending = function _writePending() {
  const data = this._pending;
  const encoding = this._pendingEncoding;
  const cb = this._pendingCallback;

  this._pending = null;
  this._pendingEncoding = '';
  this._pendingCallback = null;
  this._write(data, encoding, cb);
};


CryptoStream.prototype._read = function _read(size) {
  // XXX: EOF?!
  if (!this.pair.ssl) return this.push(null);

  // Wait for session to be resumed
  // Mark that we're done reading, but don't provide data or EOF
  if (this._resumingSession || !this._reading) return this.push('');

  var out;
  if (this === this.pair.cleartext) {
    debug('cleartext.read called with %d bytes', size);
    out = this.pair.ssl.clearOut;
  } else {
    debug('encrypted.read called with %d bytes', size);
    out = this.pair.ssl.encOut;
  }

  var bytesRead = 0;
  const start = this._buffer.offset;
  var last = start;
  do {
    assert(last === this._buffer.offset);
    var read = this._buffer.use(this.pair.ssl, out, size - bytesRead);
    if (read > 0) {
      bytesRead += read;
    }
    last = this._buffer.offset;

    // Handle and report errors
    if (this.pair.ssl && this.pair.ssl.error) {
      this.pair.error();
      break;
    }
  } while (read > 0 &&
           !this._buffer.isFull &&
           bytesRead < size &&
           this.pair.ssl !== null);

  // Get ALPN, NPN and Server name when ready
  this.pair.maybeInitFinished();

  // Create new buffer if previous was filled up
  var pool = this._buffer.pool;
  if (this._buffer.isFull) this._buffer.create();

  assert(bytesRead >= 0);

  if (this === this.pair.cleartext) {
    debug('cleartext.read succeed with %d bytes', bytesRead);
  } else {
    debug('encrypted.read succeed with %d bytes', bytesRead);
  }

  // Try writing pending data
  if (this._pending !== null) this._writePending();
  if (this._opposite._pending !== null) this._opposite._writePending();

  if (bytesRead === 0) {
    // EOF when cleartext has finished and we have nothing to read
    if (this._opposite._finished && this._internallyPendingBytes() === 0 ||
        this.pair.ssl && this.pair.ssl.receivedShutdown) {
      // Perform graceful shutdown
      this._done();

      // No half-open, sorry!
      if (this === this.pair.cleartext) {
        this._opposite._done();

        // EOF
        this.push(null);
      } else if (!this.pair.ssl || !this.pair.ssl.receivedShutdown) {
        // EOF
        this.push(null);
      }
    } else {
      // Bail out
      this.push('');
    }
  } else {
    // Give them requested data
    this.push(pool.slice(start, start + bytesRead));
  }

  // Let users know that we've some internal data to read
  var halfRead = this._internallyPendingBytes() !== 0;

  // Smart check to avoid invoking 'sslOutEnd' in the most of the cases
  if (this._halfRead !== halfRead) {
    this._halfRead = halfRead;

    // Notify listeners about internal data end
    if (!halfRead) {
      if (this === this.pair.cleartext) {
        debug('cleartext.sslOutEnd');
      } else {
        debug('encrypted.sslOutEnd');
      }

      this.emit('sslOutEnd');
    }
  }
};


CryptoStream.prototype.setTimeout = function(timeout, callback) {
  if (this.socket) this.socket.setTimeout(timeout, callback);
};


CryptoStream.prototype.setNoDelay = function(noDelay) {
  if (this.socket) this.socket.setNoDelay(noDelay);
};


CryptoStream.prototype.setKeepAlive = function(enable, initialDelay) {
  if (this.socket) this.socket.setKeepAlive(enable, initialDelay);
};

Object.defineProperty(CryptoStream.prototype, 'bytesWritten', {
  configurable: true,
  enumerable: true,
  get: function() {
    return this.socket ? this.socket.bytesWritten : 0;
  }
});

CryptoStream.prototype.getPeerCertificate = function(detailed) {
  if (this.pair.ssl) {
    return common.translatePeerCertificate(
      this.pair.ssl.getPeerCertificate(detailed));
  }

  return null;
};

CryptoStream.prototype.getSession = function() {
  if (this.pair.ssl) {
    return this.pair.ssl.getSession();
  }

  return null;
};

CryptoStream.prototype.isSessionReused = function() {
  if (this.pair.ssl) {
    return this.pair.ssl.isSessionReused();
  }

  return null;
};

CryptoStream.prototype.getCipher = function(err) {
  if (this.pair.ssl) {
    return this.pair.ssl.getCurrentCipher();
  } else {
    return null;
  }
};


CryptoStream.prototype.end = function(chunk, encoding) {
  if (this === this.pair.cleartext) {
    debug('cleartext.end');
  } else {
    debug('encrypted.end');
  }

  // Write pending data first
  if (this._pending !== null) this._writePending();

  this.writable = false;

  stream.Duplex.prototype.end.call(this, chunk, encoding);
};


CryptoStream.prototype.destroySoon = function(err) {
  if (this === this.pair.cleartext) {
    debug('cleartext.destroySoon');
  } else {
    debug('encrypted.destroySoon');
  }

  if (this.writable)
    this.end();

  if (this._writableState.finished && this._opposite._ended) {
    this.destroy();
  } else {
    // Wait for both `finish` and `end` events to ensure that all data that
    // was written on this side was read from the other side.
    var self = this;
    var waiting = 1;
    function finish() {
      if (--waiting === 0) self.destroy();
    }
    this._opposite.once('end', finish);
    if (!this._finished) {
      this.once('finish', finish);
      ++waiting;
    }
  }
};


CryptoStream.prototype.destroy = function(err) {
  if (this._destroyed) return;
  this._destroyed = true;
  this.readable = this.writable = false;

  // Destroy both ends
  if (this === this.pair.cleartext) {
    debug('cleartext.destroy');
  } else {
    debug('encrypted.destroy');
  }
  this._opposite.destroy();

  process.nextTick(destroyNT, this, err ? true : false);
};


function destroyNT(self, hadErr) {
  // Force EOF
  self.push(null);

  // Emit 'close' event
  self.emit('close', hadErr);
}


CryptoStream.prototype._done = function() {
  this._doneFlag = true;

  if (this === this.pair.encrypted && !this.pair._secureEstablished)
    return this.pair.error();

  if (this.pair.cleartext._doneFlag &&
      this.pair.encrypted._doneFlag &&
      !this.pair._doneFlag) {
    // If both streams are done:
    this.pair.destroy();
  }
};


// readyState is deprecated. Don't use it.
// Deprecation Code: DEP0004
Object.defineProperty(CryptoStream.prototype, 'readyState', {
  get: function() {
    if (this.connecting) {
      return 'opening';
    } else if (this.readable && this.writable) {
      return 'open';
    } else if (this.readable && !this.writable) {
      return 'readOnly';
    } else if (!this.readable && this.writable) {
      return 'writeOnly';
    } else {
      return 'closed';
    }
  }
});


function CleartextStream(pair, options) {
  CryptoStream.call(this, pair, options);

  // This is a fake kludge to support how the http impl sits
  // on top of net Sockets
  var self = this;
  this._handle = {
    readStop: function() {
      self._reading = false;
    },
    readStart: function() {
      if (self._reading && self._readableState.length > 0) return;
      self._reading = true;
      self.read(0);
      if (self._opposite.readable) self._opposite.read(0);
    }
  };
}
util.inherits(CleartextStream, CryptoStream);


CleartextStream.prototype._internallyPendingBytes = function() {
  if (this.pair.ssl) {
    return this.pair.ssl.clearPending();
  } else {
    return 0;
  }
};


CleartextStream.prototype.address = function() {
  return this.socket && this.socket.address();
};

Object.defineProperty(CleartextStream.prototype, 'remoteAddress', {
  configurable: true,
  enumerable: true,
  get: function() {
    return this.socket && this.socket.remoteAddress;
  }
});

Object.defineProperty(CleartextStream.prototype, 'remoteFamily', {
  configurable: true,
  enumerable: true,
  get: function() {
    return this.socket && this.socket.remoteFamily;
  }
});

Object.defineProperty(CleartextStream.prototype, 'remotePort', {
  configurable: true,
  enumerable: true,
  get: function() {
    return this.socket && this.socket.remotePort;
  }
});

Object.defineProperty(CleartextStream.prototype, 'localAddress', {
  configurable: true,
  enumerable: true,
  get: function() {
    return this.socket && this.socket.localAddress;
  }
});

Object.defineProperty(CleartextStream.prototype, 'localPort', {
  configurable: true,
  enumerable: true,
  get: function() {
    return this.socket && this.socket.localPort;
  }
});


function EncryptedStream(pair, options) {
  CryptoStream.call(this, pair, options);
}
util.inherits(EncryptedStream, CryptoStream);


EncryptedStream.prototype._internallyPendingBytes = function() {
  if (this.pair.ssl) {
    return this.pair.ssl.encPending();
  } else {
    return 0;
  }
};


function onhandshakestart() {
  debug('onhandshakestart');

  var self = this;
  var ssl = self.ssl;
  var now = Timer.now();

  assert(now >= ssl.lastHandshakeTime);

  if ((now - ssl.lastHandshakeTime) >= tls.CLIENT_RENEG_WINDOW * 1000) {
    ssl.handshakes = 0;
  }

  var first = (ssl.lastHandshakeTime === 0);
  ssl.lastHandshakeTime = now;
  if (first) return;

  if (++ssl.handshakes > tls.CLIENT_RENEG_LIMIT) {
    // Defer the error event to the next tick. We're being called from OpenSSL's
    // state machine and OpenSSL is not re-entrant. We cannot allow the user's
    // callback to destroy the connection right now, it would crash and burn.
    setImmediate(function() {
      // Old-style error is not being migrated to the newer style
      // internal/errors.js because _tls_legacy.js has been deprecated.
      var err = new Error('TLS session renegotiation attack detected');
      if (self.cleartext) self.cleartext.emit('error', err);
    });
  }
}


function onhandshakedone() {
  // for future use
  debug('onhandshakedone');
}


function onclienthello(hello) {
  const self = this;
  var once = false;

  this._resumingSession = true;
  function callback(err, session) {
    if (once) return;
    once = true;

    if (err) return self.socket.destroy(err);

    setImmediate(function() {
      self.ssl.loadSession(session);
      self.ssl.endParser();

      // Cycle data
      self._resumingSession = false;
      self.cleartext.read(0);
      self.encrypted.read(0);
    });
  }

  if (hello.sessionId.length <= 0 ||
      !this.server ||
      !this.server.emit('resumeSession', hello.sessionId, callback)) {
    callback(null, null);
  }
}


function onnewsession(key, session) {
  if (!this.server) return;

  var self = this;
  var once = false;

  if (!self.server.emit('newSession', key, session, done))
    done();

  function done() {
    if (once)
      return;
    once = true;

    if (self.ssl)
      self.ssl.newSessionDone();
  }
}


function onocspresponse(resp) {
  this.emit('OCSPResponse', resp);
}


/**
 * Provides a pair of streams to do encrypted communication.
 */

function SecurePair(context, isServer, requestCert, rejectUnauthorized,
                    options) {
  if (!(this instanceof SecurePair)) {
    return new SecurePair(context,
                          isServer,
                          requestCert,
                          rejectUnauthorized,
                          options);
  }

  options || (options = {});

  EventEmitter.call(this);

  this.server = options.server;
  this._secureEstablished = false;
  this._isServer = isServer ? true : false;
  this._encWriteState = true;
  this._clearWriteState = true;
  this._doneFlag = false;
  this._destroying = false;

  if (!context) {
    this.credentials = tls.createSecureContext();
  } else {
    this.credentials = context;
  }

  if (!this._isServer) {
    // For clients, we will always have either a given ca list or be using
    // default one
    requestCert = true;
  }

  this._rejectUnauthorized = rejectUnauthorized ? true : false;
  this._requestCert = requestCert ? true : false;

  this.ssl = new Connection(
    this.credentials.context,
    this._isServer ? true : false,
    this._isServer ? this._requestCert : options.servername,
    this._rejectUnauthorized
  );

  if (this._isServer) {
    this.ssl.onhandshakestart = () => onhandshakestart.call(this);
    this.ssl.onhandshakedone = () => onhandshakedone.call(this);
    this.ssl.onclienthello = (hello) => onclienthello.call(this, hello);
    this.ssl.onnewsession =
        (key, session) => onnewsession.call(this, key, session);
    this.ssl.lastHandshakeTime = 0;
    this.ssl.handshakes = 0;
  } else {
    this.ssl.onocspresponse = (resp) => onocspresponse.call(this, resp);
  }

  if (process.features.tls_sni) {
    if (this._isServer && options.SNICallback) {
      this.ssl.setSNICallback(options.SNICallback);
    }
    this.servername = null;
  }

  if (process.features.tls_npn && options.NPNProtocols) {
    this.ssl.setNPNProtocols(options.NPNProtocols);
    this.npnProtocol = null;
  }

  if (process.features.tls_alpn && options.ALPNProtocols) {
    // keep reference in secureContext not to be GC-ed
    this.ssl._secureContext.alpnBuffer = options.ALPNProtocols;
    this.ssl.setALPNrotocols(this.ssl._secureContext.alpnBuffer);
    this.alpnProtocol = null;
  }

  /* Acts as a r/w stream to the cleartext side of the stream. */
  this.cleartext = new CleartextStream(this, options.cleartext);

  /* Acts as a r/w stream to the encrypted side of the stream. */
  this.encrypted = new EncryptedStream(this, options.encrypted);

  /* Let streams know about each other */
  this.cleartext._opposite = this.encrypted;
  this.encrypted._opposite = this.cleartext;
  this.cleartext.init();
  this.encrypted.init();

  process.nextTick(securePairNT, this, options);
}

util.inherits(SecurePair, EventEmitter);

function securePairNT(self, options) {
  /* The Connection may be destroyed by an abort call */
  if (self.ssl) {
    self.ssl.start();

    if (options.requestOCSP)
      self.ssl.requestOCSP();

    /* In case of cipher suite failures - SSL_accept/SSL_connect may fail */
    if (self.ssl && self.ssl.error)
      self.error();
  }
}


function createSecurePair(context, isServer, requestCert,
                          rejectUnauthorized, options) {
  return new SecurePair(context, isServer, requestCert,
                        rejectUnauthorized, options);
}


SecurePair.prototype.maybeInitFinished = function() {
  if (this.ssl && !this._secureEstablished && this.ssl.isInitFinished()) {
    if (process.features.tls_npn) {
      this.npnProtocol = this.ssl.getNegotiatedProtocol();
    }

    if (process.features.tls_alpn) {
      this.alpnProtocol = this.ssl.getALPNNegotiatedProtocol();
    }

    if (process.features.tls_sni) {
      this.servername = this.ssl.getServername();
    }

    this._secureEstablished = true;
    debug('secure established');
    this.emit('secure');
  }
};


SecurePair.prototype.destroy = function() {
  if (this._destroying) return;

  if (!this._doneFlag) {
    debug('SecurePair.destroy');
    this._destroying = true;

    // SecurePair should be destroyed only after it's streams
    this.cleartext.destroy();
    this.encrypted.destroy();

    this._doneFlag = true;
    this.ssl.error = null;
    this.ssl.close();
    this.ssl = null;
  }
};


SecurePair.prototype.error = function(returnOnly) {
  var err = this.ssl.error;
  this.ssl.error = null;

  if (!this._secureEstablished) {
    // Emit ECONNRESET instead of zero return
    if (!err || err.message === 'ZERO_RETURN') {
      var connReset = new Error('socket hang up');
      connReset.code = 'ECONNRESET';
      connReset.sslError = err && err.message;

      err = connReset;
    }
    this.destroy();
    if (!returnOnly) this.emit('error', err);
  } else if (this._isServer &&
             this._rejectUnauthorized &&
             /peer did not return a certificate/.test(err.message)) {
    // Not really an error.
    this.destroy();
  } else if (!returnOnly) {
    this.cleartext.emit('error', err);
  }
  return err;
};


function pipe(pair, socket) {
  pair.encrypted.pipe(socket);
  socket.pipe(pair.encrypted);

  pair.encrypted.on('close', function() {
    process.nextTick(pipeCloseNT, pair, socket);
  });

  pair.fd = socket.fd;
  var cleartext = pair.cleartext;
  cleartext.socket = socket;
  cleartext.encrypted = pair.encrypted;
  cleartext.authorized = false;

  // cycle the data whenever the socket drains, so that
  // we can pull some more into it.  normally this would
  // be handled by the fact that pipe() triggers read() calls
  // on writable.drain, but CryptoStreams are a bit more
  // complicated.  Since the encrypted side actually gets
  // its data from the cleartext side, we have to give it a
  // light kick to get in motion again.
  socket.on('drain', function() {
    if (pair.encrypted._pending)
      pair.encrypted._writePending();
    if (pair.cleartext._pending)
      pair.cleartext._writePending();
    pair.encrypted.read(0);
    pair.cleartext.read(0);
  });

  function onerror(e) {
    if (cleartext._controlReleased) {
      cleartext.emit('error', e);
    }
  }

  function onclose() {
    socket.removeListener('error', onerror);
    socket.removeListener('timeout', ontimeout);
  }

  function ontimeout() {
    cleartext.emit('timeout');
  }

  socket.on('error', onerror);
  socket.on('close', onclose);
  socket.on('timeout', ontimeout);

  return cleartext;
}


function pipeCloseNT(pair, socket) {
  // Encrypted should be unpiped from socket to prevent possible
  // write after destroy.
  pair.encrypted.unpipe(socket);
  socket.destroySoon();
}

module.exports = {
  createSecurePair:
    internalUtil.deprecate(createSecurePair,
                           'tls.createSecurePair() is deprecated. Please use ' +
                           'tls.Socket instead.', 'DEP0064'),
  pipe
};