HttpMessage.h 11 KB

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