sig.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package dbus
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. )
  7. var sigToType = map[byte]reflect.Type{
  8. 'y': byteType,
  9. 'b': boolType,
  10. 'n': int16Type,
  11. 'q': uint16Type,
  12. 'i': int32Type,
  13. 'u': uint32Type,
  14. 'x': int64Type,
  15. 't': uint64Type,
  16. 'd': float64Type,
  17. 's': stringType,
  18. 'g': signatureType,
  19. 'o': objectPathType,
  20. 'v': variantType,
  21. 'h': unixFDIndexType,
  22. }
  23. // Signature represents a correct type signature as specified by the D-Bus
  24. // specification. The zero value represents the empty signature, "".
  25. type Signature struct {
  26. str string
  27. }
  28. // SignatureOf returns the concatenation of all the signatures of the given
  29. // values. It panics if one of them is not representable in D-Bus.
  30. func SignatureOf(vs ...interface{}) Signature {
  31. var s string
  32. for _, v := range vs {
  33. s += getSignature(reflect.TypeOf(v), &depthCounter{})
  34. }
  35. return Signature{s}
  36. }
  37. // SignatureOfType returns the signature of the given type. It panics if the
  38. // type is not representable in D-Bus.
  39. func SignatureOfType(t reflect.Type) Signature {
  40. return Signature{getSignature(t, &depthCounter{})}
  41. }
  42. // getSignature returns the signature of the given type and panics on unknown types.
  43. func getSignature(t reflect.Type, depth *depthCounter) (sig string) {
  44. if !depth.Valid() {
  45. panic("container nesting too deep")
  46. }
  47. defer func() {
  48. if len(sig) > 255 {
  49. panic("signature exceeds the length limitation")
  50. }
  51. }()
  52. // handle simple types first
  53. switch t.Kind() {
  54. case reflect.Uint8:
  55. return "y"
  56. case reflect.Bool:
  57. return "b"
  58. case reflect.Int16:
  59. return "n"
  60. case reflect.Uint16:
  61. return "q"
  62. case reflect.Int, reflect.Int32:
  63. if t == unixFDType {
  64. return "h"
  65. }
  66. return "i"
  67. case reflect.Uint, reflect.Uint32:
  68. if t == unixFDIndexType {
  69. return "h"
  70. }
  71. return "u"
  72. case reflect.Int64:
  73. return "x"
  74. case reflect.Uint64:
  75. return "t"
  76. case reflect.Float64:
  77. return "d"
  78. case reflect.Ptr:
  79. return getSignature(t.Elem(), depth)
  80. case reflect.String:
  81. if t == objectPathType {
  82. return "o"
  83. }
  84. return "s"
  85. case reflect.Struct:
  86. if t == variantType {
  87. return "v"
  88. } else if t == signatureType {
  89. return "g"
  90. }
  91. var s string
  92. for i := 0; i < t.NumField(); i++ {
  93. field := t.Field(i)
  94. if field.PkgPath == "" && field.Tag.Get("dbus") != "-" {
  95. s += getSignature(t.Field(i).Type, depth.EnterStruct())
  96. }
  97. }
  98. if len(s) == 0 {
  99. panic(InvalidTypeError{t})
  100. }
  101. return "(" + s + ")"
  102. case reflect.Array, reflect.Slice:
  103. return "a" + getSignature(t.Elem(), depth.EnterArray())
  104. case reflect.Map:
  105. if !isKeyType(t.Key()) {
  106. panic(InvalidTypeError{t})
  107. }
  108. return "a{" + getSignature(t.Key(), depth.EnterArray().EnterDictEntry()) + getSignature(t.Elem(), depth.EnterArray().EnterDictEntry()) + "}"
  109. case reflect.Interface:
  110. return "v"
  111. }
  112. panic(InvalidTypeError{t})
  113. }
  114. // ParseSignature returns the signature represented by this string, or a
  115. // SignatureError if the string is not a valid signature.
  116. func ParseSignature(s string) (sig Signature, err error) {
  117. if len(s) == 0 {
  118. return
  119. }
  120. if len(s) > 255 {
  121. return Signature{""}, SignatureError{s, "too long"}
  122. }
  123. sig.str = s
  124. for err == nil && len(s) != 0 {
  125. err, s = validSingle(s, &depthCounter{})
  126. }
  127. if err != nil {
  128. sig = Signature{""}
  129. }
  130. return
  131. }
  132. // ParseSignatureMust behaves like ParseSignature, except that it panics if s
  133. // is not valid.
  134. func ParseSignatureMust(s string) Signature {
  135. sig, err := ParseSignature(s)
  136. if err != nil {
  137. panic(err)
  138. }
  139. return sig
  140. }
  141. // Empty returns whether the signature is the empty signature.
  142. func (s Signature) Empty() bool {
  143. return s.str == ""
  144. }
  145. // Single returns whether the signature represents a single, complete type.
  146. func (s Signature) Single() bool {
  147. err, r := validSingle(s.str, &depthCounter{})
  148. return err != nil && r == ""
  149. }
  150. // String returns the signature's string representation.
  151. func (s Signature) String() string {
  152. return s.str
  153. }
  154. // A SignatureError indicates that a signature passed to a function or received
  155. // on a connection is not a valid signature.
  156. type SignatureError struct {
  157. Sig string
  158. Reason string
  159. }
  160. func (e SignatureError) Error() string {
  161. return fmt.Sprintf("dbus: invalid signature: %q (%s)", e.Sig, e.Reason)
  162. }
  163. type depthCounter struct {
  164. arrayDepth, structDepth, dictEntryDepth int
  165. }
  166. func (cnt *depthCounter) Valid() bool {
  167. return cnt.arrayDepth <= 32 && cnt.structDepth <= 32 && cnt.dictEntryDepth <= 32
  168. }
  169. func (cnt depthCounter) EnterArray() *depthCounter {
  170. cnt.arrayDepth++
  171. return &cnt
  172. }
  173. func (cnt depthCounter) EnterStruct() *depthCounter {
  174. cnt.structDepth++
  175. return &cnt
  176. }
  177. func (cnt depthCounter) EnterDictEntry() *depthCounter {
  178. cnt.dictEntryDepth++
  179. return &cnt
  180. }
  181. // Try to read a single type from this string. If it was successful, err is nil
  182. // and rem is the remaining unparsed part. Otherwise, err is a non-nil
  183. // SignatureError and rem is "". depth is the current recursion depth which may
  184. // not be greater than 64 and should be given as 0 on the first call.
  185. func validSingle(s string, depth *depthCounter) (err error, rem string) {
  186. if s == "" {
  187. return SignatureError{Sig: s, Reason: "empty signature"}, ""
  188. }
  189. if !depth.Valid() {
  190. return SignatureError{Sig: s, Reason: "container nesting too deep"}, ""
  191. }
  192. switch s[0] {
  193. case 'y', 'b', 'n', 'q', 'i', 'u', 'x', 't', 'd', 's', 'g', 'o', 'v', 'h':
  194. return nil, s[1:]
  195. case 'a':
  196. if len(s) > 1 && s[1] == '{' {
  197. i := findMatching(s[1:], '{', '}')
  198. if i == -1 {
  199. return SignatureError{Sig: s, Reason: "unmatched '{'"}, ""
  200. }
  201. i++
  202. rem = s[i+1:]
  203. s = s[2:i]
  204. if err, _ = validSingle(s[:1], depth.EnterArray().EnterDictEntry()); err != nil {
  205. return err, ""
  206. }
  207. err, nr := validSingle(s[1:], depth.EnterArray().EnterDictEntry())
  208. if err != nil {
  209. return err, ""
  210. }
  211. if nr != "" {
  212. return SignatureError{Sig: s, Reason: "too many types in dict"}, ""
  213. }
  214. return nil, rem
  215. }
  216. return validSingle(s[1:], depth.EnterArray())
  217. case '(':
  218. i := findMatching(s, '(', ')')
  219. if i == -1 {
  220. return SignatureError{Sig: s, Reason: "unmatched ')'"}, ""
  221. }
  222. rem = s[i+1:]
  223. s = s[1:i]
  224. for err == nil && s != "" {
  225. err, s = validSingle(s, depth.EnterStruct())
  226. }
  227. if err != nil {
  228. rem = ""
  229. }
  230. return
  231. }
  232. return SignatureError{Sig: s, Reason: "invalid type character"}, ""
  233. }
  234. func findMatching(s string, left, right rune) int {
  235. n := 0
  236. for i, v := range s {
  237. if v == left {
  238. n++
  239. } else if v == right {
  240. n--
  241. }
  242. if n == 0 {
  243. return i
  244. }
  245. }
  246. return -1
  247. }
  248. // typeFor returns the type of the given signature. It ignores any left over
  249. // characters and panics if s doesn't start with a valid type signature.
  250. func typeFor(s string) (t reflect.Type) {
  251. err, _ := validSingle(s, &depthCounter{})
  252. if err != nil {
  253. panic(err)
  254. }
  255. if t, ok := sigToType[s[0]]; ok {
  256. return t
  257. }
  258. switch s[0] {
  259. case 'a':
  260. if s[1] == '{' {
  261. i := strings.LastIndex(s, "}")
  262. t = reflect.MapOf(sigToType[s[2]], typeFor(s[3:i]))
  263. } else {
  264. t = reflect.SliceOf(typeFor(s[1:]))
  265. }
  266. case '(':
  267. t = interfacesType
  268. }
  269. return
  270. }