#include <libintl.h>
#define _(str) gettext(str)
+#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "http.h"
+#include "log.h"
-static int debug;
+struct http_session {
+ CURL *curl;
+ pthread_mutex_t lock;
+};
struct ucontent {
char *data;
size_t len;
};
-static CURL *curl;
-
static size_t cbk_curl(void *buffer, size_t size, size_t nmemb, void *userp)
{
size_t realsize;
return realsize;
}
-void http_init()
+struct http_session *http_session_new()
{
- if (!curl)
- curl = curl_easy_init();
+ struct http_session *sess;
+
+ sess = malloc(sizeof(struct http_session));
+ sess->curl = curl_easy_init();
+ pthread_mutex_init(&sess->lock, NULL);
+
+ return sess;
}
-void http_cleanup()
+void http_session_free(struct http_session *sess)
{
- curl_easy_cleanup(curl);
+ curl_easy_cleanup(sess->curl);
+ pthread_mutex_destroy(&sess->lock);
+ free(sess);
}
-char *http_get(const char *url, const char *content)
+static char *
+http_get(struct http_session *sess, const char *url, const char *content)
{
struct ucontent chunk;
+ int result;
chunk.data = malloc(1);
chunk.len = 0;
- curl_easy_setopt(curl, CURLOPT_URL, url);
- curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
+ pthread_mutex_lock(&sess->lock);
+
+ curl_easy_setopt(sess->curl, CURLOPT_URL, url);
+ curl_easy_setopt(sess->curl, CURLOPT_VERBOSE, 0);
if (content) {
- curl_easy_setopt(curl, CURLOPT_POSTFIELDS, content);
- curl_easy_setopt(curl,
+ curl_easy_setopt(sess->curl, CURLOPT_POSTFIELDS, content);
+ curl_easy_setopt(sess->curl,
CURLOPT_POSTFIELDSIZE,
(long)strlen(content));
}
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cbk_curl);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
+ curl_easy_setopt(sess->curl, CURLOPT_WRITEFUNCTION, cbk_curl);
+ curl_easy_setopt(sess->curl, CURLOPT_WRITEDATA, (void *)&chunk);
+
+ result = curl_easy_perform(sess->curl);
+
+ pthread_mutex_unlock(&sess->lock);
- if (curl_easy_perform(curl) == CURLE_OK)
+ 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;
}
-json_object *http_json_get(const char *url, struct json_object *j)
+json_object *
+http_json_get(struct http_session *sess, const char *url, struct json_object *j)
{
const char *in;
char *out;
struct json_object *result;
- in = json_object_to_json_string(j);
- out = http_get(url, in);
-
- if (debug)
- printf("HTTP request= %s\n",
+ 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(sess, url, in);
+
if (out) {
result = json_tokener_parse(out);
- if (debug)
- printf("HTTP reply= %s\n", out);
+
+ if (log_level >= LOG_DEBUG)
+ log_debug("HTTP reply= %s", out);
+
free(out);
return result;
}