curl.c 1.9 KB

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