GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage/nodes/benchmark/out/../src/tls_wrap.cc Lines: 432 469 92.1 %
Date: 2017-06-14 Branches: 216 311 69.5 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "tls_wrap.h"
23
#include "async-wrap.h"
24
#include "async-wrap-inl.h"
25
#include "node_buffer.h"  // Buffer
26
#include "node_crypto.h"  // SecureContext
27
#include "node_crypto_bio.h"  // NodeBIO
28
#include "node_crypto_clienthello.h"  // ClientHelloParser
29
#include "node_crypto_clienthello-inl.h"
30
#include "node_counters.h"
31
#include "node_internals.h"
32
#include "stream_base.h"
33
#include "stream_base-inl.h"
34
#include "util.h"
35
#include "util-inl.h"
36
37
namespace node {
38
39
using crypto::SecureContext;
40
using crypto::SSLWrap;
41
using v8::Context;
42
using v8::EscapableHandleScope;
43
using v8::Exception;
44
using v8::Function;
45
using v8::FunctionCallbackInfo;
46
using v8::FunctionTemplate;
47
using v8::Local;
48
using v8::Object;
49
using v8::String;
50
using v8::Value;
51
52
726
TLSWrap::TLSWrap(Environment* env,
53
                 Kind kind,
54
                 StreamBase* stream,
55
                 SecureContext* sc)
56
    : AsyncWrap(env,
57
                env->tls_wrap_constructor_function()
58
2178
                    ->NewInstance(env->context()).ToLocalChecked(),
59
                AsyncWrap::PROVIDER_TLSWRAP),
60
      SSLWrap<TLSWrap>(env, sc, kind),
61
      StreamBase(env),
62
      sc_(sc),
63
      stream_(stream),
64
      enc_in_(nullptr),
65
      enc_out_(nullptr),
66
      clear_in_(nullptr),
67
      write_size_(0),
68
      started_(false),
69
      established_(false),
70
      shutdown_(false),
71
      error_(nullptr),
72
      cycle_depth_(0),
73
2178
      eof_(false) {
74
726
  node::Wrap(object(), this);
75
726
  MakeWeak(this);
76
77
  // sc comes from an Unwrap. Make sure it was assigned.
78
726
  CHECK_NE(sc, nullptr);
79
80
  // We've our own session callbacks
81
726
  SSL_CTX_sess_set_get_cb(sc_->ctx_, SSLWrap<TLSWrap>::GetSessionCallback);
82
726
  SSL_CTX_sess_set_new_cb(sc_->ctx_, SSLWrap<TLSWrap>::NewSessionCallback);
83
84
726
  stream_->Consume();
85
726
  stream_->set_after_write_cb({ OnAfterWriteImpl, this });
86
726
  stream_->set_alloc_cb({ OnAllocImpl, this });
87
726
  stream_->set_read_cb({ OnReadImpl, this });
88
726
  stream_->set_destruct_cb({ OnDestructImpl, this });
89
90
726
  set_alloc_cb({ OnAllocSelf, this });
91
726
  set_read_cb({ OnReadSelf, this });
92
93
726
  InitSSL();
94
726
}
95
96
97
1032
TLSWrap::~TLSWrap() {
98
344
  enc_in_ = nullptr;
99
344
  enc_out_ = nullptr;
100
344
  delete clear_in_;
101
344
  clear_in_ = nullptr;
102
103
344
  sc_ = nullptr;
104
105
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
106
344
  sni_context_.Reset();
107
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
108
109
344
  ClearError();
110
688
}
111
112
113
1497
void TLSWrap::MakePending() {
114
1497
  write_item_queue_.MoveBack(&pending_write_items_);
115
1497
}
116
117
118
3615
bool TLSWrap::InvokeQueued(int status, const char* error_str) {
119
3615
  if (pending_write_items_.IsEmpty())
120
2827
    return false;
121
122
  // Process old queue
123
788
  WriteItemList queue;
124
788
  pending_write_items_.MoveBack(&queue);
125
1577
  while (WriteItem* wi = queue.PopFront()) {
126
789
    wi->w_->Done(status, error_str);
127
789
    delete wi;
128
  }
129
130
788
  return true;
131
}
132
133
134
8
void TLSWrap::NewSessionDoneCb() {
135
8
  Cycle();
136
8
}
137
138
139
726
void TLSWrap::InitSSL() {
140
  // Initialize SSL
141
726
  enc_in_ = NodeBIO::New();
142
726
  enc_out_ = NodeBIO::New();
143
726
  NodeBIO::FromBIO(enc_in_)->AssignEnvironment(env());
144
726
  NodeBIO::FromBIO(enc_out_)->AssignEnvironment(env());
145
146
726
  SSL_set_bio(ssl_, enc_in_, enc_out_);
147
148
  // NOTE: This could be overridden in SetVerifyMode
149
726
  SSL_set_verify(ssl_, SSL_VERIFY_NONE, crypto::VerifyCallback);
150
151
#ifdef SSL_MODE_RELEASE_BUFFERS
152
726
  long mode = SSL_get_mode(ssl_);  // NOLINT(runtime/int)
153
726
  SSL_set_mode(ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
154
#endif  // SSL_MODE_RELEASE_BUFFERS
155
156
726
  SSL_set_app_data(ssl_, this);
157
726
  SSL_set_info_callback(ssl_, SSLInfoCallback);
158
159
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
160
726
  if (is_server()) {
161
382
    SSL_CTX_set_tlsext_servername_callback(sc_->ctx_, SelectSNIContextCallback);
162
  }
163
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
164
165
726
  InitNPN(sc_);
166
167
726
  SSL_set_cert_cb(ssl_, SSLWrap<TLSWrap>::SSLCertCallback, this);
168
169
726
  if (is_server()) {
170
382
    SSL_set_accept_state(ssl_);
171
344
  } else if (is_client()) {
172
    // Enough space for server response (hello, cert)
173
344
    NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
174
344
    SSL_set_connect_state(ssl_);
175
  } else {
176
    // Unexpected
177
    ABORT();
178
  }
179
180
  // Initialize ring for queud clear data
181
726
  clear_in_ = new NodeBIO();
182
726
  clear_in_->AssignEnvironment(env());
183
726
}
184
185
186
726
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
187
726
  Environment* env = Environment::GetCurrent(args);
188
189


2904
  if (args.Length() < 1 || !args[0]->IsObject()) {
190
    return env->ThrowTypeError(
191
        "First argument should be a StreamWrap instance");
192
  }
193


2904
  if (args.Length() < 2 || !args[1]->IsObject()) {
194
    return env->ThrowTypeError(
195
        "Second argument should be a SecureContext instance");
196
  }
197


2904
  if (args.Length() < 3 || !args[2]->IsBoolean())
198
    return env->ThrowTypeError("Third argument should be boolean");
199
200
1452
  Local<External> stream_obj = args[0].As<External>();
201
1452
  Local<Object> sc = args[1].As<Object>();
202
2178
  Kind kind = args[2]->IsTrue() ? SSLWrap<TLSWrap>::kServer :
203
726
                                  SSLWrap<TLSWrap>::kClient;
204
205
726
  StreamBase* stream = static_cast<StreamBase*>(stream_obj->Value());
206
726
  CHECK_NE(stream, nullptr);
207
208
726
  TLSWrap* res = new TLSWrap(env, kind, stream, Unwrap<SecureContext>(sc));
209
210
2178
  args.GetReturnValue().Set(res->object());
211
}
212
213
214
3
void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
215
  TLSWrap* wrap;
216
6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
217
218
3
  CHECK(Buffer::HasInstance(args[0]));
219
3
  char* data = Buffer::Data(args[0]);
220
3
  size_t len = Buffer::Length(args[0]);
221
222
  uv_buf_t buf;
223
224
  // Copy given buffer entirely or partiall if handle becomes closed
225


9
  while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
226
3
    wrap->stream_->OnAlloc(len, &buf);
227
3
    size_t copy = buf.len > len ? len : buf.len;
228
3
    memcpy(buf.base, data, copy);
229
3
    buf.len = copy;
230
3
    wrap->stream_->OnRead(buf.len, &buf);
231
232
3
    data += copy;
233
3
    len -= copy;
234
  }
