| 83 | } |
| 84 | |
| 85 | Response Do(const Request& req) |
| 86 | { |
| 87 | try |
| 88 | { |
| 89 | CURL* curl = curl_easy_init(); |
| 90 | std::shared_ptr<void> _(nullptr, [curl](...) { curl_easy_cleanup(curl); }); |
| 91 | |
| 92 | if (!curl) |
| 93 | throw std::runtime_error("Failed to initialize curl"); |
| 94 | |
| 95 | Response res; |
| 96 | WriteThis wt; |
| 97 | |
| 98 | if (req.method == Method::POST || req.method == Method::PUT) |
| 99 | { |
| 100 | wt.readptr = req.body.c_str(); |
| 101 | wt.sizeleft = req.body.size(); |
| 102 | |
| 103 | curl_easy_setopt(curl, CURLOPT_READFUNCTION, ReadCallback); |
| 104 | curl_easy_setopt(curl, CURLOPT_READDATA, &wt); |
| 105 | curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(wt.sizeleft)); |
| 106 | } |
| 107 | |
| 108 | if (req.forceIPv4) |
| 109 | curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); |
| 110 | |
| 111 | if (req.method == Method::POST) |
| 112 | curl_easy_setopt(curl, CURLOPT_POST, 1L); |
| 113 | |
| 114 | if (req.method == Method::PUT) |
| 115 | curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); |
| 116 | |
| 117 | curl_easy_setopt(curl, CURLOPT_URL, req.url.c_str()); |
| 118 | curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true); |
| 119 | curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteData); |
| 120 | curl_easy_setopt(curl, CURLOPT_WRITEDATA, static_cast<void*>(&res)); |
| 121 | curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, HeaderCallback); |
| 122 | curl_easy_setopt(curl, CURLOPT_HEADERDATA, static_cast<void*>(&res)); |
| 123 | curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true); |
| 124 | curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, true); |
| 125 | curl_easy_setopt(curl, CURLOPT_USERAGENT, kOpenRCT2UserAgent); |
| 126 | |
| 127 | curl_slist* chunk = nullptr; |
| 128 | std::shared_ptr<void> __(nullptr, [chunk](...) { curl_slist_free_all(chunk); }); |
| 129 | for (auto header : req.header) |
| 130 | { |
| 131 | std::string hs = header.first + ": " + header.second; |
| 132 | chunk = curl_slist_append(chunk, hs.c_str()); |
| 133 | } |
| 134 | if (req.header.size() != 0) |
| 135 | { |
| 136 | if (chunk == nullptr) |
| 137 | { |
| 138 | throw std::runtime_error("Failed to set headers"); |
| 139 | } |
| 140 | curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); |
| 141 | } |
| 142 |
no test coverage detected