title: Non-blocking BIO and hang after BIO_do_connect
body: <p>I am writing a small little IRC bot in C using openssl to start a secure socket. It isn't the most beautifully written bot, but its mostly just to see how the openssl API works. Currently I have the following code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;openssl/bio.h&gt;
  #include &lt;openssl/ssl.h&gt;
  #include &lt;openssl/err.h&gt;
  
  int main() {
      SSL_load_error_strings();
      ERR_load_BIO_strings();
      OpenSSL_add_all_algorithms();
  
      BIO *bio;
      SSL_CTX * ctx = SSL_CTX_new(SSLv23_client_method());
      SSL * ssl;
  
      SSL_CTX_load_verify_locations(ctx, NULL, "/etc/ssl/certs/");
      bio = BIO_new_ssl_connect(ctx);
      BIO_get_ssl(bio, &amp; ssl);
      SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
      BIO_set_nbio(bio, 1);
      BIO_set_conn_hostname(bio, "irc.freenode.net:6697");
      BIO_do_connect(bio);
  
      if(SSL_get_verify_result(ssl) != X509_V_OK) {
          printf("error\n");
      }
  
      char irc1[] = "NICK bartender\r\n";
      char irc2[] = "USER bartender * * :serve(&amp;drinks);\r\n";
  
      BIO_write(bio, irc1, strlen(irc1));
      BIO_write(bio, irc2, strlen(irc2));
  
      fd_set read_set;
      int sock = BIO_get_fd(bio, NULL);
  
      while(1) {
          FD_ZERO(&amp;read_set);
          FD_SET(sock, &amp;read_set);
  
          struct timeval timeout = { 0, 0 };
          select(sock+1, &amp;read_set, NULL, NULL, &amp;timeout);
  
          if(FD_ISSET(sock, &amp;read_set)) {
              char buf[21];
              size_t x = BIO_read(bio, buf, 20);
  
              if(x == 0) {
                  continue;
              } else if(x == -1){
                  int code = ERR_get_error();
  
                  if(code == 0) {
                      continue;
                  }
  
                  printf("(%d)%s\n", code, ERR_error_string(code, NULL));
              } else {
                  buf[x] = '\0';
                  printf("%s", buf);
              }
          }
      }
  }
  </code></pre>
  
  <p>Whenever I compile and run this code, it just hangs and prints nothing. However, if I remove line 20 (which currently puts the socket into nonblocking mode) it works fine. Why does putting the socket in non-blocking mode cause this behavior? Thank you and have a great day!</p>