235
}
236
237
238
324
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
239
324
  Environment* env = Environment::GetCurrent(args);
240
241
  TLSWrap* wrap;
242
324
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
243
244
324
  if (wrap->started_)
245
    return env->ThrowError("Already started.");
246
324
  wrap->started_ = true;
247
248
  // Send ClientHello handshake
249
324
  CHECK(wrap->is_client());
250
324
  wrap->ClearOut();
251
324
  wrap->EncOut();
252
}
253
254
255
14252
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
256
14252
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
257
27120
    return;
258
259
  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
260
  // a non-const SSL* in OpenSSL <= 0.9.7e.
261
1383
  SSL* ssl = const_cast<SSL*>(ssl_);
262
1383
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl));
263
1383
  Environment* env = c->env();
264
1383
  Local<Object> object = c->object();
265
266
1383
  if (where & SSL_CB_HANDSHAKE_START) {
267
1420
    Local<Value> callback = object->Get(env->onhandshakestart_string());
268
710
    if (callback->IsFunction()) {
269
710
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
270
    }
271
  }
272
273
1383
  if (where & SSL_CB_HANDSHAKE_DONE) {
274
673
    c->established_ = true;
275
1346
    Local<Value> callback = object->Get(env->onhandshakedone_string());
276
673
    if (callback->IsFunction()) {
277
673
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
278
    }
279
  }
