1
0

http_client.cpp 18 KB

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