curl.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. /* get it! */
  37. res = curl_easy_perform(curl_handle);
  38. /* check for errors */
  39. if(res != CURLE_OK) {
  40. fprintf(stderr, "curl_easy_perform() failed: %s\n",
  41. curl_easy_strerror(res));
  42. }
  43. size_t dataSize = strlen(chunk.memory);
  44. char *data = calloc(dataSize + 1, 1);
  45. data = strncpy(data, chunk.memory, dataSize);
  46. /* cleanup curl stuff */
  47. curl_easy_cleanup(curl_handle);
  48. free(chunk.memory);
  49. /* we're done with libcurl, so clean it up */
  50. curl_global_cleanup();
  51. return data;
  52. }