1
0

http_client.cpp 18 KB

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