CurlHttpClient.cc 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /*
  2. * Copyright 1999-2019 Alibaba Cloud All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "CurlHttpClient.h"
  17. #include "Utils.h"
  18. #include <cassert>
  19. #include <sstream>
  20. #include <string>
  21. #include <vector>
  22. #include <iostream>
  23. #include <string.h>
  24. #include <stdio.h>
  25. using namespace std;
  26. namespace AlibabaCloud {
  27. namespace {
  28. typedef struct {
  29. const char *data;
  30. const char *pos;
  31. const char *last;
  32. } uploadContext;
  33. static size_t readCallback(void *ptr, size_t size, size_t nmemb, void *stream) {
  34. uploadContext *ctx = (uploadContext *)stream;
  35. size_t len = 0;
  36. if (ctx->pos >= ctx->last) {
  37. return 0;
  38. }
  39. if ((size == 0) || (nmemb == 0) || (size * nmemb < 1)) {
  40. return 0;
  41. }
  42. len = ctx->last - ctx->pos;
  43. if (len > size * nmemb) {
  44. len = size * nmemb;
  45. }
  46. memcpy(ptr, ctx->pos, len);
  47. ctx->pos += len;
  48. return len;
  49. }
  50. size_t recvBody(char *ptr, size_t size, size_t nmemb, void *userdata) {
  51. std::ostringstream &out = *static_cast<std::ostringstream*>(userdata);
  52. out << std::string(ptr, nmemb*size);
  53. return nmemb * size;
  54. }
  55. size_t recvHeaders(char *buffer, size_t size, size_t nitems, void *userdata) {
  56. HttpResponse *response = static_cast<HttpResponse*>(userdata);
  57. std::string line(buffer);
  58. auto pos = line.find(':');
  59. if (pos != line.npos) {
  60. std::string name = line.substr(0, pos);
  61. std::string value = line.substr(pos + 2);
  62. size_t p = 0;
  63. if ((p = value.rfind('\r')) != value.npos)
  64. value[p] = '\0';
  65. response->setHeader(name, value);
  66. }
  67. return nitems * size;
  68. }
  69. void setCUrlProxy(CURL *curlHandle, const NetworkProxy &proxy) {
  70. if (proxy.type() == NetworkProxy::Type::None)
  71. return;
  72. long type;
  73. switch (proxy.type()) {
  74. case NetworkProxy::Type::Socks5:
  75. type = CURLPROXY_SOCKS5;
  76. break;
  77. case NetworkProxy::Type::Http:
  78. default:
  79. type = CURLPROXY_HTTP;
  80. break;
  81. }
  82. curl_easy_setopt(curlHandle, CURLOPT_PROXYTYPE, type);
  83. std::ostringstream out;
  84. out << proxy.hostName() << ":" << proxy.port();
  85. curl_easy_setopt(curlHandle, CURLOPT_PROXY, out.str().c_str());
  86. if (!proxy.user().empty()) {
  87. out.clear();
  88. out << proxy.user() << ":" << proxy.password();
  89. curl_easy_setopt(curlHandle, CURLOPT_PROXYUSERPWD, out.str().c_str());
  90. }
  91. }
  92. } // namespace
  93. CurlHttpClient::CurlHttpClient() :
  94. HttpClient(),
  95. curlHandle_(curl_easy_init()) {
  96. }
  97. CurlHttpClient::~CurlHttpClient() {
  98. curl_easy_cleanup(curlHandle_);
  99. }
  100. HttpClient::HttpResponseOutcome
  101. CurlHttpClient::makeRequest(const HttpRequest &request) {
  102. curl_easy_reset(curlHandle_);
  103. HttpResponse response(request);
  104. std::string url = request.url().toString();
  105. switch (request.method()) {
  106. case HttpRequest::Method::Get:
  107. break;
  108. case HttpRequest::Method::Post: {
  109. if (request.bodySize() > 0) {
  110. curl_easy_setopt(curlHandle_, CURLOPT_POSTFIELDS, request.body());
  111. } else {
  112. curl_easy_setopt(curlHandle_, CURLOPT_POSTFIELDS, "");
  113. }
  114. }
  115. break;
  116. case HttpRequest::Method::Put: {
  117. uploadContext* ctx = (uploadContext *)malloc(sizeof(uploadContext));
  118. // this is impossible, as the size is 24 Bytes
  119. if (ctx == nullptr) {
  120. return HttpResponseOutcome(
  121. Error("MemoryAllocateError",
  122. "There is not enough memory for http transfer."));
  123. }
  124. ctx->data = request.body();
  125. ctx->pos = request.body();
  126. ctx->last = ctx->pos + request.bodySize();
  127. curl_easy_setopt(curlHandle_, CURLOPT_READFUNCTION, readCallback);
  128. curl_easy_setopt(curlHandle_, CURLOPT_UPLOAD, 1L);
  129. curl_easy_setopt(curlHandle_, CURLOPT_READDATA, ctx);
  130. }
  131. break;
  132. case HttpRequest::Method::Delete: {
  133. curl_easy_setopt(curlHandle_, CURLOPT_CUSTOMREQUEST, "DELETE");
  134. if (request.bodySize() > 0) {
  135. curl_easy_setopt(curlHandle_, CURLOPT_POSTFIELDS, request.body());
  136. } else {
  137. curl_easy_setopt(curlHandle_, CURLOPT_POSTFIELDS, "");
  138. }
  139. }
  140. break;
  141. default:
  142. break;
  143. }
  144. curl_easy_setopt(curlHandle_, CURLOPT_URL, url.c_str());
  145. curl_easy_setopt(curlHandle_, CURLOPT_SSL_VERIFYPEER, 1L);
  146. curl_easy_setopt(curlHandle_, CURLOPT_SSL_VERIFYHOST, 2L);
  147. curl_easy_setopt(curlHandle_, CURLOPT_HEADERDATA, &response);
  148. curl_easy_setopt(curlHandle_, CURLOPT_HEADERFUNCTION, recvHeaders);
  149. curl_slist *list = nullptr;
  150. auto headers = request.headers();
  151. for (const auto &p : headers) {
  152. std::string str = p.first;
  153. str.append(": ").append(p.second);
  154. list = curl_slist_append(list, str.c_str());
  155. }
  156. curl_easy_setopt(curlHandle_, CURLOPT_HTTPHEADER, list);
  157. std::ostringstream out;
  158. curl_easy_setopt(curlHandle_, CURLOPT_WRITEDATA, &out);
  159. curl_easy_setopt(curlHandle_, CURLOPT_WRITEFUNCTION, recvBody);
  160. setCUrlProxy(curlHandle_, proxy());
  161. if (GetEnv("DEBUG") == "sdk") {
  162. curl_easy_setopt(curlHandle_, CURLOPT_VERBOSE, 1L);
  163. }
  164. CURLcode res = curl_easy_perform(curlHandle_);
  165. switch (res) {
  166. case CURLE_OK: {
  167. long response_code;
  168. curl_easy_getinfo(curlHandle_, CURLINFO_RESPONSE_CODE, &response_code);
  169. response.setStatusCode(response_code);
  170. response.setBody(out.str().c_str(), out.str().length());
  171. return HttpResponseOutcome(response);
  172. }
  173. case CURLE_SSL_CONNECT_ERROR:
  174. return HttpResponseOutcome(
  175. Error("SSLConnectError",
  176. "A problem occurred somewhere in the SSL/TLS handshake."));
  177. default:
  178. return HttpResponseOutcome(
  179. Error("NetworkError",
  180. "Failed to connect to host or proxy: " +
  181. HttpMethodToString(request.method()) + " " + request.url().toString()));
  182. }
  183. }
  184. } // namespace AlibabaCloud