280
}
281
282
283
6178
void TLSWrap::EncOut() {
284
  // Ignore cycling data if ClientHello wasn't yet parsed
285
6178
  if (!hello_parser_.IsEnded())
286
3822
    return;
287
288
  // Write in progress
289
6178
  if (write_size_ != 0)
290
713
    return;
291
292
  // Wait for `newSession` callback to be invoked
293
5465
  if (is_waiting_new_session())
294
7
    return;
295
296
  // Split-off queue
297

5458
  if (established_ && !write_item_queue_.IsEmpty())
298
785
    MakePending();
299
300
5458
  if (ssl_ == nullptr)
301
1
    return;
302
303
  // No data to write
304
5457
  if (BIO_pending(enc_out_) == 0) {
305
3101
    if (clear_in_->Length() == 0)
306
2889
      InvokeQueued(0);
307
3101
    return;
308
  }
309
310
  char* data[kSimultaneousBufferCount];
311
  size_t size[arraysize(data)];
312
2356
  size_t count = arraysize(data);
313
2356
  write_size_ = NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count);
314

2356
  CHECK(write_size_ != 0 && count != 0);
315
316
  Local<Object> req_wrap_obj =
317
2356
      env()->write_wrap_constructor_function()
318
9424
          ->NewInstance(env()->context()).ToLocalChecked();
319
  WriteWrap* write_req = WriteWrap::New(env(),
320
                                        req_wrap_obj,
321
                                        this,
322
2356
                                        EncOutCb);
323
324
  uv_buf_t buf[arraysize(data)];
325
5147
  for (size_t i = 0; i < count; i++)
326
2791
    buf[i] = uv_buf_init(data[i], size[i]);
327
2356
  int err = stream_->DoWrite(write_req, buf, count, nullptr);
328
329
  // Ignore errors, this should be already handled in js
330
2356
  if (err) {
331
13
    write_req->Dispose();
332
13
    InvokeQueued(err);
333
  } else {
334
    NODE_COUNT_NET_BYTES_SENT(write_size_);
335
  }
