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: 439 475 92.4 %
Date: 2017-10-21 Branches: 219 311 70.4 %

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
35
namespace node {
36
37
using crypto::SecureContext;
38
using crypto::SSLWrap;
39
using v8::Context;
40
using v8::EscapableHandleScope;
41
using v8::Exception;
42
using v8::Function;
43
using v8::FunctionCallbackInfo;
44
using v8::FunctionTemplate;
45
using v8::Integer;
46
using v8::Local;
47
using v8::Object;
48
using v8::String;
49
using v8::Value;
50
51
784
TLSWrap::TLSWrap(Environment* env,
52
                 Kind kind,
53
                 StreamBase* stream,
54
                 SecureContext* sc)
55
    : AsyncWrap(env,
56
                env->tls_wrap_constructor_function()
57
2352
                    ->NewInstance(env->context()).ToLocalChecked(),
58
                AsyncWrap::PROVIDER_TLSWRAP),
59
      SSLWrap<TLSWrap>(env, sc, kind),
60
      StreamBase(env),
61
      sc_(sc),
62
      stream_(stream),
63
      enc_in_(nullptr),
64
      enc_out_(nullptr),
65
      clear_in_(nullptr),
66
      write_size_(0),
67
      started_(false),
68
      established_(false),
69
      shutdown_(false),
70
      cycle_depth_(0),
71
2352
      eof_(false) {
72
784
  node::Wrap(object(), this);
73
784
  MakeWeak(this);
74
75
  // sc comes from an Unwrap. Make sure it was assigned.
76
784
  CHECK_NE(sc, nullptr);
77
78
  // We've our own session callbacks
79
784
  SSL_CTX_sess_set_get_cb(sc_->ctx_, SSLWrap<TLSWrap>::GetSessionCallback);
80
784
  SSL_CTX_sess_set_new_cb(sc_->ctx_, SSLWrap<TLSWrap>::NewSessionCallback);
81
82
784
  stream_->Consume();
83
784
  stream_->set_after_write_cb({ OnAfterWriteImpl, this });
84
784
  stream_->set_alloc_cb({ OnAllocImpl, this });
85
784
  stream_->set_read_cb({ OnReadImpl, this });
86
784
  stream_->set_destruct_cb({ OnDestructImpl, this });
87
88
784
  set_alloc_cb({ OnAllocSelf, this });
89
784
  set_read_cb({ OnReadSelf, this });
90
91
784
  InitSSL();
92
784
}
93
94
95
2259
TLSWrap::~TLSWrap() {
96
753
  enc_in_ = nullptr;
97
753
  enc_out_ = nullptr;
98
753
  delete clear_in_;
99
753
  clear_in_ = nullptr;
100
101
753
  sc_ = nullptr;
102
103
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
104
753
  sni_context_.Reset();
105
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
106
1506
}
107
108
109
1650
void TLSWrap::MakePending() {
110
1650
  write_item_queue_.MoveBack(&pending_write_items_);
111
1650
}
112
113
114
4142
bool TLSWrap::InvokeQueued(int status, const char* error_str) {
115
4142
  if (pending_write_items_.IsEmpty())
116
3253
    return false;
117
118
  // Process old queue
119
889
  WriteItemList queue;
120
889
  pending_write_items_.MoveBack(&queue);
121
1784
  while (WriteItem* wi = queue.PopFront()) {
122
895
    wi->w_->Done(status, error_str);
123
895
    delete wi;
124
  }
125
126
889
  return true;
127
}
128
129
130
8
void TLSWrap::NewSessionDoneCb() {
131
8
  Cycle();
132
8
}
133
134
135
784
void TLSWrap::InitSSL() {
136
  // Initialize SSL
137
784
  enc_in_ = crypto::NodeBIO::New();
138
784
  enc_out_ = crypto::NodeBIO::New();
139
784
  crypto::NodeBIO::FromBIO(enc_in_)->AssignEnvironment(env());
140
784
  crypto::NodeBIO::FromBIO(enc_out_)->AssignEnvironment(env());
141
142
784
  SSL_set_bio(ssl_, enc_in_, enc_out_);
143
144
  // NOTE: This could be overridden in SetVerifyMode
145
784
  SSL_set_verify(ssl_, SSL_VERIFY_NONE, crypto::VerifyCallback);
146
147
#ifdef SSL_MODE_RELEASE_BUFFERS
148
784
  long mode = SSL_get_mode(ssl_);  // NOLINT(runtime/int)
149
784
  SSL_set_mode(ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
150
#endif  // SSL_MODE_RELEASE_BUFFERS
151
152
784
  SSL_set_app_data(ssl_, this);
153
784
  SSL_set_info_callback(ssl_, SSLInfoCallback);
154
155
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
156
784
  if (is_server()) {
157
408
    SSL_CTX_set_tlsext_servername_callback(sc_->ctx_, SelectSNIContextCallback);
158
  }
159
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
160
161
784
  InitNPN(sc_);
162
163
784
  SSL_set_cert_cb(ssl_, SSLWrap<TLSWrap>::SSLCertCallback, this);
164
165
784
  if (is_server()) {
166
408
    SSL_set_accept_state(ssl_);
167
376
  } else if (is_client()) {
168
    // Enough space for server response (hello, cert)
169
376
    crypto::NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
170
376
    SSL_set_connect_state(ssl_);
171
  } else {
172
    // Unexpected
173
    ABORT();
174
  }
175
176
  // Initialize ring for queud clear data
177
784
  clear_in_ = new crypto::NodeBIO();
178
784
  clear_in_->AssignEnvironment(env());
179
784
}
180
181
182
784
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
183
784
  Environment* env = Environment::GetCurrent(args);
184
185


3136
  if (args.Length() < 1 || !args[0]->IsObject()) {
186
    return env->ThrowTypeError(
187
        "First argument should be a LibuvStreamWrap instance");
188
  }
189


3136
  if (args.Length() < 2 || !args[1]->IsObject()) {
190
    return env->ThrowTypeError(
191
        "Second argument should be a SecureContext instance");
192
  }
193


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


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

6173
  if (established_ && !write_item_queue_.IsEmpty())
294
884
    MakePending();
295
296
6173
  if (ssl_ == nullptr)
297
1
    return;
298
299
  // No data to write
300
6172
  if (BIO_pending(enc_out_) == 0) {
301
3597
    UpdateWriteQueueSize();
302
3597
    if (clear_in_->Length() == 0)
303
3359
      InvokeQueued(0);
304
3597
    return;
305
  }
306
307
  char* data[kSimultaneousBufferCount];
308
  size_t size[arraysize(data)];
309
2575
  size_t count = arraysize(data);
310
  write_size_ = crypto::NodeBIO::FromBIO(enc_out_)->PeekMultiple(data,
311
                                                                 size,
312
2575
                                                                 &count);
313

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

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

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

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

466
    CHECK(written == -1 || written == static_cast<int>(avail));
501
466
    if (written == -1)
502
348
      break;
503
118
    clear_in_->Read(nullptr, avail);
504
  }
505
506
  // All written
507
6232
  if (clear_in_->Length() == 0) {
508
5884
    CHECK_GE(written, 0);
509
5884
    return true;
510
  }
511
512
  // Error or partial write
513
  int err;
514
696
  std::string error_str;
515
348
  Local<Value> arg = GetSSLError(written, &err, &error_str);
516
348
  if (!arg.IsEmpty()) {
517
5
    MakePending();
518
5
    InvokeQueued(UV_EPROTO, error_str.c_str());
519
5
    clear_in_->Reset();
520
  }
521
522
6580
  return false;
523
}
524
525
526
2557
void* TLSWrap::Cast() {
527
2557
  return reinterpret_cast<void*>(this);
528
}
529
530
531
4070
AsyncWrap* TLSWrap::GetAsyncWrap() {
532
4070
  return static_cast<AsyncWrap*>(this);
533
}
534
535
536
640
bool TLSWrap::IsIPCPipe() {
537
640
  return stream_->IsIPCPipe();
538
}
539
540
541
3
int TLSWrap::GetFD() {
542
3
  return stream_->GetFD();
543
}
544
545
546
1712
bool TLSWrap::IsAlive() {
547

1712
  return ssl_ != nullptr && stream_ != nullptr && stream_->IsAlive();
548
}
549
550
551
28
bool TLSWrap::IsClosing() {
552
28
  return stream_->IsClosing();
553
}
554
555
556
4505
uint32_t TLSWrap::UpdateWriteQueueSize(uint32_t write_queue_size) {
557
4505
  HandleScope scope(env()->isolate());
558
4505
  if (write_queue_size == 0)
559
4503
    write_queue_size = BIO_pending(enc_out_);
560
4505
  object()->Set(env()->context(),
561
                env()->write_queue_size_string(),
562
                Integer::NewFromUnsigned(env()->isolate(),
563
27030
                                         write_queue_size)).FromJust();
564
4505
  return write_queue_size;
565
}
566
567
568
416
int TLSWrap::ReadStart() {
569
416
  return stream_->ReadStart();
570
}
571
572
573
64
int TLSWrap::ReadStop() {
574
64
  return stream_->ReadStop();
575
}
576
577
578
1741
const char* TLSWrap::Error() const {
579
1741
  return error_.empty() ? nullptr : error_.c_str();
580
}
581
582
583
void TLSWrap::ClearError() {
584
  error_.clear();
585
}
586
587
588
898
int TLSWrap::DoWrite(WriteWrap* w,
589
                     uv_buf_t* bufs,
590
                     size_t count,
591
                     uv_stream_t* send_handle) {
592
898
  CHECK_EQ(send_handle, nullptr);
593
898
  CHECK_NE(ssl_, nullptr);
594
595
898
  bool empty = true;
596
597
  // Empty writes should not go through encryption process
598
  size_t i;
599
904
  for (i = 0; i < count; i++)
600
898
    if (bufs[i].len > 0) {
601
892
      empty = false;
602
892
      break;
603
    }
604
898
  if (empty) {
605
6
    ClearOut();
606
    // However, if there is any data that should be written to the socket,
607
    // the callback should not be invoked immediately
608
6
    if (BIO_pending(enc_out_) == 0) {
609
      // net.js expects writeQueueSize to be > 0 if the write isn't
610
      // immediately flushed
611
2
      UpdateWriteQueueSize(1);
612
2
      return stream_->DoWrite(w, bufs, count, send_handle);
613
    }
614
  }
615
616
  // Queue callback to execute it on next tick
617
896
  write_item_queue_.PushBack(new WriteItem(w));
618
896
  w->Dispatched();
619
620
  // Write queued data
621
896
  if (empty) {
622
4
    EncOut();
623
4
    return 0;
624
  }
625
626
  // Process enqueued data first
627
892
  if (!ClearIn()) {
628
    // If there're still data to process - enqueue current one
629
    for (i = 0; i < count; i++)
630
      clear_in_->Write(bufs[i].base, bufs[i].len);
631
    return 0;
632
  }
633
634
892
  if (ssl_ == nullptr) {
635
    ClearError();
636
    error_ = "Write after DestroySSL";
637
    return UV_EPROTO;
638
  }
639
640
892
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
641
642
892
  int written = 0;
643
4417
  for (i = 0; i < count; i++) {
644
3650
    written = SSL_write(ssl_, bufs[i].base, bufs[i].len);
645

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

20
    CHECK(avail == 0 || data != nullptr);
755
20
    return hello_parser_.Parse(data, avail);
756
  }
757
758
  // Cycle OpenSSL's state
759
2738
  Cycle();
760
}
761
762
763
328
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
764
328
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
765
766

