2 * Copyright (C) 2010-2013 jeanfi@gmail.com
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 #define _(str) gettext(str)
28 #include <curl/curl.h>
43 static size_t cbk_curl(void *buffer, size_t size, size_t nmemb, void *userp)
48 realsize = size * nmemb;
49 mem = (struct ucontent *)userp;
51 mem->data = realloc(mem->data, mem->len + realsize + 1);
53 memcpy(&(mem->data[mem->len]), buffer, realsize);
55 mem->data[mem->len] = 0;
60 struct http_session *http_session_new()
62 struct http_session *sess;
64 sess = malloc(sizeof(struct http_session));
65 sess->curl = curl_easy_init();
66 pthread_mutex_init(&sess->lock, NULL);
71 void http_session_free(struct http_session *sess)
73 curl_easy_cleanup(sess->curl);
74 pthread_mutex_destroy(&sess->lock);
79 http_get(struct http_session *sess, const char *url, const char *content)
81 struct ucontent chunk;
84 chunk.data = malloc(1);
87 pthread_mutex_lock(&sess->lock);
89 curl_easy_setopt(sess->curl, CURLOPT_URL, url);
90 curl_easy_setopt(sess->curl, CURLOPT_VERBOSE, 0);
92 curl_easy_setopt(sess->curl, CURLOPT_POSTFIELDS, content);
93 curl_easy_setopt(sess->curl,
94 CURLOPT_POSTFIELDSIZE,
95 (long)strlen(content));
97 curl_easy_setopt(sess->curl, CURLOPT_WRITEFUNCTION, cbk_curl);
98 curl_easy_setopt(sess->curl, CURLOPT_WRITEDATA, (void *)&chunk);
100 result = curl_easy_perform(sess->curl);
102 pthread_mutex_unlock(&sess->lock);
104 if (result == CURLE_OK)
108 log_err(_("HTTP request fail url=%s"), url);
114 http_json_get(struct http_session *sess, const char *url, struct json_object *j)
118 struct json_object *result;
120 if (log_level >= LOG_DEBUG)
121 log_debug("HTTP request= %s",
122 json_object_to_json_string(j));
124 in = json_object_to_json_string(j);
125 out = http_get(sess, url, in);
128 result = json_tokener_parse(out);
130 if (log_level >= LOG_DEBUG)
131 log_debug("HTTP reply= %s", out);