h2_decoder.c 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  1. /**
  2. * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. * SPDX-License-Identifier: Apache-2.0.
  4. */
  5. #include <aws/http/private/h2_decoder.h>
  6. #include <aws/http/private/hpack.h>
  7. #include <aws/http/private/strutil.h>
  8. #include <aws/common/string.h>
  9. #include <aws/http/status_code.h>
  10. #include <aws/io/logging.h>
  11. #include <inttypes.h>
  12. #ifdef _MSC_VER
  13. # pragma warning(disable : 4204) /* Declared initializers */
  14. #endif
  15. /***********************************************************************************************************************
  16. * Constants
  17. **********************************************************************************************************************/
  18. /* The scratch buffers data for states with bytes_required > 0. Must be big enough for largest state */
  19. static const size_t s_scratch_space_size = 9;
  20. /* Stream ids & dependencies should only write the bottom 31 bits */
  21. static const uint32_t s_31_bit_mask = UINT32_MAX >> 1;
  22. /* initial size for cookie buffer, buffer will grow if needed */
  23. static const size_t s_decoder_cookie_buffer_initial_size = 512;
  24. #define DECODER_LOGF(level, decoder, text, ...) \
  25. AWS_LOGF_##level(AWS_LS_HTTP_DECODER, "id=%p " text, (decoder)->logging_id, __VA_ARGS__)
  26. #define DECODER_LOG(level, decoder, text) DECODER_LOGF(level, decoder, "%s", text)
  27. #define DECODER_CALL_VTABLE(decoder, fn) \
  28. do { \
  29. if ((decoder)->vtable->fn) { \
  30. DECODER_LOG(TRACE, decoder, "Invoking callback " #fn); \
  31. struct aws_h2err vtable_err = (decoder)->vtable->fn((decoder)->userdata); \
  32. if (aws_h2err_failed(vtable_err)) { \
  33. DECODER_LOGF( \
  34. ERROR, \
  35. decoder, \
  36. "Error from callback " #fn ", %s->%s", \
  37. aws_http2_error_code_to_str(vtable_err.h2_code), \
  38. aws_error_name(vtable_err.aws_code)); \
  39. return vtable_err; \
  40. } \
  41. } \
  42. } while (false)
  43. #define DECODER_CALL_VTABLE_ARGS(decoder, fn, ...) \
  44. do { \
  45. if ((decoder)->vtable->fn) { \
  46. DECODER_LOG(TRACE, decoder, "Invoking callback " #fn); \
  47. struct aws_h2err vtable_err = (decoder)->vtable->fn(__VA_ARGS__, (decoder)->userdata); \
  48. if (aws_h2err_failed(vtable_err)) { \
  49. DECODER_LOGF( \
  50. ERROR, \
  51. decoder, \
  52. "Error from callback " #fn ", %s->%s", \
  53. aws_http2_error_code_to_str(vtable_err.h2_code), \
  54. aws_error_name(vtable_err.aws_code)); \
  55. return vtable_err; \
  56. } \
  57. } \
  58. } while (false)
  59. #define DECODER_CALL_VTABLE_STREAM(decoder, fn) \
  60. DECODER_CALL_VTABLE_ARGS(decoder, fn, (decoder)->frame_in_progress.stream_id)
  61. #define DECODER_CALL_VTABLE_STREAM_ARGS(decoder, fn, ...) \
  62. DECODER_CALL_VTABLE_ARGS(decoder, fn, (decoder)->frame_in_progress.stream_id, __VA_ARGS__)
  63. /* for storing things in array without worrying about the specific values of the other AWS_HTTP_HEADER_XYZ enums */
  64. enum pseudoheader_name {
  65. PSEUDOHEADER_UNKNOWN = -1, /* Unrecognized value */
  66. /* Request pseudo-headers */
  67. PSEUDOHEADER_METHOD,
  68. PSEUDOHEADER_SCHEME,
  69. PSEUDOHEADER_AUTHORITY,
  70. PSEUDOHEADER_PATH,
  71. /* Response pseudo-headers */
  72. PSEUDOHEADER_STATUS,
  73. PSEUDOHEADER_COUNT, /* Number of valid enums */
  74. };
  75. static const struct aws_byte_cursor *s_pseudoheader_name_to_cursor[PSEUDOHEADER_COUNT] = {
  76. [PSEUDOHEADER_METHOD] = &aws_http_header_method,
  77. [PSEUDOHEADER_SCHEME] = &aws_http_header_scheme,
  78. [PSEUDOHEADER_AUTHORITY] = &aws_http_header_authority,
  79. [PSEUDOHEADER_PATH] = &aws_http_header_path,
  80. [PSEUDOHEADER_STATUS] = &aws_http_header_status,
  81. };
  82. static const enum aws_http_header_name s_pseudoheader_to_header_name[PSEUDOHEADER_COUNT] = {
  83. [PSEUDOHEADER_METHOD] = AWS_HTTP_HEADER_METHOD,
  84. [PSEUDOHEADER_SCHEME] = AWS_HTTP_HEADER_SCHEME,
  85. [PSEUDOHEADER_AUTHORITY] = AWS_HTTP_HEADER_AUTHORITY,
  86. [PSEUDOHEADER_PATH] = AWS_HTTP_HEADER_PATH,
  87. [PSEUDOHEADER_STATUS] = AWS_HTTP_HEADER_STATUS,
  88. };
  89. static enum pseudoheader_name s_header_to_pseudoheader_name(enum aws_http_header_name name) {
  90. /* The compiled switch statement is actually faster than array lookup with bounds-checking.
  91. * (the lookup arrays above don't need to do bounds-checking) */
  92. switch (name) {
  93. case AWS_HTTP_HEADER_METHOD:
  94. return PSEUDOHEADER_METHOD;
  95. case AWS_HTTP_HEADER_SCHEME:
  96. return PSEUDOHEADER_SCHEME;
  97. case AWS_HTTP_HEADER_AUTHORITY:
  98. return PSEUDOHEADER_AUTHORITY;
  99. case AWS_HTTP_HEADER_PATH:
  100. return PSEUDOHEADER_PATH;
  101. case AWS_HTTP_HEADER_STATUS:
  102. return PSEUDOHEADER_STATUS;
  103. default:
  104. return PSEUDOHEADER_UNKNOWN;
  105. }
  106. }
  107. /***********************************************************************************************************************
  108. * State Machine
  109. **********************************************************************************************************************/
  110. typedef struct aws_h2err(state_fn)(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input);
  111. struct h2_decoder_state {
  112. state_fn *fn;
  113. uint32_t bytes_required;
  114. const char *name;
  115. };
  116. #define DEFINE_STATE(_name, _bytes_required) \
  117. static state_fn s_state_fn_##_name; \
  118. enum { s_state_##_name##_requires_##_bytes_required##_bytes = _bytes_required }; \
  119. static const struct h2_decoder_state s_state_##_name = { \
  120. .fn = s_state_fn_##_name, \
  121. .bytes_required = s_state_##_name##_requires_##_bytes_required##_bytes, \
  122. .name = #_name, \
  123. }
  124. /* Common states */
  125. DEFINE_STATE(prefix, 9);
  126. DEFINE_STATE(padding_len, 1);
  127. DEFINE_STATE(padding, 0);
  128. DEFINE_STATE(priority_block, 5);
  129. DEFINE_STATE(header_block_loop, 0);
  130. DEFINE_STATE(header_block_entry, 1); /* requires 1 byte, but may consume more */
  131. /* Frame-specific states */
  132. DEFINE_STATE(frame_data, 0);
  133. DEFINE_STATE(frame_headers, 0);
  134. DEFINE_STATE(frame_priority, 0);
  135. DEFINE_STATE(frame_rst_stream, 4);
  136. DEFINE_STATE(frame_settings_begin, 0);
  137. DEFINE_STATE(frame_settings_loop, 0);
  138. DEFINE_STATE(frame_settings_i, 6);
  139. DEFINE_STATE(frame_push_promise, 4);
  140. DEFINE_STATE(frame_ping, 8);
  141. DEFINE_STATE(frame_goaway, 8);
  142. DEFINE_STATE(frame_goaway_debug_data, 0);
  143. DEFINE_STATE(frame_window_update, 4);
  144. DEFINE_STATE(frame_continuation, 0);
  145. DEFINE_STATE(frame_unknown, 0);
  146. /* States that have nothing to do with frames */
  147. DEFINE_STATE(connection_preface_string, 1); /* requires 1 byte but may consume more */
  148. /* Helper for states that need to transition to frame-type states */
  149. static const struct h2_decoder_state *s_state_frames[AWS_H2_FRAME_TYPE_COUNT] = {
  150. [AWS_H2_FRAME_T_DATA] = &s_state_frame_data,
  151. [AWS_H2_FRAME_T_HEADERS] = &s_state_frame_headers,
  152. [AWS_H2_FRAME_T_PRIORITY] = &s_state_frame_priority,
  153. [AWS_H2_FRAME_T_RST_STREAM] = &s_state_frame_rst_stream,
  154. [AWS_H2_FRAME_T_SETTINGS] = &s_state_frame_settings_begin,
  155. [AWS_H2_FRAME_T_PUSH_PROMISE] = &s_state_frame_push_promise,
  156. [AWS_H2_FRAME_T_PING] = &s_state_frame_ping,
  157. [AWS_H2_FRAME_T_GOAWAY] = &s_state_frame_goaway,
  158. [AWS_H2_FRAME_T_WINDOW_UPDATE] = &s_state_frame_window_update,
  159. [AWS_H2_FRAME_T_CONTINUATION] = &s_state_frame_continuation,
  160. [AWS_H2_FRAME_T_UNKNOWN] = &s_state_frame_unknown,
  161. };
  162. /***********************************************************************************************************************
  163. * Struct
  164. **********************************************************************************************************************/
  165. struct aws_h2_decoder {
  166. /* Implementation data. */
  167. struct aws_allocator *alloc;
  168. const void *logging_id;
  169. struct aws_hpack_decoder hpack;
  170. bool is_server;
  171. struct aws_byte_buf scratch;
  172. const struct h2_decoder_state *state;
  173. bool state_changed;
  174. /* HTTP/2 connection preface must be first thing received (RFC-7540 3.5):
  175. * Server must receive (client must send): magic string, then SETTINGS frame.
  176. * Client must receive (server must send): SETTINGS frame. */
  177. bool connection_preface_complete;
  178. /* Cursor over the canonical client connection preface string */
  179. struct aws_byte_cursor connection_preface_cursor;
  180. /* Frame-in-progress */
  181. struct aws_frame_in_progress {
  182. enum aws_h2_frame_type type;
  183. uint32_t stream_id;
  184. uint32_t payload_len;
  185. uint8_t padding_len;
  186. struct {
  187. bool ack;
  188. bool end_stream;
  189. bool end_headers;
  190. bool priority;
  191. } flags;
  192. } frame_in_progress;
  193. /* GOAWAY buffer */
  194. struct aws_goaway_in_progress {
  195. uint32_t last_stream;
  196. uint32_t error_code;
  197. /* Buffer of the received debug data in the latest goaway frame */
  198. struct aws_byte_buf debug_data;
  199. } goaway_in_progress;
  200. /* A header-block starts with a HEADERS or PUSH_PROMISE frame, followed by 0 or more CONTINUATION frames.
  201. * It's an error for any other frame-type or stream ID to arrive while a header-block is in progress.
  202. * The header-block ends when a frame has the END_HEADERS flag set. (RFC-7540 4.3) */
  203. struct aws_header_block_in_progress {
  204. /* If 0, then no header-block in progress */
  205. uint32_t stream_id;
  206. /* Whether these are informational (1xx), normal, or trailing headers */
  207. enum aws_http_header_block block_type;
  208. /* Buffer up pseudo-headers and deliver them once they're all validated */
  209. struct aws_string *pseudoheader_values[PSEUDOHEADER_COUNT];
  210. enum aws_http_header_compression pseudoheader_compression[PSEUDOHEADER_COUNT];
  211. /* All pseudo-header fields MUST appear in the header block before regular header fields. */
  212. bool pseudoheaders_done;
  213. /* T: PUSH_PROMISE header-block
  214. * F: HEADERS header-block */
  215. bool is_push_promise;
  216. /* If frame that starts header-block has END_STREAM flag,
  217. * then frame that ends header-block also ends the stream. */
  218. bool ends_stream;
  219. /* True if something occurs that makes the header-block malformed (ex: invalid header name).
  220. * A malformed header-block is not a connection error, it's a Stream Error (RFC-7540 5.4.2).
  221. * We continue decoding and report that it's malformed in on_headers_end(). */
  222. bool malformed;
  223. bool body_headers_forbidden;
  224. /* Buffer up cookie header fields to concatenate separate ones */
  225. struct aws_byte_buf cookies;
  226. /* If separate cookie fields have different compression types, the concatenated cookie uses the strictest type.
  227. */
  228. enum aws_http_header_compression cookie_header_compression_type;
  229. } header_block_in_progress;
  230. /* Settings for decoder, which is based on the settings sent to the peer and ACKed by peer */
  231. struct {
  232. /* enable/disable server push */
  233. uint32_t enable_push;
  234. /* the size of the largest frame payload */
  235. uint32_t max_frame_size;
  236. } settings;
  237. struct aws_array_list settings_buffer_list;
  238. /* User callbacks and settings. */
  239. const struct aws_h2_decoder_vtable *vtable;
  240. void *userdata;
  241. /* If this is set to true, decode may no longer be called */
  242. bool has_errored;
  243. };
  244. /***********************************************************************************************************************/
  245. struct aws_h2_decoder *aws_h2_decoder_new(struct aws_h2_decoder_params *params) {
  246. AWS_PRECONDITION(params);
  247. AWS_PRECONDITION(params->alloc);
  248. AWS_PRECONDITION(params->vtable);
  249. struct aws_h2_decoder *decoder = NULL;
  250. void *scratch_buf = NULL;
  251. void *allocation = aws_mem_acquire_many(
  252. params->alloc, 2, &decoder, sizeof(struct aws_h2_decoder), &scratch_buf, s_scratch_space_size);
  253. if (!allocation) {
  254. goto error;
  255. }
  256. AWS_ZERO_STRUCT(*decoder);
  257. decoder->alloc = params->alloc;
  258. decoder->vtable = params->vtable;
  259. decoder->userdata = params->userdata;
  260. decoder->logging_id = params->logging_id;
  261. decoder->is_server = params->is_server;
  262. decoder->connection_preface_complete = params->skip_connection_preface;
  263. decoder->scratch = aws_byte_buf_from_empty_array(scratch_buf, s_scratch_space_size);
  264. aws_hpack_decoder_init(&decoder->hpack, params->alloc, decoder);
  265. if (decoder->is_server && !params->skip_connection_preface) {
  266. decoder->state = &s_state_connection_preface_string;
  267. decoder->connection_preface_cursor = aws_h2_connection_preface_client_string;
  268. } else {
  269. decoder->state = &s_state_prefix;
  270. }
  271. decoder->settings.enable_push = aws_h2_settings_initial[AWS_HTTP2_SETTINGS_ENABLE_PUSH];
  272. decoder->settings.max_frame_size = aws_h2_settings_initial[AWS_HTTP2_SETTINGS_MAX_FRAME_SIZE];
  273. if (aws_array_list_init_dynamic(
  274. &decoder->settings_buffer_list, decoder->alloc, 0, sizeof(struct aws_http2_setting))) {
  275. goto error;
  276. }
  277. if (aws_byte_buf_init(
  278. &decoder->header_block_in_progress.cookies, decoder->alloc, s_decoder_cookie_buffer_initial_size)) {
  279. goto error;
  280. }
  281. return decoder;
  282. error:
  283. if (decoder) {
  284. aws_hpack_decoder_clean_up(&decoder->hpack);
  285. aws_array_list_clean_up(&decoder->settings_buffer_list);
  286. aws_byte_buf_clean_up(&decoder->header_block_in_progress.cookies);
  287. }
  288. aws_mem_release(params->alloc, allocation);
  289. return NULL;
  290. }
  291. static void s_reset_header_block_in_progress(struct aws_h2_decoder *decoder) {
  292. for (size_t i = 0; i < PSEUDOHEADER_COUNT; ++i) {
  293. aws_string_destroy(decoder->header_block_in_progress.pseudoheader_values[i]);
  294. }
  295. struct aws_byte_buf cookie_backup = decoder->header_block_in_progress.cookies;
  296. AWS_ZERO_STRUCT(decoder->header_block_in_progress);
  297. decoder->header_block_in_progress.cookies = cookie_backup;
  298. aws_byte_buf_reset(&decoder->header_block_in_progress.cookies, false);
  299. }
  300. void aws_h2_decoder_destroy(struct aws_h2_decoder *decoder) {
  301. if (!decoder) {
  302. return;
  303. }
  304. aws_array_list_clean_up(&decoder->settings_buffer_list);
  305. aws_hpack_decoder_clean_up(&decoder->hpack);
  306. s_reset_header_block_in_progress(decoder);
  307. aws_byte_buf_clean_up(&decoder->header_block_in_progress.cookies);
  308. aws_byte_buf_clean_up(&decoder->goaway_in_progress.debug_data);
  309. aws_mem_release(decoder->alloc, decoder);
  310. }
  311. struct aws_h2err aws_h2_decode(struct aws_h2_decoder *decoder, struct aws_byte_cursor *data) {
  312. AWS_PRECONDITION(decoder);
  313. AWS_PRECONDITION(data);
  314. AWS_FATAL_ASSERT(!decoder->has_errored);
  315. struct aws_h2err err = AWS_H2ERR_SUCCESS;
  316. /* Run decoder state machine until we're no longer changing states.
  317. * We don't simply loop `while(data->len)` because some states consume no data,
  318. * and these states should run even when there is no data left. */
  319. do {
  320. decoder->state_changed = false;
  321. const uint32_t bytes_required = decoder->state->bytes_required;
  322. AWS_ASSERT(bytes_required <= decoder->scratch.capacity);
  323. const char *current_state_name = decoder->state->name;
  324. const size_t prev_data_len = data->len;
  325. (void)prev_data_len;
  326. if (!decoder->scratch.len && data->len >= bytes_required) {
  327. /* Easy case, there is no scratch and we have enough data, so just send it to the state */
  328. DECODER_LOGF(TRACE, decoder, "Running state '%s' with %zu bytes available", current_state_name, data->len);
  329. err = decoder->state->fn(decoder, data);
  330. if (aws_h2err_failed(err)) {
  331. goto handle_error;
  332. }
  333. AWS_ASSERT(prev_data_len - data->len >= bytes_required && "Decoder state requested more data than it used");
  334. } else {
  335. /* Otherwise, state requires a minimum amount of data and we have to use the scratch */
  336. size_t bytes_to_read = bytes_required - decoder->scratch.len;
  337. bool will_finish_state = true;
  338. if (bytes_to_read > data->len) {
  339. /* Not enough in this cursor, need to read as much as possible and then come back */
  340. bytes_to_read = data->len;
  341. will_finish_state = false;
  342. }
  343. if (AWS_LIKELY(bytes_to_read)) {
  344. /* Read the appropriate number of bytes into scratch */
  345. struct aws_byte_cursor to_read = aws_byte_cursor_advance(data, bytes_to_read);
  346. bool succ = aws_byte_buf_write_from_whole_cursor(&decoder->scratch, to_read);
  347. AWS_ASSERT(succ);
  348. (void)succ;
  349. }
  350. /* If we have the correct number of bytes, call the state */
  351. if (will_finish_state) {
  352. DECODER_LOGF(TRACE, decoder, "Running state '%s' (using scratch)", current_state_name);
  353. struct aws_byte_cursor state_data = aws_byte_cursor_from_buf(&decoder->scratch);
  354. err = decoder->state->fn(decoder, &state_data);
  355. if (aws_h2err_failed(err)) {
  356. goto handle_error;
  357. }
  358. AWS_ASSERT(state_data.len == 0 && "Decoder state requested more data than it used");
  359. } else {
  360. DECODER_LOGF(
  361. TRACE,
  362. decoder,
  363. "State '%s' requires %" PRIu32 " bytes, but only %zu available, trying again later",
  364. current_state_name,
  365. bytes_required,
  366. decoder->scratch.len);
  367. }
  368. }
  369. } while (decoder->state_changed);
  370. return AWS_H2ERR_SUCCESS;
  371. handle_error:
  372. decoder->has_errored = true;
  373. return err;
  374. }
  375. /***********************************************************************************************************************
  376. * State functions
  377. **********************************************************************************************************************/
  378. static struct aws_h2err s_decoder_switch_state(struct aws_h2_decoder *decoder, const struct h2_decoder_state *state) {
  379. /* Ensure payload is big enough to enter next state.
  380. * If this fails, then the payload length we received is too small for this frame type.
  381. * (ex: a RST_STREAM frame with < 4 bytes) */
  382. if (decoder->frame_in_progress.payload_len < state->bytes_required) {
  383. DECODER_LOGF(
  384. ERROR, decoder, "%s payload is too small", aws_h2_frame_type_to_str(decoder->frame_in_progress.type));
  385. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_FRAME_SIZE_ERROR);
  386. }
  387. DECODER_LOGF(TRACE, decoder, "Moving from state '%s' to '%s'", decoder->state->name, state->name);
  388. decoder->scratch.len = 0;
  389. decoder->state = state;
  390. decoder->state_changed = true;
  391. return AWS_H2ERR_SUCCESS;
  392. }
  393. static struct aws_h2err s_decoder_switch_to_frame_state(struct aws_h2_decoder *decoder) {
  394. AWS_ASSERT(decoder->frame_in_progress.type < AWS_H2_FRAME_TYPE_COUNT);
  395. return s_decoder_switch_state(decoder, s_state_frames[decoder->frame_in_progress.type]);
  396. }
  397. static struct aws_h2err s_decoder_reset_state(struct aws_h2_decoder *decoder) {
  398. /* Ensure we've consumed all payload (and padding) when state machine finishes this frame.
  399. * If this fails, the payload length we received is too large for this frame type.
  400. * (ex: a RST_STREAM frame with > 4 bytes) */
  401. if (decoder->frame_in_progress.payload_len > 0 || decoder->frame_in_progress.padding_len > 0) {
  402. DECODER_LOGF(
  403. ERROR, decoder, "%s frame payload is too large", aws_h2_frame_type_to_str(decoder->frame_in_progress.type));
  404. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_FRAME_SIZE_ERROR);
  405. }
  406. DECODER_LOGF(TRACE, decoder, "%s frame complete", aws_h2_frame_type_to_str(decoder->frame_in_progress.type));
  407. decoder->scratch.len = 0;
  408. decoder->state = &s_state_prefix;
  409. decoder->state_changed = true;
  410. AWS_ZERO_STRUCT(decoder->frame_in_progress);
  411. return AWS_H2ERR_SUCCESS;
  412. }
  413. /* Returns as much of the current frame's payload as possible, and updates payload_len */
  414. static struct aws_byte_cursor s_decoder_get_payload(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  415. struct aws_byte_cursor result;
  416. const uint32_t remaining_length = decoder->frame_in_progress.payload_len;
  417. if (input->len < remaining_length) {
  418. AWS_ASSERT(input->len <= UINT32_MAX);
  419. result = aws_byte_cursor_advance(input, input->len);
  420. } else {
  421. result = aws_byte_cursor_advance(input, remaining_length);
  422. }
  423. decoder->frame_in_progress.payload_len -= (uint32_t)result.len;
  424. return result;
  425. }
  426. /* clang-format off */
  427. /* Mask of flags supported by each frame type.
  428. * Frames not listed have mask of 0, which means all flags will be ignored. */
  429. static const uint8_t s_acceptable_flags_for_frame[AWS_H2_FRAME_TYPE_COUNT] = {
  430. [AWS_H2_FRAME_T_DATA] = AWS_H2_FRAME_F_END_STREAM | AWS_H2_FRAME_F_PADDED,
  431. [AWS_H2_FRAME_T_HEADERS] = AWS_H2_FRAME_F_END_STREAM | AWS_H2_FRAME_F_END_HEADERS |
  432. AWS_H2_FRAME_F_PADDED | AWS_H2_FRAME_F_PRIORITY,
  433. [AWS_H2_FRAME_T_PRIORITY] = 0,
  434. [AWS_H2_FRAME_T_RST_STREAM] = 0,
  435. [AWS_H2_FRAME_T_SETTINGS] = AWS_H2_FRAME_F_ACK,
  436. [AWS_H2_FRAME_T_PUSH_PROMISE] = AWS_H2_FRAME_F_END_HEADERS | AWS_H2_FRAME_F_PADDED,
  437. [AWS_H2_FRAME_T_PING] = AWS_H2_FRAME_F_ACK,
  438. [AWS_H2_FRAME_T_GOAWAY] = 0,
  439. [AWS_H2_FRAME_T_WINDOW_UPDATE] = 0,
  440. [AWS_H2_FRAME_T_CONTINUATION] = AWS_H2_FRAME_F_END_HEADERS,
  441. [AWS_H2_FRAME_T_UNKNOWN] = 0,
  442. };
  443. enum stream_id_rules {
  444. STREAM_ID_REQUIRED,
  445. STREAM_ID_FORBIDDEN,
  446. STREAM_ID_EITHER_WAY,
  447. };
  448. /* Frame-types generally either require a stream-id, or require that it be zero. */
  449. static const enum stream_id_rules s_stream_id_rules_for_frame[AWS_H2_FRAME_TYPE_COUNT] = {
  450. [AWS_H2_FRAME_T_DATA] = STREAM_ID_REQUIRED,
  451. [AWS_H2_FRAME_T_HEADERS] = STREAM_ID_REQUIRED,
  452. [AWS_H2_FRAME_T_PRIORITY] = STREAM_ID_REQUIRED,
  453. [AWS_H2_FRAME_T_RST_STREAM] = STREAM_ID_REQUIRED,
  454. [AWS_H2_FRAME_T_SETTINGS] = STREAM_ID_FORBIDDEN,
  455. [AWS_H2_FRAME_T_PUSH_PROMISE] = STREAM_ID_REQUIRED,
  456. [AWS_H2_FRAME_T_PING] = STREAM_ID_FORBIDDEN,
  457. [AWS_H2_FRAME_T_GOAWAY] = STREAM_ID_FORBIDDEN,
  458. [AWS_H2_FRAME_T_WINDOW_UPDATE] = STREAM_ID_EITHER_WAY, /* WINDOW_UPDATE is special and can do either */
  459. [AWS_H2_FRAME_T_CONTINUATION] = STREAM_ID_REQUIRED,
  460. [AWS_H2_FRAME_T_UNKNOWN] = STREAM_ID_EITHER_WAY, /* Everything in an UNKNOWN frame type is ignored */
  461. };
  462. /* clang-format on */
  463. /* All frames begin with a fixed 9-octet header followed by a variable-length payload. (RFC-7540 4.1)
  464. * This function processes everything preceding Frame Payload in the following diagram:
  465. * +-----------------------------------------------+
  466. * | Length (24) |
  467. * +---------------+---------------+---------------+
  468. * | Type (8) | Flags (8) |
  469. * +-+-------------+---------------+-------------------------------+
  470. * |R| Stream Identifier (31) |
  471. * +=+=============================================================+
  472. * | Frame Payload (0...) ...
  473. * +---------------------------------------------------------------+
  474. */
  475. static struct aws_h2err s_state_fn_prefix(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  476. AWS_ASSERT(input->len >= s_state_prefix_requires_9_bytes);
  477. struct aws_frame_in_progress *frame = &decoder->frame_in_progress;
  478. uint8_t raw_type = 0;
  479. uint8_t raw_flags = 0;
  480. /* Read the raw values from the first 9 bytes */
  481. bool all_read = true;
  482. all_read &= aws_byte_cursor_read_be24(input, &frame->payload_len);
  483. all_read &= aws_byte_cursor_read_u8(input, &raw_type);
  484. all_read &= aws_byte_cursor_read_u8(input, &raw_flags);
  485. all_read &= aws_byte_cursor_read_be32(input, &frame->stream_id);
  486. AWS_ASSERT(all_read);
  487. (void)all_read;
  488. /* Validate frame type */
  489. frame->type = raw_type < AWS_H2_FRAME_T_UNKNOWN ? raw_type : AWS_H2_FRAME_T_UNKNOWN;
  490. /* Validate the frame's flags
  491. * Flags that have no defined semantics for a particular frame type MUST be ignored (RFC-7540 4.1) */
  492. const uint8_t flags = raw_flags & s_acceptable_flags_for_frame[decoder->frame_in_progress.type];
  493. bool is_padded = flags & AWS_H2_FRAME_F_PADDED;
  494. decoder->frame_in_progress.flags.ack = flags & AWS_H2_FRAME_F_ACK;
  495. decoder->frame_in_progress.flags.end_stream = flags & AWS_H2_FRAME_F_END_STREAM;
  496. decoder->frame_in_progress.flags.end_headers = flags & AWS_H2_FRAME_F_END_HEADERS;
  497. decoder->frame_in_progress.flags.priority =
  498. flags & AWS_H2_FRAME_F_PRIORITY || decoder->frame_in_progress.type == AWS_H2_FRAME_T_PRIORITY;
  499. /* Connection preface requires that SETTINGS be sent first (RFC-7540 3.5).
  500. * This should be the first error we check for, so that a connection sending
  501. * total garbage data is likely to trigger this PROTOCOL_ERROR */
  502. if (!decoder->connection_preface_complete) {
  503. if (frame->type == AWS_H2_FRAME_T_SETTINGS && !frame->flags.ack) {
  504. DECODER_LOG(TRACE, decoder, "Connection preface satisfied.");
  505. decoder->connection_preface_complete = true;
  506. } else {
  507. DECODER_LOG(ERROR, decoder, "First frame must be SETTINGS");
  508. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
  509. }
  510. }
  511. /* Validate the frame's stream ID. */
  512. /* Reserved bit (1st bit) MUST be ignored when receiving (RFC-7540 4.1) */
  513. frame->stream_id &= s_31_bit_mask;
  514. /* Some frame types require a stream ID, some frame types require that stream ID be zero. */
  515. const enum stream_id_rules stream_id_rules = s_stream_id_rules_for_frame[frame->type];
  516. if (frame->stream_id) {
  517. if (stream_id_rules == STREAM_ID_FORBIDDEN) {
  518. DECODER_LOGF(ERROR, decoder, "Stream ID for %s frame must be 0.", aws_h2_frame_type_to_str(frame->type));
  519. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
  520. }
  521. } else {
  522. if (stream_id_rules == STREAM_ID_REQUIRED) {
  523. DECODER_LOGF(ERROR, decoder, "Stream ID for %s frame cannot be 0.", aws_h2_frame_type_to_str(frame->type));
  524. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
  525. }
  526. }
  527. /* A header-block starts with a HEADERS or PUSH_PROMISE frame, followed by 0 or more CONTINUATION frames.
  528. * It's an error for any other frame-type or stream ID to arrive while a header-block is in progress.
  529. * (RFC-7540 4.3) */
  530. if (frame->type == AWS_H2_FRAME_T_CONTINUATION) {
  531. if (decoder->header_block_in_progress.stream_id != frame->stream_id) {
  532. DECODER_LOG(ERROR, decoder, "Unexpected CONTINUATION frame.");
  533. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
  534. }
  535. } else {
  536. if (decoder->header_block_in_progress.stream_id) {
  537. DECODER_LOG(ERROR, decoder, "Expected CONTINUATION frame.");
  538. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
  539. }
  540. }
  541. /* Validate payload length. */
  542. uint32_t max_frame_size = decoder->settings.max_frame_size;
  543. if (frame->payload_len > max_frame_size) {
  544. DECODER_LOGF(
  545. ERROR,
  546. decoder,
  547. "Decoder's max frame size is %" PRIu32 ", but frame of size %" PRIu32 " was received.",
  548. max_frame_size,
  549. frame->payload_len);
  550. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_FRAME_SIZE_ERROR);
  551. }
  552. DECODER_LOGF(
  553. TRACE,
  554. decoder,
  555. "Done decoding frame prefix (type=%s stream-id=%" PRIu32 " payload-len=%" PRIu32 "), moving on to payload",
  556. aws_h2_frame_type_to_str(frame->type),
  557. frame->stream_id,
  558. frame->payload_len);
  559. if (is_padded) {
  560. /* Read padding length if necessary */
  561. return s_decoder_switch_state(decoder, &s_state_padding_len);
  562. }
  563. if (decoder->frame_in_progress.type == AWS_H2_FRAME_T_DATA) {
  564. /* We invoke the on_data_begin here to report the whole payload size */
  565. DECODER_CALL_VTABLE_STREAM_ARGS(
  566. decoder, on_data_begin, frame->payload_len, 0 /*padding_len*/, frame->flags.end_stream);
  567. }
  568. if (decoder->frame_in_progress.flags.priority) {
  569. /* Read the stream dependency and weight if PRIORITY is set */
  570. return s_decoder_switch_state(decoder, &s_state_priority_block);
  571. }
  572. /* Set the state to the appropriate frame's state */
  573. return s_decoder_switch_to_frame_state(decoder);
  574. }
  575. /* Frames that support padding, and have the PADDED flag set, begin with a 1-byte Pad Length.
  576. * (Actual padding comes later at the very end of the frame)
  577. * +---------------+
  578. * |Pad Length? (8)|
  579. * +---------------+
  580. */
  581. static struct aws_h2err s_state_fn_padding_len(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  582. AWS_ASSERT(input->len >= s_state_padding_len_requires_1_bytes);
  583. struct aws_frame_in_progress *frame = &decoder->frame_in_progress;
  584. /* Read the padding length */
  585. bool succ = aws_byte_cursor_read_u8(input, &frame->padding_len);
  586. AWS_ASSERT(succ);
  587. (void)succ;
  588. /* Adjust payload size so it doesn't include padding (or the 1-byte padding length) */
  589. uint32_t reduce_payload = s_state_padding_len_requires_1_bytes + frame->padding_len;
  590. if (reduce_payload > decoder->frame_in_progress.payload_len) {
  591. DECODER_LOG(ERROR, decoder, "Padding length exceeds payload length");
  592. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
  593. }
  594. if (frame->type == AWS_H2_FRAME_T_DATA) {
  595. /* We invoke the on_data_begin here to report the whole payload size and the padding size */
  596. DECODER_CALL_VTABLE_STREAM_ARGS(
  597. decoder, on_data_begin, frame->payload_len, frame->padding_len + 1, frame->flags.end_stream);
  598. }
  599. frame->payload_len -= reduce_payload;
  600. DECODER_LOGF(TRACE, decoder, "Padding length of frame: %" PRIu32, frame->padding_len);
  601. if (frame->flags.priority) {
  602. /* Read the stream dependency and weight if PRIORITY is set */
  603. return s_decoder_switch_state(decoder, &s_state_priority_block);
  604. }
  605. /* Set the state to the appropriate frame's state */
  606. return s_decoder_switch_to_frame_state(decoder);
  607. }
  608. static struct aws_h2err s_state_fn_padding(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  609. const uint8_t remaining_len = decoder->frame_in_progress.padding_len;
  610. const uint8_t consuming_len = input->len < remaining_len ? (uint8_t)input->len : remaining_len;
  611. aws_byte_cursor_advance(input, consuming_len);
  612. decoder->frame_in_progress.padding_len -= consuming_len;
  613. if (remaining_len == consuming_len) {
  614. /* Done with the frame! */
  615. return s_decoder_reset_state(decoder);
  616. }
  617. return AWS_H2ERR_SUCCESS;
  618. }
  619. /* Shared code for:
  620. * PRIORITY frame (RFC-7540 6.3)
  621. * Start of HEADERS frame IF the priority flag is set (RFC-7540 6.2)
  622. * +-+-------------+-----------------------------------------------+
  623. * |E| Stream Dependency (31) |
  624. * +-+-------------+-----------------------------------------------+
  625. * | Weight (8) |
  626. * +-+-------------+-----------------------------------------------+
  627. */
  628. static struct aws_h2err s_state_fn_priority_block(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  629. AWS_ASSERT(input->len >= s_state_priority_block_requires_5_bytes);
  630. /* #NOTE: throw priority data on the GROUND. They make us hecka vulnerable to DDoS and stuff.
  631. * https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-9513
  632. */
  633. aws_byte_cursor_advance(input, s_state_priority_block_requires_5_bytes);
  634. decoder->frame_in_progress.payload_len -= s_state_priority_block_requires_5_bytes;
  635. return s_decoder_switch_to_frame_state(decoder);
  636. }
  637. static struct aws_h2err s_state_fn_frame_data(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  638. const struct aws_byte_cursor body_data = s_decoder_get_payload(decoder, input);
  639. if (body_data.len) {
  640. DECODER_CALL_VTABLE_STREAM_ARGS(decoder, on_data_i, body_data);
  641. }
  642. if (decoder->frame_in_progress.payload_len == 0) {
  643. DECODER_CALL_VTABLE_STREAM(decoder, on_data_end);
  644. /* If frame had END_STREAM flag, alert user now */
  645. if (decoder->frame_in_progress.flags.end_stream) {
  646. DECODER_CALL_VTABLE_STREAM(decoder, on_end_stream);
  647. }
  648. /* Process padding if necessary, otherwise we're done! */
  649. return s_decoder_switch_state(decoder, &s_state_padding);
  650. }
  651. return AWS_H2ERR_SUCCESS;
  652. }
  653. static struct aws_h2err s_state_fn_frame_headers(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  654. (void)input;
  655. /* Start header-block and alert the user */
  656. decoder->header_block_in_progress.stream_id = decoder->frame_in_progress.stream_id;
  657. decoder->header_block_in_progress.is_push_promise = false;
  658. decoder->header_block_in_progress.ends_stream = decoder->frame_in_progress.flags.end_stream;
  659. DECODER_CALL_VTABLE_STREAM(decoder, on_headers_begin);
  660. /* Read the header-block fragment */
  661. return s_decoder_switch_state(decoder, &s_state_header_block_loop);
  662. }
  663. static struct aws_h2err s_state_fn_frame_priority(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  664. (void)input;
  665. /* We already processed this data in the shared priority_block state, so we're done! */
  666. return s_decoder_reset_state(decoder);
  667. }
  668. /* RST_STREAM is just a 4-byte error code.
  669. * +---------------------------------------------------------------+
  670. * | Error Code (32) |
  671. * +---------------------------------------------------------------+
  672. */
  673. static struct aws_h2err s_state_fn_frame_rst_stream(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  674. AWS_ASSERT(input->len >= s_state_frame_rst_stream_requires_4_bytes);
  675. uint32_t error_code = 0;
  676. bool succ = aws_byte_cursor_read_be32(input, &error_code);
  677. AWS_ASSERT(succ);
  678. (void)succ;
  679. decoder->frame_in_progress.payload_len -= s_state_frame_rst_stream_requires_4_bytes;
  680. DECODER_CALL_VTABLE_STREAM_ARGS(decoder, on_rst_stream, error_code);
  681. return s_decoder_reset_state(decoder);
  682. }
  683. /* A SETTINGS frame may contain any number of 6-byte entries.
  684. * This state consumes no data, but sends us into the appropriate next state */
  685. static struct aws_h2err s_state_fn_frame_settings_begin(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  686. (void)input;
  687. /* If ack is set, report and we're done */
  688. if (decoder->frame_in_progress.flags.ack) {
  689. /* Receipt of a SETTINGS frame with the ACK flag set and a length field value other
  690. * than 0 MUST be treated as a connection error of type FRAME_SIZE_ERROR */
  691. if (decoder->frame_in_progress.payload_len) {
  692. DECODER_LOGF(
  693. ERROR,
  694. decoder,
  695. "SETTINGS ACK frame received, but it has non-0 payload length %" PRIu32,
  696. decoder->frame_in_progress.payload_len);
  697. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_FRAME_SIZE_ERROR);
  698. }
  699. DECODER_CALL_VTABLE(decoder, on_settings_ack);
  700. return s_decoder_reset_state(decoder);
  701. }
  702. if (decoder->frame_in_progress.payload_len % s_state_frame_settings_i_requires_6_bytes != 0) {
  703. /* A SETTINGS frame with a length other than a multiple of 6 octets MUST be
  704. * treated as a connection error (Section 5.4.1) of type FRAME_SIZE_ERROR */
  705. DECODER_LOGF(
  706. ERROR,
  707. decoder,
  708. "Settings frame payload length is %" PRIu32 ", but it must be divisible by %" PRIu32,
  709. decoder->frame_in_progress.payload_len,
  710. s_state_frame_settings_i_requires_6_bytes);
  711. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_FRAME_SIZE_ERROR);
  712. }
  713. /* Enter looping states until all entries are consumed. */
  714. return s_decoder_switch_state(decoder, &s_state_frame_settings_loop);
  715. }
  716. /* Check if we're done consuming settings */
  717. static struct aws_h2err s_state_fn_frame_settings_loop(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  718. (void)input;
  719. if (decoder->frame_in_progress.payload_len == 0) {
  720. /* Huzzah, done with the frame, fire the callback */
  721. struct aws_array_list *buffer = &decoder->settings_buffer_list;
  722. DECODER_CALL_VTABLE_ARGS(
  723. decoder, on_settings, buffer->data, aws_array_list_length(&decoder->settings_buffer_list));
  724. /* clean up the buffer */
  725. aws_array_list_clear(&decoder->settings_buffer_list);
  726. return s_decoder_reset_state(decoder);
  727. }
  728. return s_decoder_switch_state(decoder, &s_state_frame_settings_i);
  729. }
  730. /* Each run through this state consumes one 6-byte setting.
  731. * There may be multiple settings in a SETTINGS frame.
  732. * +-------------------------------+
  733. * | Identifier (16) |
  734. * +-------------------------------+-------------------------------+
  735. * | Value (32) |
  736. * +---------------------------------------------------------------+
  737. */
  738. static struct aws_h2err s_state_fn_frame_settings_i(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  739. AWS_ASSERT(input->len >= s_state_frame_settings_i_requires_6_bytes);
  740. uint16_t id = 0;
  741. uint32_t value = 0;
  742. bool succ = aws_byte_cursor_read_be16(input, &id);
  743. AWS_ASSERT(succ);
  744. (void)succ;
  745. succ = aws_byte_cursor_read_be32(input, &value);
  746. AWS_ASSERT(succ);
  747. (void)succ;
  748. /* An endpoint that receives a SETTINGS frame with any unknown or unsupported identifier MUST ignore that setting.
  749. * RFC-7540 6.5.2 */
  750. if (id >= AWS_HTTP2_SETTINGS_BEGIN_RANGE && id < AWS_HTTP2_SETTINGS_END_RANGE) {
  751. /* check the value meets the settings bounds */
  752. if (value < aws_h2_settings_bounds[id][0] || value > aws_h2_settings_bounds[id][1]) {
  753. DECODER_LOGF(
  754. ERROR, decoder, "A value of SETTING frame is invalid, id: %" PRIu16 ", value: %" PRIu32, id, value);
  755. if (id == AWS_HTTP2_SETTINGS_INITIAL_WINDOW_SIZE) {
  756. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_FLOW_CONTROL_ERROR);
  757. } else {
  758. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
  759. }
  760. }
  761. struct aws_http2_setting setting;
  762. setting.id = id;
  763. setting.value = value;
  764. /* array_list will keep a copy of setting, it is fine to be a local variable */
  765. if (aws_array_list_push_back(&decoder->settings_buffer_list, &setting)) {
  766. DECODER_LOGF(ERROR, decoder, "Writing setting to buffer failed, %s", aws_error_name(aws_last_error()));
  767. return aws_h2err_from_last_error();
  768. }
  769. }
  770. /* Update payload len */
  771. decoder->frame_in_progress.payload_len -= s_state_frame_settings_i_requires_6_bytes;
  772. return s_decoder_switch_state(decoder, &s_state_frame_settings_loop);
  773. }
  774. /* Read 4-byte Promised Stream ID
  775. * The rest of the frame is just like HEADERS, so move on to shared states...
  776. * +-+-------------------------------------------------------------+
  777. * |R| Promised Stream ID (31) |
  778. * +-+-----------------------------+-------------------------------+
  779. */
  780. static struct aws_h2err s_state_fn_frame_push_promise(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  781. if (decoder->settings.enable_push == 0) {
  782. /* treat the receipt of a PUSH_PROMISE frame as a connection error of type PROTOCOL_ERROR.(RFC-7540 6.5.2) */
  783. DECODER_LOG(ERROR, decoder, "PUSH_PROMISE is invalid, the seting for enable push is 0");
  784. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
  785. }
  786. AWS_ASSERT(input->len >= s_state_frame_push_promise_requires_4_bytes);
  787. uint32_t promised_stream_id = 0;
  788. bool succ = aws_byte_cursor_read_be32(input, &promised_stream_id);
  789. AWS_ASSERT(succ);
  790. (void)succ;
  791. decoder->frame_in_progress.payload_len -= s_state_frame_push_promise_requires_4_bytes;
  792. /* Reserved bit (top bit) must be ignored when receiving (RFC-7540 4.1) */
  793. promised_stream_id &= s_31_bit_mask;
  794. /* Promised stream ID must not be 0 (RFC-7540 6.6).
  795. * Promised stream ID (server-initiated) must be even-numbered (RFC-7540 5.1.1). */
  796. if ((promised_stream_id == 0) || (promised_stream_id % 2) != 0) {
  797. DECODER_LOGF(ERROR, decoder, "PUSH_PROMISE is promising invalid stream ID %" PRIu32, promised_stream_id);
  798. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
  799. }
  800. /* Server cannot receive PUSH_PROMISE frames */
  801. if (decoder->is_server) {
  802. DECODER_LOG(ERROR, decoder, "Server cannot receive PUSH_PROMISE frames");
  803. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
  804. }
  805. /* Start header-block and alert the user. */
  806. decoder->header_block_in_progress.stream_id = decoder->frame_in_progress.stream_id;
  807. decoder->header_block_in_progress.is_push_promise = true;
  808. decoder->header_block_in_progress.ends_stream = false;
  809. DECODER_CALL_VTABLE_STREAM_ARGS(decoder, on_push_promise_begin, promised_stream_id);
  810. /* Read the header-block fragment */
  811. return s_decoder_switch_state(decoder, &s_state_header_block_loop);
  812. }
  813. /* PING frame is just 8-bytes of opaque data.
  814. * +---------------------------------------------------------------+
  815. * | |
  816. * | Opaque Data (64) |
  817. * | |
  818. * +---------------------------------------------------------------+
  819. */
  820. static struct aws_h2err s_state_fn_frame_ping(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  821. AWS_ASSERT(input->len >= s_state_frame_ping_requires_8_bytes);
  822. uint8_t opaque_data[AWS_HTTP2_PING_DATA_SIZE] = {0};
  823. bool succ = aws_byte_cursor_read(input, &opaque_data, AWS_HTTP2_PING_DATA_SIZE);
  824. AWS_ASSERT(succ);
  825. (void)succ;
  826. decoder->frame_in_progress.payload_len -= s_state_frame_ping_requires_8_bytes;
  827. if (decoder->frame_in_progress.flags.ack) {
  828. DECODER_CALL_VTABLE_ARGS(decoder, on_ping_ack, opaque_data);
  829. } else {
  830. DECODER_CALL_VTABLE_ARGS(decoder, on_ping, opaque_data);
  831. }
  832. return s_decoder_reset_state(decoder);
  833. }
  834. /* Read first 8 bytes of GOAWAY.
  835. * This may be followed by N bytes of debug data.
  836. * +-+-------------------------------------------------------------+
  837. * |R| Last-Stream-ID (31) |
  838. * +-+-------------------------------------------------------------+
  839. * | Error Code (32) |
  840. * +---------------------------------------------------------------+
  841. */
  842. static struct aws_h2err s_state_fn_frame_goaway(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  843. AWS_ASSERT(input->len >= s_state_frame_goaway_requires_8_bytes);
  844. uint32_t last_stream = 0;
  845. uint32_t error_code = AWS_HTTP2_ERR_NO_ERROR;
  846. bool succ = aws_byte_cursor_read_be32(input, &last_stream);
  847. AWS_ASSERT(succ);
  848. (void)succ;
  849. last_stream &= s_31_bit_mask;
  850. succ = aws_byte_cursor_read_be32(input, &error_code);
  851. AWS_ASSERT(succ);
  852. (void)succ;
  853. decoder->frame_in_progress.payload_len -= s_state_frame_goaway_requires_8_bytes;
  854. uint32_t debug_data_length = decoder->frame_in_progress.payload_len;
  855. /* Received new GOAWAY, clean up the previous one. Buffer it up and invoke the callback once the debug data decoded
  856. * fully. */
  857. decoder->goaway_in_progress.error_code = error_code;
  858. decoder->goaway_in_progress.last_stream = last_stream;
  859. int init_result = aws_byte_buf_init(&decoder->goaway_in_progress.debug_data, decoder->alloc, debug_data_length);
  860. AWS_ASSERT(init_result == 0);
  861. (void)init_result;
  862. return s_decoder_switch_state(decoder, &s_state_frame_goaway_debug_data);
  863. }
  864. /* Optional remainder of GOAWAY frame.
  865. * +---------------------------------------------------------------+
  866. * | Additional Debug Data (*) |
  867. * +---------------------------------------------------------------+
  868. */
  869. static struct aws_h2err s_state_fn_frame_goaway_debug_data(
  870. struct aws_h2_decoder *decoder,
  871. struct aws_byte_cursor *input) {
  872. struct aws_byte_cursor debug_data = s_decoder_get_payload(decoder, input);
  873. if (debug_data.len > 0) {
  874. /* As we initialized the buffer to the size of debug data, we can safely append here */
  875. aws_byte_buf_append(&decoder->goaway_in_progress.debug_data, &debug_data);
  876. }
  877. /* If this is the last data in the frame, reset decoder */
  878. if (decoder->frame_in_progress.payload_len == 0) {
  879. struct aws_byte_cursor debug_cursor = aws_byte_cursor_from_buf(&decoder->goaway_in_progress.debug_data);
  880. DECODER_CALL_VTABLE_ARGS(
  881. decoder,
  882. on_goaway,
  883. decoder->goaway_in_progress.last_stream,
  884. decoder->goaway_in_progress.error_code,
  885. debug_cursor);
  886. aws_byte_buf_clean_up(&decoder->goaway_in_progress.debug_data);
  887. return s_decoder_reset_state(decoder);
  888. }
  889. return AWS_H2ERR_SUCCESS;
  890. }
  891. /* WINDOW_UPDATE frame.
  892. * +-+-------------------------------------------------------------+
  893. * |R| Window Size Increment (31) |
  894. * +-+-------------------------------------------------------------+
  895. */
  896. static struct aws_h2err s_state_fn_frame_window_update(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  897. AWS_ASSERT(input->len >= s_state_frame_window_update_requires_4_bytes);
  898. uint32_t window_increment = 0;
  899. bool succ = aws_byte_cursor_read_be32(input, &window_increment);
  900. AWS_ASSERT(succ);
  901. (void)succ;
  902. decoder->frame_in_progress.payload_len -= s_state_frame_window_update_requires_4_bytes;
  903. window_increment &= s_31_bit_mask;
  904. DECODER_CALL_VTABLE_STREAM_ARGS(decoder, on_window_update, window_increment);
  905. return s_decoder_reset_state(decoder);
  906. }
  907. /* CONTINUATION is a lot like HEADERS, so it uses shared states. */
  908. static struct aws_h2err s_state_fn_frame_continuation(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  909. (void)input;
  910. /* Read the header-block fragment */
  911. return s_decoder_switch_state(decoder, &s_state_header_block_loop);
  912. }
  913. /* Implementations MUST ignore and discard any frame that has a type that is unknown. */
  914. static struct aws_h2err s_state_fn_frame_unknown(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  915. /* Read all data possible, and throw it on the floor */
  916. s_decoder_get_payload(decoder, input);
  917. /* If there's no more data expected, end the frame */
  918. if (decoder->frame_in_progress.payload_len == 0) {
  919. return s_decoder_reset_state(decoder);
  920. }
  921. return AWS_H2ERR_SUCCESS;
  922. }
  923. /* Perform analysis that can't be done until all pseudo-headers are received.
  924. * Then deliver buffered pseudoheaders via callback */
  925. static struct aws_h2err s_flush_pseudoheaders(struct aws_h2_decoder *decoder) {
  926. struct aws_header_block_in_progress *current_block = &decoder->header_block_in_progress;
  927. if (current_block->malformed) {
  928. goto already_malformed;
  929. }
  930. if (current_block->pseudoheaders_done) {
  931. return AWS_H2ERR_SUCCESS;
  932. }
  933. current_block->pseudoheaders_done = true;
  934. /* s_process_header_field() already checked that we're not mixing request & response pseudoheaders */
  935. bool has_request_pseudoheaders = false;
  936. for (int i = PSEUDOHEADER_METHOD; i <= PSEUDOHEADER_PATH; ++i) {
  937. if (current_block->pseudoheader_values[i] != NULL) {
  938. has_request_pseudoheaders = true;
  939. break;
  940. }
  941. }
  942. bool has_response_pseudoheaders = current_block->pseudoheader_values[PSEUDOHEADER_STATUS] != NULL;
  943. if (current_block->is_push_promise && !has_request_pseudoheaders) {
  944. DECODER_LOG(ERROR, decoder, "PUSH_PROMISE is missing :method");
  945. goto malformed;
  946. }
  947. if (has_request_pseudoheaders) {
  948. /* Request header-block. */
  949. current_block->block_type = AWS_HTTP_HEADER_BLOCK_MAIN;
  950. } else if (has_response_pseudoheaders) {
  951. /* Response header block. */
  952. /* Determine whether this is an Informational (1xx) response */
  953. struct aws_byte_cursor status_value =
  954. aws_byte_cursor_from_string(current_block->pseudoheader_values[PSEUDOHEADER_STATUS]);
  955. uint64_t status_code;
  956. if (status_value.len != 3 || aws_byte_cursor_utf8_parse_u64(status_value, &status_code)) {
  957. DECODER_LOG(ERROR, decoder, ":status header has invalid value");
  958. DECODER_LOGF(DEBUG, decoder, "Bad :status value is '" PRInSTR "'", AWS_BYTE_CURSOR_PRI(status_value));
  959. goto malformed;
  960. }
  961. if (status_code / 100 == 1) {
  962. current_block->block_type = AWS_HTTP_HEADER_BLOCK_INFORMATIONAL;
  963. if (current_block->ends_stream) {
  964. /* Informational headers do not constitute a full response (RFC-7540 8.1) */
  965. DECODER_LOG(ERROR, decoder, "Informational (1xx) response cannot END_STREAM");
  966. goto malformed;
  967. }
  968. current_block->body_headers_forbidden = true;
  969. } else {
  970. current_block->block_type = AWS_HTTP_HEADER_BLOCK_MAIN;
  971. }
  972. /**
  973. * RFC-9110 8.6.
  974. * A server MUST NOT send a Content-Length header field in any response with a status code of 1xx
  975. * (Informational) or 204 (No Content).
  976. */
  977. current_block->body_headers_forbidden |= status_code == AWS_HTTP_STATUS_CODE_204_NO_CONTENT;
  978. } else {
  979. /* Trailing header block. */
  980. if (!current_block->ends_stream) {
  981. DECODER_LOG(ERROR, decoder, "HEADERS appear to be trailer, but lack END_STREAM");
  982. goto malformed;
  983. }
  984. current_block->block_type = AWS_HTTP_HEADER_BLOCK_TRAILING;
  985. }
  986. /* #TODO RFC-7540 8.1.2.3 & 8.3 Validate request has correct pseudoheaders. Note different rules for CONNECT */
  987. /* #TODO validate pseudoheader values. each one has its own special rules */
  988. /* Finally, deliver header-fields via callback */
  989. for (size_t i = 0; i < PSEUDOHEADER_COUNT; ++i) {
  990. const struct aws_string *value_string = current_block->pseudoheader_values[i];
  991. if (value_string) {
  992. struct aws_http_header header_field = {
  993. .name = *s_pseudoheader_name_to_cursor[i],
  994. .value = aws_byte_cursor_from_string(value_string),
  995. .compression = current_block->pseudoheader_compression[i],
  996. };
  997. enum aws_http_header_name name_enum = s_pseudoheader_to_header_name[i];
  998. if (current_block->is_push_promise) {
  999. DECODER_CALL_VTABLE_STREAM_ARGS(decoder, on_push_promise_i, &header_field, name_enum);
  1000. } else {
  1001. DECODER_CALL_VTABLE_STREAM_ARGS(
  1002. decoder, on_headers_i, &header_field, name_enum, current_block->block_type);
  1003. }
  1004. }
  1005. }
  1006. return AWS_H2ERR_SUCCESS;
  1007. malformed:
  1008. /* A malformed header-block is not a connection error, it's a Stream Error (RFC-7540 5.4.2).
  1009. * We continue decoding and report that it's malformed in on_headers_end(). */
  1010. current_block->malformed = true;
  1011. return AWS_H2ERR_SUCCESS;
  1012. already_malformed:
  1013. return AWS_H2ERR_SUCCESS;
  1014. }
  1015. /* Process single header-field.
  1016. * If it's invalid, mark the header-block as malformed.
  1017. * If it's valid, and header-block is not malformed, deliver via callback. */
  1018. static struct aws_h2err s_process_header_field(
  1019. struct aws_h2_decoder *decoder,
  1020. const struct aws_http_header *header_field) {
  1021. struct aws_header_block_in_progress *current_block = &decoder->header_block_in_progress;
  1022. if (current_block->malformed) {
  1023. goto already_malformed;
  1024. }
  1025. const struct aws_byte_cursor name = header_field->name;
  1026. if (name.len == 0) {
  1027. DECODER_LOG(ERROR, decoder, "Header name is blank");
  1028. goto malformed;
  1029. }
  1030. enum aws_http_header_name name_enum = aws_http_lowercase_str_to_header_name(name);
  1031. bool is_pseudoheader = name.ptr[0] == ':';
  1032. if (is_pseudoheader) {
  1033. if (current_block->pseudoheaders_done) {
  1034. /* Note: being careful not to leak possibly sensitive data except at DEBUG level and lower */
  1035. DECODER_LOG(ERROR, decoder, "Pseudo-headers must appear before regular fields.");
  1036. DECODER_LOGF(DEBUG, decoder, "Misplaced pseudo-header is '" PRInSTR "'", AWS_BYTE_CURSOR_PRI(name));
  1037. goto malformed;
  1038. }
  1039. enum pseudoheader_name pseudoheader_enum = s_header_to_pseudoheader_name(name_enum);
  1040. if (pseudoheader_enum == PSEUDOHEADER_UNKNOWN) {
  1041. DECODER_LOG(ERROR, decoder, "Unrecognized pseudo-header");
  1042. DECODER_LOGF(DEBUG, decoder, "Unrecognized pseudo-header is '" PRInSTR "'", AWS_BYTE_CURSOR_PRI(name));
  1043. goto malformed;
  1044. }
  1045. /* Ensure request pseudo-headers vs response pseudoheaders were sent appropriately.
  1046. * This also ensures that request and response pseudoheaders aren't being mixed. */
  1047. bool expect_request_pseudoheader = decoder->is_server || current_block->is_push_promise;
  1048. bool is_request_pseudoheader = pseudoheader_enum != PSEUDOHEADER_STATUS;
  1049. if (expect_request_pseudoheader != is_request_pseudoheader) {
  1050. DECODER_LOGF(
  1051. ERROR, /* ok to log name of recognized pseudo-header at ERROR level */
  1052. decoder,
  1053. "'" PRInSTR "' pseudo-header cannot be in %s header-block to %s",
  1054. AWS_BYTE_CURSOR_PRI(name),
  1055. current_block->is_push_promise ? "PUSH_PROMISE" : "HEADERS",
  1056. decoder->is_server ? "server" : "client");
  1057. goto malformed;
  1058. }
  1059. /* Protect against duplicates. */
  1060. if (current_block->pseudoheader_values[pseudoheader_enum] != NULL) {
  1061. /* ok to log name of recognized pseudo-header at ERROR level */
  1062. DECODER_LOGF(
  1063. ERROR, decoder, "'" PRInSTR "' pseudo-header occurred multiple times", AWS_BYTE_CURSOR_PRI(name));
  1064. goto malformed;
  1065. }
  1066. /* Buffer up pseudo-headers, we'll deliver them later once they're all validated. */
  1067. current_block->pseudoheader_compression[pseudoheader_enum] = header_field->compression;
  1068. current_block->pseudoheader_values[pseudoheader_enum] =
  1069. aws_string_new_from_cursor(decoder->alloc, &header_field->value);
  1070. if (!current_block->pseudoheader_values[pseudoheader_enum]) {
  1071. return aws_h2err_from_last_error();
  1072. }
  1073. } else { /* Else regular header-field. */
  1074. /* Regular header-fields come after pseudo-headers, so make sure pseudo-headers are flushed */
  1075. if (!current_block->pseudoheaders_done) {
  1076. struct aws_h2err err = s_flush_pseudoheaders(decoder);
  1077. if (aws_h2err_failed(err)) {
  1078. return err;
  1079. }
  1080. /* might have realized that header-block is malformed during flush */
  1081. if (current_block->malformed) {
  1082. goto already_malformed;
  1083. }
  1084. }
  1085. /* Validate header name (not necessary if string already matched against a known enum) */
  1086. if (name_enum == AWS_HTTP_HEADER_UNKNOWN) {
  1087. if (!aws_strutil_is_lowercase_http_token(name)) {
  1088. DECODER_LOG(ERROR, decoder, "Header name contains invalid characters");
  1089. DECODER_LOGF(DEBUG, decoder, "Bad header name is '" PRInSTR "'", AWS_BYTE_CURSOR_PRI(name));
  1090. goto malformed;
  1091. }
  1092. }
  1093. /* #TODO Validate characters used in header_field->value */
  1094. switch (name_enum) {
  1095. case AWS_HTTP_HEADER_COOKIE:
  1096. /* for a header cookie, we will not fire callback until we concatenate them all, let's store it at the
  1097. * buffer */
  1098. if (header_field->compression > current_block->cookie_header_compression_type) {
  1099. current_block->cookie_header_compression_type = header_field->compression;
  1100. }
  1101. if (current_block->cookies.len) {
  1102. /* add a delimiter */
  1103. struct aws_byte_cursor delimiter = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("; ");
  1104. if (aws_byte_buf_append_dynamic(&current_block->cookies, &delimiter)) {
  1105. return aws_h2err_from_last_error();
  1106. }
  1107. }
  1108. if (aws_byte_buf_append_dynamic(&current_block->cookies, &header_field->value)) {
  1109. return aws_h2err_from_last_error();
  1110. }
  1111. /* Early return */
  1112. return AWS_H2ERR_SUCCESS;
  1113. case AWS_HTTP_HEADER_TRANSFER_ENCODING:
  1114. case AWS_HTTP_HEADER_UPGRADE:
  1115. case AWS_HTTP_HEADER_KEEP_ALIVE:
  1116. case AWS_HTTP_HEADER_PROXY_CONNECTION: {
  1117. /* connection-specific header field are treated as malformed (RFC9113 8.2.2) */
  1118. DECODER_LOGF(
  1119. ERROR,
  1120. decoder,
  1121. "Connection-specific header ('" PRInSTR "') found, not allowed in HTTP/2",
  1122. AWS_BYTE_CURSOR_PRI(name));
  1123. goto malformed;
  1124. } break;
  1125. case AWS_HTTP_HEADER_CONTENT_LENGTH:
  1126. if (current_block->body_headers_forbidden) {
  1127. /* The content-length are forbidden */
  1128. DECODER_LOG(ERROR, decoder, "Unexpected Content-Length header found");
  1129. goto malformed;
  1130. }
  1131. break;
  1132. default:
  1133. break;
  1134. }
  1135. /* Deliver header-field via callback */
  1136. if (current_block->is_push_promise) {
  1137. DECODER_CALL_VTABLE_STREAM_ARGS(decoder, on_push_promise_i, header_field, name_enum);
  1138. } else {
  1139. DECODER_CALL_VTABLE_STREAM_ARGS(decoder, on_headers_i, header_field, name_enum, current_block->block_type);
  1140. }
  1141. }
  1142. return AWS_H2ERR_SUCCESS;
  1143. malformed:
  1144. /* A malformed header-block is not a connection error, it's a Stream Error (RFC-7540 5.4.2).
  1145. * We continue decoding and report that it's malformed in on_headers_end(). */
  1146. current_block->malformed = true;
  1147. return AWS_H2ERR_SUCCESS;
  1148. already_malformed:
  1149. return AWS_H2ERR_SUCCESS;
  1150. }
  1151. static struct aws_h2err s_flush_cookie_header(struct aws_h2_decoder *decoder) {
  1152. struct aws_header_block_in_progress *current_block = &decoder->header_block_in_progress;
  1153. if (current_block->malformed) {
  1154. return AWS_H2ERR_SUCCESS;
  1155. }
  1156. if (current_block->cookies.len == 0) {
  1157. /* Nothing to flush */
  1158. return AWS_H2ERR_SUCCESS;
  1159. }
  1160. struct aws_http_header concatenated_cookie;
  1161. struct aws_byte_cursor header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("cookie");
  1162. concatenated_cookie.name = header_name;
  1163. concatenated_cookie.value = aws_byte_cursor_from_buf(&current_block->cookies);
  1164. concatenated_cookie.compression = current_block->cookie_header_compression_type;
  1165. if (current_block->is_push_promise) {
  1166. DECODER_CALL_VTABLE_STREAM_ARGS(decoder, on_push_promise_i, &concatenated_cookie, AWS_HTTP_HEADER_COOKIE);
  1167. } else {
  1168. DECODER_CALL_VTABLE_STREAM_ARGS(
  1169. decoder, on_headers_i, &concatenated_cookie, AWS_HTTP_HEADER_COOKIE, current_block->block_type);
  1170. }
  1171. return AWS_H2ERR_SUCCESS;
  1172. }
  1173. /* This state checks whether we've consumed the current frame's entire header-block fragment.
  1174. * We revisit this state after each entry is decoded.
  1175. * This state consumes no data. */
  1176. static struct aws_h2err s_state_fn_header_block_loop(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  1177. (void)input;
  1178. /* If we're out of payload data, handle frame complete */
  1179. if (decoder->frame_in_progress.payload_len == 0) {
  1180. /* If this is the end of the header-block, invoke callback and clear header_block_in_progress */
  1181. if (decoder->frame_in_progress.flags.end_headers) {
  1182. /* Ensure pseudo-headers have been flushed */
  1183. struct aws_h2err err = s_flush_pseudoheaders(decoder);
  1184. if (aws_h2err_failed(err)) {
  1185. return err;
  1186. }
  1187. /* flush the concatenated cookie header */
  1188. err = s_flush_cookie_header(decoder);
  1189. if (aws_h2err_failed(err)) {
  1190. return err;
  1191. }
  1192. bool malformed = decoder->header_block_in_progress.malformed;
  1193. DECODER_LOGF(TRACE, decoder, "Done decoding header-block, malformed=%d", malformed);
  1194. if (decoder->header_block_in_progress.is_push_promise) {
  1195. DECODER_CALL_VTABLE_STREAM_ARGS(decoder, on_push_promise_end, malformed);
  1196. } else {
  1197. DECODER_CALL_VTABLE_STREAM_ARGS(
  1198. decoder, on_headers_end, malformed, decoder->header_block_in_progress.block_type);
  1199. }
  1200. /* If header-block began with END_STREAM flag, alert user now */
  1201. if (decoder->header_block_in_progress.ends_stream) {
  1202. DECODER_CALL_VTABLE_STREAM(decoder, on_end_stream);
  1203. }
  1204. s_reset_header_block_in_progress(decoder);
  1205. } else {
  1206. DECODER_LOG(TRACE, decoder, "Done decoding header-block fragment, expecting CONTINUATION frames");
  1207. }
  1208. /* Finish this frame */
  1209. return s_decoder_switch_state(decoder, &s_state_padding);
  1210. }
  1211. DECODER_LOGF(
  1212. TRACE,
  1213. decoder,
  1214. "Decoding header-block entry, %" PRIu32 " bytes remaining in payload",
  1215. decoder->frame_in_progress.payload_len);
  1216. return s_decoder_switch_state(decoder, &s_state_header_block_entry);
  1217. }
  1218. /* We stay in this state until a single "entry" is decoded from the header-block fragment.
  1219. * Then we return to the header_block_loop state */
  1220. static struct aws_h2err s_state_fn_header_block_entry(struct aws_h2_decoder *decoder, struct aws_byte_cursor *input) {
  1221. /* This state requires at least 1 byte, but will likely consume more */
  1222. AWS_ASSERT(input->len >= s_state_header_block_entry_requires_1_bytes);
  1223. /* Feed header-block fragment to HPACK decoder.
  1224. * Don't let decoder consume anything beyond payload_len. */
  1225. struct aws_byte_cursor fragment = *input;
  1226. if (fragment.len > decoder->frame_in_progress.payload_len) {
  1227. fragment.len = decoder->frame_in_progress.payload_len;
  1228. }
  1229. const size_t prev_fragment_len = fragment.len;
  1230. struct aws_hpack_decode_result result;
  1231. if (aws_hpack_decode(&decoder->hpack, &fragment, &result)) {
  1232. DECODER_LOGF(ERROR, decoder, "Error decoding header-block fragment: %s", aws_error_name(aws_last_error()));
  1233. /* Any possible error from HPACK decoder (except OOM) is treated as a COMPRESSION error. */
  1234. if (aws_last_error() == AWS_ERROR_OOM) {
  1235. return aws_h2err_from_last_error();
  1236. } else {
  1237. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_COMPRESSION_ERROR);
  1238. }
  1239. }
  1240. /* HPACK decoder returns when it reaches the end of an entry, or when it's consumed the whole fragment.
  1241. * Update input & payload_len to reflect the number of bytes consumed. */
  1242. const size_t bytes_consumed = prev_fragment_len - fragment.len;
  1243. aws_byte_cursor_advance(input, bytes_consumed);
  1244. decoder->frame_in_progress.payload_len -= (uint32_t)bytes_consumed;
  1245. if (result.type == AWS_HPACK_DECODE_T_ONGOING) {
  1246. /* HPACK decoder hasn't finished entry */
  1247. if (decoder->frame_in_progress.payload_len > 0) {
  1248. /* More payload is coming. Remain in state until it arrives */
  1249. DECODER_LOG(TRACE, decoder, "Header-block entry partially decoded, waiting for more data.");
  1250. return AWS_H2ERR_SUCCESS;
  1251. }
  1252. if (decoder->frame_in_progress.flags.end_headers) {
  1253. /* Reached end of the frame's payload, and this frame ends the header-block.
  1254. * Error if we ended up with a partially decoded entry. */
  1255. DECODER_LOG(ERROR, decoder, "Compression error: incomplete entry at end of header-block");
  1256. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_COMPRESSION_ERROR);
  1257. }
  1258. /* Reached end of this frame's payload, but CONTINUATION frames are expected to arrive.
  1259. * We'll resume decoding this entry when we get them. */
  1260. DECODER_LOG(TRACE, decoder, "Header-block entry partially decoded, resumes in CONTINUATION frame");
  1261. return s_decoder_switch_state(decoder, &s_state_header_block_loop);
  1262. }
  1263. /* Finished decoding HPACK entry! */
  1264. /* #TODO Enforces dynamic table resize rules from RFC-7541 4.2
  1265. * If dynamic table size changed via SETTINGS frame, next header-block must start with DYNAMIC_TABLE_RESIZE entry.
  1266. * Is it illegal to receive a resize entry at other times? */
  1267. /* #TODO The TE header field ... MUST NOT contain any value other than "trailers" */
  1268. if (result.type == AWS_HPACK_DECODE_T_HEADER_FIELD) {
  1269. const struct aws_http_header *header_field = &result.data.header_field;
  1270. DECODER_LOGF(
  1271. TRACE,
  1272. decoder,
  1273. "Decoded header field: \"" PRInSTR ": " PRInSTR "\"",
  1274. AWS_BYTE_CURSOR_PRI(header_field->name),
  1275. AWS_BYTE_CURSOR_PRI(header_field->value));
  1276. struct aws_h2err err = s_process_header_field(decoder, header_field);
  1277. if (aws_h2err_failed(err)) {
  1278. return err;
  1279. }
  1280. }
  1281. return s_decoder_switch_state(decoder, &s_state_header_block_loop);
  1282. }
  1283. /* The first thing a client sends on a connection is a 24 byte magic string (RFC-7540 3.5).
  1284. * Note that this state doesn't "require" the full 24 bytes, it runs as data arrives.
  1285. * This avoids hanging if < 24 bytes rolled in. */
  1286. static struct aws_h2err s_state_fn_connection_preface_string(
  1287. struct aws_h2_decoder *decoder,
  1288. struct aws_byte_cursor *input) {
  1289. size_t remaining_len = decoder->connection_preface_cursor.len;
  1290. size_t consuming_len = input->len < remaining_len ? input->len : remaining_len;
  1291. struct aws_byte_cursor expected = aws_byte_cursor_advance(&decoder->connection_preface_cursor, consuming_len);
  1292. struct aws_byte_cursor received = aws_byte_cursor_advance(input, consuming_len);
  1293. if (!aws_byte_cursor_eq(&expected, &received)) {
  1294. DECODER_LOG(ERROR, decoder, "Client connection preface is invalid");
  1295. return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
  1296. }
  1297. if (decoder->connection_preface_cursor.len == 0) {
  1298. /* Done receiving connection preface string, proceed to decoding normal frames. */
  1299. return s_decoder_reset_state(decoder);
  1300. }
  1301. /* Remain in state until more data arrives */
  1302. return AWS_H2ERR_SUCCESS;
  1303. }
  1304. void aws_h2_decoder_set_setting_header_table_size(struct aws_h2_decoder *decoder, uint32_t data) {
  1305. /* Set the protocol_max_size_setting for hpack. */
  1306. aws_hpack_decoder_update_max_table_size(&decoder->hpack, data);
  1307. }
  1308. void aws_h2_decoder_set_setting_enable_push(struct aws_h2_decoder *decoder, uint32_t data) {
  1309. decoder->settings.enable_push = data;
  1310. }
  1311. void aws_h2_decoder_set_setting_max_frame_size(struct aws_h2_decoder *decoder, uint32_t data) {
  1312. decoder->settings.max_frame_size = data;
  1313. }