What is the proper way to shut down a successful OpenSSL connection?

Viewed 69

In C code (running in Ubuntu 20 Linux) I have sent a test email to a gmail address. The email is sent and arrives ok at the recipient. Now I want to shut down the connection properly. My shutdown code is as follows:

...
if (ctx!=NULL)
   SSL_CTX_free(ctx);
printf("SSL closed!\n");
if (ssl!=NULL)
   {
   i=0;
   while (i<5)
      {
      iResult = SSL_shutdown(ssl);
      if (iResult == 0)
         {
         printf("SSL shutdown in progress...\n");
         iResult=SSL_get_error(ssl,iResult);
         printf("iResult: %d\n",iResult);
         switch (iResult)
            {
            case SSL_ERROR_NONE:  //0
                 break;
            case SSL_ERROR_SSL:   //1
                 break;
            case SSL_ERROR_WANT_READ:   //2
                 iResult = SSL_read(ssl, recvbuf, BUFLEN - 1);
                 if (iResult>0)
                    printf("Byte(s) received: %d\n", iResult);
                 break;
            case SSL_ERROR_WANT_WRITE:   //3
                 break;
            case SSL_ERROR_WANT_X509_LOOKUP:  //4
                 break;
            case SSL_ERROR_SYSCALL:   //5
                 break;
            case SSL_ERROR_ZERO_RETURN:  //6
                 break;
            case SSL_ERROR_WANT_CONNECT:  //7
                 break;
            case SSL_ERROR_WANT_ACCEPT:  //8
                 break;
            case SSL_ERROR_WANT_ASYNC:  //9
                 break;
            case SSL_ERROR_WANT_ASYNC_JOB:  //10
                 break;
            case SSL_ERROR_WANT_CLIENT_HELLO_CB:  //11
                 break;
            default:
                 break;
            }
         }
      else if (iResult == 1)
         {
         printf("SSL shutdown succeeded\n");
         break;
         }
      else if (iResult == -1)
         {
         printf("SSL shutdown failed! %d\n",SSL_get_error(ssl,iResult));
         sleep(1);
         iResult = SSL_shutdown(ssl);
         break;
         }
      sleep(1);
      i++;
      }
   SSL_free(ssl);
   }

//
if (sock>0)
   {
   iResult = shutdown(sock, SHUT_RDWR);
   if (iResult == -1)
      {
      printf("shutdown failed: %d\n", errno);
      }
   else
      printf("shutdown succeeded\n");
   iResult = close(sock);
   if (iResult < 0)
      {
      printf("Error occurred while closing socket\n");
      }
   }

I am getting the following output:

221 2.0.0.0 closing connection..
SSL closed!
SSL shutdown in progress...
iResult: 5
SSL shutdown failed! 5
shutdown failed: 107

Error 5 is SSL_ERROR_SYSCALL

I've tried a number of ways but never seem to get past the error at shutdown. What is the proper way to shut down a successful session?

0 Answers
Related