http_client.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. if (req->headers.find(pair.first) == req->headers.end()) {
  120. req->headers[pair.first] = pair.second;
  121. }
  122. }
  123. return __http_client_send(cli, req, res);
  124. }
  125. int http_client_send(HttpRequest* req, HttpResponse* res, int timeout) {
  126. http_client_t cli;
  127. cli.timeout = timeout;
  128. return __http_client_send(&cli, req, res);
  129. }
  130. #ifdef WITH_CURL
  131. static size_t s_header_cb(char* buf, size_t size, size_t cnt, void* userdata) {
  132. if (buf == NULL || userdata == NULL) return 0;
  133. HttpResponse* res = (HttpResponse*)userdata;
  134. std::string str(buf);
  135. std::string::size_type pos = str.find_first_of(':');
  136. if (pos == std::string::npos) {
  137. if (strncmp(buf, "HTTP/", 5) == 0) {
  138. // status line
  139. //hlogd("%s", buf);
  140. int http_major,http_minor,status_code;
  141. if (buf[5] == '1') {
  142. // HTTP/1.1 200 OK\r\n
  143. sscanf(buf, "HTTP/%d.%d %d", &http_major, &http_minor, &status_code);
  144. }
  145. else if (buf[5] == '2') {
  146. // HTTP/2 200\r\n
  147. sscanf(buf, "HTTP/%d %d", &http_major, &status_code);
  148. http_minor = 0;
  149. }
  150. res->http_major = http_major;
  151. res->http_minor = http_minor;
  152. res->status_code = (http_status)status_code;
  153. }
  154. }
  155. else {
  156. // headers
  157. std::string key = trim(str.substr(0, pos));
  158. std::string value = trim(str.substr(pos+1));
  159. res->headers[key] = value;
  160. }
  161. return size*cnt;
  162. }
  163. static size_t s_body_cb(char *buf, size_t size, size_t cnt, void *userdata) {
  164. if (buf == NULL || userdata == NULL) return 0;
  165. HttpResponse* res = (HttpResponse*)userdata;
  166. res->body.append(buf, size*cnt);
  167. return size*cnt;
  168. }
  169. int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* res) {
  170. if (req == NULL || res == NULL) {
  171. return -1;
  172. }
  173. if (cli->curl == NULL) {
  174. cli->curl = curl_easy_init();
  175. }
  176. CURL* curl = cli->curl;
  177. // SSL
  178. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  179. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
  180. // http2
  181. if (req->http_major == 2) {
  182. //curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_0);
  183. //No Connection: Upgrade
  184. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE);
  185. }
  186. // TCP_NODELAY
  187. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  188. // method
  189. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method_str(req->method));
  190. // url
  191. req->DumpUrl();
  192. curl_easy_setopt(curl, CURLOPT_URL, req->url.c_str());
  193. //hlogd("%s %s HTTP/%d.%d", http_method_str(req->method), req->url.c_str(), req->http_major, req->http_minor);
  194. // headers
  195. req->FillContentType();
  196. struct curl_slist *headers = NULL;
  197. for (auto& pair : req->headers) {
  198. std::string header = pair.first;
  199. header += ": ";
  200. header += pair.second;
  201. headers = curl_slist_append(headers, header.c_str());
  202. }
  203. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  204. // body
  205. //struct curl_httppost* httppost = NULL;
  206. //struct curl_httppost* lastpost = NULL;
  207. if (req->body.size() == 0) {
  208. req->DumpBody();
  209. /*
  210. if (req->body.size() == 0 &&
  211. req->content_type == MULTIPART_FORM_DATA) {
  212. for (auto& pair : req->mp) {
  213. if (pair.second.filename.size() != 0) {
  214. curl_formadd(&httppost, &lastpost,
  215. CURLFORM_COPYNAME, pair.first.c_str(),
  216. CURLFORM_FILE, pair.second.filename.c_str(),
  217. CURLFORM_END);
  218. }
  219. else if (pair.second.content.size() != 0) {
  220. curl_formadd(&httppost, &lastpost,
  221. CURLFORM_COPYNAME, pair.first.c_str(),
  222. CURLFORM_COPYCONTENTS, pair.second.content.c_str(),
  223. CURLFORM_END);
  224. }
  225. }
  226. if (httppost) {
  227. curl_easy_setopt(curl, CURLOPT_HTTPPOST, httppost);
  228. }
  229. }
  230. */
  231. }
  232. if (req->body.size() != 0) {
  233. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req->body.c_str());
  234. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req->body.size());
  235. }
  236. if (cli->timeout > 0) {
  237. curl_easy_setopt(curl, CURLOPT_TIMEOUT, cli->timeout);
  238. }
  239. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, s_body_cb);
  240. curl_easy_setopt(curl, CURLOPT_WRITEDATA, res);
  241. curl_easy_setopt(curl, CURLOPT_HEADER, 0);
  242. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, s_header_cb);
  243. curl_easy_setopt(curl, CURLOPT_HEADERDATA, res);
  244. int ret = curl_easy_perform(curl);
  245. /*
  246. if (ret != 0) {
  247. hloge("curl error: %d: %s", ret, curl_easy_strerror((CURLcode)ret));
  248. }
  249. if (res->body.length() != 0) {
  250. hlogd("[Response]\n%s", res->body.c_str());
  251. }
  252. double total_time, name_time, conn_time, pre_time;
  253. curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
  254. curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &name_time);
  255. curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &conn_time);
  256. curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &pre_time);
  257. hlogd("TIME_INFO: %lf,%lf,%lf,%lf", total_time, name_time, conn_time, pre_time);
  258. */
  259. if (headers) {
  260. curl_slist_free_all(headers);
  261. }
  262. /*
  263. if (httppost) {
  264. curl_formfree(httppost);
  265. }
  266. */
  267. return ret;
  268. }
  269. const char* http_client_strerror(int errcode) {
  270. return curl_easy_strerror((CURLcode)errcode);
  271. }
  272. #else
  273. static int __http_client_connect(http_client_t* cli) {
  274. int blocktime = MAX_CONNECT_TIMEOUT;
  275. if (cli->timeout > 0) {
  276. blocktime = MIN(cli->timeout*1000, blocktime);
  277. }
  278. int connfd = ConnectTimeout(cli->host.c_str(), cli->port, blocktime);
  279. if (connfd < 0) {
  280. return connfd;
  281. }
  282. tcp_nodelay(connfd, 1);
  283. if (cli->tls) {
  284. #ifdef WITH_OPENSSL
  285. if (ssl_ctx_instance() == NULL) {
  286. ssl_ctx_init(NULL, NULL, NULL);
  287. }
  288. cli->ssl = SSL_new((SSL_CTX*)ssl_ctx_instance());
  289. SSL_set_fd(cli->ssl, connfd);
  290. if (SSL_connect(cli->ssl) != 1) {
  291. int err = SSL_get_error(cli->ssl, -1);
  292. fprintf(stderr, "SSL handshark failed: %d\n", err);
  293. SSL_free(cli->ssl);
  294. cli->ssl = NULL;
  295. closesocket(connfd);
  296. return err;
  297. }
  298. #else
  299. fprintf(stderr, "Please recompile WITH_OPENSSL\n");
  300. closesocket(connfd);
  301. return ERR_INVALID_PROTOCOL;
  302. #endif
  303. }
  304. if (cli->parser == NULL) {
  305. cli->parser = HttpParser::New(HTTP_CLIENT, (http_version)cli->http_version);
  306. }
  307. cli->fd = connfd;
  308. return 0;
  309. }
  310. int __http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* res) {
  311. // connect -> send -> recv -> http_parser
  312. int err = 0;
  313. int timeout = cli->timeout;
  314. int connfd = cli->fd;
  315. req->ParseUrl();
  316. if (cli->host.size() == 0) {
  317. cli->host = req->host;
  318. cli->port = req->port;
  319. }
  320. if (cli->tls == 0) {
  321. cli->tls = req->https;
  322. }
  323. cli->http_version = req->http_major;
  324. time_t start_time = time(NULL);
  325. time_t cur_time;
  326. int fail_cnt = 0;
  327. connect:
  328. if (connfd <= 0) {
  329. int ret = __http_client_connect(cli);
  330. if (ret != 0) {
  331. return ret;
  332. }
  333. connfd = cli->fd;
  334. }
  335. cli->parser->SubmitRequest(req);
  336. char recvbuf[1024] = {0};
  337. int total_nsend, nsend, nrecv;
  338. total_nsend = nsend = nrecv = 0;
  339. send:
  340. char* data = NULL;
  341. size_t len = 0;
  342. while (cli->parser->GetSendData(&data, &len)) {
  343. total_nsend = 0;
  344. while (1) {
  345. if (timeout > 0) {
  346. cur_time = time(NULL);
  347. if (cur_time - start_time >= timeout) {
  348. return ERR_TASK_TIMEOUT;
  349. }
  350. so_sndtimeo(connfd, (timeout-(cur_time-start_time)) * 1000);
  351. }
  352. #ifdef WITH_OPENSSL
  353. if (cli->tls) {
  354. nsend = SSL_write(cli->ssl, data+total_nsend, len-total_nsend);
  355. }
  356. #endif
  357. if (!cli->tls) {
  358. nsend = send(connfd, data+total_nsend, len-total_nsend, 0);
  359. }
  360. if (nsend <= 0) {
  361. if (++fail_cnt == 1) {
  362. // maybe keep-alive timeout, try again
  363. cli->Close();
  364. goto connect;
  365. }
  366. else {
  367. return socket_errno();
  368. }
  369. }
  370. total_nsend += nsend;
  371. if (total_nsend == len) {
  372. break;
  373. }
  374. }
  375. }
  376. cli->parser->InitResponse(res);
  377. recv:
  378. do {
  379. if (timeout > 0) {
  380. cur_time = time(NULL);
  381. if (cur_time - start_time >= timeout) {
  382. return ERR_TASK_TIMEOUT;
  383. }
  384. so_rcvtimeo(connfd, (timeout-(cur_time-start_time)) * 1000);
  385. }
  386. #ifdef WITH_OPENSSL
  387. if (cli->tls) {
  388. nrecv = SSL_read(cli->ssl, recvbuf, sizeof(recvbuf));
  389. }
  390. #endif
  391. if (!cli->tls) {
  392. nrecv = recv(connfd, recvbuf, sizeof(recvbuf), 0);
  393. }
  394. if (nrecv <= 0) {
  395. return socket_errno();
  396. }
  397. int nparse = cli->parser->FeedRecvData(recvbuf, nrecv);
  398. if (nparse != nrecv) {
  399. return ERR_PARSE;
  400. }
  401. } while(!cli->parser->IsComplete());
  402. return err;
  403. }
  404. const char* http_client_strerror(int errcode) {
  405. return socket_strerror(errcode);
  406. }
  407. #endif