extensions.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2010 The Go Authors. All rights reserved.
  4. // https://github.com/golang/protobuf
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. package proto
  32. /*
  33. * Types and routines for supporting protocol buffer extensions.
  34. */
  35. import (
  36. "errors"
  37. "fmt"
  38. "reflect"
  39. "strconv"
  40. "sync"
  41. )
  42. // ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
  43. var ErrMissingExtension = errors.New("proto: missing extension")
  44. // ExtensionRange represents a range of message extensions for a protocol buffer.
  45. // Used in code generated by the protocol compiler.
  46. type ExtensionRange struct {
  47. Start, End int32 // both inclusive
  48. }
  49. // extendableProto is an interface implemented by any protocol buffer that may be extended.
  50. type extendableProto interface {
  51. Message
  52. ExtensionRangeArray() []ExtensionRange
  53. ExtensionMap() map[int32]Extension
  54. }
  55. var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem()
  56. // ExtensionDesc represents an extension specification.
  57. // Used in generated code from the protocol compiler.
  58. type ExtensionDesc struct {
  59. ExtendedType Message // nil pointer to the type that is being extended
  60. ExtensionType interface{} // nil pointer to the extension type
  61. Field int32 // field number
  62. Name string // fully-qualified name of extension, for text formatting
  63. Tag string // protobuf tag style
  64. }
  65. func (ed *ExtensionDesc) repeated() bool {
  66. t := reflect.TypeOf(ed.ExtensionType)
  67. return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
  68. }
  69. // Extension represents an extension in a message.
  70. type Extension struct {
  71. // When an extension is stored in a message using SetExtension
  72. // only desc and value are set. When the message is marshaled
  73. // enc will be set to the encoded form of the message.
  74. //
  75. // When a message is unmarshaled and contains extensions, each
  76. // extension will have only enc set. When such an extension is
  77. // accessed using GetExtension (or GetExtensions) desc and value
  78. // will be set.
  79. desc *ExtensionDesc
  80. value interface{}
  81. enc []byte
  82. }
  83. // SetRawExtension is for testing only.
  84. func SetRawExtension(base extendableProto, id int32, b []byte) {
  85. base.ExtensionMap()[id] = Extension{enc: b}
  86. }
  87. // isExtensionField returns true iff the given field number is in an extension range.
  88. func isExtensionField(pb extendableProto, field int32) bool {
  89. for _, er := range pb.ExtensionRangeArray() {
  90. if er.Start <= field && field <= er.End {
  91. return true
  92. }
  93. }
  94. return false
  95. }
  96. // checkExtensionTypes checks that the given extension is valid for pb.
  97. func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
  98. // Check the extended type.
  99. if a, b := reflect.TypeOf(pb), reflect.TypeOf(extension.ExtendedType); a != b {
  100. return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String())
  101. }
  102. // Check the range.
  103. if !isExtensionField(pb, extension.Field) {
  104. return errors.New("proto: bad extension number; not in declared ranges")
  105. }
  106. return nil
  107. }
  108. // extPropKey is sufficient to uniquely identify an extension.
  109. type extPropKey struct {
  110. base reflect.Type
  111. field int32
  112. }
  113. var extProp = struct {
  114. sync.RWMutex
  115. m map[extPropKey]*Properties
  116. }{
  117. m: make(map[extPropKey]*Properties),
  118. }
  119. func extensionProperties(ed *ExtensionDesc) *Properties {
  120. key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
  121. extProp.RLock()
  122. if prop, ok := extProp.m[key]; ok {
  123. extProp.RUnlock()
  124. return prop
  125. }
  126. extProp.RUnlock()
  127. extProp.Lock()
  128. defer extProp.Unlock()
  129. // Check again.
  130. if prop, ok := extProp.m[key]; ok {
  131. return prop
  132. }
  133. prop := new(Properties)
  134. prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
  135. extProp.m[key] = prop
  136. return prop
  137. }
  138. // encodeExtensionMap encodes any unmarshaled (unencoded) extensions in m.
  139. func encodeExtensionMap(m map[int32]Extension) error {
  140. for k, e := range m {
  141. if e.value == nil || e.desc == nil {
  142. // Extension is only in its encoded form.
  143. continue
  144. }
  145. // We don't skip extensions that have an encoded form set,
  146. // because the extension value may have been mutated after
  147. // the last time this function was called.
  148. et := reflect.TypeOf(e.desc.ExtensionType)
  149. props := extensionProperties(e.desc)
  150. p := NewBuffer(nil)
  151. // If e.value has type T, the encoder expects a *struct{ X T }.
  152. // Pass a *T with a zero field and hope it all works out.
  153. x := reflect.New(et)
  154. x.Elem().Set(reflect.ValueOf(e.value))
  155. if err := props.enc(p, props, toStructPointer(x)); err != nil {
  156. return err
  157. }
  158. e.enc = p.buf
  159. m[k] = e
  160. }
  161. return nil
  162. }
  163. func sizeExtensionMap(m map[int32]Extension) (n int) {
  164. for _, e := range m {
  165. if e.value == nil || e.desc == nil {
  166. // Extension is only in its encoded form.
  167. n += len(e.enc)
  168. continue
  169. }
  170. // We don't skip extensions that have an encoded form set,
  171. // because the extension value may have been mutated after
  172. // the last time this function was called.
  173. et := reflect.TypeOf(e.desc.ExtensionType)
  174. props := extensionProperties(e.desc)
  175. // If e.value has type T, the encoder expects a *struct{ X T }.
  176. // Pass a *T with a zero field and hope it all works out.
  177. x := reflect.New(et)
  178. x.Elem().Set(reflect.ValueOf(e.value))
  179. n += props.size(props, toStructPointer(x))
  180. }
  181. return
  182. }
  183. // HasExtension returns whether the given extension is present in pb.
  184. func HasExtension(pb extendableProto, extension *ExtensionDesc) bool {
  185. // TODO: Check types, field numbers, etc.?
  186. _, ok := pb.ExtensionMap()[extension.Field]
  187. return ok
  188. }
  189. // ClearExtension removes the given extension from pb.
  190. func ClearExtension(pb extendableProto, extension *ExtensionDesc) {
  191. // TODO: Check types, field numbers, etc.?
  192. delete(pb.ExtensionMap(), extension.Field)
  193. }
  194. // GetExtension parses and returns the given extension of pb.
  195. // If the extension is not present and has no default value it returns ErrMissingExtension.
  196. func GetExtension(pb extendableProto, extension *ExtensionDesc) (interface{}, error) {
  197. if err := checkExtensionTypes(pb, extension); err != nil {
  198. return nil, err
  199. }
  200. emap := pb.ExtensionMap()
  201. e, ok := emap[extension.Field]
  202. if !ok {
  203. // defaultExtensionValue returns the default value or
  204. // ErrMissingExtension if there is no default.
  205. return defaultExtensionValue(extension)
  206. }
  207. if e.value != nil {
  208. // Already decoded. Check the descriptor, though.
  209. if e.desc != extension {
  210. // This shouldn't happen. If it does, it means that
  211. // GetExtension was called twice with two different
  212. // descriptors with the same field number.
  213. return nil, errors.New("proto: descriptor conflict")
  214. }
  215. return e.value, nil
  216. }
  217. v, err := decodeExtension(e.enc, extension)
  218. if err != nil {
  219. return nil, err
  220. }
  221. // Remember the decoded version and drop the encoded version.
  222. // That way it is safe to mutate what we return.
  223. e.value = v
  224. e.desc = extension
  225. e.enc = nil
  226. emap[extension.Field] = e
  227. return e.value, nil
  228. }
  229. // defaultExtensionValue returns the default value for extension.
  230. // If no default for an extension is defined ErrMissingExtension is returned.
  231. func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) {
  232. t := reflect.TypeOf(extension.ExtensionType)
  233. props := extensionProperties(extension)
  234. sf, _, err := fieldDefault(t, props)
  235. if err != nil {
  236. return nil, err
  237. }
  238. if sf == nil || sf.value == nil {
  239. // There is no default value.
  240. return nil, ErrMissingExtension
  241. }
  242. if t.Kind() != reflect.Ptr {
  243. // We do not need to return a Ptr, we can directly return sf.value.
  244. return sf.value, nil
  245. }
  246. // We need to return an interface{} that is a pointer to sf.value.
  247. value := reflect.New(t).Elem()
  248. value.Set(reflect.New(value.Type().Elem()))
  249. if sf.kind == reflect.Int32 {
  250. // We may have an int32 or an enum, but the underlying data is int32.
  251. // Since we can't set an int32 into a non int32 reflect.value directly
  252. // set it as a int32.
  253. value.Elem().SetInt(int64(sf.value.(int32)))
  254. } else {
  255. value.Elem().Set(reflect.ValueOf(sf.value))
  256. }
  257. return value.Interface(), nil
  258. }
  259. // decodeExtension decodes an extension encoded in b.
  260. func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
  261. o := NewBuffer(b)
  262. t := reflect.TypeOf(extension.ExtensionType)
  263. props := extensionProperties(extension)
  264. // t is a pointer to a struct, pointer to basic type or a slice.
  265. // Allocate a "field" to store the pointer/slice itself; the
  266. // pointer/slice will be stored here. We pass
  267. // the address of this field to props.dec.
  268. // This passes a zero field and a *t and lets props.dec
  269. // interpret it as a *struct{ x t }.
  270. value := reflect.New(t).Elem()
  271. for {
  272. // Discard wire type and field number varint. It isn't needed.
  273. if _, err := o.DecodeVarint(); err != nil {
  274. return nil, err
  275. }
  276. if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil {
  277. return nil, err
  278. }
  279. if o.index >= len(o.buf) {
  280. break
  281. }
  282. }
  283. return value.Interface(), nil
  284. }
  285. // GetExtensions returns a slice of the extensions present in pb that are also listed in es.
  286. // The returned slice has the same length as es; missing extensions will appear as nil elements.
  287. func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
  288. epb, ok := pb.(extendableProto)
  289. if !ok {
  290. err = errors.New("proto: not an extendable proto")
  291. return
  292. }
  293. extensions = make([]interface{}, len(es))
  294. for i, e := range es {
  295. extensions[i], err = GetExtension(epb, e)
  296. if err == ErrMissingExtension {
  297. err = nil
  298. }
  299. if err != nil {
  300. return
  301. }
  302. }
  303. return
  304. }
  305. // SetExtension sets the specified extension of pb to the specified value.
  306. func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{}) error {
  307. if err := checkExtensionTypes(pb, extension); err != nil {
  308. return err
  309. }
  310. typ := reflect.TypeOf(extension.ExtensionType)
  311. if typ != reflect.TypeOf(value) {
  312. return errors.New("proto: bad extension value type")
  313. }
  314. // nil extension values need to be caught early, because the
  315. // encoder can't distinguish an ErrNil due to a nil extension
  316. // from an ErrNil due to a missing field. Extensions are
  317. // always optional, so the encoder would just swallow the error
  318. // and drop all the extensions from the encoded message.
  319. if reflect.ValueOf(value).IsNil() {
  320. return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
  321. }
  322. pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value}
  323. return nil
  324. }
  325. // A global registry of extensions.
  326. // The generated code will register the generated descriptors by calling RegisterExtension.
  327. var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
  328. // RegisterExtension is called from the generated code.
  329. func RegisterExtension(desc *ExtensionDesc) {
  330. st := reflect.TypeOf(desc.ExtendedType).Elem()
  331. m := extensionMaps[st]
  332. if m == nil {
  333. m = make(map[int32]*ExtensionDesc)
  334. extensionMaps[st] = m
  335. }
  336. if _, ok := m[desc.Field]; ok {
  337. panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
  338. }
  339. m[desc.Field] = desc
  340. }
  341. // RegisteredExtensions returns a map of the registered extensions of a
  342. // protocol buffer struct, indexed by the extension number.
  343. // The argument pb should be a nil pointer to the struct type.
  344. func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
  345. return extensionMaps[reflect.TypeOf(pb).Elem()]
  346. }