336
}
337
338
339
2341
void TLSWrap::EncOutCb(WriteWrap* req_wrap, int status) {
340
2341
  TLSWrap* wrap = req_wrap->wrap()->Cast<TLSWrap>();
341
2341
  req_wrap->Dispose();
342
343
  // We should not be getting here after `DestroySSL`, because all queued writes
344
  // must be invoked with UV_ECANCELED
345
2341
  CHECK_NE(wrap->ssl_, nullptr);
346
347
  // Handle error
348
2341
  if (status) {
349
    // Ignore errors after shutdown
350
2
    if (wrap->shutdown_)
351
1
      return;
352
353
    // Notify about error
354
1
    wrap->InvokeQueued(status);
355
1
    return;
356
  }
357
358
  // Commit
359
2339
  NodeBIO::FromBIO(wrap->enc_out_)->Read(nullptr, wrap->write_size_);
360
361
  // Ensure that the progress will be made and `InvokeQueued` will be called.
362
2339
  wrap->ClearIn();
363
364
  // Try writing more data
365
2339
  wrap->write_size_ = 0;
366
2339
  wrap->EncOut();
367
}
368
369
370
3389
Local<Value> TLSWrap::GetSSLError(int status, int* err, const char** msg) {
371
3389
  EscapableHandleScope scope(env()->isolate());
372
373
  // ssl_ is already destroyed in reading EOF by close notify alert.
374
3389
  if (ssl_ == nullptr)
375
    return Local<Value>();
376
377
3389
  *err = SSL_get_error(ssl_, status);
378
3389
  switch (*err) {
379
    case SSL_ERROR_NONE:
380
    case SSL_ERROR_WANT_READ:
381
    case SSL_ERROR_WANT_WRITE:
382
    case SSL_ERROR_WANT_X509_LOOKUP:
383
3140
      break;
384
    case SSL_ERROR_ZERO_RETURN:
385
456
      return scope.Escape(env()->zero_return_string());
386
      break;
387
    default:
388
      {
389

21
        CHECK(*err == SSL_ERROR_SSL || *err == SSL_ERROR_SYSCALL);
390
391
21
        BIO* bio = BIO_new(BIO_s_mem());
392
21
        ERR_print_errors(bio);
393
394
        BUF_MEM* mem;
395
21
        BIO_get_mem_ptr(bio, &mem);
396
397
        Local<String> message =
398
21
            OneByteString(env()->isolate(), mem->data, mem->length);
399
21
        Local<Value> exception = Exception::Error(message);
400
401
21
        if (msg != nullptr) {
402
3
          CHECK_EQ(*msg, nullptr);
403
3
          char* const buf = new char[mem->length + 1];
404
3
          memcpy(buf, mem->data, mem->length);
405
3
          buf[mem->length] = '\0';
406
3
          *msg = buf;
407
        }
408
21
        BIO_free_all(bio);
409
410
        return scope.Escape(exception);
411
      }
412
  }
413
3140
  return Local<Value>();
414
}
415
416
417
2969
void TLSWrap::ClearOut() {
418
  // Ignore cycling data if ClientHello wasn't yet parsed
419
2969
  if (!hello_parser_.IsEnded())
420
233
    return;
421
422
  // No reads after EOF
423
2968
  if (eof_)
424
1
    return;
425
426
2967
  if (ssl_ == nullptr)
427
1
    return;
428
429
2966
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
430
431
  char out[kClearOutChunkSize];
432
  int read;
433
  for (;;) {
434
4083
    read = SSL_read(ssl_, out, sizeof(out));
435
436
4082
    if (read <= 0)
437
2962
      break;
438
439
1120
    char* current = out;
440
3359
    while (read > 0) {
441
1122
      int avail = read;
442
443
      uv_buf_t buf;
444
1122
      OnAlloc(avail, &buf);
445
1122
      if (static_cast<int>(buf.len) < avail)
446
2
        avail = buf.len;
447
1122
      memcpy(buf.base, current, avail);
448
1122
      OnRead(avail, &buf);
449
450
      // Caveat emptor: OnRead() calls into JS land which can result in
451
      // the SSL context object being destroyed.  We have to carefully
452
      // check that ssl_ != nullptr afterwards.
453
1120
      if (ssl_ == nullptr)
454
1
        return;
455
456
1119
      read -= avail;
457
1119
      current += avail;
458
    }
459
1117
  }
460
461
2962
  int flags = SSL_get_shutdown(ssl_);
462

2962
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
463
253
    eof_ = true;
464
253
    OnRead(UV_EOF, nullptr);
465
  }
466
467
  // We need to check whether an error occurred or the connection was
468
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
469
  // See node#1642 and SSL_read(3SSL) for details.
