curl.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "curl.h"
  2. // Borrowed from https://curl.haxx.se/libcurl/c/getinmemory.html
  3. struct MemoryStruct { char *memory;
  4. size_t size;
  5. };
  6. static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
  7. size_t realsize = size * nmemb;
  8. struct MemoryStruct *mem = (struct MemoryStruct *)userp;
  9. mem->memory = realloc(mem->memory, mem->size + realsize + 1);
  10. if(mem->memory == NULL)
  11. return 0;
  12. memcpy(&(mem->memory[mem->size]), contents, realsize);
  13. mem->size += realsize;
  14. mem->memory[mem->size] = 0;
  15. return realsize;
  16. }
  17. char *getData(char *url) {
  18. CURL *curl_handle;
  19. CURLcode res;
  20. struct MemoryStruct chunk;
  21. chunk.memory = malloc(1); /* will be grown as needed by the realloc above */
  22. chunk.size = 0; /* no data at this point */
  23. curl_global_init(CURL_GLOBAL_ALL);
  24. /* init the curl session */
  25. curl_handle = curl_easy_init();
  26. /* specify URL to get */
  27. curl_easy_setopt(curl_handle, CURLOPT_URL, url);
  28. curl_easy_setopt(curl_handle, CURLOPT_NOPROXY, "*");
  29. /* send all data to this function */
  30. curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
  31. /* we pass our 'chunk' struct to the callback function */
  32. curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
  33. /* some servers don't like requests that are made without a user-agent
  34. field, so we provide one */
  35. curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
  36. #ifdef WIN32
  37. curl_easy_setopt(curl_handle, CURLOPT_CAINFO, "cacert.pem");
  38. #endif
  39. /* get it! */
  40. res = curl_easy_perform(curl_handle);
  41. /* check for errors */
  42. if(res != CURLE_OK) {
  43. fprintf(stderr, "curl_easy_perform() failed: %s\n",
  44. curl_easy_strerror(res));
  45. }
  46. size_t dataSize = strlen(chunk.memory);
  47. char *data = calloc(dataSize + 1, 1);
  48. strncpy(data, chunk.memory, dataSize);
  49. /* cleanup curl stuff */
  50. curl_easy_cleanup(curl_handle);
  51. free(chunk.memory);
  52. /* we're done with libcurl, so clean it up */
  53. curl_global_cleanup();
  54. return data;
  55. }