2
0

HTTPClient.cpp 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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::vector<uint8_t>& 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. // Write request body
  42. if (content.size() > 0) {
  43. socketStream.write((const char*)content.data(), content.size());
  44. }
  45. socketStream.flush();
  46. // Parse response
  47. readResponseHeaders();
  48. }
  49. void HTTPClient::Response::readResponseHeaders() {
  50. char *method, *path;
  51. const char* msgPointer;
  52. size_t msgLen;
  53. int pret, minorVersion, status;
  54. size_t prevbuflen = 0, numHeaders;
  55. this->httpBufferAvailable = 0;
  56. while (1) {
  57. socketStream.getline((char*)httpBuffer.data() + httpBufferAvailable,
  58. httpBuffer.size() - httpBufferAvailable);
  59. prevbuflen = httpBufferAvailable;
  60. httpBufferAvailable += socketStream.gcount();
  61. // Restore delimiters
  62. memcpy(httpBuffer.data() + httpBufferAvailable - 2, "\r\n", 2);
  63. // Parse the request
  64. numHeaders = sizeof(phResponseHeaders) / sizeof(phResponseHeaders[0]);
  65. pret =
  66. phr_parse_response((const char*)httpBuffer.data(), httpBufferAvailable,
  67. &minorVersion, &status, &msgPointer, &msgLen,
  68. phResponseHeaders, &numHeaders, prevbuflen);
  69. if (pret > 0) {
  70. break; /* successfully parsed the request */
  71. } else if (pret == -1)
  72. throw std::runtime_error("Cannot parse http response");
  73. /* request is incomplete, continue the loop */
  74. assert(pret == -2);
  75. if (httpBufferAvailable == httpBuffer.size())
  76. throw std::runtime_error("Response too large");
  77. }
  78. this->responseHeaders = {};
  79. // Headers have benen read
  80. for (int headerIndex = 0; headerIndex < numHeaders; headerIndex++) {
  81. this->responseHeaders.push_back(
  82. ValueHeader{std::string(phResponseHeaders[headerIndex].name,
  83. phResponseHeaders[headerIndex].name_len),
  84. std::string(phResponseHeaders[headerIndex].value,
  85. phResponseHeaders[headerIndex].value_len)});
  86. }
  87. std::string contentLengthValue = std::string(header("content-length"));
  88. if (contentLengthValue.size() > 0) {
  89. this->hasContentSize = true;
  90. this->contentSize = std::stoi(contentLengthValue);
  91. }
  92. }
  93. void HTTPClient::Response::get(const std::string& url, Headers headers) {
  94. std::string method = "GET";
  95. return this->rawRequest(url, method, {}, headers);
  96. }
  97. void HTTPClient::Response::post(const std::string& url, Headers headers,
  98. const std::vector<uint8_t>& body) {
  99. std::string method = "POST";
  100. return this->rawRequest(url, method, body, headers);
  101. }
  102. size_t HTTPClient::Response::contentLength() {
  103. return contentSize;
  104. }
  105. std::string_view HTTPClient::Response::header(const std::string& headerName) {
  106. for (auto& header : this->responseHeaders) {
  107. std::string headerValue = header.first;
  108. std::transform(headerValue.begin(), headerValue.end(), headerValue.begin(),
  109. [](unsigned char c) { return std::tolower(c); });
  110. if (headerName == headerValue) {
  111. return header.second;
  112. }
  113. }
  114. return "";
  115. }
  116. size_t HTTPClient::Response::totalLength() {
  117. auto rangeHeader = header("content-range");
  118. if (rangeHeader.find("/") != std::string::npos) {
  119. return std::stoi(
  120. std::string(rangeHeader.substr(rangeHeader.find("/") + 1)));
  121. }
  122. return this->contentLength();
  123. }
  124. void HTTPClient::Response::readRawBody() {
  125. if (contentSize > 0 && rawBody.size() == 0) {
  126. rawBody = std::vector<uint8_t>(contentSize);
  127. socketStream.read((char*)rawBody.data(), contentSize);
  128. }
  129. }
  130. std::string_view HTTPClient::Response::body() {
  131. readRawBody();
  132. return std::string_view((char*)rawBody.data(), rawBody.size());
  133. }
  134. std::vector<uint8_t> HTTPClient::Response::bytes() {
  135. readRawBody();
  136. return rawBody;
  137. }