(no commit message)
[prss.git] / src / http.c
index e663b86..4438423 100644 (file)
@@ -20,6 +20,7 @@
 #include <libintl.h>
 #define _(str) gettext(str)
 
+#include <pthread.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -27,6 +28,7 @@
 #include <curl/curl.h>
 
 #include "http.h"
+#include "log.h"
 
 struct ucontent {
        char *data;
@@ -34,6 +36,7 @@ struct ucontent {
 };
 
 static CURL *curl;
+static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
 
 static size_t cbk_curl(void *buffer, size_t size, size_t nmemb, void *userp)
 {
@@ -54,7 +57,8 @@ static size_t cbk_curl(void *buffer, size_t size, size_t nmemb, void *userp)
 
 void http_init()
 {
-       curl = curl_easy_init();
+       if (!curl)
+               curl = curl_easy_init();
 }
 
 void http_cleanup()
@@ -65,26 +69,33 @@ void http_cleanup()
 char *http_get(const char *url, const char *content)
 {
        struct ucontent chunk;
+       int result;
 
        chunk.data = malloc(1);
        chunk.len = 0;
 
+       pthread_mutex_lock(&lock);
+
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
        if (content) {
                curl_easy_setopt(curl, CURLOPT_POSTFIELDS, content);
                curl_easy_setopt(curl,
-                                CURLOPT_POSTFIELDSIZE, 
+                                CURLOPT_POSTFIELDSIZE,
                                 (long)strlen(content));
        }
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cbk_curl);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
 
-       if (curl_easy_perform(curl) == CURLE_OK)
+       result = curl_easy_perform(curl);
+
+       pthread_mutex_unlock(&lock);
+
+       if (result == CURLE_OK)
                return chunk.data;
 
        free(chunk.data);
-       fprintf(stderr, _("HTTP request fail url=%s"), url);
+       log_err(_("HTTP request fail url=%s"), url);
 
        return NULL;
 }
@@ -95,11 +106,19 @@ json_object *http_json_get(const char *url, struct json_object *j)
        char *out;
        struct json_object *result;
 
+       if (log_level >= LOG_DEBUG)
+               log_debug("HTTP request= %s",
+                      json_object_to_json_string(j));
+
        in = json_object_to_json_string(j);
        out = http_get(url, in);
-       
+
        if (out) {
                result = json_tokener_parse(out);
+
+               if (log_level >= LOG_DEBUG)
+                       log_debug("HTTP reply= %s", out);
+
                free(out);
                return result;
        }