ssl_ctx.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "ssl_ctx.h"
  2. #include <stdio.h>
  3. #ifdef WITH_OPENSSL
  4. #include "openssl/ssl.h"
  5. #endif
  6. void* g_ssl_ctx = 0;
  7. int ssl_ctx_init(const char* crt_file, const char* key_file, const char* ca_file) {
  8. #ifdef WITH_OPENSSL
  9. if (g_ssl_ctx != NULL) {
  10. return 0;
  11. }
  12. SSL_CTX* ctx = SSL_CTX_new(TLS_method());
  13. if (ctx == NULL) return -10;
  14. if (ca_file && *ca_file) {
  15. if (!SSL_CTX_load_verify_locations(ctx, ca_file, NULL)) {
  16. fprintf(stderr, "ssl ca_file verify failed!\n");
  17. return -20;
  18. }
  19. }
  20. if (crt_file && *crt_file) {
  21. if (!SSL_CTX_use_certificate_file(ctx, crt_file, SSL_FILETYPE_PEM)) {
  22. fprintf(stderr, "ssl crt_file error!\n");
  23. return -20;
  24. }
  25. }
  26. if (key_file && *key_file) {
  27. if (!SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM)) {
  28. fprintf(stderr, "ssl key_file error!\n");
  29. return -30;
  30. }
  31. if (!SSL_CTX_check_private_key(ctx)) {
  32. fprintf(stderr, "ssl key_file check failed!\n");
  33. return -40;
  34. }
  35. }
  36. SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
  37. g_ssl_ctx = ctx;
  38. return 0;
  39. #else
  40. fprintf(stderr, "Please recompile WITH_OPENSSL.\n");
  41. return -1;
  42. #endif
  43. }
  44. int ssl_ctx_destory() {
  45. #ifdef WITH_OPENSSL
  46. if (g_ssl_ctx) {
  47. SSL_CTX_free((SSL_CTX*)g_ssl_ctx);
  48. g_ssl_ctx = NULL;
  49. }
  50. #endif
  51. return 0;
  52. }