1
0

HttpMessage.h 14 KB

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