http_client.cpp 12 KB

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