http_util.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. "net"
  25. "net/http"
  26. "strconv"
  27. "strings"
  28. "time"
  29. "unicode/utf8"
  30. "github.com/golang/protobuf/proto"
  31. "golang.org/x/net/http2"
  32. "golang.org/x/net/http2/hpack"
  33. spb "google.golang.org/genproto/googleapis/rpc/status"
  34. "google.golang.org/grpc/codes"
  35. "google.golang.org/grpc/status"
  36. )
  37. const (
  38. // http2MaxFrameLen specifies the max length of a HTTP2 frame.
  39. http2MaxFrameLen = 16384 // 16KB frame
  40. // http://http2.github.io/http2-spec/#SettingValues
  41. http2InitHeaderTableSize = 4096
  42. // http2IOBufSize specifies the buffer size for sending frames.
  43. defaultWriteBufSize = 32 * 1024
  44. defaultReadBufSize = 32 * 1024
  45. // baseContentType is the base content-type for gRPC. This is a valid
  46. // content-type on it's own, but can also include a content-subtype such as
  47. // "proto" as a suffix after "+" or ";". See
  48. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
  49. // for more details.
  50. baseContentType = "application/grpc"
  51. )
  52. var (
  53. clientPreface = []byte(http2.ClientPreface)
  54. http2ErrConvTab = map[http2.ErrCode]codes.Code{
  55. http2.ErrCodeNo: codes.Internal,
  56. http2.ErrCodeProtocol: codes.Internal,
  57. http2.ErrCodeInternal: codes.Internal,
  58. http2.ErrCodeFlowControl: codes.ResourceExhausted,
  59. http2.ErrCodeSettingsTimeout: codes.Internal,
  60. http2.ErrCodeStreamClosed: codes.Internal,
  61. http2.ErrCodeFrameSize: codes.Internal,
  62. http2.ErrCodeRefusedStream: codes.Unavailable,
  63. http2.ErrCodeCancel: codes.Canceled,
  64. http2.ErrCodeCompression: codes.Internal,
  65. http2.ErrCodeConnect: codes.Internal,
  66. http2.ErrCodeEnhanceYourCalm: codes.ResourceExhausted,
  67. http2.ErrCodeInadequateSecurity: codes.PermissionDenied,
  68. http2.ErrCodeHTTP11Required: codes.Internal,
  69. }
  70. statusCodeConvTab = map[codes.Code]http2.ErrCode{
  71. codes.Internal: http2.ErrCodeInternal,
  72. codes.Canceled: http2.ErrCodeCancel,
  73. codes.Unavailable: http2.ErrCodeRefusedStream,
  74. codes.ResourceExhausted: http2.ErrCodeEnhanceYourCalm,
  75. codes.PermissionDenied: http2.ErrCodeInadequateSecurity,
  76. }
  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. // Records the states during HPACK decoding. Must be reset once the
  97. // decoding of the entire headers are finished.
  98. type decodeState struct {
  99. encoding string
  100. // statusGen caches the stream status received from the trailer the server
  101. // sent. Client side only. Do not access directly. After all trailers are
  102. // parsed, use the status method to retrieve the status.
  103. statusGen *status.Status
  104. // rawStatusCode and rawStatusMsg are set from the raw trailer fields and are not
  105. // intended for direct access outside of parsing.
  106. rawStatusCode *int
  107. rawStatusMsg string
  108. httpStatus *int
  109. // Server side only fields.
  110. timeoutSet bool
  111. timeout time.Duration
  112. method string
  113. // key-value metadata map from the peer.
  114. mdata map[string][]string
  115. statsTags []byte
  116. statsTrace []byte
  117. contentSubtype string
  118. }
  119. // isReservedHeader checks whether hdr belongs to HTTP2 headers
  120. // reserved by gRPC protocol. Any other headers are classified as the
  121. // user-specified metadata.
  122. func isReservedHeader(hdr string) bool {
  123. if hdr != "" && hdr[0] == ':' {
  124. return true
  125. }
  126. switch hdr {
  127. case "content-type",
  128. "user-agent",
  129. "grpc-message-type",
  130. "grpc-encoding",
  131. "grpc-message",
  132. "grpc-status",
  133. "grpc-timeout",
  134. "grpc-status-details-bin",
  135. "te":
  136. return true
  137. default:
  138. return false
  139. }
  140. }
  141. // isWhitelistedHeader checks whether hdr should be propagated
  142. // into metadata visible to users.
  143. func isWhitelistedHeader(hdr string) bool {
  144. switch hdr {
  145. case ":authority", "user-agent":
  146. return true
  147. default:
  148. return false
  149. }
  150. }
  151. // contentSubtype returns the content-subtype for the given content-type. The
  152. // given content-type must be a valid content-type that starts with
  153. // "application/grpc". A content-subtype will follow "application/grpc" after a
  154. // "+" or ";". See
  155. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  156. // more details.
  157. //
  158. // If contentType is not a valid content-type for gRPC, the boolean
  159. // will be false, otherwise true. If content-type == "application/grpc",
  160. // "application/grpc+", or "application/grpc;", the boolean will be true,
  161. // but no content-subtype will be returned.
  162. //
  163. // contentType is assumed to be lowercase already.
  164. func contentSubtype(contentType string) (string, bool) {
  165. if contentType == baseContentType {
  166. return "", true
  167. }
  168. if !strings.HasPrefix(contentType, baseContentType) {
  169. return "", false
  170. }
  171. // guaranteed since != baseContentType and has baseContentType prefix
  172. switch contentType[len(baseContentType)] {
  173. case '+', ';':
  174. // this will return true for "application/grpc+" or "application/grpc;"
  175. // which the previous validContentType function tested to be valid, so we
  176. // just say that no content-subtype is specified in this case
  177. return contentType[len(baseContentType)+1:], true
  178. default:
  179. return "", false
  180. }
  181. }
  182. // contentSubtype is assumed to be lowercase
  183. func contentType(contentSubtype string) string {
  184. if contentSubtype == "" {
  185. return baseContentType
  186. }
  187. return baseContentType + "+" + contentSubtype
  188. }
  189. func (d *decodeState) status() *status.Status {
  190. if d.statusGen == nil {
  191. // No status-details were provided; generate status using code/msg.
  192. d.statusGen = status.New(codes.Code(int32(*(d.rawStatusCode))), d.rawStatusMsg)
  193. }
  194. return d.statusGen
  195. }
  196. const binHdrSuffix = "-bin"
  197. func encodeBinHeader(v []byte) string {
  198. return base64.RawStdEncoding.EncodeToString(v)
  199. }
  200. func decodeBinHeader(v string) ([]byte, error) {
  201. if len(v)%4 == 0 {
  202. // Input was padded, or padding was not necessary.
  203. return base64.StdEncoding.DecodeString(v)
  204. }
  205. return base64.RawStdEncoding.DecodeString(v)
  206. }
  207. func encodeMetadataHeader(k, v string) string {
  208. if strings.HasSuffix(k, binHdrSuffix) {
  209. return encodeBinHeader(([]byte)(v))
  210. }
  211. return v
  212. }
  213. func decodeMetadataHeader(k, v string) (string, error) {
  214. if strings.HasSuffix(k, binHdrSuffix) {
  215. b, err := decodeBinHeader(v)
  216. return string(b), err
  217. }
  218. return v, nil
  219. }
  220. func (d *decodeState) decodeResponseHeader(frame *http2.MetaHeadersFrame) error {
  221. for _, hf := range frame.Fields {
  222. if err := d.processHeaderField(hf); err != nil {
  223. return err
  224. }
  225. }
  226. // If grpc status exists, no need to check further.
  227. if d.rawStatusCode != nil || d.statusGen != nil {
  228. return nil
  229. }
  230. // If grpc status doesn't exist and http status doesn't exist,
  231. // then it's a malformed header.
  232. if d.httpStatus == nil {
  233. return streamErrorf(codes.Internal, "malformed header: doesn't contain status(gRPC or HTTP)")
  234. }
  235. if *(d.httpStatus) != http.StatusOK {
  236. code, ok := httpStatusConvTab[*(d.httpStatus)]
  237. if !ok {
  238. code = codes.Unknown
  239. }
  240. return streamErrorf(code, http.StatusText(*(d.httpStatus)))
  241. }
  242. // gRPC status doesn't exist and http status is OK.
  243. // Set rawStatusCode to be unknown and return nil error.
  244. // So that, if the stream has ended this Unknown status
  245. // will be propagated to the user.
  246. // Otherwise, it will be ignored. In which case, status from
  247. // a later trailer, that has StreamEnded flag set, is propagated.
  248. code := int(codes.Unknown)
  249. d.rawStatusCode = &code
  250. return nil
  251. }
  252. func (d *decodeState) addMetadata(k, v string) {
  253. if d.mdata == nil {
  254. d.mdata = make(map[string][]string)
  255. }
  256. d.mdata[k] = append(d.mdata[k], v)
  257. }
  258. func (d *decodeState) processHeaderField(f hpack.HeaderField) error {
  259. switch f.Name {
  260. case "content-type":
  261. contentSubtype, validContentType := contentSubtype(f.Value)
  262. if !validContentType {
  263. return streamErrorf(codes.Internal, "transport: received the unexpected content-type %q", f.Value)
  264. }
  265. d.contentSubtype = contentSubtype
  266. // TODO: do we want to propagate the whole content-type in the metadata,
  267. // or come up with a way to just propagate the content-subtype if it was set?
  268. // ie {"content-type": "application/grpc+proto"} or {"content-subtype": "proto"}
  269. // in the metadata?
  270. d.addMetadata(f.Name, f.Value)
  271. case "grpc-encoding":
  272. d.encoding = f.Value
  273. case "grpc-status":
  274. code, err := strconv.Atoi(f.Value)
  275. if err != nil {
  276. return streamErrorf(codes.Internal, "transport: malformed grpc-status: %v", err)
  277. }
  278. d.rawStatusCode = &code
  279. case "grpc-message":
  280. d.rawStatusMsg = decodeGrpcMessage(f.Value)
  281. case "grpc-status-details-bin":
  282. v, err := decodeBinHeader(f.Value)
  283. if err != nil {
  284. return streamErrorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err)
  285. }
  286. s := &spb.Status{}
  287. if err := proto.Unmarshal(v, s); err != nil {
  288. return streamErrorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err)
  289. }
  290. d.statusGen = status.FromProto(s)
  291. case "grpc-timeout":
  292. d.timeoutSet = true
  293. var err error
  294. if d.timeout, err = decodeTimeout(f.Value); err != nil {
  295. return streamErrorf(codes.Internal, "transport: malformed time-out: %v", err)
  296. }
  297. case ":path":
  298. d.method = f.Value
  299. case ":status":
  300. code, err := strconv.Atoi(f.Value)
  301. if err != nil {
  302. return streamErrorf(codes.Internal, "transport: malformed http-status: %v", err)
  303. }
  304. d.httpStatus = &code
  305. case "grpc-tags-bin":
  306. v, err := decodeBinHeader(f.Value)
  307. if err != nil {
  308. return streamErrorf(codes.Internal, "transport: malformed grpc-tags-bin: %v", err)
  309. }
  310. d.statsTags = v
  311. d.addMetadata(f.Name, string(v))
  312. case "grpc-trace-bin":
  313. v, err := decodeBinHeader(f.Value)
  314. if err != nil {
  315. return streamErrorf(codes.Internal, "transport: malformed grpc-trace-bin: %v", err)
  316. }
  317. d.statsTrace = v
  318. d.addMetadata(f.Name, string(v))
  319. default:
  320. if isReservedHeader(f.Name) && !isWhitelistedHeader(f.Name) {
  321. break
  322. }
  323. v, err := decodeMetadataHeader(f.Name, f.Value)
  324. if err != nil {
  325. errorf("Failed to decode metadata header (%q, %q): %v", f.Name, f.Value, err)
  326. return nil
  327. }
  328. d.addMetadata(f.Name, v)
  329. }
  330. return nil
  331. }
  332. type timeoutUnit uint8
  333. const (
  334. hour timeoutUnit = 'H'
  335. minute timeoutUnit = 'M'
  336. second timeoutUnit = 'S'
  337. millisecond timeoutUnit = 'm'
  338. microsecond timeoutUnit = 'u'
  339. nanosecond timeoutUnit = 'n'
  340. )
  341. func timeoutUnitToDuration(u timeoutUnit) (d time.Duration, ok bool) {
  342. switch u {
  343. case hour:
  344. return time.Hour, true
  345. case minute:
  346. return time.Minute, true
  347. case second:
  348. return time.Second, true
  349. case millisecond:
  350. return time.Millisecond, true
  351. case microsecond:
  352. return time.Microsecond, true
  353. case nanosecond:
  354. return time.Nanosecond, true
  355. default:
  356. }
  357. return
  358. }
  359. const maxTimeoutValue int64 = 100000000 - 1
  360. // div does integer division and round-up the result. Note that this is
  361. // equivalent to (d+r-1)/r but has less chance to overflow.
  362. func div(d, r time.Duration) int64 {
  363. if m := d % r; m > 0 {
  364. return int64(d/r + 1)
  365. }
  366. return int64(d / r)
  367. }
  368. // TODO(zhaoq): It is the simplistic and not bandwidth efficient. Improve it.
  369. func encodeTimeout(t time.Duration) string {
  370. if t <= 0 {
  371. return "0n"
  372. }
  373. if d := div(t, time.Nanosecond); d <= maxTimeoutValue {
  374. return strconv.FormatInt(d, 10) + "n"
  375. }
  376. if d := div(t, time.Microsecond); d <= maxTimeoutValue {
  377. return strconv.FormatInt(d, 10) + "u"
  378. }
  379. if d := div(t, time.Millisecond); d <= maxTimeoutValue {
  380. return strconv.FormatInt(d, 10) + "m"
  381. }
  382. if d := div(t, time.Second); d <= maxTimeoutValue {
  383. return strconv.FormatInt(d, 10) + "S"
  384. }
  385. if d := div(t, time.Minute); d <= maxTimeoutValue {
  386. return strconv.FormatInt(d, 10) + "M"
  387. }
  388. // Note that maxTimeoutValue * time.Hour > MaxInt64.
  389. return strconv.FormatInt(div(t, time.Hour), 10) + "H"
  390. }
  391. func decodeTimeout(s string) (time.Duration, error) {
  392. size := len(s)
  393. if size < 2 {
  394. return 0, fmt.Errorf("transport: timeout string is too short: %q", s)
  395. }
  396. unit := timeoutUnit(s[size-1])
  397. d, ok := timeoutUnitToDuration(unit)
  398. if !ok {
  399. return 0, fmt.Errorf("transport: timeout unit is not recognized: %q", s)
  400. }
  401. t, err := strconv.ParseInt(s[:size-1], 10, 64)
  402. if err != nil {
  403. return 0, err
  404. }
  405. return d * time.Duration(t), nil
  406. }
  407. const (
  408. spaceByte = ' '
  409. tildeByte = '~'
  410. percentByte = '%'
  411. )
  412. // encodeGrpcMessage is used to encode status code in header field
  413. // "grpc-message". It does percent encoding and also replaces invalid utf-8
  414. // characters with Unicode replacement character.
  415. //
  416. // It checks to see if each individual byte in msg is an allowable byte, and
  417. // then either percent encoding or passing it through. When percent encoding,
  418. // the byte is converted into hexadecimal notation with a '%' prepended.
  419. func encodeGrpcMessage(msg string) string {
  420. if msg == "" {
  421. return ""
  422. }
  423. lenMsg := len(msg)
  424. for i := 0; i < lenMsg; i++ {
  425. c := msg[i]
  426. if !(c >= spaceByte && c <= tildeByte && c != percentByte) {
  427. return encodeGrpcMessageUnchecked(msg)
  428. }
  429. }
  430. return msg
  431. }
  432. func encodeGrpcMessageUnchecked(msg string) string {
  433. var buf bytes.Buffer
  434. for len(msg) > 0 {
  435. r, size := utf8.DecodeRuneInString(msg)
  436. for _, b := range []byte(string(r)) {
  437. if size > 1 {
  438. // If size > 1, r is not ascii. Always do percent encoding.
  439. buf.WriteString(fmt.Sprintf("%%%02X", b))
  440. continue
  441. }
  442. // The for loop is necessary even if size == 1. r could be
  443. // utf8.RuneError.
  444. //
  445. // fmt.Sprintf("%%%02X", utf8.RuneError) gives "%FFFD".
  446. if b >= spaceByte && b <= tildeByte && b != percentByte {
  447. buf.WriteByte(b)
  448. } else {
  449. buf.WriteString(fmt.Sprintf("%%%02X", b))
  450. }
  451. }
  452. msg = msg[size:]
  453. }
  454. return buf.String()
  455. }
  456. // decodeGrpcMessage decodes the msg encoded by encodeGrpcMessage.
  457. func decodeGrpcMessage(msg string) string {
  458. if msg == "" {
  459. return ""
  460. }
  461. lenMsg := len(msg)
  462. for i := 0; i < lenMsg; i++ {
  463. if msg[i] == percentByte && i+2 < lenMsg {
  464. return decodeGrpcMessageUnchecked(msg)
  465. }
  466. }
  467. return msg
  468. }
  469. func decodeGrpcMessageUnchecked(msg string) string {
  470. var buf bytes.Buffer
  471. lenMsg := len(msg)
  472. for i := 0; i < lenMsg; i++ {
  473. c := msg[i]
  474. if c == percentByte && i+2 < lenMsg {
  475. parsed, err := strconv.ParseUint(msg[i+1:i+3], 16, 8)
  476. if err != nil {
  477. buf.WriteByte(c)
  478. } else {
  479. buf.WriteByte(byte(parsed))
  480. i += 2
  481. }
  482. } else {
  483. buf.WriteByte(c)
  484. }
  485. }
  486. return buf.String()
  487. }
  488. type bufWriter struct {
  489. buf []byte
  490. offset int
  491. batchSize int
  492. conn net.Conn
  493. err error
  494. onFlush func()
  495. }
  496. func newBufWriter(conn net.Conn, batchSize int) *bufWriter {
  497. return &bufWriter{
  498. buf: make([]byte, batchSize*2),
  499. batchSize: batchSize,
  500. conn: conn,
  501. }
  502. }
  503. func (w *bufWriter) Write(b []byte) (n int, err error) {
  504. if w.err != nil {
  505. return 0, w.err
  506. }
  507. for len(b) > 0 {
  508. nn := copy(w.buf[w.offset:], b)
  509. b = b[nn:]
  510. w.offset += nn
  511. n += nn
  512. if w.offset >= w.batchSize {
  513. err = w.Flush()
  514. }
  515. }
  516. return n, err
  517. }
  518. func (w *bufWriter) Flush() error {
  519. if w.err != nil {
  520. return w.err
  521. }
  522. if w.offset == 0 {
  523. return nil
  524. }
  525. if w.onFlush != nil {
  526. w.onFlush()
  527. }
  528. _, w.err = w.conn.Write(w.buf[:w.offset])
  529. w.offset = 0
  530. return w.err
  531. }
  532. type framer struct {
  533. writer *bufWriter
  534. fr *http2.Framer
  535. }
  536. func newFramer(conn net.Conn, writeBufferSize, readBufferSize int) *framer {
  537. r := bufio.NewReaderSize(conn, readBufferSize)
  538. w := newBufWriter(conn, writeBufferSize)
  539. f := &framer{
  540. writer: w,
  541. fr: http2.NewFramer(w, r),
  542. }
  543. // Opt-in to Frame reuse API on framer to reduce garbage.
  544. // Frames aren't safe to read from after a subsequent call to ReadFrame.
  545. f.fr.SetReuseFrames()
  546. f.fr.ReadMetaHeaders = hpack.NewDecoder(http2InitHeaderTableSize, nil)
  547. return f
  548. }