HttpMessage.cpp 14 KB

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