HttpMessage.h 14 KB

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