You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

221 lines
5.2KB

  1. #include <vector>
  2. #define CURL_STATICLIB
  3. #include <curl/curl.h>
  4. #include <network.hpp>
  5. #include <system.hpp>
  6. #include <asset.hpp>
  7. namespace rack {
  8. namespace network {
  9. static const std::vector<std::string> methodNames = {
  10. "GET", "POST", "PUT", "DELETE",
  11. };
  12. static CURL* createCurl() {
  13. CURL* curl = curl_easy_init();
  14. assert(curl);
  15. // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  16. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);
  17. std::string caPath = asset::system("cacert.pem");
  18. curl_easy_setopt(curl, CURLOPT_CAINFO, caPath.c_str());
  19. return curl;
  20. }
  21. static size_t writeStringCallback(char* ptr, size_t size, size_t nmemb, void* userdata) {
  22. std::string* str = (std::string*) userdata;
  23. size_t len = size * nmemb;
  24. str->append(ptr, len);
  25. return len;
  26. }
  27. static std::string getCookieString(const CookieMap& cookies) {
  28. std::string s;
  29. for (const auto& pair : cookies) {
  30. s += encodeUrl(pair.first);
  31. s += "=";
  32. s += encodeUrl(pair.second);
  33. s += ";";
  34. }
  35. return s;
  36. }
  37. void init() {
  38. // curl_easy_init() calls this automatically, but it's good to make sure this is done on the main thread before other threads are spawned.
  39. // https://curl.haxx.se/libcurl/c/curl_easy_init.html
  40. curl_global_init(CURL_GLOBAL_ALL);
  41. }
  42. json_t* requestJson(Method method, const std::string& url, json_t* dataJ, const CookieMap& cookies) {
  43. std::string urlS = url;
  44. CURL* curl = createCurl();
  45. char* reqStr = NULL;
  46. // Process data
  47. if (dataJ) {
  48. if (method == METHOD_GET) {
  49. // Append ?key1=value1&key2=value2&... to url
  50. urlS += "?";
  51. bool isFirst = true;
  52. const char* key;
  53. json_t* value;
  54. json_object_foreach(dataJ, key, value) {
  55. if (json_is_string(value)) {
  56. if (!isFirst)
  57. urlS += "&";
  58. urlS += key;
  59. urlS += "=";
  60. const char* str = json_string_value(value);
  61. size_t len = json_string_length(value);
  62. char* escapedStr = curl_easy_escape(curl, str, len);
  63. urlS += escapedStr;
  64. curl_free(escapedStr);
  65. isFirst = false;
  66. }
  67. }
  68. }
  69. else {
  70. reqStr = json_dumps(dataJ, 0);
  71. }
  72. }
  73. curl_easy_setopt(curl, CURLOPT_URL, urlS.c_str());
  74. // Set HTTP method
  75. if (method == METHOD_GET) {
  76. // This is CURL's default
  77. }
  78. else if (method == METHOD_POST) {
  79. curl_easy_setopt(curl, CURLOPT_POST, true);
  80. }
  81. else if (method == METHOD_PUT) {
  82. curl_easy_setopt(curl, CURLOPT_PUT, true);
  83. }
  84. else if (method == METHOD_DELETE) {
  85. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
  86. }
  87. // Set headers
  88. struct curl_slist* headers = NULL;
  89. headers = curl_slist_append(headers, "Accept: application/json");
  90. headers = curl_slist_append(headers, "Content-Type: application/json");
  91. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  92. // Cookies
  93. if (!cookies.empty()) {
  94. curl_easy_setopt(curl, CURLOPT_COOKIE, getCookieString(cookies).c_str());
  95. }
  96. // Body callbacks
  97. if (reqStr)
  98. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, reqStr);
  99. std::string resText;
  100. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeStringCallback);
  101. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resText);
  102. // Perform request
  103. INFO("Requesting %s %s", methodNames[method].c_str(), urlS.c_str());
  104. CURLcode res = curl_easy_perform(curl);
  105. // Cleanup
  106. if (reqStr)
  107. std::free(reqStr);
  108. curl_easy_cleanup(curl);
  109. curl_slist_free_all(headers);
  110. if (res != CURLE_OK)
  111. return NULL;
  112. // Parse JSON response
  113. json_error_t error;
  114. json_t* rootJ = json_loads(resText.c_str(), 0, &error);
  115. return rootJ;
  116. }
  117. static int xferInfoCallback(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) {
  118. float* progress = (float*) clientp;
  119. if (progress) {
  120. if (dltotal <= 0)
  121. *progress = 0.f;
  122. else
  123. *progress = (float)dlnow / dltotal;
  124. }
  125. return 0;
  126. }
  127. bool requestDownload(const std::string& url, const std::string& filename, float* progress, const CookieMap& cookies) {
  128. CURL* curl = createCurl();
  129. FILE* file = std::fopen(filename.c_str(), "wb");
  130. if (!file)
  131. return false;
  132. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  133. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);
  134. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
  135. curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);
  136. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, xferInfoCallback);
  137. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, progress);
  138. // Fail on 4xx and 5xx HTTP codes
  139. curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
  140. // Cookies
  141. if (!cookies.empty()) {
  142. curl_easy_setopt(curl, CURLOPT_COOKIE, getCookieString(cookies).c_str());
  143. }
  144. INFO("Downloading %s", url.c_str());
  145. CURLcode res = curl_easy_perform(curl);
  146. curl_easy_cleanup(curl);
  147. std::fclose(file);
  148. if (res != CURLE_OK)
  149. system::remove(filename);
  150. return res == CURLE_OK;
  151. }
  152. std::string encodeUrl(const std::string& s) {
  153. CURL* curl = curl_easy_init();
  154. DEFER({curl_easy_cleanup(curl);});
  155. assert(curl);
  156. char* escaped = curl_easy_escape(curl, s.c_str(), s.size());
  157. DEFER({curl_free(escaped);});
  158. return std::string(escaped);
  159. }
  160. std::string urlPath(const std::string& url) {
  161. CURLU* curl = curl_url();
  162. DEFER({curl_url_cleanup(curl);});
  163. if (curl_url_set(curl, CURLUPART_URL, url.c_str(), 0))
  164. return "";
  165. char* buf;
  166. if (curl_url_get(curl, CURLUPART_PATH, &buf, 0))
  167. return "";
  168. std::string ret = buf;
  169. curl_free(buf);
  170. return ret;
  171. }
  172. } // namespace network
  173. } // namespace rack