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.

245 lines
6.2KB

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