470
2962
  if (read <= 0) {
471
    int err;
472
2962
    Local<Value> arg = GetSSLError(read, &err, nullptr);
473
474
    // Ignore ZERO_RETURN after EOF, it is basically not a error
475

2962
    if (err == SSL_ERROR_ZERO_RETURN && eof_)
476
228
      return;
477
478
2734
    if (!arg.IsEmpty()) {
479
      // When TLS Alert are stored in wbio,
480
      // it should be flushed to socket before destroyed.
481
18
      if (BIO_pending(enc_out_) != 0)
482
9
        EncOut();
483
484
18
      MakeCallback(env()->onerror_string(), 1, &arg);
485
    }
486
2734
  }
487
}
488
489
490
5529
bool TLSWrap::ClearIn() {
491
  // Ignore cycling data if ClientHello wasn't yet parsed
492
5529
  if (!hello_parser_.IsEnded())
493
    return false;
494
495
5529
  if (ssl_ == nullptr)
496
    return false;
497
498
5529
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
499
500
5529
  int written = 0;
501
11164
  while (clear_in_->Length() > 0) {
502
422
    size_t avail = 0;
503
422
    char* data = clear_in_->Peek(&avail);
504
422
    written = SSL_write(ssl_, data, avail);
505

422
    CHECK(written == -1 || written == static_cast<int>(avail));
506
422
    if (written == -1)
507
316
      break;
508
106
    clear_in_->Read(nullptr, avail);
509
  }
510
511
  // All written
512
5529
  if (clear_in_->Length() == 0) {
513
5213
    CHECK_GE(written, 0);
514
5213
    return true;
515
  }
516
517
  // Error or partial write
518
  int err;
519
316
  const char* error_str = nullptr;
520
316
  Local<Value> arg = GetSSLError(written, &err, &error_str);
521
316
  if (!arg.IsEmpty()) {
522
3
    MakePending();
523
3
    InvokeQueued(UV_EPROTO, error_str);
524
3
    delete[] error_str;
525
3
    clear_in_->Reset();
526
  }
527
528
316
  return false;
529
}
530
531
532
2341
void* TLSWrap::Cast() {
533
2341
  return reinterpret_cast<void*>(this);
534
}
535
536
537
3645
AsyncWrap* TLSWrap::GetAsyncWrap() {
538
3645
  return static_cast<AsyncWrap*>(this);
539
}
540
541
542
482
bool TLSWrap::IsIPCPipe() {
543
482
  return stream_->IsIPCPipe();
544
}
545
546
547
2
int TLSWrap::GetFD() {
548
2
  return stream_->GetFD();
549
}
550
551
552
1562
bool TLSWrap::IsAlive() {
553

1562
  return ssl_ != nullptr && stream_ != nullptr && stream_->IsAlive();
554
}
555
556
557
3
bool TLSWrap::IsClosing() {
558
3
  return stream_->IsClosing();
559
}
560
561
562
386
int TLSWrap::ReadStart() {
563
386
  return stream_->ReadStart();
564
}
565
566
567
64
int TLSWrap::ReadStop() {
568
64
  return stream_->ReadStop();
569
}
570
571
572
1575
const char* TLSWrap::Error() const {
573
1575
  return error_;
574
}
575
576
577
344
void TLSWrap::ClearError() {
578
344
  delete[] error_;
579
344
  error_ = nullptr;
580
344
}
581
582
583
790
int TLSWrap::DoWrite(WriteWrap* w,
584
                     uv_buf_t* bufs,
585
                     size_t count,
586
                     uv_stream_t* send_handle) {
587
790
  CHECK_EQ(send_handle, nullptr);
588
790
  CHECK_NE(ssl_, nullptr);
589
590
790
  bool empty = true;
591
592
  // Empty writes should not go through encryption process
593
  size_t i;
594
792
  for (i = 0; i < count; i++)
595
790
    if (bufs[i].len > 0) {
596
788
      empty = false;
597
788
      break;
598
    }
599
790
  if (empty) {
600
2
    ClearOut();
601
    // However, if there is any data that should be written to the socket,
602
    // the callback should not be invoked immediately
603
2
    if (BIO_pending(enc_out_) == 0)
604
      return stream_->DoWrite(w, bufs, count, send_handle);
605
  }
606
607
  // Queue callback to execute it on next tick
608
790
  write_item_queue_.PushBack(new WriteItem(w));
609
790
  w->Dispatched();
610
611
  // Write queued data
612
790
  if (empty) {
613
2
    EncOut();
614
2
    return 0;
615
  }
616
617
  // Process enqueued data first
618
788
  if (!ClearIn()) {
619
    // If there're still data to process - enqueue current one
620
    for (i = 0; i < count; i++)
621
      clear_in_->Write(bufs[i].base, bufs[i].len);
622
    return 0;
623
  }
624
625
788
  if (ssl_ == nullptr) {
626
    ClearError();
627
628
    static char msg[] = "Write after DestroySSL";
629
    char* tmp = new char[sizeof(msg)];
630
    memcpy(tmp, msg, sizeof(msg));
631
    error_ = tmp;
632
    return UV_EPROTO;
633
  }
634
635
788
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
636
637
788
  int written = 0;
638
4211
  for (i = 0; i < count; i++) {
639
3534
    written = SSL_write(ssl_, bufs[i].base, bufs[i].len);
640

3534
    CHECK(written == -1 || written == static_cast<int>(bufs[i].len));
641
3534
    if (written == -1)
642
111
      break;
643
  }
644
645
788
  if (i != count) {
646
    int err;
647
111
    Local<Value> arg = GetSSLError(written, &err, &error_);
648
111
    if (!arg.IsEmpty())
649
      return UV_EPROTO;
650
651
    // No errors, queue rest
652
228
    for (; i < count; i++)
653
117
      clear_in_->Write(bufs[i].base, bufs[i].len);
654
  }
655
656
  // Try writing data immediately
657
788
  EncOut();
658
659
788
  return 0;
660
}
661
662
663
12
void TLSWrap::OnAfterWriteImpl(WriteWrap* w, void* ctx) {
664
  // Intentionally empty
665
12
}
666
667
668
2603
void TLSWrap::OnAllocImpl(size_t suggested_size, uv_buf_t* buf, void* ctx) {
669
2603
  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
670
671
2603
  if (wrap->ssl_ == nullptr) {
672
1
    *buf = uv_buf_init(nullptr, 0);
673
2604
    return;
674
  }
675
676
2602
  size_t size = 0;
677
2602
  buf->base = NodeBIO::FromBIO(wrap->enc_in_)->PeekWritable(&size);
678
2602
  buf->len = size;
679
}
680
681
682
2616
void TLSWrap::OnReadImpl(ssize_t nread,
683
                         const uv_buf_t* buf,
684
                         uv_handle_type pending,
685
                         void* ctx) {
686
2616
  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
687
2616
  wrap->DoRead(nread, buf, pending);
688
2613
}
689
690
691
706
void TLSWrap::OnDestructImpl(void* ctx) {
692
706
  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
693
706
  wrap->clear_stream();
694
706
}
695
696
697
946
void TLSWrap::OnAllocSelf(size_t suggested_size, uv_buf_t* buf, void* ctx) {
698
946
  buf->base = node::Malloc(suggested_size);
699
946
  buf->len = suggested_size;
700
946
}
701
702
703
1438
void TLSWrap::OnReadSelf(ssize_t nread,
704
                         const uv_buf_t* buf,
705
                         uv_handle_type pending,
706
                         void* ctx) {
707
1438
  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
708
  Local<Object> buf_obj;
709
1438
  if (buf != nullptr)
710
1924
    buf_obj = Buffer::New(wrap->env(), buf->base, buf->len).ToLocalChecked();
711
1438
  wrap->EmitData(nread, buf_obj, Local<Object>());
712
1436
}
713
714
715
2616
void TLSWrap::DoRead(ssize_t nread,
716
                     const uv_buf_t* buf,
717
                     uv_handle_type pending) {
718
2616
  if (nread < 0)  {
719
    // Error should be emitted only after all data was read
720
241
    ClearOut();
721
722
    // Ignore EOF if received close_notify
723
241
    if (nread == UV_EOF) {
724
239
      if (eof_)
725
1
        return;
726
238
      eof_ = true;
727
    }
728
729
240
    OnRead(nread, nullptr);
730
240
    return;
731
  }
732
733
  // Only client connections can receive data
734
2375
  if (ssl_ == nullptr) {
735
    OnRead(UV_EPROTO, nullptr);
736
    return;
737
  }
738
739
  // Commit read data
740
2375
  NodeBIO* enc_in = NodeBIO::FromBIO(enc_in_);
741
2375
  enc_in->Commit(nread);
742
743
  // Parse ClientHello first
744
2375
  if (!hello_parser_.IsEnded()) {
745
20
    size_t avail = 0;
746
20
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
747

20
    CHECK(avail == 0 || data != nullptr);
748
20
    return hello_parser_.Parse(data, avail);
749
  }
750
751
  // Cycle OpenSSL's state
752
2355
  Cycle();
753
}
754
755
756
317
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
757
317
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
758
759

