1
0

http_client.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #include "http_client.h"
  2. #include "hstring.h"
  3. #define MAX_CONNECT_TIMEOUT 3000 // ms
  4. #ifdef WITH_CURL
  5. #include "curl/curl.h"
  6. #else
  7. #include "herr.h"
  8. #include "hsocket.h"
  9. #include "HttpSession.h"
  10. #include "ssl_ctx.h"
  11. #endif
  12. #ifdef WITH_OPENSSL
  13. #include "openssl/ssl.h"
  14. #endif
  15. struct http_client_s {
  16. std::string host;
  17. int port;
  18. int tls;
  19. int http_version;
  20. int timeout; // s
  21. http_headers headers;
  22. //private:
  23. #ifdef WITH_CURL
  24. CURL* curl;
  25. #else
  26. int fd;
  27. HttpSession* session;
  28. #endif
  29. #ifdef WITH_OPENSSL
  30. SSL* ssl;
  31. #endif
  32. http_client_s() {
  33. port = DEFAULT_HTTP_PORT;
  34. tls = 0;
  35. http_version = 1;
  36. timeout = DEFAULT_HTTP_TIMEOUT;
  37. #ifdef WITH_CURL
  38. curl = NULL;
  39. #else
  40. fd = -1;
  41. session = NULL;
  42. #endif
  43. #ifdef WITH_OPENSSL
  44. ssl = NULL;
  45. #endif
  46. }
  47. ~http_client_s() {
  48. Close();
  49. }
  50. void Close() {
  51. #ifdef WITH_OPENSSL
  52. if (ssl) {
  53. SSL_free(ssl);
  54. ssl = NULL;
  55. }
  56. #endif
  57. #ifdef WITH_CURL
  58. if (curl) {
  59. curl_easy_cleanup(curl);
  60. curl = NULL;
  61. }
  62. #else
  63. if (fd > 0) {
  64. closesocket(fd);
  65. fd = -1;
  66. }
  67. if (session) {
  68. delete session;
  69. session = NULL;
  70. }
  71. #endif
  72. }
  73. };
  74. static int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* res);
  75. http_client_t* http_client_new(const char* host, int port, int tls) {
  76. http_client_t* cli = new http_client_t;
  77. cli->tls = tls;
  78. cli->port = port;
  79. if (host) {
  80. cli->host = host;
  81. cli->headers["Host"] = asprintf("%s:%d", host, port);
  82. }
  83. cli->headers["Connection"] = "keep-alive";
  84. return cli;
  85. }
  86. int http_client_del(http_client_t* cli) {
  87. if (cli == NULL) return 0;
  88. delete cli;
  89. return 0;
  90. }
  91. int http_client_set_timeout(http_client_t* cli, int timeout) {
  92. cli->timeout = timeout;
  93. return 0;
  94. }
  95. int http_client_clear_headers(http_client_t* cli) {
  96. cli->headers.clear();
  97. return 0;
  98. }
  99. int http_client_set_header(http_client_t* cli, const char* key, const char* value) {
  100. cli->headers[key] = value;
  101. return 0;
  102. }
  103. int http_client_del_header(http_client_t* cli, const char* key) {
  104. auto iter = cli->headers.find(key);
  105. if (iter != cli->headers.end()) {
  106. cli->headers.erase(iter);
  107. }
  108. return 0;
  109. }
  110. const char* http_client_get_header(http_client_t* cli, const char* key) {
  111. auto iter = cli->headers.find(key);
  112. if (iter != cli->headers.end()) {
  113. return iter->second.c_str();
  114. }
  115. return NULL;
  116. }
  117. int http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* res) {
  118. for (auto& pair : cli->headers) {
  119. req->headers[pair.first] = pair.second;
  120. }
  121. return __http_client_send(cli, req, res);
  122. }
  123. int http_client_send(HttpRequest* req, HttpResponse* res, int timeout) {
  124. http_client_t cli;
  125. cli.timeout = timeout;
  126. return __http_client_send(&cli, req, res);
  127. }
  128. #ifdef WITH_CURL
  129. static size_t s_header_cb(char* buf, size_t size, size_t cnt, void* userdata) {
  130. if (buf == NULL || userdata == NULL) return 0;
  131. HttpResponse* res = (HttpResponse*)userdata;
  132. string str(buf);
  133. string::size_type pos = str.find_first_of(':');
  134. if (pos == string::npos) {
  135. if (strncmp(buf, "HTTP/", 5) == 0) {
  136. // status line
  137. //hlogd("%s", buf);
  138. int http_major,http_minor,status_code;
  139. if (buf[5] == '1') {
  140. // HTTP/1.1 200 OK\r\n
  141. sscanf(buf, "HTTP/%d.%d %d", &http_major, &http_minor, &status_code);
  142. }
  143. else if (buf[5] == '2') {
  144. // HTTP/2 200\r\n
  145. sscanf(buf, "HTTP/%d %d", &http_major, &status_code);
  146. http_minor = 0;
  147. }
  148. res->http_major = http_major;
  149. res->http_minor = http_minor;
  150. res->status_code = (http_status)status_code;
  151. }
  152. }
  153. else {
  154. // headers
  155. string key = trim(str.substr(0, pos));
  156. string value = trim(str.substr(pos+1));
  157. res->headers[key] = value;
  158. }
  159. return size*cnt;
  160. }
  161. static size_t s_body_cb(char *buf, size_t size, size_t cnt, void *userdata) {
  162. if (buf == NULL || userdata == NULL) return 0;
  163. HttpResponse* res = (HttpResponse*)userdata;
  164. res->body.append(buf, size*cnt);
  165. return size*cnt;
  166. }
  167. int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* res) {
  168. if (req == NULL || res == NULL) {
  169. return -1;
  170. }
  171. if (cli->curl == NULL) {
  172. cli->curl = curl_easy_init();
  173. }
  174. CURL* curl = cli->curl;
  175. // SSL
  176. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  177. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
  178. // http2
  179. if (req->http_major == 2) {
  180. //curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_0);
  181. //No Connection: Upgrade
  182. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE);
  183. }
  184. // TCP_NODELAY
  185. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  186. // method
  187. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method_str(req->method));
  188. // url
  189. req->DumpUrl();
  190. curl_easy_setopt(curl, CURLOPT_URL, req->url.c_str());
  191. //hlogd("%s %s HTTP/%d.%d", http_method_str(req->method), req->url.c_str(), req->http_major, req->http_minor);
  192. // headers
  193. req->FillContentType();
  194. struct curl_slist *headers = NULL;
  195. for (auto& pair : req->headers) {
  196. string header = pair.first;
  197. header += ": ";
  198. header += pair.second;
  199. headers = curl_slist_append(headers, header.c_str());
  200. }
  201. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  202. // body
  203. struct curl_httppost* httppost = NULL;
  204. struct curl_httppost* lastpost = NULL;
  205. if (req->body.size() == 0) {
  206. req->DumpBody();
  207. if (req->body.size() == 0 &&
  208. req->content_type == MULTIPART_FORM_DATA) {
  209. for (auto& pair : req->mp) {
  210. if (pair.second.filename.size() != 0) {
  211. curl_formadd(&httppost, &lastpost,
  212. CURLFORM_COPYNAME, pair.first.c_str(),
  213. CURLFORM_FILE, pair.second.filename.c_str(),
  214. CURLFORM_END);
  215. }
  216. else if (pair.second.content.size() != 0) {
  217. curl_formadd(&httppost, &lastpost,
  218. CURLFORM_COPYNAME, pair.first.c_str(),
  219. CURLFORM_COPYCONTENTS, pair.second.content.c_str(),
  220. CURLFORM_END);
  221. }
  222. }
  223. if (httppost) {
  224. curl_easy_setopt(curl, CURLOPT_HTTPPOST, httppost);
  225. }
  226. }
  227. }
  228. if (req->body.size() != 0) {
  229. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req->body.c_str());
  230. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req->body.size());
  231. }
  232. if (cli->timeout > 0) {
  233. curl_easy_setopt(curl, CURLOPT_TIMEOUT, cli->timeout);
  234. }
  235. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, s_body_cb);
  236. curl_easy_setopt(curl, CURLOPT_WRITEDATA, res);
  237. curl_easy_setopt(curl, CURLOPT_HEADER, 0);
  238. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, s_header_cb);
  239. curl_easy_setopt(curl, CURLOPT_HEADERDATA, res);
  240. int ret = curl_easy_perform(curl);
  241. /*
  242. if (ret != 0) {
  243. hloge("curl error: %d: %s", ret, curl_easy_strerror((CURLcode)ret));
  244. }
  245. if (res->body.length() != 0) {
  246. hlogd("[Response]\n%s", res->body.c_str());
  247. }
  248. double total_time, name_time, conn_time, pre_time;
  249. curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
  250. curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &name_time);
  251. curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &conn_time);
  252. curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &pre_time);
  253. hlogd("TIME_INFO: %lf,%lf,%lf,%lf", total_time, name_time, conn_time, pre_time);
  254. */
  255. if (headers) {
  256. curl_slist_free_all(headers);
  257. }
  258. if (httppost) {
  259. curl_formfree(httppost);
  260. }
  261. return ret;
  262. }
  263. const char* http_client_strerror(int errcode) {
  264. return curl_easy_strerror((CURLcode)errcode);
  265. }
  266. #else
  267. static int __http_client_connect(http_client_t* cli) {
  268. int blocktime = MAX_CONNECT_TIMEOUT;
  269. if (cli->timeout > 0) {
  270. blocktime = MIN(cli->timeout*1000, blocktime);
  271. }
  272. int connfd = ConnectTimeout(cli->host.c_str(), cli->port, blocktime);
  273. if (connfd < 0) {
  274. return socket_errno();
  275. }
  276. tcp_nodelay(connfd, 1);
  277. if (cli->tls) {
  278. #ifdef WITH_OPENSSL
  279. if (g_ssl_ctx == NULL) {
  280. ssl_ctx_init(NULL, NULL, NULL);
  281. }
  282. cli->ssl = SSL_new((SSL_CTX*)g_ssl_ctx);
  283. SSL_set_fd(cli->ssl, connfd);
  284. if (SSL_connect(cli->ssl) != 1) {
  285. int err = SSL_get_error(cli->ssl, -1);
  286. fprintf(stderr, "SSL handshark failed: %d\n", err);
  287. SSL_free(cli->ssl);
  288. cli->ssl = NULL;
  289. closesocket(connfd);
  290. return err;
  291. }
  292. #else
  293. fprintf(stderr, "Please recompile WITH_OPENSSL\n");
  294. closesocket(connfd);
  295. return ERR_INVALID_PROTOCOL;
  296. #endif
  297. }
  298. if (cli->session == NULL) {
  299. cli->session = HttpSession::New(HTTP_CLIENT, (http_version)cli->http_version);
  300. }
  301. cli->fd = connfd;
  302. return 0;
  303. }
  304. int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* res) {
  305. // connect -> send -> recv -> http_parser
  306. int err = 0;
  307. int timeout = cli->timeout;
  308. int connfd = cli->fd;
  309. req->ParseUrl();
  310. if (cli->host.size() == 0) {
  311. cli->host = req->host;
  312. cli->port = req->port;
  313. }
  314. if (cli->tls == 0) {
  315. cli->tls = req->https;
  316. }
  317. cli->http_version = req->http_major;
  318. time_t start_time = time(NULL);
  319. time_t cur_time;
  320. int fail_cnt = 0;
  321. connect:
  322. if (connfd <= 0) {
  323. int ret = __http_client_connect(cli);
  324. if (ret != 0) {
  325. return ret;
  326. }
  327. connfd = cli->fd;
  328. }
  329. cli->session->SubmitRequest(req);
  330. char recvbuf[1024] = {0};
  331. int total_nsend, nsend, nrecv;
  332. send:
  333. char* data = NULL;
  334. size_t len = 0;
  335. while (cli->session->GetSendData(&data, &len)) {
  336. total_nsend = 0;
  337. while (1) {
  338. if (timeout > 0) {
  339. cur_time = time(NULL);
  340. if (cur_time - start_time >= timeout) {
  341. return ERR_TASK_TIMEOUT;
  342. }
  343. so_sndtimeo(connfd, (timeout-(cur_time-start_time)) * 1000);
  344. }
  345. #ifdef WITH_OPENSSL
  346. if (cli->tls) {
  347. nsend = SSL_write(cli->ssl, data+total_nsend, len-total_nsend);
  348. }
  349. #endif
  350. if (!cli->tls) {
  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->session->InitResponse(res);
  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. #ifdef WITH_OPENSSL
  380. if (cli->tls) {
  381. nrecv = SSL_read(cli->ssl, recvbuf, sizeof(recvbuf));
  382. }
  383. #endif
  384. if (!cli->tls) {
  385. nrecv = recv(connfd, recvbuf, sizeof(recvbuf), 0);
  386. }
  387. if (nrecv <= 0) {
  388. return socket_errno();
  389. }
  390. int nparse = cli->session->FeedRecvData(recvbuf, nrecv);
  391. if (nparse != nrecv) {
  392. return ERR_PARSE;
  393. }
  394. } while(cli->session->WantRecv());
  395. return err;
  396. }
  397. const char* http_client_strerror(int errcode) {
  398. return socket_strerror(errcode);
  399. }
  400. #endif