1
0

http_client.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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. HttpResponseCallback cb;
  407. void* userdata;
  408. hio_t* io;
  409. htimer_t* timer;
  410. HttpContext() {
  411. io = NULL;
  412. timer = NULL;
  413. cb = NULL;
  414. userdata = NULL;
  415. }
  416. ~HttpContext() {
  417. killTimer();
  418. // keep-alive
  419. // closeIO();
  420. }
  421. void closeIO() {
  422. if (io) {
  423. hio_close(io);
  424. io = NULL;
  425. }
  426. }
  427. void killTimer() {
  428. if (timer) {
  429. htimer_del(timer);
  430. timer = NULL;
  431. }
  432. }
  433. void callback(int state) {
  434. if (cb) {
  435. cb(state, req, resp, userdata);
  436. // NOTE: ensure cb only called once
  437. cb = NULL;
  438. }
  439. }
  440. void successCallback() {
  441. killTimer();
  442. callback(0);
  443. }
  444. void errorCallback(int error) {
  445. closeIO();
  446. callback(error);
  447. }
  448. };
  449. static void on_close(hio_t* io) {
  450. HttpContext* ctx = (HttpContext*)hevent_userdata(io);
  451. if (ctx) {
  452. hevent_set_userdata(io, NULL);
  453. ctx->io = NULL;
  454. int error = hio_error(io);
  455. ctx->callback(error);
  456. delete ctx;
  457. }
  458. }
  459. static void on_recv(hio_t* io, void* buf, int readbytes) {
  460. HttpContext* ctx = (HttpContext*)hevent_userdata(io);
  461. int nparse = ctx->parser->FeedRecvData((const char*)buf, readbytes);
  462. if (nparse != readbytes) {
  463. ctx->errorCallback(ERR_PARSE);
  464. return;
  465. }
  466. if (ctx->parser->IsComplete()) {
  467. ctx->successCallback();
  468. return;
  469. }
  470. }
  471. static void on_connect(hio_t* io) {
  472. HttpContext* ctx = (HttpContext*)hevent_userdata(io);
  473. ctx->parser = HttpParserPtr(HttpParser::New(HTTP_CLIENT, (http_version)ctx->req->http_major));
  474. ctx->parser->InitResponse(ctx->resp.get());
  475. ctx->parser->SubmitRequest(ctx->req.get());
  476. char* data = NULL;
  477. size_t len = 0;
  478. while (ctx->parser->GetSendData(&data, &len)) {
  479. hio_write(io, data, len);
  480. }
  481. hio_setcb_read(io, on_recv);
  482. hio_read(io);
  483. }
  484. static void on_timeout(htimer_t* timer) {
  485. HttpContext* ctx = (HttpContext*)hevent_userdata(timer);
  486. if (ctx) {
  487. hevent_set_userdata(timer, NULL);
  488. ctx->timer = NULL;
  489. ctx->errorCallback(ERR_TASK_TIMEOUT);
  490. }
  491. }
  492. static HTHREAD_ROUTINE(http_client_loop_thread) {
  493. hloop_t* loop = (hloop_t*)userdata;
  494. assert(loop != NULL);
  495. hloop_run(loop);
  496. return 0;
  497. }
  498. // hloop_new -> htread_create -> hloop_run ->
  499. // hio_connect -> on_connect -> hio_write -> hio_read -> on_recv ->
  500. // HttpResponseCallback -> on_close
  501. static int __http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponsePtr resp,
  502. HttpResponseCallback cb, void* userdata) {
  503. sockaddr_u peeraddr;
  504. memset(&peeraddr, 0, sizeof(peeraddr));
  505. req->ParseUrl();
  506. int ret = sockaddr_set_ipport(&peeraddr, req->host.c_str(), req->port);
  507. if (ret != 0) {
  508. return ERR_INVALID_PARAM;
  509. }
  510. int connfd = socket(peeraddr.sa.sa_family, SOCK_STREAM, 0);
  511. if (connfd < 0) {
  512. return ERR_SOCKET;
  513. }
  514. cli->mutex_.lock();
  515. if (cli->loop_ == NULL) {
  516. cli->loop_ = hloop_new(HLOOP_FLAG_AUTO_FREE);
  517. }
  518. if (cli->thread_ == 0) {
  519. cli->thread_ = hthread_create(http_client_loop_thread, cli->loop_);
  520. }
  521. cli->mutex_.unlock();
  522. hio_t* connio = hio_get(cli->loop_, connfd);
  523. assert(connio != NULL);
  524. hio_set_peeraddr(connio, &peeraddr.sa, sockaddr_len(&peeraddr));
  525. hio_setcb_connect(connio, on_connect);
  526. hio_setcb_close(connio, on_close);
  527. // https
  528. if (req->https) {
  529. hio_enable_ssl(connio);
  530. }
  531. // new HttpContext
  532. // delete on_close
  533. HttpContext* ctx = new HttpContext;
  534. ctx->req = req;
  535. ctx->resp = resp;
  536. ctx->cb = cb;
  537. ctx->userdata = userdata;
  538. ctx->io = connio;
  539. hevent_set_userdata(connio, ctx);
  540. // timeout
  541. if (req->timeout > 0) {
  542. ctx->timer = htimer_add(cli->loop_, on_timeout, req->timeout * 1000, 1);
  543. assert(ctx->timer != NULL);
  544. hevent_set_userdata(ctx->timer, ctx);
  545. }
  546. return hio_connect(connio);
  547. }
  548. int http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponsePtr resp,
  549. HttpResponseCallback cb, void* userdata) {
  550. if (!cli || !req || !resp) return ERR_NULL_POINTER;
  551. if (req->url.empty() || *req->url.c_str() == '/') {
  552. req->host = cli->host;
  553. req->port = cli->port;
  554. req->https = cli->https;
  555. }
  556. if (req->timeout == 0) {
  557. req->timeout = cli->timeout;
  558. }
  559. for (auto& pair : cli->headers) {
  560. if (req->headers.find(pair.first) == req->headers.end()) {
  561. req->headers[pair.first] = pair.second;
  562. }
  563. }
  564. return __http_client_send_async(cli, req, resp, cb, userdata);
  565. }
  566. int http_client_send_async(HttpRequestPtr req, HttpResponsePtr resp,
  567. HttpResponseCallback cb, void* userdata) {
  568. if (!req || !resp) return ERR_NULL_POINTER;
  569. if (req->timeout == 0) {
  570. req->timeout = DEFAULT_HTTP_TIMEOUT;
  571. }
  572. static http_client_t s_default_async_client;
  573. return __http_client_send_async(&s_default_async_client, req, resp, cb, userdata);
  574. }