328
  if (ssl_ != nullptr && SSL_shutdown(ssl_) == 0)
767
328
    SSL_shutdown(ssl_);
768
769
328
  shutdown_ = true;
770
328
  EncOut();
771
328
  return stream_->DoShutdown(req_wrap);
772
}
773
774
775
771
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
776
771
  Environment* env = Environment::GetCurrent(args);
777
778
  TLSWrap* wrap;
779
771
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
780
781



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


675
  if (args.Length() < 1 || !args[0]->IsString())
882
    return env->ThrowTypeError("First argument should be a string");
883
884
135
  if (wrap->started_)
885
    return env->ThrowError("Already started.");
886
887
135
  if (!wrap->is_client())
888
    return;
889
890
135
  CHECK_NE(wrap->ssl_, nullptr);
891
892
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
893
270
  node::Utf8Value servername(env->isolate(), args[0].As<String>());
894
135
  SSL_set_tlsext_host_name(wrap->ssl_, *servername);
895
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
896
}
897
898
899
399
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
900
399
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
901
399
  Environment* env = p->env();
902
903
399
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
904
905
399
  if (servername == nullptr)
906
259
    return SSL_TLSEXT_ERR_OK;
907
908
  // Call the SNI callback and use its return value as context
909
140
  Local<Object> object = p->object();
