http_client.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. #include "http_client.h"
  2. #define MAX_CONNECT_TIMEOUT 3000 // ms
  3. #include "hstring.h" // import asprintf,trim
  4. #ifdef WITH_CURL
  5. #include "curl/curl.h"
  6. #else
  7. #include "herr.h"
  8. #include "hsocket.h"
  9. #include "HttpParser.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. HttpParser* parser;
  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. parser = 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 (parser) {
  68. delete parser;
  69. parser = 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. std::string str(buf);
  133. std::string::size_type pos = str.find_first_of(':');
  134. if (pos == std::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. std::string key = trim(str.substr(0, pos));
  156. std::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. std::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. /*
  208. if (req->body.size() == 0 &&
  209. req->content_type == MULTIPART_FORM_DATA) {
  210. for (auto& pair : req->mp) {
  211. if (pair.second.filename.size() != 0) {
  212. curl_formadd(&httppost, &lastpost,
  213. CURLFORM_COPYNAME, pair.first.c_str(),
  214. CURLFORM_FILE, pair.second.filename.c_str(),
  215. CURLFORM_END);
  216. }
  217. else if (pair.second.content.size() != 0) {
  218. curl_formadd(&httppost, &lastpost,
  219. CURLFORM_COPYNAME, pair.first.c_str(),
  220. CURLFORM_COPYCONTENTS, pair.second.content.c_str(),
  221. CURLFORM_END);
  222. }
  223. }
  224. if (httppost) {
  225. curl_easy_setopt(curl, CURLOPT_HTTPPOST, httppost);
  226. }
  227. }
  228. */
  229. }
  230. if (req->body.size() != 0) {
  231. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req->body.c_str());
  232. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req->body.size());
  233. }
  234. if (cli->timeout > 0) {
  235. curl_easy_setopt(curl, CURLOPT_TIMEOUT, cli->timeout);
  236. }
  237. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, s_body_cb);
  238. curl_easy_setopt(curl, CURLOPT_WRITEDATA, res);
  239. curl_easy_setopt(curl, CURLOPT_HEADER, 0);
  240. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, s_header_cb);
  241. curl_easy_setopt(curl, CURLOPT_HEADERDATA, res);
  242. int ret = curl_easy_perform(curl);
  243. /*
  244. if (ret != 0) {
  245. hloge("curl error: %d: %s", ret, curl_easy_strerror((CURLcode)ret));
  246. }
  247. if (res->body.length() != 0) {
  248. hlogd("[Response]\n%s", res->body.c_str());
  249. }
  250. double total_time, name_time, conn_time, pre_time;
  251. curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
  252. curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &name_time);
  253. curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &conn_time);
  254. curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &pre_time);
  255. hlogd("TIME_INFO: %lf,%lf,%lf,%lf", total_time, name_time, conn_time, pre_time);
  256. */
  257. if (headers) {
  258. curl_slist_free_all(headers);
  259. }
  260. /*
  261. if (httppost) {
  262. curl_formfree(httppost);
  263. }
  264. */
  265. return ret;
  266. }
  267. const char* http_client_strerror(int errcode) {
  268. return curl_easy_strerror((CURLcode)errcode);
  269. }
  270. #else
  271. static int __http_client_connect(http_client_t* cli) {
  272. int blocktime = MAX_CONNECT_TIMEOUT;
  273. if (cli->timeout > 0) {
  274. blocktime = MIN(cli->timeout*1000, blocktime);
  275. }
  276. int connfd = ConnectTimeout(cli->host.c_str(), cli->port, blocktime);
  277. if (connfd < 0) {
  278. return connfd;
  279. }
  280. tcp_nodelay(connfd, 1);
  281. if (cli->tls) {
  282. #ifdef WITH_OPENSSL
  283. if (g_ssl_ctx == NULL) {
  284. ssl_ctx_init(NULL, NULL, NULL);
  285. }
  286. cli->ssl = SSL_new((SSL_CTX*)g_ssl_ctx);
  287. SSL_set_fd(cli->ssl, connfd);
  288. if (SSL_connect(cli->ssl) != 1) {
  289. int err = SSL_get_error(cli->ssl, -1);
  290. fprintf(stderr, "SSL handshark failed: %d\n", err);
  291. SSL_free(cli->ssl);
  292. cli->ssl = NULL;
  293. closesocket(connfd);
  294. return err;
  295. }
  296. #else
  297. fprintf(stderr, "Please recompile WITH_OPENSSL\n");
  298. closesocket(connfd);
  299. return ERR_INVALID_PROTOCOL;
  300. #endif
  301. }
  302. if (cli->parser == NULL) {
  303. cli->parser = HttpParser::New(HTTP_CLIENT, (http_version)cli->http_version);
  304. }
  305. cli->fd = connfd;
  306. return 0;
  307. }
  308. int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* res) {
  309. // connect -> send -> recv -> http_parser
  310. int err = 0;
  311. int timeout = cli->timeout;
  312. int connfd = cli->fd;
  313. req->ParseUrl();
  314. if (cli->host.size() == 0) {
  315. cli->host = req->host;
  316. cli->port = req->port;
  317. }
  318. if (cli->tls == 0) {
  319. cli->tls = req->https;
  320. }
  321. cli->http_version = req->http_major;
  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);
  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. #ifdef WITH_OPENSSL
  351. if (cli->tls) {
  352. nsend = SSL_write(cli->ssl, data+total_nsend, len-total_nsend);
  353. }
  354. #endif
  355. if (!cli->tls) {
  356. nsend = send(connfd, data+total_nsend, len-total_nsend, 0);
  357. }
  358. if (nsend <= 0) {
  359. if (++fail_cnt == 1) {
  360. // maybe keep-alive timeout, try again
  361. cli->Close();
  362. goto connect;
  363. }
  364. else {
  365. return socket_errno();
  366. }
  367. }
  368. total_nsend += nsend;
  369. if (total_nsend == len) {
  370. break;
  371. }
  372. }
  373. }
  374. cli->parser->InitResponse(res);
  375. recv:
  376. do {
  377. if (timeout > 0) {
  378. cur_time = time(NULL);
  379. if (cur_time - start_time >= timeout) {
  380. return ERR_TASK_TIMEOUT;
  381. }
  382. so_rcvtimeo(connfd, (timeout-(cur_time-start_time)) * 1000);
  383. }
  384. #ifdef WITH_OPENSSL
  385. if (cli->tls) {
  386. nrecv = SSL_read(cli->ssl, recvbuf, sizeof(recvbuf));
  387. }
  388. #endif
  389. if (!cli->tls) {
  390. nrecv = recv(connfd, recvbuf, sizeof(recvbuf), 0);
  391. }
  392. if (nrecv <= 0) {
  393. return socket_errno();
  394. }
  395. int nparse = cli->parser->FeedRecvData(recvbuf, nrecv);
  396. if (nparse != nrecv) {
  397. return ERR_PARSE;
  398. }
  399. } while(!cli->parser->IsComplete());
  400. return err;
  401. }
  402. const char* http_client_strerror(int errcode) {
  403. return socket_strerror(errcode);
  404. }
  405. #endif