HttpMessage.h 13 KB

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