317
  if (ssl_ != nullptr && SSL_shutdown(ssl_) == 0)
760
317
    SSL_shutdown(ssl_);
761
762
317
  shutdown_ = true;
763
317
  EncOut();
764
317
  return stream_->DoShutdown(req_wrap);
765
}
766
767
768
713
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
769
713
  Environment* env = Environment::GetCurrent(args);
770
771
  TLSWrap* wrap;
772
713
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
773
774



4278
  if (args.Length() < 2 || !args[0]->IsBoolean() || !args[1]->IsBoolean())
775
    return env->ThrowTypeError("Bad arguments, expected two booleans");
776
777
713
  if (wrap->ssl_ == nullptr)
778
    return env->ThrowTypeError("SetVerifyMode after destroySSL");
779
780
  int verify_mode;
781
713
  if (wrap->is_server()) {
782
738
    bool request_cert = args[0]->IsTrue();
783
369
    if (!request_cert) {
784
      // Note reject_unauthorized ignored.
785
303
      verify_mode = SSL_VERIFY_NONE;
786
    } else {
787
132
      bool reject_unauthorized = args[1]->IsTrue();
788
66
      verify_mode = SSL_VERIFY_PEER;
789
66
      if (reject_unauthorized)
790
35
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
791
    }
792
  } else {
793
    // Note request_cert and reject_unauthorized are ignored for clients.
794
344
    verify_mode = SSL_VERIFY_NONE;
795
  }
