HttpMessage.h 15 KB

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