HttpMessage.h 15 KB

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