HttpMessage.h 15 KB

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