1
0

http_client.cpp 17 KB

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