HttpMessage.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. #include "HttpMessage.h"
  2. #include <string.h>
  3. #include "htime.h"
  4. #include "hlog.h"
  5. #include "hurl.h"
  6. #include "http_parser.h" // for http_parser_url
  7. using namespace hv;
  8. http_headers DefaultHeaders;
  9. http_body NoBody;
  10. char HttpMessage::s_date[32] = {0};
  11. bool HttpCookie::parse(const std::string& str) {
  12. std::stringstream ss;
  13. ss << str;
  14. std::string kv;
  15. std::string::size_type pos;
  16. std::string key;
  17. std::string val;
  18. while (std::getline(ss, kv, ';')) {
  19. pos = kv.find_first_of('=');
  20. if (pos != std::string::npos) {
  21. key = trim(kv.substr(0, pos));
  22. val = trim(kv.substr(pos+1));
  23. } else {
  24. key = trim(kv);
  25. }
  26. const char* pkey = key.c_str();
  27. if (stricmp(pkey, "Domain") == 0) {
  28. domain = val;
  29. }
  30. else if (stricmp(pkey, "Path") == 0) {
  31. path = val;
  32. }
  33. else if (stricmp(pkey, "Expires") == 0) {
  34. expires = val;
  35. }
  36. else if (stricmp(pkey, "Max-Age") == 0) {
  37. max_age = atoi(val.c_str());
  38. }
  39. else if (stricmp(pkey, "Secure") == 0) {
  40. secure = true;
  41. }
  42. else if (stricmp(pkey, "HttpOnly") == 0) {
  43. httponly = true;
  44. }
  45. else if (stricmp(pkey, "SameSite") == 0) {
  46. samesite = stricmp(val.c_str(), "Strict") == 0 ? HttpCookie::SameSite::Strict :
  47. stricmp(val.c_str(), "Lax") == 0 ? HttpCookie::SameSite::Lax :
  48. stricmp(val.c_str(), "None") == 0 ? HttpCookie::SameSite::None :
  49. HttpCookie::SameSite::Default;
  50. }
  51. else if (value.empty() && !val.empty()) {
  52. name = key;
  53. value = val;
  54. }
  55. else {
  56. hlogw("Unrecognized key '%s'", key.c_str());
  57. }
  58. }
  59. return !name.empty() && !value.empty();
  60. }
  61. std::string HttpCookie::dump() const {
  62. assert(!name.empty() && !value.empty());
  63. std::string res;
  64. res = name;
  65. res += "=";
  66. res += value;
  67. if (!domain.empty()) {
  68. res += "; Domain=";
  69. res += domain;
  70. }
  71. if (!path.empty()) {
  72. res += "; Path=";
  73. res += path;
  74. }
  75. if (max_age > 0) {
  76. res += "; Max-Age=";
  77. res += hv::to_string(max_age);
  78. } else if (!expires.empty()) {
  79. res += "; Expires=";
  80. res += expires;
  81. }
  82. if (samesite != HttpCookie::SameSite::Default) {
  83. res += "; SameSite=";
  84. res += samesite == HttpCookie::SameSite::Strict ? "Strict" :
  85. samesite == HttpCookie::SameSite::Lax ? "Lax" :
  86. "None" ;
  87. }
  88. if (secure) {
  89. res += "; Secure";
  90. }
  91. if (httponly) {
  92. res += "; HttpOnly";
  93. }
  94. return res;
  95. }
  96. #ifndef WITHOUT_HTTP_CONTENT
  97. // NOTE: json ignore number/string, 123/"123"
  98. std::string HttpMessage::GetString(const char* key, const std::string& defvalue) {
  99. switch (ContentType()) {
  100. case APPLICATION_JSON:
  101. {
  102. if (!json.is_object()) {
  103. return defvalue;
  104. }
  105. const auto& value = json[key];
  106. if (value.is_string()) {
  107. return value;
  108. }
  109. else if (value.is_number()) {
  110. return hv::to_string(value);
  111. }
  112. else if (value.is_null()) {
  113. return "null";
  114. }
  115. else if (value.is_boolean()) {
  116. bool b = value;
  117. return b ? "true" : "false";
  118. }
  119. else {
  120. return defvalue;
  121. }
  122. }
  123. break;
  124. case MULTIPART_FORM_DATA:
  125. {
  126. auto iter = form.find(key);
  127. if (iter != form.end()) {
  128. return iter->second.content;
  129. }
  130. }
  131. break;
  132. case APPLICATION_URLENCODED:
  133. {
  134. auto iter = kv.find(key);
  135. if (iter != kv.end()) {
  136. return iter->second;
  137. }
  138. }
  139. break;
  140. default:
  141. break;
  142. }
  143. return defvalue;
  144. }
  145. template<>
  146. HV_EXPORT int64_t HttpMessage::Get(const char* key, int64_t defvalue) {
  147. if (ContentType() == APPLICATION_JSON) {
  148. if (!json.is_object()) {
  149. return defvalue;
  150. }
  151. const auto& value = json[key];
  152. if (value.is_number()) {
  153. return value;
  154. }
  155. else if (value.is_string()) {
  156. std::string str = value;
  157. return atoll(str.c_str());
  158. }
  159. else if (value.is_null()) {
  160. return 0;
  161. }
  162. else if (value.is_boolean()) {
  163. bool b = value;
  164. return b ? 1 : 0;
  165. }
  166. else {
  167. return defvalue;
  168. }
  169. }
  170. else {
  171. std::string str = GetString(key);
  172. return str.empty() ? defvalue : atoll(str.c_str());
  173. }
  174. }
  175. template<>
  176. HV_EXPORT int HttpMessage::Get(const char* key, int defvalue) {
  177. return (int)Get<int64_t>(key, defvalue);
  178. }
  179. template<>
  180. HV_EXPORT double HttpMessage::Get(const char* key, double defvalue) {
  181. if (ContentType() == APPLICATION_JSON) {
  182. if (!json.is_object()) {
  183. return defvalue;
  184. }
  185. const auto& value = json[key];
  186. if (value.is_number()) {
  187. return value;
  188. }
  189. else if (value.is_string()) {
  190. std::string str = value;
  191. return atof(str.c_str());
  192. }
  193. else if (value.is_null()) {
  194. return 0.0f;
  195. }
  196. else {
  197. return defvalue;
  198. }
  199. }
  200. else {
  201. std::string str = GetString(key);
  202. return str.empty() ? defvalue : atof(str.c_str());
  203. }
  204. }
  205. template<>
  206. HV_EXPORT float HttpMessage::Get(const char* key, float defvalue) {
  207. return (float)Get<double>(key, defvalue);
  208. }
  209. template<>
  210. HV_EXPORT bool HttpMessage::Get(const char* key, bool defvalue) {
  211. if (ContentType() == APPLICATION_JSON) {
  212. if (!json.is_object()) {
  213. return defvalue;
  214. }
  215. const auto& value = json[key];
  216. if (value.is_boolean()) {
  217. return value;
  218. }
  219. else if (value.is_string()) {
  220. std::string str = value;
  221. return getboolean(str.c_str());
  222. }
  223. else if (value.is_null()) {
  224. return false;
  225. }
  226. else if (value.is_number()) {
  227. return value != 0;
  228. }
  229. else {
  230. return defvalue;
  231. }
  232. }
  233. else {
  234. std::string str = GetString(key);
  235. return str.empty() ? defvalue : getboolean(str.c_str());
  236. }
  237. }
  238. bool HttpMessage::GetBool(const char* key, bool defvalue) {
  239. return Get<bool>(key, defvalue);
  240. }
  241. int64_t HttpMessage::GetInt(const char* key, int64_t defvalue) {
  242. return Get<int64_t>(key, defvalue);
  243. }
  244. double HttpMessage::GetFloat(const char* key, double defvalue) {
  245. return Get<double>(key, defvalue);
  246. }
  247. #endif
  248. void HttpMessage::FillContentType() {
  249. auto iter = headers.find("Content-Type");
  250. if (iter != headers.end()) {
  251. content_type = http_content_type_enum(iter->second.c_str());
  252. goto append;
  253. }
  254. #ifndef WITHOUT_HTTP_CONTENT
  255. if (content_type == CONTENT_TYPE_NONE) {
  256. if (json.size() != 0) {
  257. content_type = APPLICATION_JSON;
  258. }
  259. else if (form.size() != 0) {
  260. content_type = MULTIPART_FORM_DATA;
  261. }
  262. else if (kv.size() != 0) {
  263. content_type = X_WWW_FORM_URLENCODED;
  264. }
  265. else if (body.size() != 0) {
  266. content_type = TEXT_PLAIN;
  267. }
  268. }
  269. #endif
  270. if (content_type != CONTENT_TYPE_NONE) {
  271. headers["Content-Type"] = http_content_type_str(content_type);
  272. }
  273. append:
  274. #ifndef WITHOUT_HTTP_CONTENT
  275. if (content_type == MULTIPART_FORM_DATA) {
  276. auto iter = headers.find("Content-Type");
  277. if (iter != headers.end()) {
  278. const char* boundary = strstr(iter->second.c_str(), "boundary=");
  279. if (boundary == NULL) {
  280. boundary = DEFAULT_MULTIPART_BOUNDARY;
  281. iter->second += "; boundary=";
  282. iter->second += boundary;
  283. }
  284. }
  285. }
  286. #endif
  287. return;
  288. }
  289. void HttpMessage::FillContentLength() {
  290. auto iter = headers.find("Content-Length");
  291. if (iter != headers.end()) {
  292. content_length = atoi(iter->second.c_str());
  293. }
  294. if (content_length == 0) {
  295. DumpBody();
  296. content_length = body.size();
  297. }
  298. if (iter == headers.end() && !IsChunked()) {
  299. if (content_length != 0 || type == HTTP_RESPONSE) {
  300. headers["Content-Length"] = hv::to_string(content_length);
  301. }
  302. }
  303. }
  304. bool HttpMessage::IsChunked() {
  305. auto iter = headers.find("Transfer-Encoding");
  306. return iter == headers.end() ? false : stricmp(iter->second.c_str(), "chunked") == 0;
  307. }
  308. bool HttpMessage::IsKeepAlive() {
  309. bool keepalive = true;
  310. auto iter = headers.find("connection");
  311. if (iter != headers.end()) {
  312. const char* keepalive_value = iter->second.c_str();
  313. if (stricmp(keepalive_value, "keep-alive") == 0) {
  314. keepalive = true;
  315. }
  316. else if (stricmp(keepalive_value, "close") == 0) {
  317. keepalive = false;
  318. }
  319. else if (stricmp(keepalive_value, "upgrade") == 0) {
  320. keepalive = true;
  321. }
  322. }
  323. else if (http_major == 1 && http_minor == 0) {
  324. keepalive = false;
  325. }
  326. return keepalive;
  327. }
  328. void HttpMessage::DumpHeaders(std::string& str) {
  329. FillContentType();
  330. FillContentLength();
  331. // headers
  332. for (auto& header: headers) {
  333. // http2 :method :path :scheme :authority :status
  334. if (*str.c_str() != ':') {
  335. // %s: %s\r\n
  336. str += header.first;
  337. str += ": ";
  338. str += header.second;
  339. str += "\r\n";
  340. }
  341. }
  342. // cookies
  343. const char* cookie_field = "Cookie";
  344. if (type == HTTP_RESPONSE) {
  345. cookie_field = "Set-Cookie";
  346. }
  347. for (auto& cookie : cookies) {
  348. str += cookie_field;
  349. str += ": ";
  350. str += cookie.dump();
  351. str += "\r\n";
  352. }
  353. }
  354. void HttpMessage::DumpBody() {
  355. if (body.size() != 0) {
  356. return;
  357. }
  358. FillContentType();
  359. #ifndef WITHOUT_HTTP_CONTENT
  360. switch(content_type) {
  361. case APPLICATION_JSON:
  362. body = dump_json(json, 2);
  363. break;
  364. case MULTIPART_FORM_DATA:
  365. {
  366. auto iter = headers.find("Content-Type");
  367. if (iter == headers.end()) {
  368. return;
  369. }
  370. const char* boundary = strstr(iter->second.c_str(), "boundary=");
  371. if (boundary == NULL) {
  372. return;
  373. }
  374. boundary += strlen("boundary=");
  375. body = dump_multipart(form, boundary);
  376. }
  377. break;
  378. case X_WWW_FORM_URLENCODED:
  379. body = dump_query_params(kv);
  380. break;
  381. default:
  382. // nothing to do
  383. break;
  384. }
  385. #endif
  386. }
  387. void HttpMessage::DumpBody(std::string& str) {
  388. DumpBody();
  389. const char* content = (const char*)Content();
  390. int content_length = ContentLength();
  391. if (content && content_length) {
  392. str.append(content, content_length);
  393. }
  394. }
  395. int HttpMessage::ParseBody() {
  396. if (body.size() == 0) {
  397. return -1;
  398. }
  399. FillContentType();
  400. #ifndef WITHOUT_HTTP_CONTENT
  401. switch(content_type) {
  402. case APPLICATION_JSON:
  403. {
  404. std::string errmsg;
  405. int ret = parse_json(body.c_str(), json, errmsg);
  406. if (ret != 0 && errmsg.size() != 0) {
  407. hloge("%s", errmsg.c_str());
  408. }
  409. return ret;
  410. }
  411. case MULTIPART_FORM_DATA:
  412. {
  413. auto iter = headers.find("Content-Type");
  414. if (iter == headers.end()) {
  415. return -1;
  416. }
  417. const char* boundary = strstr(iter->second.c_str(), "boundary=");
  418. if (boundary == NULL) {
  419. return -1;
  420. }
  421. boundary += strlen("boundary=");
  422. std::string strBoundary(boundary);
  423. strBoundary = trim_pairs(strBoundary, "\"\"\'\'");
  424. return parse_multipart(body, form, strBoundary.c_str());
  425. }
  426. case X_WWW_FORM_URLENCODED:
  427. return parse_query_params(body.c_str(), kv);
  428. default:
  429. // nothing to do
  430. return 0;
  431. }
  432. #endif
  433. return 0;
  434. }
  435. std::string HttpMessage::Dump(bool is_dump_headers, bool is_dump_body) {
  436. std::string str;
  437. if (is_dump_headers) {
  438. DumpHeaders(str);
  439. }
  440. str += "\r\n";
  441. if (is_dump_body) {
  442. DumpBody(str);
  443. }
  444. return str;
  445. }
  446. void HttpRequest::DumpUrl() {
  447. std::string str;
  448. if (url.size() != 0 && strstr(url.c_str(), "://") != NULL) {
  449. // have been complete url
  450. goto query;
  451. }
  452. // scheme://
  453. str = scheme;
  454. str += "://";
  455. // host:port
  456. if (url.size() != 0 && *url.c_str() != '/') {
  457. // url begin with host
  458. str += url;
  459. }
  460. else {
  461. if (port == 0 ||
  462. port == DEFAULT_HTTP_PORT ||
  463. port == DEFAULT_HTTPS_PORT) {
  464. str += Host();
  465. }
  466. else {
  467. str += hv::asprintf("%s:%d", host.c_str(), port);
  468. }
  469. }
  470. // /path
  471. if (url.size() != 0 && *url.c_str() == '/') {
  472. // url begin with path
  473. str += url;
  474. }
  475. else if (path.size() > 1 && *path.c_str() == '/') {
  476. str += path;
  477. }
  478. else if (url.size() == 0) {
  479. str += '/';
  480. }
  481. url = str;
  482. query:
  483. // ?query
  484. if (strchr(url.c_str(), '?') == NULL &&
  485. query_params.size() != 0) {
  486. url += '?';
  487. url += dump_query_params(query_params);
  488. }
  489. }
  490. void HttpRequest::ParseUrl() {
  491. DumpUrl();
  492. http_parser_url parser;
  493. http_parser_url_init(&parser);
  494. http_parser_parse_url(url.c_str(), url.size(), 0, &parser);
  495. // scheme
  496. std::string scheme_ = url.substr(parser.field_data[UF_SCHEMA].off, parser.field_data[UF_SCHEMA].len);
  497. // host
  498. std::string host_(host);
  499. if (parser.field_set & (1<<UF_HOST)) {
  500. host_ = url.substr(parser.field_data[UF_HOST].off, parser.field_data[UF_HOST].len);
  501. }
  502. // port
  503. int port_ = parser.port ? parser.port : strcmp(scheme_.c_str(), "https") ? DEFAULT_HTTP_PORT : DEFAULT_HTTPS_PORT;
  504. if (!proxy) {
  505. scheme = scheme_;
  506. host = host_;
  507. port = port_;
  508. }
  509. FillHost(host_.c_str(), port_);
  510. // path
  511. if (parser.field_set & (1<<UF_PATH)) {
  512. const char* sp = url.c_str() + parser.field_data[UF_PATH].off;
  513. char* ep = (char*)(sp + parser.field_data[UF_PATH].len);
  514. char ev = *ep;
  515. *ep = '\0';
  516. path = url_unescape(sp);
  517. if (ev != '\0') {
  518. *ep = ev;
  519. path += ep;
  520. }
  521. }
  522. // query
  523. if (parser.field_set & (1<<UF_QUERY)) {
  524. parse_query_params(url.c_str()+parser.field_data[UF_QUERY].off, query_params);
  525. }
  526. }
  527. void HttpRequest::FillHost(const char* host, int port) {
  528. if (headers.find("Host") == headers.end()) {
  529. if (port == 0 ||
  530. port == DEFAULT_HTTP_PORT ||
  531. port == DEFAULT_HTTPS_PORT) {
  532. headers["Host"] = host;
  533. } else {
  534. headers["Host"] = asprintf("%s:%d", host, port);
  535. }
  536. }
  537. }
  538. void HttpRequest::SetHost(const char* host, int port) {
  539. this->host = host;
  540. this->port = port;
  541. FillHost(host, port);
  542. }
  543. void HttpRequest::SetProxy(const char* host, int port) {
  544. this->scheme = "http";
  545. this->host = host;
  546. this->port = port;
  547. proxy = 1;
  548. }
  549. std::string HttpRequest::Dump(bool is_dump_headers, bool is_dump_body) {
  550. ParseUrl();
  551. std::string str;
  552. str.reserve(MAX(512, path.size() + 128));
  553. // GET / HTTP/1.1\r\n
  554. str = asprintf("%s %s HTTP/%d.%d\r\n",
  555. http_method_str(method),
  556. proxy ? url.c_str() : path.c_str(),
  557. (int)http_major, (int)http_minor);
  558. if (is_dump_headers) {
  559. DumpHeaders(str);
  560. }
  561. str += "\r\n";
  562. if (is_dump_body) {
  563. DumpBody(str);
  564. }
  565. return str;
  566. }
  567. std::string HttpResponse::Dump(bool is_dump_headers, bool is_dump_body) {
  568. char c_str[256] = {0};
  569. std::string str;
  570. str.reserve(512);
  571. // HTTP/1.1 200 OK\r\n
  572. snprintf(c_str, sizeof(c_str), "HTTP/%d.%d %d %s\r\n",
  573. (int)http_major, (int)http_minor,
  574. (int)status_code, http_status_str(status_code));
  575. str = c_str;
  576. if (is_dump_headers) {
  577. if (*s_date) {
  578. headers["Date"] = s_date;
  579. } else {
  580. headers["Date"] = gmtime_fmt(time(NULL), c_str);
  581. }
  582. DumpHeaders(str);
  583. }
  584. str += "\r\n";
  585. if (is_dump_body) {
  586. DumpBody(str);
  587. }
  588. return str;
  589. }