stream_wrap: use getters, not direct field access
[platform/upstream/nodejs.git] / src / tls_wrap.cc
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 "node_buffer.h"  // Buffer
24 #include "node_crypto.h"  // SecureContext
25 #include "node_crypto_bio.h"  // NodeBIO
26 #include "node_crypto_clienthello.h"  // ClientHelloParser
27 #include "node_crypto_clienthello-inl.h"
28 #include "node_wrap.h"  // WithGenericStream
29 #include "node_counters.h"
30
31 namespace node {
32
33 using crypto::SecureContext;
34 using v8::Array;
35 using v8::Boolean;
36 using v8::Exception;
37 using v8::Function;
38 using v8::FunctionCallbackInfo;
39 using v8::FunctionTemplate;
40 using v8::Handle;
41 using v8::HandleScope;
42 using v8::Integer;
43 using v8::Local;
44 using v8::Null;
45 using v8::Object;
46 using v8::Persistent;
47 using v8::String;
48 using v8::Value;
49
50 static Cached<String> onread_sym;
51 static Cached<String> onerror_sym;
52 static Cached<String> onhandshakestart_sym;
53 static Cached<String> onhandshakedone_sym;
54 static Cached<String> onclienthello_sym;
55 static Cached<String> onnewsession_sym;
56 static Cached<String> subject_sym;
57 static Cached<String> subjectaltname_sym;
58 static Cached<String> modulus_sym;
59 static Cached<String> exponent_sym;
60 static Cached<String> issuer_sym;
61 static Cached<String> valid_from_sym;
62 static Cached<String> valid_to_sym;
63 static Cached<String> fingerprint_sym;
64 static Cached<String> name_sym;
65 static Cached<String> version_sym;
66 static Cached<String> ext_key_usage_sym;
67 static Cached<String> sessionid_sym;
68 static Cached<String> tls_ticket_sym;
69 static Cached<String> servername_sym;
70 static Cached<String> sni_context_sym;
71
72 static Persistent<Function> tlsWrap;
73
74 static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
75                                  | ASN1_STRFLGS_ESC_MSB
76                                  | XN_FLAG_SEP_MULTILINE
77                                  | XN_FLAG_FN_SN;
78
79
80 TLSCallbacks::TLSCallbacks(Kind kind,
81                            Handle<Object> sc,
82                            StreamWrapCallbacks* old)
83     : StreamWrapCallbacks(old),
84       kind_(kind),
85       ssl_(NULL),
86       enc_in_(NULL),
87       enc_out_(NULL),
88       clear_in_(NULL),
89       write_size_(0),
90       pending_write_item_(NULL),
91       started_(false),
92       established_(false),
93       shutdown_(false),
94       session_callbacks_(false),
95       next_sess_(NULL) {
96
97   // Persist SecureContext
98   sc_ = ObjectWrap::Unwrap<SecureContext>(sc);
99   sc_handle_.Reset(node_isolate, sc);
100
101   Local<Object> object = NewInstance(tlsWrap);
102   object->SetAlignedPointerInInternalField(0, this);
103   persistent().Reset(node_isolate, object);
104
105   // Initialize queue for clearIn writes
106   QUEUE_INIT(&write_item_queue_);
107
108   // We've our own session callbacks
109   SSL_CTX_sess_set_get_cb(sc_->ctx_, GetSessionCallback);
110   SSL_CTX_sess_set_new_cb(sc_->ctx_, NewSessionCallback);
111
112   InitSSL();
113 }
114
115
116 SSL_SESSION* TLSCallbacks::GetSessionCallback(SSL* s,
117                                               unsigned char* key,
118                                               int len,
119                                               int* copy) {
120   HandleScope scope(node_isolate);
121
122   TLSCallbacks* c = static_cast<TLSCallbacks*>(SSL_get_app_data(s));
123
124   *copy = 0;
125   SSL_SESSION* sess = c->next_sess_;
126   c->next_sess_ = NULL;
127
128   return sess;
129 }
130
131
132 int TLSCallbacks::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
133   HandleScope scope(node_isolate);
134
135   TLSCallbacks* c = static_cast<TLSCallbacks*>(SSL_get_app_data(s));
136   if (!c->session_callbacks_)
137     return 0;
138
139   // Check if session is small enough to be stored
140   int size = i2d_SSL_SESSION(sess, NULL);
141   if (size > SecureContext::kMaxSessionSize)
142     return 0;
143
144   // Serialize session
145   Local<Object> buff = Buffer::New(size);
146   unsigned char* serialized = reinterpret_cast<unsigned char*>(
147       Buffer::Data(buff));
148   memset(serialized, 0, size);
149   i2d_SSL_SESSION(sess, &serialized);
150
151   Local<Object> session = Buffer::New(reinterpret_cast<char*>(sess->session_id),
152                                       sess->session_id_length);
153   Handle<Value> argv[2] = { session, buff };
154   MakeCallback(c->object(), onnewsession_sym, ARRAY_SIZE(argv), argv);
155
156   return 0;
157 }
158
159
160 TLSCallbacks::~TLSCallbacks() {
161   SSL_free(ssl_);
162   ssl_ = NULL;
163   enc_in_ = NULL;
164   enc_out_ = NULL;
165   delete clear_in_;
166   clear_in_ = NULL;
167
168   sc_ = NULL;
169   sc_handle_.Dispose();
170   persistent().Dispose();
171
172 #ifdef OPENSSL_NPN_NEGOTIATED
173   npn_protos_.Dispose();
174   selected_npn_proto_.Dispose();
175 #endif  // OPENSSL_NPN_NEGOTIATED
176
177 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
178   sni_context_.Dispose();
179 #endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
180 }
181
182
183 void TLSCallbacks::InvokeQueued(int status) {
184   // Empty queue - ignore call
185   if (pending_write_item_ == NULL)
186     return;
187
188   QUEUE* q = &pending_write_item_->member_;
189   pending_write_item_ = NULL;
190
191   // Process old queue
192   while (q != &write_item_queue_) {
193     QUEUE* next = static_cast<QUEUE*>(QUEUE_NEXT(q));
194     WriteItem* wi = container_of(q, WriteItem, member_);
195     wi->cb_(&wi->w_->req_, status);
196     delete wi;
197     q = next;
198   }
199 }
200
201
202 static int VerifyCallback(int preverify_ok, X509_STORE_CTX *ctx) {
203   // Quoting SSL_set_verify(3ssl):
204   //
205   //   The VerifyCallback function is used to control the behaviour when
206   //   the SSL_VERIFY_PEER flag is set. It must be supplied by the
207   //   application and receives two arguments: preverify_ok indicates,
208   //   whether the verification of the certificate in question was passed
209   //   (preverify_ok=1) or not (preverify_ok=0). x509_ctx is a pointer to
210   //   the complete context used for the certificate chain verification.
211   //
212   //   The certificate chain is checked starting with the deepest nesting
213   //   level (the root CA certificate) and worked upward to the peer's
214   //   certificate.  At each level signatures and issuer attributes are
215   //   checked.  Whenever a verification error is found, the error number is
216   //   stored in x509_ctx and VerifyCallback is called with preverify_ok=0.
217   //   By applying X509_CTX_store_* functions VerifyCallback can locate the
218   //   certificate in question and perform additional steps (see EXAMPLES).
219   //   If no error is found for a certificate, VerifyCallback is called
220   //   with preverify_ok=1 before advancing to the next level.
221   //
222   //   The return value of VerifyCallback controls the strategy of the
223   //   further verification process. If VerifyCallback returns 0, the
224   //   verification process is immediately stopped with "verification
225   //   failed" state. If SSL_VERIFY_PEER is set, a verification failure
226   //   alert is sent to the peer and the TLS/SSL handshake is terminated. If
227   //   VerifyCallback returns 1, the verification process is continued. If
228   //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
229   //   terminated with respect to verification failures and the connection
230   //   will be established. The calling process can however retrieve the
231   //   error code of the last verification error using
232   //   SSL_get_verify_result(3) or by maintaining its own error storage
233   //   managed by VerifyCallback.
234   //
235   //   If no VerifyCallback is specified, the default callback will be
236   //   used.  Its return value is identical to preverify_ok, so that any
237   //   verification failure will lead to a termination of the TLS/SSL
238   //   handshake with an alert message, if SSL_VERIFY_PEER is set.
239   //
240   // Since we cannot perform I/O quickly enough in this callback, we ignore
241   // all preverify_ok errors and let the handshake continue. It is
242   // imparative that the user use Connection::VerifyError after the
243   // 'secure' callback has been made.
244   return 1;
245 }
246
247
248 void TLSCallbacks::InitSSL() {
249   assert(ssl_ == NULL);
250
251   // Initialize SSL
252   ssl_ = SSL_new(sc_->ctx_);
253   enc_in_ = BIO_new(NodeBIO::GetMethod());
254   enc_out_ = BIO_new(NodeBIO::GetMethod());
255
256   SSL_set_bio(ssl_, enc_in_, enc_out_);
257
258   // NOTE: This could be overriden in SetVerifyMode
259   SSL_set_verify(ssl_, SSL_VERIFY_NONE, VerifyCallback);
260
261 #ifdef SSL_MODE_RELEASE_BUFFERS
262   long mode = SSL_get_mode(ssl_);
263   SSL_set_mode(ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
264 #endif  // SSL_MODE_RELEASE_BUFFERS
265
266   SSL_set_app_data(ssl_, this);
267   SSL_set_info_callback(ssl_, SSLInfoCallback);
268
269   if (kind_ == kTLSServer) {
270     SSL_set_accept_state(ssl_);
271
272 #ifdef OPENSSL_NPN_NEGOTIATED
273     // Server should advertise NPN protocols
274     SSL_CTX_set_next_protos_advertised_cb(sc_->ctx_,
275                                           AdvertiseNextProtoCallback,
276                                           this);
277 #endif  // OPENSSL_NPN_NEGOTIATED
278
279 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
280     SSL_CTX_set_tlsext_servername_callback(sc_->ctx_, SelectSNIContextCallback);
281     SSL_CTX_set_tlsext_servername_arg(sc_->ctx_, this);
282 #endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
283   } else if (kind_ == kTLSClient) {
284     SSL_set_connect_state(ssl_);
285
286 #ifdef OPENSSL_NPN_NEGOTIATED
287     // Client should select protocol from list of advertised
288     // If server supports NPN
289     SSL_CTX_set_next_proto_select_cb(sc_->ctx_,
290                                      SelectNextProtoCallback,
291                                      this);
292 #endif  // OPENSSL_NPN_NEGOTIATED
293   } else {
294     // Unexpected
295     abort();
296   }
297
298   // Initialize ring for queud clear data
299   clear_in_ = new NodeBIO();
300 }
301
302
303 void TLSCallbacks::Wrap(const FunctionCallbackInfo<Value>& args) {
304   HandleScope scope(node_isolate);
305
306   if (args.Length() < 1 || !args[0]->IsObject())
307     return ThrowTypeError("First argument should be a StreamWrap instance");
308   if (args.Length() < 2 || !args[1]->IsObject())
309     return ThrowTypeError("Second argument should be a SecureContext instance");
310   if (args.Length() < 3 || !args[2]->IsBoolean())
311     return ThrowTypeError("Third argument should be boolean");
312
313   Local<Object> stream = args[0].As<Object>();
314   Local<Object> sc = args[1].As<Object>();
315   Kind kind = args[2]->IsTrue() ? kTLSServer : kTLSClient;
316
317   TLSCallbacks* callbacks = NULL;
318   WITH_GENERIC_STREAM(stream, {
319     callbacks = new TLSCallbacks(kind, sc, wrap->callbacks());
320     wrap->OverrideCallbacks(callbacks);
321   });
322
323   if (callbacks == NULL) {
324     return args.GetReturnValue().SetNull();
325   }
326
327   args.GetReturnValue().Set(callbacks->persistent());
328 }
329
330
331 void TLSCallbacks::Start(const FunctionCallbackInfo<Value>& args) {
332   HandleScope scope(node_isolate);
333
334   UNWRAP(TLSCallbacks);
335
336   if (wrap->started_)
337     return ThrowError("Already started.");
338   wrap->started_ = true;
339
340   // Send ClientHello handshake
341   assert(wrap->kind_ == kTLSClient);
342   wrap->ClearOut();
343   wrap->EncOut();
344 }
345
346
347 void TLSCallbacks::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
348   // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
349   // a non-const SSL* in OpenSSL <= 0.9.7e.
350   SSL* ssl = const_cast<SSL*>(ssl_);
351   if (where & SSL_CB_HANDSHAKE_START) {
352     HandleScope scope(node_isolate);
353     TLSCallbacks* c = static_cast<TLSCallbacks*>(SSL_get_app_data(ssl));
354     Local<Object> object = c->object();
355     if (object->Has(onhandshakestart_sym))
356       MakeCallback(object, onhandshakestart_sym, 0, NULL);
357   }
358   if (where & SSL_CB_HANDSHAKE_DONE) {
359     HandleScope scope(node_isolate);
360     TLSCallbacks* c = static_cast<TLSCallbacks*>(SSL_get_app_data(ssl));
361     c->established_ = true;
362     Local<Object> object = c->object();
363     if (object->Has(onhandshakedone_sym))
364       MakeCallback(object, onhandshakedone_sym, 0, NULL);
365   }
366 }
367
368
369 void TLSCallbacks::EncOut() {
370   // Ignore cycling data if ClientHello wasn't yet parsed
371   if (!hello_.IsEnded())
372     return;
373
374   // Write in progress
375   if (write_size_ != 0)
376     return;
377
378   // Split-off queue
379   if (established_ && !QUEUE_EMPTY(&write_item_queue_)) {
380     pending_write_item_ = container_of(QUEUE_NEXT(&write_item_queue_),
381                                        WriteItem,
382                                        member_);
383     QUEUE_INIT(&write_item_queue_);
384   }
385
386   // No data to write
387   if (BIO_pending(enc_out_) == 0) {
388     InvokeQueued(0);
389     return;
390   }
391
392   char* data = NodeBIO::FromBIO(enc_out_)->Peek(&write_size_);
393   assert(write_size_ != 0);
394
395   write_req_.data = this;
396   uv_buf_t buf = uv_buf_init(data, write_size_);
397   int r = uv_write(&write_req_, wrap()->stream(), &buf, 1, EncOutCb);
398
399   // Ignore errors, this should be already handled in js
400   if (!r) {
401     if (wrap()->stream()->type == UV_TCP) {
402       NODE_COUNT_NET_BYTES_SENT(write_size_);
403     } else if (wrap()->stream()->type == UV_NAMED_PIPE) {
404       NODE_COUNT_PIPE_BYTES_SENT(write_size_);
405     }
406   }
407 }
408
409
410 void TLSCallbacks::EncOutCb(uv_write_t* req, int status) {
411   HandleScope scope(node_isolate);
412
413   TLSCallbacks* callbacks = static_cast<TLSCallbacks*>(req->data);
414
415   // Handle error
416   if (status) {
417     // Ignore errors after shutdown
418     if (callbacks->shutdown_)
419       return;
420
421     // Notify about error
422     Local<Value> arg = String::Concat(
423         String::New("write cb error, status: "),
424         Integer::New(status, node_isolate)->ToString());
425     MakeCallback(callbacks->object(), onerror_sym, 1, &arg);
426     callbacks->InvokeQueued(status);
427     return;
428   }
429
430   // Commit
431   NodeBIO::FromBIO(callbacks->enc_out_)->Read(NULL, callbacks->write_size_);
432
433   // Try writing more data
434   callbacks->write_size_ = 0;
435   callbacks->EncOut();
436 }
437
438
439 Handle<Value> TLSCallbacks::GetSSLError(int status, int* err) {
440   HandleScope scope(node_isolate);
441
442   *err = SSL_get_error(ssl_, status);
443   switch (*err) {
444     case SSL_ERROR_NONE:
445     case SSL_ERROR_WANT_READ:
446     case SSL_ERROR_WANT_WRITE:
447       break;
448     case SSL_ERROR_ZERO_RETURN:
449       return scope.Close(String::NewSymbol("ZERO_RETURN"));
450       break;
451     default:
452       {
453         BUF_MEM* mem;
454         BIO* bio;
455
456         assert(*err == SSL_ERROR_SSL || *err == SSL_ERROR_SYSCALL);
457
458         bio = BIO_new(BIO_s_mem());
459         assert(bio != NULL);
460         ERR_print_errors(bio);
461         BIO_get_mem_ptr(bio, &mem);
462         Handle<Value> r = Exception::Error(String::New(mem->data, mem->length));
463         BIO_free_all(bio);
464
465         return scope.Close(r);
466       }
467   }
468   return Handle<Value>();
469 }
470
471
472 void TLSCallbacks::ClearOut() {
473   // Ignore cycling data if ClientHello wasn't yet parsed
474   if (!hello_.IsEnded())
475     return;
476
477   HandleScope scope(node_isolate);
478
479   assert(ssl_ != NULL);
480
481   char out[kClearOutChunkSize];
482   int read;
483   do {
484     read = SSL_read(ssl_, out, sizeof(out));
485     if (read > 0) {
486       Local<Value> argv[] = {
487         Integer::New(read, node_isolate),
488         Buffer::New(out, read)
489       };
490       MakeCallback(Self(), onread_sym, ARRAY_SIZE(argv), argv);
491     }
492   } while (read > 0);
493
494   if (read == -1) {
495     int err;
496     Handle<Value> argv = GetSSLError(read, &err);
497
498     if (!argv.IsEmpty())
499       MakeCallback(object(), onerror_sym, 1, &argv);
500   }
501 }
502
503
504 bool TLSCallbacks::ClearIn() {
505   // Ignore cycling data if ClientHello wasn't yet parsed
506   if (!hello_.IsEnded())
507     return false;
508
509   HandleScope scope(node_isolate);
510
511   int written = 0;
512   while (clear_in_->Length() > 0) {
513     size_t avail = 0;
514     char* data = clear_in_->Peek(&avail);
515     written = SSL_write(ssl_, data, avail);
516     assert(written == -1 || written == static_cast<int>(avail));
517     if (written == -1)
518       break;
519     clear_in_->Read(NULL, avail);
520   }
521
522   // All written
523   if (clear_in_->Length() == 0) {
524     assert(written >= 0);
525     return true;
526   }
527
528   // Error or partial write
529   int err;
530   Handle<Value> argv = GetSSLError(written, &err);
531   if (!argv.IsEmpty())
532     MakeCallback(object(), onerror_sym, 1, &argv);
533
534   return false;
535 }
536
537
538 int TLSCallbacks::DoWrite(WriteWrap* w,
539                           uv_buf_t* bufs,
540                           size_t count,
541                           uv_stream_t* send_handle,
542                           uv_write_cb cb) {
543   HandleScope scope(node_isolate);
544
545   assert(send_handle == NULL);
546
547   // Queue callback to execute it on next tick
548   WriteItem* wi = new WriteItem(w, cb);
549   bool empty = true;
550
551   // Empty writes should not go through encryption process
552   size_t i;
553   for (i = 0; i < count; i++)
554     if (bufs[i].len > 0) {
555       empty = false;
556       break;
557     }
558   if (empty) {
559     ClearOut();
560     // However if there any data that should be written to socket,
561     // callback should not be invoked immediately
562     if (BIO_pending(enc_out_) == 0)
563       return uv_write(&w->req_, wrap()->stream(), bufs, count, cb);
564   }
565
566   QUEUE_INSERT_TAIL(&write_item_queue_, &wi->member_);
567
568   // Write queued data
569   if (empty) {
570     EncOut();
571     return 0;
572   }
573
574   // Process enqueued data first
575   if (!ClearIn()) {
576     // If there're still data to process - enqueue current one
577     for (i = 0; i < count; i++)
578       clear_in_->Write(bufs[i].base, bufs[i].len);
579     return 0;
580   }
581
582   int written = 0;
583   for (i = 0; i < count; i++) {
584     written = SSL_write(ssl_, bufs[i].base, bufs[i].len);
585     assert(written == -1 || written == static_cast<int>(bufs[i].len));
586     if (written == -1)
587       break;
588   }
589
590   if (i != count) {
591     int err;
592     Handle<Value> argv = GetSSLError(written, &err);
593     if (!argv.IsEmpty()) {
594       MakeCallback(object(), onerror_sym, 1, &argv);
595       return -1;
596     }
597
598     // No errors, queue rest
599     for (; i < count; i++)
600       clear_in_->Write(bufs[i].base, bufs[i].len);
601   }
602
603   // Try writing data immediately
604   EncOut();
605
606   return 0;
607 }
608
609
610 void TLSCallbacks::AfterWrite(WriteWrap* w) {
611   // Intentionally empty
612 }
613
614
615 uv_buf_t TLSCallbacks::DoAlloc(uv_handle_t* handle, size_t suggested_size) {
616   size_t size = suggested_size;
617   char* data = NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
618   return uv_buf_init(data, size);
619 }
620
621
622 void TLSCallbacks::DoRead(uv_stream_t* handle,
623                           ssize_t nread,
624                           uv_buf_t buf,
625                           uv_handle_type pending) {
626   if (nread < 0)  {
627     // Error should be emitted only after all data was read
628     ClearOut();
629     Local<Value> arg = Integer::New(nread, node_isolate);
630     MakeCallback(Self(), onread_sym, 1, &arg);
631     return;
632   }
633
634   // Only client connections can receive data
635   assert(ssl_ != NULL);
636
637   // Commit read data
638   NodeBIO* enc_in = NodeBIO::FromBIO(enc_in_);
639   enc_in->Commit(nread);
640
641   // Parse ClientHello first
642   if (!hello_.IsEnded()) {
643     size_t avail = 0;
644     uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
645     assert(avail == 0 || data != NULL);
646     return hello_.Parse(data, avail);
647   }
648
649   // Cycle OpenSSL's state
650   Cycle();
651 }
652
653
654 int TLSCallbacks::DoShutdown(ShutdownWrap* req_wrap, uv_shutdown_cb cb) {
655   if (SSL_shutdown(ssl_) == 0)
656     SSL_shutdown(ssl_);
657   shutdown_ = true;
658   EncOut();
659   return StreamWrapCallbacks::DoShutdown(req_wrap, cb);
660 }
661
662
663 #define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: reason = #CODE; break;
664 void TLSCallbacks::VerifyError(const FunctionCallbackInfo<Value>& args) {
665   HandleScope scope(node_isolate);
666
667   UNWRAP(TLSCallbacks);
668
669   // XXX Do this check in JS land?
670   X509* peer_cert = SSL_get_peer_certificate(wrap->ssl_);
671   if (peer_cert == NULL) {
672     // We requested a certificate and they did not send us one.
673     // Definitely an error.
674     // XXX is this the right error message?
675     Local<String> s = String::New("UNABLE_TO_GET_ISSUER_CERT");
676     return args.GetReturnValue().Set(Exception::Error(s));
677   }
678   X509_free(peer_cert);
679
680   long x509_verify_error = SSL_get_verify_result(wrap->ssl_);
681
682   const char* reason = NULL;
683   Local<String> s;
684   switch (x509_verify_error) {
685   case X509_V_OK:
686     return args.GetReturnValue().SetNull();
687   CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
688   CASE_X509_ERR(UNABLE_TO_GET_CRL)
689   CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
690   CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
691   CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
692   CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
693   CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
694   CASE_X509_ERR(CERT_NOT_YET_VALID)
695   CASE_X509_ERR(CERT_HAS_EXPIRED)
696   CASE_X509_ERR(CRL_NOT_YET_VALID)
697   CASE_X509_ERR(CRL_HAS_EXPIRED)
698   CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
699   CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
700   CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
701   CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
702   CASE_X509_ERR(OUT_OF_MEM)
703   CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
704   CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
705   CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
706   CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
707   CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
708   CASE_X509_ERR(CERT_REVOKED)
709   CASE_X509_ERR(INVALID_CA)
710   CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
711   CASE_X509_ERR(INVALID_PURPOSE)
712   CASE_X509_ERR(CERT_UNTRUSTED)
713   CASE_X509_ERR(CERT_REJECTED)
714   default:
715     s = String::New(X509_verify_cert_error_string(x509_verify_error));
716     break;
717   }
718
719   if (s.IsEmpty()) {
720     s = String::New(reason);
721   }
722
723   args.GetReturnValue().Set(Exception::Error(s));
724 }
725 #undef CASE_X509_ERR
726
727
728 void TLSCallbacks::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
729   HandleScope scope(node_isolate);
730
731   UNWRAP(TLSCallbacks);
732
733   if (args.Length() < 2 || !args[0]->IsBoolean() || !args[1]->IsBoolean())
734     return ThrowTypeError("Bad arguments, expected two booleans");
735
736   int verify_mode;
737   if (wrap->kind_ == kTLSServer) {
738     bool request_cert = args[0]->IsTrue();
739     if (!request_cert) {
740       // Note reject_unauthorized ignored.
741       verify_mode = SSL_VERIFY_NONE;
742     } else {
743       bool reject_unauthorized = args[1]->IsTrue();
744       verify_mode = SSL_VERIFY_PEER;
745       if (reject_unauthorized) verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
746     }
747   } else {
748     // Note request_cert and reject_unauthorized are ignored for clients.
749     verify_mode = SSL_VERIFY_NONE;
750   }
751
752   // Always allow a connection. We'll reject in javascript.
753   SSL_set_verify(wrap->ssl_, verify_mode, VerifyCallback);
754 }
755
756
757 void TLSCallbacks::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
758   HandleScope scope(node_isolate);
759   UNWRAP(TLSCallbacks);
760   bool yes = SSL_session_reused(wrap->ssl_);
761   args.GetReturnValue().Set(yes);
762 }
763
764
765 void TLSCallbacks::EnableSessionCallbacks(
766     const FunctionCallbackInfo<Value>& args) {
767   HandleScope scope(node_isolate);
768
769   UNWRAP(TLSCallbacks);
770
771   wrap->session_callbacks_ = true;
772   EnableHelloParser(args);
773 }
774
775
776 void TLSCallbacks::EnableHelloParser(
777     const FunctionCallbackInfo<Value>& args) {
778   HandleScope scope(node_isolate);
779
780   UNWRAP(TLSCallbacks);
781
782   wrap->hello_.Start(OnClientHello, OnClientHelloParseEnd, wrap);
783 }
784
785
786 void TLSCallbacks::OnClientHello(void* arg,
787                                  const ClientHelloParser::ClientHello& hello) {
788   HandleScope scope(node_isolate);
789
790   TLSCallbacks* c = static_cast<TLSCallbacks*>(arg);
791
792   Local<Object> hello_obj = Object::New();
793   Local<Object> buff = Buffer::New(
794       reinterpret_cast<const char*>(hello.session_id()),
795                                     hello.session_size());
796   hello_obj->Set(sessionid_sym, buff);
797   if (hello.servername() == NULL) {
798     hello_obj->Set(servername_sym, String::Empty(node_isolate));
799   } else {
800     Local<String> servername = String::New(
801         reinterpret_cast<const char*>(hello.servername()),
802         hello.servername_size());
803     hello_obj->Set(servername_sym, servername);
804   }
805   hello_obj->Set(tls_ticket_sym, Boolean::New(hello.has_ticket()));
806
807   Handle<Value> argv[1] = { hello_obj };
808   MakeCallback(c->object(), onclienthello_sym, 1, argv);
809 }
810
811
812 void TLSCallbacks::OnClientHelloParseEnd(void* arg) {
813   TLSCallbacks* c = static_cast<TLSCallbacks*>(arg);
814   c->Cycle();
815 }
816
817
818 void TLSCallbacks::GetPeerCertificate(const FunctionCallbackInfo<Value>& args) {
819   HandleScope scope(node_isolate);
820
821   UNWRAP(TLSCallbacks);
822
823   Local<Object> info = Object::New();
824   X509* peer_cert = SSL_get_peer_certificate(wrap->ssl_);
825   if (peer_cert != NULL) {
826     BIO* bio = BIO_new(BIO_s_mem());
827     BUF_MEM* mem;
828     if (X509_NAME_print_ex(bio,
829                            X509_get_subject_name(peer_cert),
830                            0,
831                            X509_NAME_FLAGS) > 0) {
832       BIO_get_mem_ptr(bio, &mem);
833       info->Set(subject_sym, String::New(mem->data, mem->length));
834     }
835     (void) BIO_reset(bio);
836
837     if (X509_NAME_print_ex(bio,
838                            X509_get_issuer_name(peer_cert),
839                            0,
840                            X509_NAME_FLAGS) > 0) {
841       BIO_get_mem_ptr(bio, &mem);
842       info->Set(issuer_sym, String::New(mem->data, mem->length));
843     }
844     (void) BIO_reset(bio);
845
846     int index = X509_get_ext_by_NID(peer_cert, NID_subject_alt_name, -1);
847     if (index >= 0) {
848       X509_EXTENSION* ext;
849       int rv;
850
851       ext = X509_get_ext(peer_cert, index);
852       assert(ext != NULL);
853
854       rv = X509V3_EXT_print(bio, ext, 0, 0);
855       assert(rv == 1);
856
857       BIO_get_mem_ptr(bio, &mem);
858       info->Set(subjectaltname_sym, String::New(mem->data, mem->length));
859
860       (void) BIO_reset(bio);
861     }
862
863     EVP_PKEY* pkey = NULL;
864     RSA* rsa = NULL;
865     if (NULL != (pkey = X509_get_pubkey(peer_cert)) &&
866         NULL != (rsa = EVP_PKEY_get1_RSA(pkey))) {
867       BN_print(bio, rsa->n);
868       BIO_get_mem_ptr(bio, &mem);
869       info->Set(modulus_sym, String::New(mem->data, mem->length) );
870       (void) BIO_reset(bio);
871
872       BN_print(bio, rsa->e);
873       BIO_get_mem_ptr(bio, &mem);
874       info->Set(exponent_sym, String::New(mem->data, mem->length) );
875       (void) BIO_reset(bio);
876     }
877
878     if (pkey != NULL) {
879       EVP_PKEY_free(pkey);
880       pkey = NULL;
881     }
882     if (rsa != NULL) {
883       RSA_free(rsa);
884       rsa = NULL;
885     }
886
887     ASN1_TIME_print(bio, X509_get_notBefore(peer_cert));
888     BIO_get_mem_ptr(bio, &mem);
889     info->Set(valid_from_sym, String::New(mem->data, mem->length));
890     (void) BIO_reset(bio);
891
892     ASN1_TIME_print(bio, X509_get_notAfter(peer_cert));
893     BIO_get_mem_ptr(bio, &mem);
894     info->Set(valid_to_sym, String::New(mem->data, mem->length));
895     BIO_free_all(bio);
896
897     unsigned int md_size, i;
898     unsigned char md[EVP_MAX_MD_SIZE];
899     if (X509_digest(peer_cert, EVP_sha1(), md, &md_size)) {
900       const char hex[] = "0123456789ABCDEF";
901       char fingerprint[EVP_MAX_MD_SIZE * 3];
902
903       for (i = 0; i < md_size; i++) {
904         fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
905         fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
906         fingerprint[(3*i)+2] = ':';
907       }
908
909       if (md_size > 0)
910         fingerprint[(3*(md_size-1))+2] = '\0';
911       else
912         fingerprint[0] = '\0';
913
914       info->Set(fingerprint_sym, String::New(fingerprint));
915     }
916
917     STACK_OF(ASN1_OBJECT)* eku = static_cast<STACK_OF(ASN1_OBJECT)*>(
918         X509_get_ext_d2i(peer_cert,
919                          NID_ext_key_usage,
920                          NULL,
921                          NULL));
922     if (eku != NULL) {
923       Local<Array> ext_key_usage = Array::New();
924       char buf[256];
925
926       for (int i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
927         memset(buf, 0, sizeof(buf));
928         OBJ_obj2txt(buf, sizeof(buf) - 1, sk_ASN1_OBJECT_value(eku, i), 1);
929         ext_key_usage->Set(Integer::New(i, node_isolate), String::New(buf));
930       }
931
932       sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
933       info->Set(ext_key_usage_sym, ext_key_usage);
934     }
935
936     X509_free(peer_cert);
937   }
938
939   args.GetReturnValue().Set(info);
940 }
941
942
943 void TLSCallbacks::GetSession(const FunctionCallbackInfo<Value>& args) {
944   HandleScope scope(node_isolate);
945
946   UNWRAP(TLSCallbacks);
947
948   SSL_SESSION* sess = SSL_get_session(wrap->ssl_);
949   if (!sess) return;
950
951   int slen = i2d_SSL_SESSION(sess, NULL);
952   assert(slen > 0);
953
954   if (slen > 0) {
955     unsigned char* sbuf = new unsigned char[slen];
956     unsigned char* p = sbuf;
957     i2d_SSL_SESSION(sess, &p);
958     Local<Value> s = Encode(sbuf, slen, BINARY);
959     args.GetReturnValue().Set(s);
960     delete[] sbuf;
961     return;
962   }
963
964   args.GetReturnValue().SetNull();
965 }
966
967
968 void TLSCallbacks::SetSession(const FunctionCallbackInfo<Value>& args) {
969   HandleScope scope(node_isolate);
970
971   UNWRAP(TLSCallbacks);
972
973   if (wrap->started_)
974     return ThrowError("Already started.");
975
976   if (args.Length() < 1 ||
977       (!args[0]->IsString() && !Buffer::HasInstance(args[0]))) {
978     return ThrowTypeError("Bad argument");
979   }
980
981   size_t slen = Buffer::Length(args[0]);
982   char* sbuf = new char[slen];
983
984   ssize_t wlen = DecodeWrite(sbuf, slen, args[0], BINARY);
985   assert(wlen == static_cast<ssize_t>(slen));
986
987   const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
988   SSL_SESSION* sess = d2i_SSL_SESSION(NULL, &p, wlen);
989
990   delete[] sbuf;
991
992   if (!sess) return;
993
994   int r = SSL_set_session(wrap->ssl_, sess);
995   SSL_SESSION_free(sess);
996
997   if (!r) {
998     return ThrowError("SSL_set_session error");
999   }
1000 }
1001
1002
1003 void TLSCallbacks::LoadSession(const FunctionCallbackInfo<Value>& args) {
1004   HandleScope scope(node_isolate);
1005
1006   UNWRAP(TLSCallbacks);
1007
1008   if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1009     ssize_t slen = Buffer::Length(args[0]);
1010     char* sbuf = Buffer::Data(args[0]);
1011
1012     const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1013     SSL_SESSION* sess = d2i_SSL_SESSION(NULL, &p, slen);
1014
1015     // Setup next session and move hello to the BIO buffer
1016     if (wrap->next_sess_ != NULL)
1017       SSL_SESSION_free(wrap->next_sess_);
1018     wrap->next_sess_ = sess;
1019
1020     Local<Object> info = Object::New();
1021 #ifndef OPENSSL_NO_TLSEXT
1022     if (sess->tlsext_hostname == NULL) {
1023       info->Set(servername_sym, False(node_isolate));
1024     } else {
1025       info->Set(servername_sym, String::New(sess->tlsext_hostname));
1026     }
1027 #endif
1028     args.GetReturnValue().Set(info);
1029   }
1030 }
1031
1032 void TLSCallbacks::EndParser(const FunctionCallbackInfo<Value>& args) {
1033   HandleScope scope(node_isolate);
1034
1035   UNWRAP(TLSCallbacks);
1036
1037   wrap->hello_.End();
1038 }
1039
1040
1041 void TLSCallbacks::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
1042   HandleScope scope(node_isolate);
1043
1044   UNWRAP(TLSCallbacks);
1045
1046   const SSL_CIPHER* c;
1047
1048   c = SSL_get_current_cipher(wrap->ssl_);
1049   if (c == NULL)
1050     return;
1051
1052   const char* cipher_name = SSL_CIPHER_get_name(c);
1053   const char* cipher_version = SSL_CIPHER_get_version(c);
1054
1055   Local<Object> info = Object::New();
1056   info->Set(name_sym, String::New(cipher_name));
1057   info->Set(version_sym, String::New(cipher_version));
1058   args.GetReturnValue().Set(info);
1059 }
1060
1061
1062 #ifdef OPENSSL_NPN_NEGOTIATED
1063 int TLSCallbacks::AdvertiseNextProtoCallback(SSL* s,
1064                                              const unsigned char** data,
1065                                              unsigned int* len,
1066                                              void* arg) {
1067   TLSCallbacks* p = static_cast<TLSCallbacks*>(arg);
1068
1069   if (p->npn_protos_.IsEmpty()) {
1070     // No initialization - no NPN protocols
1071     *data = reinterpret_cast<const unsigned char*>("");
1072     *len = 0;
1073   } else {
1074     Local<Object> obj = PersistentToLocal(node_isolate, p->npn_protos_);
1075     *data = reinterpret_cast<const unsigned char*>(Buffer::Data(obj));
1076     *len = Buffer::Length(obj);
1077   }
1078
1079   return SSL_TLSEXT_ERR_OK;
1080 }
1081
1082
1083 int TLSCallbacks::SelectNextProtoCallback(SSL* s,
1084                                           unsigned char** out,
1085                                           unsigned char* outlen,
1086                                           const unsigned char* in,
1087                                           unsigned int inlen,
1088                                           void* arg) {
1089   TLSCallbacks* p = static_cast<TLSCallbacks*>(arg);
1090
1091   // Release old protocol handler if present
1092   p->selected_npn_proto_.Dispose();
1093
1094   if (p->npn_protos_.IsEmpty()) {
1095     // We should at least select one protocol
1096     // If server is using NPN
1097     *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
1098     *outlen = 8;
1099
1100     // set status: unsupported
1101     p->selected_npn_proto_.Reset(node_isolate, False(node_isolate));
1102
1103     return SSL_TLSEXT_ERR_OK;
1104   }
1105
1106   Local<Object> obj = PersistentToLocal(node_isolate, p->npn_protos_);
1107   const unsigned char* npn_protos =
1108       reinterpret_cast<const unsigned char*>(Buffer::Data(obj));
1109   size_t len = Buffer::Length(obj);
1110
1111   int status = SSL_select_next_proto(out, outlen, in, inlen, npn_protos, len);
1112   Handle<Value> result;
1113   switch (status) {
1114     case OPENSSL_NPN_UNSUPPORTED:
1115       result = Null(node_isolate);
1116       break;
1117     case OPENSSL_NPN_NEGOTIATED:
1118       result = String::New(reinterpret_cast<const char*>(*out), *outlen);
1119       break;
1120     case OPENSSL_NPN_NO_OVERLAP:
1121       result = False(node_isolate);
1122       break;
1123     default:
1124       break;
1125   }
1126
1127   if (!result.IsEmpty())
1128     p->selected_npn_proto_.Reset(node_isolate, result);
1129
1130   return SSL_TLSEXT_ERR_OK;
1131 }
1132
1133
1134 void TLSCallbacks::GetNegotiatedProto(const FunctionCallbackInfo<Value>& args) {
1135   HandleScope scope(node_isolate);
1136
1137   UNWRAP(TLSCallbacks);
1138
1139   if (wrap->kind_ == kTLSClient) {
1140     if (wrap->selected_npn_proto_.IsEmpty() == false) {
1141       args.GetReturnValue().Set(wrap->selected_npn_proto_);
1142     }
1143     return;
1144   }
1145
1146   const unsigned char* npn_proto;
1147   unsigned int npn_proto_len;
1148
1149   SSL_get0_next_proto_negotiated(wrap->ssl_, &npn_proto, &npn_proto_len);
1150
1151   if (!npn_proto) {
1152     return args.GetReturnValue().Set(false);
1153   }
1154
1155   args.GetReturnValue().Set(
1156       String::New(reinterpret_cast<const char*>(npn_proto), npn_proto_len));
1157 }
1158
1159
1160 void TLSCallbacks::SetNPNProtocols(const FunctionCallbackInfo<Value>& args) {
1161   HandleScope scope(node_isolate);
1162
1163   UNWRAP(TLSCallbacks);
1164
1165   if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
1166     return ThrowTypeError("Must give a Buffer as first argument");
1167
1168   wrap->npn_protos_.Reset(node_isolate, args[0].As<Object>());
1169 }
1170 #endif  // OPENSSL_NPN_NEGOTIATED
1171
1172
1173 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1174 void TLSCallbacks::GetServername(const FunctionCallbackInfo<Value>& args) {
1175   HandleScope scope(node_isolate);
1176
1177   UNWRAP(TLSCallbacks);
1178
1179   const char* servername = SSL_get_servername(wrap->ssl_,
1180                                               TLSEXT_NAMETYPE_host_name);
1181   if (servername != NULL) {
1182     args.GetReturnValue().Set(String::New(servername));
1183   } else {
1184     args.GetReturnValue().Set(false);
1185   }
1186 }
1187
1188
1189 void TLSCallbacks::SetServername(const FunctionCallbackInfo<Value>& args) {
1190   HandleScope scope(node_isolate);
1191
1192   UNWRAP(TLSCallbacks);
1193
1194   if (args.Length() < 1 || !args[0]->IsString())
1195     return ThrowTypeError("First argument should be a string");
1196
1197   if (wrap->started_)
1198     return ThrowError("Already started.");
1199
1200   if (wrap->kind_ != kTLSClient)
1201     return;
1202
1203 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1204   String::Utf8Value servername(args[0].As<String>());
1205   SSL_set_tlsext_host_name(wrap->ssl_, *servername);
1206 #endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1207 }
1208
1209
1210 int TLSCallbacks::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1211   HandleScope scope(node_isolate);
1212
1213   TLSCallbacks* p = static_cast<TLSCallbacks*>(arg);
1214
1215   const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1216
1217   if (servername != NULL) {
1218     // Call the SNI callback and use its return value as context
1219     Local<Object> object = p->object();
1220     Local<Value> ctx;
1221     if (object->Has(sni_context_sym)) {
1222       ctx = object->Get(sni_context_sym);
1223     }
1224
1225     if (ctx.IsEmpty() || ctx->IsUndefined())
1226       return SSL_TLSEXT_ERR_NOACK;
1227
1228     p->sni_context_.Dispose();
1229     p->sni_context_.Reset(node_isolate, ctx);
1230
1231     SecureContext* sc = ObjectWrap::Unwrap<SecureContext>(ctx.As<Object>());
1232     SSL_set_SSL_CTX(s, sc->ctx_);
1233   }
1234
1235   return SSL_TLSEXT_ERR_OK;
1236 }
1237 #endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1238
1239
1240 void TLSCallbacks::Initialize(Handle<Object> target) {
1241   HandleScope scope(node_isolate);
1242
1243   NODE_SET_METHOD(target, "wrap", TLSCallbacks::Wrap);
1244
1245   Local<FunctionTemplate> t = FunctionTemplate::New();
1246   t->InstanceTemplate()->SetInternalFieldCount(1);
1247   t->SetClassName(String::NewSymbol("TLSWrap"));
1248
1249   NODE_SET_PROTOTYPE_METHOD(t, "start", Start);
1250   NODE_SET_PROTOTYPE_METHOD(t, "getPeerCertificate", GetPeerCertificate);
1251   NODE_SET_PROTOTYPE_METHOD(t, "getSession", GetSession);
1252   NODE_SET_PROTOTYPE_METHOD(t, "setSession", SetSession);
1253   NODE_SET_PROTOTYPE_METHOD(t, "loadSession", LoadSession);
1254   NODE_SET_PROTOTYPE_METHOD(t, "endParser", EndParser);
1255   NODE_SET_PROTOTYPE_METHOD(t, "getCurrentCipher", GetCurrentCipher);
1256   NODE_SET_PROTOTYPE_METHOD(t, "verifyError", VerifyError);
1257   NODE_SET_PROTOTYPE_METHOD(t, "setVerifyMode", SetVerifyMode);
1258   NODE_SET_PROTOTYPE_METHOD(t, "isSessionReused", IsSessionReused);
1259   NODE_SET_PROTOTYPE_METHOD(t,
1260                             "enableSessionCallbacks",
1261                             EnableSessionCallbacks);
1262   NODE_SET_PROTOTYPE_METHOD(t,
1263                             "enableHelloParser",
1264                             EnableHelloParser);
1265
1266 #ifdef OPENSSL_NPN_NEGOTIATED
1267   NODE_SET_PROTOTYPE_METHOD(t, "getNegotiatedProtocol", GetNegotiatedProto);
1268   NODE_SET_PROTOTYPE_METHOD(t, "setNPNProtocols", SetNPNProtocols);
1269 #endif  // OPENSSL_NPN_NEGOTIATED
1270
1271 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1272   NODE_SET_PROTOTYPE_METHOD(t, "getServername", GetServername);
1273   NODE_SET_PROTOTYPE_METHOD(t, "setServername", SetServername);
1274 #endif  // SSL_CRT_SET_TLSEXT_SERVERNAME_CB
1275
1276   tlsWrap.Reset(node_isolate, t->GetFunction());
1277
1278   onread_sym = String::New("onread");
1279   onerror_sym = String::New("onerror");
1280   onhandshakestart_sym = String::New("onhandshakestart");
1281   onhandshakedone_sym = String::New("onhandshakedone");
1282   onclienthello_sym = String::New("onclienthello");
1283   onnewsession_sym = String::New("onnewsession");
1284
1285   subject_sym = String::New("subject");
1286   issuer_sym = String::New("issuer");
1287   valid_from_sym = String::New("valid_from");
1288   valid_to_sym = String::New("valid_to");
1289   subjectaltname_sym = String::New("subjectaltname");
1290   modulus_sym = String::New("modulus");
1291   exponent_sym = String::New("exponent");
1292   fingerprint_sym = String::New("fingerprint");
1293   name_sym = String::New("name");
1294   version_sym = String::New("version");
1295   ext_key_usage_sym = String::New("ext_key_usage");
1296   sessionid_sym = String::New("sessionId");
1297   tls_ticket_sym = String::New("tlsTicket");
1298   servername_sym = String::New("servername");
1299   sni_context_sym = String::New("sni_context");
1300 }
1301
1302 }  // namespace node
1303
1304 NODE_MODULE(node_tls_wrap, node::TLSCallbacks::Initialize)