http_client.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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 "hlog.h"
  8. #include "hstring.h"
  9. #include "hsocket.h"
  10. #include "hssl.h"
  11. #include "HttpParser.h"
  12. // for async
  13. #include "AsyncHttpClient.h"
  14. using namespace hv;
  15. struct http_client_s {
  16. std::string host;
  17. int port;
  18. int https;
  19. int timeout; // s
  20. http_headers headers;
  21. // http_proxy
  22. std::string http_proxy_host;
  23. int http_proxy_port;
  24. // https_proxy
  25. std::string https_proxy_host;
  26. int https_proxy_port;
  27. // no_proxy
  28. StringList no_proxy_hosts;
  29. //private:
  30. #ifdef WITH_CURL
  31. CURL* curl;
  32. #endif
  33. // for sync
  34. int fd;
  35. hssl_t ssl;
  36. hssl_ctx_t ssl_ctx;
  37. bool alloced_ssl_ctx;
  38. HttpParserPtr parser;
  39. // for async
  40. std::mutex mutex_;
  41. std::shared_ptr<hv::AsyncHttpClient> async_client_;
  42. http_client_s() {
  43. host = LOCALHOST;
  44. port = DEFAULT_HTTP_PORT;
  45. https = 0;
  46. timeout = DEFAULT_HTTP_TIMEOUT;
  47. #ifdef WITH_CURL
  48. curl = NULL;
  49. #endif
  50. fd = -1;
  51. ssl = NULL;
  52. ssl_ctx = NULL;
  53. alloced_ssl_ctx = false;
  54. }
  55. ~http_client_s() {
  56. Close();
  57. if (ssl_ctx && alloced_ssl_ctx) {
  58. hssl_ctx_free(ssl_ctx);
  59. ssl_ctx = NULL;
  60. }
  61. }
  62. void Close() {
  63. #ifdef WITH_CURL
  64. if (curl) {
  65. curl_easy_cleanup(curl);
  66. curl = NULL;
  67. }
  68. #endif
  69. if (ssl) {
  70. hssl_free(ssl);
  71. ssl = NULL;
  72. }
  73. SAFE_CLOSESOCKET(fd);
  74. }
  75. };
  76. static int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp);
  77. http_client_t* http_client_new(const char* host, int port, int https) {
  78. http_client_t* cli = new http_client_t;
  79. if (host) cli->host = host;
  80. cli->port = port;
  81. cli->https = https;
  82. cli->headers["Connection"] = "keep-alive";
  83. return cli;
  84. }
  85. int http_client_del(http_client_t* cli) {
  86. if (cli == NULL) return 0;
  87. delete cli;
  88. return 0;
  89. }
  90. int http_client_close(http_client_t* cli) {
  91. if (cli == NULL) return 0;
  92. cli->Close();
  93. return 0;
  94. }
  95. int http_client_set_timeout(http_client_t* cli, int timeout) {
  96. cli->timeout = timeout;
  97. return 0;
  98. }
  99. int http_client_set_ssl_ctx(http_client_t* cli, hssl_ctx_t ssl_ctx) {
  100. cli->ssl_ctx = ssl_ctx;
  101. return 0;
  102. }
  103. int http_client_new_ssl_ctx(http_client_t* cli, hssl_ctx_opt_t* opt) {
  104. opt->endpoint = HSSL_CLIENT;
  105. hssl_ctx_t ssl_ctx = hssl_ctx_new(opt);
  106. if (ssl_ctx == NULL) return ERR_NEW_SSL_CTX;
  107. cli->alloced_ssl_ctx = true;
  108. return http_client_set_ssl_ctx(cli, ssl_ctx);
  109. }
  110. int http_client_clear_headers(http_client_t* cli) {
  111. cli->headers.clear();
  112. return 0;
  113. }
  114. int http_client_set_header(http_client_t* cli, const char* key, const char* value) {
  115. cli->headers[key] = value;
  116. return 0;
  117. }
  118. int http_client_del_header(http_client_t* cli, const char* key) {
  119. auto iter = cli->headers.find(key);
  120. if (iter != cli->headers.end()) {
  121. cli->headers.erase(iter);
  122. }
  123. return 0;
  124. }
  125. const char* http_client_get_header(http_client_t* cli, const char* key) {
  126. auto iter = cli->headers.find(key);
  127. if (iter != cli->headers.end()) {
  128. return iter->second.c_str();
  129. }
  130. return NULL;
  131. }
  132. int http_client_set_http_proxy(http_client_t* cli, const char* host, int port) {
  133. cli->http_proxy_host = host;
  134. cli->http_proxy_port = port;
  135. return 0;
  136. }
  137. int http_client_set_https_proxy(http_client_t* cli, const char* host, int port) {
  138. cli->https_proxy_host = host;
  139. cli->https_proxy_port = port;
  140. return 0;
  141. }
  142. int http_client_add_no_proxy(http_client_t* cli, const char* host) {
  143. cli->no_proxy_hosts.push_back(host);
  144. return 0;
  145. }
  146. static int http_client_redirect(HttpRequest* req, HttpResponse* resp) {
  147. std::string location = resp->headers["Location"];
  148. if (!location.empty()) {
  149. hlogi("redirect %s => %s", req->url.c_str(), location.c_str());
  150. req->url = location;
  151. req->ParseUrl();
  152. req->headers["Host"] = req->host;
  153. resp->Reset();
  154. return http_client_send(req, resp);
  155. }
  156. return 0;
  157. }
  158. static int http_client_make_request(http_client_t* cli, HttpRequest* req) {
  159. if (req->url.empty() || *req->url.c_str() == '/') {
  160. req->scheme = cli->https ? "https" : "http";
  161. req->host = cli->host;
  162. req->port = cli->port;
  163. }
  164. bool https = req->IsHttps();
  165. bool use_proxy = https ? (!cli->https_proxy_host.empty()) : (!cli->http_proxy_host.empty());
  166. if (use_proxy) {
  167. if (req->host == "127.0.0.1" || req->host == "localhost") {
  168. use_proxy = false;
  169. }
  170. }
  171. if (use_proxy) {
  172. for (const auto& host : cli->no_proxy_hosts) {
  173. if (req->host == host) {
  174. use_proxy = false;
  175. break;
  176. }
  177. }
  178. }
  179. if (use_proxy) {
  180. req->SetProxy(https ? cli->https_proxy_host.c_str() : cli->http_proxy_host.c_str(),
  181. https ? cli->https_proxy_port : cli->http_proxy_port);
  182. }
  183. if (req->timeout == 0) {
  184. req->timeout = cli->timeout;
  185. }
  186. for (const auto& pair : cli->headers) {
  187. if (req->headers.find(pair.first) == req->headers.end()) {
  188. req->headers.insert(pair);
  189. }
  190. }
  191. return 0;
  192. }
  193. int http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  194. if (!cli || !req || !resp) return ERR_NULL_POINTER;
  195. http_client_make_request(cli, req);
  196. if (req->http_cb) resp->http_cb = std::move(req->http_cb);
  197. int ret = __http_client_send(cli, req, resp);
  198. if (ret != 0) return ret;
  199. // redirect
  200. if (req->redirect && HTTP_STATUS_IS_REDIRECT(resp->status_code)) {
  201. return http_client_redirect(req, resp);
  202. }
  203. return 0;
  204. }
  205. int http_client_send(HttpRequest* req, HttpResponse* resp) {
  206. if (!req || !resp) return ERR_NULL_POINTER;
  207. if (req->timeout == 0) {
  208. req->timeout = DEFAULT_HTTP_TIMEOUT;
  209. }
  210. http_client_t cli;
  211. int ret = __http_client_send(&cli, req, resp);
  212. if (ret != 0) return ret;
  213. // redirect
  214. if (req->redirect && HTTP_STATUS_IS_REDIRECT(resp->status_code)) {
  215. return http_client_redirect(req, resp);
  216. }
  217. return ret;
  218. }
  219. #ifdef WITH_CURL
  220. static size_t s_header_cb(char* buf, size_t size, size_t cnt, void* userdata) {
  221. if (buf == NULL || userdata == NULL) return 0;
  222. size_t len = size * cnt;
  223. std::string str(buf, len);
  224. HttpResponse* resp = (HttpResponse*)userdata;
  225. std::string::size_type pos = str.find_first_of(':');
  226. if (pos == std::string::npos) {
  227. if (strncmp(buf, "HTTP/", 5) == 0) {
  228. // status line
  229. //hlogd("%s", buf);
  230. int http_major,http_minor,status_code;
  231. if (buf[5] == '1') {
  232. // HTTP/1.1 200 OK\r\n
  233. sscanf(buf, "HTTP/%d.%d %d", &http_major, &http_minor, &status_code);
  234. }
  235. else if (buf[5] == '2') {
  236. // HTTP/2 200\r\n
  237. sscanf(buf, "HTTP/%d %d", &http_major, &status_code);
  238. http_minor = 0;
  239. }
  240. resp->http_major = http_major;
  241. resp->http_minor = http_minor;
  242. resp->status_code = (http_status)status_code;
  243. }
  244. }
  245. else {
  246. // headers
  247. std::string key = trim(str.substr(0, pos));
  248. std::string value = trim(str.substr(pos+1));
  249. resp->headers[key] = value;
  250. }
  251. return len;
  252. }
  253. static size_t s_body_cb(char* buf, size_t size, size_t cnt, void *userdata) {
  254. if (buf == NULL || userdata == NULL) return 0;
  255. size_t len = size * cnt;
  256. HttpMessage* resp = (HttpMessage*)userdata;
  257. if (resp->http_cb) {
  258. if (resp->content == NULL && resp->content_length == 0) {
  259. resp->content = buf;
  260. resp->content_length = len;
  261. resp->http_cb(resp, HP_HEADERS_COMPLETE, NULL, 0);
  262. }
  263. resp->http_cb(resp, HP_BODY, buf, len);
  264. } else {
  265. resp->body.append(buf, len);
  266. }
  267. return len;
  268. }
  269. int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  270. if (cli->curl == NULL) {
  271. cli->curl = curl_easy_init();
  272. }
  273. CURL* curl = cli->curl;
  274. // SSL
  275. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  276. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
  277. // http2
  278. if (req->http_major == 2) {
  279. #if LIBCURL_VERSION_NUM < 0x073100 // 7.49.0
  280. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_0);
  281. #else
  282. // No Connection: Upgrade
  283. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE);
  284. #endif
  285. }
  286. // TCP_NODELAY
  287. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  288. // method
  289. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method_str(req->method));
  290. // url
  291. req->DumpUrl();
  292. curl_easy_setopt(curl, CURLOPT_URL, req->url.c_str());
  293. //hlogd("%s %s HTTP/%d.%d", http_method_str(req->method), req->url.c_str(), req->http_major, req->http_minor);
  294. // headers
  295. req->FillContentType();
  296. struct curl_slist *headers = NULL;
  297. for (auto& pair : req->headers) {
  298. std::string header = pair.first;
  299. header += ": ";
  300. header += pair.second;
  301. headers = curl_slist_append(headers, header.c_str());
  302. }
  303. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  304. // body
  305. //struct curl_httppost* httppost = NULL;
  306. //struct curl_httppost* lastpost = NULL;
  307. if (req->body.size() == 0) {
  308. req->DumpBody();
  309. /*
  310. if (req->body.size() == 0 &&
  311. req->content_type == MULTIPART_FORM_DATA) {
  312. for (auto& pair : req->mp) {
  313. if (pair.second.filename.size() != 0) {
  314. curl_formadd(&httppost, &lastpost,
  315. CURLFORM_COPYNAME, pair.first.c_str(),
  316. CURLFORM_FILE, pair.second.filename.c_str(),
  317. CURLFORM_END);
  318. }
  319. else if (pair.second.content.size() != 0) {
  320. curl_formadd(&httppost, &lastpost,
  321. CURLFORM_COPYNAME, pair.first.c_str(),
  322. CURLFORM_COPYCONTENTS, pair.second.content.c_str(),
  323. CURLFORM_END);
  324. }
  325. }
  326. if (httppost) {
  327. curl_easy_setopt(curl, CURLOPT_HTTPPOST, httppost);
  328. }
  329. }
  330. */
  331. }
  332. if (req->body.size() != 0) {
  333. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req->body.c_str());
  334. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req->body.size());
  335. }
  336. if (req->timeout > 0) {
  337. curl_easy_setopt(curl, CURLOPT_TIMEOUT, req->timeout);
  338. }
  339. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, s_body_cb);
  340. curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp);
  341. curl_easy_setopt(curl, CURLOPT_HEADER, 0);
  342. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, s_header_cb);
  343. curl_easy_setopt(curl, CURLOPT_HEADERDATA, resp);
  344. int ret = curl_easy_perform(curl);
  345. /*
  346. if (ret != 0) {
  347. hloge("curl error: %d: %s", ret, curl_easy_strerror((CURLcode)ret));
  348. }
  349. if (resp->body.length() != 0) {
  350. hlogd("[Response]\n%s", resp->body.c_str());
  351. }
  352. double total_time, name_time, conn_time, pre_time;
  353. curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
  354. curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &name_time);
  355. curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &conn_time);
  356. curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &pre_time);
  357. hlogd("TIME_INFO: %lf,%lf,%lf,%lf", total_time, name_time, conn_time, pre_time);
  358. */
  359. if (headers) {
  360. curl_slist_free_all(headers);
  361. }
  362. /*
  363. if (httppost) {
  364. curl_formfree(httppost);
  365. }
  366. */
  367. return ret;
  368. }
  369. const char* http_client_strerror(int errcode) {
  370. return curl_easy_strerror((CURLcode)errcode);
  371. }
  372. #else
  373. static int http_client_connect(http_client_t* cli, const char* host, int port, int https, int timeout) {
  374. int blocktime = DEFAULT_CONNECT_TIMEOUT;
  375. if (timeout > 0) {
  376. blocktime = MIN(timeout*1000, blocktime);
  377. }
  378. int connfd = ConnectTimeout(host, port, blocktime);
  379. if (connfd < 0) {
  380. fprintf(stderr, "* connect %s:%d failed!\n", host, port);
  381. hloge("connect %s:%d failed!", host, port);
  382. return connfd;
  383. }
  384. tcp_nodelay(connfd, 1);
  385. if (https && cli->ssl == NULL) {
  386. // cli->ssl_ctx > g_ssl_ctx > hssl_ctx_new
  387. hssl_ctx_t ssl_ctx = NULL;
  388. if (cli->ssl_ctx) {
  389. ssl_ctx = cli->ssl_ctx;
  390. } else if (g_ssl_ctx) {
  391. ssl_ctx = g_ssl_ctx;
  392. } else {
  393. cli->ssl_ctx = ssl_ctx = hssl_ctx_new(NULL);
  394. cli->alloced_ssl_ctx = true;
  395. }
  396. if (ssl_ctx == NULL) {
  397. closesocket(connfd);
  398. return NABS(ERR_NEW_SSL_CTX);
  399. }
  400. cli->ssl = hssl_new(ssl_ctx, connfd);
  401. if (cli->ssl == NULL) {
  402. closesocket(connfd);
  403. return NABS(ERR_NEW_SSL);
  404. }
  405. if (!is_ipaddr(host)) {
  406. hssl_set_sni_hostname(cli->ssl, host);
  407. }
  408. int ret = hssl_connect(cli->ssl);
  409. if (ret != 0) {
  410. fprintf(stderr, "* ssl handshake failed: %d\n", ret);
  411. hloge("ssl handshake failed: %d", ret);
  412. hssl_free(cli->ssl);
  413. cli->ssl = NULL;
  414. closesocket(connfd);
  415. return NABS(ret);
  416. }
  417. }
  418. cli->fd = connfd;
  419. return connfd;
  420. }
  421. int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  422. // connect -> send -> recv -> http_parser
  423. int err = 0;
  424. int timeout = req->timeout;
  425. int connfd = cli->fd;
  426. bool https = req->IsHttps();
  427. bool keepalive = true;
  428. time_t start_time = time(NULL);
  429. time_t cur_time;
  430. int fail_cnt = 0;
  431. if (connfd <= 0) {
  432. req->ParseUrl();
  433. connect:
  434. connfd = http_client_connect(cli, req->host.c_str(), req->port, https, req->timeout);
  435. if (connfd < 0) {
  436. return connfd;
  437. }
  438. }
  439. if (cli->parser == NULL) {
  440. cli->parser = HttpParserPtr(HttpParser::New(HTTP_CLIENT, (http_version)req->http_major));
  441. }
  442. cli->parser->SubmitRequest(req);
  443. char recvbuf[1024] = {0};
  444. int total_nsend, nsend, nrecv;
  445. total_nsend = nsend = nrecv = 0;
  446. send:
  447. char* data = NULL;
  448. size_t len = 0;
  449. while (cli->parser->GetSendData(&data, &len)) {
  450. total_nsend = 0;
  451. while (total_nsend < len) {
  452. if (timeout > 0) {
  453. cur_time = time(NULL);
  454. if (cur_time - start_time >= timeout) {
  455. return ERR_TASK_TIMEOUT;
  456. }
  457. so_sndtimeo(connfd, (timeout-(cur_time-start_time)) * 1000);
  458. }
  459. if (https) {
  460. nsend = hssl_write(cli->ssl, data+total_nsend, len-total_nsend);
  461. }
  462. else {
  463. nsend = send(connfd, data+total_nsend, len-total_nsend, 0);
  464. }
  465. if (nsend <= 0) {
  466. if (++fail_cnt == 1) {
  467. // maybe keep-alive timeout, try again
  468. cli->Close();
  469. goto connect;
  470. }
  471. else {
  472. err = socket_errno();
  473. goto disconnect;
  474. }
  475. }
  476. total_nsend += nsend;
  477. }
  478. }
  479. cli->parser->InitResponse(resp);
  480. recv:
  481. do {
  482. if (timeout > 0) {
  483. cur_time = time(NULL);
  484. if (cur_time - start_time >= timeout) {
  485. return ERR_TASK_TIMEOUT;
  486. }
  487. so_rcvtimeo(connfd, (timeout-(cur_time-start_time)) * 1000);
  488. }
  489. if (https) {
  490. nrecv = hssl_read(cli->ssl, recvbuf, sizeof(recvbuf));
  491. }
  492. else {
  493. nrecv = recv(connfd, recvbuf, sizeof(recvbuf), 0);
  494. }
  495. if (nrecv <= 0) {
  496. if (resp->content_length == 0 && resp->http_major == 1 && resp->http_minor == 0) {
  497. // HTTP/1.0, assume close after body
  498. goto disconnect;
  499. }
  500. if (++fail_cnt == 1) {
  501. // maybe keep-alive timeout, try again
  502. cli->Close();
  503. goto connect;
  504. }
  505. else {
  506. err = socket_errno();
  507. goto disconnect;
  508. }
  509. }
  510. int nparse = cli->parser->FeedRecvData(recvbuf, nrecv);
  511. if (nparse != nrecv) {
  512. return ERR_PARSE;
  513. }
  514. } while(!cli->parser->IsComplete());
  515. keepalive = req->IsKeepAlive() && resp->IsKeepAlive();
  516. if (!keepalive) {
  517. cli->Close();
  518. }
  519. return 0;
  520. disconnect:
  521. cli->Close();
  522. return err;
  523. }
  524. const char* http_client_strerror(int errcode) {
  525. return socket_strerror(errcode);
  526. }
  527. #endif
  528. static int __http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) {
  529. if (cli->async_client_ == NULL) {
  530. cli->mutex_.lock();
  531. if (cli->async_client_ == NULL) {
  532. cli->async_client_.reset(new hv::AsyncHttpClient);
  533. }
  534. cli->mutex_.unlock();
  535. }
  536. return cli->async_client_->send(req, resp_cb);
  537. }
  538. int http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) {
  539. if (!cli || !req) return ERR_NULL_POINTER;
  540. http_client_make_request(cli, req.get());
  541. return __http_client_send_async(cli, req, resp_cb);
  542. }
  543. static http_client_t* __get_default_async_client();
  544. static void __del_default_async_client();
  545. http_client_t* __get_default_async_client() {
  546. static http_client_t* s_default_async_client = NULL;
  547. static std::mutex s_mutex;
  548. if (s_default_async_client == NULL) {
  549. s_mutex.lock();
  550. if (s_default_async_client == NULL) {
  551. hlogi("create default http async client");
  552. s_default_async_client = http_client_new();
  553. // NOTE: I have No better idea
  554. atexit(__del_default_async_client);
  555. }
  556. s_mutex.unlock();
  557. }
  558. return s_default_async_client;
  559. }
  560. void __del_default_async_client() {
  561. hlogi("destory default http async client");
  562. http_client_del(__get_default_async_client());
  563. }
  564. int http_client_send_async(HttpRequestPtr req, HttpResponseCallback resp_cb) {
  565. if (req == NULL) return ERR_NULL_POINTER;
  566. if (req->timeout == 0) {
  567. req->timeout = DEFAULT_HTTP_TIMEOUT;
  568. }
  569. return __http_client_send_async(__get_default_async_client(), req, resp_cb);
  570. }