1
0

HttpMessage.cpp 21 KB

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