2012/05/04

在 multi-thread 下使用 OpenSSL

OpenSSL 支援 multi-thread 嗎?從官網的FAQ中得知:
Yes (with limitations: an SSL connection may not concurrently be used by multiple threads). On Windows and many Unix systems, OpenSSL automatically uses the multi-threaded versions of the standard libraries. If your platform is not one of these, consult the INSTALL file.

要支援 multi-thread 必須提供兩個 callback function:CRYPTO_set_locking_callback(), CRYPTO_set_id_callback(),在需要 lock 物件時,OpenSSL 就會去 call。
pthread_mutex_t *ssl_mutex = NULL;

static void ssl_locking_cb (int mode, int type, const char* file, int line)
{
  if (mode & CRYPTO_LOCK)
    pthread_mutex_lock(&ssl_mutex[type]);
  else
    pthread_mutex_unlock(&ssl_mutex[type]);
}

static unsigned long ssl_id_cb (void)
{
  return (unsigned long)pthread_self();
}

int ssl_init (void)
{
  int   i;

  /* The number of lock we need is getting from CRYPTO_num_locks() */
  if ((ssl_mutex = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks()))
   == NULL) {
    printf("malloc() failed.\n");
    return -1;
  }

  /* Init. mutex. */
  for (i = 0; i < CRYPTO_num_locks(); i++) {
    pthread_mutex_init(&ssl_mutex[i], NULL);
  }

  /* Set up locking function */
  CRYPTO_set_locking_callback(ssl_locking_cb);
  CRYPTO_set_id_callback(ssl_id_cb);

  /* Init. library ... */
  SSL_library_init();
  ERR_load_crypto_strings();
  SSL_load_error_strings();
  OpenSSL_add_all_algorithms();
}


提升效能?

當初是在寫 server 時想讓 socket accept 後,由不同 thread 來做 SSL handshake 以提升系統的速度,但根據我的測試結果,由於不同 thread 都使用同一個 SSL_CTX 來 handshake,所以彼此間會互相 lock,效能變得跟 single thread一樣。有想過 initial 多組 SSL_CTX,但好像會遇到其他問題,就沒有再深究了。



沒有留言:

張貼留言