Home | History | Annotate | Download | only in base
      1 /*
      2  *  Copyright 2004 The WebRTC Project Authors. All rights reserved.
      3  *
      4  *  Use of this source code is governed by a BSD-style license
      5  *  that can be found in the LICENSE file in the root of the source
      6  *  tree. An additional intellectual property rights grant can be found
      7  *  in the file PATENTS.  All contributing project authors may
      8  *  be found in the AUTHORS file in the root of the source tree.
      9  */
     10 
     11 #include "webrtc/base/win32.h"
     12 #define SECURITY_WIN32
     13 #include <security.h>
     14 #include <schannel.h>
     15 
     16 #include <iomanip>
     17 #include <vector>
     18 
     19 #include "webrtc/base/common.h"
     20 #include "webrtc/base/logging.h"
     21 #include "webrtc/base/schanneladapter.h"
     22 #include "webrtc/base/sec_buffer.h"
     23 #include "webrtc/base/thread.h"
     24 
     25 namespace rtc {
     26 
     27 /////////////////////////////////////////////////////////////////////////////
     28 // SChannelAdapter
     29 /////////////////////////////////////////////////////////////////////////////
     30 
     31 extern const ConstantLabel SECURITY_ERRORS[];
     32 
     33 const ConstantLabel SCHANNEL_BUFFER_TYPES[] = {
     34   KLABEL(SECBUFFER_EMPTY),              //  0
     35   KLABEL(SECBUFFER_DATA),               //  1
     36   KLABEL(SECBUFFER_TOKEN),              //  2
     37   KLABEL(SECBUFFER_PKG_PARAMS),         //  3
     38   KLABEL(SECBUFFER_MISSING),            //  4
     39   KLABEL(SECBUFFER_EXTRA),              //  5
     40   KLABEL(SECBUFFER_STREAM_TRAILER),     //  6
     41   KLABEL(SECBUFFER_STREAM_HEADER),      //  7
     42   KLABEL(SECBUFFER_MECHLIST),           // 11
     43   KLABEL(SECBUFFER_MECHLIST_SIGNATURE), // 12
     44   KLABEL(SECBUFFER_TARGET),             // 13
     45   KLABEL(SECBUFFER_CHANNEL_BINDINGS),   // 14
     46   LASTLABEL
     47 };
     48 
     49 void DescribeBuffer(LoggingSeverity severity, const char* prefix,
     50                     const SecBuffer& sb) {
     51   LOG_V(severity)
     52     << prefix
     53     << "(" << sb.cbBuffer
     54     << ", " << FindLabel(sb.BufferType & ~SECBUFFER_ATTRMASK,
     55                           SCHANNEL_BUFFER_TYPES)
     56     << ", " << sb.pvBuffer << ")";
     57 }
     58 
     59 void DescribeBuffers(LoggingSeverity severity, const char* prefix,
     60                      const SecBufferDesc* sbd) {
     61   if (!LOG_CHECK_LEVEL_V(severity))
     62     return;
     63   LOG_V(severity) << prefix << "(";
     64   for (size_t i=0; i<sbd->cBuffers; ++i) {
     65     DescribeBuffer(severity, "  ", sbd->pBuffers[i]);
     66   }
     67   LOG_V(severity) << ")";
     68 }
     69 
     70 const ULONG SSL_FLAGS_DEFAULT = ISC_REQ_ALLOCATE_MEMORY
     71                               | ISC_REQ_CONFIDENTIALITY
     72                               | ISC_REQ_EXTENDED_ERROR
     73                               | ISC_REQ_INTEGRITY
     74                               | ISC_REQ_REPLAY_DETECT
     75                               | ISC_REQ_SEQUENCE_DETECT
     76                               | ISC_REQ_STREAM;
     77                               //| ISC_REQ_USE_SUPPLIED_CREDS;
     78 
     79 typedef std::vector<char> SChannelBuffer;
     80 
     81 struct SChannelAdapter::SSLImpl {
     82   CredHandle cred;
     83   CtxtHandle ctx;
     84   bool cred_init, ctx_init;
     85   SChannelBuffer inbuf, outbuf, readable;
     86   SecPkgContext_StreamSizes sizes;
     87 
     88   SSLImpl() : cred_init(false), ctx_init(false) { }
     89 };
     90 
     91 SChannelAdapter::SChannelAdapter(AsyncSocket* socket)
     92   : SSLAdapter(socket), state_(SSL_NONE),
     93     restartable_(false), signal_close_(false), message_pending_(false),
     94     impl_(new SSLImpl) {
     95 }
     96 
     97 SChannelAdapter::~SChannelAdapter() {
     98   Cleanup();
     99 }
    100 
    101 int
    102 SChannelAdapter::StartSSL(const char* hostname, bool restartable) {
    103   if (state_ != SSL_NONE)
    104     return ERROR_ALREADY_INITIALIZED;
    105 
    106   ssl_host_name_ = hostname;
    107   restartable_ = restartable;
    108 
    109   if (socket_->GetState() != Socket::CS_CONNECTED) {
    110     state_ = SSL_WAIT;
    111     return 0;
    112   }
    113 
    114   state_ = SSL_CONNECTING;
    115   if (int err = BeginSSL()) {
    116     Error("BeginSSL", err, false);
    117     return err;
    118   }
    119 
    120   return 0;
    121 }
    122 
    123 int
    124 SChannelAdapter::BeginSSL() {
    125   LOG(LS_VERBOSE) << "BeginSSL: " << ssl_host_name_;
    126   ASSERT(state_ == SSL_CONNECTING);
    127 
    128   SECURITY_STATUS ret;
    129 
    130   SCHANNEL_CRED sc_cred = { 0 };
    131   sc_cred.dwVersion = SCHANNEL_CRED_VERSION;
    132   //sc_cred.dwMinimumCipherStrength = 128; // Note: use system default
    133   sc_cred.dwFlags = SCH_CRED_NO_DEFAULT_CREDS | SCH_CRED_AUTO_CRED_VALIDATION;
    134 
    135   ret = AcquireCredentialsHandle(NULL, const_cast<LPTSTR>(UNISP_NAME),
    136                                  SECPKG_CRED_OUTBOUND, NULL, &sc_cred, NULL,
    137                                  NULL, &impl_->cred, NULL);
    138   if (ret != SEC_E_OK) {
    139     LOG(LS_ERROR) << "AcquireCredentialsHandle error: "
    140                   << ErrorName(ret, SECURITY_ERRORS);
    141     return ret;
    142   }
    143   impl_->cred_init = true;
    144 
    145   if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
    146     SecPkgCred_CipherStrengths cipher_strengths = { 0 };
    147     ret = QueryCredentialsAttributes(&impl_->cred,
    148                                      SECPKG_ATTR_CIPHER_STRENGTHS,
    149                                      &cipher_strengths);
    150     if (SUCCEEDED(ret)) {
    151       LOG(LS_VERBOSE) << "SChannel cipher strength: "
    152                   << cipher_strengths.dwMinimumCipherStrength << " - "
    153                   << cipher_strengths.dwMaximumCipherStrength;
    154     }
    155 
    156     SecPkgCred_SupportedAlgs supported_algs = { 0 };
    157     ret = QueryCredentialsAttributes(&impl_->cred,
    158                                      SECPKG_ATTR_SUPPORTED_ALGS,
    159                                      &supported_algs);
    160     if (SUCCEEDED(ret)) {
    161       LOG(LS_VERBOSE) << "SChannel supported algorithms:";
    162       for (DWORD i=0; i<supported_algs.cSupportedAlgs; ++i) {
    163         ALG_ID alg_id = supported_algs.palgSupportedAlgs[i];
    164         PCCRYPT_OID_INFO oinfo = CryptFindOIDInfo(CRYPT_OID_INFO_ALGID_KEY,
    165                                                   &alg_id, 0);
    166         LPCWSTR alg_name = (NULL != oinfo) ? oinfo->pwszName : L"Unknown";
    167         LOG(LS_VERBOSE) << "  " << ToUtf8(alg_name) << " (" << alg_id << ")";
    168       }
    169       CSecBufferBase::FreeSSPI(supported_algs.palgSupportedAlgs);
    170     }
    171   }
    172 
    173   ULONG flags = SSL_FLAGS_DEFAULT, ret_flags = 0;
    174   if (ignore_bad_cert())
    175     flags |= ISC_REQ_MANUAL_CRED_VALIDATION;
    176 
    177   CSecBufferBundle<2, CSecBufferBase::FreeSSPI> sb_out;
    178   ret = InitializeSecurityContextA(&impl_->cred, NULL,
    179                                    const_cast<char*>(ssl_host_name_.c_str()),
    180                                    flags, 0, 0, NULL, 0,
    181                                    &impl_->ctx, sb_out.desc(),
    182                                    &ret_flags, NULL);
    183   if (SUCCEEDED(ret))
    184     impl_->ctx_init = true;
    185   return ProcessContext(ret, NULL, sb_out.desc());
    186 }
    187 
    188 int
    189 SChannelAdapter::ContinueSSL() {
    190   LOG(LS_VERBOSE) << "ContinueSSL";
    191   ASSERT(state_ == SSL_CONNECTING);
    192 
    193   SECURITY_STATUS ret;
    194 
    195   CSecBufferBundle<2> sb_in;
    196   sb_in[0].BufferType = SECBUFFER_TOKEN;
    197   sb_in[0].cbBuffer = static_cast<unsigned long>(impl_->inbuf.size());
    198   sb_in[0].pvBuffer = &impl_->inbuf[0];
    199   //DescribeBuffers(LS_VERBOSE, "Input Buffer ", sb_in.desc());
    200 
    201   ULONG flags = SSL_FLAGS_DEFAULT, ret_flags = 0;
    202   if (ignore_bad_cert())
    203     flags |= ISC_REQ_MANUAL_CRED_VALIDATION;
    204 
    205   CSecBufferBundle<2, CSecBufferBase::FreeSSPI> sb_out;
    206   ret = InitializeSecurityContextA(&impl_->cred, &impl_->ctx,
    207                                    const_cast<char*>(ssl_host_name_.c_str()),
    208                                    flags, 0, 0, sb_in.desc(), 0,
    209                                    NULL, sb_out.desc(),
    210                                    &ret_flags, NULL);
    211   return ProcessContext(ret, sb_in.desc(), sb_out.desc());
    212 }
    213 
    214 int
    215 SChannelAdapter::ProcessContext(long int status, _SecBufferDesc* sbd_in,
    216                                 _SecBufferDesc* sbd_out) {
    217   if (status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED &&
    218       status != SEC_E_INCOMPLETE_MESSAGE) {
    219     LOG(LS_ERROR)
    220       << "InitializeSecurityContext error: "
    221       << ErrorName(status, SECURITY_ERRORS);
    222   }
    223   //if (sbd_in)
    224   //  DescribeBuffers(LS_VERBOSE, "Input Buffer ", sbd_in);
    225   //if (sbd_out)
    226   //  DescribeBuffers(LS_VERBOSE, "Output Buffer ", sbd_out);
    227 
    228   if (status == SEC_E_INCOMPLETE_MESSAGE) {
    229     // Wait for more input from server.
    230     return Flush();
    231   }
    232 
    233   if (FAILED(status)) {
    234     // We can't continue.  Common errors:
    235     // SEC_E_CERT_EXPIRED - Typically, this means the computer clock is wrong.
    236     return status;
    237   }
    238 
    239   // Note: we check both input and output buffers for SECBUFFER_EXTRA.
    240   // Experience shows it appearing in the input, but the documentation claims
    241   // it should appear in the output.
    242   size_t extra = 0;
    243   if (sbd_in) {
    244     for (size_t i=0; i<sbd_in->cBuffers; ++i) {
    245       SecBuffer& buffer = sbd_in->pBuffers[i];
    246       if (buffer.BufferType == SECBUFFER_EXTRA) {
    247         extra += buffer.cbBuffer;
    248       }
    249     }
    250   }
    251   if (sbd_out) {
    252     for (size_t i=0; i<sbd_out->cBuffers; ++i) {
    253       SecBuffer& buffer = sbd_out->pBuffers[i];
    254       if (buffer.BufferType == SECBUFFER_EXTRA) {
    255         extra += buffer.cbBuffer;
    256       } else if (buffer.BufferType == SECBUFFER_TOKEN) {
    257         impl_->outbuf.insert(impl_->outbuf.end(),
    258           reinterpret_cast<char*>(buffer.pvBuffer),
    259           reinterpret_cast<char*>(buffer.pvBuffer) + buffer.cbBuffer);
    260       }
    261     }
    262   }
    263 
    264   if (extra) {
    265     ASSERT(extra <= impl_->inbuf.size());
    266     size_t consumed = impl_->inbuf.size() - extra;
    267     memmove(&impl_->inbuf[0], &impl_->inbuf[consumed], extra);
    268     impl_->inbuf.resize(extra);
    269   } else {
    270     impl_->inbuf.clear();
    271   }
    272 
    273   if (SEC_I_CONTINUE_NEEDED == status) {
    274     // Send data to server and wait for response.
    275     // Note: ContinueSSL will result in a Flush, anyway.
    276     return impl_->inbuf.empty() ? Flush() : ContinueSSL();
    277   }
    278 
    279   if (SEC_E_OK == status) {
    280     LOG(LS_VERBOSE) << "QueryContextAttributes";
    281     status = QueryContextAttributes(&impl_->ctx, SECPKG_ATTR_STREAM_SIZES,
    282                                     &impl_->sizes);
    283     if (FAILED(status)) {
    284       LOG(LS_ERROR) << "QueryContextAttributes error: "
    285                     << ErrorName(status, SECURITY_ERRORS);
    286       return status;
    287     }
    288 
    289     state_ = SSL_CONNECTED;
    290 
    291     if (int err = DecryptData()) {
    292       return err;
    293     } else if (int err = Flush()) {
    294       return err;
    295     } else {
    296       // If we decrypted any data, queue up a notification here
    297       PostEvent();
    298       // Signal our connectedness
    299       AsyncSocketAdapter::OnConnectEvent(this);
    300     }
    301     return 0;
    302   }
    303 
    304   if (SEC_I_INCOMPLETE_CREDENTIALS == status) {
    305     // We don't support client authentication in schannel.
    306     return status;
    307   }
    308 
    309   // We don't expect any other codes
    310   ASSERT(false);
    311   return status;
    312 }
    313 
    314 int
    315 SChannelAdapter::DecryptData() {
    316   SChannelBuffer& inbuf = impl_->inbuf;
    317   SChannelBuffer& readable = impl_->readable;
    318 
    319   while (!inbuf.empty()) {
    320     CSecBufferBundle<4> in_buf;
    321     in_buf[0].BufferType = SECBUFFER_DATA;
    322     in_buf[0].cbBuffer = static_cast<unsigned long>(inbuf.size());
    323     in_buf[0].pvBuffer = &inbuf[0];
    324 
    325     //DescribeBuffers(LS_VERBOSE, "Decrypt In ", in_buf.desc());
    326     SECURITY_STATUS status = DecryptMessage(&impl_->ctx, in_buf.desc(), 0, 0);
    327     //DescribeBuffers(LS_VERBOSE, "Decrypt Out ", in_buf.desc());
    328 
    329     // Note: We are explicitly treating SEC_E_OK, SEC_I_CONTEXT_EXPIRED, and
    330     // any other successful results as continue.
    331     if (SUCCEEDED(status)) {
    332       size_t data_len = 0, extra_len = 0;
    333       for (size_t i=0; i<in_buf.desc()->cBuffers; ++i) {
    334         if (in_buf[i].BufferType == SECBUFFER_DATA) {
    335           data_len += in_buf[i].cbBuffer;
    336           readable.insert(readable.end(),
    337             reinterpret_cast<char*>(in_buf[i].pvBuffer),
    338             reinterpret_cast<char*>(in_buf[i].pvBuffer) + in_buf[i].cbBuffer);
    339         } else if (in_buf[i].BufferType == SECBUFFER_EXTRA) {
    340           extra_len += in_buf[i].cbBuffer;
    341         }
    342       }
    343       // There is a bug on Win2K where SEC_I_CONTEXT_EXPIRED is misclassified.
    344       if ((data_len == 0) && (inbuf[0] == 0x15)) {
    345         status = SEC_I_CONTEXT_EXPIRED;
    346       }
    347       if (extra_len) {
    348         size_t consumed = inbuf.size() - extra_len;
    349         memmove(&inbuf[0], &inbuf[consumed], extra_len);
    350         inbuf.resize(extra_len);
    351       } else {
    352         inbuf.clear();
    353       }
    354       // TODO: Handle SEC_I_CONTEXT_EXPIRED to do clean shutdown
    355       if (status != SEC_E_OK) {
    356         LOG(LS_INFO) << "DecryptMessage returned continuation code: "
    357                       << ErrorName(status, SECURITY_ERRORS);
    358       }
    359       continue;
    360     }
    361 
    362     if (status == SEC_E_INCOMPLETE_MESSAGE) {
    363       break;
    364     } else {
    365       return status;
    366     }
    367   }
    368 
    369   return 0;
    370 }
    371 
    372 void
    373 SChannelAdapter::Cleanup() {
    374   if (impl_->ctx_init)
    375     DeleteSecurityContext(&impl_->ctx);
    376   if (impl_->cred_init)
    377     FreeCredentialsHandle(&impl_->cred);
    378   delete impl_;
    379 }
    380 
    381 void
    382 SChannelAdapter::PostEvent() {
    383   // Check if there's anything notable to signal
    384   if (impl_->readable.empty() && !signal_close_)
    385     return;
    386 
    387   // Only one post in the queue at a time
    388   if (message_pending_)
    389     return;
    390 
    391   if (Thread* thread = Thread::Current()) {
    392     message_pending_ = true;
    393     thread->Post(this);
    394   } else {
    395     LOG(LS_ERROR) << "No thread context available for SChannelAdapter";
    396     ASSERT(false);
    397   }
    398 }
    399 
    400 void
    401 SChannelAdapter::Error(const char* context, int err, bool signal) {
    402   LOG(LS_WARNING) << "SChannelAdapter::Error("
    403                   << context << ", "
    404                   << ErrorName(err, SECURITY_ERRORS) << ")";
    405   state_ = SSL_ERROR;
    406   SetError(err);
    407   if (signal)
    408     AsyncSocketAdapter::OnCloseEvent(this, err);
    409 }
    410 
    411 int
    412 SChannelAdapter::Read() {
    413   char buffer[4096];
    414   SChannelBuffer& inbuf = impl_->inbuf;
    415   while (true) {
    416     int ret = AsyncSocketAdapter::Recv(buffer, sizeof(buffer));
    417     if (ret > 0) {
    418       inbuf.insert(inbuf.end(), buffer, buffer + ret);
    419     } else if (GetError() == EWOULDBLOCK) {
    420       return 0;  // Blocking
    421     } else {
    422       return GetError();
    423     }
    424   }
    425 }
    426 
    427 int
    428 SChannelAdapter::Flush() {
    429   int result = 0;
    430   size_t pos = 0;
    431   SChannelBuffer& outbuf = impl_->outbuf;
    432   while (pos < outbuf.size()) {
    433     int sent = AsyncSocketAdapter::Send(&outbuf[pos], outbuf.size() - pos);
    434     if (sent > 0) {
    435       pos += sent;
    436     } else if (GetError() == EWOULDBLOCK) {
    437       break;  // Blocking
    438     } else {
    439       result = GetError();
    440       break;
    441     }
    442   }
    443   if (int remainder = static_cast<int>(outbuf.size() - pos)) {
    444     memmove(&outbuf[0], &outbuf[pos], remainder);
    445     outbuf.resize(remainder);
    446   } else {
    447     outbuf.clear();
    448   }
    449   return result;
    450 }
    451 
    452 //
    453 // AsyncSocket Implementation
    454 //
    455 
    456 int
    457 SChannelAdapter::Send(const void* pv, size_t cb) {
    458   switch (state_) {
    459   case SSL_NONE:
    460     return AsyncSocketAdapter::Send(pv, cb);
    461 
    462   case SSL_WAIT:
    463   case SSL_CONNECTING:
    464     SetError(EWOULDBLOCK);
    465     return SOCKET_ERROR;
    466 
    467   case SSL_CONNECTED:
    468     break;
    469 
    470   case SSL_ERROR:
    471   default:
    472     return SOCKET_ERROR;
    473   }
    474 
    475   size_t written = 0;
    476   SChannelBuffer& outbuf = impl_->outbuf;
    477   while (written < cb) {
    478     const size_t encrypt_len = std::min<size_t>(cb - written,
    479                                                 impl_->sizes.cbMaximumMessage);
    480 
    481     CSecBufferBundle<4> out_buf;
    482     out_buf[0].BufferType = SECBUFFER_STREAM_HEADER;
    483     out_buf[0].cbBuffer = impl_->sizes.cbHeader;
    484     out_buf[1].BufferType = SECBUFFER_DATA;
    485     out_buf[1].cbBuffer = static_cast<unsigned long>(encrypt_len);
    486     out_buf[2].BufferType = SECBUFFER_STREAM_TRAILER;
    487     out_buf[2].cbBuffer = impl_->sizes.cbTrailer;
    488 
    489     size_t packet_len = out_buf[0].cbBuffer
    490                       + out_buf[1].cbBuffer
    491                       + out_buf[2].cbBuffer;
    492 
    493     SChannelBuffer message;
    494     message.resize(packet_len);
    495     out_buf[0].pvBuffer = &message[0];
    496     out_buf[1].pvBuffer = &message[out_buf[0].cbBuffer];
    497     out_buf[2].pvBuffer = &message[out_buf[0].cbBuffer + out_buf[1].cbBuffer];
    498 
    499     memcpy(out_buf[1].pvBuffer,
    500            static_cast<const char*>(pv) + written,
    501            encrypt_len);
    502 
    503     //DescribeBuffers(LS_VERBOSE, "Encrypt In ", out_buf.desc());
    504     SECURITY_STATUS res = EncryptMessage(&impl_->ctx, 0, out_buf.desc(), 0);
    505     //DescribeBuffers(LS_VERBOSE, "Encrypt Out ", out_buf.desc());
    506 
    507     if (FAILED(res)) {
    508       Error("EncryptMessage", res, false);
    509       return SOCKET_ERROR;
    510     }
    511 
    512     // We assume that the header and data segments do not change length,
    513     // or else encrypting the concatenated packet in-place is wrong.
    514     ASSERT(out_buf[0].cbBuffer == impl_->sizes.cbHeader);
    515     ASSERT(out_buf[1].cbBuffer == static_cast<unsigned long>(encrypt_len));
    516 
    517     // However, the length of the trailer may change due to padding.
    518     ASSERT(out_buf[2].cbBuffer <= impl_->sizes.cbTrailer);
    519 
    520     packet_len = out_buf[0].cbBuffer
    521                + out_buf[1].cbBuffer
    522                + out_buf[2].cbBuffer;
    523 
    524     written += encrypt_len;
    525     outbuf.insert(outbuf.end(), &message[0], &message[packet_len-1]+1);
    526   }
    527 
    528   if (int err = Flush()) {
    529     state_ = SSL_ERROR;
    530     SetError(err);
    531     return SOCKET_ERROR;
    532   }
    533 
    534   return static_cast<int>(written);
    535 }
    536 
    537 int
    538 SChannelAdapter::Recv(void* pv, size_t cb) {
    539   switch (state_) {
    540   case SSL_NONE:
    541     return AsyncSocketAdapter::Recv(pv, cb);
    542 
    543   case SSL_WAIT:
    544   case SSL_CONNECTING:
    545     SetError(EWOULDBLOCK);
    546     return SOCKET_ERROR;
    547 
    548   case SSL_CONNECTED:
    549     break;
    550 
    551   case SSL_ERROR:
    552   default:
    553     return SOCKET_ERROR;
    554   }
    555 
    556   SChannelBuffer& readable = impl_->readable;
    557   if (readable.empty()) {
    558     SetError(EWOULDBLOCK);
    559     return SOCKET_ERROR;
    560   }
    561   size_t read = _min(cb, readable.size());
    562   memcpy(pv, &readable[0], read);
    563   if (size_t remaining = readable.size() - read) {
    564     memmove(&readable[0], &readable[read], remaining);
    565     readable.resize(remaining);
    566   } else {
    567     readable.clear();
    568   }
    569 
    570   PostEvent();
    571   return static_cast<int>(read);
    572 }
    573 
    574 int
    575 SChannelAdapter::Close() {
    576   if (!impl_->readable.empty()) {
    577     LOG(WARNING) << "SChannelAdapter::Close with readable data";
    578     // Note: this isn't strictly an error, but we're using it temporarily to
    579     // track bugs.
    580     //ASSERT(false);
    581   }
    582   if (state_ == SSL_CONNECTED) {
    583     DWORD token = SCHANNEL_SHUTDOWN;
    584     CSecBufferBundle<1> sb_in;
    585     sb_in[0].BufferType = SECBUFFER_TOKEN;
    586     sb_in[0].cbBuffer = sizeof(token);
    587     sb_in[0].pvBuffer = &token;
    588     ApplyControlToken(&impl_->ctx, sb_in.desc());
    589     // TODO: In theory, to do a nice shutdown, we need to begin shutdown
    590     // negotiation with more calls to InitializeSecurityContext.  Since the
    591     // socket api doesn't support nice shutdown at this point, we don't bother.
    592   }
    593   Cleanup();
    594   impl_ = new SSLImpl;
    595   state_ = restartable_ ? SSL_WAIT : SSL_NONE;
    596   signal_close_ = false;
    597   message_pending_ = false;
    598   return AsyncSocketAdapter::Close();
    599 }
    600 
    601 Socket::ConnState
    602 SChannelAdapter::GetState() const {
    603   if (signal_close_)
    604     return CS_CONNECTED;
    605   ConnState state = socket_->GetState();
    606   if ((state == CS_CONNECTED)
    607       && ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING)))
    608     state = CS_CONNECTING;
    609   return state;
    610 }
    611 
    612 void
    613 SChannelAdapter::OnConnectEvent(AsyncSocket* socket) {
    614   LOG(LS_VERBOSE) << "SChannelAdapter::OnConnectEvent";
    615   if (state_ != SSL_WAIT) {
    616     ASSERT(state_ == SSL_NONE);
    617     AsyncSocketAdapter::OnConnectEvent(socket);
    618     return;
    619   }
    620 
    621   state_ = SSL_CONNECTING;
    622   if (int err = BeginSSL()) {
    623     Error("BeginSSL", err);
    624   }
    625 }
    626 
    627 void
    628 SChannelAdapter::OnReadEvent(AsyncSocket* socket) {
    629   if (state_ == SSL_NONE) {
    630     AsyncSocketAdapter::OnReadEvent(socket);
    631     return;
    632   }
    633 
    634   if (int err = Read()) {
    635     Error("Read", err);
    636     return;
    637   }
    638 
    639   if (impl_->inbuf.empty())
    640     return;
    641 
    642   if (state_ == SSL_CONNECTED) {
    643     if (int err = DecryptData()) {
    644       Error("DecryptData", err);
    645     } else if (!impl_->readable.empty()) {
    646       AsyncSocketAdapter::OnReadEvent(this);
    647     }
    648   } else if (state_ == SSL_CONNECTING) {
    649     if (int err = ContinueSSL()) {
    650       Error("ContinueSSL", err);
    651     }
    652   }
    653 }
    654 
    655 void
    656 SChannelAdapter::OnWriteEvent(AsyncSocket* socket) {
    657   if (state_ == SSL_NONE) {
    658     AsyncSocketAdapter::OnWriteEvent(socket);
    659     return;
    660   }
    661 
    662   if (int err = Flush()) {
    663     Error("Flush", err);
    664     return;
    665   }
    666 
    667   // See if we have more data to write
    668   if (!impl_->outbuf.empty())
    669     return;
    670 
    671   // Buffer is empty, submit notification
    672   if (state_ == SSL_CONNECTED) {
    673     AsyncSocketAdapter::OnWriteEvent(socket);
    674   }
    675 }
    676 
    677 void
    678 SChannelAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
    679   if ((state_ == SSL_NONE) || impl_->readable.empty()) {
    680     AsyncSocketAdapter::OnCloseEvent(socket, err);
    681     return;
    682   }
    683 
    684   // If readable is non-empty, then we have a pending Message
    685   // that will allow us to signal close (eventually).
    686   signal_close_ = true;
    687 }
    688 
    689 void
    690 SChannelAdapter::OnMessage(Message* pmsg) {
    691   if (!message_pending_)
    692     return;  // This occurs when socket is closed
    693 
    694   message_pending_ = false;
    695   if (!impl_->readable.empty()) {
    696     AsyncSocketAdapter::OnReadEvent(this);
    697   } else if (signal_close_) {
    698     signal_close_ = false;
    699     AsyncSocketAdapter::OnCloseEvent(this, 0); // TODO: cache this error?
    700   }
    701 }
    702 
    703 } // namespace rtc
    704