HttpMessage.h 15 KB

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