2020-12-26 16:50:29 +01:00
|
|
|
#include "http.h"
|
|
|
|
|
|
|
|
#include <string.h>
|
|
|
|
#include <curl/curl.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
2020-12-27 00:11:03 +01:00
|
|
|
static CURL* httpHandler = NULL;
|
|
|
|
|
2020-12-26 16:50:29 +01:00
|
|
|
char* request(char *url)
|
|
|
|
{
|
|
|
|
// initialize curl on the first call of this function
|
2020-12-27 00:11:03 +01:00
|
|
|
if(!httpHandler)
|
2020-12-26 16:50:29 +01:00
|
|
|
{
|
2020-12-27 00:11:03 +01:00
|
|
|
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);
|
2020-12-26 16:50:29 +01:00
|
|
|
}
|
2020-12-27 00:11:03 +01:00
|
|
|
|
2020-12-26 16:50:29 +01:00
|
|
|
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
|
|
|
|
{
|
2020-12-27 00:11:03 +01:00
|
|
|
fprintf(stderr, "CURL Error\n");
|
|
|
|
free(httpResponse.response);
|
2020-12-26 16:50:29 +01:00
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
if(return_code != CURLE_OK)
|
|
|
|
{
|
2020-12-27 00:11:03 +01:00
|
|
|
fprintf(stderr, "HTTP Error: %s (%d)\n",curl_easy_strerror(return_code), return_code);
|
|
|
|
free(httpResponse.response);
|
2020-12-26 16:50:29 +01:00
|
|
|
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;
|
2020-12-27 00:11:03 +01:00
|
|
|
|
2020-12-26 16:50:29 +01:00
|
|
|
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;
|
2020-12-27 00:11:03 +01:00
|
|
|
|
2020-12-26 16:50:29 +01:00
|
|
|
return size;
|
|
|
|
}
|