@ttsc/win32-arm64 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1062) hide show
  1. package/bin/go/VERSION +2 -2
  2. package/bin/go/bin/go.exe +0 -0
  3. package/bin/go/bin/gofmt.exe +0 -0
  4. package/bin/go/lib/time/update.bash +2 -2
  5. package/bin/go/lib/time/zoneinfo.zip +0 -0
  6. package/bin/go/pkg/include/asm_ppc64x.h +0 -16
  7. package/bin/go/pkg/tool/windows_arm64/asm.exe +0 -0
  8. package/bin/go/pkg/tool/windows_arm64/cgo.exe +0 -0
  9. package/bin/go/pkg/tool/windows_arm64/compile.exe +0 -0
  10. package/bin/go/pkg/tool/windows_arm64/cover.exe +0 -0
  11. package/bin/go/pkg/tool/windows_arm64/fix.exe +0 -0
  12. package/bin/go/pkg/tool/windows_arm64/link.exe +0 -0
  13. package/bin/go/pkg/tool/windows_arm64/preprofile.exe +0 -0
  14. package/bin/go/pkg/tool/windows_arm64/vet.exe +0 -0
  15. package/bin/go/src/archive/tar/reader.go +2 -1
  16. package/bin/go/src/archive/zip/reader.go +5 -29
  17. package/bin/go/src/archive/zip/struct.go +5 -6
  18. package/bin/go/src/archive/zip/writer.go +120 -60
  19. package/bin/go/src/bufio/bufio.go +1 -1
  20. package/bin/go/src/bytes/buffer.go +3 -3
  21. package/bin/go/src/bytes/bytes.go +45 -25
  22. package/bin/go/src/compress/flate/deflate.go +512 -363
  23. package/bin/go/src/compress/flate/deflatefast.go +156 -262
  24. package/bin/go/src/compress/flate/dict_decoder.go +1 -4
  25. package/bin/go/src/compress/flate/huffman_bit_writer.go +673 -250
  26. package/bin/go/src/compress/flate/huffman_code.go +164 -92
  27. package/bin/go/src/compress/flate/level1.go +195 -0
  28. package/bin/go/src/compress/flate/level2.go +190 -0
  29. package/bin/go/src/compress/flate/level3.go +228 -0
  30. package/bin/go/src/compress/flate/level4.go +200 -0
  31. package/bin/go/src/compress/flate/level5.go +287 -0
  32. package/bin/go/src/compress/flate/level6.go +297 -0
  33. package/bin/go/src/compress/flate/load_store.go +43 -0
  34. package/bin/go/src/compress/flate/regmask_amd64.go +9 -0
  35. package/bin/go/src/compress/flate/regmask_other.go +11 -0
  36. package/bin/go/src/compress/flate/token.go +238 -26
  37. package/bin/go/src/compress/gzip/gzip.go +8 -0
  38. package/bin/go/src/compress/zlib/writer.go +12 -0
  39. package/bin/go/src/context/context.go +6 -5
  40. package/bin/go/src/crypto/cipher/gcm.go +0 -4
  41. package/bin/go/src/crypto/crypto.go +27 -4
  42. package/bin/go/src/crypto/des/const.go +1 -1
  43. package/bin/go/src/crypto/ecdsa/ecdsa.go +21 -4
  44. package/bin/go/src/crypto/ed25519/ed25519.go +13 -0
  45. package/bin/go/src/crypto/internal/boring/aes.go +2 -3
  46. package/bin/go/src/crypto/internal/cryptotest/aead.go +53 -0
  47. package/bin/go/src/crypto/internal/cryptotest/boundary.go +34 -0
  48. package/bin/go/src/crypto/internal/cryptotest/boundary_compat.go +16 -0
  49. package/bin/go/src/crypto/internal/cryptotest/fetchmodule.go +9 -3
  50. package/bin/go/src/crypto/internal/cryptotest/fips140.go +62 -3
  51. package/bin/go/src/crypto/internal/cryptotest/hash.go +14 -0
  52. package/bin/go/src/crypto/internal/cryptotest/wycheproof/_schema/go.mod +19 -0
  53. package/bin/go/src/crypto/internal/cryptotest/wycheproof/_schema/go.sum +27 -0
  54. package/bin/go/src/crypto/internal/cryptotest/wycheproof/_schema/schema_gen.go +151 -0
  55. package/bin/go/src/crypto/internal/cryptotest/wycheproof/schema.go +9792 -0
  56. package/bin/go/src/crypto/internal/cryptotest/wycheproof/schemaversion.go +11 -0
  57. package/bin/go/src/crypto/internal/cryptotest/wycheproof/wycheproof.go +165 -0
  58. package/bin/go/src/crypto/internal/cryptotest/x509limbo/_schema/go.mod +14 -0
  59. package/bin/go/src/crypto/internal/cryptotest/x509limbo/_schema/go.sum +25 -0
  60. package/bin/go/src/crypto/internal/cryptotest/x509limbo/_schema/schema_gen.go +125 -0
  61. package/bin/go/src/crypto/internal/cryptotest/x509limbo/schema.go +591 -0
  62. package/bin/go/src/crypto/internal/cryptotest/x509limbo/schemaversion.go +14 -0
  63. package/bin/go/src/crypto/internal/fips140/aes/_asm/ctr/go.mod +1 -1
  64. package/bin/go/src/crypto/internal/fips140/aes/_asm/standard/go.mod +1 -1
  65. package/bin/go/src/crypto/internal/fips140/aes/gcm/_asm/gcm/gcm_amd64_asm.go +36 -32
  66. package/bin/go/src/crypto/internal/fips140/aes/gcm/_asm/gcm/go.mod +5 -5
  67. package/bin/go/src/crypto/internal/fips140/aes/gcm/_asm/gcm/go.sum +8 -6
  68. package/bin/go/src/crypto/internal/fips140/aes/gcm/gcm_amd64.s +29 -17
  69. package/bin/go/src/crypto/internal/fips140/aes/gcm/gcm_arm64.s +73 -72
  70. package/bin/go/src/crypto/internal/fips140/aes/gcm/ghash.go +140 -124
  71. package/bin/go/src/crypto/internal/fips140/bigmod/nat.go +18 -0
  72. package/bin/go/src/crypto/internal/fips140/check/checktest/asm_loong64.s +23 -0
  73. package/bin/go/src/crypto/internal/fips140/check/checktest/asm_none.go +1 -1
  74. package/bin/go/src/crypto/internal/fips140/check/checktest/asm_stub.go +1 -1
  75. package/bin/go/src/crypto/internal/fips140/drbg/rand.go +12 -4
  76. package/bin/go/src/crypto/internal/fips140/ecdsa/ecdsa.go +17 -10
  77. package/bin/go/src/crypto/internal/fips140/edwards25519/field/_asm/fe_amd64_asm.go +0 -90
  78. package/bin/go/src/crypto/internal/fips140/edwards25519/field/fe.go +64 -97
  79. package/bin/go/src/crypto/internal/fips140/edwards25519/field/fe_amd64.go +0 -5
  80. package/bin/go/src/crypto/internal/fips140/edwards25519/field/fe_amd64.s +0 -167
  81. package/bin/go/src/crypto/internal/fips140/edwards25519/field/fe_amd64_noasm.go +0 -2
  82. package/bin/go/src/crypto/internal/fips140/edwards25519/field/fe_generic.go +57 -1
  83. package/bin/go/src/crypto/internal/fips140/edwards25519/scalarmult.go +3 -2
  84. package/bin/go/src/crypto/internal/fips140/mldsa/mldsa.go +31 -25
  85. package/bin/go/src/crypto/internal/fips140/mldsa/semiexpanded.go +2 -2
  86. package/bin/go/src/crypto/internal/fips140/nistec/_asm/go.mod +4 -4
  87. package/bin/go/src/crypto/internal/fips140/nistec/_asm/go.sum +6 -0
  88. package/bin/go/src/crypto/internal/fips140/nistec/_asm/p256_asm.go +1 -613
  89. package/bin/go/src/crypto/internal/fips140/nistec/p256.go +2 -2
  90. package/bin/go/src/crypto/internal/fips140/nistec/p256_asm.go +7 -6
  91. package/bin/go/src/crypto/internal/fips140/nistec/p256_asm_amd64.s +0 -503
  92. package/bin/go/src/crypto/internal/fips140/nistec/p256_asm_arm64.s +4 -429
  93. package/bin/go/src/crypto/internal/fips140/nistec/p256_ordinv.go +511 -47
  94. package/bin/go/src/crypto/internal/fips140/pbkdf2/pbkdf2.go +1 -1
  95. package/bin/go/src/crypto/internal/fips140/rsa/keygen.go +48 -46
  96. package/bin/go/src/crypto/internal/fips140/rsa/largeexponent.go +365 -0
  97. package/bin/go/src/crypto/internal/fips140/rsa/pkcs1v15.go +27 -0
  98. package/bin/go/src/crypto/internal/fips140/sha256/_asm/go.mod +1 -1
  99. package/bin/go/src/crypto/internal/fips140/sha3/_asm/go.mod +1 -1
  100. package/bin/go/src/crypto/internal/fips140/sha512/_asm/go.mod +1 -1
  101. package/bin/go/src/crypto/internal/fips140/subtle/constant_time.go +1 -1
  102. package/bin/go/src/crypto/internal/fips140/subtle/xor_asm.go +1 -1
  103. package/bin/go/src/crypto/internal/fips140/subtle/xor_riscv64.go +18 -0
  104. package/bin/go/src/crypto/internal/fips140/subtle/xor_riscv64.s +33 -2
  105. package/bin/go/src/crypto/internal/fips140deps/cpu/cpu.go +2 -0
  106. package/bin/go/src/crypto/internal/fips140deps/time/time.go +7 -4
  107. package/bin/go/src/crypto/internal/fips140only/fips140only.go +0 -7
  108. package/bin/go/src/crypto/internal/fips140only/random_fips140v1.0.go +17 -0
  109. package/bin/go/src/crypto/internal/fips140only/random_fips140v1.28.go +16 -0
  110. package/bin/go/src/crypto/internal/fips140test/acvp_capabilities_fips140v1.28.json +86 -0
  111. package/bin/go/src/crypto/internal/fips140test/acvp_test_fips140v1.28.config.json +58 -0
  112. package/bin/go/src/crypto/internal/rand/rand.go +14 -14
  113. package/bin/go/src/crypto/internal/rand/random_fips140v1.0.go +20 -0
  114. package/bin/go/src/crypto/internal/rand/random_fips140v1.28.go +19 -0
  115. package/bin/go/src/crypto/mldsa/mldsa.go +97 -0
  116. package/bin/go/src/crypto/mldsa/mldsa_fips140v1.0.go +116 -0
  117. package/bin/go/src/crypto/mldsa/mldsa_fips140v1.26.go +226 -0
  118. package/bin/go/src/crypto/mlkem/mlkem.go +8 -2
  119. package/bin/go/src/crypto/rsa/fips.go +26 -8
  120. package/bin/go/src/crypto/rsa/pkcs1v15.go +2 -2
  121. package/bin/go/src/crypto/rsa/rsa.go +25 -2
  122. package/bin/go/src/crypto/sha1/sha1block_decl.go +1 -1
  123. package/bin/go/src/crypto/sha1/sha1block_generic.go +1 -1
  124. package/bin/go/src/crypto/sha1/sha1block_loong64.s +24 -8
  125. package/bin/go/src/crypto/sha1/sha1block_riscv64.s +225 -0
  126. package/bin/go/src/crypto/sha3/sha3.go +3 -2
  127. package/bin/go/src/crypto/tls/alert.go +2 -0
  128. package/bin/go/src/crypto/tls/auth.go +31 -0
  129. package/bin/go/src/crypto/tls/bogo_config.json +12 -23
  130. package/bin/go/src/crypto/tls/cipher_suites.go +3 -11
  131. package/bin/go/src/crypto/tls/common.go +106 -59
  132. package/bin/go/src/crypto/tls/common_string.go +18 -5
  133. package/bin/go/src/crypto/tls/conn.go +33 -35
  134. package/bin/go/src/crypto/tls/defaults.go +26 -20
  135. package/bin/go/src/crypto/tls/defaults_fips140.go +9 -0
  136. package/bin/go/src/crypto/tls/ech.go +9 -4
  137. package/bin/go/src/crypto/tls/generate_cert.go +8 -2
  138. package/bin/go/src/crypto/tls/handshake_client.go +17 -17
  139. package/bin/go/src/crypto/tls/handshake_client_tls13.go +8 -3
  140. package/bin/go/src/crypto/tls/handshake_server.go +26 -19
  141. package/bin/go/src/crypto/tls/handshake_server_tls13.go +8 -5
  142. package/bin/go/src/crypto/tls/key_agreement.go +5 -1
  143. package/bin/go/src/crypto/tls/key_schedule.go +42 -17
  144. package/bin/go/src/crypto/tls/prf.go +1 -1
  145. package/bin/go/src/crypto/tls/quic.go +6 -7
  146. package/bin/go/src/crypto/tls/tls.go +25 -29
  147. package/bin/go/src/crypto/x509/cert_pool.go +8 -4
  148. package/bin/go/src/crypto/x509/constraints.go +5 -0
  149. package/bin/go/src/crypto/x509/parser.go +101 -15
  150. package/bin/go/src/crypto/x509/pkcs8.go +45 -4
  151. package/bin/go/src/crypto/x509/pkix/pkix.go +33 -9
  152. package/bin/go/src/crypto/x509/root.go +113 -0
  153. package/bin/go/src/crypto/x509/root_darwin.go +8 -4
  154. package/bin/go/src/crypto/x509/root_plan9.go +2 -23
  155. package/bin/go/src/crypto/x509/root_unix.go +0 -97
  156. package/bin/go/src/crypto/x509/root_windows.go +8 -3
  157. package/bin/go/src/crypto/x509/verify.go +43 -4
  158. package/bin/go/src/crypto/x509/x509.go +169 -30
  159. package/bin/go/src/database/sql/closemu.go +119 -0
  160. package/bin/go/src/database/sql/convert.go +63 -4
  161. package/bin/go/src/database/sql/driver/driver.go +26 -0
  162. package/bin/go/src/database/sql/driver/types.go +4 -0
  163. package/bin/go/src/database/sql/internal/sql.go +22 -0
  164. package/bin/go/src/database/sql/sql.go +89 -40
  165. package/bin/go/src/debug/buildinfo/buildinfo.go +0 -13
  166. package/bin/go/src/debug/dwarf/buf.go +7 -1
  167. package/bin/go/src/debug/dwarf/class_string.go +3 -2
  168. package/bin/go/src/debug/elf/file.go +80 -50
  169. package/bin/go/src/debug/elf/reader.go +1 -1
  170. package/bin/go/src/debug/gosym/symtab.go +26 -30
  171. package/bin/go/src/debug/macho/file.go +2 -2
  172. package/bin/go/src/debug/macho/reloctype_string.go +12 -8
  173. package/bin/go/src/debug/pe/file.go +6 -3
  174. package/bin/go/src/encoding/base32/base32.go +29 -31
  175. package/bin/go/src/encoding/base64/base64.go +24 -29
  176. package/bin/go/src/encoding/gob/decode.go +7 -1
  177. package/bin/go/src/encoding/gob/type.go +6 -6
  178. package/bin/go/src/encoding/hex/hex.go +6 -6
  179. package/bin/go/src/encoding/json/decode.go +4 -3
  180. package/bin/go/src/encoding/json/encode.go +1 -2
  181. package/bin/go/src/encoding/json/fold.go +1 -1
  182. package/bin/go/src/encoding/json/internal/internal.go +11 -1
  183. package/bin/go/src/encoding/json/internal/jsonflags/flags.go +17 -9
  184. package/bin/go/src/encoding/json/internal/jsonopts/options.go +52 -37
  185. package/bin/go/src/encoding/json/internal/jsonopts/options_format.go +124 -0
  186. package/bin/go/src/encoding/json/internal/jsontest/_embed/canada_geometry.json.zst +0 -0
  187. package/bin/go/src/encoding/json/internal/jsontest/_embed/citm_catalog.json.zst +0 -0
  188. package/bin/go/src/encoding/json/internal/jsontest/_embed/golang_source.json.zst +0 -0
  189. package/bin/go/src/encoding/json/internal/jsontest/_embed/string_escaped.json.zst +0 -0
  190. package/bin/go/src/encoding/json/internal/jsontest/_embed/string_unicode.json.zst +0 -0
  191. package/bin/go/src/encoding/json/internal/jsontest/_embed/synthea_fhir.json.zst +0 -0
  192. package/bin/go/src/encoding/json/internal/jsontest/_embed/twitter_status.json.zst +0 -0
  193. package/bin/go/src/encoding/json/internal/jsontest/testdata.go +10 -4
  194. package/bin/go/src/encoding/json/internal/jsonwire/decode.go +13 -36
  195. package/bin/go/src/encoding/json/internal/jsonwire/encode.go +7 -7
  196. package/bin/go/src/encoding/json/internal/jsonwire/wire.go +30 -38
  197. package/bin/go/src/encoding/json/jsontext/decode.go +49 -14
  198. package/bin/go/src/encoding/json/jsontext/doc.go +6 -11
  199. package/bin/go/src/encoding/json/jsontext/encode.go +55 -39
  200. package/bin/go/src/encoding/json/jsontext/errors.go +34 -3
  201. package/bin/go/src/encoding/json/jsontext/export.go +14 -0
  202. package/bin/go/src/encoding/json/jsontext/options.go +8 -8
  203. package/bin/go/src/encoding/json/jsontext/quote.go +2 -2
  204. package/bin/go/src/encoding/json/jsontext/state.go +14 -14
  205. package/bin/go/src/encoding/json/jsontext/token.go +246 -101
  206. package/bin/go/src/encoding/json/jsontext/value.go +31 -16
  207. package/bin/go/src/encoding/json/stream.go +14 -2
  208. package/bin/go/src/encoding/json/v2/arshal.go +100 -114
  209. package/bin/go/src/encoding/json/v2/arshal_any.go +6 -5
  210. package/bin/go/src/encoding/json/v2/arshal_default.go +292 -189
  211. package/bin/go/src/encoding/json/v2/{arshal_inlined.go → arshal_embedded.go} +14 -14
  212. package/bin/go/src/encoding/json/v2/arshal_funcs.go +28 -47
  213. package/bin/go/src/encoding/json/v2/arshal_methods.go +98 -29
  214. package/bin/go/src/encoding/json/v2/arshal_time.go +33 -13
  215. package/bin/go/src/encoding/json/v2/doc.go +40 -55
  216. package/bin/go/src/encoding/json/v2/errors.go +29 -9
  217. package/bin/go/src/encoding/json/v2/fields.go +83 -81
  218. package/bin/go/src/encoding/json/v2/intern.go +2 -2
  219. package/bin/go/src/encoding/json/v2/options.go +57 -41
  220. package/bin/go/src/encoding/json/v2_decode.go +21 -9
  221. package/bin/go/src/encoding/json/v2_encode.go +21 -10
  222. package/bin/go/src/encoding/json/v2_indent.go +2 -0
  223. package/bin/go/src/encoding/json/v2_inject.go +7 -4
  224. package/bin/go/src/encoding/json/v2_options.go +37 -30
  225. package/bin/go/src/encoding/json/v2_scanner.go +6 -1
  226. package/bin/go/src/encoding/json/v2_stream.go +49 -14
  227. package/bin/go/src/encoding/pem/pem.go +6 -2
  228. package/bin/go/src/fmt/doc.go +11 -1
  229. package/bin/go/src/fmt/print.go +69 -82
  230. package/bin/go/src/go/ast/ast.go +4 -4
  231. package/bin/go/src/go/ast/filter.go +1 -1
  232. package/bin/go/src/go/ast/scope.go +2 -2
  233. package/bin/go/src/go/build/build.go +1 -1
  234. package/bin/go/src/go/build/constraint/vers.go +4 -1
  235. package/bin/go/src/go/build/read.go +2 -2
  236. package/bin/go/src/go/constant/kind_string.go +3 -2
  237. package/bin/go/src/go/constant/value.go +26 -4
  238. package/bin/go/src/go/doc/comment/std.go +1 -0
  239. package/bin/go/src/go/importer/importer.go +4 -3
  240. package/bin/go/src/go/internal/gccgoimporter/parser.go +2 -0
  241. package/bin/go/src/go/internal/gcimporter/ureader.go +141 -56
  242. package/bin/go/src/go/parser/parser.go +11 -22
  243. package/bin/go/src/go/printer/math.go +28 -0
  244. package/bin/go/src/go/printer/nodes.go +28 -11
  245. package/bin/go/src/go/printer/printer.go +3 -1
  246. package/bin/go/src/go/scanner/errors.go +2 -0
  247. package/bin/go/src/go/scanner/scanner.go +40 -28
  248. package/bin/go/src/go/token/position.go +7 -16
  249. package/bin/go/src/go/types/alias.go +0 -18
  250. package/bin/go/src/go/types/api.go +4 -10
  251. package/bin/go/src/go/types/api_predicates.go +2 -2
  252. package/bin/go/src/go/types/assignments.go +44 -38
  253. package/bin/go/src/go/types/builtins.go +199 -168
  254. package/bin/go/src/go/types/call.go +155 -138
  255. package/bin/go/src/go/types/check.go +0 -83
  256. package/bin/go/src/go/types/const.go +22 -10
  257. package/bin/go/src/go/types/conversions.go +19 -19
  258. package/bin/go/src/go/types/cycles.go +29 -42
  259. package/bin/go/src/go/types/decl.go +33 -81
  260. package/bin/go/src/go/types/expr.go +191 -183
  261. package/bin/go/src/go/types/gotype.go +1 -0
  262. package/bin/go/src/go/types/hash.go +309 -0
  263. package/bin/go/src/go/types/index.go +91 -61
  264. package/bin/go/src/go/types/infer.go +11 -11
  265. package/bin/go/src/go/types/instantiate.go +27 -15
  266. package/bin/go/src/go/types/interface.go +2 -2
  267. package/bin/go/src/go/types/literals.go +56 -32
  268. package/bin/go/src/go/types/lookup.go +31 -14
  269. package/bin/go/src/go/types/named.go +58 -54
  270. package/bin/go/src/go/types/object.go +4 -3
  271. package/bin/go/src/go/types/operand.go +50 -34
  272. package/bin/go/src/go/types/range.go +19 -16
  273. package/bin/go/src/go/types/recording.go +24 -7
  274. package/bin/go/src/go/types/resolver.go +16 -18
  275. package/bin/go/src/go/types/scope.go +1 -15
  276. package/bin/go/src/go/types/selection.go +3 -1
  277. package/bin/go/src/go/types/signature.go +10 -11
  278. package/bin/go/src/go/types/stmt.go +34 -28
  279. package/bin/go/src/go/types/subst.go +82 -5
  280. package/bin/go/src/go/types/trie.go +93 -0
  281. package/bin/go/src/go/types/typelists.go +28 -0
  282. package/bin/go/src/go/types/typestring.go +5 -9
  283. package/bin/go/src/go/types/typexpr.go +17 -28
  284. package/bin/go/src/go/types/unify.go +12 -3
  285. package/bin/go/src/go/types/universe.go +12 -40
  286. package/bin/go/src/go/types/version.go +4 -0
  287. package/bin/go/src/go.mod +5 -5
  288. package/bin/go/src/go.sum +8 -8
  289. package/bin/go/src/hash/maphash/hasher.go +139 -0
  290. package/bin/go/src/hash/maphash/maphash.go +59 -4
  291. package/bin/go/src/html/template/attr_string.go +3 -2
  292. package/bin/go/src/html/template/delim_string.go +3 -2
  293. package/bin/go/src/html/template/element_string.go +3 -2
  294. package/bin/go/src/html/template/jsctx_string.go +3 -2
  295. package/bin/go/src/html/template/state_string.go +3 -2
  296. package/bin/go/src/html/template/template.go +7 -4
  297. package/bin/go/src/html/template/transition.go +1 -1
  298. package/bin/go/src/html/template/urlpart_string.go +3 -2
  299. package/bin/go/src/image/format.go +9 -0
  300. package/bin/go/src/image/gif/reader.go +18 -0
  301. package/bin/go/src/image/jpeg/huffman.go +22 -3
  302. package/bin/go/src/image/jpeg/reader.go +54 -29
  303. package/bin/go/src/image/jpeg/scan.go +68 -38
  304. package/bin/go/src/image/png/writer.go +8 -0
  305. package/bin/go/src/index/suffixarray/suffixarray.go +14 -6
  306. package/bin/go/src/internal/abi/abi_generic.go +1 -1
  307. package/bin/go/src/internal/abi/abi_s390x.go +0 -2
  308. package/bin/go/src/internal/abi/compiletype.go +30 -0
  309. package/bin/go/src/internal/abi/iface.go +13 -1
  310. package/bin/go/src/internal/abi/map.go +21 -3
  311. package/bin/go/src/internal/abi/type.go +136 -27
  312. package/bin/go/src/internal/buildcfg/exp.go +8 -8
  313. package/bin/go/src/internal/buildcfg/zbootstrap.go +1 -1
  314. package/bin/go/src/internal/bytealg/bytealg.go +16 -16
  315. package/bin/go/src/internal/bytealg/compare_s390x.s +0 -24
  316. package/bin/go/src/internal/bytealg/equal_s390x.s +0 -18
  317. package/bin/go/src/internal/bytealg/indexbyte_arm64.s +28 -0
  318. package/bin/go/src/internal/bytealg/indexbyte_s390x.s +0 -33
  319. package/bin/go/src/internal/coverage/encodemeta/encode.go +1 -1
  320. package/bin/go/src/internal/cpu/cpu.go +22 -7
  321. package/bin/go/src/internal/cpu/cpu_arm64.go +8 -1
  322. package/bin/go/src/internal/cpu/cpu_arm64.s +7 -0
  323. package/bin/go/src/internal/cpu/cpu_arm64_darwin.go +2 -0
  324. package/bin/go/src/internal/cpu/cpu_arm64_freebsd.go +2 -1
  325. package/bin/go/src/internal/cpu/cpu_arm64_hwcap.go +2 -0
  326. package/bin/go/src/internal/cpu/cpu_arm64_openbsd.go +6 -1
  327. package/bin/go/src/internal/cpu/cpu_arm64_other.go +1 -1
  328. package/bin/go/src/internal/cpu/cpu_arm64_windows.go +26 -0
  329. package/bin/go/src/internal/cpu/cpu_loong64.go +14 -2
  330. package/bin/go/src/internal/cpu/cpu_riscv64.go +10 -0
  331. package/bin/go/src/internal/cpu/cpu_riscv64_linux.go +21 -0
  332. package/bin/go/src/internal/cpu/cpu_windows.go +20 -0
  333. package/bin/go/src/internal/cpu/cpu_x86.go +2 -0
  334. package/bin/go/src/internal/filepathlite/path_windows.go +30 -17
  335. package/bin/go/src/internal/fuzz/fuzz.go +5 -1
  336. package/bin/go/src/internal/fuzz/mutator.go +2 -2
  337. package/bin/go/src/internal/fuzz/worker.go +1 -1
  338. package/bin/go/src/internal/gate/gate.go +76 -0
  339. package/bin/go/src/internal/godebugs/table.go +29 -10
  340. package/bin/go/src/internal/goexperiment/exp_mapsplitgroup_off.go +8 -0
  341. package/bin/go/src/internal/goexperiment/exp_mapsplitgroup_on.go +8 -0
  342. package/bin/go/src/internal/goexperiment/flags.go +5 -3
  343. package/bin/go/src/internal/goversion/goversion.go +1 -1
  344. package/bin/go/src/internal/lazyregexp/lazyre.go +4 -0
  345. package/bin/go/src/internal/nettest/conn.go +437 -0
  346. package/bin/go/src/internal/nettest/listener.go +148 -0
  347. package/bin/go/src/internal/nettest/packetconn.go +250 -0
  348. package/bin/go/src/internal/nettest/queue.go +33 -0
  349. package/bin/go/src/internal/pkgbits/syncmarker_string.go +4 -4
  350. package/bin/go/src/internal/pkgbits/version.go +27 -1
  351. package/bin/go/src/internal/platform/supported.go +8 -10
  352. package/bin/go/src/internal/platform/zosarch.go +1 -3
  353. package/bin/go/src/internal/poll/fd_mutex.go +49 -10
  354. package/bin/go/src/internal/poll/fd_unix.go +6 -1
  355. package/bin/go/src/internal/poll/fd_windows.go +175 -191
  356. package/bin/go/src/internal/poll/fd_writev_libc.go +1 -1
  357. package/bin/go/src/internal/poll/fd_writev_unix.go +1 -1
  358. package/bin/go/src/internal/poll/file_plan9.go +4 -4
  359. package/bin/go/src/internal/poll/sendfile_windows.go +1 -3
  360. package/bin/go/src/internal/poll/splice_linux.go +1 -1
  361. package/bin/go/src/internal/profile/encode.go +1 -1
  362. package/bin/go/src/internal/profile/profile.go +5 -3
  363. package/bin/go/src/internal/profilerecord/profilerecord.go +2 -2
  364. package/bin/go/src/internal/reflectlite/value.go +1 -15
  365. package/bin/go/src/internal/runtime/atomic/atomic_386.go +0 -6
  366. package/bin/go/src/internal/runtime/atomic/atomic_amd64.go +0 -6
  367. package/bin/go/src/internal/runtime/atomic/atomic_andor_generic.go +0 -11
  368. package/bin/go/src/internal/runtime/atomic/atomic_arm.go +0 -6
  369. package/bin/go/src/internal/runtime/atomic/atomic_loong64.go +2 -2
  370. package/bin/go/src/internal/runtime/atomic/atomic_loong64.s +22 -11
  371. package/bin/go/src/internal/runtime/atomic/atomic_mipsx.go +0 -10
  372. package/bin/go/src/internal/runtime/atomic/atomic_riscv64.s +4 -4
  373. package/bin/go/src/internal/runtime/atomic/atomic_s390x.go +0 -6
  374. package/bin/go/src/internal/runtime/atomic/atomic_wasm.go +0 -31
  375. package/bin/go/src/internal/runtime/atomic/linkname.go +34 -0
  376. package/bin/go/src/internal/runtime/exithook/hooks.go +0 -4
  377. package/bin/go/src/internal/runtime/gc/scan/expand_amd64.s +2285 -2285
  378. package/bin/go/src/internal/runtime/gc/scan/mkasm.go +1 -1
  379. package/bin/go/src/internal/runtime/gc/scan/scan_amd64.go +2 -1
  380. package/bin/go/src/internal/runtime/gc/scan/scan_amd64.s +4 -2
  381. package/bin/go/src/internal/runtime/maps/group.go +22 -13
  382. package/bin/go/src/internal/runtime/maps/map.go +35 -14
  383. package/bin/go/src/internal/runtime/maps/memhash_386.s +408 -0
  384. package/bin/go/src/internal/runtime/maps/memhash_aes.go +38 -0
  385. package/bin/go/src/internal/runtime/maps/memhash_aes_asm.go +24 -0
  386. package/bin/go/src/internal/runtime/maps/memhash_aes_simd.go +49 -0
  387. package/bin/go/src/internal/runtime/maps/memhash_align_check.go +10 -0
  388. package/bin/go/src/internal/runtime/maps/memhash_align_nocheck.go +16 -0
  389. package/bin/go/src/internal/runtime/maps/memhash_amd64.s +426 -0
  390. package/bin/go/src/internal/runtime/maps/memhash_arm64.s +366 -0
  391. package/bin/go/src/internal/runtime/maps/memhash_noaes.go +43 -0
  392. package/bin/go/src/internal/runtime/maps/memhash_nosimd_amd64.s +33 -0
  393. package/bin/go/src/internal/runtime/maps/runtime.go +37 -88
  394. package/bin/go/src/internal/runtime/maps/runtime_alg.go +93 -0
  395. package/bin/go/src/internal/runtime/maps/runtime_fast32.go +111 -97
  396. package/bin/go/src/internal/runtime/maps/runtime_fast64.go +137 -98
  397. package/bin/go/src/internal/runtime/maps/runtime_faststr.go +96 -89
  398. package/bin/go/src/{runtime/hash32.go → internal/runtime/maps/runtime_hash32.go} +8 -10
  399. package/bin/go/src/{runtime/hash64.go → internal/runtime/maps/runtime_hash64.go} +8 -8
  400. package/bin/go/src/internal/runtime/maps/table.go +66 -3
  401. package/bin/go/src/internal/runtime/math/math.go +0 -21
  402. package/bin/go/src/internal/runtime/startlinetest/func_amd64.s +2 -1
  403. package/bin/go/src/internal/runtime/sys/dit_arm64.go +3 -0
  404. package/bin/go/src/internal/runtime/sys/dit_arm64.s +16 -3
  405. package/bin/go/src/internal/runtime/syscall/linux/asm_linux_s390x.s +0 -23
  406. package/bin/go/src/internal/runtime/syscall/windows/asm_windows_386.s +7 -4
  407. package/bin/go/src/internal/runtime/syscall/windows/asm_windows_amd64.s +10 -8
  408. package/bin/go/src/internal/runtime/syscall/windows/asm_windows_arm64.s +0 -1
  409. package/bin/go/src/internal/runtime/syscall/windows/defs_windows.go +4 -0
  410. package/bin/go/src/internal/runtime/syscall/windows/syscall_windows.go +7 -9
  411. package/bin/go/src/internal/strconv/atof.go +69 -42
  412. package/bin/go/src/internal/strconv/atoi.go +1 -0
  413. package/bin/go/src/internal/strconv/ftoa.go +329 -357
  414. package/bin/go/src/internal/strconv/itoa.go +53 -59
  415. package/bin/go/src/internal/strconv/pow10gen.go +15 -3
  416. package/bin/go/src/internal/strconv/pow10tab.go +670 -670
  417. package/bin/go/src/internal/strconv/uscale.go +290 -0
  418. package/bin/go/src/internal/stringslite/strings.go +14 -42
  419. package/bin/go/src/internal/syscall/unix/asm_openbsd.s +0 -2
  420. package/bin/go/src/internal/syscall/unix/at.go +1 -1
  421. package/bin/go/src/internal/syscall/unix/at_fstatat.go +1 -1
  422. package/bin/go/src/internal/syscall/unix/at_libc2.go +1 -1
  423. package/bin/go/src/internal/syscall/unix/at_openbsd.go +0 -2
  424. package/bin/go/src/internal/syscall/unix/faccessat_bsd.go +1 -1
  425. package/bin/go/src/internal/syscall/unix/faccessat_openbsd.go +0 -2
  426. package/bin/go/src/internal/syscall/windows/at_windows.go +5 -5
  427. package/bin/go/src/internal/syscall/windows/net_windows.go +1 -0
  428. package/bin/go/src/internal/syscall/windows/string_windows.go +6 -3
  429. package/bin/go/src/internal/syscall/windows/syscall_windows.go +2 -0
  430. package/bin/go/src/internal/syscall/windows/types_windows.go +89 -4
  431. package/bin/go/src/internal/syscall/windows/zsyscall_windows.go +7 -0
  432. package/bin/go/src/internal/testenv/testenv.go +24 -1
  433. package/bin/go/src/internal/trace/event.go +1 -1
  434. package/bin/go/src/internal/trace/tracev2/events.go +2 -0
  435. package/bin/go/src/internal/trace/traceviewer/pprof.go +1 -0
  436. package/bin/go/src/internal/types/errors/generrordocs.go +1 -1
  437. package/bin/go/src/io/fs/fs.go +4 -1
  438. package/bin/go/src/io/fs/glob.go +1 -1
  439. package/bin/go/src/io/fs/readdir.go +3 -3
  440. package/bin/go/src/io/fs/readfile.go +3 -3
  441. package/bin/go/src/io/fs/stat.go +1 -1
  442. package/bin/go/src/io/fs/sub.go +4 -2
  443. package/bin/go/src/iter/iter.go +2 -2
  444. package/bin/go/src/log/slog/handler.go +0 -1
  445. package/bin/go/src/log/slog/json_handler.go +7 -1
  446. package/bin/go/src/log/slog/logger.go +16 -0
  447. package/bin/go/src/log/slog/text_handler.go +10 -1
  448. package/bin/go/src/log/slog/value.go +1 -1
  449. package/bin/go/src/log/syslog/doc.go +5 -0
  450. package/bin/go/src/math/abs.go +1 -1
  451. package/bin/go/src/math/big/accuracy_string.go +4 -4
  452. package/bin/go/src/math/big/arith.go +1 -1
  453. package/bin/go/src/math/big/arith_loong64.s +2 -4
  454. package/bin/go/src/math/big/float.go +2 -0
  455. package/bin/go/src/math/big/ftoa.go +11 -5
  456. package/bin/go/src/math/big/int.go +84 -1
  457. package/bin/go/src/math/big/intconv.go +19 -4
  458. package/bin/go/src/math/big/internal/asmgen/loong64.go +2 -0
  459. package/bin/go/src/math/big/nat.go +68 -17
  460. package/bin/go/src/math/big/natdiv.go +8 -5
  461. package/bin/go/src/math/big/roundingmode_string.go +3 -2
  462. package/bin/go/src/math/copysign.go +1 -2
  463. package/bin/go/src/math/exp2_asm.go +1 -1
  464. package/bin/go/src/math/exp2_noasm.go +1 -1
  465. package/bin/go/src/math/exp_asm.go +1 -1
  466. package/bin/go/src/math/exp_loong64.s +4 -12
  467. package/bin/go/src/math/exp_noasm.go +1 -1
  468. package/bin/go/src/math/exp_riscv64.s +236 -0
  469. package/bin/go/src/math/nextafter.go +4 -2
  470. package/bin/go/src/math/pow10.go +1 -1
  471. package/bin/go/src/math/rand/v2/rand.go +14 -4
  472. package/bin/go/src/mime/type.go +3 -2
  473. package/bin/go/src/net/dial.go +10 -6
  474. package/bin/go/src/net/dnsclient_unix.go +37 -8
  475. package/bin/go/src/net/dnsconfig.go +6 -0
  476. package/bin/go/src/net/fd_plan9.go +13 -6
  477. package/bin/go/src/net/fd_unix.go +3 -7
  478. package/bin/go/src/net/fd_windows.go +4 -9
  479. package/bin/go/src/net/file_plan9.go +1 -1
  480. package/bin/go/src/net/file_posix.go +1 -5
  481. package/bin/go/src/net/http/client.go +21 -4
  482. package/bin/go/src/net/http/clientconn.go +20 -1
  483. package/bin/go/src/net/http/clone.go +1 -10
  484. package/bin/go/src/net/http/cookie.go +5 -6
  485. package/bin/go/src/net/http/cookiejar/jar.go +6 -4
  486. package/bin/go/src/net/http/fcgi/fcgi.go +1 -2
  487. package/bin/go/src/net/http/fs.go +8 -1
  488. package/bin/go/src/net/http/http.go +29 -12
  489. package/bin/go/src/net/http/http2.go +561 -0
  490. package/bin/go/src/net/http/httptest/server.go +305 -60
  491. package/bin/go/src/net/http/httptrace/trace.go +78 -27
  492. package/bin/go/src/net/http/httputil/reverseproxy.go +0 -30
  493. package/bin/go/src/net/http/internal/common.go +14 -0
  494. package/bin/go/src/net/http/internal/http2/api.go +161 -0
  495. package/bin/go/src/net/http/internal/http2/ascii.go +53 -0
  496. package/bin/go/src/net/http/internal/http2/ciphers.go +641 -0
  497. package/bin/go/src/net/http/internal/http2/client_conn_pool.go +285 -0
  498. package/bin/go/src/net/http/internal/http2/config.go +118 -0
  499. package/bin/go/src/net/http/internal/http2/databuffer.go +146 -0
  500. package/bin/go/src/net/http/internal/http2/errors.go +173 -0
  501. package/bin/go/src/net/http/internal/http2/flow.go +175 -0
  502. package/bin/go/src/net/http/internal/http2/frame.go +1905 -0
  503. package/bin/go/src/net/http/internal/http2/gotrack.go +181 -0
  504. package/bin/go/src/net/http/internal/http2/http2.go +403 -0
  505. package/bin/go/src/net/http/internal/http2/pipe.go +184 -0
  506. package/bin/go/src/net/http/internal/http2/server.go +3238 -0
  507. package/bin/go/src/net/http/internal/http2/transport.go +3267 -0
  508. package/bin/go/src/net/http/internal/http2/write.go +380 -0
  509. package/bin/go/src/net/http/internal/http2/writesched.go +289 -0
  510. package/bin/go/src/net/http/internal/http2/writesched_priority_rfc9218.go +224 -0
  511. package/bin/go/src/net/http/internal/http2/writesched_roundrobin.go +119 -0
  512. package/bin/go/src/net/http/internal/httpcommon/httpcommon.go +8 -0
  513. package/bin/go/src/net/http/internal/httpsfv/httpsfv.go +666 -0
  514. package/bin/go/src/net/http/internal/sniff.go +304 -0
  515. package/bin/go/src/net/http/omithttp2.go +28 -49
  516. package/bin/go/src/net/http/pprof/pprof.go +11 -17
  517. package/bin/go/src/net/http/request.go +30 -3
  518. package/bin/go/src/net/http/response.go +6 -2
  519. package/bin/go/src/net/http/server.go +366 -144
  520. package/bin/go/src/net/http/sniff.go +2 -289
  521. package/bin/go/src/net/http/transfer.go +64 -21
  522. package/bin/go/src/net/http/transport.go +288 -83
  523. package/bin/go/src/net/ip.go +4 -0
  524. package/bin/go/src/net/ipsock_plan9.go +4 -4
  525. package/bin/go/src/net/ipsock_posix.go +8 -2
  526. package/bin/go/src/net/lookup.go +10 -0
  527. package/bin/go/src/net/lookup_windows.go +1 -1
  528. package/bin/go/src/net/mail/message.go +8 -3
  529. package/bin/go/src/net/net.go +2 -0
  530. package/bin/go/src/net/netip/netip.go +68 -61
  531. package/bin/go/src/net/sock_posix.go +1 -4
  532. package/bin/go/src/net/textproto/reader.go +11 -3
  533. package/bin/go/src/net/udpsock_plan9.go +2 -7
  534. package/bin/go/src/net/unixsock.go +11 -3
  535. package/bin/go/src/net/url/url.go +33 -0
  536. package/bin/go/src/os/dir_darwin.go +7 -0
  537. package/bin/go/src/os/exec/exec.go +16 -2
  538. package/bin/go/src/os/exec.go +1 -0
  539. package/bin/go/src/os/file.go +8 -1
  540. package/bin/go/src/os/root_windows.go +5 -1
  541. package/bin/go/src/os/signal/doc.go +3 -2
  542. package/bin/go/src/os/signal/signal.go +18 -6
  543. package/bin/go/src/os/statat_unix.go +5 -1
  544. package/bin/go/src/path/filepath/path.go +4 -0
  545. package/bin/go/src/reflect/asm_s390x.s +0 -10
  546. package/bin/go/src/reflect/iter.go +13 -13
  547. package/bin/go/src/reflect/makefunc.go +2 -1
  548. package/bin/go/src/reflect/map.go +61 -18
  549. package/bin/go/src/reflect/type.go +63 -46
  550. package/bin/go/src/reflect/value.go +59 -16
  551. package/bin/go/src/regexp/exec.go +5 -5
  552. package/bin/go/src/regexp/regexp.go +382 -319
  553. package/bin/go/src/regexp/syntax/parse.go +19 -10
  554. package/bin/go/src/runtime/HACKING.md +19 -0
  555. package/bin/go/src/runtime/_mkmalloc/constants.go +6 -4
  556. package/bin/go/src/runtime/_mkmalloc/go.mod +1 -1
  557. package/bin/go/src/runtime/_mkmalloc/mkmalloc.go +405 -64
  558. package/bin/go/src/runtime/alg.go +21 -53
  559. package/bin/go/src/runtime/asm_386.s +11 -461
  560. package/bin/go/src/runtime/asm_amd64.s +30 -537
  561. package/bin/go/src/runtime/asm_arm.s +4 -39
  562. package/bin/go/src/runtime/asm_arm64.s +15 -428
  563. package/bin/go/src/runtime/asm_loong64.s +37 -47
  564. package/bin/go/src/runtime/asm_mips64x.s +15 -15
  565. package/bin/go/src/runtime/asm_mipsx.s +0 -15
  566. package/bin/go/src/runtime/asm_ppc64x.h +0 -16
  567. package/bin/go/src/runtime/asm_ppc64x.s +13 -59
  568. package/bin/go/src/runtime/asm_riscv64.s +30 -91
  569. package/bin/go/src/runtime/asm_s390x.s +49 -49
  570. package/bin/go/src/runtime/asm_wasm.s +0 -15
  571. package/bin/go/src/runtime/atomic_riscv64.s +1 -1
  572. package/bin/go/src/runtime/cgo/abi_riscv64.h +72 -0
  573. package/bin/go/src/runtime/cgo/asm_riscv64.s +7 -48
  574. package/bin/go/src/runtime/cgo/callbacks.go +0 -42
  575. package/bin/go/src/runtime/cgo/callbacks_unix.go +58 -0
  576. package/bin/go/src/runtime/cgo/cgo.go +6 -3
  577. package/bin/go/src/runtime/cgo/gcc_aix_ppc64.S +21 -9
  578. package/bin/go/src/runtime/cgo/gcc_android.c +0 -26
  579. package/bin/go/src/runtime/cgo/gcc_clearenv.c +1 -1
  580. package/bin/go/src/runtime/cgo/gcc_fatalf.c +14 -3
  581. package/bin/go/src/runtime/cgo/{gcc_libinit.c → gcc_libinit_unix.c} +18 -65
  582. package/bin/go/src/runtime/cgo/gcc_libinit_windows.c +23 -35
  583. package/bin/go/src/runtime/cgo/gcc_linux_ppc64x.S +16 -7
  584. package/bin/go/src/runtime/cgo/gcc_netbsd.c +8 -56
  585. package/bin/go/src/runtime/cgo/gcc_s390x.S +13 -4
  586. package/bin/go/src/runtime/cgo/gcc_sigaction.c +1 -1
  587. package/bin/go/src/runtime/cgo/gcc_unix.c +63 -0
  588. package/bin/go/src/runtime/cgo/gcc_util.c +0 -19
  589. package/bin/go/src/runtime/cgo/handle.go +3 -0
  590. package/bin/go/src/runtime/cgo/libcgo.h +7 -10
  591. package/bin/go/src/runtime/cgo/libcgo_unix.h +2 -10
  592. package/bin/go/src/runtime/cgo/pthread_unix.c +138 -0
  593. package/bin/go/src/runtime/cgo/sigaction.go +1 -1
  594. package/bin/go/src/runtime/cgo/windows.go +18 -1
  595. package/bin/go/src/runtime/cgo_ppc64x.go +1 -1
  596. package/bin/go/src/runtime/cgo_sigaction.go +1 -1
  597. package/bin/go/src/runtime/cgocall.go +10 -2
  598. package/bin/go/src/runtime/chan.go +2 -16
  599. package/bin/go/src/runtime/coro.go +2 -2
  600. package/bin/go/src/runtime/cpuflags.go +4 -3
  601. package/bin/go/src/runtime/debug/garbage.go +6 -6
  602. package/bin/go/src/runtime/debug/mod.go +1 -1
  603. package/bin/go/src/runtime/debug/stack.go +1 -1
  604. package/bin/go/src/runtime/debugcall.go +0 -3
  605. package/bin/go/src/runtime/error.go +6 -0
  606. package/bin/go/src/runtime/extern.go +5 -3
  607. package/bin/go/src/runtime/heapdump.go +1 -1
  608. package/bin/go/src/runtime/iface.go +20 -10
  609. package/bin/go/src/runtime/libinit.go +48 -0
  610. package/bin/go/src/runtime/lock_js.go +4 -2
  611. package/bin/go/src/runtime/lock_spinbit.go +13 -12
  612. package/bin/go/src/runtime/lock_wasip1.go +4 -2
  613. package/bin/go/src/runtime/lockrank.go +24 -21
  614. package/bin/go/src/runtime/lockrank_off.go +5 -2
  615. package/bin/go/src/runtime/lockrank_on.go +8 -7
  616. package/bin/go/src/runtime/malloc.go +10 -26
  617. package/bin/go/src/runtime/malloc_generated.go +819 -8628
  618. package/bin/go/src/runtime/malloc_stubs.go +187 -197
  619. package/bin/go/src/runtime/malloc_tables_generated.go +16 -882
  620. package/bin/go/src/runtime/map.go +4 -4
  621. package/bin/go/src/runtime/mbitmap.go +3 -1
  622. package/bin/go/src/runtime/mem.go +2 -6
  623. package/bin/go/src/runtime/mem_sbrk.go +4 -0
  624. package/bin/go/src/runtime/memclr_s390x.s +0 -5
  625. package/bin/go/src/runtime/memmove_s390x.s +0 -7
  626. package/bin/go/src/runtime/metrics/doc.go +5 -29
  627. package/bin/go/src/runtime/metrics/sample.go +3 -0
  628. package/bin/go/src/runtime/metrics.go +3 -2
  629. package/bin/go/src/runtime/mgc.go +41 -25
  630. package/bin/go/src/runtime/mgcmark.go +5 -0
  631. package/bin/go/src/runtime/mgcmark_greenteagc.go +1 -1
  632. package/bin/go/src/runtime/mgcpacer.go +1 -3
  633. package/bin/go/src/runtime/mgcscavenge.go +1 -1
  634. package/bin/go/src/runtime/mheap.go +1 -10
  635. package/bin/go/src/runtime/mklockrank.go +6 -1
  636. package/bin/go/src/runtime/mkpreempt.go +7 -0
  637. package/bin/go/src/runtime/mprof.go +12 -23
  638. package/bin/go/src/runtime/os2_aix.go +3 -3
  639. package/bin/go/src/runtime/os3_solaris.go +10 -0
  640. package/bin/go/src/runtime/os_aix.go +9 -2
  641. package/bin/go/src/runtime/os_darwin.go +3 -8
  642. package/bin/go/src/runtime/os_dragonfly.go +10 -0
  643. package/bin/go/src/runtime/os_js.go +10 -0
  644. package/bin/go/src/runtime/os_linux32.go +19 -6
  645. package/bin/go/src/runtime/os_netbsd.go +10 -0
  646. package/bin/go/src/runtime/os_openbsd.go +10 -0
  647. package/bin/go/src/runtime/os_plan9.go +10 -0
  648. package/bin/go/src/runtime/os_wasip1.go +10 -0
  649. package/bin/go/src/runtime/os_windows.go +45 -12
  650. package/bin/go/src/runtime/os_workdir_ios_arm64.go +98 -0
  651. package/bin/go/src/runtime/os_workdir_stub.go +9 -0
  652. package/bin/go/src/runtime/panic.go +93 -8
  653. package/bin/go/src/runtime/plugin.go +1 -3
  654. package/bin/go/src/runtime/pprof/pprof.go +11 -14
  655. package/bin/go/src/runtime/pprof/protomem.go +8 -15
  656. package/bin/go/src/runtime/preempt_loong64.s +8 -4
  657. package/bin/go/src/runtime/preempt_noxreg.go +2 -0
  658. package/bin/go/src/runtime/preempt_xreg.go +29 -2
  659. package/bin/go/src/runtime/print.go +9 -1
  660. package/bin/go/src/runtime/proc.go +68 -17
  661. package/bin/go/src/runtime/race_riscv64.s +40 -83
  662. package/bin/go/src/runtime/race_s390x.s +0 -16
  663. package/bin/go/src/runtime/rand.go +40 -12
  664. package/bin/go/src/runtime/{rt0_linux_ppc64le.s → rt0_linux_ppc64x.s} +12 -2
  665. package/bin/go/src/runtime/runtime-gdb.py +13 -2
  666. package/bin/go/src/runtime/runtime1.go +69 -18
  667. package/bin/go/src/runtime/runtime2.go +23 -22
  668. package/bin/go/src/runtime/secret/secret.go +7 -2
  669. package/bin/go/src/runtime/secret.go +27 -9
  670. package/bin/go/src/runtime/secret_nosecret.go +1 -1
  671. package/bin/go/src/runtime/sigaction.go +1 -1
  672. package/bin/go/src/runtime/signal_unix.go +5 -3
  673. package/bin/go/src/runtime/softfloat64.go +7 -2
  674. package/bin/go/src/runtime/string.go +4 -1
  675. package/bin/go/src/runtime/stubs.go +14 -4
  676. package/bin/go/src/runtime/stubs_amd64.go +4 -0
  677. package/bin/go/src/runtime/stubs_arm.go +10 -1
  678. package/bin/go/src/runtime/stubs_arm64.go +13 -0
  679. package/bin/go/src/runtime/stubs_loong64.go +18 -0
  680. package/bin/go/src/runtime/stubs_mips64x.go +9 -0
  681. package/bin/go/src/runtime/stubs_mipsx.go +11 -0
  682. package/bin/go/src/runtime/stubs_ppc64x.go +15 -0
  683. package/bin/go/src/runtime/stubs_riscv64.go +13 -0
  684. package/bin/go/src/runtime/stubs_s390x.go +18 -0
  685. package/bin/go/src/runtime/symtab.go +15 -16
  686. package/bin/go/src/runtime/synctest.go +2 -4
  687. package/bin/go/src/runtime/sys_aix_ppc64.s +9 -0
  688. package/bin/go/src/runtime/sys_darwin.go +2 -20
  689. package/bin/go/src/runtime/sys_darwin_amd64.s +1 -4
  690. package/bin/go/src/runtime/sys_darwin_arm64.s +3 -6
  691. package/bin/go/src/runtime/sys_freebsd_riscv64.s +2 -2
  692. package/bin/go/src/runtime/sys_ios_arm64.go +151 -0
  693. package/bin/go/src/runtime/sys_ios_arm64.s +78 -0
  694. package/bin/go/src/runtime/sys_linux_amd64.s +7 -1
  695. package/bin/go/src/runtime/sys_linux_loong64.s +8 -14
  696. package/bin/go/src/runtime/sys_linux_ppc64x.s +0 -12
  697. package/bin/go/src/runtime/sys_linux_riscv64.s +2 -2
  698. package/bin/go/src/runtime/sys_openbsd.go +1 -1
  699. package/bin/go/src/runtime/sys_openbsd_riscv64.s +16 -16
  700. package/bin/go/src/runtime/syscall_windows.go +2 -6
  701. package/bin/go/src/runtime/time.go +19 -57
  702. package/bin/go/src/runtime/trace/subscribe.go +0 -3
  703. package/bin/go/src/runtime/traceback.go +90 -13
  704. package/bin/go/src/runtime/traceregion.go +3 -3
  705. package/bin/go/src/runtime/tracestring.go +5 -0
  706. package/bin/go/src/runtime/type.go +85 -15
  707. package/bin/go/src/runtime/utf8.go +2 -2
  708. package/bin/go/src/simd/archsimd/_gen/go.mod +2 -2
  709. package/bin/go/src/simd/archsimd/_gen/go.sum +2 -2
  710. package/bin/go/src/simd/archsimd/_gen/main.go +106 -15
  711. package/bin/go/src/simd/archsimd/_gen/midway/comments.yaml +151 -0
  712. package/bin/go/src/simd/archsimd/_gen/midway/intersect_simd_ops.go +836 -0
  713. package/bin/go/src/simd/archsimd/_gen/sgutil/asbits.go +139 -0
  714. package/bin/go/src/simd/archsimd/_gen/sgutil/compare_natural.go +73 -0
  715. package/bin/go/src/simd/archsimd/_gen/sgutil/formatted_files.go +66 -0
  716. package/bin/go/src/simd/archsimd/_gen/sgutil/insert_ordered_map.go +159 -0
  717. package/bin/go/src/simd/archsimd/_gen/sgutil/merge_generic_ops.go +245 -0
  718. package/bin/go/src/simd/archsimd/_gen/simdgen/arch.go +173 -0
  719. package/bin/go/src/simd/archsimd/_gen/simdgen/arm64/emit.go +166 -0
  720. package/bin/go/src/simd/archsimd/_gen/simdgen/arm64/instruction.go +642 -0
  721. package/bin/go/src/simd/archsimd/_gen/simdgen/arm64/load.go +54 -0
  722. package/bin/go/src/simd/archsimd/_gen/simdgen/arm64/operands.go +406 -0
  723. package/bin/go/src/simd/archsimd/_gen/simdgen/etetest.sh +1 -1
  724. package/bin/go/src/simd/archsimd/_gen/simdgen/gen_simdGenericOps.go +19 -52
  725. package/bin/go/src/simd/archsimd/_gen/simdgen/gen_simdIntrinsics.go +162 -98
  726. package/bin/go/src/simd/archsimd/_gen/simdgen/gen_simdMachineOps.go +50 -19
  727. package/bin/go/src/simd/archsimd/_gen/simdgen/gen_simdTypes.go +198 -140
  728. package/bin/go/src/simd/archsimd/_gen/simdgen/gen_simdrules.go +278 -57
  729. package/bin/go/src/simd/archsimd/_gen/simdgen/gen_simdssa.go +133 -68
  730. package/bin/go/src/simd/archsimd/_gen/simdgen/gen_utility.go +163 -30
  731. package/bin/go/src/simd/archsimd/_gen/simdgen/go_amd64.yaml +1 -0
  732. package/bin/go/src/simd/archsimd/_gen/simdgen/go_arm64.yaml +1 -0
  733. package/bin/go/src/simd/archsimd/_gen/simdgen/godefs.go +113 -15
  734. package/bin/go/src/simd/archsimd/_gen/simdgen/main.go +62 -17
  735. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/AddSub/categories.yaml +12 -12
  736. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/AddSub/{go.yaml → go_amd64.yaml} +12 -12
  737. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/AddSub/go_arm64.yaml +91 -0
  738. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/BitwiseLogic/categories.yaml +11 -3
  739. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/BitwiseLogic/go_arm64.yaml +43 -0
  740. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Compares/go_arm64.yaml +81 -0
  741. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Converts/categories.yaml +11 -6
  742. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Converts/{go.yaml → go_amd64.yaml} +8 -8
  743. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Converts/go_arm64.yaml +358 -0
  744. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/FPonlyArith/categories.yaml +5 -5
  745. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/FPonlyArith/{go.yaml → go_amd64.yaml} +4 -4
  746. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/FPonlyArith/go_arm64.yaml +52 -0
  747. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/GaloisField/categories.yaml +29 -11
  748. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/GaloisField/{go.yaml → go_amd64.yaml} +1 -0
  749. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/GaloisField/go_arm64.yaml +10 -0
  750. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/IntOnlyArith/categories.yaml +2 -5
  751. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/IntOnlyArith/{go.yaml → go_amd64.yaml} +2 -3
  752. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/IntOnlyArith/go_arm64.yaml +35 -0
  753. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/MLOps/categories.yaml +5 -8
  754. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/MLOps/{go.yaml → go_amd64.yaml} +7 -5
  755. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/MLOps/go_arm64.yaml +31 -0
  756. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/MinMax/go_arm64.yaml +61 -0
  757. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Moves/categories.yaml +79 -23
  758. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Moves/{go.yaml → go_amd64.yaml} +213 -104
  759. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Moves/go_arm64.yaml +264 -0
  760. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Mul/categories.yaml +6 -2
  761. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Mul/{go.yaml → go_amd64.yaml} +3 -3
  762. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Mul/go_arm64.yaml +38 -0
  763. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/NegAbs/categories.yaml +7 -0
  764. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/NegAbs/go_arm64.yaml +36 -0
  765. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Others/categories.yaml +5 -1
  766. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Others/go_arm64.yaml +19 -0
  767. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Reduce/categories.yaml +16 -0
  768. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Reduce/go_arm64.yaml +71 -0
  769. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/ShiftRotate/categories.yaml +156 -41
  770. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/ShiftRotate/go_amd64.yaml +299 -0
  771. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/ShiftRotate/go_arm64.yaml +202 -0
  772. package/bin/go/src/simd/archsimd/_gen/simdgen/types.yaml +2 -0
  773. package/bin/go/src/simd/archsimd/_gen/simdgen/xed.go +44 -11
  774. package/bin/go/src/simd/archsimd/_gen/tmplgen/main.go +668 -123
  775. package/bin/go/src/simd/archsimd/_gen/unify/closure.go +1 -1
  776. package/bin/go/src/simd/archsimd/_gen/unify/env.go +35 -3
  777. package/bin/go/src/simd/archsimd/_gen/unify/yaml.go +4 -4
  778. package/bin/go/src/simd/archsimd/_gen/wasmgen/main.go +2064 -0
  779. package/bin/go/src/simd/archsimd/clmul_arm64.go +79 -0
  780. package/bin/go/src/simd/archsimd/clmul_emulated.go +103 -0
  781. package/bin/go/src/simd/archsimd/compare_gen_arm64.go +155 -0
  782. package/bin/go/src/simd/archsimd/cpu.go +1 -1
  783. package/bin/go/src/simd/archsimd/cpu_other.go +21 -0
  784. package/bin/go/src/simd/archsimd/doc.go +0 -2
  785. package/bin/go/src/simd/archsimd/dummy.s +1 -1
  786. package/bin/go/src/simd/archsimd/generate.go +1 -1
  787. package/bin/go/src/simd/archsimd/internal/test_helpers/checkslices.go +2 -2
  788. package/bin/go/src/simd/archsimd/maskmerge_gen_amd64.go +330 -0
  789. package/bin/go/src/simd/archsimd/maskmerge_gen_arm64.go +167 -0
  790. package/bin/go/src/simd/archsimd/ops_amd64.go +4210 -2475
  791. package/bin/go/src/simd/archsimd/ops_arm64.go +2186 -0
  792. package/bin/go/src/simd/archsimd/ops_emulated_amd64.go +205 -0
  793. package/bin/go/src/simd/archsimd/ops_emulated_wasm.go +212 -0
  794. package/bin/go/src/simd/archsimd/ops_internal_amd64.go +500 -56
  795. package/bin/go/src/simd/archsimd/ops_internal_arm64.go +234 -0
  796. package/bin/go/src/simd/archsimd/ops_wasm.go +1795 -0
  797. package/bin/go/src/simd/archsimd/other_gen_amd64.go +576 -72
  798. package/bin/go/src/simd/archsimd/other_gen_arm64.go +519 -0
  799. package/bin/go/src/simd/archsimd/shuffles_amd64.go +217 -76
  800. package/bin/go/src/simd/archsimd/slice_gen_amd64.go +594 -532
  801. package/bin/go/src/simd/archsimd/slice_gen_arm64.go +125 -0
  802. package/bin/go/src/simd/archsimd/slicepart_128.go +302 -0
  803. package/bin/go/src/simd/archsimd/slicepart_amd64.go +36 -235
  804. package/bin/go/src/simd/archsimd/slicepart_arm64.go +217 -0
  805. package/bin/go/src/simd/archsimd/slicepart_wasm.go +217 -0
  806. package/bin/go/src/simd/archsimd/string.go +1 -1
  807. package/bin/go/src/simd/archsimd/types_amd64.go +165 -341
  808. package/bin/go/src/simd/archsimd/types_arm64.go +224 -0
  809. package/bin/go/src/simd/archsimd/types_wasm.go +354 -0
  810. package/bin/go/src/simd/archsimd/unsafe_helpers.go +60 -0
  811. package/bin/go/src/simd/doc.go +91 -0
  812. package/bin/go/src/simd/dummy.s +7 -0
  813. package/bin/go/src/simd/internal/bridge/decls_amd64.go +4085 -0
  814. package/bin/go/src/simd/internal/bridge/decls_arm64.go +1369 -0
  815. package/bin/go/src/simd/internal/bridge/decls_wasm.go +1369 -0
  816. package/bin/go/src/simd/internal/bridge/import_hook.go +13 -0
  817. package/bin/go/src/simd/internal/bridge/simd_emulated.go +3275 -0
  818. package/bin/go/src/simd/internal/bridge/simd_types_emulated.go +95 -0
  819. package/bin/go/src/simd/internal/bridge/tofrom_128.go +65 -0
  820. package/bin/go/src/simd/internal/bridge/tofrom_amd64.go +123 -0
  821. package/bin/go/src/simd/internal/bridge/tofrom_emulated.go +63 -0
  822. package/bin/go/src/simd/midway_amd64.go +34 -0
  823. package/bin/go/src/simd/midway_arm64.go +22 -0
  824. package/bin/go/src/simd/midway_common.go +138 -0
  825. package/bin/go/src/simd/midway_wasm.go +13 -0
  826. package/bin/go/src/simd/simd_emulated.go +3275 -0
  827. package/bin/go/src/simd/simd_stubs.go +1041 -0
  828. package/bin/go/src/simd/simd_types.go +96 -0
  829. package/bin/go/src/simd/tofrom_amd64.go +374 -0
  830. package/bin/go/src/simd/tofrom_arm64.go +290 -0
  831. package/bin/go/src/simd/tofrom_wasm.go +290 -0
  832. package/bin/go/src/slices/slices.go +9 -7
  833. package/bin/go/src/strconv/isprint.go +81 -51
  834. package/bin/go/src/strings/builder.go +1 -1
  835. package/bin/go/src/strings/strings.go +44 -35
  836. package/bin/go/src/sync/atomic/doc.go +7 -0
  837. package/bin/go/src/sync/cond.go +4 -2
  838. package/bin/go/src/sync/pool.go +6 -15
  839. package/bin/go/src/sync/runtime2_lockrank.go +1 -2
  840. package/bin/go/src/syscall/exec_bsd.go +3 -3
  841. package/bin/go/src/syscall/exec_libc2.go +1 -1
  842. package/bin/go/src/syscall/exec_linux.go +7 -2
  843. package/bin/go/src/syscall/fs_js.go +9 -4
  844. package/bin/go/src/syscall/fs_wasip1.go +6 -0
  845. package/bin/go/src/syscall/js/js.go +2 -2
  846. package/bin/go/src/syscall/linkname_bsd.go +8 -0
  847. package/bin/go/src/syscall/linkname_libc.go +1 -1
  848. package/bin/go/src/syscall/linkname_openbsd.go +0 -2
  849. package/bin/go/src/syscall/mkall.sh +6 -17
  850. package/bin/go/src/syscall/syscall_aix.go +5 -0
  851. package/bin/go/src/syscall/syscall_linux_386.go +9 -0
  852. package/bin/go/src/syscall/syscall_linux_amd64.go +5 -0
  853. package/bin/go/src/syscall/syscall_linux_arm.go +4 -0
  854. package/bin/go/src/syscall/syscall_linux_arm64.go +3 -0
  855. package/bin/go/src/syscall/syscall_linux_loong64.go +3 -0
  856. package/bin/go/src/syscall/syscall_linux_mipsx.go +4 -0
  857. package/bin/go/src/syscall/syscall_linux_riscv64.go +3 -0
  858. package/bin/go/src/syscall/syscall_linux_s390x.go +5 -0
  859. package/bin/go/src/syscall/syscall_openbsd.go +77 -2
  860. package/bin/go/src/syscall/syscall_plan9.go +25 -0
  861. package/bin/go/src/syscall/syscall_solaris.go +11 -0
  862. package/bin/go/src/syscall/syscall_unix.go +19 -0
  863. package/bin/go/src/syscall/syscall_windows.go +1 -1
  864. package/bin/go/src/testing/synctest/synctest.go +21 -0
  865. package/bin/go/src/testing/testing.go +211 -52
  866. package/bin/go/src/text/template/parse/lex.go +6 -6
  867. package/bin/go/src/text/template/parse/node.go +21 -16
  868. package/bin/go/src/text/template/parse/parse.go +23 -6
  869. package/bin/go/src/text/template/template.go +5 -3
  870. package/bin/go/src/time/format.go +3 -0
  871. package/bin/go/src/time/sleep.go +0 -33
  872. package/bin/go/src/time/tick.go +3 -2
  873. package/bin/go/src/time/time.go +2 -2
  874. package/bin/go/src/time/tzdata/zzipdata.go +1 -1
  875. package/bin/go/src/time/zoneinfo.go +5 -4
  876. package/bin/go/src/time/zoneinfo_read.go +1 -1
  877. package/bin/go/src/unicode/tables.go +898 -417
  878. package/bin/go/src/uuid/uuid.go +273 -0
  879. package/bin/go/src/vendor/golang.org/x/crypto/chacha20poly1305/chacha20poly1305_amd64.go +3 -3
  880. package/bin/go/src/vendor/golang.org/x/crypto/chacha20poly1305/chacha20poly1305_amd64.s +2066 -6598
  881. package/bin/go/src/vendor/golang.org/x/crypto/hkdf/hkdf.go +100 -0
  882. package/bin/go/src/vendor/golang.org/x/net/dns/dnsmessage/message.go +5 -4
  883. package/bin/go/src/vendor/golang.org/x/net/http/httpproxy/proxy.go +4 -4
  884. package/bin/go/src/vendor/golang.org/x/net/http3/http3.go +46 -0
  885. package/bin/go/src/vendor/golang.org/x/net/idna/{idna10.0.0.go → idna.go} +133 -35
  886. package/bin/go/src/vendor/golang.org/x/net/idna/punycode.go +4 -1
  887. package/bin/go/src/vendor/golang.org/x/net/idna/tables15.0.0.go +1 -1
  888. package/bin/go/src/vendor/golang.org/x/net/idna/tables17.0.0.go +5302 -0
  889. package/bin/go/src/vendor/golang.org/x/net/internal/http3/body.go +231 -0
  890. package/bin/go/src/vendor/golang.org/x/net/internal/http3/conn.go +131 -0
  891. package/bin/go/src/vendor/golang.org/x/net/internal/http3/doc.go +10 -0
  892. package/bin/go/src/vendor/golang.org/x/net/internal/http3/errors.go +102 -0
  893. package/bin/go/src/vendor/golang.org/x/net/internal/http3/http3.go +95 -0
  894. package/bin/go/src/vendor/golang.org/x/net/internal/http3/qpack.go +356 -0
  895. package/bin/go/src/vendor/golang.org/x/net/internal/http3/qpack_decode.go +81 -0
  896. package/bin/go/src/vendor/golang.org/x/net/internal/http3/qpack_encode.go +61 -0
  897. package/bin/go/src/vendor/golang.org/x/net/internal/http3/qpack_static.go +142 -0
  898. package/bin/go/src/vendor/golang.org/x/net/internal/http3/quic.go +40 -0
  899. package/bin/go/src/vendor/golang.org/x/net/internal/http3/roundtrip.go +423 -0
  900. package/bin/go/src/vendor/golang.org/x/net/internal/http3/server.go +866 -0
  901. package/bin/go/src/vendor/golang.org/x/net/internal/http3/settings.go +66 -0
  902. package/bin/go/src/vendor/golang.org/x/net/internal/http3/stream.go +260 -0
  903. package/bin/go/src/vendor/golang.org/x/net/internal/http3/transport.go +333 -0
  904. package/bin/go/src/vendor/golang.org/x/net/internal/http3/varint.go +23 -0
  905. package/bin/go/src/vendor/golang.org/x/net/internal/httpcommon/ascii.go +53 -0
  906. package/bin/go/src/vendor/golang.org/x/net/internal/httpcommon/headermap.go +115 -0
  907. package/bin/go/src/vendor/golang.org/x/net/internal/httpcommon/request.go +475 -0
  908. package/bin/go/src/vendor/golang.org/x/net/internal/quic/quicwire/wire.go +150 -0
  909. package/bin/go/src/vendor/golang.org/x/net/quic/ack_delay.go +26 -0
  910. package/bin/go/src/vendor/golang.org/x/net/quic/acks.go +213 -0
  911. package/bin/go/src/vendor/golang.org/x/net/quic/atomic_bits.go +31 -0
  912. package/bin/go/src/vendor/golang.org/x/net/quic/config.go +158 -0
  913. package/bin/go/src/vendor/golang.org/x/net/quic/congestion_reno.go +306 -0
  914. package/bin/go/src/vendor/golang.org/x/net/quic/conn.go +434 -0
  915. package/bin/go/src/vendor/golang.org/x/net/quic/conn_close.go +340 -0
  916. package/bin/go/src/vendor/golang.org/x/net/quic/conn_flow.go +142 -0
  917. package/bin/go/src/vendor/golang.org/x/net/quic/conn_id.go +502 -0
  918. package/bin/go/src/vendor/golang.org/x/net/quic/conn_loss.go +85 -0
  919. package/bin/go/src/vendor/golang.org/x/net/quic/conn_recv.go +631 -0
  920. package/bin/go/src/vendor/golang.org/x/net/quic/conn_send.go +407 -0
  921. package/bin/go/src/vendor/golang.org/x/net/quic/conn_streams.go +483 -0
  922. package/bin/go/src/vendor/golang.org/x/net/quic/crypto_stream.go +157 -0
  923. package/bin/go/src/vendor/golang.org/x/net/quic/dgram.go +53 -0
  924. package/bin/go/src/vendor/golang.org/x/net/quic/doc.go +50 -0
  925. package/bin/go/src/vendor/golang.org/x/net/quic/endpoint.go +478 -0
  926. package/bin/go/src/vendor/golang.org/x/net/quic/errors.go +129 -0
  927. package/bin/go/src/vendor/golang.org/x/net/quic/frame_debug.go +730 -0
  928. package/bin/go/src/vendor/golang.org/x/net/quic/gate.go +86 -0
  929. package/bin/go/src/vendor/golang.org/x/net/quic/idle.go +168 -0
  930. package/bin/go/src/vendor/golang.org/x/net/quic/log.go +67 -0
  931. package/bin/go/src/vendor/golang.org/x/net/quic/loss.go +521 -0
  932. package/bin/go/src/{runtime/cgo/gcc_stack_windows.c → vendor/golang.org/x/net/quic/math.go} +7 -2
  933. package/bin/go/src/vendor/golang.org/x/net/quic/pacer.go +129 -0
  934. package/bin/go/src/vendor/golang.org/x/net/quic/packet.go +267 -0
  935. package/bin/go/src/vendor/golang.org/x/net/quic/packet_number.go +72 -0
  936. package/bin/go/src/vendor/golang.org/x/net/quic/packet_parser.go +519 -0
  937. package/bin/go/src/vendor/golang.org/x/net/quic/packet_protection.go +539 -0
  938. package/bin/go/src/vendor/golang.org/x/net/quic/packet_writer.go +566 -0
  939. package/bin/go/src/vendor/golang.org/x/net/quic/path.go +87 -0
  940. package/bin/go/src/vendor/golang.org/x/net/quic/ping.go +14 -0
  941. package/bin/go/src/vendor/golang.org/x/net/quic/pipe.go +173 -0
  942. package/bin/go/src/vendor/golang.org/x/net/quic/qlog.go +272 -0
  943. package/bin/go/src/vendor/golang.org/x/net/quic/queue.go +63 -0
  944. package/bin/go/src/vendor/golang.org/x/net/quic/quic.go +221 -0
  945. package/bin/go/src/vendor/golang.org/x/net/quic/race_disabled.go +10 -0
  946. package/bin/go/src/vendor/golang.org/x/net/quic/race_enabled.go +27 -0
  947. package/bin/go/src/vendor/golang.org/x/net/quic/rangeset.go +193 -0
  948. package/bin/go/src/vendor/golang.org/x/net/quic/retry.go +240 -0
  949. package/bin/go/src/vendor/golang.org/x/net/quic/rtt.go +71 -0
  950. package/bin/go/src/vendor/golang.org/x/net/quic/sent_packet.go +119 -0
  951. package/bin/go/src/vendor/golang.org/x/net/quic/sent_packet_list.go +93 -0
  952. package/bin/go/src/vendor/golang.org/x/net/quic/sent_val.go +103 -0
  953. package/bin/go/src/vendor/golang.org/x/net/quic/skip.go +62 -0
  954. package/bin/go/src/vendor/golang.org/x/net/quic/stateless_reset.go +59 -0
  955. package/bin/go/src/vendor/golang.org/x/net/quic/stream.go +1106 -0
  956. package/bin/go/src/vendor/golang.org/x/net/quic/stream_limits.go +138 -0
  957. package/bin/go/src/vendor/golang.org/x/net/quic/tls.go +123 -0
  958. package/bin/go/src/vendor/golang.org/x/net/quic/transport_params.go +283 -0
  959. package/bin/go/src/vendor/golang.org/x/net/quic/udp.go +28 -0
  960. package/bin/go/src/vendor/golang.org/x/net/quic/udp_darwin.go +45 -0
  961. package/bin/go/src/vendor/golang.org/x/net/quic/udp_linux.go +39 -0
  962. package/bin/go/src/vendor/golang.org/x/net/quic/udp_msg.go +245 -0
  963. package/bin/go/src/vendor/golang.org/x/net/quic/udp_other.go +62 -0
  964. package/bin/go/src/vendor/golang.org/x/net/quic/udp_packetconn.go +67 -0
  965. package/bin/go/src/vendor/golang.org/x/sys/cpu/asm_darwin_arm64_gc.s +12 -0
  966. package/bin/go/src/vendor/golang.org/x/sys/cpu/cpu.go +12 -7
  967. package/bin/go/src/vendor/golang.org/x/sys/cpu/cpu_arm64.go +3 -6
  968. package/bin/go/src/vendor/golang.org/x/sys/cpu/cpu_darwin_arm64.go +67 -0
  969. package/bin/go/src/vendor/golang.org/x/sys/cpu/cpu_darwin_arm64_other.go +31 -0
  970. package/bin/go/src/vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go +1 -0
  971. package/bin/go/src/vendor/golang.org/x/sys/cpu/cpu_linux_riscv64.go +2 -0
  972. package/bin/go/src/vendor/golang.org/x/sys/cpu/cpu_loong64.go +14 -2
  973. package/bin/go/src/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go +4 -2
  974. package/bin/go/src/vendor/golang.org/x/sys/cpu/cpu_riscv64.go +1 -0
  975. package/bin/go/src/vendor/golang.org/x/sys/cpu/cpu_windows.go +26 -0
  976. package/bin/go/src/vendor/golang.org/x/sys/cpu/cpu_windows_arm64.go +38 -0
  977. package/bin/go/src/vendor/golang.org/x/sys/cpu/cpu_x86.go +124 -50
  978. package/bin/go/src/vendor/golang.org/x/sys/cpu/syscall_darwin_arm64_gc.go +54 -0
  979. package/bin/go/src/vendor/golang.org/x/sys/cpu/zcpu_windows.go +48 -0
  980. package/bin/go/src/vendor/golang.org/x/text/secure/bidirule/bidirule.go +4 -0
  981. package/bin/go/src/vendor/golang.org/x/text/unicode/bidi/tables15.0.0.go +1 -1
  982. package/bin/go/src/vendor/golang.org/x/text/unicode/bidi/tables17.0.0.go +2135 -0
  983. package/bin/go/src/vendor/golang.org/x/text/unicode/norm/forminfo.go +18 -8
  984. package/bin/go/src/vendor/golang.org/x/text/unicode/norm/tables15.0.0.go +1410 -1410
  985. package/bin/go/src/vendor/golang.org/x/text/unicode/norm/{tables13.0.0.go → tables17.0.0.go} +3530 -3186
  986. package/bin/go/src/vendor/modules.txt +14 -8
  987. package/bin/ttsc-cache.exe +0 -0
  988. package/bin/ttsc.exe +0 -0
  989. package/bin/ttscserver.exe +0 -0
  990. package/package.json +1 -1
  991. package/bin/go/src/crypto/internal/fips140/nistec/p256_ordinv_noasm.go +0 -13
  992. package/bin/go/src/go/internal/scannerhooks/hooks.go +0 -11
  993. package/bin/go/src/hash/maphash/maphash_purego.go +0 -200
  994. package/bin/go/src/hash/maphash/maphash_runtime.go +0 -64
  995. package/bin/go/src/internal/goexperiment/exp_goroutineleakprofile_off.go +0 -8
  996. package/bin/go/src/internal/goexperiment/exp_goroutineleakprofile_on.go +0 -8
  997. package/bin/go/src/internal/strconv/atofeisel.go +0 -166
  998. package/bin/go/src/internal/strconv/ftoadbox.go +0 -349
  999. package/bin/go/src/internal/strconv/ftoafixed.go +0 -184
  1000. package/bin/go/src/internal/strconv/math.go +0 -179
  1001. package/bin/go/src/net/http/h2_bundle.go +0 -12371
  1002. package/bin/go/src/net/http/h2_error.go +0 -37
  1003. package/bin/go/src/runtime/cgo/gcc_darwin_amd64.c +0 -61
  1004. package/bin/go/src/runtime/cgo/gcc_darwin_arm64.c +0 -148
  1005. package/bin/go/src/runtime/cgo/gcc_dragonfly_amd64.c +0 -61
  1006. package/bin/go/src/runtime/cgo/gcc_freebsd.c +0 -72
  1007. package/bin/go/src/runtime/cgo/gcc_freebsd_amd64.c +0 -72
  1008. package/bin/go/src/runtime/cgo/gcc_linux.c +0 -67
  1009. package/bin/go/src/runtime/cgo/gcc_linux_amd64.c +0 -92
  1010. package/bin/go/src/runtime/cgo/gcc_linux_arm64.c +0 -88
  1011. package/bin/go/src/runtime/cgo/gcc_linux_s390x.c +0 -64
  1012. package/bin/go/src/runtime/cgo/gcc_openbsd.c +0 -62
  1013. package/bin/go/src/runtime/cgo/gcc_ppc64x.c +0 -68
  1014. package/bin/go/src/runtime/cgo/gcc_signal2_ios_arm64.c +0 -11
  1015. package/bin/go/src/runtime/cgo/gcc_signal_ios_arm64.c +0 -213
  1016. package/bin/go/src/runtime/cgo/gcc_signal_ios_nolldb.c +0 -10
  1017. package/bin/go/src/runtime/cgo/gcc_solaris_amd64.c +0 -83
  1018. package/bin/go/src/runtime/cgo/gcc_stack_darwin.c +0 -25
  1019. package/bin/go/src/runtime/cgo/gcc_stack_unix.c +0 -48
  1020. package/bin/go/src/runtime/cgo/gcc_windows_386.c +0 -55
  1021. package/bin/go/src/runtime/cgo/gcc_windows_amd64.c +0 -54
  1022. package/bin/go/src/runtime/cgo/gcc_windows_arm64.c +0 -42
  1023. package/bin/go/src/runtime/cgo/libcgo_windows.h +0 -6
  1024. package/bin/go/src/runtime/cgo/signal_ios_arm64.go +0 -10
  1025. package/bin/go/src/runtime/cgo/signal_ios_arm64.s +0 -56
  1026. package/bin/go/src/runtime/rt0_linux_ppc64.s +0 -28
  1027. package/bin/go/src/runtime/stubs_ppc64.go +0 -12
  1028. package/bin/go/src/simd/archsimd/_gen/simdgen/go.yaml +0 -1
  1029. package/bin/go/src/simd/archsimd/_gen/simdgen/ops/ShiftRotate/go.yaml +0 -172
  1030. package/bin/go/src/syscall/asm_openbsd_mips64.s +0 -129
  1031. package/bin/go/src/syscall/syscall_openbsd1.go +0 -12
  1032. package/bin/go/src/syscall/syscall_openbsd_libc.go +0 -84
  1033. package/bin/go/src/syscall/syscall_openbsd_mips64.go +0 -43
  1034. package/bin/go/src/syscall/zerrors_openbsd_mips64.go +0 -1682
  1035. package/bin/go/src/syscall/zsyscall_openbsd_mips64.go +0 -1289
  1036. package/bin/go/src/syscall/zsysnum_openbsd_mips64.go +0 -218
  1037. package/bin/go/src/syscall/ztypes_openbsd_mips64.go +0 -443
  1038. package/bin/go/src/vendor/golang.org/x/net/idna/go118.go +0 -13
  1039. package/bin/go/src/vendor/golang.org/x/net/idna/idna9.0.0.go +0 -717
  1040. package/bin/go/src/vendor/golang.org/x/net/idna/pre_go118.go +0 -11
  1041. package/bin/go/src/vendor/golang.org/x/net/idna/tables10.0.0.go +0 -4559
  1042. package/bin/go/src/vendor/golang.org/x/net/idna/tables11.0.0.go +0 -4653
  1043. package/bin/go/src/vendor/golang.org/x/net/idna/tables12.0.0.go +0 -4733
  1044. package/bin/go/src/vendor/golang.org/x/net/idna/tables13.0.0.go +0 -4959
  1045. package/bin/go/src/vendor/golang.org/x/net/idna/tables9.0.0.go +0 -4486
  1046. package/bin/go/src/vendor/golang.org/x/net/idna/trie12.0.0.go +0 -30
  1047. package/bin/go/src/vendor/golang.org/x/net/idna/trie13.0.0.go +0 -30
  1048. package/bin/go/src/vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go +0 -11
  1049. package/bin/go/src/vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go +0 -14
  1050. package/bin/go/src/vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go +0 -1815
  1051. package/bin/go/src/vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go +0 -1887
  1052. package/bin/go/src/vendor/golang.org/x/text/unicode/bidi/tables12.0.0.go +0 -1923
  1053. package/bin/go/src/vendor/golang.org/x/text/unicode/bidi/tables13.0.0.go +0 -1955
  1054. package/bin/go/src/vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go +0 -1781
  1055. package/bin/go/src/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go +0 -7657
  1056. package/bin/go/src/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go +0 -7693
  1057. package/bin/go/src/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go +0 -7710
  1058. package/bin/go/src/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go +0 -7637
  1059. /package/bin/go/src/simd/archsimd/_gen/simdgen/ops/BitwiseLogic/{go.yaml → go_amd64.yaml} +0 -0
  1060. /package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Compares/{go.yaml → go_amd64.yaml} +0 -0
  1061. /package/bin/go/src/simd/archsimd/_gen/simdgen/ops/MinMax/{go.yaml → go_amd64.yaml} +0 -0
  1062. /package/bin/go/src/simd/archsimd/_gen/simdgen/ops/Others/{go.yaml → go_amd64.yaml} +0 -0
