http_client.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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 "hstring.h"
  8. #include "hsocket.h"
  9. #include "hssl.h"
  10. #include "HttpParser.h"
  11. // for async
  12. #include "hthread.h"
  13. #include "hloop.h"
  14. struct http_client_s {
  15. std::string host;
  16. int port;
  17. int https;
  18. int timeout; // s
  19. http_headers headers;
  20. //private:
  21. #ifdef WITH_CURL
  22. CURL* curl;
  23. #endif
  24. int fd;
  25. // for sync
  26. hssl_t ssl;
  27. HttpParserPtr parser;
  28. // for async
  29. std::mutex mutex_;
  30. hthread_t thread_;
  31. hloop_t* loop_;
  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. thread_ = 0;
  43. loop_ = NULL;
  44. }
  45. ~http_client_s() {
  46. Close();
  47. }
  48. void Close() {
  49. if (loop_) {
  50. hloop_stop(loop_);
  51. loop_ = NULL;
  52. }
  53. if (thread_) {
  54. hthread_join(thread_);
  55. thread_ = 0;
  56. }
  57. #ifdef WITH_CURL
  58. if (curl) {
  59. curl_easy_cleanup(curl);
  60. curl = NULL;
  61. }
  62. #endif
  63. if (ssl) {
  64. hssl_free(ssl);
  65. ssl = NULL;
  66. }
  67. if (fd > 0) {
  68. closesocket(fd);
  69. fd = -1;
  70. }
  71. }
  72. };
  73. static int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp);
  74. http_client_t* http_client_new(const char* host, int port, int https) {
  75. http_client_t* cli = new http_client_t;
  76. if (host) cli->host = host;
  77. cli->port = port;
  78. cli->https = https;
  79. cli->headers["Connection"] = "keep-alive";
  80. return cli;
  81. }
  82. int http_client_del(http_client_t* cli) {
  83. if (cli == NULL) return 0;
  84. delete cli;
  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_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  114. if (!cli || !req || !resp) return ERR_NULL_POINTER;
  115. if (req->url.empty() || *req->url.c_str() == '/') {
  116. req->host = cli->host;
  117. req->port = cli->port;
  118. req->https = cli->https;
  119. }
  120. if (req->timeout == 0) {
  121. req->timeout = cli->timeout;
  122. }
  123. for (auto& pair : cli->headers) {
  124. if (req->headers.find(pair.first) == req->headers.end()) {
  125. req->headers[pair.first] = pair.second;
  126. }
  127. }
  128. return __http_client_send(cli, req, resp);
  129. }
  130. int http_client_send(HttpRequest* req, HttpResponse* resp) {
  131. if (!req || !resp) return ERR_NULL_POINTER;
  132. if (req->timeout == 0) {
  133. req->timeout = DEFAULT_HTTP_TIMEOUT;
  134. }
  135. http_client_t cli;
  136. return __http_client_send(&cli, req, resp);
  137. }
  138. #ifdef WITH_CURL
  139. static size_t s_header_cb(char* buf, size_t size, size_t cnt, void* userdata) {
  140. if (buf == NULL || userdata == NULL) return 0;
  141. HttpResponse* resp = (HttpResponse*)userdata;
  142. std::string str(buf);
  143. std::string::size_type pos = str.find_first_of(':');
  144. if (pos == std::string::npos) {
  145. if (strncmp(buf, "HTTP/", 5) == 0) {
  146. // status line
  147. //hlogd("%s", buf);
  148. int http_major,http_minor,status_code;
  149. if (buf[5] == '1') {
  150. // HTTP/1.1 200 OK\r\n
  151. sscanf(buf, "HTTP/%d.%d %d", &http_major, &http_minor, &status_code);
  152. }
  153. else if (buf[5] == '2') {
  154. // HTTP/2 200\r\n
  155. sscanf(buf, "HTTP/%d %d", &http_major, &status_code);
  156. http_minor = 0;
  157. }
  158. resp->http_major = http_major;
  159. resp->http_minor = http_minor;
  160. resp->status_code = (http_status)status_code;
  161. }
  162. }
  163. else {
  164. // headers
  165. std::string key = trim(str.substr(0, pos));
  166. std::string value = trim(str.substr(pos+1));
  167. resp->headers[key] = value;
  168. }
  169. return size*cnt;
  170. }
  171. static size_t s_body_cb(char *buf, size_t size, size_t cnt, void *userdata) {
  172. if (buf == NULL || userdata == NULL) return 0;
  173. HttpResponse* resp = (HttpResponse*)userdata;
  174. resp->body.append(buf, size*cnt);
  175. return size*cnt;
  176. }
  177. int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  178. if (cli->curl == NULL) {
  179. cli->curl = curl_easy_init();
  180. }
  181. CURL* curl = cli->curl;
  182. // SSL
  183. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  184. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
  185. // http2
  186. if (req->http_major == 2) {
  187. #if LIBCURL_VERSION_NUM < 0x073100 // 7.49.0
  188. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_0);
  189. #else
  190. // No Connection: Upgrade
  191. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE);
  192. #endif
  193. }
  194. // TCP_NODELAY
  195. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  196. // method
  197. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method_str(req->method));
  198. // url
  199. req->DumpUrl();
  200. curl_easy_setopt(curl, CURLOPT_URL, req->url.c_str());
  201. //hlogd("%s %s HTTP/%d.%d", http_method_str(req->method), req->url.c_str(), req->http_major, req->http_minor);
  202. // headers
  203. req->FillContentType();
  204. struct curl_slist *headers = NULL;
  205. for (auto& pair : req->headers) {
  206. std::string header = pair.first;
  207. header += ": ";
  208. header += pair.second;
  209. headers = curl_slist_append(headers, header.c_str());
  210. }
  211. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  212. // body
  213. //struct curl_httppost* httppost = NULL;
  214. //struct curl_httppost* lastpost = NULL;
  215. if (req->body.size() == 0) {
  216. req->DumpBody();
  217. /*
  218. if (req->body.size() == 0 &&
  219. req->content_type == MULTIPART_FORM_DATA) {
  220. for (auto& pair : req->mp) {
  221. if (pair.second.filename.size() != 0) {
  222. curl_formadd(&httppost, &lastpost,
  223. CURLFORM_COPYNAME, pair.first.c_str(),
  224. CURLFORM_FILE, pair.second.filename.c_str(),
  225. CURLFORM_END);
  226. }
  227. else if (pair.second.content.size() != 0) {
  228. curl_formadd(&httppost, &lastpost,
  229. CURLFORM_COPYNAME, pair.first.c_str(),
  230. CURLFORM_COPYCONTENTS, pair.second.content.c_str(),
  231. CURLFORM_END);
  232. }
  233. }
  234. if (httppost) {
  235. curl_easy_setopt(curl, CURLOPT_HTTPPOST, httppost);
  236. }
  237. }
  238. */
  239. }
  240. if (req->body.size() != 0) {
  241. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req->body.c_str());
  242. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req->body.size());
  243. }
  244. if (req->timeout > 0) {
  245. curl_easy_setopt(curl, CURLOPT_TIMEOUT, req->timeout);
  246. }
  247. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, s_body_cb);
  248. curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp);
  249. curl_easy_setopt(curl, CURLOPT_HEADER, 0);
  250. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, s_header_cb);
  251. curl_easy_setopt(curl, CURLOPT_HEADERDATA, resp);
  252. int ret = curl_easy_perform(curl);
  253. /*
  254. if (ret != 0) {
  255. hloge("curl error: %d: %s", ret, curl_easy_strerror((CURLcode)ret));
  256. }
  257. if (resp->body.length() != 0) {
  258. hlogd("[Response]\n%s", resp->body.c_str());
  259. }
  260. double total_time, name_time, conn_time, pre_time;
  261. curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
  262. curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &name_time);
  263. curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &conn_time);
  264. curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &pre_time);
  265. hlogd("TIME_INFO: %lf,%lf,%lf,%lf", total_time, name_time, conn_time, pre_time);
  266. */
  267. if (headers) {
  268. curl_slist_free_all(headers);
  269. }
  270. /*
  271. if (httppost) {
  272. curl_formfree(httppost);
  273. }
  274. */
  275. return ret;
  276. }
  277. const char* http_client_strerror(int errcode) {
  278. return curl_easy_strerror((CURLcode)errcode);
  279. }
  280. #else
  281. static int __http_client_connect(http_client_t* cli, HttpRequest* req) {
  282. int blocktime = DEFAULT_CONNECT_TIMEOUT;
  283. if (req->timeout > 0) {
  284. blocktime = MIN(req->timeout*1000, blocktime);
  285. }
  286. req->ParseUrl();
  287. int connfd = ConnectTimeout(req->host.c_str(), req->port, blocktime);
  288. if (connfd < 0) {
  289. return connfd;
  290. }
  291. tcp_nodelay(connfd, 1);
  292. if (req->https) {
  293. if (hssl_ctx_instance() == NULL) {
  294. hssl_ctx_init(NULL);
  295. }
  296. hssl_ctx_t ssl_ctx = hssl_ctx_instance();
  297. if (ssl_ctx == NULL) {
  298. closesocket(connfd);
  299. return ERR_INVALID_PROTOCOL;
  300. }
  301. cli->ssl = hssl_new(ssl_ctx, connfd);
  302. int ret = hssl_connect(cli->ssl);
  303. if (ret != 0) {
  304. fprintf(stderr, "SSL handshark failed: %d\n", ret);
  305. hssl_free(cli->ssl);
  306. cli->ssl = NULL;
  307. closesocket(connfd);
  308. return ret;
  309. }
  310. }
  311. if (cli->parser == NULL) {
  312. cli->parser = HttpParserPtr(HttpParser::New(HTTP_CLIENT, (http_version)req->http_major));
  313. }
  314. cli->fd = connfd;
  315. return 0;
  316. }
  317. int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  318. // connect -> send -> recv -> http_parser
  319. int err = 0;
  320. int timeout = req->timeout;
  321. int connfd = cli->fd;
  322. time_t start_time = time(NULL);
  323. time_t cur_time;
  324. int fail_cnt = 0;
  325. connect:
  326. if (connfd <= 0) {
  327. int ret = __http_client_connect(cli, req);
  328. if (ret != 0) {
  329. return ret;
  330. }
  331. connfd = cli->fd;
  332. }
  333. cli->parser->SubmitRequest(req);
  334. char recvbuf[1024] = {0};
  335. int total_nsend, nsend, nrecv;
  336. total_nsend = nsend = nrecv = 0;
  337. send:
  338. char* data = NULL;
  339. size_t len = 0;
  340. while (cli->parser->GetSendData(&data, &len)) {
  341. total_nsend = 0;
  342. while (1) {
  343. if (timeout > 0) {
  344. cur_time = time(NULL);
  345. if (cur_time - start_time >= timeout) {
  346. return ERR_TASK_TIMEOUT;
  347. }
  348. so_sndtimeo(connfd, (timeout-(cur_time-start_time)) * 1000);
  349. }
  350. if (req->https) {
  351. nsend = hssl_write(cli->ssl, data+total_nsend, len-total_nsend);
  352. }
  353. else {
  354. nsend = send(connfd, data+total_nsend, len-total_nsend, 0);
  355. }
  356. if (nsend <= 0) {
  357. if (++fail_cnt == 1) {
  358. // maybe keep-alive timeout, try again
  359. cli->Close();
  360. goto connect;
  361. }
  362. else {
  363. return socket_errno();
  364. }
  365. }
  366. total_nsend += nsend;
  367. if (total_nsend == len) {
  368. break;
  369. }
  370. }
  371. }
  372. cli->parser->InitResponse(resp);
  373. recv:
  374. do {
  375. if (timeout > 0) {
  376. cur_time = time(NULL);
  377. if (cur_time - start_time >= timeout) {
  378. return ERR_TASK_TIMEOUT;
  379. }
  380. so_rcvtimeo(connfd, (timeout-(cur_time-start_time)) * 1000);
  381. }
  382. if (req->https) {
  383. nrecv = hssl_read(cli->ssl, recvbuf, sizeof(recvbuf));
  384. }
  385. else {
  386. nrecv = recv(connfd, recvbuf, sizeof(recvbuf), 0);
  387. }
  388. if (nrecv <= 0) {
  389. return socket_errno();
  390. }
  391. int nparse = cli->parser->FeedRecvData(recvbuf, nrecv);
  392. if (nparse != nrecv) {
  393. return ERR_PARSE;
  394. }
  395. } while(!cli->parser->IsComplete());
  396. return err;
  397. }
  398. const char* http_client_strerror(int errcode) {
  399. return socket_strerror(errcode);
  400. }
  401. #endif
  402. struct HttpContext {
  403. HttpRequestPtr req;
  404. HttpResponsePtr resp;
  405. HttpParserPtr parser;
  406. hio_t* io;
  407. htimer_t* timer;
  408. HttpResponseCallback cb;
  409. void* userdata;
  410. HttpContext() {
  411. io = NULL;
  412. timer = NULL;
  413. cb = NULL;
  414. userdata = NULL;
  415. }
  416. ~HttpContext() {
  417. killTimer();
  418. }
  419. void closeIO() {
  420. if (io) {
  421. hio_close(io);
  422. io = NULL;
  423. }
  424. }
  425. void killTimer() {
  426. if (timer) {
  427. htimer_del(timer);
  428. timer = NULL;
  429. }
  430. }
  431. void callback(int state) {
  432. if (cb) {
  433. cb(state, req, resp, userdata);
  434. // NOTE: ensure cb only called once
  435. cb = NULL;
  436. }
  437. }
  438. void successCallback() {
  439. killTimer();
  440. callback(0);
  441. }
  442. void errorCallback(int error) {
  443. closeIO();
  444. callback(error);
  445. }
  446. };
  447. static void on_close(hio_t* io) {
  448. HttpContext* ctx = (HttpContext*)hevent_userdata(io);
  449. if (ctx) {
  450. int error = hio_error(io);
  451. ctx->callback(error);
  452. delete ctx;
  453. hevent_set_userdata(io, NULL);
  454. }
  455. }
  456. static void on_recv(hio_t* io, void* buf, int readbytes) {
  457. HttpContext* ctx = (HttpContext*)hevent_userdata(io);
  458. int nparse = ctx->parser->FeedRecvData((const char*)buf, readbytes);
  459. if (nparse != readbytes) {
  460. ctx->errorCallback(ERR_PARSE);
  461. return;
  462. }
  463. if (ctx->parser->IsComplete()) {
  464. ctx->successCallback();
  465. return;
  466. }
  467. }
  468. static void on_connect(hio_t* io) {
  469. HttpContext* ctx = (HttpContext*)hevent_userdata(io);
  470. ctx->parser = HttpParserPtr(HttpParser::New(HTTP_CLIENT, (http_version)ctx->req->http_major));
  471. ctx->parser->InitResponse(ctx->resp.get());
  472. ctx->parser->SubmitRequest(ctx->req.get());
  473. char* data = NULL;
  474. size_t len = 0;
  475. while (ctx->parser->GetSendData(&data, &len)) {
  476. hio_write(io, data, len);
  477. }
  478. hio_setcb_read(io, on_recv);
  479. hio_read(io);
  480. }
  481. static void on_timeout(htimer_t* timer) {
  482. HttpContext* ctx = (HttpContext*)hevent_userdata(timer);
  483. ctx->errorCallback(ERR_TASK_TIMEOUT);
  484. }
  485. static HTHREAD_ROUTINE(http_client_loop_thread) {
  486. hloop_t* loop = (hloop_t*)userdata;
  487. assert(loop != NULL);
  488. hloop_run(loop);
  489. return 0;
  490. }
  491. // hloop_new -> htread_create -> hloop_run ->
  492. // hio_connect -> on_connect -> hio_write -> hio_read -> on_recv ->
  493. // HttpResponseCallback -> on_close
  494. static int __http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponsePtr resp,
  495. HttpResponseCallback cb, void* userdata) {
  496. sockaddr_u peeraddr;
  497. memset(&peeraddr, 0, sizeof(peeraddr));
  498. req->ParseUrl();
  499. int ret = sockaddr_set_ipport(&peeraddr, req->host.c_str(), req->port);
  500. if (ret != 0) {
  501. return ERR_INVALID_PARAM;
  502. }
  503. int connfd = socket(peeraddr.sa.sa_family, SOCK_STREAM, 0);
  504. if (connfd < 0) {
  505. return ERR_SOCKET;
  506. }
  507. cli->mutex_.lock();
  508. if (cli->loop_ == NULL) {
  509. cli->loop_ = hloop_new(HLOOP_FLAG_AUTO_FREE);
  510. }
  511. if (cli->thread_ == 0) {
  512. cli->thread_ = hthread_create(http_client_loop_thread, cli->loop_);
  513. }
  514. cli->mutex_.unlock();
  515. hio_t* connio = hio_get(cli->loop_, connfd);
  516. assert(connio != NULL);
  517. hio_set_peeraddr(connio, &peeraddr.sa, sockaddr_len(&peeraddr));
  518. hio_setcb_connect(connio, on_connect);
  519. hio_setcb_close(connio, on_close);
  520. // https
  521. if (req->https) {
  522. hio_enable_ssl(connio);
  523. }
  524. // new HttpContext
  525. // delete on_close
  526. HttpContext* ctx = new HttpContext;
  527. ctx->io = connio;
  528. ctx->req = req;
  529. ctx->resp = resp;
  530. ctx->cb = cb;
  531. ctx->userdata = userdata;
  532. hevent_set_userdata(connio, ctx);
  533. // timeout
  534. if (req->timeout > 0) {
  535. ctx->timer = htimer_add(cli->loop_, on_timeout, req->timeout * 1000, 1);
  536. assert(ctx->timer != NULL);
  537. hevent_set_userdata(ctx->timer, ctx);
  538. }
  539. return hio_connect(connio);
  540. }
  541. int http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponsePtr resp,
  542. HttpResponseCallback cb, void* userdata) {
  543. if (!cli || !req || !resp) return ERR_NULL_POINTER;
  544. if (req->url.empty() || *req->url.c_str() == '/') {
  545. req->host = cli->host;
  546. req->port = cli->port;
  547. req->https = cli->https;
  548. }
  549. if (req->timeout == 0) {
  550. req->timeout = cli->timeout;
  551. }
  552. for (auto& pair : cli->headers) {
  553. if (req->headers.find(pair.first) == req->headers.end()) {
  554. req->headers[pair.first] = pair.second;
  555. }
  556. }
  557. return __http_client_send_async(cli, req, resp, cb, userdata);
  558. }
  559. int http_client_send_async(HttpRequestPtr req, HttpResponsePtr resp,
  560. HttpResponseCallback cb, void* userdata) {
  561. if (!req || !resp) return ERR_NULL_POINTER;
  562. if (req->timeout == 0) {
  563. req->timeout = DEFAULT_HTTP_TIMEOUT;
  564. }
  565. static http_client_t s_default_async_client;
  566. return __http_client_send_async(&s_default_async_client, req, resp, cb, userdata);
  567. }