http_client.cpp 15 KB

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