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