HttpMessage.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. #ifndef HV_HTTP_MESSAGE_H_
  2. #define HV_HTTP_MESSAGE_H_
  3. /*
  4. * @class HttpMessage
  5. * HttpRequest extends HttpMessage
  6. * HttpResponse extends HttpMessage
  7. *
  8. * @member
  9. * request-line: GET / HTTP/1.1\r\n => method path
  10. * response-line: HTTP/1.1 200 OK\r\n => status_code
  11. * headers, cookies
  12. * body
  13. *
  14. * content, content_length, content_type
  15. * json, form, kv
  16. *
  17. * @function
  18. * Content, ContentLength, ContentType
  19. * ParseUrl, ParseBody
  20. * DumpUrl, DumpHeaders, DumpBody, Dump
  21. * GetHeader, GetParam, GetJson, GetFormData, GetUrlEncoded
  22. * SetHeader, SetParam, SetBody, SetFormData, SetUrlEncoded
  23. * Get<T>, Set<T>
  24. * GetString, GetBool, GetInt, GetFloat
  25. * String, Data, Json, File, FormFile
  26. *
  27. * @example
  28. * examples/http_server_test.cpp
  29. * examples/http_client_test.cpp
  30. * examples/httpd
  31. *
  32. */
  33. #include <memory>
  34. #include <string>
  35. #include <map>
  36. #include <functional>
  37. #include "hexport.h"
  38. #include "hbase.h"
  39. #include "hstring.h"
  40. #include "hfile.h"
  41. #include "hpath.h"
  42. #include "httpdef.h"
  43. #include "http_content.h"
  44. namespace hv {
  45. struct NetAddr {
  46. std::string ip;
  47. int port;
  48. std::string ipport() {
  49. return hv::asprintf("%s:%d", ip.c_str(), port);
  50. }
  51. };
  52. }
  53. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
  54. // Cookie: sessionid=1; domain=.example.com; path=/; max-age=86400; secure; httponly
  55. struct HV_EXPORT HttpCookie {
  56. std::string name;
  57. std::string value;
  58. std::string domain;
  59. std::string path;
  60. std::string expires;
  61. int max_age;
  62. bool secure;
  63. bool httponly;
  64. enum SameSite {
  65. Default,
  66. Strict,
  67. Lax,
  68. None
  69. } samesite;
  70. enum Priority {
  71. NotSet,
  72. Low,
  73. Medium,
  74. High,
  75. } priority;
  76. hv::KeyValue kv; // for multiple names
  77. HttpCookie() {
  78. init();
  79. }
  80. void init() {
  81. max_age = 0;
  82. secure = false;
  83. httponly = false;
  84. samesite = Default;
  85. priority = NotSet;
  86. }
  87. void reset() {
  88. init();
  89. name.clear();
  90. value.clear();
  91. domain.clear();
  92. path.clear();
  93. expires.clear();
  94. kv.clear();
  95. }
  96. bool parse(const std::string& str);
  97. std::string dump() const;
  98. };
  99. typedef std::map<std::string, std::string, hv::StringCaseLess> http_headers;
  100. typedef std::vector<HttpCookie> http_cookies;
  101. typedef std::string http_body;
  102. HV_EXPORT extern http_headers DefaultHeaders;
  103. HV_EXPORT extern http_body NoBody;
  104. HV_EXPORT extern HttpCookie NoCookie;
  105. class HV_EXPORT HttpMessage {
  106. public:
  107. static char s_date[32];
  108. int type;
  109. unsigned short http_major;
  110. unsigned short http_minor;
  111. http_headers headers;
  112. http_cookies cookies;
  113. http_body body;
  114. // http_cb
  115. std::function<void(HttpMessage*, http_parser_state state, const char* data, size_t size)> http_cb;
  116. // structured content
  117. void* content; // DATA_NO_COPY
  118. size_t content_length;
  119. http_content_type content_type;
  120. #ifndef WITHOUT_HTTP_CONTENT
  121. hv::Json json; // APPLICATION_JSON
  122. hv::MultiPart form; // MULTIPART_FORM_DATA
  123. hv::KeyValue kv; // X_WWW_FORM_URLENCODED
  124. // T=[bool, int, int64_t, float, double]
  125. template<typename T>
  126. T Get(const char* key, T defvalue = 0);
  127. std::string GetString(const char* key, const std::string& = "");
  128. bool GetBool(const char* key, bool defvalue = 0);
  129. int64_t GetInt(const char* key, int64_t defvalue = 0);
  130. double GetFloat(const char* key, double defvalue = 0);
  131. template<typename T>
  132. void Set(const char* key, const T& value) {
  133. switch (ContentType()) {
  134. case APPLICATION_JSON:
  135. json[key] = value;
  136. break;
  137. case MULTIPART_FORM_DATA:
  138. form[key] = hv::FormData(value);
  139. break;
  140. case X_WWW_FORM_URLENCODED:
  141. kv[key] = hv::to_string(value);
  142. break;
  143. default:
  144. break;
  145. }
  146. }
  147. /*
  148. * @usage https://github.com/nlohmann/json
  149. *
  150. * null: Json(nullptr);
  151. * boolean: Json(true);
  152. * number: Json(123);
  153. * string: Json("hello");
  154. * object: Json(std::map<string, ValueType>);
  155. * Json(hv::Json::object({
  156. {"k1", "v1"},
  157. {"k2", "v2"}
  158. }));
  159. * array: Json(std::vector<ValueType>);
  160. Json(hv::Json::array(
  161. {1, 2, 3}
  162. ));
  163. */
  164. // Content-Type: application/json
  165. template<typename T>
  166. int Json(const T& t) {
  167. content_type = APPLICATION_JSON;
  168. hv::Json j(t);
  169. body = j.dump(2);
  170. return 200;
  171. }
  172. const hv::Json& GetJson() {
  173. if (json.empty() && ContentType() == APPLICATION_JSON) {
  174. ParseBody();
  175. }
  176. return json;
  177. }
  178. // Content-Type: multipart/form-data
  179. template<typename T>
  180. void SetFormData(const char* name, const T& t) {
  181. form[name] = hv::FormData(t);
  182. }
  183. void SetFormFile(const char* name, const char* filepath) {
  184. form[name] = hv::FormData(NULL, filepath);
  185. }
  186. int FormFile(const char* name, const char* filepath) {
  187. content_type = MULTIPART_FORM_DATA;
  188. form[name] = hv::FormData(NULL, filepath);
  189. return 200;
  190. }
  191. const hv::MultiPart& GetForm() {
  192. if (form.empty() && ContentType() == MULTIPART_FORM_DATA) {
  193. ParseBody();
  194. }
  195. return form;
  196. }
  197. std::string GetFormData(const char* name, const std::string& defvalue = hv::empty_string) {
  198. if (form.empty() && ContentType() == MULTIPART_FORM_DATA) {
  199. ParseBody();
  200. }
  201. auto iter = form.find(name);
  202. return iter == form.end() ? defvalue : iter->second.content;
  203. }
  204. int SaveFormFile(const char* name, const char* path) {
  205. if (ContentType() != MULTIPART_FORM_DATA) {
  206. return HTTP_STATUS_BAD_REQUEST;
  207. }
  208. if (form.empty()) {
  209. ParseBody();
  210. if (form.empty()) return HTTP_STATUS_BAD_REQUEST;
  211. }
  212. auto iter = form.find(name);
  213. if (iter == form.end()) {
  214. return HTTP_STATUS_BAD_REQUEST;
  215. }
  216. const auto& formdata = iter->second;
  217. if (formdata.content.empty()) {
  218. return HTTP_STATUS_BAD_REQUEST;
  219. }
  220. std::string filepath(path);
  221. if (HPath::isdir(path)) {
  222. filepath = HPath::join(filepath, formdata.filename);
  223. }
  224. HFile file;
  225. if (file.open(filepath.c_str(), "wb") != 0) {
  226. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  227. }
  228. file.write(formdata.content.data(), formdata.content.size());
  229. return 200;
  230. }
  231. // Content-Type: application/x-www-form-urlencoded
  232. template<typename T>
  233. void SetUrlEncoded(const char* key, const T& t) {
  234. kv[key] = hv::to_string(t);
  235. }
  236. const hv::KeyValue& GetUrlEncoded() {
  237. if (kv.empty() && ContentType() == X_WWW_FORM_URLENCODED) {
  238. ParseBody();
  239. }
  240. return kv;
  241. }
  242. std::string GetUrlEncoded(const char* key, const std::string& defvalue = hv::empty_string) {
  243. if (kv.empty() && ContentType() == X_WWW_FORM_URLENCODED) {
  244. ParseBody();
  245. }
  246. auto iter = kv.find(key);
  247. return iter == kv.end() ? defvalue : iter->second;
  248. }
  249. #endif
  250. HttpMessage() {
  251. type = HTTP_BOTH;
  252. Init();
  253. }
  254. virtual ~HttpMessage() {}
  255. void Init() {
  256. http_major = 1;
  257. http_minor = 1;
  258. content = NULL;
  259. content_length = 0;
  260. content_type = CONTENT_TYPE_NONE;
  261. }
  262. virtual void Reset() {
  263. Init();
  264. headers.clear();
  265. cookies.clear();
  266. body.clear();
  267. #ifndef WITHOUT_HTTP_CONTENT
  268. json.clear();
  269. form.clear();
  270. kv.clear();
  271. #endif
  272. }
  273. // structured-content -> content_type <-> headers["Content-Type"]
  274. void FillContentType();
  275. // body.size -> content_length <-> headers["Content-Length"]
  276. void FillContentLength();
  277. bool IsChunked();
  278. bool IsKeepAlive();
  279. // headers
  280. void SetHeader(const char* key, const std::string& value) {
  281. headers[key] = value;
  282. }
  283. std::string GetHeader(const char* key, const std::string& defvalue = hv::empty_string) {
  284. auto iter = headers.find(key);
  285. return iter == headers.end() ? defvalue : iter->second;
  286. }
  287. // body
  288. void SetBody(const std::string& body) {
  289. this->body = body;
  290. }
  291. const std::string& Body() {
  292. return this->body;
  293. }
  294. // headers -> string
  295. void DumpHeaders(std::string& str);
  296. // structured content -> body
  297. void DumpBody();
  298. void DumpBody(std::string& str);
  299. // body -> structured content
  300. // @retval 0:succeed
  301. int ParseBody();
  302. virtual std::string Dump(bool is_dump_headers, bool is_dump_body);
  303. void* Content() {
  304. if (content == NULL && body.size() != 0) {
  305. content = (void*)body.data();
  306. }
  307. return content;
  308. }
  309. size_t ContentLength() {
  310. if (content_length == 0) {
  311. FillContentLength();
  312. }
  313. return content_length;
  314. }
  315. http_content_type ContentType() {
  316. if (content_type == CONTENT_TYPE_NONE) {
  317. FillContentType();
  318. }
  319. return content_type;
  320. }
  321. void SetContentType(http_content_type type) {
  322. content_type = type;
  323. }
  324. void SetContentType(const char* type) {
  325. content_type = http_content_type_enum(type);
  326. }
  327. void SetContentTypeByFilename(const char* filepath) {
  328. const char* suffix = hv_suffixname(filepath);
  329. if (suffix) {
  330. content_type = http_content_type_enum_by_suffix(suffix);
  331. }
  332. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  333. content_type = APPLICATION_OCTET_STREAM;
  334. }
  335. }
  336. void AddCookie(const HttpCookie& cookie) {
  337. cookies.push_back(cookie);
  338. }
  339. const HttpCookie& GetCookie(const std::string& name) {
  340. for (auto iter = cookies.begin(); iter != cookies.end(); ++iter) {
  341. if (iter->name == name) {
  342. return *iter;
  343. }
  344. }
  345. return NoCookie;
  346. }
  347. int String(const std::string& str) {
  348. content_type = TEXT_PLAIN;
  349. body = str;
  350. return 200;
  351. }
  352. int Data(void* data, int len, bool nocopy = true) {
  353. content_type = APPLICATION_OCTET_STREAM;
  354. if (nocopy) {
  355. content = data;
  356. content_length = len;
  357. } else {
  358. content_length = body.size();
  359. body.resize(content_length + len);
  360. memcpy((void*)(body.data() + content_length), data, len);
  361. content_length += len;
  362. }
  363. return 200;
  364. }
  365. int File(const char* filepath) {
  366. HFile file;
  367. if (file.open(filepath, "rb") != 0) {
  368. return HTTP_STATUS_NOT_FOUND;
  369. }
  370. SetContentTypeByFilename(filepath);
  371. file.readall(body);
  372. return 200;
  373. }
  374. int SaveFile(const char* filepath) {
  375. HFile file;
  376. if (file.open(filepath, "wb") != 0) {
  377. return HTTP_STATUS_NOT_FOUND;
  378. }
  379. file.write(body.data(), body.size());
  380. return 200;
  381. }
  382. };
  383. #define DEFAULT_HTTP_USER_AGENT "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
  384. #define DEFAULT_HTTP_TIMEOUT 60 // s
  385. #define DEFAULT_HTTP_CONNECT_TIMEOUT 10 // s
  386. #define DEFAULT_HTTP_FAIL_RETRY_COUNT 1
  387. #define DEFAULT_HTTP_FAIL_RETRY_DELAY 1000 // ms
  388. class HV_EXPORT HttpRequest : public HttpMessage {
  389. public:
  390. http_method method;
  391. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  392. std::string url;
  393. // structured url
  394. std::string scheme;
  395. std::string host;
  396. int port;
  397. std::string path;
  398. hv::QueryParams query_params;
  399. // client_addr
  400. hv::NetAddr client_addr; // for http server save client addr of request
  401. // for HttpClient
  402. uint16_t timeout; // unit: s
  403. uint16_t connect_timeout;// unit: s
  404. uint32_t retry_count; // just for AsyncHttpClient fail retry
  405. uint32_t retry_delay; // just for AsyncHttpClient fail retry
  406. unsigned redirect: 1;
  407. unsigned proxy : 1;
  408. HttpRequest() : HttpMessage() {
  409. type = HTTP_REQUEST;
  410. Init();
  411. }
  412. void Init() {
  413. headers["User-Agent"] = DEFAULT_HTTP_USER_AGENT;
  414. headers["Accept"] = "*/*";
  415. method = HTTP_GET;
  416. scheme = "http";
  417. host = "127.0.0.1";
  418. port = DEFAULT_HTTP_PORT;
  419. path = "/";
  420. timeout = DEFAULT_HTTP_TIMEOUT;
  421. connect_timeout = DEFAULT_HTTP_CONNECT_TIMEOUT;
  422. retry_count = DEFAULT_HTTP_FAIL_RETRY_COUNT;
  423. retry_delay = DEFAULT_HTTP_FAIL_RETRY_DELAY;
  424. redirect = 1;
  425. proxy = 0;
  426. }
  427. virtual void Reset() {
  428. HttpMessage::Reset();
  429. Init();
  430. url.clear();
  431. query_params.clear();
  432. }
  433. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  434. // method
  435. void SetMethod(const char* method) {
  436. this->method = http_method_enum(method);
  437. }
  438. const char* Method() {
  439. return http_method_str(method);
  440. }
  441. // scheme
  442. bool IsHttps() {
  443. return strncmp(scheme.c_str(), "https", 5) == 0 ||
  444. strncmp(url.c_str(), "https://", 8) == 0;
  445. }
  446. // url
  447. void SetUrl(const char* url) {
  448. this->url = url;
  449. }
  450. const std::string& Url() {
  451. return url;
  452. }
  453. // structed url -> url
  454. void DumpUrl();
  455. // url -> structed url
  456. void ParseUrl();
  457. // /path?query#fragment
  458. std::string FullPath() { return path; }
  459. // /path
  460. std::string Path();
  461. // ?query_params
  462. template<typename T>
  463. void SetParam(const char* key, const T& t) {
  464. query_params[key] = hv::to_string(t);
  465. }
  466. std::string GetParam(const char* key, const std::string& defvalue = hv::empty_string) {
  467. auto iter = query_params.find(key);
  468. return iter == query_params.end() ? defvalue : iter->second;
  469. }
  470. // Host:
  471. std::string Host() {
  472. auto iter = headers.find("Host");
  473. return iter == headers.end() ? host : iter->second;
  474. }
  475. void FillHost(const char* host, int port = DEFAULT_HTTP_PORT);
  476. void SetHost(const char* host, int port = DEFAULT_HTTP_PORT);
  477. void SetProxy(const char* host, int port);
  478. bool IsProxy() { return proxy; }
  479. void SetTimeout(int sec) { timeout = sec; }
  480. void SetConnectTimeout(int sec) { connect_timeout = sec; }
  481. void AllowRedirect(bool on = true) { redirect = on; }
  482. // NOTE: SetRetry just for AsyncHttpClient
  483. void SetRetry(int count = DEFAULT_HTTP_FAIL_RETRY_COUNT,
  484. int delay = DEFAULT_HTTP_FAIL_RETRY_DELAY) {
  485. retry_count = count;
  486. retry_delay = delay;
  487. }
  488. // Range: bytes=0-4095
  489. void SetRange(long from = 0, long to = -1) {
  490. headers["Range"] = hv::asprintf("bytes=%ld-%ld", from, to);
  491. }
  492. bool GetRange(long& from, long& to) {
  493. auto iter = headers.find("Range");
  494. if (iter != headers.end()) {
  495. sscanf(iter->second.c_str(), "bytes=%ld-%ld", &from, &to);
  496. return true;
  497. }
  498. from = to = 0;
  499. return false;
  500. }
  501. };
  502. class HV_EXPORT HttpResponse : public HttpMessage {
  503. public:
  504. http_status status_code;
  505. const char* status_message() {
  506. return http_status_str(status_code);
  507. }
  508. HttpResponse() : HttpMessage() {
  509. type = HTTP_RESPONSE;
  510. Init();
  511. }
  512. void Init() {
  513. status_code = HTTP_STATUS_OK;
  514. }
  515. virtual void Reset() {
  516. HttpMessage::Reset();
  517. Init();
  518. }
  519. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  520. // Content-Range: bytes 0-4095/10240000
  521. void SetRange(long from, long to, long total) {
  522. headers["Content-Range"] = hv::asprintf("bytes %ld-%ld/%ld", from, to, total);
  523. }
  524. bool GetRange(long& from, long& to, long& total) {
  525. auto iter = headers.find("Content-Range");
  526. if (iter != headers.end()) {
  527. sscanf(iter->second.c_str(), "bytes %ld-%ld/%ld", &from, &to, &total);
  528. return true;
  529. }
  530. from = to = total = 0;
  531. return false;
  532. }
  533. int Redirect(const std::string& location, http_status status = HTTP_STATUS_FOUND) {
  534. status_code = status;
  535. headers["Location"] = location;
  536. return status_code;
  537. }
  538. };
  539. typedef std::shared_ptr<HttpRequest> HttpRequestPtr;
  540. typedef std::shared_ptr<HttpResponse> HttpResponsePtr;
  541. typedef std::function<void(const HttpResponsePtr&)> HttpResponseCallback;
  542. #endif // HV_HTTP_MESSAGE_H_