adds openssl callbacks to use https protocol in multithread
[apps/native/tizen-things-daemon.git] / daemon / src / ttd-http.c
index ed3f78d..fabbf86 100644 (file)
  */
 
 #include <curl/curl.h>
+#include <openssl/crypto.h>
 #include <glib.h>
 #include "ttd-log.h"
 
 #define CERT_FILE_PATH "/opt/share/cert-svc/ca-certificate.crt"
 
+static GMutex *mutex_a = NULL;
+static int http_initialized = 0;
+
+static void __locking_function(int mode, int n, const char *file, int line)
+{
+       if(mode & CRYPTO_LOCK)
+               g_mutex_lock(&mutex_a[n]);
+       else
+               g_mutex_unlock(&mutex_a[n]);
+}
+
+static unsigned long __id_function(void)
+{
+       return ((unsigned long)g_thread_self());
+}
+
+int __ssl_thread_mutex_setup(void)
+{
+       int i;
+
+       mutex_a = g_malloc(CRYPTO_num_locks() * sizeof(GMutex));
+       if(!mutex_a)
+               return -1;
+
+       for(i = 0; i < CRYPTO_num_locks(); i++)
+               g_mutex_init(&mutex_a[i]);
+
+       CRYPTO_set_id_callback(__id_function);
+       CRYPTO_set_locking_callback(__locking_function);
+
+       return 0;
+}
+
+static int __ssl_thread_mutex_cleanup(void)
+{
+       int i;
+
+       if(!mutex_a)
+               return -1;
+
+       CRYPTO_set_id_callback(NULL);
+       CRYPTO_set_locking_callback(NULL);
+
+       for(i = 0; i < CRYPTO_num_locks(); i++)
+               g_mutex_clear(&mutex_a[i]);
+
+       g_free(mutex_a);
+       mutex_a = NULL;
+
+       return 0;
+}
+
+
 int ttd_http_init(void)
 {
+       int ret = 0;
        curl_global_init(CURL_GLOBAL_DEFAULT);
+       ret = __ssl_thread_mutex_setup();
+       if (ret) {
+               _E("failed to setup ssl thread mutex");
+               return -1;
+       }
+
+       http_initialized = 1;
+
        return 0;
 }
 
 int ttd_http_fini(void)
 {
+       __ssl_thread_mutex_cleanup();
        curl_global_cleanup();
+       http_initialized = 0;
+
        return 0;
 }
 
@@ -62,6 +128,7 @@ int ttd_http_get_cloud_cmd(const char *url, char **cmd_json)
        CURL *curl = NULL;
        CURLcode res = CURLE_OK;
 
+       retvm_if(!http_initialized, -1, "http is not initialized yet");
        retvm_if(!url, -1, "url is null");
        retvm_if(!cmd_json, -1, "cmd_json is null");
 
@@ -94,6 +161,7 @@ int ttd_http_post_cmd_result(const char *url, const char *result_json)
        CURLcode res = CURLE_OK;
        struct curl_slist *headers = NULL;
 
+       retvm_if(!http_initialized, -1, "http is not initialized yet");
        retvm_if(!url, -1, "url is null");
        retvm_if(!result_json, -1, "result_json is null");