http_util.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. /*
  2. *
  3. * Copyright 2014 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package transport
  19. import (
  20. "bufio"
  21. "bytes"
  22. "encoding/base64"
  23. "fmt"
  24. "io"
  25. "math"
  26. "net"
  27. "net/http"
  28. "strconv"
  29. "strings"
  30. "time"
  31. "unicode/utf8"
  32. "github.com/golang/protobuf/proto"
  33. "golang.org/x/net/http2"
  34. "golang.org/x/net/http2/hpack"
  35. spb "google.golang.org/genproto/googleapis/rpc/status"
  36. "google.golang.org/grpc/codes"
  37. "google.golang.org/grpc/status"
  38. )
  39. const (
  40. // http2MaxFrameLen specifies the max length of a HTTP2 frame.
  41. http2MaxFrameLen = 16384 // 16KB frame
  42. // http://http2.github.io/http2-spec/#SettingValues
  43. http2InitHeaderTableSize = 4096
  44. // baseContentType is the base content-type for gRPC. This is a valid
  45. // content-type on it's own, but can also include a content-subtype such as
  46. // "proto" as a suffix after "+" or ";". See
  47. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
  48. // for more details.
  49. baseContentType = "application/grpc"
  50. )
  51. var (
  52. clientPreface = []byte(http2.ClientPreface)
  53. http2ErrConvTab = map[http2.ErrCode]codes.Code{
  54. http2.ErrCodeNo: codes.Internal,
  55. http2.ErrCodeProtocol: codes.Internal,
  56. http2.ErrCodeInternal: codes.Internal,
  57. http2.ErrCodeFlowControl: codes.ResourceExhausted,
  58. http2.ErrCodeSettingsTimeout: codes.Internal,
  59. http2.ErrCodeStreamClosed: codes.Internal,
  60. http2.ErrCodeFrameSize: codes.Internal,
  61. http2.ErrCodeRefusedStream: codes.Unavailable,
  62. http2.ErrCodeCancel: codes.Canceled,
  63. http2.ErrCodeCompression: codes.Internal,
  64. http2.ErrCodeConnect: codes.Internal,
  65. http2.ErrCodeEnhanceYourCalm: codes.ResourceExhausted,
  66. http2.ErrCodeInadequateSecurity: codes.PermissionDenied,
  67. http2.ErrCodeHTTP11Required: codes.Internal,
  68. }
  69. statusCodeConvTab = map[codes.Code]http2.ErrCode{
  70. codes.Internal: http2.ErrCodeInternal,
  71. codes.Canceled: http2.ErrCodeCancel,
  72. codes.Unavailable: http2.ErrCodeRefusedStream,
  73. codes.ResourceExhausted: http2.ErrCodeEnhanceYourCalm,
  74. codes.PermissionDenied: http2.ErrCodeInadequateSecurity,
  75. }
  76. // HTTPStatusConvTab is the HTTP status code to gRPC error code conversion table.
  77. HTTPStatusConvTab = map[int]codes.Code{
  78. // 400 Bad Request - INTERNAL.
  79. http.StatusBadRequest: codes.Internal,
  80. // 401 Unauthorized - UNAUTHENTICATED.
  81. http.StatusUnauthorized: codes.Unauthenticated,
  82. // 403 Forbidden - PERMISSION_DENIED.
  83. http.StatusForbidden: codes.PermissionDenied,
  84. // 404 Not Found - UNIMPLEMENTED.
  85. http.StatusNotFound: codes.Unimplemented,
  86. // 429 Too Many Requests - UNAVAILABLE.
  87. http.StatusTooManyRequests: codes.Unavailable,
  88. // 502 Bad Gateway - UNAVAILABLE.
  89. http.StatusBadGateway: codes.Unavailable,
  90. // 503 Service Unavailable - UNAVAILABLE.
  91. http.StatusServiceUnavailable: codes.Unavailable,
  92. // 504 Gateway timeout - UNAVAILABLE.
  93. http.StatusGatewayTimeout: codes.Unavailable,
  94. }
  95. )
  96. type parsedHeaderData struct {
  97. encoding string
  98. // statusGen caches the stream status received from the trailer the server
  99. // sent. Client side only. Do not access directly. After all trailers are
  100. // parsed, use the status method to retrieve the status.
  101. statusGen *status.Status
  102. // rawStatusCode and rawStatusMsg are set from the raw trailer fields and are not
  103. // intended for direct access outside of parsing.
  104. rawStatusCode *int
  105. rawStatusMsg string
  106. httpStatus *int
  107. // Server side only fields.
  108. timeoutSet bool
  109. timeout time.Duration
  110. method string
  111. // key-value metadata map from the peer.
  112. mdata map[string][]string
  113. statsTags []byte
  114. statsTrace []byte
  115. contentSubtype string
  116. // isGRPC field indicates whether the peer is speaking gRPC (otherwise HTTP).
  117. //
  118. // We are in gRPC mode (peer speaking gRPC) if:
  119. // * We are client side and have already received a HEADER frame that indicates gRPC peer.
  120. // * The header contains valid a content-type, i.e. a string starts with "application/grpc"
  121. // And we should handle error specific to gRPC.
  122. //
  123. // Otherwise (i.e. a content-type string starts without "application/grpc", or does not exist), we
  124. // are in HTTP fallback mode, and should handle error specific to HTTP.
  125. isGRPC bool
  126. grpcErr error
  127. httpErr error
  128. contentTypeErr string
  129. }
  130. // decodeState configures decoding criteria and records the decoded data.
  131. type decodeState struct {
  132. // whether decoding on server side or not
  133. serverSide bool
  134. // Records the states during HPACK decoding. It will be filled with info parsed from HTTP HEADERS
  135. // frame once decodeHeader function has been invoked and returned.
  136. data parsedHeaderData
  137. }
  138. // isReservedHeader checks whether hdr belongs to HTTP2 headers
  139. // reserved by gRPC protocol. Any other headers are classified as the
  140. // user-specified metadata.
  141. func isReservedHeader(hdr string) bool {
  142. if hdr != "" && hdr[0] == ':' {
  143. return true
  144. }
  145. switch hdr {
  146. case "content-type",
  147. "user-agent",
  148. "grpc-message-type",
  149. "grpc-encoding",
  150. "grpc-message",
  151. "grpc-status",
  152. "grpc-timeout",
  153. "grpc-status-details-bin",
  154. // Intentionally exclude grpc-previous-rpc-attempts and
  155. // grpc-retry-pushback-ms, which are "reserved", but their API
  156. // intentionally works via metadata.
  157. "te":
  158. return true
  159. default:
  160. return false
  161. }
  162. }
  163. // isWhitelistedHeader checks whether hdr should be propagated into metadata
  164. // visible to users, even though it is classified as "reserved", above.
  165. func isWhitelistedHeader(hdr string) bool {
  166. switch hdr {
  167. case ":authority", "user-agent":
  168. return true
  169. default:
  170. return false
  171. }
  172. }
  173. // contentSubtype returns the content-subtype for the given content-type. The
  174. // given content-type must be a valid content-type that starts with
  175. // "application/grpc". A content-subtype will follow "application/grpc" after a
  176. // "+" or ";". See
  177. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  178. // more details.
  179. //
  180. // If contentType is not a valid content-type for gRPC, the boolean
  181. // will be false, otherwise true. If content-type == "application/grpc",
  182. // "application/grpc+", or "application/grpc;", the boolean will be true,
  183. // but no content-subtype will be returned.
  184. //
  185. // contentType is assumed to be lowercase already.
  186. func contentSubtype(contentType string) (string, bool) {
  187. if contentType == baseContentType {
  188. return "", true
  189. }
  190. if !strings.HasPrefix(contentType, baseContentType) {
  191. return "", false
  192. }
  193. // guaranteed since != baseContentType and has baseContentType prefix
  194. switch contentType[len(baseContentType)] {
  195. case '+', ';':
  196. // this will return true for "application/grpc+" or "application/grpc;"
  197. // which the previous validContentType function tested to be valid, so we
  198. // just say that no content-subtype is specified in this case
  199. return contentType[len(baseContentType)+1:], true
  200. default:
  201. return "", false
  202. }
  203. }
  204. // contentSubtype is assumed to be lowercase
  205. func contentType(contentSubtype string) string {
  206. if contentSubtype == "" {
  207. return baseContentType
  208. }
  209. return baseContentType + "+" + contentSubtype
  210. }
  211. func (d *decodeState) status() *status.Status {
  212. if d.data.statusGen == nil {
  213. // No status-details were provided; generate status using code/msg.
  214. d.data.statusGen = status.New(codes.Code(int32(*(d.data.rawStatusCode))), d.data.rawStatusMsg)
  215. }
  216. return d.data.statusGen
  217. }
  218. const binHdrSuffix = "-bin"
  219. func encodeBinHeader(v []byte) string {
  220. return base64.RawStdEncoding.EncodeToString(v)
  221. }
  222. func decodeBinHeader(v string) ([]byte, error) {
  223. if len(v)%4 == 0 {
  224. // Input was padded, or padding was not necessary.
  225. return base64.StdEncoding.DecodeString(v)
  226. }
  227. return base64.RawStdEncoding.DecodeString(v)
  228. }
  229. func encodeMetadataHeader(k, v string) string {
  230. if strings.HasSuffix(k, binHdrSuffix) {
  231. return encodeBinHeader(([]byte)(v))
  232. }
  233. return v
  234. }
  235. func decodeMetadataHeader(k, v string) (string, error) {
  236. if strings.HasSuffix(k, binHdrSuffix) {
  237. b, err := decodeBinHeader(v)
  238. return string(b), err
  239. }
  240. return v, nil
  241. }
  242. func (d *decodeState) decodeHeader(frame *http2.MetaHeadersFrame) error {
  243. // frame.Truncated is set to true when framer detects that the current header
  244. // list size hits MaxHeaderListSize limit.
  245. if frame.Truncated {
  246. return status.Error(codes.Internal, "peer header list size exceeded limit")
  247. }
  248. for _, hf := range frame.Fields {
  249. d.processHeaderField(hf)
  250. }
  251. if d.data.isGRPC {
  252. if d.data.grpcErr != nil {
  253. return d.data.grpcErr
  254. }
  255. if d.serverSide {
  256. return nil
  257. }
  258. if d.data.rawStatusCode == nil && d.data.statusGen == nil {
  259. // gRPC status doesn't exist.
  260. // Set rawStatusCode to be unknown and return nil error.
  261. // So that, if the stream has ended this Unknown status
  262. // will be propagated to the user.
  263. // Otherwise, it will be ignored. In which case, status from
  264. // a later trailer, that has StreamEnded flag set, is propagated.
  265. code := int(codes.Unknown)
  266. d.data.rawStatusCode = &code
  267. }
  268. return nil
  269. }
  270. // HTTP fallback mode
  271. if d.data.httpErr != nil {
  272. return d.data.httpErr
  273. }
  274. var (
  275. code = codes.Internal // when header does not include HTTP status, return INTERNAL
  276. ok bool
  277. )
  278. if d.data.httpStatus != nil {
  279. code, ok = HTTPStatusConvTab[*(d.data.httpStatus)]
  280. if !ok {
  281. code = codes.Unknown
  282. }
  283. }
  284. return status.Error(code, d.constructHTTPErrMsg())
  285. }
  286. // constructErrMsg constructs error message to be returned in HTTP fallback mode.
  287. // Format: HTTP status code and its corresponding message + content-type error message.
  288. func (d *decodeState) constructHTTPErrMsg() string {
  289. var errMsgs []string
  290. if d.data.httpStatus == nil {
  291. errMsgs = append(errMsgs, "malformed header: missing HTTP status")
  292. } else {
  293. errMsgs = append(errMsgs, fmt.Sprintf("%s: HTTP status code %d", http.StatusText(*(d.data.httpStatus)), *d.data.httpStatus))
  294. }
  295. if d.data.contentTypeErr == "" {
  296. errMsgs = append(errMsgs, "transport: missing content-type field")
  297. } else {
  298. errMsgs = append(errMsgs, d.data.contentTypeErr)
  299. }
  300. return strings.Join(errMsgs, "; ")
  301. }
  302. func (d *decodeState) addMetadata(k, v string) {
  303. if d.data.mdata == nil {
  304. d.data.mdata = make(map[string][]string)
  305. }
  306. d.data.mdata[k] = append(d.data.mdata[k], v)
  307. }
  308. func (d *decodeState) processHeaderField(f hpack.HeaderField) {
  309. switch f.Name {
  310. case "content-type":
  311. contentSubtype, validContentType := contentSubtype(f.Value)
  312. if !validContentType {
  313. d.data.contentTypeErr = fmt.Sprintf("transport: received the unexpected content-type %q", f.Value)
  314. return
  315. }
  316. d.data.contentSubtype = contentSubtype
  317. // TODO: do we want to propagate the whole content-type in the metadata,
  318. // or come up with a way to just propagate the content-subtype if it was set?
  319. // ie {"content-type": "application/grpc+proto"} or {"content-subtype": "proto"}
  320. // in the metadata?
  321. d.addMetadata(f.Name, f.Value)
  322. d.data.isGRPC = true
  323. case "grpc-encoding":
  324. d.data.encoding = f.Value
  325. case "grpc-status":
  326. code, err := strconv.Atoi(f.Value)
  327. if err != nil {
  328. d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-status: %v", err)
  329. return
  330. }
  331. d.data.rawStatusCode = &code
  332. case "grpc-message":
  333. d.data.rawStatusMsg = decodeGrpcMessage(f.Value)
  334. case "grpc-status-details-bin":
  335. v, err := decodeBinHeader(f.Value)
  336. if err != nil {
  337. d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err)
  338. return
  339. }
  340. s := &spb.Status{}
  341. if err := proto.Unmarshal(v, s); err != nil {
  342. d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err)
  343. return
  344. }
  345. d.data.statusGen = status.FromProto(s)
  346. case "grpc-timeout":
  347. d.data.timeoutSet = true
  348. var err error
  349. if d.data.timeout, err = decodeTimeout(f.Value); err != nil {
  350. d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed time-out: %v", err)
  351. }
  352. case ":path":
  353. d.data.method = f.Value
  354. case ":status":
  355. code, err := strconv.Atoi(f.Value)
  356. if err != nil {
  357. d.data.httpErr = status.Errorf(codes.Internal, "transport: malformed http-status: %v", err)
  358. return
  359. }
  360. d.data.httpStatus = &code
  361. case "grpc-tags-bin":
  362. v, err := decodeBinHeader(f.Value)
  363. if err != nil {
  364. d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-tags-bin: %v", err)
  365. return
  366. }
  367. d.data.statsTags = v
  368. d.addMetadata(f.Name, string(v))
  369. case "grpc-trace-bin":
  370. v, err := decodeBinHeader(f.Value)
  371. if err != nil {
  372. d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-trace-bin: %v", err)
  373. return
  374. }
  375. d.data.statsTrace = v
  376. d.addMetadata(f.Name, string(v))
  377. default:
  378. if isReservedHeader(f.Name) && !isWhitelistedHeader(f.Name) {
  379. break
  380. }
  381. v, err := decodeMetadataHeader(f.Name, f.Value)
  382. if err != nil {
  383. errorf("Failed to decode metadata header (%q, %q): %v", f.Name, f.Value, err)
  384. return
  385. }
  386. d.addMetadata(f.Name, v)
  387. }
  388. }
  389. type timeoutUnit uint8
  390. const (
  391. hour timeoutUnit = 'H'
  392. minute timeoutUnit = 'M'
  393. second timeoutUnit = 'S'
  394. millisecond timeoutUnit = 'm'
  395. microsecond timeoutUnit = 'u'
  396. nanosecond timeoutUnit = 'n'
  397. )
  398. func timeoutUnitToDuration(u timeoutUnit) (d time.Duration, ok bool) {
  399. switch u {
  400. case hour:
  401. return time.Hour, true
  402. case minute:
  403. return time.Minute, true
  404. case second:
  405. return time.Second, true
  406. case millisecond:
  407. return time.Millisecond, true
  408. case microsecond:
  409. return time.Microsecond, true
  410. case nanosecond:
  411. return time.Nanosecond, true
  412. default:
  413. }
  414. return
  415. }
  416. const maxTimeoutValue int64 = 100000000 - 1
  417. // div does integer division and round-up the result. Note that this is
  418. // equivalent to (d+r-1)/r but has less chance to overflow.
  419. func div(d, r time.Duration) int64 {
  420. if m := d % r; m > 0 {
  421. return int64(d/r + 1)
  422. }
  423. return int64(d / r)
  424. }
  425. // TODO(zhaoq): It is the simplistic and not bandwidth efficient. Improve it.
  426. func encodeTimeout(t time.Duration) string {
  427. if t <= 0 {
  428. return "0n"
  429. }
  430. if d := div(t, time.Nanosecond); d <= maxTimeoutValue {
  431. return strconv.FormatInt(d, 10) + "n"
  432. }
  433. if d := div(t, time.Microsecond); d <= maxTimeoutValue {
  434. return strconv.FormatInt(d, 10) + "u"
  435. }
  436. if d := div(t, time.Millisecond); d <= maxTimeoutValue {
  437. return strconv.FormatInt(d, 10) + "m"
  438. }
  439. if d := div(t, time.Second); d <= maxTimeoutValue {
  440. return strconv.FormatInt(d, 10) + "S"
  441. }
  442. if d := div(t, time.Minute); d <= maxTimeoutValue {
  443. return strconv.FormatInt(d, 10) + "M"
  444. }
  445. // Note that maxTimeoutValue * time.Hour > MaxInt64.
  446. return strconv.FormatInt(div(t, time.Hour), 10) + "H"
  447. }
  448. func decodeTimeout(s string) (time.Duration, error) {
  449. size := len(s)
  450. if size < 2 {
  451. return 0, fmt.Errorf("transport: timeout string is too short: %q", s)
  452. }
  453. if size > 9 {
  454. // Spec allows for 8 digits plus the unit.
  455. return 0, fmt.Errorf("transport: timeout string is too long: %q", s)
  456. }
  457. unit := timeoutUnit(s[size-1])
  458. d, ok := timeoutUnitToDuration(unit)
  459. if !ok {
  460. return 0, fmt.Errorf("transport: timeout unit is not recognized: %q", s)
  461. }
  462. t, err := strconv.ParseInt(s[:size-1], 10, 64)
  463. if err != nil {
  464. return 0, err
  465. }
  466. const maxHours = math.MaxInt64 / int64(time.Hour)
  467. if d == time.Hour && t > maxHours {
  468. // This timeout would overflow math.MaxInt64; clamp it.
  469. return time.Duration(math.MaxInt64), nil
  470. }
  471. return d * time.Duration(t), nil
  472. }
  473. const (
  474. spaceByte = ' '
  475. tildeByte = '~'
  476. percentByte = '%'
  477. )
  478. // encodeGrpcMessage is used to encode status code in header field
  479. // "grpc-message". It does percent encoding and also replaces invalid utf-8
  480. // characters with Unicode replacement character.
  481. //
  482. // It checks to see if each individual byte in msg is an allowable byte, and
  483. // then either percent encoding or passing it through. When percent encoding,
  484. // the byte is converted into hexadecimal notation with a '%' prepended.
  485. func encodeGrpcMessage(msg string) string {
  486. if msg == "" {
  487. return ""
  488. }
  489. lenMsg := len(msg)
  490. for i := 0; i < lenMsg; i++ {
  491. c := msg[i]
  492. if !(c >= spaceByte && c <= tildeByte && c != percentByte) {
  493. return encodeGrpcMessageUnchecked(msg)
  494. }
  495. }
  496. return msg
  497. }
  498. func encodeGrpcMessageUnchecked(msg string) string {
  499. var buf bytes.Buffer
  500. for len(msg) > 0 {
  501. r, size := utf8.DecodeRuneInString(msg)
  502. for _, b := range []byte(string(r)) {
  503. if size > 1 {
  504. // If size > 1, r is not ascii. Always do percent encoding.
  505. buf.WriteString(fmt.Sprintf("%%%02X", b))
  506. continue
  507. }
  508. // The for loop is necessary even if size == 1. r could be
  509. // utf8.RuneError.
  510. //
  511. // fmt.Sprintf("%%%02X", utf8.RuneError) gives "%FFFD".
  512. if b >= spaceByte && b <= tildeByte && b != percentByte {
  513. buf.WriteByte(b)
  514. } else {
  515. buf.WriteString(fmt.Sprintf("%%%02X", b))
  516. }
  517. }
  518. msg = msg[size:]
  519. }
  520. return buf.String()
  521. }
  522. // decodeGrpcMessage decodes the msg encoded by encodeGrpcMessage.
  523. func decodeGrpcMessage(msg string) string {
  524. if msg == "" {
  525. return ""
  526. }
  527. lenMsg := len(msg)
  528. for i := 0; i < lenMsg; i++ {
  529. if msg[i] == percentByte && i+2 < lenMsg {
  530. return decodeGrpcMessageUnchecked(msg)
  531. }
  532. }
  533. return msg
  534. }
  535. func decodeGrpcMessageUnchecked(msg string) string {
  536. var buf bytes.Buffer
  537. lenMsg := len(msg)
  538. for i := 0; i < lenMsg; i++ {
  539. c := msg[i]
  540. if c == percentByte && i+2 < lenMsg {
  541. parsed, err := strconv.ParseUint(msg[i+1:i+3], 16, 8)
  542. if err != nil {
  543. buf.WriteByte(c)
  544. } else {
  545. buf.WriteByte(byte(parsed))
  546. i += 2
  547. }
  548. } else {
  549. buf.WriteByte(c)
  550. }
  551. }
  552. return buf.String()
  553. }
  554. type bufWriter struct {
  555. buf []byte
  556. offset int
  557. batchSize int
  558. conn net.Conn
  559. err error
  560. onFlush func()
  561. }
  562. func newBufWriter(conn net.Conn, batchSize int) *bufWriter {
  563. return &bufWriter{
  564. buf: make([]byte, batchSize*2),
  565. batchSize: batchSize,
  566. conn: conn,
  567. }
  568. }
  569. func (w *bufWriter) Write(b []byte) (n int, err error) {
  570. if w.err != nil {
  571. return 0, w.err
  572. }
  573. if w.batchSize == 0 { // Buffer has been disabled.
  574. return w.conn.Write(b)
  575. }
  576. for len(b) > 0 {
  577. nn := copy(w.buf[w.offset:], b)
  578. b = b[nn:]
  579. w.offset += nn
  580. n += nn
  581. if w.offset >= w.batchSize {
  582. err = w.Flush()
  583. }
  584. }
  585. return n, err
  586. }
  587. func (w *bufWriter) Flush() error {
  588. if w.err != nil {
  589. return w.err
  590. }
  591. if w.offset == 0 {
  592. return nil
  593. }
  594. if w.onFlush != nil {
  595. w.onFlush()
  596. }
  597. _, w.err = w.conn.Write(w.buf[:w.offset])
  598. w.offset = 0
  599. return w.err
  600. }
  601. type framer struct {
  602. writer *bufWriter
  603. fr *http2.Framer
  604. }
  605. func newFramer(conn net.Conn, writeBufferSize, readBufferSize int, maxHeaderListSize uint32) *framer {
  606. if writeBufferSize < 0 {
  607. writeBufferSize = 0
  608. }
  609. var r io.Reader = conn
  610. if readBufferSize > 0 {
  611. r = bufio.NewReaderSize(r, readBufferSize)
  612. }
  613. w := newBufWriter(conn, writeBufferSize)
  614. f := &framer{
  615. writer: w,
  616. fr: http2.NewFramer(w, r),
  617. }
  618. f.fr.SetMaxReadFrameSize(http2MaxFrameLen)
  619. // Opt-in to Frame reuse API on framer to reduce garbage.
  620. // Frames aren't safe to read from after a subsequent call to ReadFrame.
  621. f.fr.SetReuseFrames()
  622. f.fr.MaxHeaderListSize = maxHeaderListSize
  623. f.fr.ReadMetaHeaders = hpack.NewDecoder(http2InitHeaderTableSize, nil)
  624. return f
  625. }