796
797
  // Always allow a connection. We'll reject in javascript.
798
713
  SSL_set_verify(wrap->ssl_, verify_mode, crypto::VerifyCallback);
799
}
800
801
802
20
void TLSWrap::EnableSessionCallbacks(
803
    const FunctionCallbackInfo<Value>& args) {
804
  TLSWrap* wrap;
805
20
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
806
20
  if (wrap->ssl_ == nullptr) {
807
    return wrap->env()->ThrowTypeError(
808
        "EnableSessionCallbacks after destroySSL");
809
  }
810
20
  wrap->enable_session_callbacks();
811
20
  NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
812
  wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
813
                            OnClientHelloParseEnd,
814
20
                            wrap);
815
}
816
817
818
709
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
819
  TLSWrap* wrap;
820
1418
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
821
822
  // Move all writes to pending
823
709
  wrap->MakePending();
824
825
  // And destroy
826
709
  wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
827
828
  // Destroy the SSL structure and friends
829
709
  wrap->SSLWrap<TLSWrap>::DestroySSL();
830
831
709
  delete wrap->clear_in_;
832
709
  wrap->clear_in_ = nullptr;
833
}
834
835
836
22
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
837
  TLSWrap* wrap;
838
44
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
839
22
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
840
}
841
842
843
39
void TLSWrap::OnClientHelloParseEnd(void* arg) {
844
39
  TLSWrap* c = static_cast<TLSWrap*>(arg);
845
39
  c->Cycle();
846
39
}
847
848
849
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
850
360
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
851
360
  Environment* env = Environment::GetCurrent(args);
852
853
  TLSWrap* wrap;
