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.

246 lines
6.3KB

  1. #include <vector>
  2. #include <openssl/crypto.h>
  3. #define CURL_STATICLIB
  4. #include <curl/curl.h>
  5. #include <network.hpp>
  6. #include <system.hpp>
  7. #include <asset.hpp>
  8. namespace rack {
  9. namespace network {
  10. static const std::vector<std::string> methodNames = {
  11. "GET", "POST", "PUT", "DELETE",
  12. };
  13. static CURL* createCurl() {
  14. CURL* curl = curl_easy_init();
  15. assert(curl);
  16. // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  17. std::string userAgent = APP_NAME + " " + APP_EDITION_NAME + "/" + APP_VERSION;
  18. curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgent.c_str());
  19. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);
  20. // Timeout to wait on initial HTTP connection.
  21. // This is lower than the typical HTTP timeout of 60 seconds to avoid DAWs from aborting plugin scans.
  22. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  23. // If curl can't resolve a DNS entry, it sends a signal to interrupt the process.
  24. // However, since we use curl on non-main thread, this crashes the application.
  25. // So tell curl not to signal.
  26. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  27. std::string caPath = asset::system("cacert.pem");
  28. curl_easy_setopt(curl, CURLOPT_CAINFO, caPath.c_str());
  29. return curl;
  30. }
  31. static size_t writeStringCallback(char* ptr, size_t size, size_t nmemb, void* userdata) {
  32. std::string* str = (std::string*) userdata;
  33. size_t len = size * nmemb;
  34. str->append(ptr, len);
  35. return len;
  36. }
  37. static std::string getCookieString(const CookieMap& cookies) {
  38. std::string s;
  39. for (const auto& pair : cookies) {
  40. s += encodeUrl(pair.first);
  41. s += "=";
  42. s += encodeUrl(pair.second);
  43. s += ";";
  44. }
  45. return s;
  46. }
  47. void init() {
  48. // Because OpenSSL is compiled with no-pinshared, we need to initialize without defining atexit(), since we want to destroy it when libRack is unloaded.
  49. OPENSSL_init_crypto(OPENSSL_INIT_NO_ATEXIT, NULL);
  50. // 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.
  51. // https://curl.haxx.se/libcurl/c/curl_easy_init.html
  52. curl_global_init(CURL_GLOBAL_ALL);
  53. }
  54. void destroy() {
  55. curl_global_cleanup();
  56. // Don't destroy OpenSSL because it's not designed to be reinitialized.
  57. // OPENSSL_cleanup();
  58. }
  59. json_t* requestJson(Method method, const std::string& url, json_t* dataJ, const CookieMap& cookies) {
  60. std::string urlS = url;
  61. CURL* curl = createCurl();
  62. char* reqStr = NULL;
  63. // Process data
  64. if (dataJ) {
  65. if (method == METHOD_GET) {
  66. // Append ?key1=value1&key2=value2&... to url
  67. urlS += "?";
  68. bool isFirst = true;
  69. const char* key;
  70. json_t* value;
  71. json_object_foreach(dataJ, key, value) {
  72. if (json_is_string(value)) {
  73. if (!isFirst)
  74. urlS += "&";
  75. urlS += key;
  76. urlS += "=";
  77. const char* str = json_string_value(value);
  78. size_t len = json_string_length(value);
  79. char* escapedStr = curl_easy_escape(curl, str, len);
  80. urlS += escapedStr;
  81. curl_free(escapedStr);
  82. isFirst = false;
  83. }
  84. }
  85. }
  86. else {
  87. reqStr = json_dumps(dataJ, 0);
  88. }
  89. }
  90. curl_easy_setopt(curl, CURLOPT_URL, urlS.c_str());
  91. // Set HTTP method
  92. if (method == METHOD_GET) {
  93. // This is CURL's default
  94. }
  95. else if (method == METHOD_POST) {
  96. curl_easy_setopt(curl, CURLOPT_POST, true);
  97. }
  98. else if (method == METHOD_PUT) {
  99. curl_easy_setopt(curl, CURLOPT_PUT, true);
  100. }
  101. else if (method == METHOD_DELETE) {
  102. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
  103. }
  104. // Set headers
  105. struct curl_slist* headers = NULL;
  106. headers = curl_slist_append(headers, "Accept: application/json");
  107. headers = curl_slist_append(headers, "Content-Type: application/json");
  108. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  109. // Cookies
  110. if (!cookies.empty()) {
  111. curl_easy_setopt(curl, CURLOPT_COOKIE, getCookieString(cookies).c_str());
  112. }
  113. // Body callbacks
  114. if (reqStr)
  115. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, reqStr);
  116. std::string resText;
  117. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeStringCallback);
  118. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resText);
  119. // Perform request
  120. INFO("Requesting JSON %s %s", methodNames[method].c_str(), urlS.c_str());
  121. CURLcode res = curl_easy_perform(curl);
  122. // Cleanup
  123. if (reqStr)
  124. std::free(reqStr);
  125. curl_easy_cleanup(curl);
  126. curl_slist_free_all(headers);
  127. if (res != CURLE_OK) {
  128. WARN("Could not request %s: %s", urlS.c_str(), curl_easy_strerror(res));
  129. return NULL;
  130. }
  131. // Parse JSON response
  132. json_error_t error;
  133. json_t* rootJ = json_loads(resText.c_str(), 0, &error);
  134. return rootJ;
  135. }
  136. static int xferInfoCallback(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) {
  137. float* progress = (float*) clientp;
  138. if (progress) {
  139. if (dltotal <= 0)
  140. *progress = 0.f;
  141. else
  142. *progress = (float)dlnow / dltotal;
  143. }
  144. return 0;
  145. }
  146. bool requestDownload(const std::string& url, const std::string& filename, float* progress, const CookieMap& cookies) {
  147. CURL* curl = createCurl();
  148. FILE* file = std::fopen(filename.c_str(), "wb");
  149. if (!file)
  150. return false;
  151. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  152. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);
  153. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
  154. curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);
  155. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, xferInfoCallback);
  156. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, progress);
  157. // Fail on 4xx and 5xx HTTP codes
  158. curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
  159. // Cookies
  160. if (!cookies.empty()) {
  161. curl_easy_setopt(curl, CURLOPT_COOKIE, getCookieString(cookies).c_str());
  162. }
  163. INFO("Requesting download %s", url.c_str());
  164. CURLcode res = curl_easy_perform(curl);
  165. curl_easy_cleanup(curl);
  166. std::fclose(file);
  167. if (res != CURLE_OK) {
  168. system::remove(filename);
  169. WARN("Could not download %s: %s", url.c_str(), curl_easy_strerror(res));
  170. return false;
  171. }
  172. return true;
  173. }
  174. std::string encodeUrl(const std::string& s) {
  175. CURL* curl = createCurl();
  176. DEFER({curl_easy_cleanup(curl);});
  177. assert(curl);
  178. char* escaped = curl_easy_escape(curl, s.c_str(), s.size());
  179. DEFER({curl_free(escaped);});
  180. return std::string(escaped);
  181. }
  182. std::string urlPath(const std::string& url) {
  183. CURLU* curl = curl_url();
  184. DEFER({curl_url_cleanup(curl);});
  185. if (curl_url_set(curl, CURLUPART_URL, url.c_str(), 0))
  186. return "";
  187. char* buf;
  188. if (curl_url_get(curl, CURLUPART_PATH, &buf, 0))
  189. return "";
  190. std::string ret = buf;
  191. curl_free(buf);
  192. return ret;
  193. }
  194. } // namespace network
  195. } // namespace rack