HTTPClient.cpp 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. #include "HTTPClient.h"
  2. #include <string.h> // for memcpy
  3. #include <algorithm> // for transform
  4. #include <cassert> // for assert
  5. #include <cctype> // for tolower
  6. #include <ostream> // for operator<<, basic_ostream
  7. #include <stdexcept> // for runtime_error
  8. #include "BellSocket.h" // for bell
  9. using namespace bell;
  10. void HTTPClient::Response::connect(const std::string& url) {
  11. urlParser = bell::URLParser::parse(url);
  12. // Open socket of type
  13. this->socketStream.open(urlParser.host, urlParser.port,
  14. urlParser.schema == "https");
  15. }
  16. HTTPClient::Response::~Response() {
  17. if (this->socketStream.isOpen()) {
  18. this->socketStream.close();
  19. }
  20. }
  21. void HTTPClient::Response::rawRequest(const std::string& url,
  22. const std::string& method,
  23. const std::string& content,
  24. Headers& headers) {
  25. urlParser = bell::URLParser::parse(url);
  26. // Prepare a request
  27. const char* reqEnd = "\r\n";
  28. socketStream << method << " " << urlParser.path << " HTTP/1.1" << reqEnd;
  29. socketStream << "Host: " << urlParser.host << ":" << urlParser.port << reqEnd;
  30. socketStream << "Connection: keep-alive" << reqEnd;
  31. socketStream << "Accept: */*" << reqEnd;
  32. // Write content
  33. if (content.size() > 0) {
  34. socketStream << "Content-Length: " << content.size() << reqEnd;
  35. }
  36. // Write headers
  37. for (auto& header : headers) {
  38. socketStream << header.first << ": " << header.second << reqEnd;
  39. }
  40. socketStream << reqEnd;
  41. socketStream.flush();
  42. // Parse response
  43. readResponseHeaders();
  44. }
  45. void HTTPClient::Response::readResponseHeaders() {
  46. char *method, *path;
  47. const char* msgPointer;
  48. size_t msgLen;
  49. int pret, minorVersion, status;
  50. size_t prevbuflen = 0, numHeaders;
  51. this->httpBufferAvailable = 0;
  52. while (1) {
  53. socketStream.getline((char*)httpBuffer.data() + httpBufferAvailable,
  54. httpBuffer.size() - httpBufferAvailable);
  55. prevbuflen = httpBufferAvailable;
  56. httpBufferAvailable += socketStream.gcount();
  57. // Restore delimiters
  58. memcpy(httpBuffer.data() + httpBufferAvailable - 2, "\r\n", 2);
  59. // Parse the request
  60. numHeaders = sizeof(phResponseHeaders) / sizeof(phResponseHeaders[0]);
  61. pret =
  62. phr_parse_response((const char*)httpBuffer.data(), httpBufferAvailable,
  63. &minorVersion, &status, &msgPointer, &msgLen,
  64. phResponseHeaders, &numHeaders, prevbuflen);
  65. if (pret > 0) {
  66. break; /* successfully parsed the request */
  67. } else if (pret == -1)
  68. throw std::runtime_error("Cannot parse http response");
  69. /* request is incomplete, continue the loop */
  70. assert(pret == -2);
  71. if (httpBufferAvailable == httpBuffer.size())
  72. throw std::runtime_error("Response too large");
  73. }
  74. this->responseHeaders = {};
  75. // Headers have benen read
  76. for (int headerIndex = 0; headerIndex < numHeaders; headerIndex++) {
  77. this->responseHeaders.push_back(
  78. ValueHeader{std::string(phResponseHeaders[headerIndex].name,
  79. phResponseHeaders[headerIndex].name_len),
  80. std::string(phResponseHeaders[headerIndex].value,
  81. phResponseHeaders[headerIndex].value_len)});
  82. }
  83. std::string contentLengthValue = std::string(header("content-length"));
  84. if (contentLengthValue.size() > 0) {
  85. this->hasContentSize = true;
  86. this->contentSize = std::stoi(contentLengthValue);
  87. }
  88. }
  89. void HTTPClient::Response::get(const std::string& url, Headers headers) {
  90. std::string method = "GET";
  91. return this->rawRequest(url, method, "", headers);
  92. }
  93. size_t HTTPClient::Response::contentLength() {
  94. return contentSize;
  95. }
  96. std::string_view HTTPClient::Response::header(const std::string& headerName) {
  97. for (auto& header : this->responseHeaders) {
  98. std::string headerValue = header.first;
  99. std::transform(headerValue.begin(), headerValue.end(), headerValue.begin(),
  100. [](unsigned char c) { return std::tolower(c); });
  101. if (headerName == headerValue) {
  102. return header.second;
  103. }
  104. }
  105. return "";
  106. }
  107. size_t HTTPClient::Response::totalLength() {
  108. auto rangeHeader = header("content-range");
  109. if (rangeHeader.find("/") != std::string::npos) {
  110. return std::stoi(
  111. std::string(rangeHeader.substr(rangeHeader.find("/") + 1)));
  112. }
  113. return this->contentLength();
  114. }
  115. void HTTPClient::Response::readRawBody() {
  116. if (contentSize > 0 && rawBody.size() == 0) {
  117. rawBody = std::vector<uint8_t>(contentSize);
  118. socketStream.read((char*)rawBody.data(), contentSize);
  119. }
  120. }
  121. std::string_view HTTPClient::Response::body() {
  122. readRawBody();
  123. return std::string_view((char*)rawBody.data(), rawBody.size());
  124. }
  125. std::vector<uint8_t> HTTPClient::Response::bytes() {
  126. readRawBody();
  127. return rawBody;
  128. }