HttpMessage.h 11 KB

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