1
0

HttpMessage.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. bool IsUpgrade();
  245. // headers
  246. void SetHeader(const char* key, const std::string& value);
  247. std::string GetHeader(const char* key, const std::string& defvalue = hv::empty_string);
  248. // cookies
  249. void AddCookie(const HttpCookie& cookie);
  250. const HttpCookie& GetCookie(const std::string& name);
  251. // body
  252. void SetBody(const std::string& body);
  253. const std::string& Body();
  254. // headers -> string
  255. void DumpHeaders(std::string& str);
  256. // structured content -> body
  257. void DumpBody();
  258. void DumpBody(std::string& str);
  259. // body -> structured content
  260. // @retval 0:succeed
  261. int ParseBody();
  262. virtual std::string Dump(bool is_dump_headers, bool is_dump_body);
  263. void* Content() {
  264. if (content == NULL && body.size() != 0) {
  265. content = (void*)body.data();
  266. }
  267. return content;
  268. }
  269. size_t ContentLength() {
  270. if (content_length == 0) {
  271. FillContentLength();
  272. }
  273. return content_length;
  274. }
  275. http_content_type ContentType() {
  276. if (content_type == CONTENT_TYPE_NONE) {
  277. FillContentType();
  278. }
  279. return content_type;
  280. }
  281. void SetContentType(http_content_type type) {
  282. content_type = type;
  283. }
  284. void SetContentType(const char* type) {
  285. content_type = http_content_type_enum(type);
  286. }
  287. void SetContentTypeByFilename(const char* filepath) {
  288. const char* suffix = hv_suffixname(filepath);
  289. if (suffix) {
  290. content_type = http_content_type_enum_by_suffix(suffix);
  291. }
  292. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  293. content_type = APPLICATION_OCTET_STREAM;
  294. }
  295. }
  296. int String(const std::string& str) {
  297. content_type = TEXT_PLAIN;
  298. body = str;
  299. return 200;
  300. }
  301. int Data(void* data, int len, bool nocopy = true) {
  302. content_type = APPLICATION_OCTET_STREAM;
  303. if (nocopy) {
  304. content = data;
  305. content_length = len;
  306. } else {
  307. content_length = body.size();
  308. body.resize(content_length + len);
  309. memcpy((void*)(body.data() + content_length), data, len);
  310. content_length += len;
  311. }
  312. return 200;
  313. }
  314. int File(const char* filepath) {
  315. HFile file;
  316. if (file.open(filepath, "rb") != 0) {
  317. return HTTP_STATUS_NOT_FOUND;
  318. }
  319. SetContentTypeByFilename(filepath);
  320. file.readall(body);
  321. return 200;
  322. }
  323. int SaveFile(const char* filepath) {
  324. HFile file;
  325. if (file.open(filepath, "wb") != 0) {
  326. return HTTP_STATUS_NOT_FOUND;
  327. }
  328. file.write(body.data(), body.size());
  329. return 200;
  330. }
  331. };
  332. #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"
  333. #define DEFAULT_HTTP_TIMEOUT 60 // s
  334. #define DEFAULT_HTTP_CONNECT_TIMEOUT 10 // s
  335. #define DEFAULT_HTTP_FAIL_RETRY_COUNT 1
  336. #define DEFAULT_HTTP_FAIL_RETRY_DELAY 1000 // ms
  337. class HV_EXPORT HttpRequest : public HttpMessage {
  338. public:
  339. http_method method;
  340. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  341. std::string url;
  342. // structured url
  343. std::string scheme;
  344. std::string host;
  345. int port;
  346. std::string path;
  347. hv::QueryParams query_params;
  348. // client_addr
  349. hv::NetAddr client_addr; // for http server save client addr of request
  350. // for HttpClient
  351. uint16_t timeout; // unit: s
  352. uint16_t connect_timeout;// unit: s
  353. uint32_t retry_count;
  354. uint32_t retry_delay; // unit: ms
  355. unsigned redirect: 1;
  356. unsigned proxy : 1;
  357. unsigned cancel : 1;
  358. HttpRequest();
  359. void Init();
  360. virtual void Reset();
  361. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  362. // method
  363. void SetMethod(const char* method) {
  364. this->method = http_method_enum(method);
  365. }
  366. const char* Method() {
  367. return http_method_str(method);
  368. }
  369. // scheme
  370. bool IsHttps() {
  371. return strncmp(scheme.c_str(), "https", 5) == 0 ||
  372. strncmp(url.c_str(), "https://", 8) == 0;
  373. }
  374. // url
  375. void SetUrl(const char* url) {
  376. this->url = url;
  377. }
  378. const std::string& Url() {
  379. return url;
  380. }
  381. // structed url -> url
  382. void DumpUrl();
  383. // url -> structed url
  384. void ParseUrl();
  385. // /path?query#fragment
  386. std::string FullPath() { return path; }
  387. // /path
  388. std::string Path();
  389. // ?query_params
  390. template<typename T>
  391. void SetParam(const char* key, const T& t) {
  392. query_params[key] = hv::to_string(t);
  393. }
  394. std::string GetParam(const char* key, const std::string& defvalue = hv::empty_string) {
  395. auto iter = query_params.find(key);
  396. return iter == query_params.end() ? defvalue : iter->second;
  397. }
  398. // Host:
  399. std::string Host() {
  400. auto iter = headers.find("Host");
  401. return iter == headers.end() ? host : iter->second;
  402. }
  403. void FillHost(const char* host, int port = DEFAULT_HTTP_PORT);
  404. void SetHost(const char* host, int port = DEFAULT_HTTP_PORT);
  405. void SetProxy(const char* host, int port);
  406. bool IsProxy() { return proxy; }
  407. // Auth
  408. void SetAuth(const std::string& auth);
  409. void SetBasicAuth(const std::string& username, const std::string& password);
  410. void SetBearerTokenAuth(const std::string& token);
  411. void SetTimeout(int sec) { timeout = sec; }
  412. void SetConnectTimeout(int sec) { connect_timeout = sec; }
  413. void AllowRedirect(bool on = true) { redirect = on; }
  414. // NOTE: SetRetry just for AsyncHttpClient
  415. void SetRetry(int count = DEFAULT_HTTP_FAIL_RETRY_COUNT,
  416. int delay = DEFAULT_HTTP_FAIL_RETRY_DELAY) {
  417. retry_count = count;
  418. retry_delay = delay;
  419. }
  420. void Cancel() { cancel = 1; }
  421. bool IsCanceled() { return cancel == 1; }
  422. // Range: bytes=0-4095
  423. void SetRange(long from = 0, long to = -1);
  424. bool GetRange(long& from, long& to);
  425. };
  426. class HV_EXPORT HttpResponse : public HttpMessage {
  427. public:
  428. http_status status_code;
  429. const char* status_message() {
  430. return http_status_str(status_code);
  431. }
  432. HttpResponse();
  433. void Init();
  434. virtual void Reset();
  435. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  436. // Content-Range: bytes 0-4095/10240000
  437. void SetRange(long from, long to, long total);
  438. bool GetRange(long& from, long& to, long& total);
  439. int Redirect(const std::string& location, http_status status = HTTP_STATUS_FOUND) {
  440. status_code = status;
  441. SetHeader("Location", location);
  442. return status_code;
  443. }
  444. };
  445. typedef std::shared_ptr<HttpRequest> HttpRequestPtr;
  446. typedef std::shared_ptr<HttpResponse> HttpResponsePtr;
  447. typedef std::function<void(const HttpResponsePtr&)> HttpResponseCallback;
  448. #endif // HV_HTTP_MESSAGE_H_