HttpMessage.h 14 KB

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