854
720
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
855
856
360
  CHECK_NE(wrap->ssl_, nullptr);
857
858
  const char* servername = SSL_get_servername(wrap->ssl_,
859
360
                                              TLSEXT_NAMETYPE_host_name);
860
360
  if (servername != nullptr) {
861
369
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
862
  } else {
863
474
    args.GetReturnValue().Set(false);
864
  }
865
}
866
867
868
114
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
869
114
  Environment* env = Environment::GetCurrent(args);
870
871
  TLSWrap* wrap;
872
114
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
873
874


570
  if (args.Length() < 1 || !args[0]->IsString())
875
    return env->ThrowTypeError("First argument should be a string");
876
877
114
  if (wrap->started_)
878
    return env->ThrowError("Already started.");
879
880
114
  if (!wrap->is_client())
881
    return;
882
883
114
  CHECK_NE(wrap->ssl_, nullptr);
884
885
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
886
228
  node::Utf8Value servername(env->isolate(), args[0].As<String>());
887
114
  SSL_set_tlsext_host_name(wrap->ssl_, *servername);
888
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
889
}
890
891
892
371
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
893
371
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
894
371
  Environment* env = p->env();
895
896
371
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
897
898
371
  if (servername == nullptr)
899
245
    return SSL_TLSEXT_ERR_OK;
900
901
  // Call the SNI callback and use its return value as context
902
126
  Local<Object> object = p->object();
903
252
  Local<Value> ctx = object->Get(env->sni_context_string());
904
905
  // Not an object, probably undefined or null
906
126
  if (!ctx->IsObject())
907
126
    return SSL_TLSEXT_ERR_NOACK;
908
909
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
910
  if (!cons->HasInstance(ctx)) {
911
    // Failure: incorrect SNI context object
912
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
913
    p->MakeCallback(env->onerror_string(), 1, &err);
914
    return SSL_TLSEXT_ERR_NOACK;
915
  }
916
917
  p->sni_context_.Reset();
918
  p->sni_context_.Reset(env->isolate(), ctx);
919
920
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
921
  CHECK_NE(sc, nullptr);
922
  p->SetSNIContext(sc);
923
  return SSL_TLSEXT_ERR_OK;
924
}
925
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
926
927
928
176
void TLSWrap::Initialize(Local<Object> target,
929
                         Local<Value> unused,
930
                         Local<Context> context) {
931
176
  Environment* env = Environment::GetCurrent(context);
932
933
176
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
934
935
1630
  auto constructor = [](const FunctionCallbackInfo<Value>& args) {
936
727
    CHECK(args.IsConstructCall());
937
1454
    args.This()->SetAlignedPointerInInternalField(0, nullptr);
938
1630
  };
939
176
  auto t = env->NewFunctionTemplate(constructor);
940
352
  t->InstanceTemplate()->SetInternalFieldCount(1);
941
352
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap"));
942
943
176
  env->SetProtoMethod(t, "getAsyncId", AsyncWrap::GetAsyncId);
944
176
  env->SetProtoMethod(t, "asyncReset", AsyncWrap::AsyncReset);
945
176
  env->SetProtoMethod(t, "receive", Receive);
946
176
  env->SetProtoMethod(t, "start", Start);
947
176
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
948
176
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
949
176
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
950
176
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
951
952
176
  StreamBase::AddMethods<TLSWrap>(env, t, StreamBase::kFlagHasWritev);
953
176
  SSLWrap<TLSWrap>::AddMethods(env, t);
954
955
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
956
176
  env->SetProtoMethod(t, "getServername", GetServername);
957
176
  env->SetProtoMethod(t, "setServername", SetServername);
958
#endif  // SSL_CRT_SET_TLSEXT_SERVERNAME_CB
959
960
176
  env->set_tls_wrap_constructor_template(t);
961
176
  env->set_tls_wrap_constructor_function(t->GetFunction());
962
963
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap"),
964
528
              t->GetFunction());
965
176
}
966
967
}  // namespace node
968
969
2441
NODE_MODULE_CONTEXT_AWARE_BUILTIN(tls_wrap, node::TLSWrap::Initialize)