HttpMessage.h 12 KB

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