apple安全传输代码错误

时间:2017-02-08 19:42:11

标签: c++ macos ssl secure-transport

我有以下Apple Security API初始化代码:

    OSStatus status = noErr;
    sslContext = SSLCreateContext(kCFAllocatorDefault, kSSLClientSide, kSSLStreamType);
    if (sslContext == nullptr)
    {
        throw std::runtime_error("cannot create ssl context");
    }

    status = SSLSetIOFuncs(sslContext, socketRead, socketWrite);
    if (status != noErr)
    {
        throw std::runtime_error("cannot set ssl io functions");
    }

    status = SSLSetConnection(sslContext, reinterpret_cast<void*>(&handle));
    if (status != noErr)
    {
        throw std::runtime_error("cannot set ssl connections");
    }

    status = SSLSetPeerDomainName(sslContext, address.c_str(), address.length());
    if (status != noErr)
    {
        throw std::runtime_error("cannot set ssl peer domain name");
    }

    status = SSLSetSessionOption(sslContext, kSSLSessionOptionBreakOnServerAuth, true);
    if (status != noErr)
    {
        throw std::runtime_error("cannot set ssl options");
    }

    status = SSLHandshake(sslContext);
    if (status != noErr)
    {
        throw std::runtime_error("cannot perform ssl handshake");
    }

在这一行:

status = SSLHandshake(sslContext);

调用我的SSLWriteFunc回调。它尝试通过SSLWrite发送174个字节(我并不意味着发送它),但无论如何它都会失败。但是在有关SSLHandshake的文档中,它已写入&#34;成功返回后,会话已准备好使用SSLRead( :)和SSLWrite函数进行正常的安全通信(:)。&#34 ;.所以在我的情况下没有从这个方法返回,然后我的SSLWriteFunc突然尝试通过SSLWrite发送数据。我只是不明白自己做错了什么。请大家帮帮我

1 个答案:

答案 0 :(得分:0)

SSLRead()SSLWrite()应该从您的应用代码中调用,而不是从SSLReadFuncSSLWriteFunc回调中调用。

SSLReadFuncSSLWriteFunc回调中,SecureTransport要求您从套接字(使用SSLSetConnection设置)接收/发送数据。因此,在SSLWriteFunc中,您将获得通过套接字发送的加密数据。您对SSLWriteFunc的实现应该类似于:

OSStatus mySSLWriteFunc(SSLConnectionRef connection, const void *data, size_t *dataLength)
{
    int *handle;
    SSLGetConnection(connection, &handle);
    size_t result = write(*handle, data, *dataLength);
    if (result == -1)
    {
        if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
            return errSSLWouldBlock;
        else
            // fill this in
    }
    else
    {
        *dataLength = result;
    }
    return noErr;
}

您希望为此添加额外的错误处理(如果套接字关闭等),但这应该是基本结构。