forked from cpp/cWikiBot
58 lines
1.6 KiB
C
58 lines
1.6 KiB
C
#include "http.h"
|
|
|
|
#include <string.h>
|
|
#include <curl/curl.h>
|
|
#include <stdlib.h>
|
|
|
|
static CURL* httpHandler = NULL;
|
|
|
|
char* request(char *url)
|
|
{
|
|
// initialize curl on the first call of this function
|
|
if(!httpHandler)
|
|
{
|
|
httpHandler = curl_easy_init();
|
|
curl_easy_setopt(httpHandler,CURLOPT_USERAGENT, "cWikiBot/0.1 (https://git.zom.bi/cpp/cWikiBot; cpp@zom.bi) libcurl4/7.64.0");
|
|
curl_easy_setopt(httpHandler,CURLOPT_WRITEFUNCTION, httpResponseCallback);
|
|
}
|
|
|
|
struct httpResponse_t httpResponse;
|
|
httpResponse.response = malloc(1);
|
|
httpResponse.size = 0;
|
|
CURLcode return_code;
|
|
if(httpHandler) {
|
|
curl_easy_setopt(httpHandler,CURLOPT_URL, url);
|
|
curl_easy_setopt(httpHandler,CURLOPT_WRITEDATA, (void *)&httpResponse);
|
|
return_code = curl_easy_perform(httpHandler);
|
|
}
|
|
else
|
|
{
|
|
fprintf(stderr, "CURL Error\n");
|
|
free(httpResponse.response);
|
|
return NULL;
|
|
}
|
|
if(return_code != CURLE_OK)
|
|
{
|
|
fprintf(stderr, "HTTP Error: %s (%d)\n",curl_easy_strerror(return_code), return_code);
|
|
free(httpResponse.response);
|
|
return NULL;
|
|
}
|
|
return httpResponse.response;
|
|
}
|
|
size_t httpResponseCallback(char *data, size_t wordlength, size_t bytecount, void *out)
|
|
{
|
|
// wordlength should be always 1, but this appears to be more secure.
|
|
size_t size = wordlength * bytecount;
|
|
struct httpResponse_t *mem = (struct httpResponse_t *) out;
|
|
|
|
char *newData = realloc(mem->response, mem->size + size +1);
|
|
if(newData == NULL)
|
|
return 0;
|
|
mem->response = newData;
|
|
memcpy(&(mem->response[mem->size]), data, size);
|
|
mem->size += size;
|
|
// Null-terminate the byte chunk, to effectively have a C-String.
|
|
mem->response[mem-> size] = 0;
|
|
|
|
return size;
|
|
}
|