decode.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. // Copyright 2018 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 textpb
  5. import (
  6. "fmt"
  7. "strings"
  8. "github.com/golang/protobuf/v2/internal/encoding/text"
  9. "github.com/golang/protobuf/v2/internal/errors"
  10. "github.com/golang/protobuf/v2/internal/pragma"
  11. "github.com/golang/protobuf/v2/internal/set"
  12. "github.com/golang/protobuf/v2/proto"
  13. pref "github.com/golang/protobuf/v2/reflect/protoreflect"
  14. "github.com/golang/protobuf/v2/reflect/protoregistry"
  15. )
  16. // Unmarshal reads the given []byte into the given proto.Message.
  17. // TODO: may want to describe when Unmarshal returns error.
  18. func Unmarshal(m proto.Message, b []byte) error {
  19. return UnmarshalOptions{}.Unmarshal(m, b)
  20. }
  21. // UnmarshalOptions is a configurable textproto format parser.
  22. type UnmarshalOptions struct {
  23. pragma.NoUnkeyedLiterals
  24. // Resolver is the registry used for type lookups when unmarshaling extensions
  25. // and processing Any. If Resolver is not set, unmarshaling will default to
  26. // using protoregistry.GlobalTypes.
  27. Resolver *protoregistry.Types
  28. }
  29. // Unmarshal reads the given []byte and populates the given proto.Message using options in
  30. // UnmarshalOptions object.
  31. func (o UnmarshalOptions) Unmarshal(m proto.Message, b []byte) error {
  32. var nerr errors.NonFatal
  33. mr := m.ProtoReflect()
  34. // Clear all fields before populating it.
  35. // TODO: Determine if this needs to be consistent with jsonpb and binary unmarshal where
  36. // behavior is to merge values into existing message. If decision is to not clear the fields
  37. // ahead, code will need to be updated properly when merging nested messages.
  38. resetMessage(mr)
  39. // Parse into text.Value of message type.
  40. val, err := text.Unmarshal(b)
  41. if !nerr.Merge(err) {
  42. return err
  43. }
  44. if o.Resolver == nil {
  45. o.Resolver = protoregistry.GlobalTypes
  46. }
  47. err = o.unmarshalMessage(val.Message(), mr)
  48. if !nerr.Merge(err) {
  49. return err
  50. }
  51. return nerr.E
  52. }
  53. // resetMessage clears all fields of given protoreflect.Message.
  54. // TODO: This should go into the proto package.
  55. func resetMessage(m pref.Message) {
  56. knownFields := m.KnownFields()
  57. knownFields.Range(func(num pref.FieldNumber, _ pref.Value) bool {
  58. knownFields.Clear(num)
  59. return true
  60. })
  61. unknownFields := m.UnknownFields()
  62. unknownFields.Range(func(num pref.FieldNumber, _ pref.RawFields) bool {
  63. unknownFields.Set(num, nil)
  64. return true
  65. })
  66. extTypes := knownFields.ExtensionTypes()
  67. extTypes.Range(func(xt pref.ExtensionType) bool {
  68. extTypes.Remove(xt)
  69. return true
  70. })
  71. }
  72. // unmarshalMessage unmarshals a [][2]text.Value message into the given protoreflect.Message.
  73. func (o UnmarshalOptions) unmarshalMessage(tmsg [][2]text.Value, m pref.Message) error {
  74. var nerr errors.NonFatal
  75. msgType := m.Type()
  76. fieldDescs := msgType.Fields()
  77. reservedNames := msgType.ReservedNames()
  78. knownFields := m.KnownFields()
  79. xtTypes := knownFields.ExtensionTypes()
  80. var reqNums set.Ints
  81. var seenNums set.Ints
  82. for _, tfield := range tmsg {
  83. tkey := tfield[0]
  84. tval := tfield[1]
  85. var fd pref.FieldDescriptor
  86. var name pref.Name
  87. switch tkey.Type() {
  88. case text.Name:
  89. name, _ = tkey.Name()
  90. fd = fieldDescs.ByName(name)
  91. if fd == nil {
  92. // Check if this is a group field.
  93. fd = fieldDescs.ByName(pref.Name(strings.ToLower(string(name))))
  94. }
  95. case text.String:
  96. // TODO: Handle Any expansions here as well.
  97. // Handle extensions. Extensions have to be registered first in the message's
  98. // ExtensionTypes before setting a value to it.
  99. xtName := pref.FullName(tkey.String())
  100. // Check first if it is already registered. This is the case for repeated fields.
  101. xt := xtTypes.ByName(xtName)
  102. if xt == nil {
  103. var err error
  104. xt, err = o.Resolver.FindExtensionByName(xtName)
  105. if err != nil && err != protoregistry.NotFound {
  106. return err
  107. }
  108. if xt != nil {
  109. xtTypes.Register(xt)
  110. }
  111. }
  112. fd = xt
  113. }
  114. if fd == nil {
  115. // Ignore reserved names.
  116. if reservedNames.Has(name) {
  117. continue
  118. }
  119. // TODO: Can provide option to ignore unknown message fields.
  120. return errors.New("%v contains unknown field: %v", msgType.FullName(), tkey)
  121. }
  122. if cardinality := fd.Cardinality(); cardinality == pref.Repeated {
  123. // Map or list fields have cardinality of repeated.
  124. if err := o.unmarshalRepeated(tval, fd, knownFields); !nerr.Merge(err) {
  125. return err
  126. }
  127. } else {
  128. // Required or optional fields.
  129. num := uint64(fd.Number())
  130. if seenNums.Has(num) {
  131. return errors.New("non-repeated field %v is repeated", fd.FullName())
  132. }
  133. if err := o.unmarshalSingular(tval, fd, knownFields); !nerr.Merge(err) {
  134. return err
  135. }
  136. if cardinality == pref.Required {
  137. reqNums.Set(num)
  138. }
  139. seenNums.Set(num)
  140. }
  141. }
  142. // Check for any missing required fields.
  143. allReqNums := msgType.RequiredNumbers()
  144. if reqNums.Len() != allReqNums.Len() {
  145. for i := 0; i < allReqNums.Len(); i++ {
  146. if num := allReqNums.Get(i); !reqNums.Has(uint64(num)) {
  147. nerr.AppendRequiredNotSet(string(fieldDescs.ByNumber(num).FullName()))
  148. }
  149. }
  150. }
  151. return nerr.E
  152. }
  153. // unmarshalSingular unmarshals given text.Value into the non-repeated field.
  154. func (o UnmarshalOptions) unmarshalSingular(input text.Value, fd pref.FieldDescriptor, knownFields pref.KnownFields) error {
  155. num := fd.Number()
  156. var nerr errors.NonFatal
  157. var val pref.Value
  158. switch fd.Kind() {
  159. case pref.MessageKind, pref.GroupKind:
  160. if input.Type() != text.Message {
  161. return errors.New("%v contains invalid message/group value: %v", fd.FullName(), input)
  162. }
  163. m := knownFields.NewMessage(num)
  164. if err := o.unmarshalMessage(input.Message(), m); !nerr.Merge(err) {
  165. return err
  166. }
  167. val = pref.ValueOf(m)
  168. default:
  169. var err error
  170. val, err = unmarshalScalar(input, fd)
  171. if !nerr.Merge(err) {
  172. return err
  173. }
  174. }
  175. knownFields.Set(num, val)
  176. return nerr.E
  177. }
  178. // unmarshalRepeated unmarshals given text.Value into a repeated field. Caller should only
  179. // call this for cardinality=repeated.
  180. func (o UnmarshalOptions) unmarshalRepeated(input text.Value, fd pref.FieldDescriptor, knownFields pref.KnownFields) error {
  181. var items []text.Value
  182. // If input is not a list, turn it into a list.
  183. if input.Type() != text.List {
  184. items = []text.Value{input}
  185. } else {
  186. items = input.List()
  187. }
  188. var nerr errors.NonFatal
  189. num := fd.Number()
  190. val := knownFields.Get(num)
  191. if !fd.IsMap() {
  192. if err := o.unmarshalList(items, fd, val.List()); !nerr.Merge(err) {
  193. return err
  194. }
  195. } else {
  196. if err := o.unmarshalMap(items, fd, val.Map()); !nerr.Merge(err) {
  197. return err
  198. }
  199. }
  200. return nerr.E
  201. }
  202. // unmarshalScalar converts the given text.Value to a scalar/enum protoreflect.Value specified in
  203. // the given FieldDescriptor. Caller should not pass in a FieldDescriptor for a message/group kind.
  204. func unmarshalScalar(input text.Value, fd pref.FieldDescriptor) (pref.Value, error) {
  205. const b32 = false
  206. const b64 = true
  207. switch kind := fd.Kind(); kind {
  208. case pref.BoolKind:
  209. if b, ok := input.Bool(); ok {
  210. return pref.ValueOf(bool(b)), nil
  211. }
  212. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  213. if n, ok := input.Int(b32); ok {
  214. return pref.ValueOf(int32(n)), nil
  215. }
  216. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  217. if n, ok := input.Int(b64); ok {
  218. return pref.ValueOf(int64(n)), nil
  219. }
  220. case pref.Uint32Kind, pref.Fixed32Kind:
  221. if n, ok := input.Uint(b32); ok {
  222. return pref.ValueOf(uint32(n)), nil
  223. }
  224. case pref.Uint64Kind, pref.Fixed64Kind:
  225. if n, ok := input.Uint(b64); ok {
  226. return pref.ValueOf(uint64(n)), nil
  227. }
  228. case pref.FloatKind:
  229. if n, ok := input.Float(b32); ok {
  230. return pref.ValueOf(float32(n)), nil
  231. }
  232. case pref.DoubleKind:
  233. if n, ok := input.Float(b64); ok {
  234. return pref.ValueOf(float64(n)), nil
  235. }
  236. case pref.StringKind:
  237. if input.Type() == text.String {
  238. return pref.ValueOf(string(input.String())), nil
  239. }
  240. case pref.BytesKind:
  241. if input.Type() == text.String {
  242. return pref.ValueOf([]byte(input.String())), nil
  243. }
  244. case pref.EnumKind:
  245. // If input is int32, use directly.
  246. if n, ok := input.Int(b32); ok {
  247. return pref.ValueOf(pref.EnumNumber(n)), nil
  248. } else {
  249. if name, ok := input.Name(); ok {
  250. // Lookup EnumNumber based on name.
  251. if enumVal := fd.EnumType().Values().ByName(name); enumVal != nil {
  252. return pref.ValueOf(enumVal.Number()), nil
  253. }
  254. }
  255. }
  256. default:
  257. panic(fmt.Sprintf("invalid scalar kind %v", kind))
  258. }
  259. return pref.Value{}, errors.New("%v contains invalid scalar value: %v", fd.FullName(), input)
  260. }
  261. // unmarshalList unmarshals given []text.Value into given protoreflect.List.
  262. func (o UnmarshalOptions) unmarshalList(inputList []text.Value, fd pref.FieldDescriptor, list pref.List) error {
  263. var nerr errors.NonFatal
  264. switch fd.Kind() {
  265. case pref.MessageKind, pref.GroupKind:
  266. for _, input := range inputList {
  267. if input.Type() != text.Message {
  268. return errors.New("%v contains invalid message/group value: %v", fd.FullName(), input)
  269. }
  270. m := list.NewMessage()
  271. if err := o.unmarshalMessage(input.Message(), m); !nerr.Merge(err) {
  272. return err
  273. }
  274. list.Append(pref.ValueOf(m))
  275. }
  276. default:
  277. for _, input := range inputList {
  278. val, err := unmarshalScalar(input, fd)
  279. if !nerr.Merge(err) {
  280. return err
  281. }
  282. list.Append(val)
  283. }
  284. }
  285. return nerr.E
  286. }
  287. // unmarshalMap unmarshals given []text.Value into given protoreflect.Map.
  288. func (o UnmarshalOptions) unmarshalMap(input []text.Value, fd pref.FieldDescriptor, mmap pref.Map) error {
  289. var nerr errors.NonFatal
  290. fields := fd.MessageType().Fields()
  291. keyDesc := fields.ByNumber(1)
  292. valDesc := fields.ByNumber(2)
  293. // Determine ahead whether map entry is a scalar type or a message type in order to call the
  294. // appropriate unmarshalMapValue func inside the for loop below.
  295. unmarshalMapValue := o.unmarshalMapScalarValue
  296. switch valDesc.Kind() {
  297. case pref.MessageKind, pref.GroupKind:
  298. unmarshalMapValue = o.unmarshalMapMessageValue
  299. }
  300. for _, entry := range input {
  301. if entry.Type() != text.Message {
  302. return errors.New("%v contains invalid map entry: %v", fd.FullName(), entry)
  303. }
  304. tkey, tval, err := parseMapEntry(entry.Message(), fd.FullName())
  305. if !nerr.Merge(err) {
  306. return err
  307. }
  308. pkey, err := unmarshalMapKey(tkey, keyDesc)
  309. if !nerr.Merge(err) {
  310. return err
  311. }
  312. err = unmarshalMapValue(tval, pkey, valDesc, mmap)
  313. if !nerr.Merge(err) {
  314. return err
  315. }
  316. }
  317. return nerr.E
  318. }
  319. // parseMapEntry parses [][2]text.Value for field names key and value, and return corresponding
  320. // field values. If there are duplicate field names, the value for the last field is returned. If
  321. // the field name does not exist, it will return the zero value of text.Value. It will return an
  322. // error if there are unknown field names.
  323. func parseMapEntry(mapEntry [][2]text.Value, name pref.FullName) (key text.Value, value text.Value, err error) {
  324. for _, field := range mapEntry {
  325. keyStr, ok := field[0].Name()
  326. if ok {
  327. switch keyStr {
  328. case "key":
  329. if key.Type() != 0 {
  330. return key, value, errors.New("%v contains duplicate key field", name)
  331. }
  332. key = field[1]
  333. case "value":
  334. if value.Type() != 0 {
  335. return key, value, errors.New("%v contains duplicate value field", name)
  336. }
  337. value = field[1]
  338. default:
  339. ok = false
  340. }
  341. }
  342. if !ok {
  343. // TODO: Do not return error if ignore unknown option is added and enabled.
  344. return key, value, errors.New("%v contains unknown map entry name: %v", name, field[0])
  345. }
  346. }
  347. return key, value, nil
  348. }
  349. // unmarshalMapKey converts given text.Value into a protoreflect.MapKey. A map key type is any
  350. // integral or string type.
  351. func unmarshalMapKey(input text.Value, fd pref.FieldDescriptor) (pref.MapKey, error) {
  352. // If input is not set, use the zero value.
  353. if input.Type() == 0 {
  354. return fd.Default().MapKey(), nil
  355. }
  356. val, err := unmarshalScalar(input, fd)
  357. if err != nil {
  358. return pref.MapKey{}, errors.New("%v contains invalid key: %v", fd.FullName(), input)
  359. }
  360. return val.MapKey(), nil
  361. }
  362. // unmarshalMapMessageValue unmarshals given message-type text.Value into a protoreflect.Map for
  363. // the given MapKey.
  364. func (o UnmarshalOptions) unmarshalMapMessageValue(input text.Value, pkey pref.MapKey, _ pref.FieldDescriptor, mmap pref.Map) error {
  365. var nerr errors.NonFatal
  366. var value [][2]text.Value
  367. if input.Type() != 0 {
  368. value = input.Message()
  369. }
  370. m := mmap.NewMessage()
  371. if err := o.unmarshalMessage(value, m); !nerr.Merge(err) {
  372. return err
  373. }
  374. mmap.Set(pkey, pref.ValueOf(m))
  375. return nerr.E
  376. }
  377. // unmarshalMapScalarValue unmarshals given scalar-type text.Value into a protoreflect.Map
  378. // for the given MapKey.
  379. func (o UnmarshalOptions) unmarshalMapScalarValue(input text.Value, pkey pref.MapKey, fd pref.FieldDescriptor, mmap pref.Map) error {
  380. var val pref.Value
  381. if input.Type() == 0 {
  382. val = fd.Default()
  383. } else {
  384. var err error
  385. val, err = unmarshalScalar(input, fd)
  386. if err != nil {
  387. return err
  388. }
  389. }
  390. mmap.Set(pkey, val)
  391. return nil
  392. }