使用OpenSSL库的IMAP客户端

时间:2014-08-26 22:28:41

标签: openssl imap

我正在尝试编写一个简单的SSL IMAP客户端。为此我使用的是OpenSSL库和C ++(g ++编译器)。我发现了很多关于IMAP的信息,我可以成功地与IMAP服务器通信。但我注意到,当没有数据要接收时,BIO_read()会永久阻止。我还通过查看this示例(我没有使用证书验证)在非阻塞(?)模式下尝试使用SSL_read()并得到同样的问题。

简化的源代码:

<...>
BIO *bio;
SSL *ssl;
SSL_CTX *ctx;

CRYPTO_malloc_init(); // Initialize malloc, free, etc for OpenSSL's use
SSL_library_init(); // Initialize OpenSSL's SSL libraries
SSL_load_error_strings(); // Load SSL error strings
ERR_load_BIO_strings(); // Load BIO error strings
OpenSSL_add_all_algorithms(); // Load all available encryption algorithms

ctx = SSL_CTX_new(SSLv23_client_method());
bio = BIO_new_ssl_connect(ctx);
BIO_get_ssl(bio, &ssl);
SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);

BIO_set_conn_hostname(bio, "imap.gmail.com:993");
BIO_do_connect(bio);

char tmp[10000];
cout << "Bytes received: " << BIO_read(bio, tmp, 1000) << endl; //Got 68 bytes - full anwer (server welcome string)
cout << "Bytes received: " << BIO_read(bio, tmp, 1000) << endl; //No more data to receive - I expecting 0 (zero), but it blocks forever.
cout << "Bytes received: " << BIO_read(bio, tmp, 1000) << endl;

There is full source code(见第49行)


P上。 S:对不起我的英语不好,我希望大家都明白。

1 个答案:

答案 0 :(得分:0)

尝试使用BIO_pending()来确定是否应该执行另一个BIO_read。

类似的东西:

while (bytes_remaining = BIO_pending(bio))
cout << "Bytes received: " << BIO_read(bio, tmp, bytes_remaining) << endl;

可能会为你工作。