http_client.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. #include "http_client.h"
  2. #include <mutex>
  3. #ifdef WITH_CURL
  4. #include "curl/curl.h"
  5. #endif
  6. #include "herr.h"
  7. #include "hstring.h"
  8. #include "hsocket.h"
  9. #include "hssl.h"
  10. #include "HttpParser.h"
  11. // for async
  12. #include "AsyncHttpClient.h"
  13. struct http_client_s {
  14. std::string host;
  15. int port;
  16. int https;
  17. int timeout; // s
  18. http_headers headers;
  19. //private:
  20. #ifdef WITH_CURL
  21. CURL* curl;
  22. #endif
  23. // for sync
  24. int fd;
  25. hssl_t ssl;
  26. HttpParserPtr parser;
  27. // for async
  28. std::mutex mutex_;
  29. std::shared_ptr<hv::AsyncHttpClient> async_client_;
  30. http_client_s() {
  31. host = LOCALHOST;
  32. port = DEFAULT_HTTP_PORT;
  33. https = 0;
  34. timeout = DEFAULT_HTTP_TIMEOUT;
  35. #ifdef WITH_CURL
  36. curl = NULL;
  37. #endif
  38. fd = -1;
  39. ssl = NULL;
  40. }
  41. ~http_client_s() {
  42. Close();
  43. }
  44. void Close() {
  45. #ifdef WITH_CURL
  46. if (curl) {
  47. curl_easy_cleanup(curl);
  48. curl = NULL;
  49. }
  50. #endif
  51. if (ssl) {
  52. hssl_free(ssl);
  53. ssl = NULL;
  54. }
  55. if (fd > 0) {
  56. closesocket(fd);
  57. fd = -1;
  58. }
  59. }
  60. };
  61. static int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp);
  62. http_client_t* http_client_new(const char* host, int port, int https) {
  63. http_client_t* cli = new http_client_t;
  64. if (host) cli->host = host;
  65. cli->port = port;
  66. cli->https = https;
  67. cli->headers["Connection"] = "keep-alive";
  68. return cli;
  69. }
  70. int http_client_del(http_client_t* cli) {
  71. if (cli == NULL) return 0;
  72. delete cli;
  73. return 0;
  74. }
  75. int http_client_set_timeout(http_client_t* cli, int timeout) {
  76. cli->timeout = timeout;
  77. return 0;
  78. }
  79. int http_client_clear_headers(http_client_t* cli) {
  80. cli->headers.clear();
  81. return 0;
  82. }
  83. int http_client_set_header(http_client_t* cli, const char* key, const char* value) {
  84. cli->headers[key] = value;
  85. return 0;
  86. }
  87. int http_client_del_header(http_client_t* cli, const char* key) {
  88. auto iter = cli->headers.find(key);
  89. if (iter != cli->headers.end()) {
  90. cli->headers.erase(iter);
  91. }
  92. return 0;
  93. }
  94. const char* http_client_get_header(http_client_t* cli, const char* key) {
  95. auto iter = cli->headers.find(key);
  96. if (iter != cli->headers.end()) {
  97. return iter->second.c_str();
  98. }
  99. return NULL;
  100. }
  101. int http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  102. if (!cli || !req || !resp) return ERR_NULL_POINTER;
  103. if (req->url.empty() || *req->url.c_str() == '/') {
  104. req->scheme = cli->https ? "https" : "http";
  105. req->host = cli->host;
  106. req->port = cli->port;
  107. }
  108. if (req->timeout == 0) {
  109. req->timeout = cli->timeout;
  110. }
  111. for (auto& pair : cli->headers) {
  112. if (req->headers.find(pair.first) == req->headers.end()) {
  113. req->headers[pair.first] = pair.second;
  114. }
  115. }
  116. return __http_client_send(cli, req, resp);
  117. }
  118. int http_client_send(HttpRequest* req, HttpResponse* resp) {
  119. if (!req || !resp) return ERR_NULL_POINTER;
  120. if (req->timeout == 0) {
  121. req->timeout = DEFAULT_HTTP_TIMEOUT;
  122. }
  123. http_client_t cli;
  124. return __http_client_send(&cli, req, resp);
  125. }
  126. #ifdef WITH_CURL
  127. static size_t s_header_cb(char* buf, size_t size, size_t cnt, void* userdata) {
  128. if (buf == NULL || userdata == NULL) return 0;
  129. HttpResponse* resp = (HttpResponse*)userdata;
  130. std::string str(buf);
  131. std::string::size_type pos = str.find_first_of(':');
  132. if (pos == std::string::npos) {
  133. if (strncmp(buf, "HTTP/", 5) == 0) {
  134. // status line
  135. //hlogd("%s", buf);
  136. int http_major,http_minor,status_code;
  137. if (buf[5] == '1') {
  138. // HTTP/1.1 200 OK\r\n
  139. sscanf(buf, "HTTP/%d.%d %d", &http_major, &http_minor, &status_code);
  140. }
  141. else if (buf[5] == '2') {
  142. // HTTP/2 200\r\n
  143. sscanf(buf, "HTTP/%d %d", &http_major, &status_code);
  144. http_minor = 0;
  145. }
  146. resp->http_major = http_major;
  147. resp->http_minor = http_minor;
  148. resp->status_code = (http_status)status_code;
  149. }
  150. }
  151. else {
  152. // headers
  153. std::string key = trim(str.substr(0, pos));
  154. std::string value = trim(str.substr(pos+1));
  155. resp->headers[key] = value;
  156. }
  157. return size*cnt;
  158. }
  159. static size_t s_body_cb(char *buf, size_t size, size_t cnt, void *userdata) {
  160. if (buf == NULL || userdata == NULL) return 0;
  161. HttpResponse* resp = (HttpResponse*)userdata;
  162. resp->body.append(buf, size*cnt);
  163. return size*cnt;
  164. }
  165. int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  166. if (cli->curl == NULL) {
  167. cli->curl = curl_easy_init();
  168. }
  169. CURL* curl = cli->curl;
  170. // SSL
  171. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  172. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
  173. // http2
  174. if (req->http_major == 2) {
  175. #if LIBCURL_VERSION_NUM < 0x073100 // 7.49.0
  176. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_0);
  177. #else
  178. // No Connection: Upgrade
  179. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE);
  180. #endif
  181. }
  182. // TCP_NODELAY
  183. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  184. // method
  185. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method_str(req->method));
  186. // url
  187. req->DumpUrl();
  188. curl_easy_setopt(curl, CURLOPT_URL, req->url.c_str());
  189. //hlogd("%s %s HTTP/%d.%d", http_method_str(req->method), req->url.c_str(), req->http_major, req->http_minor);
  190. // headers
  191. req->FillContentType();
  192. struct curl_slist *headers = NULL;
  193. for (auto& pair : req->headers) {
  194. std::string header = pair.first;
  195. header += ": ";
  196. header += pair.second;
  197. headers = curl_slist_append(headers, header.c_str());
  198. }
  199. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  200. // body
  201. //struct curl_httppost* httppost = NULL;
  202. //struct curl_httppost* lastpost = NULL;
  203. if (req->body.size() == 0) {
  204. req->DumpBody();
  205. /*
  206. if (req->body.size() == 0 &&
  207. req->content_type == MULTIPART_FORM_DATA) {
  208. for (auto& pair : req->mp) {
  209. if (pair.second.filename.size() != 0) {
  210. curl_formadd(&httppost, &lastpost,
  211. CURLFORM_COPYNAME, pair.first.c_str(),
  212. CURLFORM_FILE, pair.second.filename.c_str(),
  213. CURLFORM_END);
  214. }
  215. else if (pair.second.content.size() != 0) {
  216. curl_formadd(&httppost, &lastpost,
  217. CURLFORM_COPYNAME, pair.first.c_str(),
  218. CURLFORM_COPYCONTENTS, pair.second.content.c_str(),
  219. CURLFORM_END);
  220. }
  221. }
  222. if (httppost) {
  223. curl_easy_setopt(curl, CURLOPT_HTTPPOST, httppost);
  224. }
  225. }
  226. */
  227. }
  228. if (req->body.size() != 0) {
  229. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req->body.c_str());
  230. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req->body.size());
  231. }
  232. if (req->timeout > 0) {
  233. curl_easy_setopt(curl, CURLOPT_TIMEOUT, req->timeout);
  234. }
  235. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, s_body_cb);
  236. curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp);
  237. curl_easy_setopt(curl, CURLOPT_HEADER, 0);
  238. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, s_header_cb);
  239. curl_easy_setopt(curl, CURLOPT_HEADERDATA, resp);
  240. int ret = curl_easy_perform(curl);
  241. /*
  242. if (ret != 0) {
  243. hloge("curl error: %d: %s", ret, curl_easy_strerror((CURLcode)ret));
  244. }
  245. if (resp->body.length() != 0) {
  246. hlogd("[Response]\n%s", resp->body.c_str());
  247. }
  248. double total_time, name_time, conn_time, pre_time;
  249. curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
  250. curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &name_time);
  251. curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &conn_time);
  252. curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &pre_time);
  253. hlogd("TIME_INFO: %lf,%lf,%lf,%lf", total_time, name_time, conn_time, pre_time);
  254. */
  255. if (headers) {
  256. curl_slist_free_all(headers);
  257. }
  258. /*
  259. if (httppost) {
  260. curl_formfree(httppost);
  261. }
  262. */
  263. return ret;
  264. }
  265. const char* http_client_strerror(int errcode) {
  266. return curl_easy_strerror((CURLcode)errcode);
  267. }
  268. #else
  269. static int __http_client_connect(http_client_t* cli, HttpRequest* req) {
  270. int blocktime = DEFAULT_CONNECT_TIMEOUT;
  271. if (req->timeout > 0) {
  272. blocktime = MIN(req->timeout*1000, blocktime);
  273. }
  274. req->ParseUrl();
  275. int connfd = ConnectTimeout(req->host.c_str(), req->port, blocktime);
  276. if (connfd < 0) {
  277. return connfd;
  278. }
  279. tcp_nodelay(connfd, 1);
  280. if (strcmp(req->scheme.c_str(), "https") == 0) {
  281. hssl_ctx_t ssl_ctx = hssl_ctx_instance();
  282. if (ssl_ctx == NULL) {
  283. closesocket(connfd);
  284. return ERR_INVALID_PROTOCOL;
  285. }
  286. cli->ssl = hssl_new(ssl_ctx, connfd);
  287. int ret = hssl_connect(cli->ssl);
  288. if (ret != 0) {
  289. fprintf(stderr, "SSL handshake failed: %d\n", ret);
  290. hssl_free(cli->ssl);
  291. cli->ssl = NULL;
  292. closesocket(connfd);
  293. return ret;
  294. }
  295. }
  296. if (cli->parser == NULL) {
  297. cli->parser = HttpParserPtr(HttpParser::New(HTTP_CLIENT, (http_version)req->http_major));
  298. }
  299. cli->fd = connfd;
  300. return 0;
  301. }
  302. int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  303. // connect -> send -> recv -> http_parser
  304. int err = 0;
  305. int timeout = req->timeout;
  306. int connfd = cli->fd;
  307. time_t start_time = time(NULL);
  308. time_t cur_time;
  309. int fail_cnt = 0;
  310. connect:
  311. if (connfd <= 0) {
  312. int ret = __http_client_connect(cli, req);
  313. if (ret != 0) {
  314. return ret;
  315. }
  316. connfd = cli->fd;
  317. }
  318. cli->parser->SubmitRequest(req);
  319. char recvbuf[1024] = {0};
  320. int total_nsend, nsend, nrecv;
  321. total_nsend = nsend = nrecv = 0;
  322. send:
  323. char* data = NULL;
  324. size_t len = 0;
  325. bool https = strcmp(req->scheme.c_str(), "https") == 0;
  326. while (cli->parser->GetSendData(&data, &len)) {
  327. total_nsend = 0;
  328. while (1) {
  329. if (timeout > 0) {
  330. cur_time = time(NULL);
  331. if (cur_time - start_time >= timeout) {
  332. return ERR_TASK_TIMEOUT;
  333. }
  334. so_sndtimeo(connfd, (timeout-(cur_time-start_time)) * 1000);
  335. }
  336. if (https) {
  337. nsend = hssl_write(cli->ssl, data+total_nsend, len-total_nsend);
  338. }
  339. else {
  340. nsend = send(connfd, data+total_nsend, len-total_nsend, 0);
  341. }
  342. if (nsend <= 0) {
  343. if (++fail_cnt == 1) {
  344. // maybe keep-alive timeout, try again
  345. cli->Close();
  346. goto connect;
  347. }
  348. else {
  349. return socket_errno();
  350. }
  351. }
  352. total_nsend += nsend;
  353. if (total_nsend == len) {
  354. break;
  355. }
  356. }
  357. }
  358. cli->parser->InitResponse(resp);
  359. recv:
  360. do {
  361. if (timeout > 0) {
  362. cur_time = time(NULL);
  363. if (cur_time - start_time >= timeout) {
  364. return ERR_TASK_TIMEOUT;
  365. }
  366. so_rcvtimeo(connfd, (timeout-(cur_time-start_time)) * 1000);
  367. }
  368. if (https) {
  369. nrecv = hssl_read(cli->ssl, recvbuf, sizeof(recvbuf));
  370. }
  371. else {
  372. nrecv = recv(connfd, recvbuf, sizeof(recvbuf), 0);
  373. }
  374. if (nrecv <= 0) {
  375. return socket_errno();
  376. }
  377. int nparse = cli->parser->FeedRecvData(recvbuf, nrecv);
  378. if (nparse != nrecv) {
  379. return ERR_PARSE;
  380. }
  381. } while(!cli->parser->IsComplete());
  382. return err;
  383. }
  384. const char* http_client_strerror(int errcode) {
  385. return socket_strerror(errcode);
  386. }
  387. #endif
  388. static int __http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) {
  389. if (cli->async_client_ == NULL) {
  390. cli->mutex_.lock();
  391. if (cli->async_client_ == NULL) {
  392. cli->async_client_.reset(new hv::AsyncHttpClient);
  393. }
  394. cli->mutex_.unlock();
  395. }
  396. return cli->async_client_->send(req, resp_cb);
  397. }
  398. int http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) {
  399. if (!cli || !req) return ERR_NULL_POINTER;
  400. if (req->url.empty() || *req->url.c_str() == '/') {
  401. req->scheme = cli->https ? "https" : "http";
  402. req->host = cli->host;
  403. req->port = cli->port;
  404. }
  405. if (req->timeout == 0) {
  406. req->timeout = cli->timeout;
  407. }
  408. for (auto& pair : cli->headers) {
  409. if (req->headers.find(pair.first) == req->headers.end()) {
  410. req->headers[pair.first] = pair.second;
  411. }
  412. }
  413. return __http_client_send_async(cli, req, resp_cb);
  414. }
  415. int http_client_send_async(HttpRequestPtr req, HttpResponseCallback resp_cb) {
  416. if (req == NULL) return ERR_NULL_POINTER;
  417. if (req->timeout == 0) {
  418. req->timeout = DEFAULT_HTTP_TIMEOUT;
  419. }
  420. static http_client_t s_default_async_client;
  421. return __http_client_send_async(&s_default_async_client, req, resp_cb);
  422. }