lib.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. // Copyright 2010 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. // Package proto marshals and unmarshals protocol buffer messages as the
  5. // wire-format and text-format. For more information, see:
  6. // https://developers.google.com/protocol-buffers/docs/gotutorial
  7. package proto
  8. import (
  9. "fmt"
  10. "log"
  11. "reflect"
  12. "sort"
  13. "strconv"
  14. "sync"
  15. "github.com/golang/protobuf/v2/runtime/protoiface"
  16. )
  17. // requiredNotSetError is an error type returned by either Marshal or Unmarshal.
  18. // Marshal reports this when a required field is not initialized.
  19. // Unmarshal reports this when a required field is missing from the wire data.
  20. type requiredNotSetError struct{ field string }
  21. func (e *requiredNotSetError) Error() string {
  22. if e.field == "" {
  23. return fmt.Sprintf("proto: required field not set")
  24. }
  25. return fmt.Sprintf("proto: required field %q not set", e.field)
  26. }
  27. func (e *requiredNotSetError) RequiredNotSet() bool {
  28. return true
  29. }
  30. type invalidUTF8Error struct{ field string }
  31. func (e *invalidUTF8Error) Error() string {
  32. if e.field == "" {
  33. return "proto: invalid UTF-8 detected"
  34. }
  35. return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field)
  36. }
  37. func (e *invalidUTF8Error) InvalidUTF8() bool {
  38. return true
  39. }
  40. // errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8.
  41. // This error should not be exposed to the external API as such errors should
  42. // be recreated with the field information.
  43. var errInvalidUTF8 = &invalidUTF8Error{}
  44. // isNonFatal reports whether the error is either a RequiredNotSet error
  45. // or a InvalidUTF8 error.
  46. func isNonFatal(err error) bool {
  47. if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() {
  48. return true
  49. }
  50. if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() {
  51. return true
  52. }
  53. return false
  54. }
  55. type nonFatal struct{ E error }
  56. // Merge merges err into nf and reports whether it was successful.
  57. // Otherwise it returns false for any fatal non-nil errors.
  58. func (nf *nonFatal) Merge(err error) (ok bool) {
  59. if err == nil {
  60. return true // not an error
  61. }
  62. if !isNonFatal(err) {
  63. return false // fatal error
  64. }
  65. if nf.E == nil {
  66. nf.E = err // store first instance of non-fatal error
  67. }
  68. return true
  69. }
  70. // Message is implemented by generated protocol buffer messages.
  71. type Message = protoiface.MessageV1
  72. var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
  73. var marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
  74. type (
  75. oneofFuncsIface interface {
  76. XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
  77. }
  78. oneofWrappersIface interface {
  79. XXX_OneofWrappers() []interface{}
  80. }
  81. )
  82. // A Buffer is a buffer manager for marshaling and unmarshaling
  83. // protocol buffers. It may be reused between invocations to
  84. // reduce memory usage. It is not necessary to use a Buffer;
  85. // the global functions Marshal and Unmarshal create a
  86. // temporary Buffer and are fine for most applications.
  87. type Buffer struct {
  88. buf []byte // encode/decode byte stream
  89. index int // read point
  90. deterministic bool
  91. }
  92. // NewBuffer allocates a new Buffer and initializes its internal data to
  93. // the contents of the argument slice.
  94. func NewBuffer(e []byte) *Buffer {
  95. return &Buffer{buf: e}
  96. }
  97. // Reset resets the Buffer, ready for marshaling a new protocol buffer.
  98. func (p *Buffer) Reset() {
  99. p.buf = p.buf[0:0] // for reading/writing
  100. p.index = 0 // for reading
  101. }
  102. // SetBuf replaces the internal buffer with the slice,
  103. // ready for unmarshaling the contents of the slice.
  104. func (p *Buffer) SetBuf(s []byte) {
  105. p.buf = s
  106. p.index = 0
  107. }
  108. // Bytes returns the contents of the Buffer.
  109. func (p *Buffer) Bytes() []byte { return p.buf }
  110. // SetDeterministic sets whether to use deterministic serialization.
  111. //
  112. // Deterministic serialization guarantees that for a given binary, equal
  113. // messages will always be serialized to the same bytes. This implies:
  114. //
  115. // - Repeated serialization of a message will return the same bytes.
  116. // - Different processes of the same binary (which may be executing on
  117. // different machines) will serialize equal messages to the same bytes.
  118. //
  119. // Note that the deterministic serialization is NOT canonical across
  120. // languages. It is not guaranteed to remain stable over time. It is unstable
  121. // across different builds with schema changes due to unknown fields.
  122. // Users who need canonical serialization (e.g., persistent storage in a
  123. // canonical form, fingerprinting, etc.) should define their own
  124. // canonicalization specification and implement their own serializer rather
  125. // than relying on this API.
  126. //
  127. // If deterministic serialization is requested, map entries will be sorted
  128. // by keys in lexographical order. This is an implementation detail and
  129. // subject to change.
  130. func (p *Buffer) SetDeterministic(deterministic bool) {
  131. p.deterministic = deterministic
  132. }
  133. // DebugPrint dumps the encoded data in b in a debugging format with a header
  134. // including the string s. Used in testing but made available for general debugging.
  135. func (p *Buffer) DebugPrint(s string, b []byte) {
  136. var u uint64
  137. obuf := p.buf
  138. index := p.index
  139. p.buf = b
  140. p.index = 0
  141. depth := 0
  142. fmt.Printf("\n--- %s ---\n", s)
  143. out:
  144. for {
  145. for i := 0; i < depth; i++ {
  146. fmt.Print(" ")
  147. }
  148. index := p.index
  149. if index == len(p.buf) {
  150. break
  151. }
  152. op, err := p.DecodeVarint()
  153. if err != nil {
  154. fmt.Printf("%3d: fetching op err %v\n", index, err)
  155. break out
  156. }
  157. tag := op >> 3
  158. wire := op & 7
  159. switch wire {
  160. default:
  161. fmt.Printf("%3d: t=%3d unknown wire=%d\n",
  162. index, tag, wire)
  163. break out
  164. case WireBytes:
  165. var r []byte
  166. r, err = p.DecodeRawBytes(false)
  167. if err != nil {
  168. break out
  169. }
  170. fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
  171. if len(r) <= 6 {
  172. for i := 0; i < len(r); i++ {
  173. fmt.Printf(" %.2x", r[i])
  174. }
  175. } else {
  176. for i := 0; i < 3; i++ {
  177. fmt.Printf(" %.2x", r[i])
  178. }
  179. fmt.Printf(" ..")
  180. for i := len(r) - 3; i < len(r); i++ {
  181. fmt.Printf(" %.2x", r[i])
  182. }
  183. }
  184. fmt.Printf("\n")
  185. case WireFixed32:
  186. u, err = p.DecodeFixed32()
  187. if err != nil {
  188. fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
  189. break out
  190. }
  191. fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
  192. case WireFixed64:
  193. u, err = p.DecodeFixed64()
  194. if err != nil {
  195. fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
  196. break out
  197. }
  198. fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
  199. case WireVarint:
  200. u, err = p.DecodeVarint()
  201. if err != nil {
  202. fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
  203. break out
  204. }
  205. fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
  206. case WireStartGroup:
  207. fmt.Printf("%3d: t=%3d start\n", index, tag)
  208. depth++
  209. case WireEndGroup:
  210. depth--
  211. fmt.Printf("%3d: t=%3d end\n", index, tag)
  212. }
  213. }
  214. if depth != 0 {
  215. fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
  216. }
  217. fmt.Printf("\n")
  218. p.buf = obuf
  219. p.index = index
  220. }
  221. // SetDefaults sets unset protocol buffer fields to their default values.
  222. // It only modifies fields that are both unset and have defined defaults.
  223. // It recursively sets default values in any non-nil sub-messages.
  224. func SetDefaults(pb Message) {
  225. if setDefaultsAlt != nil {
  226. setDefaultsAlt(pb) // populated by hooks_enabled.go
  227. return
  228. }
  229. setDefaults(reflect.ValueOf(pb), true, false)
  230. }
  231. // v is a pointer to a struct.
  232. func setDefaults(v reflect.Value, recur, zeros bool) {
  233. v = v.Elem()
  234. defaultMu.RLock()
  235. dm, ok := defaults[v.Type()]
  236. defaultMu.RUnlock()
  237. if !ok {
  238. dm = buildDefaultMessage(v.Type())
  239. defaultMu.Lock()
  240. defaults[v.Type()] = dm
  241. defaultMu.Unlock()
  242. }
  243. for _, sf := range dm.scalars {
  244. f := v.Field(sf.index)
  245. if !f.IsNil() {
  246. // field already set
  247. continue
  248. }
  249. dv := sf.value
  250. if dv == nil && !zeros {
  251. // no explicit default, and don't want to set zeros
  252. continue
  253. }
  254. fptr := f.Addr().Interface() // **T
  255. // TODO: Consider batching the allocations we do here.
  256. switch sf.kind {
  257. case reflect.Bool:
  258. b := new(bool)
  259. if dv != nil {
  260. *b = dv.(bool)
  261. }
  262. *(fptr.(**bool)) = b
  263. case reflect.Float32:
  264. f := new(float32)
  265. if dv != nil {
  266. *f = dv.(float32)
  267. }
  268. *(fptr.(**float32)) = f
  269. case reflect.Float64:
  270. f := new(float64)
  271. if dv != nil {
  272. *f = dv.(float64)
  273. }
  274. *(fptr.(**float64)) = f
  275. case reflect.Int32:
  276. // might be an enum
  277. if ft := f.Type(); ft != int32PtrType {
  278. // enum
  279. f.Set(reflect.New(ft.Elem()))
  280. if dv != nil {
  281. f.Elem().SetInt(int64(dv.(int32)))
  282. }
  283. } else {
  284. // int32 field
  285. i := new(int32)
  286. if dv != nil {
  287. *i = dv.(int32)
  288. }
  289. *(fptr.(**int32)) = i
  290. }
  291. case reflect.Int64:
  292. i := new(int64)
  293. if dv != nil {
  294. *i = dv.(int64)
  295. }
  296. *(fptr.(**int64)) = i
  297. case reflect.String:
  298. s := new(string)
  299. if dv != nil {
  300. *s = dv.(string)
  301. }
  302. *(fptr.(**string)) = s
  303. case reflect.Uint8:
  304. // exceptional case: []byte
  305. var b []byte
  306. if dv != nil {
  307. db := dv.([]byte)
  308. b = make([]byte, len(db))
  309. copy(b, db)
  310. } else {
  311. b = []byte{}
  312. }
  313. *(fptr.(*[]byte)) = b
  314. case reflect.Uint32:
  315. u := new(uint32)
  316. if dv != nil {
  317. *u = dv.(uint32)
  318. }
  319. *(fptr.(**uint32)) = u
  320. case reflect.Uint64:
  321. u := new(uint64)
  322. if dv != nil {
  323. *u = dv.(uint64)
  324. }
  325. *(fptr.(**uint64)) = u
  326. default:
  327. log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
  328. }
  329. }
  330. for _, ni := range dm.nested {
  331. f := v.Field(ni)
  332. // f is *T or []*T or map[T]*T
  333. switch f.Kind() {
  334. case reflect.Ptr:
  335. if f.IsNil() {
  336. continue
  337. }
  338. setDefaults(f, recur, zeros)
  339. case reflect.Slice:
  340. for i := 0; i < f.Len(); i++ {
  341. e := f.Index(i)
  342. if e.IsNil() {
  343. continue
  344. }
  345. setDefaults(e, recur, zeros)
  346. }
  347. case reflect.Map:
  348. for _, k := range f.MapKeys() {
  349. e := f.MapIndex(k)
  350. if e.IsNil() {
  351. continue
  352. }
  353. setDefaults(e, recur, zeros)
  354. }
  355. }
  356. }
  357. }
  358. var (
  359. // defaults maps a protocol buffer struct type to a slice of the fields,
  360. // with its scalar fields set to their proto-declared non-zero default values.
  361. defaultMu sync.RWMutex
  362. defaults = make(map[reflect.Type]defaultMessage)
  363. int32PtrType = reflect.TypeOf((*int32)(nil))
  364. )
  365. // defaultMessage represents information about the default values of a message.
  366. type defaultMessage struct {
  367. scalars []scalarField
  368. nested []int // struct field index of nested messages
  369. }
  370. type scalarField struct {
  371. index int // struct field index
  372. kind reflect.Kind // element type (the T in *T or []T)
  373. value interface{} // the proto-declared default value, or nil
  374. }
  375. // t is a struct type.
  376. func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
  377. sprop := GetProperties(t)
  378. for fi, prop := range sprop.Prop {
  379. if prop.Tag <= 0 {
  380. // XXX_unrecognized
  381. continue
  382. }
  383. ft := t.Field(fi).Type
  384. sf, nested, err := fieldDefault(ft, prop)
  385. switch {
  386. case err != nil:
  387. log.Print(err)
  388. case nested:
  389. dm.nested = append(dm.nested, fi)
  390. case sf != nil:
  391. sf.index = fi
  392. dm.scalars = append(dm.scalars, *sf)
  393. }
  394. }
  395. return dm
  396. }
  397. // fieldDefault returns the scalarField for field type ft.
  398. // sf will be nil if the field can not have a default.
  399. // nestedMessage will be true if this is a nested message.
  400. // Note that sf.index is not set on return.
  401. func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
  402. var canHaveDefault bool
  403. switch ft.Kind() {
  404. case reflect.Ptr:
  405. if ft.Elem().Kind() == reflect.Struct {
  406. nestedMessage = true
  407. } else {
  408. canHaveDefault = true // proto2 scalar field
  409. }
  410. case reflect.Slice:
  411. switch ft.Elem().Kind() {
  412. case reflect.Ptr:
  413. nestedMessage = true // repeated message
  414. case reflect.Uint8:
  415. canHaveDefault = true // bytes field
  416. }
  417. case reflect.Map:
  418. if ft.Elem().Kind() == reflect.Ptr {
  419. nestedMessage = true // map with message values
  420. }
  421. }
  422. if !canHaveDefault {
  423. if nestedMessage {
  424. return nil, true, nil
  425. }
  426. return nil, false, nil
  427. }
  428. // We now know that ft is a pointer or slice.
  429. sf = &scalarField{kind: ft.Elem().Kind()}
  430. // scalar fields without defaults
  431. if !prop.HasDefault {
  432. return sf, false, nil
  433. }
  434. // a scalar field: either *T or []byte
  435. switch ft.Elem().Kind() {
  436. case reflect.Bool:
  437. x, err := strconv.ParseBool(prop.Default)
  438. if err != nil {
  439. return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
  440. }
  441. sf.value = x
  442. case reflect.Float32:
  443. x, err := strconv.ParseFloat(prop.Default, 32)
  444. if err != nil {
  445. return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
  446. }
  447. sf.value = float32(x)
  448. case reflect.Float64:
  449. x, err := strconv.ParseFloat(prop.Default, 64)
  450. if err != nil {
  451. return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
  452. }
  453. sf.value = x
  454. case reflect.Int32:
  455. x, err := strconv.ParseInt(prop.Default, 10, 32)
  456. if err != nil {
  457. return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
  458. }
  459. sf.value = int32(x)
  460. case reflect.Int64:
  461. x, err := strconv.ParseInt(prop.Default, 10, 64)
  462. if err != nil {
  463. return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
  464. }
  465. sf.value = x
  466. case reflect.String:
  467. sf.value = prop.Default
  468. case reflect.Uint8:
  469. // []byte (not *uint8)
  470. sf.value = []byte(prop.Default)
  471. case reflect.Uint32:
  472. x, err := strconv.ParseUint(prop.Default, 10, 32)
  473. if err != nil {
  474. return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
  475. }
  476. sf.value = uint32(x)
  477. case reflect.Uint64:
  478. x, err := strconv.ParseUint(prop.Default, 10, 64)
  479. if err != nil {
  480. return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
  481. }
  482. sf.value = x
  483. default:
  484. return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
  485. }
  486. return sf, false, nil
  487. }
  488. // mapKeys returns a sort.Interface to be used for sorting the map keys.
  489. // Map fields may have key types of non-float scalars, strings and enums.
  490. func mapKeys(vs []reflect.Value) sort.Interface {
  491. s := mapKeySorter{vs: vs}
  492. // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps.
  493. if len(vs) == 0 {
  494. return s
  495. }
  496. switch vs[0].Kind() {
  497. case reflect.Int32, reflect.Int64:
  498. s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
  499. case reflect.Uint32, reflect.Uint64:
  500. s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
  501. case reflect.Bool:
  502. s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true
  503. case reflect.String:
  504. s.less = func(a, b reflect.Value) bool { return a.String() < b.String() }
  505. default:
  506. panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind()))
  507. }
  508. return s
  509. }
  510. type mapKeySorter struct {
  511. vs []reflect.Value
  512. less func(a, b reflect.Value) bool
  513. }
  514. func (s mapKeySorter) Len() int { return len(s.vs) }
  515. func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
  516. func (s mapKeySorter) Less(i, j int) bool {
  517. return s.less(s.vs[i], s.vs[j])
  518. }
  519. // isProto3Zero reports whether v is a zero proto3 value.
  520. func isProto3Zero(v reflect.Value) bool {
  521. switch v.Kind() {
  522. case reflect.Bool:
  523. return !v.Bool()
  524. case reflect.Int32, reflect.Int64:
  525. return v.Int() == 0
  526. case reflect.Uint32, reflect.Uint64:
  527. return v.Uint() == 0
  528. case reflect.Float32, reflect.Float64:
  529. return v.Float() == 0
  530. case reflect.String:
  531. return v.String() == ""
  532. }
  533. return false
  534. }
  535. const (
  536. // ProtoPackageIsVersion3 is referenced from generated protocol buffer files
  537. // to assert that that code is compatible with this version of the proto package.
  538. ProtoPackageIsVersion3 = true
  539. // ProtoPackageIsVersion2 is referenced from generated protocol buffer files
  540. // to assert that that code is compatible with this version of the proto package.
  541. ProtoPackageIsVersion2 = true
  542. // ProtoPackageIsVersion1 is referenced from generated protocol buffer files
  543. // to assert that that code is compatible with this version of the proto package.
  544. ProtoPackageIsVersion1 = true
  545. )
  546. // InternalMessageInfo is a type used internally by generated .pb.go files.
  547. // This type is not intended to be used by non-generated code.
  548. // This type is not subject to any compatibility guarantee.
  549. type InternalMessageInfo struct {
  550. marshal *marshalInfo
  551. unmarshal *unmarshalInfo
  552. merge *mergeInfo
  553. discard *discardInfo
  554. }