910
280
  Local<Value> ctx = object->Get(env->sni_context_string());
911
912
  // Not an object, probably undefined or null
913
140
  if (!ctx->IsObject())
914
140
    return SSL_TLSEXT_ERR_NOACK;
915
916
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
917
  if (!cons->HasInstance(ctx)) {
918
    // Failure: incorrect SNI context object
919
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
920
    p->MakeCallback(env->onerror_string(), 1, &err);
921
    return SSL_TLSEXT_ERR_NOACK;
922
  }
923
924
  p->sni_context_.Reset();
925
  p->sni_context_.Reset(env->isolate(), ctx);
926
927
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
928
  CHECK_NE(sc, nullptr);
929
  p->SetSNIContext(sc);
930
  return SSL_TLSEXT_ERR_OK;
931
}
932
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
933
934
935
2
void TLSWrap::UpdateWriteQueueSize(const FunctionCallbackInfo<Value>& args) {
936
  TLSWrap* wrap;
937
4
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
938
939
2
  uint32_t write_queue_size = wrap->UpdateWriteQueueSize();
940
4
  args.GetReturnValue().Set(write_queue_size);
941
}
942
943
944
327
void TLSWrap::Initialize(Local<Object> target,
945
                         Local<Value> unused,
946
                         Local<Context> context) {
947
327
  Environment* env = Environment::GetCurrent(context);
948
949
327
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
950
951
1897
  auto constructor = [](const FunctionCallbackInfo<Value>& args) {
952
785
    CHECK(args.IsConstructCall());
953
1570
    args.This()->SetAlignedPointerInInternalField(0, nullptr);
954
1897
  };
955
956
  Local<String> tlsWrapString =
957
327
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
958
959
327
  auto t = env->NewFunctionTemplate(constructor);
960
654
  t->InstanceTemplate()->SetInternalFieldCount(1);
961
327
  t->SetClassName(tlsWrapString);
962
963
327
  AsyncWrap::AddWrapMethods(env, t, AsyncWrap::kFlagHasReset);
964
327
  env->SetProtoMethod(t, "receive", Receive);
965
327
  env->SetProtoMethod(t, "start", Start);
966
327
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
967
327
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
968
327
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
969
327
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
970
327
  env->SetProtoMethod(t, "updateWriteQueueSize", UpdateWriteQueueSize);
971
972
327
  StreamBase::AddMethods<TLSWrap>(env, t, StreamBase::kFlagHasWritev);
973
327
  SSLWrap<TLSWrap>::AddMethods(env, t);
974
975
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
976
327
  env->SetProtoMethod(t, "getServername", GetServername);
977
327
  env->SetProtoMethod(t, "setServername", SetServername);
978
#endif  // SSL_CRT_SET_TLSEXT_SERVERNAME_CB
979
980
327
  env->set_tls_wrap_constructor_function(t->GetFunction());
981
982
654
  target->Set(tlsWrapString, t->GetFunction());
983
327
}
984
985
}  // namespace node
986
987
3245
NODE_MODULE_CONTEXT_AWARE_BUILTIN(tls_wrap, node::TLSWrap::Initialize)