HttpMessage.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. * Get, Set
  20. * GetHeader, GetParam, GetString, GetBool, GetInt, GetFloat
  21. * String, Data, File, Json
  22. *
  23. * @example
  24. * see examples/httpd
  25. *
  26. */
  27. #include <memory>
  28. #include <string>
  29. #include <map>
  30. #include <functional>
  31. #include "hexport.h"
  32. #include "hbase.h"
  33. #include "hstring.h"
  34. #include "hfile.h"
  35. #include "hpath.h"
  36. #include "httpdef.h"
  37. #include "http_content.h"
  38. struct HNetAddr {
  39. std::string ip;
  40. int port;
  41. std::string ipport() {
  42. return hv::asprintf("%s:%d", ip.c_str(), port);
  43. }
  44. };
  45. // Cookie: sessionid=1; domain=.example.com; path=/; max-age=86400; secure; httponly
  46. struct HV_EXPORT HttpCookie {
  47. std::string name;
  48. std::string value;
  49. std::string domain;
  50. std::string path;
  51. int max_age;
  52. bool secure;
  53. bool httponly;
  54. HttpCookie() {
  55. max_age = 86400;
  56. secure = false;
  57. httponly = false;
  58. }
  59. bool parse(const std::string& str);
  60. std::string dump() const;
  61. };
  62. typedef std::map<std::string, std::string, hv::StringCaseLess> http_headers;
  63. typedef std::vector<HttpCookie> http_cookies;
  64. typedef std::string http_body;
  65. typedef std::function<void(const char* data, size_t size)> http_body_cb;
  66. typedef std::function<void(const char* data, size_t size)> http_chunked_cb;
  67. class HV_EXPORT HttpMessage {
  68. public:
  69. static char s_date[32];
  70. int type;
  71. unsigned short http_major;
  72. unsigned short http_minor;
  73. http_headers headers;
  74. http_cookies cookies;
  75. http_body body;
  76. http_body_cb body_cb;
  77. http_chunked_cb chunked_cb; // Transfer-Encoding: chunked
  78. // structured content
  79. void* content; // DATA_NO_COPY
  80. int content_length;
  81. http_content_type content_type;
  82. #ifndef WITHOUT_HTTP_CONTENT
  83. hv::Json json; // APPLICATION_JSON
  84. MultiPart form; // MULTIPART_FORM_DATA
  85. hv::KeyValue kv; // X_WWW_FORM_URLENCODED
  86. // T=[bool, int, int64_t, float, double]
  87. template<typename T>
  88. T Get(const char* key, T defvalue = 0);
  89. std::string GetString(const char* key, const std::string& = "");
  90. bool GetBool(const char* key, bool defvalue = 0);
  91. int64_t GetInt(const char* key, int64_t defvalue = 0);
  92. double GetFloat(const char* key, double defvalue = 0);
  93. template<typename T>
  94. void Set(const char* key, const T& value) {
  95. switch (content_type) {
  96. case APPLICATION_JSON:
  97. json[key] = value;
  98. break;
  99. case MULTIPART_FORM_DATA:
  100. form[key] = FormData(value);
  101. break;
  102. case X_WWW_FORM_URLENCODED:
  103. kv[key] = hv::to_string(value);
  104. break;
  105. default:
  106. break;
  107. }
  108. }
  109. /*
  110. * @usage https://github.com/nlohmann/json
  111. *
  112. * null: Json(nullptr);
  113. * boolean: Json(true);
  114. * number: Json(123);
  115. * string: Json("hello");
  116. * object: Json(std::map<string, ValueType>);
  117. * Json(hv::Json::object({
  118. {"k1", "v1"},
  119. {"k2", "v2"}
  120. }));
  121. * array: Json(std::vector<ValueType>);
  122. Json(hv::Json::array(
  123. {1, 2, 3}
  124. ));
  125. */
  126. template<typename T>
  127. int Json(const T& t) {
  128. content_type = APPLICATION_JSON;
  129. json = t;
  130. return 200;
  131. }
  132. void FormFile(const char* name, const char* filepath) {
  133. content_type = MULTIPART_FORM_DATA;
  134. form[name] = FormData(NULL, filepath);
  135. }
  136. int SaveFormFile(const char* name, const char* path) {
  137. if (content_type != MULTIPART_FORM_DATA) {
  138. return HTTP_STATUS_BAD_REQUEST;
  139. }
  140. const FormData& formdata = form[name];
  141. if (formdata.content.empty()) {
  142. return HTTP_STATUS_BAD_REQUEST;
  143. }
  144. std::string filepath(path);
  145. if (HPath::isdir(path)) {
  146. filepath = HPath::join(filepath, formdata.filename);
  147. }
  148. HFile file;
  149. if (file.open(filepath.c_str(), "wb") != 0) {
  150. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  151. }
  152. file.write(formdata.content.data(), formdata.content.size());
  153. return 200;
  154. }
  155. #endif
  156. HttpMessage() {
  157. type = HTTP_BOTH;
  158. Init();
  159. }
  160. virtual ~HttpMessage() {}
  161. void Init() {
  162. http_major = 1;
  163. http_minor = 1;
  164. content = NULL;
  165. content_length = 0;
  166. content_type = CONTENT_TYPE_NONE;
  167. }
  168. virtual void Reset() {
  169. Init();
  170. headers.clear();
  171. body.clear();
  172. #ifndef WITHOUT_HTTP_CONTENT
  173. json.clear();
  174. form.clear();
  175. kv.clear();
  176. #endif
  177. }
  178. // structured-content -> content_type <-> headers Content-Type
  179. void FillContentType();
  180. // body.size -> content_length <-> headers Content-Length
  181. void FillContentLength();
  182. bool IsChunked();
  183. bool IsKeepAlive();
  184. std::string GetHeader(const char* key, const std::string& defvalue = "") {
  185. auto iter = headers.find(key);
  186. return iter == headers.end() ? defvalue : iter->second;
  187. }
  188. // headers -> string
  189. void DumpHeaders(std::string& str);
  190. // structured content -> body
  191. void DumpBody();
  192. void DumpBody(std::string& str);
  193. // body -> structured content
  194. // @retval 0:succeed
  195. int ParseBody();
  196. virtual std::string Dump(bool is_dump_headers, bool is_dump_body);
  197. void* Content() {
  198. if (content == NULL && body.size() != 0) {
  199. content = (void*)body.data();
  200. }
  201. return content;
  202. }
  203. int ContentLength() {
  204. if (content_length == 0) {
  205. FillContentLength();
  206. }
  207. return content_length;
  208. }
  209. http_content_type ContentType() {
  210. if (content_type == CONTENT_TYPE_NONE) {
  211. FillContentType();
  212. }
  213. return content_type;
  214. }
  215. void AddCookie(const HttpCookie& cookie) {
  216. cookies.push_back(cookie);
  217. }
  218. int String(const std::string& str) {
  219. content_type = TEXT_PLAIN;
  220. body = str;
  221. return 200;
  222. }
  223. int Data(void* data, int len, bool nocopy = true) {
  224. content_type = APPLICATION_OCTET_STREAM;
  225. if (nocopy) {
  226. content = data;
  227. content_length = len;
  228. } else {
  229. content_length = body.size();
  230. body.resize(content_length + len);
  231. memcpy((void*)(body.data() + content_length), data, len);
  232. content_length += len;
  233. }
  234. return 200;
  235. }
  236. int File(const char* filepath) {
  237. HFile file;
  238. if (file.open(filepath, "rb") != 0) {
  239. return HTTP_STATUS_NOT_FOUND;
  240. }
  241. const char* suffix = hv_suffixname(filepath);
  242. if (suffix) {
  243. content_type = http_content_type_enum_by_suffix(suffix);
  244. }
  245. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  246. content_type = APPLICATION_OCTET_STREAM;
  247. }
  248. file.readall(body);
  249. return 200;
  250. }
  251. int SaveFile(const char* filepath) {
  252. HFile file;
  253. if (file.open(filepath, "wb") != 0) {
  254. return HTTP_STATUS_NOT_FOUND;
  255. }
  256. file.write(body.data(), body.size());
  257. return 200;
  258. }
  259. };
  260. #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"
  261. class HV_EXPORT HttpRequest : public HttpMessage {
  262. public:
  263. http_method method;
  264. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  265. std::string url;
  266. // structured url
  267. std::string scheme;
  268. std::string host;
  269. int port;
  270. std::string path;
  271. QueryParams query_params;
  272. // client_addr
  273. HNetAddr client_addr; // for http server save client addr of request
  274. int timeout; // for http client timeout
  275. bool redirect; // for http_client redirect
  276. HttpRequest() : HttpMessage() {
  277. type = HTTP_REQUEST;
  278. Init();
  279. }
  280. void Init() {
  281. headers["User-Agent"] = DEFAULT_USER_AGENT;
  282. headers["Accept"] = "*/*";
  283. method = HTTP_GET;
  284. scheme = "http";
  285. host = "127.0.0.1";
  286. port = DEFAULT_HTTP_PORT;
  287. path = "/";
  288. timeout = 0;
  289. redirect = true;
  290. }
  291. virtual void Reset() {
  292. HttpMessage::Reset();
  293. Init();
  294. url.clear();
  295. query_params.clear();
  296. }
  297. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  298. // structed url -> url
  299. void DumpUrl();
  300. // url -> structed url
  301. void ParseUrl();
  302. std::string Host() {
  303. auto iter = headers.find("Host");
  304. return iter == headers.end() ? host : iter->second;
  305. }
  306. std::string Path() {
  307. const char* s = path.c_str();
  308. const char* e = s;
  309. while (*e && *e != '?' && *e != '#') ++e;
  310. return std::string(s, e);
  311. }
  312. std::string GetParam(const char* key, const std::string& defvalue = "") {
  313. auto iter = query_params.find(key);
  314. return iter == query_params.end() ? defvalue : iter->second;
  315. }
  316. // Range: bytes=0-4095
  317. void SetRange(long from = 0, long to = -1) {
  318. headers["Range"] = hv::asprintf("bytes=%ld-%ld", from, to);
  319. }
  320. bool GetRange(long& from, long& to) {
  321. auto iter = headers.find("Range");
  322. if (iter != headers.end()) {
  323. sscanf(iter->second.c_str(), "bytes=%ld-%ld", &from, &to);
  324. return true;
  325. }
  326. from = to = 0;
  327. return false;
  328. }
  329. // Cookie
  330. void SetCookie(const HttpCookie& cookie) {
  331. headers["Cookie"] = cookie.dump();
  332. }
  333. bool GetCookie(HttpCookie& cookie) {
  334. std::string str = GetHeader("Cookie");
  335. if (str.empty()) return false;
  336. return cookie.parse(str);
  337. }
  338. };
  339. class HV_EXPORT HttpResponse : public HttpMessage {
  340. public:
  341. http_status status_code;
  342. const char* status_message() {
  343. return http_status_str(status_code);
  344. }
  345. HttpResponse() : HttpMessage() {
  346. type = HTTP_RESPONSE;
  347. Init();
  348. }
  349. void Init() {
  350. status_code = HTTP_STATUS_OK;
  351. }
  352. virtual void Reset() {
  353. HttpMessage::Reset();
  354. Init();
  355. }
  356. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  357. // Content-Range: bytes 0-4095/10240000
  358. void SetRange(long from, long to, long total) {
  359. headers["Content-Range"] = hv::asprintf("bytes %ld-%ld/%ld", from, to, total);
  360. }
  361. bool GetRange(long& from, long& to, long& total) {
  362. auto iter = headers.find("Content-Range");
  363. if (iter != headers.end()) {
  364. sscanf(iter->second.c_str(), "bytes %ld-%ld/%ld", &from, &to, &total);
  365. return true;
  366. }
  367. from = to = total = 0;
  368. return false;
  369. }
  370. // Set-Cookie
  371. void SetCookie(const HttpCookie& cookie) {
  372. headers["Set-Cookie"] = cookie.dump();
  373. }
  374. bool GetCookie(HttpCookie& cookie) {
  375. std::string str = GetHeader("Set-Cookie");
  376. if (str.empty()) return false;
  377. return cookie.parse(str);
  378. }
  379. };
  380. typedef std::shared_ptr<HttpRequest> HttpRequestPtr;
  381. typedef std::shared_ptr<HttpResponse> HttpResponsePtr;
  382. typedef std::function<void(const HttpResponsePtr&)> HttpResponseCallback;
  383. #endif // HV_HTTP_MESSAGE_H_