HttpMessage.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. HttpCookie() {
  71. max_age = 0;
  72. secure = false;
  73. httponly = false;
  74. samesite = Default;
  75. }
  76. bool parse(const std::string& str);
  77. std::string dump() const;
  78. };
  79. typedef std::map<std::string, std::string, hv::StringCaseLess> http_headers;
  80. typedef std::vector<HttpCookie> http_cookies;
  81. typedef std::string http_body;
  82. HV_EXPORT extern http_headers DefaultHeaders;
  83. HV_EXPORT extern http_body NoBody;
  84. class HV_EXPORT HttpMessage {
  85. public:
  86. static char s_date[32];
  87. int type;
  88. unsigned short http_major;
  89. unsigned short http_minor;
  90. http_headers headers;
  91. http_cookies cookies;
  92. http_body body;
  93. // http_cb
  94. std::function<void(HttpMessage*, http_parser_state state, const char* data, size_t size)> http_cb;
  95. // structured content
  96. void* content; // DATA_NO_COPY
  97. size_t content_length;
  98. http_content_type content_type;
  99. #ifndef WITHOUT_HTTP_CONTENT
  100. hv::Json json; // APPLICATION_JSON
  101. hv::MultiPart form; // MULTIPART_FORM_DATA
  102. hv::KeyValue kv; // X_WWW_FORM_URLENCODED
  103. // T=[bool, int, int64_t, float, double]
  104. template<typename T>
  105. T Get(const char* key, T defvalue = 0);
  106. std::string GetString(const char* key, const std::string& = "");
  107. bool GetBool(const char* key, bool defvalue = 0);
  108. int64_t GetInt(const char* key, int64_t defvalue = 0);
  109. double GetFloat(const char* key, double defvalue = 0);
  110. template<typename T>
  111. void Set(const char* key, const T& value) {
  112. switch (ContentType()) {
  113. case APPLICATION_JSON:
  114. json[key] = value;
  115. break;
  116. case MULTIPART_FORM_DATA:
  117. form[key] = hv::FormData(value);
  118. break;
  119. case X_WWW_FORM_URLENCODED:
  120. kv[key] = hv::to_string(value);
  121. break;
  122. default:
  123. break;
  124. }
  125. }
  126. /*
  127. * @usage https://github.com/nlohmann/json
  128. *
  129. * null: Json(nullptr);
  130. * boolean: Json(true);
  131. * number: Json(123);
  132. * string: Json("hello");
  133. * object: Json(std::map<string, ValueType>);
  134. * Json(hv::Json::object({
  135. {"k1", "v1"},
  136. {"k2", "v2"}
  137. }));
  138. * array: Json(std::vector<ValueType>);
  139. Json(hv::Json::array(
  140. {1, 2, 3}
  141. ));
  142. */
  143. // Content-Type: application/json
  144. template<typename T>
  145. int Json(const T& t) {
  146. content_type = APPLICATION_JSON;
  147. hv::Json j(t);
  148. body = j.dump(2);
  149. return 200;
  150. }
  151. const hv::Json& GetJson() {
  152. if (json.empty() && ContentType() == APPLICATION_JSON) {
  153. ParseBody();
  154. }
  155. return json;
  156. }
  157. // Content-Type: multipart/form-data
  158. template<typename T>
  159. void SetFormData(const char* name, const T& t) {
  160. form[name] = hv::FormData(t);
  161. }
  162. void SetFormFile(const char* name, const char* filepath) {
  163. form[name] = hv::FormData(NULL, filepath);
  164. }
  165. int FormFile(const char* name, const char* filepath) {
  166. content_type = MULTIPART_FORM_DATA;
  167. form[name] = hv::FormData(NULL, filepath);
  168. return 200;
  169. }
  170. const hv::MultiPart& GetForm() {
  171. if (form.empty() && ContentType() == MULTIPART_FORM_DATA) {
  172. ParseBody();
  173. }
  174. return form;
  175. }
  176. std::string GetFormData(const char* name, const std::string& defvalue = hv::empty_string) {
  177. if (form.empty() && ContentType() == MULTIPART_FORM_DATA) {
  178. ParseBody();
  179. }
  180. auto iter = form.find(name);
  181. return iter == form.end() ? defvalue : iter->second.content;
  182. }
  183. int SaveFormFile(const char* name, const char* path) {
  184. if (ContentType() != MULTIPART_FORM_DATA) {
  185. return HTTP_STATUS_BAD_REQUEST;
  186. }
  187. if (form.empty()) {
  188. ParseBody();
  189. if (form.empty()) return HTTP_STATUS_BAD_REQUEST;
  190. }
  191. const hv::FormData& formdata = form[name];
  192. if (formdata.content.empty()) {
  193. return HTTP_STATUS_BAD_REQUEST;
  194. }
  195. std::string filepath(path);
  196. if (HPath::isdir(path)) {
  197. filepath = HPath::join(filepath, formdata.filename);
  198. }
  199. HFile file;
  200. if (file.open(filepath.c_str(), "wb") != 0) {
  201. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  202. }
  203. file.write(formdata.content.data(), formdata.content.size());
  204. return 200;
  205. }
  206. // Content-Type: application/x-www-form-urlencoded
  207. template<typename T>
  208. void SetUrlEncoded(const char* key, const T& t) {
  209. kv[key] = hv::to_string(t);
  210. }
  211. const hv::KeyValue& GetUrlEncoded() {
  212. if (kv.empty() && ContentType() == X_WWW_FORM_URLENCODED) {
  213. ParseBody();
  214. }
  215. return kv;
  216. }
  217. std::string GetUrlEncoded(const char* key, const std::string& defvalue = hv::empty_string) {
  218. if (kv.empty() && ContentType() == X_WWW_FORM_URLENCODED) {
  219. ParseBody();
  220. }
  221. auto iter = kv.find(key);
  222. return iter == kv.end() ? defvalue : iter->second;
  223. }
  224. #endif
  225. HttpMessage() {
  226. type = HTTP_BOTH;
  227. Init();
  228. }
  229. virtual ~HttpMessage() {}
  230. void Init() {
  231. http_major = 1;
  232. http_minor = 1;
  233. content = NULL;
  234. content_length = 0;
  235. content_type = CONTENT_TYPE_NONE;
  236. }
  237. virtual void Reset() {
  238. Init();
  239. headers.clear();
  240. cookies.clear();
  241. body.clear();
  242. #ifndef WITHOUT_HTTP_CONTENT
  243. json.clear();
  244. form.clear();
  245. kv.clear();
  246. #endif
  247. }
  248. // structured-content -> content_type <-> headers Content-Type
  249. void FillContentType();
  250. // body.size -> content_length <-> headers Content-Length
  251. void FillContentLength();
  252. bool IsChunked();
  253. bool IsKeepAlive();
  254. // headers
  255. void SetHeader(const char* key, const std::string& value) {
  256. headers[key] = value;
  257. }
  258. std::string GetHeader(const char* key, const std::string& defvalue = hv::empty_string) {
  259. auto iter = headers.find(key);
  260. return iter == headers.end() ? defvalue : iter->second;
  261. }
  262. // body
  263. void SetBody(const std::string& body) {
  264. this->body = body;
  265. }
  266. const std::string& Body() {
  267. return this->body;
  268. }
  269. // headers -> string
  270. void DumpHeaders(std::string& str);
  271. // structured content -> body
  272. void DumpBody();
  273. void DumpBody(std::string& str);
  274. // body -> structured content
  275. // @retval 0:succeed
  276. int ParseBody();
  277. virtual std::string Dump(bool is_dump_headers, bool is_dump_body);
  278. void* Content() {
  279. if (content == NULL && body.size() != 0) {
  280. content = (void*)body.data();
  281. }
  282. return content;
  283. }
  284. size_t ContentLength() {
  285. if (content_length == 0) {
  286. FillContentLength();
  287. }
  288. return content_length;
  289. }
  290. http_content_type ContentType() {
  291. if (content_type == CONTENT_TYPE_NONE) {
  292. FillContentType();
  293. }
  294. return content_type;
  295. }
  296. void SetContentTypeByFilename(const char* filepath) {
  297. const char* suffix = hv_suffixname(filepath);
  298. if (suffix) {
  299. content_type = http_content_type_enum_by_suffix(suffix);
  300. }
  301. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  302. content_type = APPLICATION_OCTET_STREAM;
  303. }
  304. }
  305. void AddCookie(const HttpCookie& cookie) {
  306. cookies.push_back(cookie);
  307. }
  308. int String(const std::string& str) {
  309. content_type = TEXT_PLAIN;
  310. body = str;
  311. return 200;
  312. }
  313. int Data(void* data, int len, bool nocopy = true) {
  314. content_type = APPLICATION_OCTET_STREAM;
  315. if (nocopy) {
  316. content = data;
  317. content_length = len;
  318. } else {
  319. content_length = body.size();
  320. body.resize(content_length + len);
  321. memcpy((void*)(body.data() + content_length), data, len);
  322. content_length += len;
  323. }
  324. return 200;
  325. }
  326. int File(const char* filepath) {
  327. HFile file;
  328. if (file.open(filepath, "rb") != 0) {
  329. return HTTP_STATUS_NOT_FOUND;
  330. }
  331. SetContentTypeByFilename(filepath);
  332. file.readall(body);
  333. return 200;
  334. }
  335. int SaveFile(const char* filepath) {
  336. HFile file;
  337. if (file.open(filepath, "wb") != 0) {
  338. return HTTP_STATUS_NOT_FOUND;
  339. }
  340. file.write(body.data(), body.size());
  341. return 200;
  342. }
  343. };
  344. #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"
  345. #define DEFAULT_HTTP_TIMEOUT 60 // s
  346. #define DEFAULT_HTTP_FAIL_RETRY_COUNT 1
  347. #define DEFAULT_HTTP_FAIL_RETRY_DELAY 1000 // ms
  348. class HV_EXPORT HttpRequest : public HttpMessage {
  349. public:
  350. http_method method;
  351. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  352. std::string url;
  353. // structured url
  354. std::string scheme;
  355. std::string host;
  356. int port;
  357. std::string path;
  358. hv::QueryParams query_params;
  359. // client_addr
  360. hv::NetAddr client_addr; // for http server save client addr of request
  361. // for HttpClient
  362. int timeout; // unit: s
  363. int retry_count; // just for AsyncHttpClient fail retry
  364. int retry_delay; // just for AsyncHttpClient fail retry
  365. unsigned redirect: 1;
  366. unsigned proxy : 1;
  367. HttpRequest() : HttpMessage() {
  368. type = HTTP_REQUEST;
  369. Init();
  370. }
  371. void Init() {
  372. headers["User-Agent"] = DEFAULT_HTTP_USER_AGENT;
  373. headers["Accept"] = "*/*";
  374. method = HTTP_GET;
  375. scheme = "http";
  376. host = "127.0.0.1";
  377. port = DEFAULT_HTTP_PORT;
  378. path = "/";
  379. timeout = DEFAULT_HTTP_TIMEOUT;
  380. retry_count = DEFAULT_HTTP_FAIL_RETRY_COUNT;
  381. retry_delay = DEFAULT_HTTP_FAIL_RETRY_DELAY;
  382. redirect = 1;
  383. proxy = 0;
  384. }
  385. virtual void Reset() {
  386. HttpMessage::Reset();
  387. Init();
  388. url.clear();
  389. query_params.clear();
  390. }
  391. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  392. // method
  393. void SetMethod(const char* method) {
  394. this->method = http_method_enum(method);
  395. }
  396. const char* Method() {
  397. return http_method_str(method);
  398. }
  399. // scheme
  400. bool IsHttps() {
  401. return strncmp(scheme.c_str(), "https", 5) == 0 ||
  402. strncmp(url.c_str(), "https://", 8) == 0;
  403. }
  404. // url
  405. void SetUrl(const char* url) {
  406. this->url = url;
  407. }
  408. const std::string& Url() {
  409. return url;
  410. }
  411. // structed url -> url
  412. void DumpUrl();
  413. // url -> structed url
  414. void ParseUrl();
  415. // /path?query#fragment
  416. std::string FullPath() { return path; }
  417. // /path
  418. std::string Path();
  419. // ?query_params
  420. template<typename T>
  421. void SetParam(const char* key, const T& t) {
  422. query_params[key] = hv::to_string(t);
  423. }
  424. std::string GetParam(const char* key, const std::string& defvalue = hv::empty_string) {
  425. auto iter = query_params.find(key);
  426. return iter == query_params.end() ? defvalue : iter->second;
  427. }
  428. // Host:
  429. std::string Host() {
  430. auto iter = headers.find("Host");
  431. return iter == headers.end() ? host : iter->second;
  432. }
  433. void FillHost(const char* host, int port = DEFAULT_HTTP_PORT);
  434. void SetHost(const char* host, int port = DEFAULT_HTTP_PORT);
  435. void SetProxy(const char* host, int port);
  436. bool IsProxy() { return proxy; }
  437. // Range: bytes=0-4095
  438. void SetRange(long from = 0, long to = -1) {
  439. headers["Range"] = hv::asprintf("bytes=%ld-%ld", from, to);
  440. }
  441. bool GetRange(long& from, long& to) {
  442. auto iter = headers.find("Range");
  443. if (iter != headers.end()) {
  444. sscanf(iter->second.c_str(), "bytes=%ld-%ld", &from, &to);
  445. return true;
  446. }
  447. from = to = 0;
  448. return false;
  449. }
  450. // Cookie:
  451. void SetCookie(const HttpCookie& cookie) {
  452. headers["Cookie"] = cookie.dump();
  453. }
  454. bool GetCookie(HttpCookie& cookie) {
  455. std::string str = GetHeader("Cookie");
  456. if (str.empty()) return false;
  457. return cookie.parse(str);
  458. }
  459. };
  460. class HV_EXPORT HttpResponse : public HttpMessage {
  461. public:
  462. http_status status_code;
  463. const char* status_message() {
  464. return http_status_str(status_code);
  465. }
  466. HttpResponse() : HttpMessage() {
  467. type = HTTP_RESPONSE;
  468. Init();
  469. }
  470. void Init() {
  471. status_code = HTTP_STATUS_OK;
  472. }
  473. virtual void Reset() {
  474. HttpMessage::Reset();
  475. Init();
  476. }
  477. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  478. // Content-Range: bytes 0-4095/10240000
  479. void SetRange(long from, long to, long total) {
  480. headers["Content-Range"] = hv::asprintf("bytes %ld-%ld/%ld", from, to, total);
  481. }
  482. bool GetRange(long& from, long& to, long& total) {
  483. auto iter = headers.find("Content-Range");
  484. if (iter != headers.end()) {
  485. sscanf(iter->second.c_str(), "bytes %ld-%ld/%ld", &from, &to, &total);
  486. return true;
  487. }
  488. from = to = total = 0;
  489. return false;
  490. }
  491. // Set-Cookie
  492. void SetCookie(const HttpCookie& cookie) {
  493. headers["Set-Cookie"] = cookie.dump();
  494. }
  495. bool GetCookie(HttpCookie& cookie) {
  496. std::string str = GetHeader("Set-Cookie");
  497. if (str.empty()) return false;
  498. return cookie.parse(str);
  499. }
  500. };
  501. typedef std::shared_ptr<HttpRequest> HttpRequestPtr;
  502. typedef std::shared_ptr<HttpResponse> HttpResponsePtr;
  503. typedef std::function<void(const HttpResponsePtr&)> HttpResponseCallback;
  504. #endif // HV_HTTP_MESSAGE_H_