Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
97 lines (79 sloc) 1.91 KB
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <curl/curl.h>
#include "na.h"
#include "http.h"
static struct curl_buffer *curl_buffer_alloc(void)
{
struct curl_buffer *buffer;
buffer = zalloc(sizeof(*buffer));
if (!buffer)
return NULL;
/* start out with a data buffer of 1 byte to
* make the buffer fill logic simpler */
buffer->data = zalloc(1);
if (!buffer->data) {
free(buffer);
return NULL;
}
buffer->length = 0;
return buffer;
}
static void curl_buffer_free(struct curl_buffer *buffer)
{
if (!buffer)
return;
free(buffer->data);
free(buffer);
}
static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
void *userp)
{
struct curl_buffer *curl_buf = userp;
size_t buffer_size = size * nmemb;
char *temp;
if (!buffer || !buffer_size || !curl_buf)
return -EINVAL;
/* add to the data we already have */
temp = zalloc(curl_buf->length + buffer_size + 1);
if (!temp)
return -ENOMEM;
memcpy(temp, curl_buf->data, curl_buf->length);
free(curl_buf->data);
curl_buf->data = temp;
memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
curl_buf->length += buffer_size;
return buffer_size;
}
char *send_request(const char *uri, const char *data)
{
struct curl_buffer *curl_buf;
CURL *curl;
int ret;
char *response = NULL;
if (!uri)
return NULL;
curl_buf = curl_buffer_alloc();
if (!curl_buf)
return NULL;
curl = curl_easy_init();
if (!curl)
goto out_curl_alloc;
curl_easy_setopt(curl, CURLOPT_URL, uri);
if (data) {
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
}
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
ret = curl_easy_perform(curl);
if (ret)
goto out_curl_init;
response = strdup(curl_buf->data);
out_curl_init:
curl_easy_cleanup(curl);
out_curl_alloc:
curl_buffer_free(curl_buf);
return response;
}