HttpMessage.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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 SetContentType(http_content_type type) {
  298. content_type = type;
  299. }
  300. void SetContentType(const char* type) {
  301. content_type = http_content_type_enum(type);
  302. }
  303. void SetContentTypeByFilename(const char* filepath) {
  304. const char* suffix = hv_suffixname(filepath);
  305. if (suffix) {
  306. content_type = http_content_type_enum_by_suffix(suffix);
  307. }
  308. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  309. content_type = APPLICATION_OCTET_STREAM;
  310. }
  311. }
  312. void AddCookie(const HttpCookie& cookie) {
  313. cookies.push_back(cookie);
  314. }
  315. const HttpCookie& GetCookie(const std::string& name) {
  316. for (auto iter = cookies.begin(); iter != cookies.end(); ++iter) {
  317. if (iter->name == name) {
  318. return *iter;
  319. }
  320. }
  321. return NoCookie;
  322. }
  323. int String(const std::string& str) {
  324. content_type = TEXT_PLAIN;
  325. body = str;
  326. return 200;
  327. }
  328. int Data(void* data, int len, bool nocopy = true) {
  329. content_type = APPLICATION_OCTET_STREAM;
  330. if (nocopy) {
  331. content = data;
  332. content_length = len;
  333. } else {
  334. content_length = body.size();
  335. body.resize(content_length + len);
  336. memcpy((void*)(body.data() + content_length), data, len);
  337. content_length += len;
  338. }
  339. return 200;
  340. }
  341. int File(const char* filepath) {
  342. HFile file;
  343. if (file.open(filepath, "rb") != 0) {
  344. return HTTP_STATUS_NOT_FOUND;
  345. }
  346. SetContentTypeByFilename(filepath);
  347. file.readall(body);
  348. return 200;
  349. }
  350. int SaveFile(const char* filepath) {
  351. HFile file;
  352. if (file.open(filepath, "wb") != 0) {
  353. return HTTP_STATUS_NOT_FOUND;
  354. }
  355. file.write(body.data(), body.size());
  356. return 200;
  357. }
  358. };
  359. #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"
  360. #define DEFAULT_HTTP_TIMEOUT 60 // s
  361. #define DEFAULT_HTTP_CONNECT_TIMEOUT 10 // s
  362. #define DEFAULT_HTTP_FAIL_RETRY_COUNT 1
  363. #define DEFAULT_HTTP_FAIL_RETRY_DELAY 1000 // ms
  364. class HV_EXPORT HttpRequest : public HttpMessage {
  365. public:
  366. http_method method;
  367. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  368. std::string url;
  369. // structured url
  370. std::string scheme;
  371. std::string host;
  372. int port;
  373. std::string path;
  374. hv::QueryParams query_params;
  375. // client_addr
  376. hv::NetAddr client_addr; // for http server save client addr of request
  377. // for HttpClient
  378. uint16_t timeout; // unit: s
  379. uint16_t connect_timeout;// unit: s
  380. uint32_t retry_count; // just for AsyncHttpClient fail retry
  381. uint32_t retry_delay; // just for AsyncHttpClient fail retry
  382. unsigned redirect: 1;
  383. unsigned proxy : 1;
  384. HttpRequest() : HttpMessage() {
  385. type = HTTP_REQUEST;
  386. Init();
  387. }
  388. void Init() {
  389. headers["User-Agent"] = DEFAULT_HTTP_USER_AGENT;
  390. headers["Accept"] = "*/*";
  391. method = HTTP_GET;
  392. scheme = "http";
  393. host = "127.0.0.1";
  394. port = DEFAULT_HTTP_PORT;
  395. path = "/";
  396. timeout = DEFAULT_HTTP_TIMEOUT;
  397. connect_timeout = DEFAULT_HTTP_CONNECT_TIMEOUT;
  398. retry_count = DEFAULT_HTTP_FAIL_RETRY_COUNT;
  399. retry_delay = DEFAULT_HTTP_FAIL_RETRY_DELAY;
  400. redirect = 1;
  401. proxy = 0;
  402. }
  403. virtual void Reset() {
  404. HttpMessage::Reset();
  405. Init();
  406. url.clear();
  407. query_params.clear();
  408. }
  409. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  410. // method
  411. void SetMethod(const char* method) {
  412. this->method = http_method_enum(method);
  413. }
  414. const char* Method() {
  415. return http_method_str(method);
  416. }
  417. // scheme
  418. bool IsHttps() {
  419. return strncmp(scheme.c_str(), "https", 5) == 0 ||
  420. strncmp(url.c_str(), "https://", 8) == 0;
  421. }
  422. // url
  423. void SetUrl(const char* url) {
  424. this->url = url;
  425. }
  426. const std::string& Url() {
  427. return url;
  428. }
  429. // structed url -> url
  430. void DumpUrl();
  431. // url -> structed url
  432. void ParseUrl();
  433. // /path?query#fragment
  434. std::string FullPath() { return path; }
  435. // /path
  436. std::string Path();
  437. // ?query_params
  438. template<typename T>
  439. void SetParam(const char* key, const T& t) {
  440. query_params[key] = hv::to_string(t);
  441. }
  442. std::string GetParam(const char* key, const std::string& defvalue = hv::empty_string) {
  443. auto iter = query_params.find(key);
  444. return iter == query_params.end() ? defvalue : iter->second;
  445. }
  446. // Host:
  447. std::string Host() {
  448. auto iter = headers.find("Host");
  449. return iter == headers.end() ? host : iter->second;
  450. }
  451. void FillHost(const char* host, int port = DEFAULT_HTTP_PORT);
  452. void SetHost(const char* host, int port = DEFAULT_HTTP_PORT);
  453. void SetProxy(const char* host, int port);
  454. bool IsProxy() { return proxy; }
  455. // Range: bytes=0-4095
  456. void SetRange(long from = 0, long to = -1) {
  457. headers["Range"] = hv::asprintf("bytes=%ld-%ld", from, to);
  458. }
  459. bool GetRange(long& from, long& to) {
  460. auto iter = headers.find("Range");
  461. if (iter != headers.end()) {
  462. sscanf(iter->second.c_str(), "bytes=%ld-%ld", &from, &to);
  463. return true;
  464. }
  465. from = to = 0;
  466. return false;
  467. }
  468. };
  469. class HV_EXPORT HttpResponse : public HttpMessage {
  470. public:
  471. http_status status_code;
  472. const char* status_message() {
  473. return http_status_str(status_code);
  474. }
  475. HttpResponse() : HttpMessage() {
  476. type = HTTP_RESPONSE;
  477. Init();
  478. }
  479. void Init() {
  480. status_code = HTTP_STATUS_OK;
  481. }
  482. virtual void Reset() {
  483. HttpMessage::Reset();
  484. Init();
  485. }
  486. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  487. // Content-Range: bytes 0-4095/10240000
  488. void SetRange(long from, long to, long total) {
  489. headers["Content-Range"] = hv::asprintf("bytes %ld-%ld/%ld", from, to, total);
  490. }
  491. bool GetRange(long& from, long& to, long& total) {
  492. auto iter = headers.find("Content-Range");
  493. if (iter != headers.end()) {
  494. sscanf(iter->second.c_str(), "bytes %ld-%ld/%ld", &from, &to, &total);
  495. return true;
  496. }
  497. from = to = total = 0;
  498. return false;
  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_