HttpMessage.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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. auto kv_iter = iter->kv.find(name);
  426. if (kv_iter != iter->kv.end()) {
  427. iter->name = name;
  428. iter->value = kv_iter->second;
  429. return *iter;
  430. }
  431. }
  432. return NoCookie;
  433. }
  434. // body
  435. void HttpMessage::SetBody(const std::string& body) {
  436. this->body = body;
  437. }
  438. const std::string& HttpMessage::Body() {
  439. return this->body;
  440. }
  441. void HttpMessage::DumpHeaders(std::string& str) {
  442. FillContentType();
  443. FillContentLength();
  444. // headers
  445. for (auto& header: headers) {
  446. // http2 :method :path :scheme :authority :status
  447. if (*str.c_str() != ':') {
  448. // %s: %s\r\n
  449. str += header.first;
  450. str += ": ";
  451. // fix CVE-2023-26148
  452. // if the value has \r\n, translate to \\r\\n
  453. if (header.second.find("\r") != std::string::npos ||
  454. header.second.find("\n") != std::string::npos) {
  455. std::string newStr = "";
  456. for (size_t i = 0; i < header.second.size(); ++i) {
  457. if (header.second[i] == '\r') {
  458. newStr += "\\r";
  459. } else if (header.second[i] == '\n') {
  460. newStr += "\\n";
  461. } else {
  462. newStr += header.second[i];
  463. }
  464. }
  465. str += newStr;
  466. } else {
  467. str += header.second;
  468. }
  469. str += "\r\n";
  470. }
  471. }
  472. // cookies
  473. const char* cookie_field = "Cookie";
  474. if (type == HTTP_RESPONSE) {
  475. cookie_field = "Set-Cookie";
  476. }
  477. for (auto& cookie : cookies) {
  478. str += cookie_field;
  479. str += ": ";
  480. str += cookie.dump();
  481. str += "\r\n";
  482. }
  483. }
  484. void HttpMessage::DumpBody() {
  485. if (body.size() != 0) {
  486. return;
  487. }
  488. FillContentType();
  489. #ifndef WITHOUT_HTTP_CONTENT
  490. switch(content_type) {
  491. case APPLICATION_JSON:
  492. body = dump_json(json, 2);
  493. break;
  494. case MULTIPART_FORM_DATA:
  495. {
  496. auto iter = headers.find("Content-Type");
  497. if (iter == headers.end()) {
  498. return;
  499. }
  500. const char* boundary = strstr(iter->second.c_str(), "boundary=");
  501. if (boundary == NULL) {
  502. return;
  503. }
  504. boundary += strlen("boundary=");
  505. body = dump_multipart(form, boundary);
  506. }
  507. break;
  508. case X_WWW_FORM_URLENCODED:
  509. body = dump_query_params(kv);
  510. break;
  511. default:
  512. // nothing to do
  513. break;
  514. }
  515. #endif
  516. }
  517. void HttpMessage::DumpBody(std::string& str) {
  518. DumpBody();
  519. const char* content = (const char*)Content();
  520. size_t content_length = ContentLength();
  521. if (content && content_length) {
  522. str.append(content, content_length);
  523. }
  524. }
  525. int HttpMessage::ParseBody() {
  526. if (body.size() == 0) {
  527. return -1;
  528. }
  529. FillContentType();
  530. #ifndef WITHOUT_HTTP_CONTENT
  531. switch(content_type) {
  532. case APPLICATION_JSON:
  533. {
  534. std::string errmsg;
  535. int ret = parse_json(body.c_str(), json, errmsg);
  536. if (ret != 0 && errmsg.size() != 0) {
  537. hloge("%s", errmsg.c_str());
  538. }
  539. return ret;
  540. }
  541. case MULTIPART_FORM_DATA:
  542. {
  543. auto iter = headers.find("Content-Type");
  544. if (iter == headers.end()) {
  545. return -1;
  546. }
  547. const char* boundary = strstr(iter->second.c_str(), "boundary=");
  548. if (boundary == NULL) {
  549. return -1;
  550. }
  551. boundary += strlen("boundary=");
  552. std::string strBoundary(boundary);
  553. strBoundary = trim_pairs(strBoundary, "\"\"\'\'");
  554. return parse_multipart(body, form, strBoundary.c_str());
  555. }
  556. case X_WWW_FORM_URLENCODED:
  557. return parse_query_params(body.c_str(), kv);
  558. default:
  559. // nothing to do
  560. return 0;
  561. }
  562. #endif
  563. return 0;
  564. }
  565. std::string HttpMessage::Dump(bool is_dump_headers, bool is_dump_body) {
  566. std::string str;
  567. if (is_dump_headers) {
  568. DumpHeaders(str);
  569. }
  570. str += "\r\n";
  571. if (is_dump_body) {
  572. DumpBody(str);
  573. }
  574. return str;
  575. }
  576. HttpRequest::HttpRequest() : HttpMessage() {
  577. type = HTTP_REQUEST;
  578. Init();
  579. }
  580. void HttpRequest::Init() {
  581. headers["User-Agent"] = DEFAULT_HTTP_USER_AGENT;
  582. headers["Accept"] = "*/*";
  583. method = HTTP_GET;
  584. scheme = "http";
  585. host = "127.0.0.1";
  586. port = DEFAULT_HTTP_PORT;
  587. path = "/";
  588. timeout = DEFAULT_HTTP_TIMEOUT;
  589. connect_timeout = DEFAULT_HTTP_CONNECT_TIMEOUT;
  590. retry_count = DEFAULT_HTTP_FAIL_RETRY_COUNT;
  591. retry_delay = DEFAULT_HTTP_FAIL_RETRY_DELAY;
  592. redirect = 1;
  593. proxy = 0;
  594. cancel = 0;
  595. }
  596. void HttpRequest::Reset() {
  597. HttpMessage::Reset();
  598. Init();
  599. url.clear();
  600. query_params.clear();
  601. }
  602. void HttpRequest::DumpUrl() {
  603. std::string str;
  604. if (url.size() != 0 &&
  605. *url.c_str() != '/' &&
  606. strstr(url.c_str(), "://") != NULL) {
  607. // have been complete url
  608. goto query;
  609. }
  610. // scheme://
  611. str = scheme;
  612. str += "://";
  613. // host:port
  614. if (url.size() != 0 && *url.c_str() != '/') {
  615. // url begin with host
  616. str += url;
  617. }
  618. else {
  619. if (port == 0 ||
  620. port == DEFAULT_HTTP_PORT ||
  621. port == DEFAULT_HTTPS_PORT) {
  622. str += Host();
  623. }
  624. else {
  625. str += hv::asprintf("%s:%d", host.c_str(), port);
  626. }
  627. }
  628. // /path
  629. if (url.size() != 0 && *url.c_str() == '/') {
  630. // url begin with path
  631. str += url;
  632. }
  633. else if (path.size() > 1 && *path.c_str() == '/') {
  634. str += path;
  635. }
  636. else if (url.size() == 0) {
  637. str += '/';
  638. }
  639. url = str;
  640. query:
  641. // ?query
  642. if (strchr(url.c_str(), '?') == NULL &&
  643. query_params.size() != 0) {
  644. url += '?';
  645. url += dump_query_params(query_params);
  646. }
  647. }
  648. void HttpRequest::ParseUrl() {
  649. DumpUrl();
  650. hurl_t parser;
  651. hv_parse_url(&parser, url.c_str());
  652. // scheme
  653. std::string scheme_ = url.substr(parser.fields[HV_URL_SCHEME].off, parser.fields[HV_URL_SCHEME].len);
  654. // host
  655. std::string host_(host);
  656. if (parser.fields[HV_URL_HOST].len > 0) {
  657. host_ = url.substr(parser.fields[HV_URL_HOST].off, parser.fields[HV_URL_HOST].len);
  658. }
  659. // port
  660. int port_ = parser.port ? parser.port : strcmp(scheme_.c_str(), "https") ? DEFAULT_HTTP_PORT : DEFAULT_HTTPS_PORT;
  661. if (!proxy) {
  662. scheme = scheme_;
  663. host = host_;
  664. port = port_;
  665. }
  666. FillHost(host_.c_str(), port_);
  667. // path
  668. if (parser.fields[HV_URL_PATH].len > 0) {
  669. path = url.substr(parser.fields[HV_URL_PATH].off);
  670. }
  671. // query
  672. if (parser.fields[HV_URL_QUERY].len > 0) {
  673. parse_query_params(url.c_str()+parser.fields[HV_URL_QUERY].off, query_params);
  674. }
  675. }
  676. std::string HttpRequest::Path() {
  677. const char* s = path.c_str();
  678. const char* e = s;
  679. while (*e && *e != '?' && *e != '#') ++e;
  680. return HUrl::unescape(std::string(s, e));
  681. }
  682. void HttpRequest::FillHost(const char* host, int port) {
  683. if (headers.find("Host") == headers.end()) {
  684. if (port == 0 ||
  685. port == DEFAULT_HTTP_PORT ||
  686. port == DEFAULT_HTTPS_PORT) {
  687. headers["Host"] = host;
  688. } else {
  689. headers["Host"] = hv::NetAddr::to_string(host, port);
  690. }
  691. }
  692. }
  693. void HttpRequest::SetHost(const char* host, int port) {
  694. this->host = host;
  695. this->port = port;
  696. FillHost(host, port);
  697. }
  698. void HttpRequest::SetProxy(const char* host, int port) {
  699. this->scheme = "http";
  700. this->host = host;
  701. this->port = port;
  702. proxy = 1;
  703. }
  704. void HttpRequest::SetAuth(const std::string& auth) {
  705. SetHeader("Authorization", auth);
  706. }
  707. void HttpRequest::SetBasicAuth(const std::string& username, const std::string& password) {
  708. std::string strAuth = hv::asprintf("%s:%s", username.c_str(), password.c_str());
  709. std::string base64Auth = hv::Base64Encode((const unsigned char*)strAuth.c_str(), strAuth.size());
  710. SetAuth(std::string("Basic ") + base64Auth);
  711. }
  712. void HttpRequest::SetBearerTokenAuth(const std::string& token) {
  713. SetAuth(std::string("Bearer ") + token);
  714. }
  715. std::string HttpRequest::Dump(bool is_dump_headers, bool is_dump_body) {
  716. ParseUrl();
  717. std::string str;
  718. str.reserve(MAX(512, path.size() + 128));
  719. // GET / HTTP/1.1\r\n
  720. str = asprintf("%s %s HTTP/%d.%d\r\n",
  721. http_method_str(method),
  722. proxy ? url.c_str() : path.c_str(),
  723. (int)http_major, (int)http_minor);
  724. if (is_dump_headers) {
  725. DumpHeaders(str);
  726. }
  727. str += "\r\n";
  728. if (is_dump_body) {
  729. DumpBody(str);
  730. }
  731. return str;
  732. }
  733. void HttpRequest::SetRange(long from, long to) {
  734. SetHeader("Range", hv::asprintf("bytes=%ld-%ld", from, to));
  735. }
  736. bool HttpRequest::GetRange(long& from, long& to) {
  737. auto iter = headers.find("Range");
  738. if (iter != headers.end()) {
  739. sscanf(iter->second.c_str(), "bytes=%ld-%ld", &from, &to);
  740. return true;
  741. }
  742. from = to = 0;
  743. return false;
  744. }
  745. HttpResponse::HttpResponse() : HttpMessage() {
  746. type = HTTP_RESPONSE;
  747. Init();
  748. }
  749. void HttpResponse::Init() {
  750. status_code = HTTP_STATUS_OK;
  751. }
  752. void HttpResponse::Reset() {
  753. HttpMessage::Reset();
  754. Init();
  755. }
  756. std::string HttpResponse::Dump(bool is_dump_headers, bool is_dump_body) {
  757. char c_str[256] = {0};
  758. std::string str;
  759. str.reserve(512);
  760. // HTTP/1.1 200 OK\r\n
  761. snprintf(c_str, sizeof(c_str), "HTTP/%d.%d %d %s\r\n",
  762. (int)http_major, (int)http_minor,
  763. (int)status_code, http_status_str(status_code));
  764. str = c_str;
  765. if (is_dump_headers) {
  766. if (*s_date) {
  767. headers["Date"] = s_date;
  768. } else {
  769. headers["Date"] = gmtime_fmt(time(NULL), c_str);
  770. }
  771. DumpHeaders(str);
  772. }
  773. str += "\r\n";
  774. if (is_dump_body) {
  775. DumpBody(str);
  776. }
  777. return str;
  778. }
  779. void HttpResponse::SetRange(long from, long to, long total) {
  780. SetHeader("Content-Range", hv::asprintf("bytes %ld-%ld/%ld", from, to, total));
  781. }
  782. bool HttpResponse::GetRange(long& from, long& to, long& total) {
  783. auto iter = headers.find("Content-Range");
  784. if (iter != headers.end()) {
  785. sscanf(iter->second.c_str(), "bytes %ld-%ld/%ld", &from, &to, &total);
  786. return true;
  787. }
  788. from = to = total = 0;
  789. return false;
  790. }