encoder.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. package dbus
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "io"
  6. "reflect"
  7. )
  8. // An encoder encodes values to the D-Bus wire format.
  9. type encoder struct {
  10. out io.Writer
  11. order binary.ByteOrder
  12. pos int
  13. }
  14. // NewEncoder returns a new encoder that writes to out in the given byte order.
  15. func newEncoder(out io.Writer, order binary.ByteOrder) *encoder {
  16. return newEncoderAtOffset(out, 0, order)
  17. }
  18. // newEncoderAtOffset returns a new encoder that writes to out in the given
  19. // byte order. Specify the offset to initialize pos for proper alignment
  20. // computation.
  21. func newEncoderAtOffset(out io.Writer, offset int, order binary.ByteOrder) *encoder {
  22. enc := new(encoder)
  23. enc.out = out
  24. enc.order = order
  25. enc.pos = offset
  26. return enc
  27. }
  28. // Aligns the next output to be on a multiple of n. Panics on write errors.
  29. func (enc *encoder) align(n int) {
  30. pad := enc.padding(0, n)
  31. if pad > 0 {
  32. empty := make([]byte, pad)
  33. if _, err := enc.out.Write(empty); err != nil {
  34. panic(err)
  35. }
  36. enc.pos += pad
  37. }
  38. }
  39. // pad returns the number of bytes of padding, based on current position and additional offset.
  40. // and alignment.
  41. func (enc *encoder) padding(offset, algn int) int {
  42. abs := enc.pos + offset
  43. if abs%algn != 0 {
  44. newabs := (abs + algn - 1) & ^(algn - 1)
  45. return newabs - abs
  46. }
  47. return 0
  48. }
  49. // Calls binary.Write(enc.out, enc.order, v) and panics on write errors.
  50. func (enc *encoder) binwrite(v interface{}) {
  51. if err := binary.Write(enc.out, enc.order, v); err != nil {
  52. panic(err)
  53. }
  54. }
  55. // Encode encodes the given values to the underyling reader. All written values
  56. // are aligned properly as required by the D-Bus spec.
  57. func (enc *encoder) Encode(vs ...interface{}) (err error) {
  58. defer func() {
  59. err, _ = recover().(error)
  60. }()
  61. for _, v := range vs {
  62. enc.encode(reflect.ValueOf(v), 0)
  63. }
  64. return nil
  65. }
  66. // encode encodes the given value to the writer and panics on error. depth holds
  67. // the depth of the container nesting.
  68. func (enc *encoder) encode(v reflect.Value, depth int) {
  69. enc.align(alignment(v.Type()))
  70. switch v.Kind() {
  71. case reflect.Uint8:
  72. var b [1]byte
  73. b[0] = byte(v.Uint())
  74. if _, err := enc.out.Write(b[:]); err != nil {
  75. panic(err)
  76. }
  77. enc.pos++
  78. case reflect.Bool:
  79. if v.Bool() {
  80. enc.encode(reflect.ValueOf(uint32(1)), depth)
  81. } else {
  82. enc.encode(reflect.ValueOf(uint32(0)), depth)
  83. }
  84. case reflect.Int16:
  85. enc.binwrite(int16(v.Int()))
  86. enc.pos += 2
  87. case reflect.Uint16:
  88. enc.binwrite(uint16(v.Uint()))
  89. enc.pos += 2
  90. case reflect.Int32:
  91. enc.binwrite(int32(v.Int()))
  92. enc.pos += 4
  93. case reflect.Uint32:
  94. enc.binwrite(uint32(v.Uint()))
  95. enc.pos += 4
  96. case reflect.Int64:
  97. enc.binwrite(v.Int())
  98. enc.pos += 8
  99. case reflect.Uint64:
  100. enc.binwrite(v.Uint())
  101. enc.pos += 8
  102. case reflect.Float64:
  103. enc.binwrite(v.Float())
  104. enc.pos += 8
  105. case reflect.String:
  106. enc.encode(reflect.ValueOf(uint32(len(v.String()))), depth)
  107. b := make([]byte, v.Len()+1)
  108. copy(b, v.String())
  109. b[len(b)-1] = 0
  110. n, err := enc.out.Write(b)
  111. if err != nil {
  112. panic(err)
  113. }
  114. enc.pos += n
  115. case reflect.Ptr:
  116. enc.encode(v.Elem(), depth)
  117. case reflect.Slice, reflect.Array:
  118. if depth >= 64 {
  119. panic(FormatError("input exceeds container depth limit"))
  120. }
  121. // Lookahead offset: 4 bytes for uint32 length (with alignment),
  122. // plus alignment for elements.
  123. n := enc.padding(0, 4) + 4
  124. offset := enc.pos + n + enc.padding(n, alignment(v.Type().Elem()))
  125. var buf bytes.Buffer
  126. bufenc := newEncoderAtOffset(&buf, offset, enc.order)
  127. for i := 0; i < v.Len(); i++ {
  128. bufenc.encode(v.Index(i), depth+1)
  129. }
  130. enc.encode(reflect.ValueOf(uint32(buf.Len())), depth)
  131. length := buf.Len()
  132. enc.align(alignment(v.Type().Elem()))
  133. if _, err := buf.WriteTo(enc.out); err != nil {
  134. panic(err)
  135. }
  136. enc.pos += length
  137. case reflect.Struct:
  138. if depth >= 64 && v.Type() != signatureType {
  139. panic(FormatError("input exceeds container depth limit"))
  140. }
  141. switch t := v.Type(); t {
  142. case signatureType:
  143. str := v.Field(0)
  144. enc.encode(reflect.ValueOf(byte(str.Len())), depth+1)
  145. b := make([]byte, str.Len()+1)
  146. copy(b, str.String())
  147. b[len(b)-1] = 0
  148. n, err := enc.out.Write(b)
  149. if err != nil {
  150. panic(err)
  151. }
  152. enc.pos += n
  153. case variantType:
  154. variant := v.Interface().(Variant)
  155. enc.encode(reflect.ValueOf(variant.sig), depth+1)
  156. enc.encode(reflect.ValueOf(variant.value), depth+1)
  157. default:
  158. for i := 0; i < v.Type().NumField(); i++ {
  159. field := t.Field(i)
  160. if field.PkgPath == "" && field.Tag.Get("dbus") != "-" {
  161. enc.encode(v.Field(i), depth+1)
  162. }
  163. }
  164. }
  165. case reflect.Map:
  166. // Maps are arrays of structures, so they actually increase the depth by
  167. // 2.
  168. if depth >= 63 {
  169. panic(FormatError("input exceeds container depth limit"))
  170. }
  171. if !isKeyType(v.Type().Key()) {
  172. panic(InvalidTypeError{v.Type()})
  173. }
  174. keys := v.MapKeys()
  175. // Lookahead offset: 4 bytes for uint32 length (with alignment),
  176. // plus 8-byte alignment
  177. n := enc.padding(0, 4) + 4
  178. offset := enc.pos + n + enc.padding(n, 8)
  179. var buf bytes.Buffer
  180. bufenc := newEncoderAtOffset(&buf, offset, enc.order)
  181. for _, k := range keys {
  182. bufenc.align(8)
  183. bufenc.encode(k, depth+2)
  184. bufenc.encode(v.MapIndex(k), depth+2)
  185. }
  186. enc.encode(reflect.ValueOf(uint32(buf.Len())), depth)
  187. length := buf.Len()
  188. enc.align(8)
  189. if _, err := buf.WriteTo(enc.out); err != nil {
  190. panic(err)
  191. }
  192. enc.pos += length
  193. default:
  194. panic(InvalidTypeError{v.Type()})
  195. }
  196. }