HttpMessage.h 15 KB

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