http_client.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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. // proxy
  275. if (req->IsProxy()) {
  276. curl_easy_setopt(curl, CURLOPT_PROXY, req->host.c_str());
  277. curl_easy_setopt(curl, CURLOPT_PROXYPORT, req->port);
  278. }
  279. // SSL
  280. if (req->IsHttps()) {
  281. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  282. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
  283. }
  284. // http2
  285. if (req->http_major == 2) {
  286. #if LIBCURL_VERSION_NUM < 0x073100 // 7.49.0
  287. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_0);
  288. #else
  289. // No Connection: Upgrade
  290. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE);
  291. #endif
  292. }
  293. // TCP_NODELAY
  294. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  295. // method
  296. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method_str(req->method));
  297. // url
  298. req->DumpUrl();
  299. curl_easy_setopt(curl, CURLOPT_URL, req->url.c_str());
  300. //hlogd("%s %s HTTP/%d.%d", http_method_str(req->method), req->url.c_str(), req->http_major, req->http_minor);
  301. // headers
  302. req->FillContentType();
  303. struct curl_slist *headers = NULL;
  304. for (auto& pair : req->headers) {
  305. std::string header = pair.first;
  306. header += ": ";
  307. header += pair.second;
  308. headers = curl_slist_append(headers, header.c_str());
  309. }
  310. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  311. // body
  312. //struct curl_httppost* httppost = NULL;
  313. //struct curl_httppost* lastpost = NULL;
  314. if (req->body.size() == 0) {
  315. req->DumpBody();
  316. /*
  317. if (req->body.size() == 0 &&
  318. req->content_type == MULTIPART_FORM_DATA) {
  319. for (auto& pair : req->mp) {
  320. if (pair.second.filename.size() != 0) {
  321. curl_formadd(&httppost, &lastpost,
  322. CURLFORM_COPYNAME, pair.first.c_str(),
  323. CURLFORM_FILE, pair.second.filename.c_str(),
  324. CURLFORM_END);
  325. }
  326. else if (pair.second.content.size() != 0) {
  327. curl_formadd(&httppost, &lastpost,
  328. CURLFORM_COPYNAME, pair.first.c_str(),
  329. CURLFORM_COPYCONTENTS, pair.second.content.c_str(),
  330. CURLFORM_END);
  331. }
  332. }
  333. if (httppost) {
  334. curl_easy_setopt(curl, CURLOPT_HTTPPOST, httppost);
  335. }
  336. }
  337. */
  338. }
  339. if (req->body.size() != 0) {
  340. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req->body.c_str());
  341. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req->body.size());
  342. }
  343. if (req->timeout > 0) {
  344. curl_easy_setopt(curl, CURLOPT_TIMEOUT, req->timeout);
  345. }
  346. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, s_body_cb);
  347. curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp);
  348. curl_easy_setopt(curl, CURLOPT_HEADER, 0);
  349. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, s_header_cb);
  350. curl_easy_setopt(curl, CURLOPT_HEADERDATA, resp);
  351. int ret = curl_easy_perform(curl);
  352. /*
  353. if (ret != 0) {
  354. hloge("curl error: %d: %s", ret, curl_easy_strerror((CURLcode)ret));
  355. }
  356. if (resp->body.length() != 0) {
  357. hlogd("[Response]\n%s", resp->body.c_str());
  358. }
  359. double total_time, name_time, conn_time, pre_time;
  360. curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
  361. curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &name_time);
  362. curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &conn_time);
  363. curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &pre_time);
  364. hlogd("TIME_INFO: %lf,%lf,%lf,%lf", total_time, name_time, conn_time, pre_time);
  365. */
  366. if (headers) {
  367. curl_slist_free_all(headers);
  368. }
  369. /*
  370. if (httppost) {
  371. curl_formfree(httppost);
  372. }
  373. */
  374. return ret;
  375. }
  376. const char* http_client_strerror(int errcode) {
  377. return curl_easy_strerror((CURLcode)errcode);
  378. }
  379. #else
  380. static int http_client_connect(http_client_t* cli, const char* host, int port, int https, int timeout) {
  381. int blocktime = DEFAULT_CONNECT_TIMEOUT;
  382. if (timeout > 0) {
  383. blocktime = MIN(timeout*1000, blocktime);
  384. }
  385. int connfd = ConnectTimeout(host, port, blocktime);
  386. if (connfd < 0) {
  387. fprintf(stderr, "* connect %s:%d failed!\n", host, port);
  388. hloge("connect %s:%d failed!", host, port);
  389. return connfd;
  390. }
  391. tcp_nodelay(connfd, 1);
  392. if (https && cli->ssl == NULL) {
  393. // cli->ssl_ctx > g_ssl_ctx > hssl_ctx_new
  394. hssl_ctx_t ssl_ctx = NULL;
  395. if (cli->ssl_ctx) {
  396. ssl_ctx = cli->ssl_ctx;
  397. } else if (g_ssl_ctx) {
  398. ssl_ctx = g_ssl_ctx;
  399. } else {
  400. cli->ssl_ctx = ssl_ctx = hssl_ctx_new(NULL);
  401. cli->alloced_ssl_ctx = true;
  402. }
  403. if (ssl_ctx == NULL) {
  404. closesocket(connfd);
  405. return NABS(ERR_NEW_SSL_CTX);
  406. }
  407. cli->ssl = hssl_new(ssl_ctx, connfd);
  408. if (cli->ssl == NULL) {
  409. closesocket(connfd);
  410. return NABS(ERR_NEW_SSL);
  411. }
  412. if (!is_ipaddr(host)) {
  413. hssl_set_sni_hostname(cli->ssl, host);
  414. }
  415. int ret = hssl_connect(cli->ssl);
  416. if (ret != 0) {
  417. fprintf(stderr, "* ssl handshake failed: %d\n", ret);
  418. hloge("ssl handshake failed: %d", ret);
  419. hssl_free(cli->ssl);
  420. cli->ssl = NULL;
  421. closesocket(connfd);
  422. return NABS(ret);
  423. }
  424. }
  425. cli->fd = connfd;
  426. return connfd;
  427. }
  428. int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  429. // connect -> send -> recv -> http_parser
  430. int err = 0;
  431. int timeout = req->timeout;
  432. int connfd = cli->fd;
  433. bool https = req->IsHttps() && !req->IsProxy();
  434. bool keepalive = true;
  435. time_t start_time = time(NULL);
  436. time_t cur_time;
  437. int fail_cnt = 0;
  438. if (connfd <= 0) {
  439. req->ParseUrl();
  440. connect:
  441. connfd = http_client_connect(cli, req->host.c_str(), req->port, https, req->timeout);
  442. if (connfd < 0) {
  443. return connfd;
  444. }
  445. }
  446. if (cli->parser == NULL) {
  447. cli->parser = HttpParserPtr(HttpParser::New(HTTP_CLIENT, (http_version)req->http_major));
  448. }
  449. cli->parser->SubmitRequest(req);
  450. char recvbuf[1024] = {0};
  451. int total_nsend, nsend, nrecv;
  452. total_nsend = nsend = nrecv = 0;
  453. send:
  454. char* data = NULL;
  455. size_t len = 0;
  456. while (cli->parser->GetSendData(&data, &len)) {
  457. total_nsend = 0;
  458. while (total_nsend < len) {
  459. if (timeout > 0) {
  460. cur_time = time(NULL);
  461. if (cur_time - start_time >= timeout) {
  462. return ERR_TASK_TIMEOUT;
  463. }
  464. so_sndtimeo(connfd, (timeout-(cur_time-start_time)) * 1000);
  465. }
  466. if (https) {
  467. nsend = hssl_write(cli->ssl, data+total_nsend, len-total_nsend);
  468. }
  469. else {
  470. nsend = send(connfd, data+total_nsend, len-total_nsend, 0);
  471. }
  472. if (nsend <= 0) {
  473. if (++fail_cnt == 1) {
  474. // maybe keep-alive timeout, try again
  475. cli->Close();
  476. goto connect;
  477. }
  478. else {
  479. err = socket_errno();
  480. goto disconnect;
  481. }
  482. }
  483. total_nsend += nsend;
  484. }
  485. }
  486. cli->parser->InitResponse(resp);
  487. recv:
  488. do {
  489. if (timeout > 0) {
  490. cur_time = time(NULL);
  491. if (cur_time - start_time >= timeout) {
  492. return ERR_TASK_TIMEOUT;
  493. }
  494. so_rcvtimeo(connfd, (timeout-(cur_time-start_time)) * 1000);
  495. }
  496. if (https) {
  497. nrecv = hssl_read(cli->ssl, recvbuf, sizeof(recvbuf));
  498. }
  499. else {
  500. nrecv = recv(connfd, recvbuf, sizeof(recvbuf), 0);
  501. }
  502. if (nrecv <= 0) {
  503. if (resp->content_length == 0 && resp->http_major == 1 && resp->http_minor == 0) {
  504. // HTTP/1.0, assume close after body
  505. goto disconnect;
  506. }
  507. if (++fail_cnt == 1) {
  508. // maybe keep-alive timeout, try again
  509. cli->Close();
  510. goto connect;
  511. }
  512. else {
  513. err = socket_errno();
  514. goto disconnect;
  515. }
  516. }
  517. int nparse = cli->parser->FeedRecvData(recvbuf, nrecv);
  518. if (nparse != nrecv) {
  519. return ERR_PARSE;
  520. }
  521. } while(!cli->parser->IsComplete());
  522. keepalive = req->IsKeepAlive() && resp->IsKeepAlive();
  523. if (!keepalive) {
  524. cli->Close();
  525. }
  526. return 0;
  527. disconnect:
  528. cli->Close();
  529. return err;
  530. }
  531. const char* http_client_strerror(int errcode) {
  532. return socket_strerror(errcode);
  533. }
  534. #endif
  535. static int __http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) {
  536. if (cli->async_client_ == NULL) {
  537. cli->mutex_.lock();
  538. if (cli->async_client_ == NULL) {
  539. cli->async_client_.reset(new hv::AsyncHttpClient);
  540. }
  541. cli->mutex_.unlock();
  542. }
  543. return cli->async_client_->send(req, resp_cb);
  544. }
  545. int http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) {
  546. if (!cli || !req) return ERR_NULL_POINTER;
  547. http_client_make_request(cli, req.get());
  548. return __http_client_send_async(cli, req, resp_cb);
  549. }
  550. static http_client_t* __get_default_async_client();
  551. static void __del_default_async_client();
  552. http_client_t* __get_default_async_client() {
  553. static http_client_t* s_default_async_client = NULL;
  554. static std::mutex s_mutex;
  555. if (s_default_async_client == NULL) {
  556. s_mutex.lock();
  557. if (s_default_async_client == NULL) {
  558. hlogi("create default http async client");
  559. s_default_async_client = http_client_new();
  560. // NOTE: I have No better idea
  561. atexit(__del_default_async_client);
  562. }
  563. s_mutex.unlock();
  564. }
  565. return s_default_async_client;
  566. }
  567. void __del_default_async_client() {
  568. hlogi("destory default http async client");
  569. http_client_del(__get_default_async_client());
  570. }
  571. int http_client_send_async(HttpRequestPtr req, HttpResponseCallback resp_cb) {
  572. if (req == NULL) return ERR_NULL_POINTER;
  573. if (req->timeout == 0) {
  574. req->timeout = DEFAULT_HTTP_TIMEOUT;
  575. }
  576. return __http_client_send_async(__get_default_async_client(), req, resp_cb);
  577. }