HttpMessage.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. auto iter = form.find(name);
  193. if (iter == form.end()) {
  194. return HTTP_STATUS_BAD_REQUEST;
  195. }
  196. const auto& formdata = iter->second;
  197. if (formdata.content.empty()) {
  198. return HTTP_STATUS_BAD_REQUEST;
  199. }
  200. std::string filepath(path);
  201. if (HPath::isdir(path)) {
  202. filepath = HPath::join(filepath, formdata.filename);
  203. }
  204. HFile file;
  205. if (file.open(filepath.c_str(), "wb") != 0) {
  206. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  207. }
  208. file.write(formdata.content.data(), formdata.content.size());
  209. return 200;
  210. }
  211. // Content-Type: application/x-www-form-urlencoded
  212. template<typename T>
  213. void SetUrlEncoded(const char* key, const T& t) {
  214. kv[key] = hv::to_string(t);
  215. }
  216. const hv::KeyValue& GetUrlEncoded() {
  217. if (kv.empty() && ContentType() == X_WWW_FORM_URLENCODED) {
  218. ParseBody();
  219. }
  220. return kv;
  221. }
  222. std::string GetUrlEncoded(const char* key, const std::string& defvalue = hv::empty_string) {
  223. if (kv.empty() && ContentType() == X_WWW_FORM_URLENCODED) {
  224. ParseBody();
  225. }
  226. auto iter = kv.find(key);
  227. return iter == kv.end() ? defvalue : iter->second;
  228. }
  229. #endif
  230. HttpMessage() {
  231. type = HTTP_BOTH;
  232. Init();
  233. }
  234. virtual ~HttpMessage() {}
  235. void Init() {
  236. http_major = 1;
  237. http_minor = 1;
  238. content = NULL;
  239. content_length = 0;
  240. content_type = CONTENT_TYPE_NONE;
  241. }
  242. virtual void Reset() {
  243. Init();
  244. headers.clear();
  245. cookies.clear();
  246. body.clear();
  247. #ifndef WITHOUT_HTTP_CONTENT
  248. json.clear();
  249. form.clear();
  250. kv.clear();
  251. #endif
  252. }
  253. // structured-content -> content_type <-> headers["Content-Type"]
  254. void FillContentType();
  255. // body.size -> content_length <-> headers["Content-Length"]
  256. void FillContentLength();
  257. bool IsChunked();
  258. bool IsKeepAlive();
  259. // headers
  260. void SetHeader(const char* key, const std::string& value) {
  261. headers[key] = value;
  262. }
  263. std::string GetHeader(const char* key, const std::string& defvalue = hv::empty_string) {
  264. auto iter = headers.find(key);
  265. return iter == headers.end() ? defvalue : iter->second;
  266. }
  267. // body
  268. void SetBody(const std::string& body) {
  269. this->body = body;
  270. }
  271. const std::string& Body() {
  272. return this->body;
  273. }
  274. // headers -> string
  275. void DumpHeaders(std::string& str);
  276. // structured content -> body
  277. void DumpBody();
  278. void DumpBody(std::string& str);
  279. // body -> structured content
  280. // @retval 0:succeed
  281. int ParseBody();
  282. virtual std::string Dump(bool is_dump_headers, bool is_dump_body);
  283. void* Content() {
  284. if (content == NULL && body.size() != 0) {
  285. content = (void*)body.data();
  286. }
  287. return content;
  288. }
  289. size_t ContentLength() {
  290. if (content_length == 0) {
  291. FillContentLength();
  292. }
  293. return content_length;
  294. }
  295. http_content_type ContentType() {
  296. if (content_type == CONTENT_TYPE_NONE) {
  297. FillContentType();
  298. }
  299. return content_type;
  300. }
  301. void SetContentType(http_content_type type) {
  302. content_type = type;
  303. }
  304. void SetContentType(const char* type) {
  305. content_type = http_content_type_enum(type);
  306. }
  307. void SetContentTypeByFilename(const char* filepath) {
  308. const char* suffix = hv_suffixname(filepath);
  309. if (suffix) {
  310. content_type = http_content_type_enum_by_suffix(suffix);
  311. }
  312. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  313. content_type = APPLICATION_OCTET_STREAM;
  314. }
  315. }
  316. void AddCookie(const HttpCookie& cookie) {
  317. cookies.push_back(cookie);
  318. }
  319. const HttpCookie& GetCookie(const std::string& name) {
  320. for (auto iter = cookies.begin(); iter != cookies.end(); ++iter) {
  321. if (iter->name == name) {
  322. return *iter;
  323. }
  324. }
  325. return NoCookie;
  326. }
  327. int String(const std::string& str) {
  328. content_type = TEXT_PLAIN;
  329. body = str;
  330. return 200;
  331. }
  332. int Data(void* data, int len, bool nocopy = true) {
  333. content_type = APPLICATION_OCTET_STREAM;
  334. if (nocopy) {
  335. content = data;
  336. content_length = len;
  337. } else {
  338. content_length = body.size();
  339. body.resize(content_length + len);
  340. memcpy((void*)(body.data() + content_length), data, len);
  341. content_length += len;
  342. }
  343. return 200;
  344. }
  345. int File(const char* filepath) {
  346. HFile file;
  347. if (file.open(filepath, "rb") != 0) {
  348. return HTTP_STATUS_NOT_FOUND;
  349. }
  350. SetContentTypeByFilename(filepath);
  351. file.readall(body);
  352. return 200;
  353. }
  354. int SaveFile(const char* filepath) {
  355. HFile file;
  356. if (file.open(filepath, "wb") != 0) {
  357. return HTTP_STATUS_NOT_FOUND;
  358. }
  359. file.write(body.data(), body.size());
  360. return 200;
  361. }
  362. };
  363. #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"
  364. #define DEFAULT_HTTP_TIMEOUT 60 // s
  365. #define DEFAULT_HTTP_CONNECT_TIMEOUT 10 // s
  366. #define DEFAULT_HTTP_FAIL_RETRY_COUNT 1
  367. #define DEFAULT_HTTP_FAIL_RETRY_DELAY 1000 // ms
  368. class HV_EXPORT HttpRequest : public HttpMessage {
  369. public:
  370. http_method method;
  371. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  372. std::string url;
  373. // structured url
  374. std::string scheme;
  375. std::string host;
  376. int port;
  377. std::string path;
  378. hv::QueryParams query_params;
  379. // client_addr
  380. hv::NetAddr client_addr; // for http server save client addr of request
  381. // for HttpClient
  382. uint16_t timeout; // unit: s
  383. uint16_t connect_timeout;// unit: s
  384. uint32_t retry_count; // just for AsyncHttpClient fail retry
  385. uint32_t retry_delay; // just for AsyncHttpClient fail retry
  386. unsigned redirect: 1;
  387. unsigned proxy : 1;
  388. HttpRequest() : HttpMessage() {
  389. type = HTTP_REQUEST;
  390. Init();
  391. }
  392. void Init() {
  393. headers["User-Agent"] = DEFAULT_HTTP_USER_AGENT;
  394. headers["Accept"] = "*/*";
  395. method = HTTP_GET;
  396. scheme = "http";
  397. host = "127.0.0.1";
  398. port = DEFAULT_HTTP_PORT;
  399. path = "/";
  400. timeout = DEFAULT_HTTP_TIMEOUT;
  401. connect_timeout = DEFAULT_HTTP_CONNECT_TIMEOUT;
  402. retry_count = DEFAULT_HTTP_FAIL_RETRY_COUNT;
  403. retry_delay = DEFAULT_HTTP_FAIL_RETRY_DELAY;
  404. redirect = 1;
  405. proxy = 0;
  406. }
  407. virtual void Reset() {
  408. HttpMessage::Reset();
  409. Init();
  410. url.clear();
  411. query_params.clear();
  412. }
  413. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  414. // method
  415. void SetMethod(const char* method) {
  416. this->method = http_method_enum(method);
  417. }
  418. const char* Method() {
  419. return http_method_str(method);
  420. }
  421. // scheme
  422. bool IsHttps() {
  423. return strncmp(scheme.c_str(), "https", 5) == 0 ||
  424. strncmp(url.c_str(), "https://", 8) == 0;
  425. }
  426. // url
  427. void SetUrl(const char* url) {
  428. this->url = url;
  429. }
  430. const std::string& Url() {
  431. return url;
  432. }
  433. // structed url -> url
  434. void DumpUrl();
  435. // url -> structed url
  436. void ParseUrl();
  437. // /path?query#fragment
  438. std::string FullPath() { return path; }
  439. // /path
  440. std::string Path();
  441. // ?query_params
  442. template<typename T>
  443. void SetParam(const char* key, const T& t) {
  444. query_params[key] = hv::to_string(t);
  445. }
  446. std::string GetParam(const char* key, const std::string& defvalue = hv::empty_string) {
  447. auto iter = query_params.find(key);
  448. return iter == query_params.end() ? defvalue : iter->second;
  449. }
  450. // Host:
  451. std::string Host() {
  452. auto iter = headers.find("Host");
  453. return iter == headers.end() ? host : iter->second;
  454. }
  455. void FillHost(const char* host, int port = DEFAULT_HTTP_PORT);
  456. void SetHost(const char* host, int port = DEFAULT_HTTP_PORT);
  457. void SetProxy(const char* host, int port);
  458. bool IsProxy() { return proxy; }
  459. void SetTimeout(int sec) { timeout = sec; }
  460. void SetConnectTimeout(int sec) { connect_timeout = sec; }
  461. void AllowRedirect(bool on = true) { redirect = on; }
  462. // NOTE: SetRetry just for AsyncHttpClient
  463. void SetRetry(int count = DEFAULT_HTTP_FAIL_RETRY_COUNT,
  464. int delay = DEFAULT_HTTP_FAIL_RETRY_DELAY) {
  465. retry_count = count;
  466. retry_delay = delay;
  467. }
  468. // Range: bytes=0-4095
  469. void SetRange(long from = 0, long to = -1) {
  470. headers["Range"] = hv::asprintf("bytes=%ld-%ld", from, to);
  471. }
  472. bool GetRange(long& from, long& to) {
  473. auto iter = headers.find("Range");
  474. if (iter != headers.end()) {
  475. sscanf(iter->second.c_str(), "bytes=%ld-%ld", &from, &to);
  476. return true;
  477. }
  478. from = to = 0;
  479. return false;
  480. }
  481. };
  482. class HV_EXPORT HttpResponse : public HttpMessage {
  483. public:
  484. http_status status_code;
  485. const char* status_message() {
  486. return http_status_str(status_code);
  487. }
  488. HttpResponse() : HttpMessage() {
  489. type = HTTP_RESPONSE;
  490. Init();
  491. }
  492. void Init() {
  493. status_code = HTTP_STATUS_OK;
  494. }
  495. virtual void Reset() {
  496. HttpMessage::Reset();
  497. Init();
  498. }
  499. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  500. // Content-Range: bytes 0-4095/10240000
  501. void SetRange(long from, long to, long total) {
  502. headers["Content-Range"] = hv::asprintf("bytes %ld-%ld/%ld", from, to, total);
  503. }
  504. bool GetRange(long& from, long& to, long& total) {
  505. auto iter = headers.find("Content-Range");
  506. if (iter != headers.end()) {
  507. sscanf(iter->second.c_str(), "bytes %ld-%ld/%ld", &from, &to, &total);
  508. return true;
  509. }
  510. from = to = total = 0;
  511. return false;
  512. }
  513. int Redirect(const std::string& location, http_status status = HTTP_STATUS_FOUND) {
  514. status_code = status;
  515. headers["Location"] = location;
  516. return status_code;
  517. }
  518. };
  519. typedef std::shared_ptr<HttpRequest> HttpRequestPtr;
  520. typedef std::shared_ptr<HttpResponse> HttpResponsePtr;
  521. typedef std::function<void(const HttpResponsePtr&)> HttpResponseCallback;
  522. #endif // HV_HTTP_MESSAGE_H_