@@ -0,0 +1,3238 @@
1
+ // Copyright 2014 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // TODO: turn off the serve goroutine when idle, so
6
+ // an idle conn only has the readFrames goroutine active. (which could
7
+ // also be optimized probably to pin less memory in crypto/tls). This
8
+ // would involve tracking when the serve goroutine is active (atomic
9
+ // int32 read/CAS probably?) and starting it up when frames arrive,
10
+ // and shutting it down when all handlers exit. the occasional PING
11
+ // packets could use time.AfterFunc to call sc.wakeStartServeLoop()
12
+ // (which is a no-op if already running) and then queue the PING write
13
+ // as normal. The serve loop would then exit in most cases (if no
14
+ // Handlers running) and not be woken up again until the PING packet
15
+ // returns.
16
+
17
+ // TODO (maybe): add a mechanism for Handlers to going into
18
+ // half-closed-local mode (rw.(io.Closer) test?) but not exit their
19
+ // handler, and continue to be able to read from the
20
+ // Request.Body. This would be a somewhat semantic change from HTTP/1
21
+ // (or at least what we expose in net/http), so I'd probably want to
22
+ // add it there too. For now, this package says that returning from
23
+ // the Handler ServeHTTP function means you're both done reading and
24
+ // done writing, without a way to stop just one or the other.
25
+
26
+ package http2
27
+
28
+ import (
29
+ "bufio"
30
+ "bytes"
31
+ "context"
32
+ "crypto/rand"
33
+ "crypto/tls"
34
+ "errors"
35
+ "fmt"
36
+ "io"
37
+ "log"
38
+ "math"
39
+ "net"
40
+ "net/http/internal"
41
+ "net/http/internal/httpcommon"
42
+ "net/textproto"
43
+ "net/url"
44
+ "os"
45
+ "reflect"
46
+ "runtime"
47
+ "slices"
48
+ "strconv"
49
+ "strings"
50
+ "sync"
51
+ "time"
52
+
53
+ "golang.org/x/net/http/httpguts"
54
+ "golang.org/x/net/http2/hpack"
55
+ )
56
+
57
+ const (
58
+ prefaceTimeout = 10 * time.Second
59
+ firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
60
+ handlerChunkWriteSize = 4 << 10
61
+ defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
62
+
63
+ // maxQueuedControlFrames is the maximum number of control frames like
64
+ // SETTINGS, PING and RST_STREAM that will be queued for writing before
65
+ // the connection is closed to prevent memory exhaustion attacks.
66
+ maxQueuedControlFrames = 10000
67
+ )
68
+
69
+ var (
70
+ errClientDisconnected = errors.New("client disconnected")
71
+ errClosedBody = errors.New("body closed by handler")
72
+ errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
73
+ errStreamClosed = errors.New("http2: stream closed")
74
+ )
75
+
76
+ var responseWriterStatePool = sync.Pool{
77
+ New: func() any {
78
+ rws := &responseWriterState{}
79
+ rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
80
+ return rws
81
+ },
82
+ }
83
+
84
+ // Test hooks.
85
+ var (
86
+ testHookOnConn func()
87
+ testHookOnPanicMu *sync.Mutex // nil except in tests
88
+ testHookOnPanic func(sc *serverConn, panicVal any) (rePanic bool)
89
+ )
90
+
91
+ // Server is an HTTP/2 server.
92
+ type Server struct {
93
+ mu sync.Mutex
94
+ activeConns map[*serverConn]struct{}
95
+
96
+ // Pool of error channels. This is per-Server rather than global
97
+ // because channels can't be reused across synctest bubbles.
98
+ errChanPool sync.Pool
99
+ }
100
+
101
+ func (s *Server) registerConn(sc *serverConn) {
102
+ if s == nil {
103
+ return // if the Server was used without calling ConfigureServer
104
+ }
105
+ s.mu.Lock()
106
+ s.activeConns[sc] = struct{}{}
107
+ s.mu.Unlock()
108
+ }
109
+
110
+ func (s *Server) unregisterConn(sc *serverConn) {
111
+ if s == nil {
112
+ return // if the Server was used without calling ConfigureServer
113
+ }
114
+ s.mu.Lock()
115
+ delete(s.activeConns, sc)
116
+ s.mu.Unlock()
117
+ }
118
+
119
+ func (s *Server) startGracefulShutdown() {
120
+ if s == nil {
121
+ return // if the Server was used without calling ConfigureServer
122
+ }
123
+ s.mu.Lock()
124
+ for sc := range s.activeConns {
125
+ sc.startGracefulShutdown()
126
+ }
127
+ s.mu.Unlock()
128
+ }
129
+
130
+ // Global error channel pool used for uninitialized Servers.
131
+ // We use a per-Server pool when possible to avoid using channels across synctest bubbles.
132
+ var errChanPool = sync.Pool{
133
+ New: func() any { return make(chan error, 1) },
134
+ }
135
+
136
+ func (s *Server) getErrChan() chan error {
137
+ if s == nil {
138
+ return errChanPool.Get().(chan error) // Server used without calling ConfigureServer
139
+ }
140
+ return s.errChanPool.Get().(chan error)
141
+ }
142
+
143
+ func (s *Server) putErrChan(ch chan error) {
144
+ if s == nil {
145
+ errChanPool.Put(ch) // Server used without calling ConfigureServer
146
+ return
147
+ }
148
+ s.errChanPool.Put(ch)
149
+ }
150
+
151
+ func (s *Server) Configure(conf ServerConfig, tcfg *tls.Config) error {
152
+ s.activeConns = make(map[*serverConn]struct{})
153
+ s.errChanPool = sync.Pool{New: func() any { return make(chan error, 1) }}
154
+
155
+ if tcfg.CipherSuites != nil && tcfg.MinVersion < tls.VersionTLS13 {
156
+ // If they already provided a TLS 1.0–1.2 CipherSuite list, return an
157
+ // error if it is missing ECDHE_RSA_WITH_AES_128_GCM_SHA256 or
158
+ // ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.
159
+ haveRequired := false
160
+ for _, cs := range tcfg.CipherSuites {
161
+ switch cs {
162
+ case tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
163
+ // Alternative MTI cipher to not discourage ECDSA-only servers.
164
+ // See http://golang.org/cl/30721 for further information.
165
+ tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
166
+ haveRequired = true
167
+ }
168
+ }
169
+ if !haveRequired {
170
+ return fmt.Errorf("http2: TLSConfig.CipherSuites is missing an HTTP/2-required AES_128_GCM_SHA256 cipher (need at least one of TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 or TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)")
171
+ }
172
+ }
173
+
174
+ // Note: not setting MinVersion to tls.VersionTLS12,
175
+ // as we don't want to interfere with HTTP/1.1 traffic
176
+ // on the user's server. We enforce TLS 1.2 later once
177
+ // we accept a connection. Ideally this should be done
178
+ // during next-proto selection, but using TLS <1.2 with
179
+ // HTTP/2 is still the client's bug.
180
+
181
+ return nil
182
+ }
183
+
184
+ func (s *Server) GracefulShutdown() {
185
+ s.startGracefulShutdown()
186
+ }
187
+
188
+ // ServeConnOpts are options for the Server.ServeConn method.
189
+ type ServeConnOpts struct {
190
+ // Context is the base context to use.
191
+ // If nil, context.Background is used.
192
+ Context context.Context
193
+
194
+ // BaseConfig optionally sets the base configuration
195
+ // for values. If nil, defaults are used.
196
+ BaseConfig ServerConfig
197
+
198
+ // Handler specifies which handler to use for processing
199
+ // requests. If nil, BaseConfig.Handler is used. If BaseConfig
200
+ // or BaseConfig.Handler is nil, http.DefaultServeMux is used.
201
+ Handler Handler
202
+
203
+ // Settings is the decoded contents of the HTTP2-Settings header
204
+ // in an h2c upgrade request.
205
+ Settings []byte
206
+
207
+ UpgradeRequest *ServerRequest
208
+
209
+ // SawClientPreface is set if the HTTP/2 connection preface
210
+ // has already been read from the connection.
211
+ SawClientPreface bool
212
+ }
213
+
214
+ func (o *ServeConnOpts) context() context.Context {
215
+ if o != nil && o.Context != nil {
216
+ return o.Context
217
+ }
218
+ return context.Background()
219
+ }
220
+
221
+ // ServeConn serves HTTP/2 requests on the provided connection and
222
+ // blocks until the connection is no longer readable.
223
+ //
224
+ // ServeConn starts speaking HTTP/2 assuming that c has not had any
225
+ // reads or writes. It writes its initial settings frame and expects
226
+ // to be able to read the preface and settings frame from the
227
+ // client. If c has a ConnectionState method like a *tls.Conn, the
228
+ // ConnectionState is used to verify the TLS ciphersuite and to set
229
+ // the Request.TLS field in Handlers.
230
+ //
231
+ // ServeConn does not support h2c by itself. Any h2c support must be
232
+ // implemented in terms of providing a suitably-behaving net.Conn.
233
+ //
234
+ // The opts parameter is optional. If nil, default values are used.
235
+ func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) {
236
+ if opts == nil {
237
+ opts = &ServeConnOpts{}
238
+ }
239
+
240
+ var newf func(*serverConn)
241
+ if inTests {
242
+ // Fetch NewConnContextKey if set, leave newf as nil otherwise.
243
+ newf, _ = opts.Context.Value(NewConnContextKey).(func(*serverConn))
244
+ }
245
+
246
+ s.serveConn(c, opts, newf)
247
+ }
248
+
249
+ type contextKey string
250
+
251
+ var (
252
+ NewConnContextKey = new("NewConnContextKey")
253
+ ConnectionStateContextKey = new("ConnectionStateContextKey")
254
+ )
255
+
256
+ func (s *Server) serveConn(c net.Conn, opts *ServeConnOpts, newf func(*serverConn)) {
257
+ baseCtx, cancel := serverConnBaseContext(c, opts)
258
+ defer cancel()
259
+
260
+ conf := configFromServer(opts.BaseConfig)
261
+ sc := &serverConn{
262
+ srv: s,
263
+ hs: opts.BaseConfig,
264
+ conn: c,
265
+ baseCtx: baseCtx,
266
+ remoteAddrStr: c.RemoteAddr().String(),
267
+ bw: newBufferedWriter(c, conf.WriteByteTimeout),
268
+ handler: opts.Handler,
269
+ streams: make(map[uint32]*stream),
270
+ readFrameCh: make(chan readFrameResult),
271
+ wantWriteFrameCh: make(chan FrameWriteRequest, 8),
272
+ serveMsgCh: make(chan any, 8),
273
+ wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync
274
+ bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way
275
+ doneServing: make(chan struct{}),
276
+ clientMaxStreams: math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value"
277
+ advMaxStreams: uint32(conf.MaxConcurrentStreams),
278
+ initialStreamRecvWindowSize: int32(conf.MaxReceiveBufferPerStream),
279
+ maxFrameSize: initialMaxFrameSize,
280
+ pingTimeout: conf.PingTimeout,
281
+ countErrorFunc: conf.CountError,
282
+ serveG: newGoroutineLock(),
283
+ pushEnabled: true,
284
+ sawClientPreface: opts.SawClientPreface,
285
+ }
286
+ if newf != nil {
287
+ newf(sc)
288
+ }
289
+
290
+ s.registerConn(sc)
291
+ defer s.unregisterConn(sc)
292
+
293
+ switch {
294
+ case sc.hs.DisableClientPriority():
295
+ sc.writeSched = newRoundRobinWriteScheduler()
296
+ default:
297
+ sc.writeSched = newPriorityWriteSchedulerRFC9218()
298
+ }
299
+
300
+ // These start at the RFC-specified defaults. If there is a higher
301
+ // configured value for inflow, that will be updated when we send a
302
+ // WINDOW_UPDATE shortly after sending SETTINGS.
303
+ sc.flow.init()
304
+ sc.inflow.init(initialWindowSize)
305
+ sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
306
+ sc.hpackEncoder.SetMaxDynamicTableSizeLimit(uint32(conf.MaxEncoderHeaderTableSize))
307
+
308
+ fr := NewFramer(sc.bw, c)
309
+ if conf.CountError != nil {
310
+ fr.countError = conf.CountError
311
+ }
312
+ fr.ReadMetaHeaders = hpack.NewDecoder(uint32(conf.MaxDecoderHeaderTableSize), nil)
313
+ fr.MaxHeaderListSize = sc.maxHeaderListSize()
314
+ fr.MaxHeaderValueCount = sc.hs.MaxHeaderValueCount()
315
+ fr.SetMaxReadFrameSize(uint32(conf.MaxReadFrameSize))
316
+ sc.framer = fr
317
+
318
+ if tc, ok := c.(connectionStater); ok {
319
+ sc.tlsState = new(tls.ConnectionState)
320
+ *sc.tlsState = tc.ConnectionState()
321
+
322
+ // Optionally override the ConnectionState in tests.
323
+ if inTests {
324
+ f, ok := opts.Context.Value(ConnectionStateContextKey).(func() tls.ConnectionState)
325
+ if ok {
326
+ *sc.tlsState = f()
327
+ }
328
+ }
329
+
330
+ // 9.2 Use of TLS Features
331
+ // An implementation of HTTP/2 over TLS MUST use TLS
332
+ // 1.2 or higher with the restrictions on feature set
333
+ // and cipher suite described in this section. Due to
334
+ // implementation limitations, it might not be
335
+ // possible to fail TLS negotiation. An endpoint MUST
336
+ // immediately terminate an HTTP/2 connection that
337
+ // does not meet the TLS requirements described in
338
+ // this section with a connection error (Section
339
+ // 5.4.1) of type INADEQUATE_SECURITY.
340
+ if sc.tlsState.Version < tls.VersionTLS12 {
341
+ sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
342
+ return
343
+ }
344
+
345
+ if sc.tlsState.ServerName == "" {
346
+ // Client must use SNI, but we don't enforce that anymore,
347
+ // since it was causing problems when connecting to bare IP
348
+ // addresses during development.
349
+ //
350
+ // TODO: optionally enforce? Or enforce at the time we receive
351
+ // a new request, and verify the ServerName matches the :authority?
352
+ // But that precludes proxy situations, perhaps.
353
+ //
354
+ // So for now, do nothing here again.
355
+ }
356
+
357
+ if !conf.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
358
+ // "Endpoints MAY choose to generate a connection error
359
+ // (Section 5.4.1) of type INADEQUATE_SECURITY if one of
360
+ // the prohibited cipher suites are negotiated."
361
+ //
362
+ // We choose that. In my opinion, the spec is weak
363
+ // here. It also says both parties must support at least
364
+ // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
365
+ // excuses here. If we really must, we could allow an
366
+ // "AllowInsecureWeakCiphers" option on the server later.
367
+ // Let's see how it plays out first.
368
+ sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
369
+ return
370
+ }
371
+ }
372
+
373
+ if opts.Settings != nil {
374
+ fr := &SettingsFrame{
375
+ FrameHeader: FrameHeader{valid: true},
376
+ p: opts.Settings,
377
+ }
378
+ if err := fr.ForeachSetting(sc.processSetting); err != nil {
379
+ sc.rejectConn(ErrCodeProtocol, "invalid settings")
380
+ return
381
+ }
382
+ opts.Settings = nil
383
+ }
384
+
385
+ if opts.UpgradeRequest != nil {
386
+ sc.upgradeRequest(opts.UpgradeRequest)
387
+ opts.UpgradeRequest = nil
388
+ }
389
+
390
+ sc.serve(conf)
391
+ }
392
+
393
+ func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx context.Context, cancel func()) {
394
+ return context.WithCancel(opts.context())
395
+ }
396
+
397
+ func (sc *serverConn) rejectConn(err ErrCode, debug string) {
398
+ sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
399
+ // ignoring errors. hanging up anyway.
400
+ sc.framer.WriteGoAway(0, err, []byte(debug))
401
+ sc.bw.Flush()
402
+ sc.conn.Close()
403
+ }
404
+
405
+ type serverConn struct {
406
+ // Immutable:
407
+ srv *Server
408
+ hs ServerConfig
409
+ conn net.Conn
410
+ bw *bufferedWriter // writing to conn
411
+ handler Handler
412
+ baseCtx context.Context
413
+ framer *Framer
414
+ doneServing chan struct{} // closed when serverConn.serve ends
415
+ readFrameCh chan readFrameResult // written by serverConn.readFrames
416
+ wantWriteFrameCh chan FrameWriteRequest // from handlers -> serve
417
+ wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes
418
+ bodyReadCh chan bodyReadMsg // from handlers -> serve
419
+ serveMsgCh chan any // misc messages & code to send to / run on the serve loop
420
+ flow connOutflow // conn-wide (not stream-specific) outbound flow control
421
+ inflow inflow // conn-wide inbound flow control
422
+ tlsState *tls.ConnectionState // shared by all handlers, like net/http
423
+ remoteAddrStr string
424
+ writeSched WriteScheduler
425
+ countErrorFunc func(errType string)
426
+
427
+ // Everything following is owned by the serve loop; use serveG.check():
428
+ serveG goroutineLock // used to verify funcs are on serve()
429
+ pushEnabled bool
430
+ sawClientPreface bool // preface has already been read, used in h2c upgrade
431
+ sawFirstSettings bool // got the initial SETTINGS frame after the preface
432
+ needToSendSettingsAck bool
433
+ unackedSettings int // how many SETTINGS have we sent without ACKs?
434
+ pendingEncoderTableSize bool // peer changed SETTINGS_HEADER_TABLE_SIZE; apply to hpackEncoder before the next frame write
435
+ encoderTableSizeMin uint32 // smallest SETTINGS_HEADER_TABLE_SIZE since the last apply
436
+ encoderTableSize uint32 // latest SETTINGS_HEADER_TABLE_SIZE
437
+ queuedControlFrames int // control frames in the writeSched queue
438
+ clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
439
+ advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
440
+ curClientStreams uint32 // number of open streams initiated by the client
441
+ curPushedStreams uint32 // number of open streams initiated by server push
442
+ curHandlers uint32 // number of running handler goroutines
443
+ maxClientStreamID uint32 // max ever seen from client (odd), or 0 if there have been no client requests
444
+ maxPushPromiseID uint32 // ID of the last push promise (even), or 0 if there have been no pushes
445
+ streams map[uint32]*stream
446
+ unstartedHandlers []unstartedHandler
447
+ initialStreamRecvWindowSize int32
448
+ maxFrameSize int32
449
+ peerMaxHeaderListSize uint32 // zero means unknown (default)
450
+ canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
451
+ canonHeaderKeysSize int // canonHeader keys size in bytes
452
+ writingFrame bool // started writing a frame (on serve goroutine or separate)
453
+ writingFrameAsync bool // started a frame on its own goroutine but haven't heard back on wroteFrameCh
454
+ needsFrameFlush bool // last frame write wasn't a flush
455
+ inGoAway bool // we've started to or sent GOAWAY
456
+ inFrameScheduleLoop bool // whether we're in the scheduleFrameWrite loop
457
+ needToSendGoAway bool // we need to schedule a GOAWAY frame write
458
+ pingSent bool
459
+ sentPingData [8]byte
460
+ goAwayCode ErrCode
461
+ shutdownTimer *time.Timer // nil until used
462
+ idleTimer *time.Timer // nil if unused
463
+ readIdleTimeout time.Duration
464
+ pingTimeout time.Duration
465
+ readIdleTimer *time.Timer // nil if unused
466
+
467
+ // Owned by the writeFrameAsync goroutine:
468
+ headerWriteBuf bytes.Buffer
469
+ hpackEncoder *hpack.Encoder
470
+
471
+ // Used by startGracefulShutdown.
472
+ shutdownOnce sync.Once
473
+
474
+ // Used for RFC 9218 prioritization.
475
+ hasIntermediary bool // connection is done via an intermediary / proxy
476
+ priorityAware bool // the client has sent priority signal, meaning that it is aware of it.
477
+ }
478
+
479
+ func (sc *serverConn) writeSchedIgnoresRFC7540() bool {
480
+ switch sc.writeSched.(type) {
481
+ case *priorityWriteSchedulerRFC9218:
482
+ return true
483
+ case *roundRobinWriteScheduler:
484
+ return true
485
+ default:
486
+ return false
487
+ }
488
+ }
489
+
490
+ const DefaultMaxHeaderBytes = 1 << 20 // keep this in sync with net/http
491
+
492
+ func (sc *serverConn) maxHeaderListSize() uint32 {
493
+ n := sc.hs.MaxHeaderBytes()
494
+ if n <= 0 {
495
+ n = DefaultMaxHeaderBytes
496
+ }
497
+ return uint32(adjustHTTP1MaxHeaderSize(int64(n)))
498
+ }
499
+
500
+ func (sc *serverConn) curOpenStreams() uint32 {
501
+ sc.serveG.check()
502
+ return sc.curClientStreams + sc.curPushedStreams
503
+ }
504
+
505
+ // stream represents a stream. This is the minimal metadata needed by
506
+ // the serve goroutine. Most of the actual stream state is owned by
507
+ // the http.Handler's goroutine in the responseWriter. Because the
508
+ // responseWriter's responseWriterState is recycled at the end of a
509
+ // handler, this struct intentionally has no pointer to the
510
+ // *responseWriter{,State} itself, as the Handler ending nils out the
511
+ // responseWriter's state field.
512
+ type stream struct {
513
+ // immutable:
514
+ sc *serverConn
515
+ id uint32
516
+ body *pipe // non-nil if expecting DATA frames
517
+ reqBody *requestBody
518
+ cw closeWaiter // closed wait stream transitions to closed state
519
+ ctx context.Context
520
+ cancelCtx func()
521
+
522
+ // owned by serverConn's serve loop:
523
+ bodyBytes int64 // body bytes seen so far
524
+ declBodyBytes int64 // or -1 if undeclared
525
+ flow outflow // limits writing from Handler to client
526
+ inflow inflow // what the client is allowed to POST/etc to us
527
+ state streamState
528
+ resetQueued bool // RST_STREAM queued for write; set by sc.resetStream
529
+ gotTrailerHeader bool // HEADER frame for trailers was seen
530
+ wroteHeaders bool // whether we wrote headers (not status 100)
531
+ readDeadline *time.Timer // nil if unused
532
+ writeDeadline *time.Timer // nil if unused
533
+ closeErr error // set before cw is closed
534
+
535
+ trailer Header // accumulated trailers
536
+ reqTrailer Header // handler's Request.Trailer
537
+ }
538
+
539
+ func (sc *serverConn) Framer() *Framer { return sc.framer }
540
+ func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
541
+ func (sc *serverConn) Flush() error { return sc.bw.Flush() }
542
+ func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
543
+ return sc.hpackEncoder, &sc.headerWriteBuf
544
+ }
545
+
546
+ func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
547
+ sc.serveG.check()
548
+ // http://tools.ietf.org/html/rfc7540#section-5.1
549
+ if st, ok := sc.streams[streamID]; ok {
550
+ return st.state, st
551
+ }
552
+ // "The first use of a new stream identifier implicitly closes all
553
+ // streams in the "idle" state that might have been initiated by
554
+ // that peer with a lower-valued stream identifier. For example, if
555
+ // a client sends a HEADERS frame on stream 7 without ever sending a
556
+ // frame on stream 5, then stream 5 transitions to the "closed"
557
+ // state when the first frame for stream 7 is sent or received."
558
+ if streamID%2 == 1 {
559
+ if streamID <= sc.maxClientStreamID {
560
+ return stateClosed, nil
561
+ }
562
+ } else {
563
+ if streamID <= sc.maxPushPromiseID {
564
+ return stateClosed, nil
565
+ }
566
+ }
567
+ return stateIdle, nil
568
+ }
569
+
570
+ // setConnState calls the net/http ConnState hook for this connection, if configured.
571
+ // Note that the net/http package does StateNew and StateClosed for us.
572
+ // There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
573
+ func (sc *serverConn) setConnState(state ConnState) {
574
+ sc.hs.ConnState(sc.conn, state)
575
+ }
576
+
577
+ func (sc *serverConn) vlogf(format string, args ...any) {
578
+ if VerboseLogs {
579
+ sc.logf(format, args...)
580
+ }
581
+ }
582
+
583
+ func (sc *serverConn) logf(format string, args ...any) {
584
+ if lg := sc.hs.ErrorLog(); lg != nil {
585
+ lg.Printf(format, args...)
586
+ } else {
587
+ log.Printf(format, args...)
588
+ }
589
+ }
590
+
591
+ // errno returns v's underlying uintptr, else 0.
592
+ //
593
+ // TODO: remove this helper function once http2 can use build
594
+ // tags. See comment in isClosedConnError.
595
+ func errno(v error) uintptr {
596
+ if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
597
+ return uintptr(rv.Uint())
598
+ }
599
+ return 0
600
+ }
601
+
602
+ // isClosedConnError reports whether err is an error from use of a closed
603
+ // network connection.
604
+ func isClosedConnError(err error) bool {
605
+ if err == nil {
606
+ return false
607
+ }
608
+
609
+ if errors.Is(err, net.ErrClosed) {
610
+ return true
611
+ }
612
+
613
+ // TODO(bradfitz): x/tools/cmd/bundle doesn't really support
614
+ // build tags, so I can't make an http2_windows.go file with
615
+ // Windows-specific stuff. Fix that and move this, once we
616
+ // have a way to bundle this into std's net/http somehow.
617
+ if runtime.GOOS == "windows" {
618
+ if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
619
+ if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
620
+ const WSAECONNABORTED = 10053
621
+ const WSAECONNRESET = 10054
622
+ if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
623
+ return true
624
+ }
625
+ }
626
+ }
627
+ }
628
+ return false
629
+ }
630
+
631
+ func (sc *serverConn) condlogf(err error, format string, args ...any) {
632
+ if err == nil {
633
+ return
634
+ }
635
+ if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) || err == errPrefaceTimeout {
636
+ // Boring, expected errors.
637
+ sc.vlogf(format, args...)
638
+ } else {
639
+ sc.logf(format, args...)
640
+ }
641
+ }
642
+
643
+ // maxCachedCanonicalHeadersKeysSize is an arbitrarily-chosen limit on the size
644
+ // of the entries in the canonHeader cache.
645
+ // This should be larger than the size of unique, uncommon header keys likely to
646
+ // be sent by the peer, while not so high as to permit unreasonable memory usage
647
+ // if the peer sends an unbounded number of unique header keys.
648
+ const maxCachedCanonicalHeadersKeysSize = 2048
649
+
650
+ func (sc *serverConn) canonicalHeader(v string) string {
651
+ sc.serveG.check()
652
+ cv, ok := httpcommon.CachedCanonicalHeader(v)
653
+ if ok {
654
+ return cv
655
+ }
656
+ cv, ok = sc.canonHeader[v]
657
+ if ok {
658
+ return cv
659
+ }
660
+ if sc.canonHeader == nil {
661
+ sc.canonHeader = make(map[string]string)
662
+ }
663
+ cv = textproto.CanonicalMIMEHeaderKey(v)
664
+ size := 100 + len(v)*2 // 100 bytes of map overhead + key + value
665
+ if sc.canonHeaderKeysSize+size <= maxCachedCanonicalHeadersKeysSize {
666
+ sc.canonHeader[v] = cv
667
+ sc.canonHeaderKeysSize += size
668
+ }
669
+ return cv
670
+ }
671
+
672
+ type readFrameResult struct {
673
+ f Frame // valid until readMore is called
674
+ err error
675
+
676
+ // readMore should be called once the consumer no longer needs or
677
+ // retains f. After readMore, f is invalid and more frames can be
678
+ // read.
679
+ readMore func()
680
+ }
681
+
682
+ // readFrames is the loop that reads incoming frames.
683
+ // It takes care to only read one frame at a time, blocking until the
684
+ // consumer is done with the frame.
685
+ // It's run on its own goroutine.
686
+ func (sc *serverConn) readFrames() {
687
+ gate := make(chan struct{})
688
+ gateDone := func() { gate <- struct{}{} }
689
+ for {
690
+ f, err := sc.framer.ReadFrame()
691
+ select {
692
+ case sc.readFrameCh <- readFrameResult{f, err, gateDone}:
693
+ case <-sc.doneServing:
694
+ return
695
+ }
696
+ select {
697
+ case <-gate:
698
+ case <-sc.doneServing:
699
+ return
700
+ }
701
+ if terminalReadFrameError(err) {
702
+ return
703
+ }
704
+ }
705
+ }
706
+
707
+ // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
708
+ type frameWriteResult struct {
709
+ _ incomparable
710
+ wr FrameWriteRequest // what was written (or attempted)
711
+ err error // result of the writeFrame call
712
+ }
713
+
714
+ // writeFrameAsync runs in its own goroutine and writes a single frame
715
+ // and then reports when it's done.
716
+ // At most one goroutine can be running writeFrameAsync at a time per
717
+ // serverConn.
718
+ func (sc *serverConn) writeFrameAsync(wr FrameWriteRequest, wd *writeData) {
719
+ var err error
720
+ if wd == nil {
721
+ err = wr.write.writeFrame(sc)
722
+ } else {
723
+ err = sc.framer.endWrite()
724
+ }
725
+ sc.wroteFrameCh <- frameWriteResult{wr: wr, err: err}
726
+ }
727
+
728
+ func (sc *serverConn) closeAllStreamsOnConnClose() {
729
+ sc.serveG.check()
730
+ for _, st := range sc.streams {
731
+ sc.closeStream(st, errClientDisconnected)
732
+ }
733
+ }
734
+
735
+ func (sc *serverConn) stopShutdownTimer() {
736
+ sc.serveG.check()
737
+ if t := sc.shutdownTimer; t != nil {
738
+ t.Stop()
739
+ }
740
+ }
741
+
742
+ func (sc *serverConn) notePanic() {
743
+ // Note: this is for serverConn.serve panicking, not http.Handler code.
744
+ if testHookOnPanicMu != nil {
745
+ testHookOnPanicMu.Lock()
746
+ defer testHookOnPanicMu.Unlock()
747
+ }
748
+ if testHookOnPanic != nil {
749
+ if e := recover(); e != nil {
750
+ if testHookOnPanic(sc, e) {
751
+ panic(e)
752
+ }
753
+ }
754
+ }
755
+ }
756
+
757
+ func (sc *serverConn) serve(conf Config) {
758
+ sc.serveG.check()
759
+ defer sc.notePanic()
760
+ defer sc.conn.Close()
761
+ defer sc.closeAllStreamsOnConnClose()
762
+ defer sc.stopShutdownTimer()
763
+ defer close(sc.doneServing) // unblocks handlers trying to send
764
+
765
+ if VerboseLogs {
766
+ sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
767
+ }
768
+
769
+ settings := writeSettings{
770
+ {SettingMaxFrameSize, uint32(conf.MaxReadFrameSize)},
771
+ {SettingMaxConcurrentStreams, sc.advMaxStreams},
772
+ {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
773
+ {SettingHeaderTableSize, uint32(conf.MaxDecoderHeaderTableSize)},
774
+ {SettingInitialWindowSize, uint32(sc.initialStreamRecvWindowSize)},
775
+ }
776
+ if !disableExtendedConnectProtocol {
777
+ settings = append(settings, Setting{SettingEnableConnectProtocol, 1})
778
+ }
779
+ if sc.writeSchedIgnoresRFC7540() {
780
+ settings = append(settings, Setting{SettingNoRFC7540Priorities, 1})
781
+ }
782
+ sc.writeFrame(FrameWriteRequest{
783
+ write: settings,
784
+ })
785
+ sc.unackedSettings++
786
+
787
+ // Each connection starts with initialWindowSize inflow tokens.
788
+ // If a higher value is configured, we add more tokens.
789
+ if diff := conf.MaxReceiveBufferPerConnection - initialWindowSize; diff > 0 {
790
+ sc.sendWindowUpdate(nil, int(diff))
791
+ }
792
+
793
+ if err := sc.readPreface(); err != nil {
794
+ sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
795
+ return
796
+ }
797
+ // Now that we've got the preface, get us out of the
798
+ // "StateNew" state. We can't go directly to idle, though.
799
+ // Active means we read some data and anticipate a request. We'll
800
+ // do another Active when we get a HEADERS frame.
801
+ sc.setConnState(ConnStateActive)
802
+ sc.setConnState(ConnStateIdle)
803
+
804
+ if idle := sc.hs.IdleTimeout(); idle > 0 {
805
+ sc.idleTimer = time.AfterFunc(idle, sc.onIdleTimer)
806
+ defer sc.idleTimer.Stop()
807
+ }
808
+
809
+ if conf.SendPingTimeout > 0 {
810
+ sc.readIdleTimeout = conf.SendPingTimeout
811
+ sc.readIdleTimer = time.AfterFunc(conf.SendPingTimeout, sc.onReadIdleTimer)
812
+ defer sc.readIdleTimer.Stop()
813
+ }
814
+
815
+ go sc.readFrames() // closed by defer sc.conn.Close above
816
+
817
+ settingsTimer := time.AfterFunc(firstSettingsTimeout, sc.onSettingsTimer)
818
+ defer settingsTimer.Stop()
819
+
820
+ lastFrameTime := time.Now()
821
+ loopNum := 0
822
+ for {
823
+ loopNum++
824
+ select {
825
+ case wr := <-sc.wantWriteFrameCh:
826
+ if se, ok := wr.write.(StreamError); ok {
827
+ sc.resetStream(se)
828
+ break
829
+ }
830
+ sc.writeFrame(wr)
831
+ case res := <-sc.wroteFrameCh:
832
+ sc.wroteFrame(res)
833
+ case res := <-sc.readFrameCh:
834
+ lastFrameTime = time.Now()
835
+ // Process any written frames before reading new frames from the client since a
836
+ // written frame could have triggered a new stream to be started.
837
+ if sc.writingFrameAsync {
838
+ select {
839
+ case wroteRes := <-sc.wroteFrameCh:
840
+ sc.wroteFrame(wroteRes)
841
+ default:
842
+ }
843
+ }
844
+ if !sc.processFrameFromReader(res) {
845
+ return
846
+ }
847
+ res.readMore()
848
+ if settingsTimer != nil {
849
+ settingsTimer.Stop()
850
+ settingsTimer = nil
851
+ }
852
+ case m := <-sc.bodyReadCh:
853
+ sc.noteBodyRead(m.st, m.n)
854
+ case msg := <-sc.serveMsgCh:
855
+ switch v := msg.(type) {
856
+ case func(int):
857
+ v(loopNum) // for testing
858
+ case *serverMessage:
859
+ switch v {
860
+ case settingsTimerMsg:
861
+ sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
862
+ return
863
+ case idleTimerMsg:
864
+ sc.vlogf("connection is idle")
865
+ sc.goAway(ErrCodeNo)
866
+ case readIdleTimerMsg:
867
+ sc.handlePingTimer(lastFrameTime)
868
+ case shutdownTimerMsg:
869
+ sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
870
+ return
871
+ case gracefulShutdownMsg:
872
+ sc.startGracefulShutdownInternal()
873
+ case handlerDoneMsg:
874
+ sc.handlerDone()
875
+ default:
876
+ panic("unknown timer")
877
+ }
878
+ case *startPushRequest:
879
+ sc.startPush(v)
880
+ case func(*serverConn):
881
+ v(sc)
882
+ default:
883
+ panic(fmt.Sprintf("unexpected type %T", v))
884
+ }
885
+ }
886
+
887
+ // If the peer is causing us to generate a lot of control frames,
888
+ // but not reading them from us, assume they are trying to make us
889
+ // run out of memory.
890
+ if sc.queuedControlFrames > maxQueuedControlFrames {
891
+ sc.vlogf("http2: too many control frames in send queue, closing connection")
892
+ return
893
+ }
894
+
895
+ // Start the shutdown timer after sending a GOAWAY. When sending GOAWAY
896
+ // with no error code (graceful shutdown), don't start the timer until
897
+ // all open streams have been completed.
898
+ sentGoAway := sc.inGoAway && !sc.needToSendGoAway && !sc.writingFrame
899
+ gracefulShutdownComplete := sc.goAwayCode == ErrCodeNo && sc.curOpenStreams() == 0
900
+ if sentGoAway && sc.shutdownTimer == nil && (sc.goAwayCode != ErrCodeNo || gracefulShutdownComplete) {
901
+ sc.shutDownIn(goAwayTimeout)
902
+ }
903
+ }
904
+ }
905
+
906
+ func (sc *serverConn) handlePingTimer(lastFrameReadTime time.Time) {
907
+ if sc.pingSent {
908
+ sc.logf("timeout waiting for PING response")
909
+ if f := sc.countErrorFunc; f != nil {
910
+ f("conn_close_lost_ping")
911
+ }
912
+ sc.conn.Close()
913
+ return
914
+ }
915
+
916
+ pingAt := lastFrameReadTime.Add(sc.readIdleTimeout)
917
+ now := time.Now()
918
+ if pingAt.After(now) {
919
+ // We received frames since arming the ping timer.
920
+ // Reset it for the next possible timeout.
921
+ sc.readIdleTimer.Reset(pingAt.Sub(now))
922
+ return
923
+ }
924
+
925
+ sc.pingSent = true
926
+ // Ignore crypto/rand.Read errors: It generally can't fail, and worse case if it does
927
+ // is we send a PING frame containing 0s.
928
+ _, _ = rand.Read(sc.sentPingData[:])
929
+ sc.writeFrame(FrameWriteRequest{
930
+ write: &writePing{data: sc.sentPingData},
931
+ })
932
+ sc.readIdleTimer.Reset(sc.pingTimeout)
933
+ }
934
+
935
+ type serverMessage int
936
+
937
+ // Message values sent to serveMsgCh.
938
+ var (
939
+ settingsTimerMsg = new(serverMessage)
940
+ idleTimerMsg = new(serverMessage)
941
+ readIdleTimerMsg = new(serverMessage)
942
+ shutdownTimerMsg = new(serverMessage)
943
+ gracefulShutdownMsg = new(serverMessage)
944
+ handlerDoneMsg = new(serverMessage)
945
+ )
946
+
947
+ func (sc *serverConn) onSettingsTimer() { sc.sendServeMsg(settingsTimerMsg) }
948
+ func (sc *serverConn) onIdleTimer() { sc.sendServeMsg(idleTimerMsg) }
949
+ func (sc *serverConn) onReadIdleTimer() { sc.sendServeMsg(readIdleTimerMsg) }
950
+ func (sc *serverConn) onShutdownTimer() { sc.sendServeMsg(shutdownTimerMsg) }
951
+
952
+ func (sc *serverConn) sendServeMsg(msg any) {
953
+ sc.serveG.checkNotOn() // NOT
954
+ select {
955
+ case sc.serveMsgCh <- msg:
956
+ case <-sc.doneServing:
957
+ }
958
+ }
959
+
960
+ var errPrefaceTimeout = errors.New("timeout waiting for client preface")
961
+
962
+ // readPreface reads the ClientPreface greeting from the peer or
963
+ // returns errPrefaceTimeout on timeout, or an error if the greeting
964
+ // is invalid.
965
+ func (sc *serverConn) readPreface() error {
966
+ if sc.sawClientPreface {
967
+ return nil
968
+ }
969
+ errc := make(chan error, 1)
970
+ go func() {
971
+ // Read the client preface
972
+ buf := make([]byte, len(ClientPreface))
973
+ if _, err := io.ReadFull(sc.conn, buf); err != nil {
974
+ errc <- err
975
+ } else if !bytes.Equal(buf, clientPreface) {
976
+ errc <- fmt.Errorf("bogus greeting %q", buf)
977
+ } else {
978
+ errc <- nil
979
+ }
980
+ }()
981
+ timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
982
+ defer timer.Stop()
983
+ select {
984
+ case <-timer.C:
985
+ return errPrefaceTimeout
986
+ case err := <-errc:
987
+ if err == nil {
988
+ if VerboseLogs {
989
+ sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
990
+ }
991
+ }
992
+ return err
993
+ }
994
+ }
995
+
996
+ var writeDataPool = sync.Pool{
997
+ New: func() any { return new(writeData) },
998
+ }
999
+
1000
+ // writeDataFromHandler writes DATA response frames from a handler on
1001
+ // the given stream.
1002
+ func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
1003
+ ch := sc.srv.getErrChan()
1004
+ writeArg := writeDataPool.Get().(*writeData)
1005
+ *writeArg = writeData{stream.id, data, endStream}
1006
+ err := sc.writeFrameFromHandler(FrameWriteRequest{
1007
+ write: writeArg,
1008
+ stream: stream,
1009
+ done: ch,
1010
+ })
1011
+ if err != nil {
1012
+ return err
1013
+ }
1014
+ var frameWriteDone bool // the frame write is done (successfully or not)
1015
+ select {
1016
+ case err = <-ch:
1017
+ frameWriteDone = true
1018
+ case <-sc.doneServing:
1019
+ return errClientDisconnected
1020
+ case <-stream.cw:
1021
+ // If both ch and stream.cw were ready (as might
1022
+ // happen on the final Write after an http.Handler
1023
+ // ends), prefer the write result. Otherwise this
1024
+ // might just be us successfully closing the stream.
1025
+ // The writeFrameAsync and serve goroutines guarantee
1026
+ // that the ch send will happen before the stream.cw
1027
+ // close.
1028
+ select {
1029
+ case err = <-ch:
1030
+ frameWriteDone = true
1031
+ default:
1032
+ return errStreamClosed
1033
+ }
1034
+ }
1035
+ sc.srv.putErrChan(ch)
1036
+ if frameWriteDone {
1037
+ writeDataPool.Put(writeArg)
1038
+ }
1039
+ return err
1040
+ }
1041
+
1042
+ // writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts
1043
+ // if the connection has gone away.
1044
+ //
1045
+ // This must not be run from the serve goroutine itself, else it might
1046
+ // deadlock writing to sc.wantWriteFrameCh (which is only mildly
1047
+ // buffered and is read by serve itself). If you're on the serve
1048
+ // goroutine, call writeFrame instead.
1049
+ func (sc *serverConn) writeFrameFromHandler(wr FrameWriteRequest) error {
1050
+ sc.serveG.checkNotOn() // NOT
1051
+ select {
1052
+ case sc.wantWriteFrameCh <- wr:
1053
+ return nil
1054
+ case <-sc.doneServing:
1055
+ // Serve loop is gone.
1056
+ // Client has closed their connection to the server.
1057
+ return errClientDisconnected
1058
+ }
1059
+ }
1060
+
1061
+ // writeFrame schedules a frame to write and sends it if there's nothing
1062
+ // already being written.
1063
+ //
1064
+ // There is no pushback here (the serve goroutine never blocks). It's
1065
+ // the http.Handlers that block, waiting for their previous frames to
1066
+ // make it onto the wire
1067
+ //
1068
+ // If you're not on the serve goroutine, use writeFrameFromHandler instead.
1069
+ func (sc *serverConn) writeFrame(wr FrameWriteRequest) {
1070
+ sc.serveG.check()
1071
+
1072
+ // If true, wr will not be written and wr.done will not be signaled.
1073
+ var ignoreWrite bool
1074
+
1075
+ // We are not allowed to write frames on closed streams. RFC 7540 Section
1076
+ // 5.1.1 says: "An endpoint MUST NOT send frames other than PRIORITY on
1077
+ // a closed stream." Our server never sends PRIORITY, so that exception
1078
+ // does not apply.
1079
+ //
1080
+ // The serverConn might close an open stream while the stream's handler
1081
+ // is still running. For example, the server might close a stream when it
1082
+ // receives bad data from the client. If this happens, the handler might
1083
+ // attempt to write a frame after the stream has been closed (since the
1084
+ // handler hasn't yet been notified of the close). In this case, we simply
1085
+ // ignore the frame. The handler will notice that the stream is closed when
1086
+ // it waits for the frame to be written.
1087
+ //
1088
+ // As an exception to this rule, we allow sending RST_STREAM after close.
1089
+ // This allows us to immediately reject new streams without tracking any
1090
+ // state for those streams (except for the queued RST_STREAM frame). This
1091
+ // may result in duplicate RST_STREAMs in some cases, but the client should
1092
+ // ignore those.
1093
+ if wr.StreamID() != 0 {
1094
+ _, isReset := wr.write.(StreamError)
1095
+ if state, _ := sc.state(wr.StreamID()); state == stateClosed && !isReset {
1096
+ ignoreWrite = true
1097
+ }
1098
+ }
1099
+
1100
+ // Don't send a 100-continue response if we've already sent headers.
1101
+ // See golang.org/issue/14030.
1102
+ switch wr.write.(type) {
1103
+ case *writeResHeaders:
1104
+ wr.stream.wroteHeaders = true
1105
+ case write100ContinueHeadersFrame:
1106
+ if wr.stream.wroteHeaders {
1107
+ // We do not need to notify wr.done because this frame is
1108
+ // never written with wr.done != nil.
1109
+ if wr.done != nil {
1110
+ panic("wr.done != nil for write100ContinueHeadersFrame")
1111
+ }
1112
+ ignoreWrite = true
1113
+ }
1114
+ }
1115
+
1116
+ if !ignoreWrite {
1117
+ if wr.isControl() {
1118
+ sc.queuedControlFrames++
1119
+ // For extra safety, detect wraparounds, which should not happen,
1120
+ // and pull the plug.
1121
+ if sc.queuedControlFrames < 0 {
1122
+ sc.conn.Close()
1123
+ }
1124
+ }
1125
+ sc.writeSched.Push(wr)
1126
+ }
1127
+ sc.scheduleFrameWrite()
1128
+ }
1129
+
1130
+ // startFrameWrite starts a goroutine to write wr (in a separate
1131
+ // goroutine since that might block on the network), and updates the
1132
+ // serve goroutine's state about the world, updated from info in wr.
1133
+ func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) {
1134
+ sc.serveG.check()
1135
+ if sc.writingFrame {
1136
+ panic("internal error: can only be writing one frame at a time")
1137
+ }
1138
+
1139
+ st := wr.stream
1140
+ if st != nil {
1141
+ switch st.state {
1142
+ case stateHalfClosedLocal:
1143
+ switch wr.write.(type) {
1144
+ case StreamError, handlerPanicRST, writeWindowUpdate:
1145
+ // RFC 7540 Section 5.1 allows sending RST_STREAM, PRIORITY, and WINDOW_UPDATE
1146
+ // in this state. (We never send PRIORITY from the server, so that is not checked.)
1147
+ default:
1148
+ panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr))
1149
+ }
1150
+ case stateClosed:
1151
+ panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr))
1152
+ }
1153
+ }
1154
+ if wpp, ok := wr.write.(*writePushPromise); ok {
1155
+ var err error
1156
+ wpp.promisedID, err = wpp.allocatePromisedID()
1157
+ if err != nil {
1158
+ sc.writingFrameAsync = false
1159
+ wr.replyToWriter(err)
1160
+ return
1161
+ }
1162
+ }
1163
+
1164
+ sc.writingFrame = true
1165
+ sc.needsFrameFlush = true
1166
+ if sc.pendingEncoderTableSize {
1167
+ // hpackEncoder may be in use by writeFrameAsync, so SETTINGS
1168
+ // changes to it are deferred until no frame is being written.
1169
+ // Replaying the smallest size before the latest one keeps the
1170
+ // encoder's view identical to having applied every change
1171
+ // (RFC 7541, Section 4.2).
1172
+ sc.pendingEncoderTableSize = false
1173
+ sc.hpackEncoder.SetMaxDynamicTableSize(sc.encoderTableSizeMin)
1174
+ sc.hpackEncoder.SetMaxDynamicTableSize(sc.encoderTableSize)
1175
+ }
1176
+ if wr.write.staysWithinBuffer(sc.bw.Available()) {
1177
+ sc.writingFrameAsync = false
1178
+ err := wr.write.writeFrame(sc)
1179
+ sc.wroteFrame(frameWriteResult{wr: wr, err: err})
1180
+ } else if wd, ok := wr.write.(*writeData); ok {
1181
+ // Encode the frame in the serve goroutine, to ensure we don't have
1182
+ // any lingering asynchronous references to data passed to Write.
1183
+ // See https://go.dev/issue/58446.
1184
+ sc.framer.startWriteDataPadded(wd.streamID, wd.endStream, wd.p, nil)
1185
+ sc.writingFrameAsync = true
1186
+ go sc.writeFrameAsync(wr, wd)
1187
+ } else {
1188
+ sc.writingFrameAsync = true
1189
+ go sc.writeFrameAsync(wr, nil)
1190
+ }
1191
+ }
1192
+
1193
+ // errHandlerPanicked is the error given to any callers blocked in a read from
1194
+ // Request.Body when the main goroutine panics. Since most handlers read in the
1195
+ // main ServeHTTP goroutine, this will show up rarely.
1196
+ var errHandlerPanicked = errors.New("http2: handler panicked")
1197
+
1198
+ // wroteFrame is called on the serve goroutine with the result of
1199
+ // whatever happened on writeFrameAsync.
1200
+ func (sc *serverConn) wroteFrame(res frameWriteResult) {
1201
+ sc.serveG.check()
1202
+ if !sc.writingFrame {
1203
+ panic("internal error: expected to be already writing a frame")
1204
+ }
1205
+ sc.writingFrame = false
1206
+ sc.writingFrameAsync = false
1207
+
1208
+ if res.err != nil {
1209
+ sc.conn.Close()
1210
+ }
1211
+
1212
+ wr := res.wr
1213
+
1214
+ if writeEndsStream(wr.write) {
1215
+ st := wr.stream
1216
+ if st == nil {
1217
+ panic("internal error: expecting non-nil stream")
1218
+ }
1219
+ switch st.state {
1220
+ case stateOpen:
1221
+ // Here we would go to stateHalfClosedLocal in
1222
+ // theory, but since our handler is done and
1223
+ // the net/http package provides no mechanism
1224
+ // for closing a ResponseWriter while still
1225
+ // reading data (see possible TODO at top of
1226
+ // this file), we go into closed state here
1227
+ // anyway, after telling the peer we're
1228
+ // hanging up on them. We'll transition to
1229
+ // stateClosed after the RST_STREAM frame is
1230
+ // written.
1231
+ st.state = stateHalfClosedLocal
1232
+ // Section 8.1: a server MAY request that the client abort
1233
+ // transmission of a request without error by sending a
1234
+ // RST_STREAM with an error code of NO_ERROR after sending
1235
+ // a complete response.
1236
+ sc.resetStream(streamError(st.id, ErrCodeNo))
1237
+ case stateHalfClosedRemote:
1238
+ sc.closeStream(st, errHandlerComplete)
1239
+ }
1240
+ } else {
1241
+ switch v := wr.write.(type) {
1242
+ case StreamError:
1243
+ // st may be unknown if the RST_STREAM was generated to reject bad input.
1244
+ if st, ok := sc.streams[v.StreamID]; ok {
1245
+ sc.closeStream(st, v)
1246
+ }
1247
+ case handlerPanicRST:
1248
+ sc.closeStream(wr.stream, errHandlerPanicked)
1249
+ }
1250
+ }
1251
+
1252
+ // Reply (if requested) to unblock the ServeHTTP goroutine.
1253
+ wr.replyToWriter(res.err)
1254
+
1255
+ sc.scheduleFrameWrite()
1256
+ }
1257
+
1258
+ // scheduleFrameWrite tickles the frame writing scheduler.
1259
+ //
1260
+ // If a frame is already being written, nothing happens. This will be called again
1261
+ // when the frame is done being written.
1262
+ //
1263
+ // If a frame isn't being written and we need to send one, the best frame
1264
+ // to send is selected by writeSched.
1265
+ //
1266
+ // If a frame isn't being written and there's nothing else to send, we
1267
+ // flush the write buffer.
1268
+ func (sc *serverConn) scheduleFrameWrite() {
1269
+ sc.serveG.check()
1270
+ if sc.writingFrame || sc.inFrameScheduleLoop {
1271
+ return
1272
+ }
1273
+ sc.inFrameScheduleLoop = true
1274
+ for !sc.writingFrameAsync {
1275
+ if sc.flow.flowErr && (!sc.inGoAway || sc.goAwayCode == ErrCodeNo) {
1276
+ sc.inGoAway = true
1277
+ sc.needToSendGoAway = true
1278
+ sc.goAwayCode = ErrCodeFlowControl
1279
+ }
1280
+ if sc.needToSendGoAway {
1281
+ sc.needToSendGoAway = false
1282
+ sc.startFrameWrite(FrameWriteRequest{
1283
+ write: &writeGoAway{
1284
+ maxStreamID: sc.maxClientStreamID,
1285
+ code: sc.goAwayCode,
1286
+ },
1287
+ })
1288
+ continue
1289
+ }
1290
+ if sc.needToSendSettingsAck {
1291
+ sc.needToSendSettingsAck = false
1292
+ sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}})
1293
+ continue
1294
+ }
1295
+ if !sc.inGoAway || sc.goAwayCode == ErrCodeNo {
1296
+ if wr, ok := sc.writeSched.Pop(); ok {
1297
+ if wr.isControl() {
1298
+ sc.queuedControlFrames--
1299
+ }
1300
+ sc.startFrameWrite(wr)
1301
+ continue
1302
+ }
1303
+ if sc.flow.flowErr {
1304
+ continue
1305
+ }
1306
+ }
1307
+ if sc.needsFrameFlush {
1308
+ sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}})
1309
+ sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
1310
+ continue
1311
+ }
1312
+ break
1313
+ }
1314
+ sc.inFrameScheduleLoop = false
1315
+ }
1316
+
1317
+ // startGracefulShutdown gracefully shuts down a connection. This
1318
+ // sends GOAWAY with ErrCodeNo to tell the client we're gracefully
1319
+ // shutting down. The connection isn't closed until all current
1320
+ // streams are done.
1321
+ //
1322
+ // startGracefulShutdown returns immediately; it does not wait until
1323
+ // the connection has shut down.
1324
+ func (sc *serverConn) startGracefulShutdown() {
1325
+ sc.serveG.checkNotOn() // NOT
1326
+ sc.shutdownOnce.Do(func() { sc.sendServeMsg(gracefulShutdownMsg) })
1327
+ }
1328
+
1329
+ // After sending GOAWAY with an error code (non-graceful shutdown), the
1330
+ // connection will close after goAwayTimeout.
1331
+ //
1332
+ // If we close the connection immediately after sending GOAWAY, there may
1333
+ // be unsent data in our kernel receive buffer, which will cause the kernel
1334
+ // to send a TCP RST on close() instead of a FIN. This RST will abort the
1335
+ // connection immediately, whether or not the client had received the GOAWAY.
1336
+ //
1337
+ // Ideally we should delay for at least 1 RTT + epsilon so the client has
1338
+ // a chance to read the GOAWAY and stop sending messages. Measuring RTT
1339
+ // is hard, so we approximate with 1 second. See golang.org/issue/18701.
1340
+ //
1341
+ // This is a var so it can be shorter in tests, where all requests uses the
1342
+ // loopback interface making the expected RTT very small.
1343
+ //
1344
+ // TODO: configurable?
1345
+ var goAwayTimeout = 1 * time.Second
1346
+
1347
+ func (sc *serverConn) startGracefulShutdownInternal() {
1348
+ sc.goAway(ErrCodeNo)
1349
+ }
1350
+
1351
+ func (sc *serverConn) goAway(code ErrCode) {
1352
+ sc.serveG.check()
1353
+ if sc.inGoAway {
1354
+ if sc.goAwayCode == ErrCodeNo {
1355
+ sc.goAwayCode = code
1356
+ }
1357
+ return
1358
+ }
1359
+ sc.inGoAway = true
1360
+ sc.needToSendGoAway = true
1361
+ sc.goAwayCode = code
1362
+ sc.scheduleFrameWrite()
1363
+ }
1364
+
1365
+ func (sc *serverConn) shutDownIn(d time.Duration) {
1366
+ sc.serveG.check()
1367
+ sc.shutdownTimer = time.AfterFunc(d, sc.onShutdownTimer)
1368
+ }
1369
+
1370
+ func (sc *serverConn) resetStream(se StreamError) {
1371
+ sc.serveG.check()
1372
+ sc.writeFrame(FrameWriteRequest{write: se})
1373
+ if st, ok := sc.streams[se.StreamID]; ok {
1374
+ st.resetQueued = true
1375
+ }
1376
+ }
1377
+
1378
+ // processFrameFromReader processes the serve loop's read from readFrameCh from the
1379
+ // frame-reading goroutine.
1380
+ // processFrameFromReader returns whether the connection should be kept open.
1381
+ func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
1382
+ sc.serveG.check()
1383
+ err := res.err
1384
+ if err != nil {
1385
+ if err == ErrFrameTooLarge {
1386
+ sc.goAway(ErrCodeFrameSize)
1387
+ return true // goAway will close the loop
1388
+ }
1389
+ clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
1390
+ if clientGone {
1391
+ // TODO: could we also get into this state if
1392
+ // the peer does a half close
1393
+ // (e.g. CloseWrite) because they're done
1394
+ // sending frames but they're still wanting
1395
+ // our open replies? Investigate.
1396
+ // TODO: add CloseWrite to crypto/tls.Conn first
1397
+ // so we have a way to test this? I suppose
1398
+ // just for testing we could have a non-TLS mode.
1399
+ return false
1400
+ }
1401
+ } else {
1402
+ f := res.f
1403
+ if VerboseLogs {
1404
+ sc.vlogf("http2: server read frame %v", summarizeFrame(f))
1405
+ }
1406
+ err = sc.processFrame(f)
1407
+ if err == nil {
1408
+ return true
1409
+ }
1410
+ }
1411
+
1412
+ switch ev := err.(type) {
1413
+ case StreamError:
1414
+ sc.resetStream(ev)
1415
+ return true
1416
+ case goAwayFlowError:
1417
+ sc.goAway(ErrCodeFlowControl)
1418
+ return true
1419
+ case ConnectionError:
1420
+ if res.f != nil {
1421
+ if id := res.f.Header().StreamID; id > sc.maxClientStreamID {
1422
+ sc.maxClientStreamID = id
1423
+ }
1424
+ }
1425
+ sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
1426
+ sc.goAway(ErrCode(ev))
1427
+ return true // goAway will handle shutdown
1428
+ default:
1429
+ if res.err != nil {
1430
+ sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
1431
+ } else {
1432
+ sc.logf("http2: server closing client connection: %v", err)
1433
+ }
1434
+ return false
1435
+ }
1436
+ }
1437
+
1438
+ func (sc *serverConn) processFrame(f Frame) error {
1439
+ sc.serveG.check()
1440
+
1441
+ // First frame received must be SETTINGS.
1442
+ if !sc.sawFirstSettings {
1443
+ if _, ok := f.(*SettingsFrame); !ok {
1444
+ return sc.countError("first_settings", ConnectionError(ErrCodeProtocol))
1445
+ }
1446
+ sc.sawFirstSettings = true
1447
+ }
1448
+
1449
+ // Discard frames for streams initiated after the identified last
1450
+ // stream sent in a GOAWAY, or all frames after sending an error.
1451
+ // We still need to return connection-level flow control for DATA frames.
1452
+ // RFC 9113 Section 6.8.
1453
+ if sc.inGoAway && (sc.goAwayCode != ErrCodeNo || f.Header().StreamID > sc.maxClientStreamID) {
1454
+
1455
+ if f, ok := f.(*DataFrame); ok {
1456
+ if !sc.inflow.take(f.Length) {
1457
+ return sc.countError("data_flow", streamError(f.Header().StreamID, ErrCodeFlowControl))
1458
+ }
1459
+ sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
1460
+ }
1461
+ return nil
1462
+ }
1463
+
1464
+ switch f := f.(type) {
1465
+ case *SettingsFrame:
1466
+ return sc.processSettings(f)
1467
+ case *MetaHeadersFrame:
1468
+ return sc.processHeaders(f)
1469
+ case *WindowUpdateFrame:
1470
+ return sc.processWindowUpdate(f)
1471
+ case *PingFrame:
1472
+ return sc.processPing(f)
1473
+ case *DataFrame:
1474
+ return sc.processData(f)
1475
+ case *RSTStreamFrame:
1476
+ return sc.processResetStream(f)
1477
+ case *PriorityFrame:
1478
+ return sc.processPriority(f)
1479
+ case *GoAwayFrame:
1480
+ return sc.processGoAway(f)
1481
+ case *PushPromiseFrame:
1482
+ // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
1483
+ // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
1484
+ return sc.countError("push_promise", ConnectionError(ErrCodeProtocol))
1485
+ case *PriorityUpdateFrame:
1486
+ return sc.processPriorityUpdate(f)
1487
+ default:
1488
+ sc.vlogf("http2: server ignoring frame: %v", f.Header())
1489
+ return nil
1490
+ }
1491
+ }
1492
+
1493
+ func (sc *serverConn) processPing(f *PingFrame) error {
1494
+ sc.serveG.check()
1495
+ if f.IsAck() {
1496
+ if sc.pingSent && sc.sentPingData == f.Data {
1497
+ // This is a response to a PING we sent.
1498
+ sc.pingSent = false
1499
+ sc.readIdleTimer.Reset(sc.readIdleTimeout)
1500
+ }
1501
+ // 6.7 PING: " An endpoint MUST NOT respond to PING frames
1502
+ // containing this flag."
1503
+ return nil
1504
+ }
1505
+ if f.StreamID != 0 {
1506
+ // "PING frames are not associated with any individual
1507
+ // stream. If a PING frame is received with a stream
1508
+ // identifier field value other than 0x0, the recipient MUST
1509
+ // respond with a connection error (Section 5.4.1) of type
1510
+ // PROTOCOL_ERROR."
1511
+ return sc.countError("ping_on_stream", ConnectionError(ErrCodeProtocol))
1512
+ }
1513
+ sc.writeFrame(FrameWriteRequest{write: writePingAck{f}})
1514
+ return nil
1515
+ }
1516
+
1517
+ func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
1518
+ sc.serveG.check()
1519
+ switch {
1520
+ case f.StreamID != 0: // stream-level flow control
1521
+ state, st := sc.state(f.StreamID)
1522
+ if state == stateIdle {
1523
+ // Section 5.1: "Receiving any frame other than HEADERS
1524
+ // or PRIORITY on a stream in this state MUST be
1525
+ // treated as a connection error (Section 5.4.1) of
1526
+ // type PROTOCOL_ERROR."
1527
+ return sc.countError("stream_idle", ConnectionError(ErrCodeProtocol))
1528
+ }
1529
+ if st == nil {
1530
+ // "WINDOW_UPDATE can be sent by a peer that has sent a
1531
+ // frame bearing the END_STREAM flag. This means that a
1532
+ // receiver could receive a WINDOW_UPDATE frame on a "half
1533
+ // closed (remote)" or "closed" stream. A receiver MUST
1534
+ // NOT treat this as an error, see Section 5.1."
1535
+ return nil
1536
+ }
1537
+ if !st.flow.add(int32(f.Increment)) {
1538
+ if st.flow.conn.flowErr {
1539
+ // This is a lazily-detected connection-level flow control error.
1540
+ return sc.countError("bad_flow", ConnectionError(ErrCodeFlowControl))
1541
+ }
1542
+ return sc.countError("bad_flow", streamError(f.StreamID, ErrCodeFlowControl))
1543
+ }
1544
+ default: // connection-level flow control
1545
+ if !sc.flow.add(int32(f.Increment)) {
1546
+ return goAwayFlowError{}
1547
+ }
1548
+ }
1549
+ sc.scheduleFrameWrite()
1550
+ return nil
1551
+ }
1552
+
1553
+ func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
1554
+ sc.serveG.check()
1555
+
1556
+ state, st := sc.state(f.StreamID)
1557
+ if state == stateIdle {
1558
+ // 6.4 "RST_STREAM frames MUST NOT be sent for a
1559
+ // stream in the "idle" state. If a RST_STREAM frame
1560
+ // identifying an idle stream is received, the
1561
+ // recipient MUST treat this as a connection error
1562
+ // (Section 5.4.1) of type PROTOCOL_ERROR.
1563
+ return sc.countError("reset_idle_stream", ConnectionError(ErrCodeProtocol))
1564
+ }
1565
+ if st != nil {
1566
+ st.cancelCtx()
1567
+ sc.closeStream(st, streamError(f.StreamID, f.ErrCode))
1568
+ }
1569
+ return nil
1570
+ }
1571
+
1572
+ func (sc *serverConn) closeStream(st *stream, err error) {
1573
+ sc.serveG.check()
1574
+ if st.state == stateIdle || st.state == stateClosed {
1575
+ panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
1576
+ }
1577
+ st.state = stateClosed
1578
+ if st.readDeadline != nil {
1579
+ st.readDeadline.Stop()
1580
+ }
1581
+ if st.writeDeadline != nil {
1582
+ st.writeDeadline.Stop()
1583
+ }
1584
+ if st.isPushed() {
1585
+ sc.curPushedStreams--
1586
+ } else {
1587
+ sc.curClientStreams--
1588
+ }
1589
+ delete(sc.streams, st.id)
1590
+ if len(sc.streams) == 0 {
1591
+ sc.setConnState(ConnStateIdle)
1592
+ idleTimeout := sc.hs.IdleTimeout()
1593
+ if idleTimeout > 0 && sc.idleTimer != nil {
1594
+ sc.idleTimer.Reset(idleTimeout)
1595
+ }
1596
+ if h1ServerKeepAlivesDisabled(sc.hs) {
1597
+ sc.startGracefulShutdownInternal()
1598
+ }
1599
+ }
1600
+ if p := st.body; p != nil {
1601
+ p.CloseWithError(err)
1602
+ }
1603
+ if e, ok := err.(StreamError); ok {
1604
+ if e.Cause != nil {
1605
+ err = e.Cause
1606
+ } else {
1607
+ err = errStreamClosed
1608
+ }
1609
+ }
1610
+ st.closeErr = err
1611
+ st.cancelCtx()
1612
+ st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
1613
+ sc.writeSched.CloseStream(st.id)
1614
+ }
1615
+
1616
+ func (sc *serverConn) processSettings(f *SettingsFrame) error {
1617
+ sc.serveG.check()
1618
+ if f.IsAck() {
1619
+ sc.unackedSettings--
1620
+ if sc.unackedSettings < 0 {
1621
+ // Why is the peer ACKing settings we never sent?
1622
+ // The spec doesn't mention this case, but
1623
+ // hang up on them anyway.
1624
+ return sc.countError("ack_mystery", ConnectionError(ErrCodeProtocol))
1625
+ }
1626
+ return nil
1627
+ }
1628
+ if f.NumSettings() > 100 || f.HasDuplicates() {
1629
+ // This isn't actually in the spec, but hang up on
1630
+ // suspiciously large settings frames or those with
1631
+ // duplicate entries.
1632
+ return sc.countError("settings_big_or_dups", ConnectionError(ErrCodeProtocol))
1633
+ }
1634
+ if err := f.ForeachSetting(sc.processSetting); err != nil {
1635
+ return err
1636
+ }
1637
+ // TODO: judging by RFC 7540, Section 6.5.3 each SETTINGS frame should be
1638
+ // acknowledged individually, even if multiple are received before the ACK.
1639
+ sc.needToSendSettingsAck = true
1640
+ sc.scheduleFrameWrite()
1641
+ return nil
1642
+ }
1643
+
1644
+ func (sc *serverConn) processSetting(s Setting) error {
1645
+ sc.serveG.check()
1646
+ if err := s.Valid(); err != nil {
1647
+ return err
1648
+ }
1649
+ if VerboseLogs {
1650
+ sc.vlogf("http2: server processing setting %v", s)
1651
+ }
1652
+ switch s.ID {
1653
+ case SettingHeaderTableSize:
1654
+ // Applied by startFrameWrite; see comment there.
1655
+ if !sc.pendingEncoderTableSize || s.Val < sc.encoderTableSizeMin {
1656
+ sc.encoderTableSizeMin = s.Val
1657
+ }
1658
+ sc.encoderTableSize = s.Val
1659
+ sc.pendingEncoderTableSize = true
1660
+ case SettingEnablePush:
1661
+ sc.pushEnabled = s.Val != 0
1662
+ case SettingMaxConcurrentStreams:
1663
+ sc.clientMaxStreams = s.Val
1664
+ case SettingInitialWindowSize:
1665
+ return sc.processSettingInitialWindowSize(s.Val)
1666
+ case SettingMaxFrameSize:
1667
+ sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31
1668
+ case SettingMaxHeaderListSize:
1669
+ sc.peerMaxHeaderListSize = s.Val
1670
+ case SettingEnableConnectProtocol:
1671
+ // Receipt of this parameter by a server does not
1672
+ // have any impact
1673
+ case SettingNoRFC7540Priorities:
1674
+ if s.Val > 1 {
1675
+ return ConnectionError(ErrCodeProtocol)
1676
+ }
1677
+ default:
1678
+ // Unknown setting: "An endpoint that receives a SETTINGS
1679
+ // frame with any unknown or unsupported identifier MUST
1680
+ // ignore that setting."
1681
+ if VerboseLogs {
1682
+ sc.vlogf("http2: server ignoring unknown setting %v", s)
1683
+ }
1684
+ }
1685
+ return nil
1686
+ }
1687
+
1688
+ func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
1689
+ sc.serveG.check()
1690
+ if !sc.flow.changeInitialWindowSize(int64(val)) {
1691
+ // 6.9.2 Initial Flow Control Window Size
1692
+ // "An endpoint MUST treat a change to
1693
+ // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
1694
+ // control window to exceed the maximum size as a
1695
+ // connection error (Section 5.4.1) of type
1696
+ // FLOW_CONTROL_ERROR."
1697
+ return sc.countError("setting_win_size", ConnectionError(ErrCodeFlowControl))
1698
+ }
1699
+ return nil
1700
+ }
1701
+
1702
+ func (sc *serverConn) processData(f *DataFrame) error {
1703
+ sc.serveG.check()
1704
+ id := f.Header().StreamID
1705
+
1706
+ data := f.Data()
1707
+ state, st := sc.state(id)
1708
+ if id == 0 || state == stateIdle {
1709
+ // Section 6.1: "DATA frames MUST be associated with a
1710
+ // stream. If a DATA frame is received whose stream
1711
+ // identifier field is 0x0, the recipient MUST respond
1712
+ // with a connection error (Section 5.4.1) of type
1713
+ // PROTOCOL_ERROR."
1714
+ //
1715
+ // Section 5.1: "Receiving any frame other than HEADERS
1716
+ // or PRIORITY on a stream in this state MUST be
1717
+ // treated as a connection error (Section 5.4.1) of
1718
+ // type PROTOCOL_ERROR."
1719
+ return sc.countError("data_on_idle", ConnectionError(ErrCodeProtocol))
1720
+ }
1721
+
1722
+ // "If a DATA frame is received whose stream is not in "open"
1723
+ // or "half closed (local)" state, the recipient MUST respond
1724
+ // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
1725
+ if st == nil || state != stateOpen || st.gotTrailerHeader || st.resetQueued {
1726
+ // This includes sending a RST_STREAM if the stream is
1727
+ // in stateHalfClosedLocal (which currently means that
1728
+ // the http.Handler returned, so it's done reading &
1729
+ // done writing). Try to stop the client from sending
1730
+ // more DATA.
1731
+
1732
+ // But still enforce their connection-level flow control,
1733
+ // and return any flow control bytes since we're not going
1734
+ // to consume them.
1735
+ if !sc.inflow.take(f.Length) {
1736
+ return sc.countError("data_flow", streamError(id, ErrCodeFlowControl))
1737
+ }
1738
+ sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
1739
+
1740
+ if st != nil && st.resetQueued {
1741
+ // Already have a stream error in flight. Don't send another.
1742
+ return nil
1743
+ }
1744
+ return sc.countError("closed", streamError(id, ErrCodeStreamClosed))
1745
+ }
1746
+ if st.body == nil {
1747
+ panic("internal error: should have a body in this state")
1748
+ }
1749
+
1750
+ // Sender sending more than they'd declared?
1751
+ if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
1752
+ if !sc.inflow.take(f.Length) {
1753
+ return sc.countError("data_flow", streamError(id, ErrCodeFlowControl))
1754
+ }
1755
+ sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
1756
+
1757
+ st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
1758
+ // RFC 7540, sec 8.1.2.6: A request or response is also malformed if the
1759
+ // value of a content-length header field does not equal the sum of the
1760
+ // DATA frame payload lengths that form the body.
1761
+ return sc.countError("send_too_much", streamError(id, ErrCodeProtocol))
1762
+ }
1763
+ if f.Length > 0 {
1764
+ // Check whether the client has flow control quota.
1765
+ if !takeInflows(&sc.inflow, &st.inflow, f.Length) {
1766
+ return sc.countError("flow_on_data_length", streamError(id, ErrCodeFlowControl))
1767
+ }
1768
+
1769
+ if len(data) > 0 {
1770
+ st.bodyBytes += int64(len(data))
1771
+ wrote, err := st.body.Write(data)
1772
+ if err != nil {
1773
+ // The handler has closed the request body.
1774
+ // Return the connection-level flow control for the discarded data,
1775
+ // but not the stream-level flow control.
1776
+ sc.sendWindowUpdate(nil, int(f.Length)-wrote)
1777
+ return nil
1778
+ }
1779
+ if wrote != len(data) {
1780
+ panic("internal error: bad Writer")
1781
+ }
1782
+ }
1783
+
1784
+ // Return any padded flow control now, since we won't
1785
+ // refund it later on body reads.
1786
+ // Call sendWindowUpdate even if there is no padding,
1787
+ // to return buffered flow control credit if the sent
1788
+ // window has shrunk.
1789
+ pad := int32(f.Length) - int32(len(data))
1790
+ sc.sendWindowUpdate32(nil, pad)
1791
+ sc.sendWindowUpdate32(st, pad)
1792
+ }
1793
+ if f.StreamEnded() {
1794
+ st.endStream()
1795
+ }
1796
+ return nil
1797
+ }
1798
+
1799
+ func (sc *serverConn) processGoAway(f *GoAwayFrame) error {
1800
+ sc.serveG.check()
1801
+ if f.ErrCode != ErrCodeNo {
1802
+ sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f)
1803
+ } else {
1804
+ sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f)
1805
+ }
1806
+ sc.startGracefulShutdownInternal()
1807
+ // http://tools.ietf.org/html/rfc7540#section-6.8
1808
+ // We should not create any new streams, which means we should disable push.
1809
+ sc.pushEnabled = false
1810
+ return nil
1811
+ }
1812
+
1813
+ // isPushed reports whether the stream is server-initiated.
1814
+ func (st *stream) isPushed() bool {
1815
+ return st.id%2 == 0
1816
+ }
1817
+
1818
+ // endStream closes a Request.Body's pipe. It is called when a DATA
1819
+ // frame says a request body is over (or after trailers).
1820
+ func (st *stream) endStream() {
1821
+ sc := st.sc
1822
+ sc.serveG.check()
1823
+
1824
+ if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
1825
+ st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
1826
+ st.declBodyBytes, st.bodyBytes))
1827
+ } else {
1828
+ st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
1829
+ st.body.CloseWithError(io.EOF)
1830
+ }
1831
+ st.state = stateHalfClosedRemote
1832
+ }
1833
+
1834
+ // copyTrailersToHandlerRequest is run in the Handler's goroutine in
1835
+ // its Request.Body.Read just before it gets io.EOF.
1836
+ func (st *stream) copyTrailersToHandlerRequest() {
1837
+ for k, vv := range st.trailer {
1838
+ if _, ok := st.reqTrailer[k]; ok {
1839
+ // Only copy it over it was pre-declared.
1840
+ st.reqTrailer[k] = vv
1841
+ }
1842
+ }
1843
+ }
1844
+
1845
+ // onReadTimeout is run on its own goroutine (from time.AfterFunc)
1846
+ // when the stream's ReadTimeout has fired.
1847
+ func (st *stream) onReadTimeout() {
1848
+ if st.body != nil {
1849
+ // Wrap the ErrDeadlineExceeded to avoid callers depending on us
1850
+ // returning the bare error.
1851
+ st.body.CloseWithError(fmt.Errorf("%w", os.ErrDeadlineExceeded))
1852
+ }
1853
+ }
1854
+
1855
+ // onWriteTimeout is run on its own goroutine (from time.AfterFunc)
1856
+ // when the stream's WriteTimeout has fired.
1857
+ func (st *stream) onWriteTimeout() {
1858
+ st.sc.writeFrameFromHandler(FrameWriteRequest{write: StreamError{
1859
+ StreamID: st.id,
1860
+ Code: ErrCodeInternal,
1861
+ Cause: os.ErrDeadlineExceeded,
1862
+ }})
1863
+ }
1864
+
1865
+ func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
1866
+ sc.serveG.check()
1867
+ id := f.StreamID
1868
+ // http://tools.ietf.org/html/rfc7540#section-5.1.1
1869
+ // Streams initiated by a client MUST use odd-numbered stream
1870
+ // identifiers. [...] An endpoint that receives an unexpected
1871
+ // stream identifier MUST respond with a connection error
1872
+ // (Section 5.4.1) of type PROTOCOL_ERROR.
1873
+ if id%2 != 1 {
1874
+ return sc.countError("headers_even", ConnectionError(ErrCodeProtocol))
1875
+ }
1876
+ // A HEADERS frame can be used to create a new stream or
1877
+ // send a trailer for an open one. If we already have a stream
1878
+ // open, let it process its own HEADERS frame (trailers at this
1879
+ // point, if it's valid).
1880
+ if st := sc.streams[f.StreamID]; st != nil {
1881
+ if st.resetQueued {
1882
+ // We're sending RST_STREAM to close the stream, so don't bother
1883
+ // processing this frame.
1884
+ return nil
1885
+ }
1886
+ // RFC 7540, sec 5.1: If an endpoint receives additional frames, other than
1887
+ // WINDOW_UPDATE, PRIORITY, or RST_STREAM, for a stream that is in
1888
+ // this state, it MUST respond with a stream error (Section 5.4.2) of
1889
+ // type STREAM_CLOSED.
1890
+ if st.state == stateHalfClosedRemote {
1891
+ return sc.countError("headers_half_closed", streamError(id, ErrCodeStreamClosed))
1892
+ }
1893
+ return st.processTrailerHeaders(f)
1894
+ }
1895
+
1896
+ // [...] The identifier of a newly established stream MUST be
1897
+ // numerically greater than all streams that the initiating
1898
+ // endpoint has opened or reserved. [...] An endpoint that
1899
+ // receives an unexpected stream identifier MUST respond with
1900
+ // a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
1901
+ if id <= sc.maxClientStreamID {
1902
+ return sc.countError("stream_went_down", ConnectionError(ErrCodeProtocol))
1903
+ }
1904
+ sc.maxClientStreamID = id
1905
+
1906
+ if sc.idleTimer != nil {
1907
+ sc.idleTimer.Stop()
1908
+ }
1909
+
1910
+ // http://tools.ietf.org/html/rfc7540#section-5.1.2
1911
+ // [...] Endpoints MUST NOT exceed the limit set by their peer. An
1912
+ // endpoint that receives a HEADERS frame that causes their
1913
+ // advertised concurrent stream limit to be exceeded MUST treat
1914
+ // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR
1915
+ // or REFUSED_STREAM.
1916
+ if sc.curClientStreams+1 > sc.advMaxStreams {
1917
+ if sc.unackedSettings == 0 {
1918
+ // They should know better.
1919
+ return sc.countError("over_max_streams", streamError(id, ErrCodeProtocol))
1920
+ }
1921
+ // Assume it's a network race, where they just haven't
1922
+ // received our last SETTINGS update. But actually
1923
+ // this can't happen yet, because we don't yet provide
1924
+ // a way for users to adjust server parameters at
1925
+ // runtime.
1926
+ return sc.countError("over_max_streams_race", streamError(id, ErrCodeRefusedStream))
1927
+ }
1928
+
1929
+ initialState := stateOpen
1930
+ if f.StreamEnded() {
1931
+ initialState = stateHalfClosedRemote
1932
+ }
1933
+
1934
+ // We are handling two special cases here:
1935
+ // 1. When a request is sent via an intermediary, we force priority to be
1936
+ // u=3,i. This is essentially a round-robin behavior, and is done to ensure
1937
+ // fairness between, for example, multiple clients using the same proxy.
1938
+ // 2. Until a client has shown that it is aware of RFC 9218, we make its
1939
+ // streams non-incremental by default. This is done to preserve the
1940
+ // historical behavior of handling streams in a round-robin manner, rather
1941
+ // than one-by-one to completion.
1942
+ initialPriority := defaultRFC9218Priority(sc.priorityAware && !sc.hasIntermediary)
1943
+ if _, ok := sc.writeSched.(*priorityWriteSchedulerRFC9218); ok && !sc.hasIntermediary {
1944
+ headerPriority, priorityAware, hasIntermediary := f.rfc9218Priority(sc.priorityAware)
1945
+ initialPriority = headerPriority
1946
+ sc.hasIntermediary = hasIntermediary
1947
+ if priorityAware {
1948
+ sc.priorityAware = true
1949
+ }
1950
+ }
1951
+ st := sc.newStream(id, 0, initialState, initialPriority)
1952
+
1953
+ if f.HasPriority() {
1954
+ if err := sc.checkPriority(f.StreamID, f.Priority); err != nil {
1955
+ return err
1956
+ }
1957
+ if !sc.writeSchedIgnoresRFC7540() {
1958
+ sc.writeSched.AdjustStream(st.id, f.Priority)
1959
+ }
1960
+ }
1961
+
1962
+ rw, req, err := sc.newWriterAndRequest(st, f)
1963
+ if err != nil {
1964
+ return err
1965
+ }
1966
+ st.reqTrailer = req.Trailer
1967
+ if st.reqTrailer != nil {
1968
+ st.trailer = make(Header)
1969
+ }
1970
+ st.body = st.reqBody.pipe // may be nil
1971
+ st.declBodyBytes = req.ContentLength
1972
+
1973
+ handler := sc.handler.ServeHTTP
1974
+ if f.Truncated {
1975
+ // Their header list was too long. Send a 431 error.
1976
+ handler = handleHeaderListTooLong
1977
+ } else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil {
1978
+ handler = serve400Handler{err}.ServeHTTP
1979
+ }
1980
+
1981
+ if sc.hs.ReadTimeout() > 0 {
1982
+ st.readDeadline = time.AfterFunc(sc.hs.ReadTimeout(), st.onReadTimeout)
1983
+ }
1984
+
1985
+ return sc.scheduleHandler(st, rw, req, handler)
1986
+ }
1987
+
1988
+ func (sc *serverConn) upgradeRequest(req *ServerRequest) {
1989
+ sc.serveG.check()
1990
+ id := uint32(1)
1991
+ sc.maxClientStreamID = id
1992
+ st := sc.newStream(id, 0, stateHalfClosedRemote, defaultRFC9218Priority(sc.priorityAware && !sc.hasIntermediary))
1993
+ st.reqTrailer = req.Trailer
1994
+ if st.reqTrailer != nil {
1995
+ st.trailer = make(Header)
1996
+ }
1997
+ rw := sc.newResponseWriter(st)
1998
+ rw.rws.req = *req
1999
+ req = &rw.rws.req
2000
+
2001
+ // This is the first request on the connection,
2002
+ // so start the handler directly rather than going
2003
+ // through scheduleHandler.
2004
+ sc.curHandlers++
2005
+ go sc.runHandler(rw, req, sc.handler.ServeHTTP)
2006
+ }
2007
+
2008
+ func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error {
2009
+ sc := st.sc
2010
+ sc.serveG.check()
2011
+ if st.gotTrailerHeader {
2012
+ return sc.countError("dup_trailers", ConnectionError(ErrCodeProtocol))
2013
+ }
2014
+ st.gotTrailerHeader = true
2015
+ if !f.StreamEnded() {
2016
+ return sc.countError("trailers_not_ended", streamError(st.id, ErrCodeProtocol))
2017
+ }
2018
+
2019
+ if len(f.PseudoFields()) > 0 {
2020
+ return sc.countError("trailers_pseudo", streamError(st.id, ErrCodeProtocol))
2021
+ }
2022
+ if f.Truncated {
2023
+ return sc.countError("trailers_too_large", streamError(st.id, ErrCodeProtocol))
2024
+ }
2025
+ if st.trailer != nil {
2026
+ for _, hf := range f.RegularFields() {
2027
+ key := sc.canonicalHeader(hf.Name)
2028
+ if !httpguts.ValidTrailerHeader(key) {
2029
+ // TODO: send more details to the peer somehow. But http2 has
2030
+ // no way to send debug data at a stream level. Discuss with
2031
+ // HTTP folk.
2032
+ return sc.countError("trailers_bogus", streamError(st.id, ErrCodeProtocol))
2033
+ }
2034
+ st.trailer[key] = append(st.trailer[key], hf.Value)
2035
+ }
2036
+ }
2037
+ st.endStream()
2038
+ return nil
2039
+ }
2040
+
2041
+ func (sc *serverConn) checkPriority(streamID uint32, p PriorityParam) error {
2042
+ if streamID == p.StreamDep {
2043
+ // Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat
2044
+ // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR."
2045
+ // Section 5.3.3 says that a stream can depend on one of its dependencies,
2046
+ // so it's only self-dependencies that are forbidden.
2047
+ return sc.countError("priority", streamError(streamID, ErrCodeProtocol))
2048
+ }
2049
+ return nil
2050
+ }
2051
+
2052
+ func (sc *serverConn) processPriority(f *PriorityFrame) error {
2053
+ if err := sc.checkPriority(f.StreamID, f.PriorityParam); err != nil {
2054
+ return err
2055
+ }
2056
+ // We need to avoid calling AdjustStream when using the RFC 9218 write
2057
+ // scheduler. Otherwise, incremental's zero value in PriorityParam will
2058
+ // unexpectedly make all streams non-incremental. This causes us to process
2059
+ // streams one-by-one to completion rather than doing it in a round-robin
2060
+ // manner (the historical behavior), which might be unexpected to users.
2061
+ if sc.writeSchedIgnoresRFC7540() {
2062
+ return nil
2063
+ }
2064
+ sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam)
2065
+ return nil
2066
+ }
2067
+
2068
+ func (sc *serverConn) processPriorityUpdate(f *PriorityUpdateFrame) error {
2069
+ sc.priorityAware = true
2070
+ if _, ok := sc.writeSched.(*priorityWriteSchedulerRFC9218); !ok {
2071
+ return nil
2072
+ }
2073
+ p, ok := parseRFC9218Priority(f.Priority, sc.priorityAware)
2074
+ if !ok {
2075
+ return sc.countError("unparsable_priority_update", streamError(f.PrioritizedStreamID, ErrCodeProtocol))
2076
+ }
2077
+ sc.writeSched.AdjustStream(f.PrioritizedStreamID, p)
2078
+ return nil
2079
+ }
2080
+
2081
+ func (sc *serverConn) newStream(id, pusherID uint32, state streamState, priority PriorityParam) *stream {
2082
+ sc.serveG.check()
2083
+ if id == 0 {
2084
+ panic("internal error: cannot create stream with id 0")
2085
+ }
2086
+
2087
+ ctx, cancelCtx := context.WithCancel(sc.baseCtx)
2088
+ st := &stream{
2089
+ sc: sc,
2090
+ id: id,
2091
+ state: state,
2092
+ ctx: ctx,
2093
+ cancelCtx: cancelCtx,
2094
+ }
2095
+ st.cw.Init()
2096
+ st.flow.conn = &sc.flow // link to conn-level counter
2097
+ st.inflow.init(sc.initialStreamRecvWindowSize)
2098
+ if writeTimeout := sc.hs.WriteTimeout(); writeTimeout > 0 {
2099
+ st.writeDeadline = time.AfterFunc(writeTimeout, st.onWriteTimeout)
2100
+ }
2101
+
2102
+ sc.streams[id] = st
2103
+ sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID, priority: priority})
2104
+ if st.isPushed() {
2105
+ sc.curPushedStreams++
2106
+ } else {
2107
+ sc.curClientStreams++
2108
+ }
2109
+ if sc.curOpenStreams() == 1 {
2110
+ sc.setConnState(ConnStateActive)
2111
+ }
2112
+
2113
+ return st
2114
+ }
2115
+
2116
+ func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *ServerRequest, error) {
2117
+ sc.serveG.check()
2118
+
2119
+ rp := httpcommon.ServerRequestParam{
2120
+ Method: f.PseudoValue("method"),
2121
+ Scheme: f.PseudoValue("scheme"),
2122
+ Authority: f.PseudoValue("authority"),
2123
+ Path: f.PseudoValue("path"),
2124
+ Protocol: f.PseudoValue("protocol"),
2125
+ }
2126
+
2127
+ // extended connect is disabled, so we should not see :protocol
2128
+ if disableExtendedConnectProtocol && rp.Protocol != "" {
2129
+ return nil, nil, sc.countError("bad_connect", streamError(f.StreamID, ErrCodeProtocol))
2130
+ }
2131
+
2132
+ isConnect := rp.Method == "CONNECT"
2133
+ if isConnect {
2134
+ if rp.Protocol == "" && (rp.Path != "" || rp.Scheme != "" || rp.Authority == "") {
2135
+ return nil, nil, sc.countError("bad_connect", streamError(f.StreamID, ErrCodeProtocol))
2136
+ }
2137
+ } else if rp.Method == "" || rp.Path == "" || (rp.Scheme != "https" && rp.Scheme != "http") {
2138
+ // See 8.1.2.6 Malformed Requests and Responses:
2139
+ //
2140
+ // Malformed requests or responses that are detected
2141
+ // MUST be treated as a stream error (Section 5.4.2)
2142
+ // of type PROTOCOL_ERROR."
2143
+ //
2144
+ // 8.1.2.3 Request Pseudo-Header Fields
2145
+ // "All HTTP/2 requests MUST include exactly one valid
2146
+ // value for the :method, :scheme, and :path
2147
+ // pseudo-header fields"
2148
+ return nil, nil, sc.countError("bad_path_method", streamError(f.StreamID, ErrCodeProtocol))
2149
+ }
2150
+
2151
+ header := make(Header)
2152
+ rp.Header = header
2153
+ for _, hf := range f.RegularFields() {
2154
+ header.Add(sc.canonicalHeader(hf.Name), hf.Value)
2155
+ }
2156
+ if rp.Authority == "" {
2157
+ rp.Authority = header.Get("Host")
2158
+ }
2159
+ if rp.Protocol != "" {
2160
+ header.Set(":protocol", rp.Protocol)
2161
+ }
2162
+
2163
+ rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
2164
+ if err != nil {
2165
+ return nil, nil, err
2166
+ }
2167
+ bodyOpen := !f.StreamEnded()
2168
+ if clens, ok := rp.Header["Content-Length"]; ok {
2169
+ if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil {
2170
+ req.ContentLength = int64(cl)
2171
+ } else {
2172
+ req.ContentLength = 0
2173
+ }
2174
+ if !bodyOpen && req.ContentLength != 0 {
2175
+ return nil, nil, sc.countError("bodyless_content_length", streamError(f.StreamID, ErrCodeProtocol))
2176
+ }
2177
+ if len(clens) > 1 {
2178
+ for _, dup := range clens[1:] {
2179
+ if clens[0] != dup {
2180
+ return nil, nil, sc.countError("duplicate_content_length", streamError(f.StreamID, ErrCodeProtocol))
2181
+ }
2182
+ }
2183
+ rp.Header["Content-Length"] = clens[:1]
2184
+ }
2185
+ }
2186
+ if bodyOpen {
2187
+ if _, ok := rp.Header["Content-Length"]; !ok {
2188
+ req.ContentLength = -1
2189
+ }
2190
+ st.reqBody.pipe = &pipe{
2191
+ b: &dataBuffer{expected: req.ContentLength},
2192
+ }
2193
+ }
2194
+ return rw, req, nil
2195
+ }
2196
+
2197
+ func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp httpcommon.ServerRequestParam) (*responseWriter, *ServerRequest, error) {
2198
+ sc.serveG.check()
2199
+
2200
+ res := httpcommon.NewServerRequest(rp)
2201
+ if res.InvalidReason != "" {
2202
+ return nil, nil, sc.countError(res.InvalidReason, streamError(st.id, ErrCodeProtocol))
2203
+ }
2204
+
2205
+ st.reqBody = &requestBody{
2206
+ conn: sc,
2207
+ stream: st,
2208
+ needsContinue: res.NeedsContinue,
2209
+ }
2210
+ rw := sc.newResponseWriter(st)
2211
+ rw.rws.req = ServerRequest{
2212
+ Context: st.ctx,
2213
+ Method: rp.Method,
2214
+ URL: res.URL,
2215
+ RemoteAddr: sc.remoteAddrStr,
2216
+ Header: rp.Header,
2217
+ RequestURI: res.RequestURI,
2218
+ Proto: "HTTP/2.0",
2219
+ ProtoMajor: 2,
2220
+ ProtoMinor: 0,
2221
+ TLS: sc.tlsState,
2222
+ Host: rp.Authority,
2223
+ Body: st.reqBody,
2224
+ Trailer: res.Trailer,
2225
+ }
2226
+ return rw, &rw.rws.req, nil
2227
+ }
2228
+
2229
+ func (sc *serverConn) newResponseWriter(st *stream) *responseWriter {
2230
+ rws := responseWriterStatePool.Get().(*responseWriterState)
2231
+ bwSave := rws.bw
2232
+ *rws = responseWriterState{} // zero all the fields
2233
+ rws.conn = sc
2234
+ rws.bw = bwSave
2235
+ rws.bw.Reset(chunkWriter{rws})
2236
+ rws.stream = st
2237
+ return &responseWriter{rws: rws}
2238
+ }
2239
+
2240
+ type unstartedHandler struct {
2241
+ streamID uint32
2242
+ rw *responseWriter
2243
+ req *ServerRequest
2244
+ handler func(*ResponseWriter, *ServerRequest)
2245
+ body *pipe
2246
+ }
2247
+
2248
+ // scheduleHandler starts a handler goroutine,
2249
+ // or schedules one to start as soon as an existing handler finishes.
2250
+ func (sc *serverConn) scheduleHandler(st *stream, rw *responseWriter, req *ServerRequest, handler func(*ResponseWriter, *ServerRequest)) error {
2251
+ sc.serveG.check()
2252
+ maxHandlers := sc.advMaxStreams
2253
+ if sc.curHandlers < maxHandlers {
2254
+ sc.curHandlers++
2255
+ go sc.runHandler(rw, req, handler)
2256
+ return nil
2257
+ }
2258
+ if len(sc.unstartedHandlers) > int(4*sc.advMaxStreams) {
2259
+ return sc.countError("too_many_early_resets", ConnectionError(ErrCodeEnhanceYourCalm))
2260
+ }
2261
+ sc.unstartedHandlers = append(sc.unstartedHandlers, unstartedHandler{
2262
+ streamID: st.id,
2263
+ rw: rw,
2264
+ req: req,
2265
+ handler: handler,
2266
+ body: st.body,
2267
+ })
2268
+ return nil
2269
+ }
2270
+
2271
+ func (sc *serverConn) handlerDone() {
2272
+ sc.serveG.check()
2273
+ sc.curHandlers--
2274
+ i := 0
2275
+ maxHandlers := sc.advMaxStreams
2276
+ for ; i < len(sc.unstartedHandlers); i++ {
2277
+ u := sc.unstartedHandlers[i]
2278
+ if sc.streams[u.streamID] == nil {
2279
+ // This stream was reset before its goroutine had a chance to start.
2280
+ if u.body != nil {
2281
+ u.body.BreakWithError(errClosedBody)
2282
+ sc.sendWindowUpdate(nil, u.body.Len())
2283
+ }
2284
+ continue
2285
+ }
2286
+ if sc.curHandlers >= maxHandlers {
2287
+ break
2288
+ }
2289
+ sc.curHandlers++
2290
+ go sc.runHandler(u.rw, u.req, u.handler)
2291
+ sc.unstartedHandlers[i] = unstartedHandler{} // don't retain references
2292
+ }
2293
+ sc.unstartedHandlers = sc.unstartedHandlers[i:]
2294
+ if len(sc.unstartedHandlers) == 0 {
2295
+ sc.unstartedHandlers = nil
2296
+ }
2297
+ }
2298
+
2299
+ // Run on its own goroutine.
2300
+ func (sc *serverConn) runHandler(rw *responseWriter, req *ServerRequest, handler func(*ResponseWriter, *ServerRequest)) {
2301
+ defer sc.sendServeMsg(handlerDoneMsg)
2302
+ didPanic := true
2303
+ defer func() {
2304
+ rw.rws.stream.cancelCtx()
2305
+ if req.MultipartForm != nil {
2306
+ req.MultipartForm.RemoveAll()
2307
+ }
2308
+ if b := rw.rws.stream.reqBody; b != nil {
2309
+ // Closing the body refunds flow control credit for any unconsumed data.
2310
+ // (reqBody is nil for Upgrade: h2c requests, but those do not use flow
2311
+ // control for the request body.)
2312
+ b.Close()
2313
+ }
2314
+ if didPanic {
2315
+ e := recover()
2316
+ sc.writeFrameFromHandler(FrameWriteRequest{
2317
+ write: handlerPanicRST{rw.rws.stream.id},
2318
+ stream: rw.rws.stream,
2319
+ })
2320
+ // Same as net/http:
2321
+ if e != nil && e != ErrAbortHandler {
2322
+ const size = 64 << 10
2323
+ buf := make([]byte, size)
2324
+ buf = buf[:runtime.Stack(buf, false)]
2325
+ sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
2326
+ }
2327
+ return
2328
+ }
2329
+ rw.handlerDone()
2330
+ }()
2331
+ handler(rw, req)
2332
+ didPanic = false
2333
+ }
2334
+
2335
+ func handleHeaderListTooLong(w *ResponseWriter, r *ServerRequest) {
2336
+ // 10.5.1 Limits on Header Block Size:
2337
+ // .. "A server that receives a larger header block than it is
2338
+ // willing to handle can send an HTTP 431 (Request Header Fields Too
2339
+ // Large) status code"
2340
+ const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
2341
+ w.WriteHeader(statusRequestHeaderFieldsTooLarge)
2342
+ io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
2343
+ }
2344
+
2345
+ // called from handler goroutines.
2346
+ // h may be nil.
2347
+ func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
2348
+ sc.serveG.checkNotOn() // NOT on
2349
+ var errc chan error
2350
+ if headerData.h != nil {
2351
+ // If there's a header map (which we don't own), so we have to block on
2352
+ // waiting for this frame to be written, so an http.Flush mid-handler
2353
+ // writes out the correct value of keys, before a handler later potentially
2354
+ // mutates it.
2355
+ errc = sc.srv.getErrChan()
2356
+ }
2357
+ if err := sc.writeFrameFromHandler(FrameWriteRequest{
2358
+ write: headerData,
2359
+ stream: st,
2360
+ done: errc,
2361
+ }); err != nil {
2362
+ return err
2363
+ }
2364
+ if errc != nil {
2365
+ select {
2366
+ case err := <-errc:
2367
+ sc.srv.putErrChan(errc)
2368
+ return err
2369
+ case <-sc.doneServing:
2370
+ return errClientDisconnected
2371
+ case <-st.cw:
2372
+ return errStreamClosed
2373
+ }
2374
+ }
2375
+ return nil
2376
+ }
2377
+
2378
+ // called from handler goroutines.
2379
+ func (sc *serverConn) write100ContinueHeaders(st *stream) {
2380
+ sc.writeFrameFromHandler(FrameWriteRequest{
2381
+ write: write100ContinueHeadersFrame{st.id},
2382
+ stream: st,
2383
+ })
2384
+ }
2385
+
2386
+ // A bodyReadMsg tells the server loop that the http.Handler read n
2387
+ // bytes of the DATA from the client on the given stream.
2388
+ type bodyReadMsg struct {
2389
+ st *stream
2390
+ n int
2391
+ }
2392
+
2393
+ // called from handler goroutines.
2394
+ // Notes that the handler for the given stream ID read n bytes of its body
2395
+ // and schedules flow control tokens to be sent.
2396
+ func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) {
2397
+ sc.serveG.checkNotOn() // NOT on
2398
+ if n > 0 {
2399
+ select {
2400
+ case sc.bodyReadCh <- bodyReadMsg{st, n}:
2401
+ case <-sc.doneServing:
2402
+ }
2403
+ }
2404
+ }
2405
+
2406
+ func (sc *serverConn) noteBodyRead(st *stream, n int) {
2407
+ sc.serveG.check()
2408
+ sc.sendWindowUpdate(nil, n) // conn-level
2409
+ if st != nil && st.state != stateHalfClosedRemote && st.state != stateClosed {
2410
+ // Don't send this WINDOW_UPDATE if the stream is closed
2411
+ // remotely.
2412
+ sc.sendWindowUpdate(st, n)
2413
+ }
2414
+ }
2415
+
2416
+ // st may be nil for conn-level
2417
+ func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
2418
+ sc.sendWindowUpdate(st, int(n))
2419
+ }
2420
+
2421
+ // st may be nil for conn-level
2422
+ func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
2423
+ sc.serveG.check()
2424
+ var streamID uint32
2425
+ var send int32
2426
+ if st == nil {
2427
+ send = sc.inflow.add(n)
2428
+ } else {
2429
+ streamID = st.id
2430
+ send = st.inflow.add(n)
2431
+ }
2432
+ if send == 0 {
2433
+ return
2434
+ }
2435
+ sc.writeFrame(FrameWriteRequest{
2436
+ write: writeWindowUpdate{streamID: streamID, n: uint32(send)},
2437
+ stream: st,
2438
+ })
2439
+ }
2440
+
2441
+ // requestBody is the Handler's Request.Body type.
2442
+ // Read and Close may be called concurrently.
2443
+ type requestBody struct {
2444
+ _ incomparable
2445
+ stream *stream
2446
+ conn *serverConn
2447
+ closeOnce sync.Once // for use by Close only
2448
+ sawEOF bool // for use by Read only
2449
+ pipe *pipe // non-nil if we have an HTTP entity message body
2450
+ needsContinue bool // need to send a 100-continue
2451
+ }
2452
+
2453
+ func (b *requestBody) Close() error {
2454
+ b.closeOnce.Do(func() {
2455
+ if b.pipe != nil {
2456
+ b.pipe.BreakWithError(errClosedBody)
2457
+ if unread := b.pipe.Len(); unread > 0 {
2458
+ b.conn.noteBodyReadFromHandler(nil, unread, errClosedBody)
2459
+ }
2460
+ }
2461
+ })
2462
+ return nil
2463
+ }
2464
+
2465
+ func (b *requestBody) Read(p []byte) (n int, err error) {
2466
+ if b.needsContinue {
2467
+ b.needsContinue = false
2468
+ b.conn.write100ContinueHeaders(b.stream)
2469
+ }
2470
+ if b.pipe == nil || b.sawEOF {
2471
+ return 0, io.EOF
2472
+ }
2473
+ n, err = b.pipe.Read(p)
2474
+ if err == io.EOF {
2475
+ b.sawEOF = true
2476
+ }
2477
+ b.conn.noteBodyReadFromHandler(b.stream, n, err)
2478
+ return
2479
+ }
2480
+
2481
+ // responseWriter is the http.ResponseWriter implementation. It's
2482
+ // intentionally small (1 pointer wide) to minimize garbage. The
2483
+ // responseWriterState pointer inside is zeroed at the end of a
2484
+ // request (in handlerDone) and calls on the responseWriter thereafter
2485
+ // simply crash (caller's mistake), but the much larger responseWriterState
2486
+ // and buffers are reused between multiple requests.
2487
+ type responseWriter struct {
2488
+ rws *responseWriterState
2489
+ }
2490
+
2491
+ type responseWriterState struct {
2492
+ // immutable within a request:
2493
+ stream *stream
2494
+ req ServerRequest
2495
+ conn *serverConn
2496
+
2497
+ // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
2498
+ bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
2499
+
2500
+ // mutated by http.Handler goroutine:
2501
+ handlerHeader Header // nil until called
2502
+ snapHeader Header // snapshot of handlerHeader at WriteHeader time
2503
+ trailers []string // set in writeChunk
2504
+ status int // status code passed to WriteHeader
2505
+ wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
2506
+ sentHeader bool // have we sent the header frame?
2507
+ handlerDone bool // handler has finished
2508
+
2509
+ sentContentLen int64 // non-zero if handler set a Content-Length header
2510
+ wroteBytes int64
2511
+
2512
+ closeNotifierMu sync.Mutex // guards closeNotifierCh
2513
+ closeNotifierCh chan bool // nil until first used
2514
+ }
2515
+
2516
+ type chunkWriter struct{ rws *responseWriterState }
2517
+
2518
+ func (cw chunkWriter) Write(p []byte) (n int, err error) {
2519
+ n, err = cw.rws.writeChunk(p)
2520
+ if err == errStreamClosed {
2521
+ // If writing failed because the stream has been closed,
2522
+ // return the reason it was closed.
2523
+ err = cw.rws.stream.closeErr
2524
+ }
2525
+ return n, err
2526
+ }
2527
+
2528
+ func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) > 0 }
2529
+
2530
+ func (rws *responseWriterState) hasNonemptyTrailers() bool {
2531
+ for _, trailer := range rws.trailers {
2532
+ if _, ok := rws.handlerHeader[trailer]; ok {
2533
+ return true
2534
+ }
2535
+ }
2536
+ return false
2537
+ }
2538
+
2539
+ // declareTrailer is called for each Trailer header when the
2540
+ // response header is written. It notes that a header will need to be
2541
+ // written in the trailers at the end of the response.
2542
+ func (rws *responseWriterState) declareTrailer(k string) {
2543
+ k = textproto.CanonicalMIMEHeaderKey(k)
2544
+ if !httpguts.ValidTrailerHeader(k) {
2545
+ // Forbidden by RFC 7230, section 4.1.2.
2546
+ rws.conn.logf("ignoring invalid trailer %q", k)
2547
+ return
2548
+ }
2549
+ if !slices.Contains(rws.trailers, k) {
2550
+ rws.trailers = append(rws.trailers, k)
2551
+ }
2552
+ }
2553
+
2554
+ const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" // keep in sync with net/http
2555
+
2556
+ // writeChunk writes chunks from the bufio.Writer. But because
2557
+ // bufio.Writer may bypass its chunking, sometimes p may be
2558
+ // arbitrarily large.
2559
+ //
2560
+ // writeChunk is also responsible (on the first chunk) for sending the
2561
+ // HEADER response.
2562
+ func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
2563
+ if !rws.wroteHeader {
2564
+ rws.writeHeader(200)
2565
+ }
2566
+
2567
+ if rws.handlerDone {
2568
+ rws.promoteUndeclaredTrailers()
2569
+ }
2570
+
2571
+ isHeadResp := rws.req.Method == "HEAD"
2572
+ if !rws.sentHeader {
2573
+ rws.sentHeader = true
2574
+ var ctype, clen string
2575
+ if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
2576
+ rws.snapHeader.Del("Content-Length")
2577
+ if cl, err := strconv.ParseUint(clen, 10, 63); err == nil {
2578
+ rws.sentContentLen = int64(cl)
2579
+ } else {
2580
+ clen = ""
2581
+ }
2582
+ }
2583
+ _, hasContentLength := rws.snapHeader["Content-Length"]
2584
+ if !hasContentLength && clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
2585
+ clen = strconv.Itoa(len(p))
2586
+ }
2587
+ _, hasContentType := rws.snapHeader["Content-Type"]
2588
+ // If the Content-Encoding is non-blank, we shouldn't
2589
+ // sniff the body. See Issue golang.org/issue/31753.
2590
+ ce := rws.snapHeader.Get("Content-Encoding")
2591
+ hasCE := len(ce) > 0
2592
+ if !hasCE && !hasContentType && bodyAllowedForStatus(rws.status) && len(p) > 0 {
2593
+ ctype = internal.DetectContentType(p)
2594
+ }
2595
+ var date string
2596
+ if _, ok := rws.snapHeader["Date"]; !ok {
2597
+ // TODO(bradfitz): be faster here, like net/http? measure.
2598
+ date = time.Now().UTC().Format(TimeFormat)
2599
+ }
2600
+
2601
+ for _, v := range rws.snapHeader["Trailer"] {
2602
+ foreachHeaderElement(v, rws.declareTrailer)
2603
+ }
2604
+
2605
+ // "Connection" headers aren't allowed in HTTP/2 (RFC 7540, 8.1.2.2),
2606
+ // but respect "Connection" == "close" to mean sending a GOAWAY and tearing
2607
+ // down the TCP connection when idle, like we do for HTTP/1.
2608
+ // TODO: remove more Connection-specific header fields here, in addition
2609
+ // to "Connection".
2610
+ if _, ok := rws.snapHeader["Connection"]; ok {
2611
+ v := rws.snapHeader.Get("Connection")
2612
+ delete(rws.snapHeader, "Connection")
2613
+ if v == "close" {
2614
+ rws.conn.startGracefulShutdown()
2615
+ }
2616
+ }
2617
+
2618
+ endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
2619
+ err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
2620
+ streamID: rws.stream.id,
2621
+ httpResCode: rws.status,
2622
+ h: rws.snapHeader,
2623
+ endStream: endStream,
2624
+ contentType: ctype,
2625
+ contentLength: clen,
2626
+ date: date,
2627
+ })
2628
+ if err != nil {
2629
+ return 0, err
2630
+ }
2631
+ if endStream {
2632
+ return 0, nil
2633
+ }
2634
+ }
2635
+ if isHeadResp {
2636
+ return len(p), nil
2637
+ }
2638
+ if len(p) == 0 && !rws.handlerDone {
2639
+ return 0, nil
2640
+ }
2641
+
2642
+ // only send trailers if they have actually been defined by the
2643
+ // server handler.
2644
+ hasNonemptyTrailers := rws.hasNonemptyTrailers()
2645
+ endStream := rws.handlerDone && !hasNonemptyTrailers
2646
+ if len(p) > 0 || endStream {
2647
+ // only send a 0 byte DATA frame if we're ending the stream.
2648
+ if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
2649
+ return 0, err
2650
+ }
2651
+ }
2652
+
2653
+ if rws.handlerDone && hasNonemptyTrailers {
2654
+ err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
2655
+ streamID: rws.stream.id,
2656
+ h: rws.handlerHeader,
2657
+ trailers: rws.trailers,
2658
+ endStream: true,
2659
+ })
2660
+ return len(p), err
2661
+ }
2662
+ return len(p), nil
2663
+ }
2664
+
2665
+ // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
2666
+ // that, if present, signals that the map entry is actually for
2667
+ // the response trailers, and not the response headers. The prefix
2668
+ // is stripped after the ServeHTTP call finishes and the values are
2669
+ // sent in the trailers.
2670
+ //
2671
+ // This mechanism is intended only for trailers that are not known
2672
+ // prior to the headers being written. If the set of trailers is fixed
2673
+ // or known before the header is written, the normal Go trailers mechanism
2674
+ // is preferred:
2675
+ //
2676
+ // https://golang.org/pkg/net/http/#ResponseWriter
2677
+ // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
2678
+ const TrailerPrefix = "Trailer:"
2679
+
2680
+ // promoteUndeclaredTrailers permits http.Handlers to set trailers
2681
+ // after the header has already been flushed. Because the Go
2682
+ // ResponseWriter interface has no way to set Trailers (only the
2683
+ // Header), and because we didn't want to expand the ResponseWriter
2684
+ // interface, and because nobody used trailers, and because RFC 7230
2685
+ // says you SHOULD (but not must) predeclare any trailers in the
2686
+ // header, the official ResponseWriter rules said trailers in Go must
2687
+ // be predeclared, and then we reuse the same ResponseWriter.Header()
2688
+ // map to mean both Headers and Trailers. When it's time to write the
2689
+ // Trailers, we pick out the fields of Headers that were declared as
2690
+ // trailers. That worked for a while, until we found the first major
2691
+ // user of Trailers in the wild: gRPC (using them only over http2),
2692
+ // and gRPC libraries permit setting trailers mid-stream without
2693
+ // predeclaring them. So: change of plans. We still permit the old
2694
+ // way, but we also permit this hack: if a Header() key begins with
2695
+ // "Trailer:", the suffix of that key is a Trailer. Because ':' is an
2696
+ // invalid token byte anyway, there is no ambiguity. (And it's already
2697
+ // filtered out) It's mildly hacky, but not terrible.
2698
+ //
2699
+ // This method runs after the Handler is done and promotes any Header
2700
+ // fields to be trailers.
2701
+ func (rws *responseWriterState) promoteUndeclaredTrailers() {
2702
+ for k, vv := range rws.handlerHeader {
2703
+ if !strings.HasPrefix(k, TrailerPrefix) {
2704
+ continue
2705
+ }
2706
+ trailerKey := strings.TrimPrefix(k, TrailerPrefix)
2707
+ rws.declareTrailer(trailerKey)
2708
+ rws.handlerHeader[textproto.CanonicalMIMEHeaderKey(trailerKey)] = vv
2709
+ }
2710
+
2711
+ if len(rws.trailers) > 1 {
2712
+ slices.Sort(rws.trailers)
2713
+ }
2714
+ }
2715
+
2716
+ func (w *responseWriter) SetReadDeadline(deadline time.Time) error {
2717
+ st := w.rws.stream
2718
+ if !deadline.IsZero() && deadline.Before(time.Now()) {
2719
+ // If we're setting a deadline in the past, reset the stream immediately
2720
+ // so writes after SetWriteDeadline returns will fail.
2721
+ st.onReadTimeout()
2722
+ return nil
2723
+ }
2724
+ w.rws.conn.sendServeMsg(func(sc *serverConn) {
2725
+ if st.readDeadline != nil {
2726
+ if !st.readDeadline.Stop() {
2727
+ // Deadline already exceeded, or stream has been closed.
2728
+ return
2729
+ }
2730
+ }
2731
+ if deadline.IsZero() {
2732
+ st.readDeadline = nil
2733
+ } else if st.readDeadline == nil {
2734
+ st.readDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onReadTimeout)
2735
+ } else {
2736
+ st.readDeadline.Reset(deadline.Sub(time.Now()))
2737
+ }
2738
+ })
2739
+ return nil
2740
+ }
2741
+
2742
+ func (w *responseWriter) SetWriteDeadline(deadline time.Time) error {
2743
+ st := w.rws.stream
2744
+ if !deadline.IsZero() && deadline.Before(time.Now()) {
2745
+ // If we're setting a deadline in the past, reset the stream immediately
2746
+ // so writes after SetWriteDeadline returns will fail.
2747
+ st.onWriteTimeout()
2748
+ return nil
2749
+ }
2750
+ w.rws.conn.sendServeMsg(func(sc *serverConn) {
2751
+ if st.writeDeadline != nil {
2752
+ if !st.writeDeadline.Stop() {
2753
+ // Deadline already exceeded, or stream has been closed.
2754
+ return
2755
+ }
2756
+ }
2757
+ if deadline.IsZero() {
2758
+ st.writeDeadline = nil
2759
+ } else if st.writeDeadline == nil {
2760
+ st.writeDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onWriteTimeout)
2761
+ } else {
2762
+ st.writeDeadline.Reset(deadline.Sub(time.Now()))
2763
+ }
2764
+ })
2765
+ return nil
2766
+ }
2767
+
2768
+ func (w *responseWriter) EnableFullDuplex() error {
2769
+ // We always support full duplex responses, so this is a no-op.
2770
+ return nil
2771
+ }
2772
+
2773
+ func (w *responseWriter) Flush() {
2774
+ w.FlushError()
2775
+ }
2776
+
2777
+ func (w *responseWriter) FlushError() error {
2778
+ rws := w.rws
2779
+ if rws == nil {
2780
+ panic("Header called after Handler finished")
2781
+ }
2782
+ var err error
2783
+ if rws.bw.Buffered() > 0 {
2784
+ err = rws.bw.Flush()
2785
+ } else {
2786
+ // The bufio.Writer won't call chunkWriter.Write
2787
+ // (writeChunk with zero bytes), so we have to do it
2788
+ // ourselves to force the HTTP response header and/or
2789
+ // final DATA frame (with END_STREAM) to be sent.
2790
+ _, err = chunkWriter{rws}.Write(nil)
2791
+ if err == nil {
2792
+ select {
2793
+ case <-rws.stream.cw:
2794
+ err = rws.stream.closeErr
2795
+ default:
2796
+ }
2797
+ }
2798
+ }
2799
+ return err
2800
+ }
2801
+
2802
+ func (w *responseWriter) CloseNotify() <-chan bool {
2803
+ rws := w.rws
2804
+ if rws == nil {
2805
+ panic("CloseNotify called after Handler finished")
2806
+ }
2807
+ rws.closeNotifierMu.Lock()
2808
+ ch := rws.closeNotifierCh
2809
+ if ch == nil {
2810
+ ch = make(chan bool, 1)
2811
+ rws.closeNotifierCh = ch
2812
+ cw := rws.stream.cw
2813
+ go func() {
2814
+ cw.Wait() // wait for close
2815
+ ch <- true
2816
+ }()
2817
+ }
2818
+ rws.closeNotifierMu.Unlock()
2819
+ return ch
2820
+ }
2821
+
2822
+ func (w *responseWriter) Header() Header {
2823
+ rws := w.rws
2824
+ if rws == nil {
2825
+ panic("Header called after Handler finished")
2826
+ }
2827
+ if rws.handlerHeader == nil {
2828
+ rws.handlerHeader = make(Header)
2829
+ }
2830
+ return rws.handlerHeader
2831
+ }
2832
+
2833
+ // checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode.
2834
+ func checkWriteHeaderCode(code int) {
2835
+ // Issue 22880: require valid WriteHeader status codes.
2836
+ // For now we only enforce that it's three digits.
2837
+ // In the future we might block things over 599 (600 and above aren't defined
2838
+ // at http://httpwg.org/specs/rfc7231.html#status.codes).
2839
+ // But for now any three digits.
2840
+ //
2841
+ // We used to send "HTTP/1.1 000 0" on the wire in responses but there's
2842
+ // no equivalent bogus thing we can realistically send in HTTP/2,
2843
+ // so we'll consistently panic instead and help people find their bugs
2844
+ // early. (We can't return an error from WriteHeader even if we wanted to.)
2845
+ if code < 100 || code > 999 {
2846
+ panic(fmt.Sprintf("invalid WriteHeader code %v", code))
2847
+ }
2848
+ }
2849
+
2850
+ func (w *responseWriter) WriteHeader(code int) {
2851
+ rws := w.rws
2852
+ if rws == nil {
2853
+ panic("WriteHeader called after Handler finished")
2854
+ }
2855
+ rws.writeHeader(code)
2856
+ }
2857
+
2858
+ func (rws *responseWriterState) writeHeader(code int) {
2859
+ if rws.wroteHeader {
2860
+ return
2861
+ }
2862
+
2863
+ checkWriteHeaderCode(code)
2864
+
2865
+ // Handle informational headers
2866
+ if code >= 100 && code <= 199 {
2867
+ // Per RFC 8297 we must not clear the current header map
2868
+ h := rws.handlerHeader
2869
+
2870
+ _, cl := h["Content-Length"]
2871
+ _, te := h["Transfer-Encoding"]
2872
+ if cl || te {
2873
+ h = cloneHeader(h)
2874
+ h.Del("Content-Length")
2875
+ h.Del("Transfer-Encoding")
2876
+ }
2877
+
2878
+ rws.conn.writeHeaders(rws.stream, &writeResHeaders{
2879
+ streamID: rws.stream.id,
2880
+ httpResCode: code,
2881
+ h: h,
2882
+ endStream: rws.handlerDone && !rws.hasTrailers(),
2883
+ })
2884
+
2885
+ return
2886
+ }
2887
+
2888
+ rws.wroteHeader = true
2889
+ rws.status = code
2890
+ if len(rws.handlerHeader) > 0 {
2891
+ rws.snapHeader = cloneHeader(rws.handlerHeader)
2892
+ }
2893
+ }
2894
+
2895
+ func cloneHeader(h Header) Header {
2896
+ h2 := make(Header, len(h))
2897
+ for k, vv := range h {
2898
+ vv2 := make([]string, len(vv))
2899
+ copy(vv2, vv)
2900
+ h2[k] = vv2
2901
+ }
2902
+ return h2
2903
+ }
2904
+
2905
+ // The Life Of A Write is like this:
2906
+ //
2907
+ // * Handler calls w.Write or w.WriteString ->
2908
+ // * -> rws.bw (*bufio.Writer) ->
2909
+ // * (Handler might call Flush)
2910
+ // * -> chunkWriter{rws}
2911
+ // * -> responseWriterState.writeChunk(p []byte)
2912
+ // * -> responseWriterState.writeChunk (most of the magic; see comment there)
2913
+ func (w *responseWriter) Write(p []byte) (n int, err error) {
2914
+ return w.write(len(p), p, "")
2915
+ }
2916
+
2917
+ func (w *responseWriter) WriteString(s string) (n int, err error) {
2918
+ return w.write(len(s), nil, s)
2919
+ }
2920
+
2921
+ // either dataB or dataS is non-zero.
2922
+ func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
2923
+ rws := w.rws
2924
+ if rws == nil {
2925
+ panic("Write called after Handler finished")
2926
+ }
2927
+ if !rws.wroteHeader {
2928
+ w.WriteHeader(200)
2929
+ }
2930
+ if !bodyAllowedForStatus(rws.status) {
2931
+ return 0, ErrBodyNotAllowed
2932
+ }
2933
+ rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
2934
+ if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
2935
+ // TODO: send a RST_STREAM
2936
+ return 0, errors.New("http2: handler wrote more than declared Content-Length")
2937
+ }
2938
+
2939
+ if dataB != nil {
2940
+ return rws.bw.Write(dataB)
2941
+ } else {
2942
+ return rws.bw.WriteString(dataS)
2943
+ }
2944
+ }
2945
+
2946
+ func (w *responseWriter) handlerDone() {
2947
+ rws := w.rws
2948
+ rws.handlerDone = true
2949
+ w.Flush()
2950
+ w.rws = nil
2951
+ responseWriterStatePool.Put(rws)
2952
+ }
2953
+
2954
+ // Push errors.
2955
+ var (
2956
+ ErrRecursivePush = errors.New("http2: recursive push not allowed")
2957
+ ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
2958
+ )
2959
+
2960
+ func (w *responseWriter) Push(target, method string, header Header) error {
2961
+ st := w.rws.stream
2962
+ sc := st.sc
2963
+ sc.serveG.checkNotOn()
2964
+
2965
+ // No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream."
2966
+ // http://tools.ietf.org/html/rfc7540#section-6.6
2967
+ if st.isPushed() {
2968
+ return ErrRecursivePush
2969
+ }
2970
+
2971
+ // Default options.
2972
+ if method == "" {
2973
+ method = "GET"
2974
+ }
2975
+ if header == nil {
2976
+ header = Header{}
2977
+ }
2978
+ wantScheme := "http"
2979
+ if w.rws.req.TLS != nil {
2980
+ wantScheme = "https"
2981
+ }
2982
+
2983
+ // Validate the request.
2984
+ u, err := url.Parse(target)
2985
+ if err != nil {
2986
+ return err
2987
+ }
2988
+ if u.Scheme == "" {
2989
+ if !strings.HasPrefix(target, "/") {
2990
+ return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
2991
+ }
2992
+ u.Scheme = wantScheme
2993
+ u.Host = w.rws.req.Host
2994
+ } else {
2995
+ if u.Scheme != wantScheme {
2996
+ return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
2997
+ }
2998
+ if u.Host == "" {
2999
+ return errors.New("URL must have a host")
3000
+ }
3001
+ }
3002
+ for k := range header {
3003
+ if strings.HasPrefix(k, ":") {
3004
+ return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
3005
+ }
3006
+ // These headers are meaningful only if the request has a body,
3007
+ // but PUSH_PROMISE requests cannot have a body.
3008
+ // http://tools.ietf.org/html/rfc7540#section-8.2
3009
+ // Also disallow Host, since the promised URL must be absolute.
3010
+ if asciiEqualFold(k, "content-length") ||
3011
+ asciiEqualFold(k, "content-encoding") ||
3012
+ asciiEqualFold(k, "trailer") ||
3013
+ asciiEqualFold(k, "te") ||
3014
+ asciiEqualFold(k, "expect") ||
3015
+ asciiEqualFold(k, "host") {
3016
+ return fmt.Errorf("promised request headers cannot include %q", k)
3017
+ }
3018
+ }
3019
+ if err := checkValidHTTP2RequestHeaders(header); err != nil {
3020
+ return err
3021
+ }
3022
+
3023
+ // The RFC effectively limits promised requests to GET and HEAD:
3024
+ // "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]"
3025
+ // http://tools.ietf.org/html/rfc7540#section-8.2
3026
+ if method != "GET" && method != "HEAD" {
3027
+ return fmt.Errorf("method %q must be GET or HEAD", method)
3028
+ }
3029
+
3030
+ msg := &startPushRequest{
3031
+ parent: st,
3032
+ method: method,
3033
+ url: u,
3034
+ header: cloneHeader(header),
3035
+ done: sc.srv.getErrChan(),
3036
+ }
3037
+
3038
+ select {
3039
+ case <-sc.doneServing:
3040
+ return errClientDisconnected
3041
+ case <-st.cw:
3042
+ return errStreamClosed
3043
+ case sc.serveMsgCh <- msg:
3044
+ }
3045
+
3046
+ select {
3047
+ case <-sc.doneServing:
3048
+ return errClientDisconnected
3049
+ case <-st.cw:
3050
+ return errStreamClosed
3051
+ case err := <-msg.done:
3052
+ sc.srv.putErrChan(msg.done)
3053
+ return err
3054
+ }
3055
+ }
3056
+
3057
+ type startPushRequest struct {
3058
+ parent *stream
3059
+ method string
3060
+ url *url.URL
3061
+ header Header
3062
+ done chan error
3063
+ }
3064
+
3065
+ func (sc *serverConn) startPush(msg *startPushRequest) {
3066
+ sc.serveG.check()
3067
+
3068
+ // http://tools.ietf.org/html/rfc7540#section-6.6.
3069
+ // PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that
3070
+ // is in either the "open" or "half-closed (remote)" state.
3071
+ if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote {
3072
+ // responseWriter.Push checks that the stream is peer-initiated.
3073
+ msg.done <- errStreamClosed
3074
+ return
3075
+ }
3076
+
3077
+ // http://tools.ietf.org/html/rfc7540#section-6.6.
3078
+ if !sc.pushEnabled {
3079
+ msg.done <- ErrNotSupported
3080
+ return
3081
+ }
3082
+
3083
+ // PUSH_PROMISE frames must be sent in increasing order by stream ID, so
3084
+ // we allocate an ID for the promised stream lazily, when the PUSH_PROMISE
3085
+ // is written. Once the ID is allocated, we start the request handler.
3086
+ allocatePromisedID := func() (uint32, error) {
3087
+ sc.serveG.check()
3088
+
3089
+ // Check this again, just in case. Technically, we might have received
3090
+ // an updated SETTINGS by the time we got around to writing this frame.
3091
+ if !sc.pushEnabled {
3092
+ return 0, ErrNotSupported
3093
+ }
3094
+ // http://tools.ietf.org/html/rfc7540#section-6.5.2.
3095
+ if sc.curPushedStreams+1 > sc.clientMaxStreams {
3096
+ return 0, ErrPushLimitReached
3097
+ }
3098
+
3099
+ // http://tools.ietf.org/html/rfc7540#section-5.1.1.
3100
+ // Streams initiated by the server MUST use even-numbered identifiers.
3101
+ // A server that is unable to establish a new stream identifier can send a GOAWAY
3102
+ // frame so that the client is forced to open a new connection for new streams.
3103
+ if sc.maxPushPromiseID+2 >= 1<<31 {
3104
+ sc.startGracefulShutdownInternal()
3105
+ return 0, ErrPushLimitReached
3106
+ }
3107
+ sc.maxPushPromiseID += 2
3108
+ promisedID := sc.maxPushPromiseID
3109
+
3110
+ // http://tools.ietf.org/html/rfc7540#section-8.2.
3111
+ // Strictly speaking, the new stream should start in "reserved (local)", then
3112
+ // transition to "half closed (remote)" after sending the initial HEADERS, but
3113
+ // we start in "half closed (remote)" for simplicity.
3114
+ // See further comments at the definition of stateHalfClosedRemote.
3115
+ promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote, defaultRFC9218Priority(sc.priorityAware && !sc.hasIntermediary))
3116
+ rw, req, err := sc.newWriterAndRequestNoBody(promised, httpcommon.ServerRequestParam{
3117
+ Method: msg.method,
3118
+ Scheme: msg.url.Scheme,
3119
+ Authority: msg.url.Host,
3120
+ Path: msg.url.RequestURI(),
3121
+ Header: cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE
3122
+ })
3123
+ if err != nil {
3124
+ // Should not happen, since we've already validated msg.url.
3125
+ panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
3126
+ }
3127
+
3128
+ sc.curHandlers++
3129
+ go sc.runHandler(rw, req, sc.handler.ServeHTTP)
3130
+ return promisedID, nil
3131
+ }
3132
+
3133
+ sc.writeFrame(FrameWriteRequest{
3134
+ write: &writePushPromise{
3135
+ streamID: msg.parent.id,
3136
+ method: msg.method,
3137
+ url: msg.url,
3138
+ h: msg.header,
3139
+ allocatePromisedID: allocatePromisedID,
3140
+ },
3141
+ stream: msg.parent,
3142
+ done: msg.done,
3143
+ })
3144
+ }
3145
+
3146
+ // foreachHeaderElement splits v according to the "#rule" construction
3147
+ // in RFC 7230 section 7 and calls fn for each non-empty element.
3148
+ func foreachHeaderElement(v string, fn func(string)) {
3149
+ v = textproto.TrimString(v)
3150
+ if v == "" {
3151
+ return
3152
+ }
3153
+ if !strings.Contains(v, ",") {
3154
+ fn(v)
3155
+ return
3156
+ }
3157
+ for f := range strings.SplitSeq(v, ",") {
3158
+ if f = textproto.TrimString(f); f != "" {
3159
+ fn(f)
3160
+ }
3161
+ }
3162
+ }
3163
+
3164
+ // From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
3165
+ var connHeaders = []string{
3166
+ "Connection",
3167
+ "Keep-Alive",
3168
+ "Proxy-Connection",
3169
+ "Transfer-Encoding",
3170
+ "Upgrade",
3171
+ }
3172
+
3173
+ // checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
3174
+ // per RFC 7540 Section 8.1.2.2.
3175
+ // The returned error is reported to users.
3176
+ func checkValidHTTP2RequestHeaders(h Header) error {
3177
+ for _, k := range connHeaders {
3178
+ if _, ok := h[k]; ok {
3179
+ return fmt.Errorf("request header %q is not valid in HTTP/2", k)
3180
+ }
3181
+ }
3182
+ te := h["Te"]
3183
+ if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
3184
+ return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
3185
+ }
3186
+ return nil
3187
+ }
3188
+
3189
+ type serve400Handler struct {
3190
+ err error
3191
+ }
3192
+
3193
+ func (handler serve400Handler) ServeHTTP(w *ResponseWriter, r *ServerRequest) {
3194
+ const statusBadRequest = 400
3195
+
3196
+ // TODO: Dedup with http.Error?
3197
+ h := w.Header()
3198
+ h.Del("Content-Length")
3199
+ h.Set("Content-Type", "text/plain; charset=utf-8")
3200
+ h.Set("X-Content-Type-Options", "nosniff")
3201
+ w.WriteHeader(statusBadRequest)
3202
+ fmt.Fprintln(w, handler.err.Error())
3203
+ }
3204
+
3205
+ // h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
3206
+ // disabled. See comments on h1ServerShutdownChan above for why
3207
+ // the code is written this way.
3208
+ func h1ServerKeepAlivesDisabled(hs ServerConfig) bool {
3209
+ return !hs.DoKeepAlives()
3210
+ }
3211
+
3212
+ func (sc *serverConn) countError(name string, err error) error {
3213
+ if sc == nil || sc.srv == nil {
3214
+ return err
3215
+ }
3216
+ f := sc.countErrorFunc
3217
+ if f == nil {
3218
+ return err
3219
+ }
3220
+ var typ string
3221
+ var code ErrCode
3222
+ switch e := err.(type) {
3223
+ case ConnectionError:
3224
+ typ = "conn"
3225
+ code = ErrCode(e)
3226
+ case StreamError:
3227
+ typ = "stream"
3228
+ code = ErrCode(e.Code)
3229
+ default:
3230
+ return err
3231
+ }
3232
+ codeStr := errCodeName[code]
3233
+ if codeStr == "" {
3234
+ codeStr = strconv.Itoa(int(code))
3235
+ }
3236
+ f(fmt.Sprintf("%s_%s_%s", typ, codeStr, name))
3237
+ return err
3238
+ }