HttpMessage.h 11 KB

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