http_client.cpp 15 KB

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