http_client.cpp 17 KB

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