HttpMessage.h 17 KB

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