http_client.cpp 16 KB

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