HttpMessage.h 10 KB

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