http_client.cpp 17 KB

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