Http2Session.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. #ifdef WITH_NGHTTP2
  2. #include "Http2Session.h"
  3. static nghttp2_nv make_nv(const char* name, const char* value) {
  4. nghttp2_nv nv;
  5. nv.name = (uint8_t*)name;
  6. nv.value = (uint8_t*)value;
  7. nv.namelen = strlen(name);
  8. nv.valuelen = strlen(value);
  9. nv.flags = NGHTTP2_NV_FLAG_NONE;
  10. return nv;
  11. }
  12. static nghttp2_nv make_nv2(const char* name, const char* value,
  13. int namelen, int valuelen) {
  14. nghttp2_nv nv;
  15. nv.name = (uint8_t*)name;
  16. nv.value = (uint8_t*)value;
  17. nv.namelen = namelen; nv.valuelen = valuelen;
  18. nv.flags = NGHTTP2_NV_FLAG_NONE;
  19. return nv;
  20. }
  21. static void print_frame_hd(const nghttp2_frame_hd* hd) {
  22. printd("[frame] length=%d type=%x flags=%x stream_id=%d\n",
  23. (int)hd->length, (int)hd->type, (int)hd->flags, hd->stream_id);
  24. }
  25. static int on_header_callback(nghttp2_session *session,
  26. const nghttp2_frame *frame,
  27. const uint8_t *name, size_t namelen,
  28. const uint8_t *value, size_t valuelen,
  29. uint8_t flags, void *userdata);
  30. static int on_data_chunk_recv_callback(nghttp2_session *session,
  31. uint8_t flags, int32_t stream_id, const uint8_t *data,
  32. size_t len, void *userdata);
  33. static int on_frame_recv_callback(nghttp2_session *session,
  34. const nghttp2_frame *frame, void *userdata);
  35. /*
  36. static ssize_t data_source_read_callback(nghttp2_session *session,
  37. int32_t stream_id, uint8_t *buf, size_t length,
  38. uint32_t *data_flags, nghttp2_data_source *source, void *userdata);
  39. */
  40. Http2Session::Http2Session(http_session_type type) {
  41. this->type = type;
  42. if (cbs == NULL) {
  43. nghttp2_session_callbacks_new(&cbs);
  44. nghttp2_session_callbacks_set_on_header_callback(cbs, on_header_callback);
  45. nghttp2_session_callbacks_set_on_data_chunk_recv_callback(cbs, on_data_chunk_recv_callback);
  46. nghttp2_session_callbacks_set_on_frame_recv_callback(cbs, on_frame_recv_callback);
  47. }
  48. if (type == HTTP_CLIENT) {
  49. nghttp2_session_client_new(&session, cbs, NULL);
  50. state = HSS_SEND_MAGIC;
  51. }
  52. else if (type == HTTP_SERVER) {
  53. nghttp2_session_server_new(&session, cbs, NULL);
  54. state = HSS_SEND_SETTINGS;
  55. }
  56. nghttp2_session_set_user_data(session, this);
  57. submited = NULL;
  58. parsed = NULL;
  59. stream_id = -1;
  60. stream_closed = 0;
  61. nghttp2_settings_entry settings[] = {
  62. {NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, 100}
  63. };
  64. nghttp2_submit_settings(session, NGHTTP2_FLAG_NONE, settings, ARRAY_SIZE(settings));
  65. state = HSS_SEND_SETTINGS;
  66. }
  67. Http2Session::~Http2Session() {
  68. if (session) {
  69. nghttp2_session_del(session);
  70. session = NULL;
  71. }
  72. }
  73. int Http2Session::GetSendData(char** data, size_t* len) {
  74. // HTTP2_MAGIC,HTTP2_SETTINGS,HTTP2_HEADERS
  75. *len = nghttp2_session_mem_send(session, (const uint8_t**)data);
  76. printd("nghttp2_session_mem_send %d\n", *len);
  77. if (*len != 0) return *len;
  78. if (submited == NULL) return 0;
  79. // HTTP2_DATA
  80. if (state == HSS_SEND_HEADERS) {
  81. void* content = submited->Content();
  82. int content_length = submited->ContentLength();
  83. // HTTP2 DATA framehd
  84. state = HSS_SEND_DATA_FRAME_HD;
  85. http2_frame_hd framehd;
  86. framehd.length = content_length;
  87. framehd.type = HTTP2_DATA;
  88. framehd.flags = HTTP2_FLAG_END_STREAM;
  89. framehd.stream_id = stream_id;
  90. *data = (char*)frame_hdbuf;
  91. *len = HTTP2_FRAME_HDLEN;
  92. printd("HTTP2 DATA framehd-------------------\n");
  93. if (submited->ContentType() == APPLICATION_GRPC) {
  94. printd("grpc DATA framehd-----------------\n");
  95. grpc_message_hd msghd;
  96. msghd.flags = 0;
  97. msghd.length = content_length;
  98. if (type == HTTP_SERVER) {
  99. // grpc server send grpc-status in HTTP2 header frame
  100. framehd.flags = HTTP2_FLAG_NONE;
  101. #ifdef TEST_PROTOBUF
  102. // @test protobuf
  103. // message StringMessage {
  104. // string str = 1;
  105. // }
  106. int protobuf_taglen = 0;
  107. int tag = PROTOBUF_MAKE_TAG(1, WIRE_TYPE_LENGTH_DELIMITED);
  108. unsigned char* p = frame_hdbuf + HTTP2_FRAME_HDLEN + GRPC_MESSAGE_HDLEN;
  109. int bytes = varint_encode(tag, p);
  110. protobuf_taglen += bytes;
  111. p += bytes;
  112. bytes = varint_encode(content_length, p);
  113. protobuf_taglen += bytes;
  114. msghd.length += protobuf_taglen;
  115. framehd.length += protobuf_taglen;
  116. *len += protobuf_taglen;
  117. #endif
  118. }
  119. grpc_message_hd_pack(&msghd, frame_hdbuf + HTTP2_FRAME_HDLEN);
  120. framehd.length += GRPC_MESSAGE_HDLEN;
  121. *len += GRPC_MESSAGE_HDLEN;
  122. }
  123. http2_frame_hd_pack(&framehd, frame_hdbuf);
  124. }
  125. else if (state == HSS_SEND_DATA_FRAME_HD) {
  126. // HTTP2 DATA
  127. printd("HTTP2 DATA-------------------\n");
  128. void* content = submited->Content();
  129. int content_length = submited->ContentLength();
  130. if (content_length == 0) {
  131. state = HSS_SEND_DONE;
  132. }
  133. else {
  134. state = HSS_SEND_DATA;
  135. *data = (char*)content;
  136. *len = content_length;
  137. }
  138. }
  139. else if (state == HSS_SEND_DATA) {
  140. state = HSS_SEND_DONE;
  141. if (submited->ContentType() == APPLICATION_GRPC) {
  142. if (type == HTTP_SERVER) {
  143. // grpc HEADERS grpc-status
  144. printd("grpc HEADERS grpc-status-----------------\n");
  145. int flags = NGHTTP2_FLAG_END_STREAM | NGHTTP2_FLAG_END_HEADERS;
  146. nghttp2_nv nv = make_nv("grpc-status", "0");
  147. nghttp2_submit_headers(session, flags, stream_id, NULL, &nv, 1, NULL);
  148. *len = nghttp2_session_mem_send(session, (const uint8_t**)data);
  149. }
  150. }
  151. }
  152. printd("GetSendData %d\n", *len);
  153. return *len;
  154. }
  155. int Http2Session::FeedRecvData(const char* data, size_t len) {
  156. printd("nghttp2_session_mem_recv %d\n", len);
  157. size_t ret = nghttp2_session_mem_recv(session, (const uint8_t*)data, len);
  158. if (ret != len) {
  159. error = ret;
  160. }
  161. return (int)ret;
  162. }
  163. bool Http2Session::WantRecv() {
  164. return stream_id == -1 || stream_closed == 0;
  165. }
  166. int Http2Session::SubmitRequest(HttpRequest* req) {
  167. submited = req;
  168. req->FillContentType();
  169. req->FillContentLength();
  170. if (req->ContentType() == APPLICATION_GRPC) {
  171. req->method = HTTP_POST;
  172. req->headers["te"] = "trailers";
  173. req->headers["user-agent"] = "grpc-c++/1.16.0 grpc-c/6.0.0 (linux; nghttp2; hw)";
  174. req->headers["accept-encoding"] = "identity";
  175. req->headers["grpc-accept-encoding"] = "identity";
  176. }
  177. std::vector<nghttp2_nv> nvs;
  178. char c_str[256] = {0};
  179. req->ParseUrl();
  180. nvs.push_back(make_nv(":method", http_method_str(req->method)));
  181. nvs.push_back(make_nv(":path", req->path.c_str()));
  182. nvs.push_back(make_nv(":scheme", req->https ? "https" : "http"));
  183. if (req->port == 0 ||
  184. req->port == DEFAULT_HTTP_PORT ||
  185. req->port == DEFAULT_HTTPS_PORT) {
  186. nvs.push_back(make_nv(":authority", req->host.c_str()));
  187. }
  188. else {
  189. snprintf(c_str, sizeof(c_str), "%s:%d", req->host.c_str(), req->port);
  190. nvs.push_back(make_nv(":authority", c_str));
  191. }
  192. const char* name;
  193. const char* value;
  194. for (auto& header : req->headers) {
  195. name = header.first.c_str();
  196. value = header.second.c_str();
  197. strlower((char*)name);
  198. if (strcmp(name, "connection") == 0) {
  199. // HTTP2 default keep-alive
  200. continue;
  201. }
  202. if (strcmp(name, "content-length") == 0) {
  203. // HTTP2 have frame_hd.length
  204. continue;
  205. }
  206. nvs.push_back(make_nv2(name, value, header.first.size(), header.second.size()));
  207. }
  208. int flags = NGHTTP2_FLAG_END_HEADERS;
  209. // we set EOS on DATA frame
  210. stream_id = nghttp2_submit_headers(session, flags, -1, NULL, &nvs[0], nvs.size(), NULL);
  211. // avoid DATA_SOURCE_COPY, we do not use nghttp2_submit_data
  212. // nghttp2_data_provider data_prd;
  213. // data_prd.read_callback = data_source_read_callback;
  214. //stream_id = nghttp2_submit_request(session, NULL, &nvs[0], nvs.size(), &data_prd, NULL);
  215. stream_closed = 0;
  216. state = HSS_SEND_HEADERS;
  217. return 0;
  218. }
  219. int Http2Session::SubmitResponse(HttpResponse* res) {
  220. submited = res;
  221. res->FillContentType();
  222. res->FillContentLength();
  223. if (parsed && parsed->ContentType() == APPLICATION_GRPC) {
  224. // correct content_type: application/grpc
  225. if (res->ContentType() != APPLICATION_GRPC) {
  226. res->content_type = APPLICATION_GRPC;
  227. res->headers["content-type"] = http_content_type_str(APPLICATION_GRPC);
  228. }
  229. //res->headers["accept-encoding"] = "identity";
  230. //res->headers["grpc-accept-encoding"] = "identity";
  231. //res->headers["grpc-status"] = "0";
  232. #ifdef TEST_PROTOBUF
  233. res->status_code = HTTP_STATUS_OK;
  234. #endif
  235. }
  236. std::vector<nghttp2_nv> nvs;
  237. char c_str[256] = {0};
  238. snprintf(c_str, sizeof(c_str), "%d", res->status_code);
  239. nvs.push_back(make_nv(":status", c_str));
  240. const char* name;
  241. const char* value;
  242. for (auto& header : res->headers) {
  243. name = header.first.c_str();
  244. value = header.second.c_str();
  245. strlower((char*)name);
  246. if (strcmp(name, "connection") == 0) {
  247. // HTTP2 default keep-alive
  248. continue;
  249. }
  250. if (strcmp(name, "content-length") == 0) {
  251. // HTTP2 have frame_hd.length
  252. continue;
  253. }
  254. nvs.push_back(make_nv2(name, value, header.first.size(), header.second.size()));
  255. }
  256. int flags = NGHTTP2_FLAG_END_HEADERS;
  257. // we set EOS on DATA frame
  258. if (stream_id == -1) {
  259. // upgrade
  260. nghttp2_session_upgrade(session, NULL, 0, NULL);
  261. stream_id = 1;
  262. }
  263. nghttp2_submit_headers(session, flags, stream_id, NULL, &nvs[0], nvs.size(), NULL);
  264. // avoid DATA_SOURCE_COPY, we do not use nghttp2_submit_data
  265. // data_prd.read_callback = data_source_read_callback;
  266. //nghttp2_submit_response(session, stream_id, &nvs[0], nvs.size(), &data_prd);
  267. stream_closed = 0;
  268. state = HSS_SEND_HEADERS;
  269. return 0;
  270. }
  271. int Http2Session::InitResponse(HttpResponse* res) {
  272. res->Reset();
  273. res->http_major = 2;
  274. res->http_minor = 0;
  275. parsed = res;
  276. return 0;
  277. }
  278. int Http2Session::InitRequest(HttpRequest* req) {
  279. req->Reset();
  280. req->http_major = 2;
  281. req->http_minor = 0;
  282. parsed = req;
  283. return 0;
  284. }
  285. int Http2Session::GetError() {
  286. return error;
  287. }
  288. const char* Http2Session::StrError(int error) {
  289. return nghttp2_http2_strerror(error);
  290. }
  291. nghttp2_session_callbacks* Http2Session::cbs = NULL;
  292. int on_header_callback(nghttp2_session *session,
  293. const nghttp2_frame *frame,
  294. const uint8_t *_name, size_t namelen,
  295. const uint8_t *_value, size_t valuelen,
  296. uint8_t flags, void *userdata) {
  297. printd("on_header_callback\n");
  298. print_frame_hd(&frame->hd);
  299. const char* name = (const char*)_name;
  300. const char* value = (const char*)_value;
  301. printd("%s: %s\n", name, value);
  302. Http2Session* hss = (Http2Session*)userdata;
  303. if (*name == ':') {
  304. if (hss->parsed->type == HTTP_REQUEST) {
  305. // :method :path :scheme :authority
  306. HttpRequest* req = (HttpRequest*)hss->parsed;
  307. if (strcmp(name, ":method") == 0) {
  308. req->method = http_method_enum(value);
  309. }
  310. else if (strcmp(name, ":path") == 0) {
  311. req->url = value;
  312. }
  313. else if (strcmp(name, ":scheme") == 0) {
  314. req->headers["Scheme"] = value;
  315. }
  316. else if (strcmp(name, ":authority") == 0) {
  317. req->headers["Host"] = value;
  318. }
  319. }
  320. else if (hss->parsed->type == HTTP_RESPONSE) {
  321. HttpResponse* res = (HttpResponse*)hss->parsed;
  322. if (strcmp(name, ":status") == 0) {
  323. res->status_code = (http_status)atoi(value);
  324. }
  325. }
  326. }
  327. else {
  328. hss->parsed->headers[name] = value;
  329. if (strcmp(name, "content-type") == 0) {
  330. hss->parsed->content_type = http_content_type_enum(value);
  331. }
  332. }
  333. return 0;
  334. }
  335. int on_data_chunk_recv_callback(nghttp2_session *session,
  336. uint8_t flags, int32_t stream_id, const uint8_t *data,
  337. size_t len, void *userdata) {
  338. printd("on_data_chunk_recv_callback\n");
  339. printd("stream_id=%d length=%d\n", stream_id, (int)len);
  340. //printd("%.*s\n", (int)len, data);
  341. Http2Session* hss = (Http2Session*)userdata;
  342. if (hss->parsed->ContentType() == APPLICATION_GRPC) {
  343. // grpc_message_hd
  344. printd("grpc Length-Prefixed-Message-----------------\n");
  345. if (len >= GRPC_MESSAGE_HDLEN) {
  346. data += GRPC_MESSAGE_HDLEN;
  347. len -= GRPC_MESSAGE_HDLEN;
  348. }
  349. }
  350. hss->parsed->body.insert(hss->parsed->body.size(), (const char*)data, len);
  351. return 0;
  352. }
  353. int on_frame_recv_callback(nghttp2_session *session,
  354. const nghttp2_frame *frame, void *userdata) {
  355. printd("on_frame_recv_callback\n");
  356. print_frame_hd(&frame->hd);
  357. Http2Session* hss = (Http2Session*)userdata;
  358. switch (frame->hd.type) {
  359. case NGHTTP2_DATA:
  360. case NGHTTP2_HEADERS:
  361. hss->stream_id = frame->hd.stream_id;
  362. if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
  363. printd("on_stream_closed stream_id=%d\n", hss->stream_id);
  364. hss->stream_closed = 1;
  365. }
  366. break;
  367. case NGHTTP2_PING:
  368. break;
  369. default:
  370. break;
  371. }
  372. return 0;
  373. }
  374. #endif