X-Git-Url: https://git.wpitchoune.net/gitweb/?p=prss.git;a=blobdiff_plain;f=src%2Fhttp.c;h=cd465154e562e023633c8d8e72c2125a3c024558;hp=52238ec9ace98c1b97956a450f69bfd2fe4cfa23;hb=7d847f77b7f18f13654d34d20f515f27574b70e8;hpb=09a826a93753ebb1b82fbc30574c034f084e02b8 diff --git a/src/http.c b/src/http.c index 52238ec..cd46515 100644 --- a/src/http.c +++ b/src/http.c @@ -20,6 +20,7 @@ #include #define _(str) gettext(str) +#include #include #include #include @@ -29,13 +30,16 @@ #include "http.h" #include "log.h" +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; @@ -53,36 +57,51 @@ static size_t cbk_curl(void *buffer, size_t size, size_t nmemb, void *userp) 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); @@ -91,7 +110,8 @@ char *http_get(const char *url, const char *content) 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; @@ -102,7 +122,7 @@ json_object *http_json_get(const char *url, struct json_object *j) json_object_to_json_string(j)); in = json_object_to_json_string(j); - out = http_get(url, in); + out = http_get(sess, url, in); if (out) { result = json_tokener_parse(out);