1
0

HttpMessage.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. #include "HttpMessage.h"
  2. #include <string.h>
  3. #include "htime.h"
  4. #include "hlog.h"
  5. #include "hurl.h"
  6. #include "base64.h"
  7. using namespace hv;
  8. http_headers DefaultHeaders;
  9. http_body NoBody;
  10. HttpCookie NoCookie;
  11. char HttpMessage::s_date[32] = {0};
  12. HttpCookie::HttpCookie() {
  13. init();
  14. }
  15. void HttpCookie::init() {
  16. max_age = 0;
  17. secure = false;
  18. httponly = false;
  19. samesite = Default;
  20. priority = NotSet;
  21. }
  22. void HttpCookie::reset() {
  23. init();
  24. name.clear();
  25. value.clear();
  26. domain.clear();
  27. path.clear();
  28. expires.clear();
  29. kv.clear();
  30. }
  31. bool HttpCookie::parse(const std::string& str) {
  32. std::stringstream ss;
  33. ss << str;
  34. std::string line;
  35. std::string::size_type pos;
  36. std::string key;
  37. std::string val;
  38. reset();
  39. while (std::getline(ss, line, ';')) {
  40. pos = line.find_first_of('=');
  41. if (pos != std::string::npos) {
  42. key = trim(line.substr(0, pos));
  43. val = trim(line.substr(pos+1));
  44. const char* pkey = key.c_str();
  45. if (stricmp(pkey, "Domain") == 0) {
  46. domain = val;
  47. }
  48. else if (stricmp(pkey, "Path") == 0) {
  49. path = val;
  50. }
  51. else if (stricmp(pkey, "Expires") == 0) {
  52. expires = val;
  53. }
  54. else if (stricmp(pkey, "Max-Age") == 0) {
  55. max_age = atoi(val.c_str());
  56. }
  57. else if (stricmp(pkey, "SameSite") == 0) {
  58. samesite = stricmp(val.c_str(), "Strict") == 0 ? HttpCookie::SameSite::Strict :
  59. stricmp(val.c_str(), "Lax") == 0 ? HttpCookie::SameSite::Lax :
  60. stricmp(val.c_str(), "None") == 0 ? HttpCookie::SameSite::None :
  61. HttpCookie::SameSite::Default;
  62. }
  63. else if (stricmp(pkey, "Priority") == 0) {
  64. priority = stricmp(val.c_str(), "Low") == 0 ? HttpCookie::Priority::Low :
  65. stricmp(val.c_str(), "Medium") == 0 ? HttpCookie::Priority::Medium :
  66. stricmp(val.c_str(), "High") == 0 ? HttpCookie::Priority::High :
  67. HttpCookie::Priority::NotSet ;
  68. }
  69. else {
  70. if (name.empty()) {
  71. name = key;
  72. value = val;
  73. }
  74. kv[key] = val;
  75. }
  76. } else {
  77. key = trim(line);
  78. const char* pkey = key.c_str();
  79. if (stricmp(pkey, "Secure") == 0) {
  80. secure = true;
  81. }
  82. else if (stricmp(pkey, "HttpOnly") == 0) {
  83. httponly = true;
  84. }
  85. else {
  86. hlogw("Unrecognized key '%s'", key.c_str());
  87. }
  88. }
  89. }
  90. return !name.empty();
  91. }
  92. std::string HttpCookie::dump() const {
  93. assert(!name.empty() || !kv.empty());
  94. std::string res;
  95. if (!name.empty()) {
  96. res = name;
  97. res += "=";
  98. res += value;
  99. }
  100. for (auto& pair : kv) {
  101. if (pair.first == name) continue;
  102. if (!res.empty()) res += "; ";
  103. res += pair.first;
  104. res += "=";
  105. res += pair.second;
  106. }
  107. if (!domain.empty()) {
  108. res += "; Domain=";
  109. res += domain;
  110. }
  111. if (!path.empty()) {
  112. res += "; Path=";
  113. res += path;
  114. }
  115. if (max_age > 0) {
  116. res += "; Max-Age=";
  117. res += hv::to_string(max_age);
  118. } else if (!expires.empty()) {
  119. res += "; Expires=";
  120. res += expires;
  121. }
  122. if (samesite != HttpCookie::SameSite::Default) {
  123. res += "; SameSite=";
  124. res += samesite == HttpCookie::SameSite::Strict ? "Strict" :
  125. samesite == HttpCookie::SameSite::Lax ? "Lax" :
  126. "None" ;
  127. }
  128. if (priority != HttpCookie::Priority::NotSet) {
  129. res += "; Priority=";
  130. res += priority == HttpCookie::Priority::Low ? "Low" :
  131. priority == HttpCookie::Priority::Medium ? "Medium" :
  132. "High" ;
  133. }
  134. if (secure) {
  135. res += "; Secure";
  136. }
  137. if (httponly) {
  138. res += "; HttpOnly";
  139. }
  140. return res;
  141. }
  142. HttpMessage::HttpMessage() {
  143. type = HTTP_BOTH;
  144. Init();
  145. }
  146. HttpMessage::~HttpMessage() {
  147. }
  148. void HttpMessage::Init() {
  149. http_major = 1;
  150. http_minor = 1;
  151. content = NULL;
  152. content_length = 0;
  153. content_type = CONTENT_TYPE_NONE;
  154. }
  155. void HttpMessage::Reset() {
  156. Init();
  157. headers.clear();
  158. cookies.clear();
  159. body.clear();
  160. #ifndef WITHOUT_HTTP_CONTENT
  161. json.clear();
  162. form.clear();
  163. kv.clear();
  164. #endif
  165. }
  166. #ifndef WITHOUT_HTTP_CONTENT
  167. // NOTE: json ignore number/string, 123/"123"
  168. std::string HttpMessage::GetString(const char* key, const std::string& defvalue) {
  169. switch (ContentType()) {
  170. case APPLICATION_JSON:
  171. {
  172. if (json.empty()) {
  173. ParseBody();
  174. }
  175. if (!json.is_object()) {
  176. return defvalue;
  177. }
  178. const auto& value = json[key];
  179. if (value.is_string()) {
  180. return value;
  181. }
  182. else if (value.is_number()) {
  183. return hv::to_string(value);
  184. }
  185. else if (value.is_boolean()) {
  186. bool b = value;
  187. return b ? "true" : "false";
  188. }
  189. else {
  190. return defvalue;
  191. }
  192. }
  193. break;
  194. case MULTIPART_FORM_DATA:
  195. {
  196. if (form.empty()) {
  197. ParseBody();
  198. }
  199. auto iter = form.find(key);
  200. if (iter != form.end()) {
  201. return iter->second.content;
  202. }
  203. }
  204. break;
  205. case APPLICATION_URLENCODED:
  206. {
  207. if (kv.empty()) {
  208. ParseBody();
  209. }
  210. auto iter = kv.find(key);
  211. if (iter != kv.end()) {
  212. return iter->second;
  213. }
  214. }
  215. break;
  216. default:
  217. break;
  218. }
  219. return defvalue;
  220. }
  221. template<>
  222. HV_EXPORT int64_t HttpMessage::Get(const char* key, int64_t defvalue) {
  223. if (ContentType() == APPLICATION_JSON) {
  224. if (json.empty()) {
  225. ParseBody();
  226. }
  227. if (!json.is_object()) {
  228. return defvalue;
  229. }
  230. const auto& value = json[key];
  231. if (value.is_number()) {
  232. return value;
  233. }
  234. else if (value.is_string()) {
  235. std::string str = value;
  236. return atoll(str.c_str());
  237. }
  238. else if (value.is_boolean()) {
  239. bool b = value;
  240. return b ? 1 : 0;
  241. }
  242. else {
  243. return defvalue;
  244. }
  245. }
  246. else {
  247. std::string str = GetString(key);
  248. return str.empty() ? defvalue : atoll(str.c_str());
  249. }
  250. }
  251. template<>
  252. HV_EXPORT int HttpMessage::Get(const char* key, int defvalue) {
  253. return (int)Get<int64_t>(key, defvalue);
  254. }
  255. template<>
  256. HV_EXPORT double HttpMessage::Get(const char* key, double defvalue) {
  257. if (ContentType() == APPLICATION_JSON) {
  258. if (json.empty()) {
  259. ParseBody();
  260. }
  261. if (!json.is_object()) {
  262. return defvalue;
  263. }
  264. const auto& value = json[key];
  265. if (value.is_number()) {
  266. return value;
  267. }
  268. else if (value.is_string()) {
  269. std::string str = value;
  270. return atof(str.c_str());
  271. }
  272. else {
  273. return defvalue;
  274. }
  275. }
  276. else {
  277. std::string str = GetString(key);
  278. return str.empty() ? defvalue : atof(str.c_str());
  279. }
  280. }
  281. template<>
  282. HV_EXPORT float HttpMessage::Get(const char* key, float defvalue) {
  283. return (float)Get<double>(key, defvalue);
  284. }
  285. template<>
  286. HV_EXPORT bool HttpMessage::Get(const char* key, bool defvalue) {
  287. if (ContentType() == APPLICATION_JSON) {
  288. if (json.empty()) {
  289. ParseBody();
  290. }
  291. if (!json.is_object()) {
  292. return defvalue;
  293. }
  294. const auto& value = json[key];
  295. if (value.is_boolean()) {
  296. return value;
  297. }
  298. else if (value.is_string()) {
  299. std::string str = value;
  300. return hv_getboolean(str.c_str());
  301. }
  302. else if (value.is_number()) {
  303. return value != 0;
  304. }
  305. else {
  306. return defvalue;
  307. }
  308. }
  309. else {
  310. std::string str = GetString(key);
  311. return str.empty() ? defvalue : hv_getboolean(str.c_str());
  312. }
  313. }
  314. bool HttpMessage::GetBool(const char* key, bool defvalue) {
  315. return Get<bool>(key, defvalue);
  316. }
  317. int64_t HttpMessage::GetInt(const char* key, int64_t defvalue) {
  318. return Get<int64_t>(key, defvalue);
  319. }
  320. double HttpMessage::GetFloat(const char* key, double defvalue) {
  321. return Get<double>(key, defvalue);
  322. }
  323. #endif
  324. void HttpMessage::FillContentType() {
  325. auto iter = headers.find("Content-Type");
  326. if (iter != headers.end()) {
  327. content_type = http_content_type_enum(iter->second.c_str());
  328. goto append;
  329. }
  330. #ifndef WITHOUT_HTTP_CONTENT
  331. if (content_type == CONTENT_TYPE_NONE) {
  332. if (json.size() != 0) {
  333. content_type = APPLICATION_JSON;
  334. }
  335. else if (form.size() != 0) {
  336. content_type = MULTIPART_FORM_DATA;
  337. }
  338. else if (kv.size() != 0) {
  339. content_type = X_WWW_FORM_URLENCODED;
  340. }
  341. else if (body.size() != 0) {
  342. content_type = TEXT_PLAIN;
  343. }
  344. }
  345. #endif
  346. if (content_type != CONTENT_TYPE_NONE) {
  347. headers["Content-Type"] = http_content_type_str(content_type);
  348. }
  349. append:
  350. #ifndef WITHOUT_HTTP_CONTENT
  351. if (content_type == MULTIPART_FORM_DATA) {
  352. auto iter = headers.find("Content-Type");
  353. if (iter != headers.end()) {
  354. const char* boundary = strstr(iter->second.c_str(), "boundary=");
  355. if (boundary == NULL) {
  356. boundary = DEFAULT_MULTIPART_BOUNDARY;
  357. iter->second += "; boundary=";
  358. iter->second += boundary;
  359. }
  360. }
  361. }
  362. #endif
  363. return;
  364. }
  365. void HttpMessage::FillContentLength() {
  366. auto iter = headers.find("Content-Length");
  367. if (iter != headers.end()) {
  368. content_length = atoll(iter->second.c_str());
  369. }
  370. if (content_length == 0) {
  371. DumpBody();
  372. content_length = body.size();
  373. }
  374. if (iter == headers.end() && !IsChunked() && content_type != TEXT_EVENT_STREAM) {
  375. if (content_length != 0 || type == HTTP_RESPONSE) {
  376. headers["Content-Length"] = hv::to_string(content_length);
  377. }
  378. }
  379. }
  380. bool HttpMessage::IsChunked() {
  381. auto iter = headers.find("Transfer-Encoding");
  382. return iter != headers.end() && stricmp(iter->second.c_str(), "chunked") == 0;
  383. }
  384. bool HttpMessage::IsKeepAlive() {
  385. bool keepalive = true;
  386. auto iter = headers.find("connection");
  387. if (iter != headers.end()) {
  388. const char* keepalive_value = iter->second.c_str();
  389. if (stricmp(keepalive_value, "keep-alive") == 0) {
  390. keepalive = true;
  391. }
  392. else if (stricmp(keepalive_value, "close") == 0) {
  393. keepalive = false;
  394. }
  395. else if (stricmp(keepalive_value, "upgrade") == 0) {
  396. keepalive = true;
  397. }
  398. }
  399. else if (http_major == 1 && http_minor == 0) {
  400. keepalive = false;
  401. }
  402. return keepalive;
  403. }
  404. bool HttpMessage::IsUpgrade() {
  405. auto iter = headers.find("upgrade");
  406. return iter != headers.end();
  407. }
  408. // headers
  409. void HttpMessage::SetHeader(const char* key, const std::string& value) {
  410. headers[key] = value;
  411. }
  412. std::string HttpMessage::GetHeader(const char* key, const std::string& defvalue) {
  413. auto iter = headers.find(key);
  414. return iter == headers.end() ? defvalue : iter->second;
  415. }
  416. // cookies
  417. void HttpMessage::AddCookie(const HttpCookie& cookie) {
  418. cookies.push_back(cookie);
  419. }
  420. const HttpCookie& HttpMessage::GetCookie(const std::string& name) {
  421. for (auto iter = cookies.begin(); iter != cookies.end(); ++iter) {
  422. if (iter->name == name) {
  423. return *iter;
  424. }
  425. }
  426. return NoCookie;
  427. }
  428. // body
  429. void HttpMessage::SetBody(const std::string& body) {
  430. this->body = body;
  431. }
  432. const std::string& HttpMessage::Body() {
  433. return this->body;
  434. }
  435. void HttpMessage::DumpHeaders(std::string& str) {
  436. FillContentType();
  437. FillContentLength();
  438. // headers
  439. for (auto& header: headers) {
  440. // http2 :method :path :scheme :authority :status
  441. if (*str.c_str() != ':') {
  442. // %s: %s\r\n
  443. str += header.first;
  444. str += ": ";
  445. // fix CVE-2023-26148
  446. // if the value has \r\n, translate to \\r\\n
  447. if (header.second.find("\r") != std::string::npos ||
  448. header.second.find("\n") != std::string::npos) {
  449. std::string newStr = "";
  450. for (size_t i = 0; i < header.second.size(); ++i) {
  451. if (header.second[i] == '\r') {
  452. newStr += "\\r";
  453. } else if (header.second[i] == '\n') {
  454. newStr += "\\n";
  455. } else {
  456. newStr += header.second[i];
  457. }
  458. }
  459. str += newStr;
  460. } else {
  461. str += header.second;
  462. }
  463. str += "\r\n";
  464. }
  465. }
  466. // cookies
  467. const char* cookie_field = "Cookie";
  468. if (type == HTTP_RESPONSE) {
  469. cookie_field = "Set-Cookie";
  470. }
  471. for (auto& cookie : cookies) {
  472. str += cookie_field;
  473. str += ": ";
  474. str += cookie.dump();
  475. str += "\r\n";
  476. }
  477. }
  478. void HttpMessage::DumpBody() {
  479. if (body.size() != 0) {
  480. return;
  481. }
  482. FillContentType();
  483. #ifndef WITHOUT_HTTP_CONTENT
  484. switch(content_type) {
  485. case APPLICATION_JSON:
  486. body = dump_json(json, 2);
  487. break;
  488. case MULTIPART_FORM_DATA:
  489. {
  490. auto iter = headers.find("Content-Type");
  491. if (iter == headers.end()) {
  492. return;
  493. }
  494. const char* boundary = strstr(iter->second.c_str(), "boundary=");
  495. if (boundary == NULL) {
  496. return;
  497. }
  498. boundary += strlen("boundary=");
  499. body = dump_multipart(form, boundary);
  500. }
  501. break;
  502. case X_WWW_FORM_URLENCODED:
  503. body = dump_query_params(kv);
  504. break;
  505. default:
  506. // nothing to do
  507. break;
  508. }
  509. #endif
  510. }
  511. void HttpMessage::DumpBody(std::string& str) {
  512. DumpBody();
  513. const char* content = (const char*)Content();
  514. size_t content_length = ContentLength();
  515. if (content && content_length) {
  516. str.append(content, content_length);
  517. }
  518. }
  519. int HttpMessage::ParseBody() {
  520. if (body.size() == 0) {
  521. return -1;
  522. }
  523. FillContentType();
  524. #ifndef WITHOUT_HTTP_CONTENT
  525. switch(content_type) {
  526. case APPLICATION_JSON:
  527. {
  528. std::string errmsg;
  529. int ret = parse_json(body.c_str(), json, errmsg);
  530. if (ret != 0 && errmsg.size() != 0) {
  531. hloge("%s", errmsg.c_str());
  532. }
  533. return ret;
  534. }
  535. case MULTIPART_FORM_DATA:
  536. {
  537. auto iter = headers.find("Content-Type");
  538. if (iter == headers.end()) {
  539. return -1;
  540. }
  541. const char* boundary = strstr(iter->second.c_str(), "boundary=");
  542. if (boundary == NULL) {
  543. return -1;
  544. }
  545. boundary += strlen("boundary=");
  546. std::string strBoundary(boundary);
  547. strBoundary = trim_pairs(strBoundary, "\"\"\'\'");
  548. return parse_multipart(body, form, strBoundary.c_str());
  549. }
  550. case X_WWW_FORM_URLENCODED:
  551. return parse_query_params(body.c_str(), kv);
  552. default:
  553. // nothing to do
  554. return 0;
  555. }
  556. #endif
  557. return 0;
  558. }
  559. std::string HttpMessage::Dump(bool is_dump_headers, bool is_dump_body) {
  560. std::string str;
  561. if (is_dump_headers) {
  562. DumpHeaders(str);
  563. }
  564. str += "\r\n";
  565. if (is_dump_body) {
  566. DumpBody(str);
  567. }
  568. return str;
  569. }
  570. HttpRequest::HttpRequest() : HttpMessage() {
  571. type = HTTP_REQUEST;
  572. Init();
  573. }
  574. void HttpRequest::Init() {
  575. headers["User-Agent"] = DEFAULT_HTTP_USER_AGENT;
  576. headers["Accept"] = "*/*";
  577. method = HTTP_GET;
  578. scheme = "http";
  579. host = "127.0.0.1";
  580. port = DEFAULT_HTTP_PORT;
  581. path = "/";
  582. timeout = DEFAULT_HTTP_TIMEOUT;
  583. connect_timeout = DEFAULT_HTTP_CONNECT_TIMEOUT;
  584. retry_count = DEFAULT_HTTP_FAIL_RETRY_COUNT;
  585. retry_delay = DEFAULT_HTTP_FAIL_RETRY_DELAY;
  586. redirect = 1;
  587. proxy = 0;
  588. cancel = 0;
  589. }
  590. void HttpRequest::Reset() {
  591. HttpMessage::Reset();
  592. Init();
  593. url.clear();
  594. query_params.clear();
  595. }
  596. void HttpRequest::DumpUrl() {
  597. std::string str;
  598. if (url.size() != 0 &&
  599. *url.c_str() != '/' &&
  600. strstr(url.c_str(), "://") != NULL) {
  601. // have been complete url
  602. goto query;
  603. }
  604. // scheme://
  605. str = scheme;
  606. str += "://";
  607. // host:port
  608. if (url.size() != 0 && *url.c_str() != '/') {
  609. // url begin with host
  610. str += url;
  611. }
  612. else {
  613. if (port == 0 ||
  614. port == DEFAULT_HTTP_PORT ||
  615. port == DEFAULT_HTTPS_PORT) {
  616. str += Host();
  617. }
  618. else {
  619. str += hv::asprintf("%s:%d", host.c_str(), port);
  620. }
  621. }
  622. // /path
  623. if (url.size() != 0 && *url.c_str() == '/') {
  624. // url begin with path
  625. str += url;
  626. }
  627. else if (path.size() > 1 && *path.c_str() == '/') {
  628. str += path;
  629. }
  630. else if (url.size() == 0) {
  631. str += '/';
  632. }
  633. url = str;
  634. query:
  635. // ?query
  636. if (strchr(url.c_str(), '?') == NULL &&
  637. query_params.size() != 0) {
  638. url += '?';
  639. url += dump_query_params(query_params);
  640. }
  641. }
  642. void HttpRequest::ParseUrl() {
  643. DumpUrl();
  644. hurl_t parser;
  645. hv_parse_url(&parser, url.c_str());
  646. // scheme
  647. std::string scheme_ = url.substr(parser.fields[HV_URL_SCHEME].off, parser.fields[HV_URL_SCHEME].len);
  648. // host
  649. std::string host_(host);
  650. if (parser.fields[HV_URL_HOST].len > 0) {
  651. host_ = url.substr(parser.fields[HV_URL_HOST].off, parser.fields[HV_URL_HOST].len);
  652. }
  653. // port
  654. int port_ = parser.port ? parser.port : strcmp(scheme_.c_str(), "https") ? DEFAULT_HTTP_PORT : DEFAULT_HTTPS_PORT;
  655. if (!proxy) {
  656. scheme = scheme_;
  657. host = host_;
  658. port = port_;
  659. }
  660. FillHost(host_.c_str(), port_);
  661. // path
  662. if (parser.fields[HV_URL_PATH].len > 0) {
  663. path = url.substr(parser.fields[HV_URL_PATH].off);
  664. }
  665. // query
  666. if (parser.fields[HV_URL_QUERY].len > 0) {
  667. parse_query_params(url.c_str()+parser.fields[HV_URL_QUERY].off, query_params);
  668. }
  669. }
  670. std::string HttpRequest::Path() {
  671. const char* s = path.c_str();
  672. const char* e = s;
  673. while (*e && *e != '?' && *e != '#') ++e;
  674. return HUrl::unescape(std::string(s, e));
  675. }
  676. void HttpRequest::FillHost(const char* host, int port) {
  677. if (headers.find("Host") == headers.end()) {
  678. if (port == 0 ||
  679. port == DEFAULT_HTTP_PORT ||
  680. port == DEFAULT_HTTPS_PORT) {
  681. headers["Host"] = host;
  682. } else {
  683. headers["Host"] = asprintf("%s:%d", host, port);
  684. }
  685. }
  686. }
  687. void HttpRequest::SetHost(const char* host, int port) {
  688. this->host = host;
  689. this->port = port;
  690. FillHost(host, port);
  691. }
  692. void HttpRequest::SetProxy(const char* host, int port) {
  693. this->scheme = "http";
  694. this->host = host;
  695. this->port = port;
  696. proxy = 1;
  697. }
  698. void HttpRequest::SetAuth(const std::string& auth) {
  699. SetHeader("Authorization", auth);
  700. }
  701. void HttpRequest::SetBasicAuth(const std::string& username, const std::string& password) {
  702. std::string strAuth = hv::asprintf("%s:%s", username.c_str(), password.c_str());
  703. std::string base64Auth = hv::Base64Encode((const unsigned char*)strAuth.c_str(), strAuth.size());
  704. SetAuth(std::string("Basic ") + base64Auth);
  705. }
  706. void HttpRequest::SetBearerTokenAuth(const std::string& token) {
  707. SetAuth(std::string("Bearer ") + token);
  708. }
  709. std::string HttpRequest::Dump(bool is_dump_headers, bool is_dump_body) {
  710. ParseUrl();
  711. std::string str;
  712. str.reserve(MAX(512, path.size() + 128));
  713. // GET / HTTP/1.1\r\n
  714. str = asprintf("%s %s HTTP/%d.%d\r\n",
  715. http_method_str(method),
  716. proxy ? url.c_str() : path.c_str(),
  717. (int)http_major, (int)http_minor);
  718. if (is_dump_headers) {
  719. DumpHeaders(str);
  720. }
  721. str += "\r\n";
  722. if (is_dump_body) {
  723. DumpBody(str);
  724. }
  725. return str;
  726. }
  727. void HttpRequest::SetRange(long from, long to) {
  728. SetHeader("Range", hv::asprintf("bytes=%ld-%ld", from, to));
  729. }
  730. bool HttpRequest::GetRange(long& from, long& to) {
  731. auto iter = headers.find("Range");
  732. if (iter != headers.end()) {
  733. sscanf(iter->second.c_str(), "bytes=%ld-%ld", &from, &to);
  734. return true;
  735. }
  736. from = to = 0;
  737. return false;
  738. }
  739. HttpResponse::HttpResponse() : HttpMessage() {
  740. type = HTTP_RESPONSE;
  741. Init();
  742. }
  743. void HttpResponse::Init() {
  744. status_code = HTTP_STATUS_OK;
  745. }
  746. void HttpResponse::Reset() {
  747. HttpMessage::Reset();
  748. Init();
  749. }
  750. std::string HttpResponse::Dump(bool is_dump_headers, bool is_dump_body) {
  751. char c_str[256] = {0};
  752. std::string str;
  753. str.reserve(512);
  754. // HTTP/1.1 200 OK\r\n
  755. snprintf(c_str, sizeof(c_str), "HTTP/%d.%d %d %s\r\n",
  756. (int)http_major, (int)http_minor,
  757. (int)status_code, http_status_str(status_code));
  758. str = c_str;
  759. if (is_dump_headers) {
  760. if (*s_date) {
  761. headers["Date"] = s_date;
  762. } else {
  763. headers["Date"] = gmtime_fmt(time(NULL), c_str);
  764. }
  765. DumpHeaders(str);
  766. }
  767. str += "\r\n";
  768. if (is_dump_body) {
  769. DumpBody(str);
  770. }
  771. return str;
  772. }
  773. void HttpResponse::SetRange(long from, long to, long total) {
  774. SetHeader("Content-Range", hv::asprintf("bytes %ld-%ld/%ld", from, to, total));
  775. }
  776. bool HttpResponse::GetRange(long& from, long& to, long& total) {
  777. auto iter = headers.find("Content-Range");
  778. if (iter != headers.end()) {
  779. sscanf(iter->second.c_str(), "bytes %ld-%ld/%ld", &from, &to, &total);
  780. return true;
  781. }
  782. from = to = total = 0;
  783. return false;
  784. }