title: OpenSSL Non-Blocking Socket SSL_read() unpredictable
body: <p>I'm trying to make a non-blocking socket w/OpenSSL so I can loop over SSL_read() until there's no more data left, then break the loop. After a lot of work, I finally got the connection working, but now for the first thousand+ iterations SSL_read() will return -1. After, it will give me the actual data on the socket. SSL_read() also is not returning an accurate number of bytes read, it ALWAYS says -1 even when it's reading the correct bytes. I was able to get it working perfectly w/blocking sockets but non blocking seems problematic...</p>
  
  <pre><code>char *sslRead (connection *c)
  {
  const int readSize = 1024;
  char *rc = NULL;
  int r;
  int received = -1, count = 0;
  int TotalReceived = 0, ReallocSize = 0;
  char buffer[1024];
  
  if (c)
  {
      while (1)
      {
  
          received = SSL_read (c-&gt;sslHandle, buffer, readSize);
  
      buffer[received] = '\0';
  
          TotalReceived += received;
          printf("Buffsize - %i - %s \n", received, buffer);
  
  
          if (received &lt;= 0)
          {
  
              // this line added per advice of Eric Tsui but does not
              // change behaviour 
              received = SSL_read (c-&gt;sslHandle, buffer, readSize);
  
  
  
              //printf(" received equal to or less than 0\n")
              switch (SSL_get_error(c-&gt;sslHandle, received))
              {
                  case SSL_ERROR_NONE:
                  {
                          printf("SSL_ERROR_NONE %i\n", count);
                          //if (received != -1)
                          //  goto END;
                          break;
                  }   
                  case SSL_ERROR_ZERO_RETURN: 
                  {
                          printf("SSL_ERROR_ZERO_RETURN %i\n", count);
                          goto END;
                          break;
                  }   
                  case SSL_ERROR_WANT_READ: 
                  {
                          printf("SSL_ERROR_WANT_READ %i\n", count);
  
                          break;
                  }
                  case SSL_ERROR_WANT_WRITE: 
                  {
                          printf("SSL_ERROR_WANT_WRITE %i\n", count);
                          goto END;
                          //break;
                  }
                  default:
                  {
                          printf("error %i\n", received); 
                          break;
                  }
              }     
  
  
              count++;
          }
      }
  }
  END:
  return rc;
  }
  </code></pre>
  
  <p>If you've done this before, I'd really appreciate if you could tell me what's wrong with this code. Thanks.</p>